repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
idrop-link/idrop.link-osx
idrop.link/PreferencesWindowController.swift
2
3206
// // PreferencesWindowController.swift // idrop.link // // Created by Christian Schulze on 17/04/15. // Copyright (c) 2015 Christian Schulze. All rights reserved. // import Foundation import Cocoa /** WindowController for the Preferences window. */ class PreferencesWindowController: NSWindowController { @IBOutlet var _window: NSWindow! @IBOutlet weak var tabView: NSTabView! // Tabs @IBOutlet weak var generalTab: NSTabViewItem! @IBOutlet weak var userTab: NSTabViewItem! // General Tab @IBOutlet weak var doOpenAtStartup: NSButton! // General Tab @IBOutlet weak var doAutoUploadScreens: NSButton! // User Tab @IBOutlet weak var email: NSTextField! var user: User? var userDefaults: NSUserDefaults var appUrl: NSURL? @IBAction func changeTab(sender: AnyObject) { let sndr = sender as! NSToolbarItem switch sndr.tag { case 1: tabView.selectTabViewItem(generalTab) case 2: tabView.selectTabViewItem(userTab) default: break; } } @IBAction func persistToLoginItems(sender: AnyObject) { if doOpenAtStartup.state == NSOnState { LoginItemController.setLaunchAtLogin(self.appUrl!, enabled: true) } else if doOpenAtStartup.state == NSOffState { LoginItemController.setLaunchAtLogin(self.appUrl!, enabled: false) } else { // well, this is the "NSMixedState". though it should not apply // here we log this just in case print("Detected invalid button state `NSMixedState` @ Preferences->Global->Start at Login") } } @IBAction func persistAutoUpload(sender: AnyObject) { let enabled = self.doAutoUploadScreens.state == NSOnState self.userDefaults.setBool(enabled, forKey: "auto-upload") } override init(window: NSWindow?) { self.userDefaults = NSUserDefaults.standardUserDefaults() super.init(window: window) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func awakeFromNib() { var deactivate:Bool = true if (userDefaults.boolForKey("auto-upload")) { Swift.print("enabled") self.doAutoUploadScreens.state = NSOnState } else { Swift.print("disabled") self.doAutoUploadScreens.state = NSOffState } self.appUrl = NSURL.fileURLWithPath(NSBundle.mainBundle().bundlePath) if let usr = self.user { if let mail = usr.email { self.email.stringValue = mail deactivate = false } } if deactivate { self.email.enabled = false } if let _ = self.appUrl { if LoginItemController.willLaunchAtLogin(self.appUrl!) { doOpenAtStartup.state = NSOnState } else { doOpenAtStartup.state = NSOffState } } else { // we can't save it anyway doOpenAtStartup.enabled = false } } }
mit
7a8e427e5d0d973e714bdfc9537db564
27.633929
103
0.601061
4.8429
false
false
false
false
tkausch/swiftalgorithms
CodePuzzles/Sudoku.playground/Contents.swift
1
8730
//: # Sudoku //: A standard Sudoku contains 81 cells, in a 9×9 grid, and has 9 boxes, each box being the intersection of the first, middle, or last 3 rows, //: and the first, middle, or last 3 columns. Each cell may contain a number from one to nine, and each number can only occur once in each row, //: column, and box. A Sudoku starts with some cells containing numbers (clues), and the goal is to solve the remaining cells. //: Proper Sudokus have one solution. //: //: **Question:** Given a sudoku grid, we need to verify if the already filled in numbers doesn't violate //: the sudoku rules. The rules are very simple: //: * Each row has numbers from 1-9 and no repetitions //: * Each column has numbers from 1-9 and no repetitions //: * Each 3x3 cube has numbers from 1-9 and no repetitions //: //: **Solution:** The following algorithm adds a check for each row, column and box. Calculating the box indices is a little bit tricky but still straight forward using div and modulo operators. As we have two for loops that iterate over the board runtime complexity is **O(n2)**. func isValidSudoku(_ board: [[Character]]) -> Bool { let n = board.count for i in 0..<n { var colSet = Set<Character>() var rowSet = Set<Character>() var boxSet = Set<Character>() let rowIdx = 3*(i/3) let colIdx = 3*(i%3) for j in 0..<n { if board[i][j] != Character(".") && !rowSet.insert(board[i][j]).inserted { return false } if board[j][i] != Character(".") && !colSet.insert(board[j][i]).inserted { return false } if board[rowIdx + j/3][colIdx + j%3] != Character(".") && !boxSet.insert(board[rowIdx + j/3][colIdx + j%3]).inserted { return false } } } return true } var validSudoku: [[Character]] = [ [".", "3", ".", "1", ".", ".", ".", ".", "6"], [".", "6", ".", "3", "9", ".", ".", "1", "."], ["4", ".", ".", ".", "2", "6", ".", "7", "."], ["5", "9", "1", "6", ".", ".", "4", ".", "."], [".", ".", "7", ".", "4", ".", "1", ".", "."], [".", ".", "4", ".", ".", "2", "3", "5", "9"], [".", "4", ".", "2", "7", ".", ".", ".", "5"], [".", "7", ".", ".", "3", "5", ".", "4", "."], ["9", ".", ".", ".", ".", "8", ".", "3", "."] ] isValidSudoku(validSudoku) let invalidRowSudoku: [[Character]] = [ [".", "3", ".", "1", ".", ".", ".", ".", "6"], [".", "6", ".", "3", "9", ".", ".", "1", "."], ["4", ".", ".", ".", "2", "6", ".", "7", "."], ["5", "9", "1", "6", ".", ".", "4", ".", "."], [".", ".", "7", ".", "4", ".", "1", ".", "."], [".", ".", "4", ".", ".", "2", "3", "5", "9"], [".", "4", ".", "2", "7", ".", ".", ".", "5"], [".", "7", "3", ".", "3", "5", ".", "4", "."], ["9", ".", ".", ".", ".", "8", ".", "3", "."] ] isValidSudoku(invalidRowSudoku) let invalidColSudoku: [[Character]] = [ [".", "3", ".", "1", ".", ".", ".", ".", "6"], [".", "6", ".", "3", "9", ".", ".", "1", "."], ["4", ".", ".", ".", "2", "6", ".", "7", "."], ["5", "9", "1", "6", ".", ".", "4", ".", "."], [".", ".", "7", ".", "4", ".", "1", ".", "."], [".", ".", "4", ".", ".", "2", "3", "5", "9"], [".", "4", ".", "2", "7", ".", ".", ".", "5"], [".", "7", ".", ".", "3", "5", ".", "4", "."], ["9", ".", "1", ".", ".", "8", ".", "3", "."] ] isValidSudoku(invalidColSudoku) let invalidBoxSudoku: [[Character]] = [ [".", "3", ".", "1", ".", ".", ".", ".", "6"], [".", "6", ".", "3", "9", ".", ".", "1", "."], ["4", ".", ".", ".", "2", "6", ".", "7", "."], ["5", "9", "1", "6", ".", ".", "4", ".", "."], [".", "5", "7", ".", "4", ".", "1", ".", "."], [".", ".", "4", ".", ".", "2", "3", "5", "9"], [".", "4", ".", "2", "7", ".", ".", ".", "5"], [".", "7", ".", ".", "3", "5", ".", "4", "."], ["9", ".", ".", ".", ".", "8", ".", "3", "."] ] isValidSudoku(invalidBoxSudoku) //: There are several computer algorithms that will solve most 9×9 puzzles (n=9) in fractions of a second, but combinatorial explosion //: occurs as n increases, creating limits to the properties of Sudokus that can be constructed, analyzed, and solved as n increases. //: ## Backtracking (depth-first) search algorithm //: The simplest approach solving Sudoku puzzles is using a backtracking algorithm, which is a type of brute force search. //: Backtracking is a depth-first search (in contrast to a breadth-first search), because it will completely explore one branch //: to a possible solution before moving to another branch. Although it has been established that approximately 6.67 x 10^21 final ^ //: grids exist, a brute force algorithm can be a practical method to solve Sudoku puzzles. //: func solveSudoku(_ board: inout [[Character]]) -> Bool { guard isValidSudoku(board) else { return false } let n = board.count func nextEmptyField() -> (row: Int, col: Int)? { for i in 0..<n { for j in 0..<n { if board[i][j] == Character(".") { return (i,j) } } } return nil } func hasValidFieldValue(_ row: Int, _ col: Int) -> Bool { var colSet = Set<Character>() var rowSet = Set<Character>() var boxSet = Set<Character>() let rowIdx = 3*(row/3) let colIdx = 3*(col/3) for j in 0..<n { if board[row][j] != Character(".") && !rowSet.insert(board[row][j]).inserted { return false } if board[j][col] != Character(".") && !colSet.insert(board[j][col]).inserted { return false } if board[rowIdx + j/3][colIdx + j%3] != Character(".") && !boxSet.insert(board[rowIdx + j/3][colIdx + j%3]).inserted { return false } } return true } func solveSudoku() -> Bool { if let idx = nextEmptyField() { var value = 0 repeat { value += 1 board[idx.row][idx.col] = Character(String(value)) if hasValidFieldValue(idx.row, idx.col) && solveSudoku() { return true } } while value < n board[idx.row][idx.col] = Character(".") return false } else { return true; } } return solveSudoku(); } var veryHardSudoku : [[Character]] = [ [".",".",".","3","4",".",".",".","."], ["6",".",".",".",".","1",".","4","."], ["7",".","4",".",".","5","1",".","."], ["8",".",".",".","6",".",".","1","5"], [".","2",".",".",".",".","4",".","7"], ["5",".",".",".",".",".",".",".","3"], [".",".",".","9",".",".",".",".","."], [".",".","7",".","5","3",".",".","."], [".",".",".","4","1",".","5","2","."] ] solveSudoku(&veryHardSudoku) print(veryHardSudoku) //: The disadvantage of this method is that the solving time may be comparatively slow compared to algorithms modeled after deductive methods. //: Moreover a Sudoku can be constructed to work against backtracking. Assuming the solver works from top to bottom, a //: puzzle with few clues (17), no clues in the top row, and has a solution "987654321" for the first row, would work in //: opposition to the algorithm. Thus the program would spend significant time "counting" upward before //: it arrives at the grid which satisfies the puzzle. var constructedSudoku : [[Character]] = [ [".",".",".",".",".",".",".",".","."], [".",".",".",".",".","3",".","8","5"], [".",".","1",".","2",".",".",".","."], [".",".",".","5",".","7",".",".","."], [".",".","4",".",".",".","1",".","."], [".","9",".",".",".",".",".",".","."], ["5",".",".",".",".",".",".","7","3"], [".",".","2",".","1",".",".",".","."], [".",".",".",".","4",".",".",".","9"] ] solveSudoku(&constructedSudoku) print(constructedSudoku) //: ## Stochastic algorithms //: Sudoku can be solved using stochastic (random-based) algorithms. The primary motivation behind using these //: techniques is that difficult puzzles can be solved as efficiently as simple puzzles. //: This is due to the fact that the solution space is searched stochastically until a suitable solution is found. //: Hence, the puzzle does not have to be logically solvable or easy for a solution to be reached efficiently. //: //: An example of this method is to: //: 1. Randomly assign numbers to the blank cells in the grid. //: 2. Calculate the number of errors. //: 3. "Shuffle" the inserted numbers until the number of mistakes is reduced to zero.
gpl-3.0
f528a09ffd2d7b80dbc3816bc0b7f871
40.561905
280
0.46093
3.684255
false
false
false
false
kysonyangs/ysbilibili
ysbilibili/Classes/Player/LivePlayer/View/ZHNlivePlayFullScreenMenuView.swift
1
2607
// // ZHNlivePlayFullScreenMenuView.swift // zhnbilibili // // Created by zhn on 16/12/10. // Copyright © 2016年 zhn. All rights reserved. // import UIKit @objc protocol ZHNliveFullscreenMenuViewDelegate { @objc optional func backAction() } class ZHNlivePlayFullScreenMenuView: ZHNplayerMenuBaseView { // 代理 weak var delegate: ZHNliveFullscreenMenuViewDelegate? // MARK: - 懒加载控件 lazy var liveTopBackImageView: UIImageView = { let liveTopBackImageView = UIImageView() liveTopBackImageView.isUserInteractionEnabled = true liveTopBackImageView.image = UIImage(named: "live_player_vtop_bg")?.ysResizingImage() return liveTopBackImageView }() lazy var liveBottomBackImageView: UIImageView = { let liveBottomBackImageView = UIImageView() liveBottomBackImageView.isUserInteractionEnabled = true liveBottomBackImageView.image = UIImage(named: "live_player_vbottom_bg")?.ysResizingImage() return liveBottomBackImageView }() lazy var menuTop: ZHNliveFullScreenMenuViewTop = { let menuTop = ZHNliveFullScreenMenuViewTop.instanceView() menuTop.supView = self return menuTop }() lazy var menuBottm: ZHNliveFullScreenMenuViewBottom = { let menuBottom = ZHNliveFullScreenMenuViewBottom.instanceView() menuBottom.supView = self return menuBottom }() // MARK: - life cycle override init(frame: CGRect) { super.init(frame: frame) topContainerView.addSubview(liveTopBackImageView) topContainerView.addSubview(menuTop) bottomContainerView.addSubview(liveBottomBackImageView) bottomContainerView.addSubview(menuBottm) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() liveTopBackImageView.snp.makeConstraints { (make) in make.left.top.right.equalTo(self) make.height.equalTo(100) } menuTop.snp.makeConstraints { (make) in make.left.right.equalTo(self) make.top.equalTo(self).offset(10) make.height.equalTo(50) } liveBottomBackImageView.snp.makeConstraints { (make) in make.left.right.bottom.equalTo(self) make.height.equalTo(70) } menuBottm.snp.makeConstraints { (make) in make.left.right.bottom.equalTo(self) make.height.equalTo(50) } } }
mit
044d5b4afbebb2a2ffa4124677f35c59
30.975309
99
0.661776
4.47323
false
false
false
false
biohazardlover/ROer
Roer/FilterCategory.swift
1
915
import Foundation enum FilterCategoryType: String { case More = "More" } class FilterCategory: NSObject { var name: String? var type: String? var filterItems: [FilterItem]? var selectedFilterItem: FilterItem? } extension FilterCategory { convenience init(contents: [AnyHashable: Any]) { self.init() name = contents["Name"] as? String type = contents["Type"] as? String if let filterItems = contents["FilterItems"] as? [[AnyHashable: Any]] { self.filterItems = filterItems.map({ (filterItem) -> FilterItem in return FilterItem(contents: filterItem as [NSObject : AnyObject]) }) selectedFilterItem = self.filterItems?.first } } } extension FilterCategory { var localizedName: String? { return name?.localized } }
mit
7e634e10964f40ae8006d6e36518a7c3
19.795455
81
0.586885
4.621212
false
false
false
false
joelrorseth/AtMe
AtMe/ConvoAuxViewController.swift
1
4730
// // ConvoAuxViewController.swift // AtMe // // Created by Joel Rorseth on 2017-08-01. // Copyright © 2017 Joel Rorseth. All rights reserved. // import UIKit class ConvoAuxViewController: UIViewController, AlertController { lazy var databaseManager = DatabaseController() lazy var authManager = AuthController() var username: String? var convoID: String? var uid: String? @IBOutlet var displayPictureImageView: UIImageView! @IBOutlet var nameLabel: UILabel! @IBOutlet var usernameLabel: UILabel! @IBOutlet var blockUserButton: UIButton! @IBOutlet var reportUserButton: UIButton! /** Handle user pressing the Block User button. */ @IBAction func didPressBlockUserButton(_ sender: UIButton) { guard let uid = self.uid, let convoID = self.convoID, let username = self.username else { return } presentConfirmationAlert(title: "Confirm Block", message: Constants.Messages.confirmBlockMessage, completion: { _ in // Add user to current user's blocked list, leave conversation self.authManager.blockUser(uid: uid, username: username) self.databaseManager.leaveConversation(convoID: convoID, with: username, completion: { self.performSegue(withIdentifier: "UnwindToChatListSegue", sender: nil) }) }) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Set display picture frame to circle (need this for default image especially) self.displayPictureImageView.layer.masksToBounds = true self.displayPictureImageView.layer.cornerRadius = self.displayPictureImageView.frame.size.width / 2 } /** Method called when view is loaded onto screen. */ override func viewDidLoad() { super.viewDidLoad() // Set display picture frame to circle (need this for default image especially) self.displayPictureImageView.layer.cornerRadius = self.displayPictureImageView.frame.size.width / 2 guard let uid = self.uid, let username = self.username else { presentSimpleAlert(title: "Error Loading Profile", message: Constants.Errors.loadProfileError, completion: { _ in self.dismiss(animated: true, completion: nil) }) return } // Download display picture into large central image view databaseManager.downloadImage(into: displayPictureImageView, from: "displayPictures/\(uid)/\(uid).JPG", completion: { _ in self.displayPictureImageView.layer.masksToBounds = true self.displayPictureImageView.layer.cornerRadius = self.displayPictureImageView.frame.size.width / 2 }) // Set the name of user authManager.findNameFor(uid: uid, completion: { name in if let name = name { self.nameLabel.text = name } }) // In case user has already blocked this user, disable authManager.userOrCurrentUserHasBlocked(uid: uid, username: username, completion: { blocked in if blocked { self.blockUserButton.isEnabled = false self.blockUserButton.isUserInteractionEnabled = false self.blockUserButton.backgroundColor = UIColor.lightGray self.blockUserButton.setTitle("Already Blocked", for: .normal) } }) blockUserButton.layer.cornerRadius = Constants.Radius.regularRadius reportUserButton.layer.cornerRadius = Constants.Radius.regularRadius usernameLabel.text = "@\(username)" } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == Constants.Segues.reportUserSegue { let vc = segue.destination as! ReportUserViewController // Pass in details about user whom is being reported if let uid = self.uid, let username = self.username, let convoID = self.convoID { vc.violatorUid = uid vc.violatorUsername = username vc.convoID = convoID } } } override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool { if identifier == Constants.Segues.reportUserSegue { // Make sure optionals can be unwrapped before segue is performed if let _ = self.uid, let _ = self.username, let _ = self.convoID { return true } else { return false } } return true } }
apache-2.0
0f6ddcec96703d2bb1994c1c3cc3d3a4
37.762295
130
0.631212
5.117965
false
false
false
false
alberttra/A-Framework
Pod/Classes/Logger.swift
1
1031
// // Reporter.swift // Journey // // Created by Albert Tra on 08/01/16. // Copyright © 2016 Albert Tra. All rights reserved. // import Foundation import CoreLocation public class Logger { init() { } public func log<T>(sender: T, function: String = #function, uuid: String? = "", message: String? = "") { let classname = NSStringFromClass(T.self as! AnyClass) let location = "Location: \t" + (classname as String) + " --> " + function var separateLine = "=" for _ in 0...location.characters.count { separateLine = separateLine + "=" } print("\n") print(separateLine) print("Location: \t", (classname as String) + " --> " + function) if uuid != nil { print("UUID: \t\t", uuid!) } if message != nil { print(" ---------------------------------------") print("Message: \t", message!) } print(separateLine) } }
mit
ebb130ead31e3e687b065ce6f9010de2
24.75
108
0.48835
4.238683
false
false
false
false
ZulwiyozaPutra/Alien-Adventure-Tutorial
Alien Adventure/RarityOfItems.swift
1
1897
// // RarityOfItems.swift // Alien Adventure // // Created by Jarrod Parkes on 10/4/15. // Copyright © 2015 Udacity. All rights reserved. // extension Hero { func rarityOfItems(inventory: [UDItem]) -> [UDItemRarity:Int] { var commonAmmount: Int = 0 var uncommonAmmount: Int = 0 var rareAmount: Int = 0 var legendaryAmount: Int = 0 var itemRarityDict = [UDItemRarity: Int]() for item in inventory { print("checking \(item.name)") let rarityItem = item.rarity switch rarityItem { case .common: commonAmmount = commonAmmount + 1 print("commonAmount is \(commonAmmount) now") case .uncommon: uncommonAmmount = uncommonAmmount + 1 print("uncommonAmount is \(uncommonAmmount) now") case .rare: rareAmount = rareAmount + 1 print("rareAmount is \(rareAmount) now") case .legendary: legendaryAmount = legendaryAmount + 1 print("legendaryAmount is \(legendaryAmount) now") } } print("next is common to legendary") print(commonAmmount) print(uncommonAmmount) print(rareAmount) print(legendaryAmount) itemRarityDict[.common] = commonAmmount itemRarityDict[.uncommon] = uncommonAmmount itemRarityDict[.rare] = rareAmount itemRarityDict[.legendary] = legendaryAmount return itemRarityDict } } // If you have completed this function and it is working correctly, feel free to skip this part of the adventure by opening the "Under the Hood" folder, and making the following change in Settings.swift: "static var RequestsToSkip = 4"
mit
e262746a46dd03cc8035bbb41c6d9d42
31.689655
235
0.573312
4.590799
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/selluv-ios/Classes/Controller/UI/Tabs/Tab3Sell/SLV_340_SellDirectStep4PriceController.swift
1
20724
// // SLV_340_SellDirectStep4PriceController.swift // selluv-ios // // Created by 조백근 on 2016. 11. 8.. // Copyright © 2016년 BitBoy Labs. All rights reserved. // /* 판매 직접 스텝4 가격 컨트롤러 */ import SwifterSwift import SnapKit import RealmSwift import MaterialKit class SLV_340_SellDirectStep4PriceController: SLVBaseStatusHiddenController { var tr_presentTransition: TRViewControllerTransitionDelegate? @IBOutlet weak var priceTextField: UITextField! @IBOutlet weak var wonLabel: UILabel! @IBOutlet weak var moneySlider: SLVSlider! @IBOutlet weak var priceView: UIView! @IBOutlet weak var inputCollection: UICollectionView! @IBOutlet weak var stepLabel: UILabel! @IBOutlet weak var closeButton: UIButton! @IBOutlet weak var bottomView: UIView! @IBOutlet weak var progressView: UIView! @IBOutlet weak var backgroudProgressView: UIView! @IBOutlet weak var stepProgressView: KYCircularProgress! @IBOutlet weak var step1Button: UIButton! @IBOutlet weak var step2Button: UIButton! @IBOutlet weak var step3Button: UIButton! @IBOutlet weak var step4Button: UIButton! @IBOutlet weak var step5Button: UIButton! var buttonPulse4:LFTPulseAnimation? fileprivate var progressValue = sell_step_3_value fileprivate var progressTimer: Timer? var purchaseCell: SLVPurchasedPriceCell? var adjustCell: SLVAdjustmentPriceCell? var promotionCell: SLVPromotionCell? fileprivate lazy var myToolbar = AccessoryToolbar() fileprivate lazy var promotionToolbar = PromotionToolbar() var hopePirceTextField: MKTextField? var purchasedTextField: MKTextField? @IBOutlet weak var promotionTextField: UITextField! override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tabController.animationTabBarHidden(true) tabController.hideFab() self.moneySlider.maximumValue = 999 self.inputCollection.reloadData() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.navigationController?.isNavigationBarHidden = false self.navigationItem.hidesBackButton = true self.playStepProgress() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) UIView.cancelPreviousPerformRequests(withTarget: self) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) self.resetStepProgress() } override func viewDidLoad() { super.viewDidLoad() self.setupNavigationButtons() self.setupSlider() self.setupCollectionView() self.setupProgress() self.setupButtonPulse2() self.priceTextField.delegate = self self.setupPromotionBar() self.setupDataBinding() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func setupSlider() { let normal = UIImage(named: "sell-range-thumb-default.png") let select = UIImage(named: "sell-range-thumb-hilighted.png") self.moneySlider.setThumbImage(normal, for: .normal) self.moneySlider.setThumbImage(select, for: .highlighted) self.moneySlider.addTarget(self, action: #selector(SLV_340_SellDirectStep4PriceController.sliderValueChange(sender:)), for: .valueChanged) } lazy var keypadLayout: NSLayoutConstraint? = { let keyboard = NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: self.bottomLayoutGuide, attribute: NSLayoutAttribute.top, multiplier: 1.0, constant: 0.0) return keyboard }() func settingKeypadLayout() { self.view.addConstraint(self.keypadLayout!) } func clearKeypadLayout() { self.view.removeConstraint(self.keypadLayout!) } func setupButtonPulse2() { let bounds = self.step4Button.bounds let x = bounds.size.width/2 let y = bounds.size.height/2 self.buttonPulse4 = LFTPulseAnimation(repeatCount: 2, radius:10, position:CGPoint(x: x, y: y)) self.step4Button.layer.insertSublayer(self.buttonPulse4!, below: self.step4Button.layer) } func setupProgress() { self.stepProgressView.delegate = self let path = UIBezierPath() path.move(to: CGPoint(x: 0, y: 0)) path.addLine(to:CGPoint(x: self.view.bounds.size.width, y: 0)) path.close() self.stepProgressView.path = path self.stepProgressView.colors = [bg_color_step] self.resetStepProgress() } func setupCollectionView() { inputCollection.delegate = self inputCollection.dataSource = self inputCollection.contentInset = UIEdgeInsetsMake(0, 0, 67, 0) } func setupNavigationButtons() { let back = UIButton() back.setImage(UIImage(named:"ic-back-arrow.png"), for: .normal) back.frame = CGRect(x: 17, y: 23, width: 12+32, height: 20) back.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 26) back.addTarget(self, action: #selector(SLV_320_SellDirectStep2ItemInfoController.back(sender:)), for: .touchUpInside) let item = UIBarButtonItem(customView: back) self.navigationItem.leftBarButtonItem = item let newDoneButton = UIBarButtonItem(title: "다음", style: UIBarButtonItemStyle.done, target: self, action: #selector(SLV_340_SellDirectStep4PriceController.next(sender:))) self.navigationItem.rightBarButtonItem = newDoneButton } func setupPromotionBar() { self.promotionTextField.delegate = self self.promotionTextField.addTarget(self, action: #selector(SLV_340_SellDirectStep4PriceController.promotionValueChange(sender:)), for: .editingChanged) var done: (()->()) = { self.promotionToolbar.done() } self.promotionToolbar.setupButton(block: { (button) in if self.promotionToolbar.textField != nil { let code = self.promotionToolbar.textField?.text?.trimmed if let coupon = code { if coupon == "" { done() return } SellDataModel.shared.coupon(code: coupon, isBuy: false, block: { (success) in if success { AlertHelper.alert(message: "쿠폰이 적용되었습니다.", title: "안내") done() } }) } } }) } //MARK: Data binding func setupDataBinding() { let price = TempInputInfoModel.shared.currentModel.productPrice let model = TempInputInfoModel.shared.currentModel.priceInfo model.setupUpdateAll { if self.adjustCell != nil { self.adjustCell!.maxPaymentLabel.text = model.maxAdjustmentAmount().0 self.adjustCell!.depositLabel.text = model.depositAmount().0 self.adjustCell!.accumulateLabel.text = model.selluvMaxAccumulatedAmount().0 } } model.setupUpdateCoupon { //adjustmentAmount,selluvMaxAccumulatedAmount, selluvPromotionCodePayback if self.adjustCell != nil { self.adjustCell!.accumulateLabel.text = model.selluvMaxAccumulatedAmount().0 } } self.delay(time: 1) { if let price = price { let value = price.float! / 10000 let comma = String.decimalAmountWithForm(value: value, pointCount: 1) self.priceTextField.text = comma model.updatePrice(sell: price) } else { let money = self.priceTextField.text?.trimmed.float ?? 0 let value = (money * Float(10000)).cleanValue model.updatePrice(sell: value) } } } //MARK: Animation //MARK: Event func back(sender: UIBarButtonItem?) { let model = TempInputInfoModel.shared.currentModel let restart = model.restartScene if restart == 4 { model.restartScene = 3 let board = UIStoryboard(name:"Sell", bundle: nil) let step2Controller = board.instantiateViewController(withIdentifier: "SLV_330_SellDirectStep3AdditionalInfoController") as! SLV_330_SellDirectStep3AdditionalInfoController self.navigationController?.tr_pushViewController(step2Controller, method: TRPushTransitionMethod.reverse, statusBarStyle: .hide) { } } else { _ = self.navigationController?.tr_popViewController() } } func next(sender: UIBarButtonItem? = nil) { log.debug("next(sender:)") //유효성 체크 if TempInputInfoModel.shared.checkInputStepDataValidation(step: .price4) == false { return } let board = UIStoryboard(name:"Sell", bundle: nil) let stepController = board.instantiateViewController(withIdentifier: "SLV_350_SellDirectStep5SellerInfoController") as! SLV_350_SellDirectStep5SellerInfoController self.navigationController?.tr_pushViewController(stepController, method: TRPushTransitionMethod.default, statusBarStyle: .hide) { } } @IBAction func touchClose(_ sender: Any) { let model = TempInputInfoModel.shared.currentModel let restart = model.restartScene if restart >= 0 { model.restartScene = -1 } AlertHelper.confirm(message: "저장하지 않은 STEP은 나중에 이어서 등록할 수 없습니다.", title: "저장은 하셨어요?", no: "저장 후 닫기", cancel: { (action) in TempInputInfoModel.shared.checkInputStepDataValidation(step: .price4) TempInputInfoModel.shared.saveCurrentModel() tabController.closePresent {} }, ok: "바로 닫기", done: { (action) in tabController.closePresent {} }) { } } @IBAction func touchStepProgress(_ sender: Any) { } func sliderValueChange(sender: SLVSlider) { if self.moneySlider.isHighlighted { let currentValue = self.moneySlider.value let money = round(currentValue * 10)/10 //반올림 // let commaValue = NumberFormatter.localizedString(from: NSNumber(value: money), number: NumberFormatter.Style.decimal) let commaValue = String.decimalAmountWithForm(value: money, pointCount: 1) self.priceTextField.text = commaValue//String(fromat: "%.01f", money)//소수점 한자리만 let convertMoney = money * 10000 let convertValue = convertMoney.cleanValue TempInputInfoModel.shared.currentModel.productPrice = convertValue let max = self.moneySlider.maximumValue let min = self.moneySlider.minimumValue if currentValue >= max && max <= 1000000 { self.moneySlider.maximumValue = max + 10 self.moneySlider.resetValue() } if currentValue <= min { if max > 999 { self.moneySlider.maximumValue = max - 10 self.moneySlider.resetValue() } } } } func promotionValueChange(sender: UITextField) { let textField = sender if self.promotionToolbar.textField != nil { self.promotionToolbar.textField?.text = textField.text } } func touchDetailAdjustmentPriceInfo(sender: UIButton) { let frame = CGRect(x: 0, y: 390, width: self.view.bounds.width, height: 116) let board = UIStoryboard(name:"Sell", bundle: nil) let navigationController = board.instantiateViewController(withIdentifier: "priceNavigationController") as! UINavigationController let controller = navigationController.viewControllers.first as! SLV_341_SellStep4PriceDetailController controller.modalDelegate = self self.tr_presentViewController(navigationController, method: TRPresentTransitionMethod.expendable(frame: frame)) { print("Present finished.") } } } extension SLV_340_SellDirectStep4PriceController { func resetStepProgress() { self.stepProgressView.progress = sell_step_4_value self.step1Button.isEnabled = true self.step2Button.isEnabled = true self.step3Button.isEnabled = true self.step4Button.isEnabled = false self.buttonPulse4?.reset() } func playStepProgress() { if self.progressTimer != nil { self.progressTimer?.invalidate() self.progressTimer = nil } self.progressTimer = Timer.scheduledTimer(timeInterval: 0.05, target: self, selector: #selector(SLV_340_SellDirectStep4PriceController.updateStepProgress), userInfo: nil, repeats: true) } //0.03, 0.12, 0.25, 0.36, 0.48 func updateStepProgress() { progressValue = progressValue + 0.01 self.stepProgressView.progress = progressValue if progressValue > sell_step_4_value { self.progressTimer?.invalidate() self.progressTimer = nil } } } // MARK: - UICollectionViewDelegate - extension SLV_340_SellDirectStep4PriceController: UICollectionViewDelegateFlowLayout { public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let row = indexPath.row if row == 0 { return CGSize(width: self.view.bounds.width, height: 52) } else if row == 1 { return CGSize(width: self.view.bounds.width, height: 170) } else if row == 2 { return CGSize(width: self.view.bounds.width, height: 160) } return .zero } } // MARK: - UICollectionViewDataSource - extension SLV_340_SellDirectStep4PriceController: UICollectionViewDataSource { public func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 3 } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let row = indexPath.row if row == 0 { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SLVPurchasedPriceCell", for: indexPath) as! SLVPurchasedPriceCell if self.purchaseCell == nil { self.purchaseCell = cell self.purchasedTextField = cell.purchasedTestField self.purchasedTextField!.delegate = self } cell.setupButton(block: { (button) in self.purchasedTextField?.becomeFirstResponder() }) return cell } else if row == 1 { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SLVAdjustmentPriceCell", for: indexPath) as! SLVAdjustmentPriceCell if self.adjustCell == nil { self.adjustCell = cell } cell.setupButton(block: { (button) in self.touchDetailAdjustmentPriceInfo(sender: button!) }) return cell } else if row == 2 { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SLVPromotionCell", for: indexPath) as! SLVPromotionCell if self.promotionCell == nil { self.promotionCell = cell } cell.setupButton(block: { (button) in self.promotionTextField.becomeFirstResponder() }) return cell } let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "", for: indexPath) return cell } } extension SLV_340_SellDirectStep4PriceController: KYCircularProgressDelegate { //0.05, 0.272, 0.5, 0.7, 0.9 func progressChanged(progress: Double, circularProgress: KYCircularProgress) { if progress >= sell_step_4_value { self.step4Button.isEnabled = true self.buttonPulse4?.start() } } } extension SLV_340_SellDirectStep4PriceController: ModalTransitionDelegate { func modalViewControllerDismiss(callbackData data:AnyObject?) { log.debug("SLV_340_SellDirectStep4PriceController.modalViewControllerDismiss(callbackData:)") tr_dismissViewController(completion: { if let back = data { let cb = back as! [String: String] let keys = cb.keys if keys.contains("command") == true { let key = cb["command"] if key != nil { if key == "next" { self.next(sender: nil) } } } } }) } } extension SLV_340_SellDirectStep4PriceController: UITextFieldDelegate { func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { self.bottomView.isHidden = true if textField == self.promotionTextField { if textField.inputAccessoryView == nil { textField.inputAccessoryView = self.promotionToolbar } self.promotionToolbar.currentView = textField self.promotionToolbar.textField?.text = "" self.promotionTextField.text = "" } else { let fields = [self.priceTextField, self.purchasedTextField] _ = fields.map() { if textField == $0 { if textField == self.purchasedTextField { self.settingKeypadLayout() } if textField.inputAccessoryView == nil { textField.inputAccessoryView = self.myToolbar } self.myToolbar.currentView = textField return } } } return true } func textFieldDidBeginEditing(_ textField: UITextField) { if textField == self.priceTextField {//텍스트 필드 커스텀 } else if textField == self.purchasedTextField { var value: CGFloat = self.keypadLayout!.constant self.keypadLayout?.constant = 160//커스텀 처리 } } func textFieldShouldReturn(_ textField: UITextField) -> Bool { return true } func textFieldDidEndEditing(_ textField: UITextField) { textField.inputAccessoryView = nil self.bottomView.isHidden = false self.keypadLayout!.constant = 0 var title = textField.text?.trimmed if textField == self.priceTextField { if title == "" { title == "0" } let value = String.removeFormAmount(value: title!).float let commaValue = String.decimalAmountWithForm(value: value!, pointCount: 1) self.priceTextField.text = commaValue//String(fromat: "%.01f", money)//소수점 한자리만 let convertMoney = value! * 10000 let convertValue = convertMoney.cleanValue TempInputInfoModel.shared.currentModel.productPrice = convertValue } else if textField == self.purchasedTextField { self.clearKeypadLayout() if title != "" { let value = String.removeFormAmount(value: title!).float let commaValue = String.decimalAmountWithForm(value: value!, pointCount: 1) self.purchasedTextField?.text = commaValue//String(fromat: "%.01f", money)//소수점 한자리만 TempInputInfoModel.shared.currentModel.purchasedPrice = String.removeFormAmount(value: commaValue) self.purchaseCell?.rigthtView?.isHidden = false } else { self.purchaseCell?.rigthtView?.isHidden = true } } else if textField == self.promotionTextField { } } }
mit
b904aae17d5334d886a4e372ed4a3132
37.688679
228
0.620239
4.786415
false
false
false
false
ello/ello-ios
Specs/Controllers/Stream/Presenters/StreamImageCellPresenterSpec.swift
1
19201
//// /// StreamImageCellPresenterSpec.swift // @testable import Ello import Quick import Nimble class StreamImageCellPresenterSpec: QuickSpec { override func spec() { beforeEach { StreamKind.following.setIsGridView(false) } describe("StreamImageCellPresenter") { context("column number differences") { var post: Post! var imageRegion: ImageRegion! var cell: StreamImageCell! var item: StreamCellItem! beforeEach { post = Post.stub([:]) imageRegion = ImageRegion.stub([:]) cell = StreamImageCell.loadFromNib() item = StreamCellItem(jsonable: post, type: .image(data: imageRegion)) } context("single column") { it("configures fail constraints correctly") { StreamImageCellPresenter.configure( cell, streamCellItem: item, streamKind: .following, indexPath: IndexPath(item: 0, section: 0), currentUser: nil ) expect(cell.isGridView) == false } } context("multiple columns") { it("configures fail constraints correctly") { StreamKind.following.setIsGridView(true) StreamImageCellPresenter.configure( cell, streamCellItem: item, streamKind: .following, indexPath: IndexPath(item: 0, section: 0), currentUser: nil ) expect(cell.isGridView) == true } } } context("no asset") { context("image is a gif") { it("configures a stream image cell") { let post: Post = stub([:]) let imageRegion: ImageRegion = stub([ "url": URL(string: "http://www.example.com/image.gif")! ]) let cell: StreamImageCell = StreamImageCell.loadFromNib() let item: StreamCellItem = StreamCellItem( jsonable: post, type: .image(data: imageRegion) ) StreamImageCellPresenter.configure( cell, streamCellItem: item, streamKind: .following, indexPath: IndexPath(item: 0, section: 0), currentUser: nil ) expect(cell.mode) == StreamImageCellMode.gif expect(cell.isLargeImage) == false expect(cell.largeImagePlayButton?.isHidden) == true } } context("image is not a gif") { it("configures a stream image cell") { let post: Post = stub([:]) let imageRegion: ImageRegion = stub([ "url": URL(string: "http://www.example.com/image.jpg")! ]) let cell: StreamImageCell = StreamImageCell.loadFromNib() let item: StreamCellItem = StreamCellItem( jsonable: post, type: .image(data: imageRegion) ) StreamImageCellPresenter.configure( cell, streamCellItem: item, streamKind: .following, indexPath: IndexPath(item: 0, section: 0), currentUser: nil ) expect(cell.mode) == StreamImageCellMode.image expect(cell.isLargeImage) == false expect(cell.largeImagePlayButton?.isHidden) == true } } } context("has asset") { context("not a gif") { it("configures a stream image cell") { let post: Post = stub([:]) let optimized: Attachment = stub([ "url": URL(string: "http://www.example.com/optimized.jpg")!, "type": "image/jpg", "size": 9999999 ]) let hdpi: Attachment = stub([ "url": URL(string: "http://www.example.com/hdpi.jpg")!, "type": "image/jpg", "size": 445566 ]) let asset: Asset = stub([ "hdpi": hdpi, "optimized": optimized ]) let imageRegion: ImageRegion = stub([ "asset": asset, "url": URL(string: "http://www.example.com/image.jpg")! ]) let cell: StreamImageCell = StreamImageCell.loadFromNib() let item: StreamCellItem = StreamCellItem( jsonable: post, type: .image(data: imageRegion) ) StreamImageCellPresenter.configure( cell, streamCellItem: item, streamKind: .following, indexPath: IndexPath(item: 0, section: 0), currentUser: nil ) expect(cell.mode) == StreamImageCellMode.image expect(cell.isLargeImage) == false expect(cell.largeImagePlayButton?.isHidden) == true } } context("large filesize video") { it("configures a stream image cell") { let post: Post = stub([:]) let optimized: Attachment = stub([ "url": URL(string: "http://www.example.com/optimized.gif")!, "type": "image/gif", "size": 9999999 ]) let hdpi: Attachment = stub([ "url": URL(string: "http://www.example.com/hdpi.gif")!, "type": "image/gif", "size": 445566 ]) let video: Attachment = stub([ "url": URL(string: "http://www.example.com/video.mp4")!, "type": "video/mp4", "size": 9999999 ]) let asset: Asset = stub([ "hdpi": hdpi, "video": video, "optimized": optimized ]) let imageRegion: ImageRegion = stub([ "asset": asset, "url": URL(string: "http://www.example.com/image.gif")! ]) let cell: StreamImageCell = StreamImageCell.loadFromNib() let item: StreamCellItem = StreamCellItem( jsonable: post, type: .image(data: imageRegion) ) StreamImageCellPresenter.configure( cell, streamCellItem: item, streamKind: .following, indexPath: IndexPath(item: 0, section: 0), currentUser: nil ) expect(cell.mode) == StreamImageCellMode.gif expect(cell.isLargeImage) == true expect(cell.largeImagePlayButton?.isHidden) == false } } context("small filesize video") { it("configures a stream image cell") { let post: Post = stub([:]) let optimized: Attachment = stub([ "url": URL(string: "http://www.example.com/optimized.gif")!, "type": "image/gif", "size": 999_999 ]) let hdpi: Attachment = stub([ "url": URL(string: "http://www.example.com/hdpi.gif")!, "type": "image/gif", "size": 445_566 ]) let video: Attachment = stub([ "url": URL(string: "http://www.example.com/video.mp4")!, "type": "video/mp4", "size": 111_111 ]) let asset: Asset = stub([ "hdpi": hdpi, "video": video, "optimized": optimized ]) let imageRegion: ImageRegion = stub([ "asset": asset, "url": URL(string: "http://www.example.com/image.gif")! ]) let cell: StreamImageCell = StreamImageCell.loadFromNib() let item: StreamCellItem = StreamCellItem( jsonable: post, type: .image(data: imageRegion) ) StreamImageCellPresenter.configure( cell, streamCellItem: item, streamKind: .following, indexPath: IndexPath(item: 0, section: 0), currentUser: nil ) expect(cell.mode) == StreamImageCellMode.gif expect(cell.isLargeImage) == false expect(cell.largeImagePlayButton?.isHidden) == true } } context("large filesize gif") { it("configures a stream image cell") { let post: Post = stub([:]) let optimized: Attachment = stub([ "url": URL(string: "http://www.example.com/optimized.gif")!, "type": "image/gif", "size": 9999999 ]) let hdpi: Attachment = stub([ "url": URL(string: "http://www.example.com/hdpi.gif")!, "type": "image/gif", "size": 445566 ]) let asset: Asset = stub([ "hdpi": hdpi, "optimized": optimized ]) let imageRegion: ImageRegion = stub([ "asset": asset, "url": URL(string: "http://www.example.com/image.gif")! ]) let cell: StreamImageCell = StreamImageCell.loadFromNib() let item: StreamCellItem = StreamCellItem( jsonable: post, type: .image(data: imageRegion) ) StreamImageCellPresenter.configure( cell, streamCellItem: item, streamKind: .following, indexPath: IndexPath(item: 0, section: 0), currentUser: nil ) expect(cell.mode) == StreamImageCellMode.gif expect(cell.isLargeImage) == true expect(cell.largeImagePlayButton?.isHidden) == false } } context("small filesize gif") { it("configures a stream image cell") { let post: Post = stub([:]) let optimized: Attachment = stub([ "url": URL(string: "http://www.example.com/optimized.gif")!, "type": "image/gif", "size": 445566 ]) let hdpi: Attachment = stub([ "url": URL(string: "http://www.example.com/hdpi.gif")!, "type": "image/gif", "size": 445566 ]) let asset: Asset = stub([ "hdpi": hdpi, "optimized": optimized ]) let imageRegion: ImageRegion = stub([ "asset": asset, "url": URL(string: "http://www.example.com/image.gif")! ]) let cell: StreamImageCell = StreamImageCell.loadFromNib() let item: StreamCellItem = StreamCellItem( jsonable: post, type: .image(data: imageRegion) ) StreamImageCellPresenter.configure( cell, streamCellItem: item, streamKind: .following, indexPath: IndexPath(item: 0, section: 0), currentUser: nil ) expect(cell.mode) == StreamImageCellMode.gif expect(cell.isLargeImage) == false expect(cell.largeImagePlayButton?.isHidden) == true } } context("buyButton link") { it("hides buyButton by default") { let post: Post = stub([:]) let imageRegion: ImageRegion = stub([:]) let cell: StreamImageCell = StreamImageCell.loadFromNib() let item: StreamCellItem = StreamCellItem( jsonable: post, type: .image(data: imageRegion) ) StreamImageCellPresenter.configure( cell, streamCellItem: item, streamKind: .following, indexPath: IndexPath(item: 0, section: 0), currentUser: nil ) expect(cell.buyButton?.isHidden) == true expect(cell.buyButtonGreen?.isHidden) == true } it("shows buyButton if link is present") { let post: Post = stub([:]) let imageRegion: ImageRegion = stub([ "buyButtonURL": URL(string: "https://amazon.com")! ]) let cell: StreamImageCell = StreamImageCell.loadFromNib() let item: StreamCellItem = StreamCellItem( jsonable: post, type: .image(data: imageRegion) ) StreamImageCellPresenter.configure( cell, streamCellItem: item, streamKind: .following, indexPath: IndexPath(item: 0, section: 0), currentUser: nil ) expect(cell.buyButton?.isHidden) == false expect(cell.buyButtonGreen?.isHidden) == false } it("sets buy button width to 40 in list") { let post: Post = stub([:]) let imageRegion: ImageRegion = stub([ "buyButtonURL": URL(string: "https://amazon.com")! ]) let cell: StreamImageCell = StreamImageCell.loadFromNib() let item: StreamCellItem = StreamCellItem( jsonable: post, type: .image(data: imageRegion) ) StreamImageCellPresenter.configure( cell, streamCellItem: item, streamKind: .following, indexPath: IndexPath(item: 0, section: 0), currentUser: nil ) cell.layoutIfNeeded() expect(cell.buyButtonGreen?.frame.size.width) == 40 expect(cell.buyButtonGreen?.frame.size.height) == 40 } it("sets buy button width to 30 in grid") { StreamKind.following.setIsGridView(true) let post: Post = stub([:]) let imageRegion: ImageRegion = stub([ "buyButtonURL": URL(string: "https://amazon.com")! ]) let cell: StreamImageCell = StreamImageCell.loadFromNib() let item: StreamCellItem = StreamCellItem( jsonable: post, type: .image(data: imageRegion) ) StreamImageCellPresenter.configure( cell, streamCellItem: item, streamKind: .following, indexPath: IndexPath(item: 0, section: 0), currentUser: nil ) cell.layoutIfNeeded() expect(cell.buyButtonGreen?.frame.size.width) == 30 expect(cell.buyButtonGreen?.frame.size.height) == 30 } } } } } }
mit
9f432e096b944d4d9f208895913fc7a6
39.085595
90
0.378314
6.522079
false
false
false
false
CartoDB/mobile-ios-samples
AdvancedMap.Swift/Feature Demo/Package.swift
1
4019
// // Country.swift // AdvancedMap.Swift // // Created by Aare Undo on 27/06/2017. // Copyright © 2017 CARTO. All rights reserved. // import Foundation import CartoMobileSDK class Package : NSObject { var id: String! var name: String! var status: NTPackageStatus! var info: NTPackageInfo! static let BBOX_IDENTIFIER = "bbox(" var isCustomRegionPackage: Bool { get { if (id == nil) { return false; } return id.contains(Package.BBOX_IDENTIFIER) } } static let CUSTOM_REGION_FOLDER_NAME = "CUSTOM REGIONS" var isCustomRegionFolder: Bool { get { return name == Package.CUSTOM_REGION_FOLDER_NAME } } func isGroup() -> Bool { // Custom region packages will have status & info == nil, but they're not groups return status == nil && info == nil && !isCustomRegionPackage } func isSmallerThan1MB() -> Bool { return info.getSize() < (1024 * 1024); } func getStatusText() -> String { var status = "Available"; status += getVersionAndSize() // Check if the package is downloaded/is being downloaded (so that status is not null) if (self.status != nil) { if (self.status.getCurrentAction() == NTPackageAction.PACKAGE_ACTION_READY) { status = "Ready"; status += getVersionAndSize() } else if (self.status.getCurrentAction() == NTPackageAction.PACKAGE_ACTION_WAITING) { status = "Queued"; } else { if (self.status.getCurrentAction() == NTPackageAction.PACKAGE_ACTION_COPYING) { status = "Copying"; } else if (self.status.getCurrentAction() == NTPackageAction.PACKAGE_ACTION_DOWNLOADING) { status = "Downloading"; } else if (self.status.getCurrentAction() == NTPackageAction.PACKAGE_ACTION_REMOVING) { status = "Removing"; } status += " " + String(describing: self.status.getProgress()) + "%"; } } return status; } func getVersionAndSize() -> String { if (isCustomRegionPackage) { return ""; } let version = String(info.getVersion()) let size = String(describing: info.getSizeInMB()) if (isSmallerThan1MB()) { return " v." + version + " (<1MB)"; } return " v." + version + " (" + size + " MB)"; } static let READY = "READY" static let QUEUED = "QUEUED" static let ACTION_PAUSE = "PAUSE" static let ACTION_RESUME = "RESUME" static let ACTION_CANCEL = "CANCEL" static let ACTION_DOWNLOAD = "DOWNLOAD" static let ACTION_REMOVE = "REMOVE" var isDownloading: Bool { if (status == nil) { return false } return status.getCurrentAction() == NTPackageAction.PACKAGE_ACTION_DOWNLOADING && !status.isPaused() } var isQueued: Bool { if (status == nil) { return false } return status.getCurrentAction() == NTPackageAction.PACKAGE_ACTION_WAITING && !status.isPaused() } func getActionText() -> String { if (self.status == nil) { return Package.ACTION_DOWNLOAD } if (self.status.getCurrentAction() == NTPackageAction.PACKAGE_ACTION_READY) { return Package.ACTION_REMOVE } else if (self.status.getCurrentAction() == NTPackageAction.PACKAGE_ACTION_WAITING) { return Package.ACTION_CANCEL } if (status.isPaused()) { return Package.ACTION_RESUME } else { return Package.ACTION_PAUSE } } }
bsd-2-clause
583faeff97e86451e5798560b10fd1a4
26.520548
108
0.531608
4.571104
false
false
false
false
ifeherva/HSTracker
HSTracker/Logging/LogReaderManager.swift
1
6572
/* * This file is part of the HSTracker package. * (c) Benjamin Michotte <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * Created on 13/02/16. */ import Foundation import BTree final class LogReaderManager { // lower update times result in faster operation but higher CPU usage static let updateDelay: TimeInterval = 0.05 let powerGameStateParser: LogEventParser let rachelleHandler = RachelleHandler() let arenaHandler: LogEventParser let loadingScreenHandler: LogEventParser private let powerLog: LogReader private let rachelle: LogReader private let arena: LogReader private let loadingScreen: LogReader private var readers: [LogReader] { return [powerLog, rachelle, arena, loadingScreen] } public static let dateStringFormatter: LogDateFormatter = { let formatter = LogDateFormatter() formatter.locale = Locale(identifier: "en_US_POSIX") formatter.dateFormat = "HH:mm:ss" return formatter }() public static let iso8601StringFormatter: LogDateFormatter = { let formatter = LogDateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" return formatter }() public static let fullDateStringFormatter: LogDateFormatter = { let formatter = LogDateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm:ssZZZZZ" return formatter }() public static let timeZone = TimeZone.current public static let calendar = Calendar.current var running = false var stopped = false private var queue: DispatchQueue? private var processMap = Map<LogDate, [LogLine]>() private let coreManager: CoreManager init(logPath: String, coreManager: CoreManager) { self.coreManager = coreManager loadingScreenHandler = LoadingScreenHandler(with: coreManager) powerGameStateParser = PowerGameStateParser(with: coreManager.game) arenaHandler = ArenaHandler(with: coreManager) let rx = "GameState.DebugPrintEntityChoices\\(\\)\\s-\\sid=(\\d) Player=(.+) TaskList=(\\d)" let plReader = LogReaderInfo(name: .power, startsWithFilters: [["PowerTaskList.DebugPrintPower", rx], ["GameState."]], containsFilters: [["Begin Spectating", "Start Spectator", "End Spectator"], []]) powerLog = LogReader(info: plReader, logPath: logPath) rachelle = LogReader(info: LogReaderInfo(name: .rachelle), logPath: logPath) arena = LogReader(info: LogReaderInfo(name: .arena), logPath: logPath) loadingScreen = LogReader(info: LogReaderInfo(name: .loadingScreen, startsWithFilters: [[ "LoadingScreen.OnSceneLoaded", "Gameplay"]]), logPath: logPath) } func start() { guard !running else { logger.error("LogReaderManager is already running") return } logger.info("LogReaderManager is starting") queue = DispatchQueue(label: "be.michotte.hstracker.logReaderManager", attributes: []) guard let queue = queue else { logger.error("LogReaderManager can not create queue") return } queue.async { self.startLogReaders() } } private func startLogReaders() { stopped = false running = true let entryPoint = self.entryPoint() for reader in readers { reader.start(manager: self, entryPoint: entryPoint) } while !stopped { autoreleasepool { for reader in readers { let loglines = reader.collect(index: 0) for line in loglines { var lineList: [LogLine]? if let loglist = processMap[line.time] { lineList = loglist } else { lineList = [LogLine]() } lineList?.append(line) processMap[line.time] = lineList } } // save powerlines for replay upload let powerLines = powerLog.collect(index: 1) for line in powerLines { coreManager.game.add(powerLog: line) } for lineList in processMap.values { if stopped { break } for line in lineList { if stopped { break } processLine(line: line) } } processMap.removeAll() } Thread.sleep(forTimeInterval: LogReaderManager.updateDelay) } running = false } func stop(eraseLogFile: Bool) { logger.info("Stopping all trackers") stopped = true running = false for reader in readers { reader.stop(eraseLogFile: eraseLogFile) } } func restart(eraseLogFile: Bool = false) { logger.info("LogReaderManager is restarting") stop(eraseLogFile: eraseLogFile) start() } private func entryPoint() -> LogDate { let powerEntry = powerLog.findEntryPoint(choices: ["tag=GOLD_REWARD_STATE", "End Spectator"]) let loadingScreenEntry = loadingScreen.findEntryPoint(choice: "Gameplay.Start") let pe = LogReaderManager.iso8601StringFormatter.string(from: powerEntry) let lse = LogReaderManager.iso8601StringFormatter.string(from: loadingScreenEntry) logger.verbose("powerEntry : \(pe) / loadingScreenEntry : \(lse)") return powerEntry > loadingScreenEntry ? powerEntry : loadingScreenEntry } private func processLine(line: LogLine) { switch line.namespace { case .power: self.powerGameStateParser.handle(logLine: line) case .rachelle: self.rachelleHandler.handle(logLine: line) case .arena: self.arenaHandler.handle(logLine: line) case .loadingScreen: self.loadingScreenHandler.handle(logLine: line) default: break } } }
mit
d35e98291748b9ca79c4d57e95ffb2fe
34.144385
112
0.577298
4.846608
false
false
false
false
tuffz/pi-weather-app
Carthage/Checkouts/realm-cocoa/examples/tvos/swift-2.2/PreloadedData/PlacesViewController.swift
1
2432
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // 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 UIKit import RealmSwift class PlacesViewController: UITableViewController, UITextFieldDelegate { @IBOutlet weak var searchField: UITextField! var results: Results<Place>? override func viewDidLoad() { super.viewDidLoad() let seedFileURL = NSBundle.mainBundle().URLForResource("Places", withExtension: "realm") let config = Realm.Configuration(fileURL: seedFileURL, readOnly: true) Realm.Configuration.defaultConfiguration = config reloadData() } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return results?.count ?? 0 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) let place = results![indexPath.row] cell.textLabel!.text = place.postalCode if let county = place.county { cell.detailTextLabel!.text = String(format: "%@, %@, %@", place.placeName!, place.state!, county) } else { cell.detailTextLabel!.text = String(format: "%@, %@", place.placeName!, place.state!) } return cell } func reloadData() { let realm = try! Realm() results = realm.objects(Place.self) if let text = searchField.text where !text.isEmpty { results = results?.filter("postalCode beginswith %@", text) } results = results?.sorted("postalCode") tableView?.reloadData() } func textFieldDidEndEditing(textField: UITextField) { reloadData() } }
mit
0418bfd12e37c75736c2a0e4ef5ec4ee
33.742857
118
0.632813
5.207709
false
true
false
false
cdtschange/SwiftMKit
SwiftMKitDemo/SwiftMKitDemo/UI/UI/TreeView/MKUITreeViewCellTableViewCell.swift
1
4191
// // MKUITreeViewCellTableViewCell.swift // SwiftMKitDemo // // Created by apple on 16/5/26. // Copyright © 2016年 cdts. All rights reserved. // import UIKit import CocoaLumberjack class MKUITreeViewCellTableViewCell: UITableViewCell { var parentNode: MKTreeViewNode? var node: MKTreeViewNode? { willSet { if lblName != nil { lblName.text = newValue!.name indentationLevel = newValue!.depth indentationWidth = 30 if imgPoint != nil { imgPoint.isHidden = newValue!.parentId != -1 } // 判断是否需要设置圆角 if let fatherNode = parentNode { if let children = fatherNode.children { var maskPath: UIBezierPath = UIBezierPath() // FIXME: 宽度计算!!! bgView.w = UIScreen.main.bounds.size.width - 39 - 15 if children.count == 1 { // 上下左右四个圆角 maskPath = UIBezierPath(roundedRect: bgView.bounds, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: InnerConst.CornerRadius, height: InnerConst.CornerRadius)) } else { if newValue?.nodeId == children.first?.nodeId { // 第一个cell 上边需要圆角 maskPath = UIBezierPath(roundedRect: bgView.bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: InnerConst.CornerRadius, height: InnerConst.CornerRadius)) } else if newValue?.nodeId == children.last?.nodeId { // 最后一个cell 下边需要圆角 maskPath = UIBezierPath(roundedRect: bgView.bounds, byRoundingCorners: [.bottomLeft, .bottomRight], cornerRadii: CGSize(width: InnerConst.CornerRadius, height: InnerConst.CornerRadius)) } else { maskPath = UIBezierPath(roundedRect: bgView.bounds, byRoundingCorners: .allCorners, cornerRadii: CGSize.zero) } } let maskLayer = CAShapeLayer() maskLayer.frame = bgView.bounds maskLayer.path = maskPath.cgPath bgView.layer.mask = maskLayer } } else { guard let children = newValue!.children, children.count > 0 else { imgArrow.isHidden = true return } // 这里可以正常使用children变量 imgArrow.isHidden = false } } } } @IBOutlet weak var lblName: UILabel! @IBOutlet weak var imgPoint: UIImageView! @IBOutlet weak var lineView_V: UIView! @IBOutlet weak var bgView: UIView! @IBOutlet weak var imgArrow: UIImageView! @IBOutlet weak var imgLastArrow: UIImageView! weak var lbl: UILabel? @IBOutlet weak var lblName_LeftConstraint: NSLayoutConstraint! struct InnerConst { static let CellID_Parent = "ParentCell" static let CellID_Sub = "SubCell" static let NibName = "MKUITreeViewCellTableViewCell" static let CornerRadius: CGFloat = 7 } override func awakeFromNib() { super.awakeFromNib() self.selectionStyle = .none contentView.backgroundColor = UIColor(r: 240/255.0, g: 243/255.0, b: 252/255.0, a: 1.0) } class func getCell(_ tableView: UITableView, isParentNode: Bool) -> MKUITreeViewCellTableViewCell { let ID = isParentNode ? InnerConst.CellID_Parent : InnerConst.CellID_Sub var cell = tableView.dequeueReusableCell(withIdentifier: ID) as? MKUITreeViewCellTableViewCell if cell == nil { let index = isParentNode ? 0 : 1 cell = Bundle.main.loadNibNamed(InnerConst.NibName, owner: nil, options: nil)![index] as? MKUITreeViewCellTableViewCell } return cell! } }
mit
cd5f28d3d762db31c747367b862b54db
43.347826
217
0.56152
5.257732
false
false
false
false
czechboy0/BuildaUtils
Source/Script.swift
2
4323
// // Script.swift // Buildasaur // // Created by Honza Dvorsky on 12/05/15. // Copyright (c) 2015 Honza Dvorsky. All rights reserved. // import Foundation /** * A utility class for running terminal Scripts from your Mac app. */ #if os(OSX) open class Script { public typealias ScriptResponse = (terminationStatus: Int, standardOutput: String, standardError: String) /** * Run a script by passing in a name of the script (e.g. if you use just 'git', it will first * resolve by using the 'git' at path `which git`) or the full path (such as '/usr/bin/git'). * Optional arguments are passed in as an array of Strings and an optional environment dictionary * as a map from String to String. * Back you get a 'ScriptResponse', which is a tuple around the termination status and outputs (standard and error). */ open class func run(_ name: String, arguments: [String] = [], environment: [String: String] = [:]) -> ScriptResponse { //first resolve the name of the script to a path with `which` let resolved = self.runResolved("/usr/bin/which", arguments: [name], environment: [:]) //which returns the path + \n, so strip the newline let path = resolved.standardOutput.stripTrailingNewline() //if resolving failed, just abort and propagate the failed run up if (resolved.terminationStatus != 0) || path.isEmpty { return resolved } //ok, we have a valid path, run the script let result = self.runResolved(path, arguments: arguments, environment: environment) return result } /** * An alternative to Script.run is Script.runInTemporaryScript, which first dumps the passed in script * string into a temporary file, runs it and then deletes it. More useful for more complex script that involve * piping data between multiple scripts etc. Might be slower than Script.run, however. */ open class func runTemporaryScript(_ script: String) -> ScriptResponse { var resp: ScriptResponse! self.runInTemporaryScript(script, block: { (scriptPath, error) -> () in resp = Script.run("/bin/bash", arguments: [scriptPath]) }) return resp } fileprivate class func runInTemporaryScript(_ script: String, block: (_ scriptPath: String, _ error: NSError?) -> ()) { let uuid = UUID().uuidString // Bug? https://forums.developer.apple.com/thread/13580 let tempPath = (NSTemporaryDirectory() as NSString).appendingPathComponent(uuid) do { //write the script to file try script.write(toFile: tempPath, atomically: true, encoding: String.Encoding.utf8) block(tempPath, nil) //delete the temp script try FileManager.default.removeItem(atPath: tempPath) } catch { Log.error(error) } } fileprivate class func runResolved(_ path: String, arguments: [String], environment: [String: String]) -> ScriptResponse { let outputPipe = Pipe() let errorPipe = Pipe() let outputFile = outputPipe.fileHandleForReading let errorFile = errorPipe.fileHandleForReading let task = Process() task.launchPath = path task.arguments = arguments var env = ProcessInfo.processInfo.environment for (_, keyValue) in environment.enumerated() { env[keyValue.0] = keyValue.1 } task.environment = env task.standardOutput = outputPipe task.standardError = errorPipe task.launch() task.waitUntilExit() let terminationStatus = Int(task.terminationStatus) let output = self.stringFromFileAndClose(outputFile) let error = self.stringFromFileAndClose(errorFile) return (terminationStatus, output, error) } fileprivate class func stringFromFileAndClose(_ file: FileHandle) -> String { let data = file.readDataToEndOfFile() file.closeFile() let output = String(data: data, encoding: String.Encoding.utf8) return output ?? "" } } #endif
mit
2e208809f6f73a50831d9e67e41462e3
35.635593
126
0.622947
4.798002
false
false
false
false
ben-ng/swift
validation-test/compiler_crashers_fixed/00228-swift-clangimporter-loadextensions.swift
1
720
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck func s() -> o { r q { } protocol p { typealias m = q } m r : p { } func r<s : t, o : p where o.m == s> (s: o) { } func r<s : p where s.m == s> (s: s) { } m s<p : u> { } class t<s : s, r : s where s.t == r> : q { } class t<s, r> { } protocol s { func r() { } } func t(s) -> <p>(() -> p) { } class q<m : t
apache-2.0
a5dcc6c9f5e2746ebfea1ae9a3c432f7
20.818182
79
0.595833
2.779923
false
false
false
false
413738916/ZhiBoTest
ZhiBoSwift/ZhiBoSwift/Classes/Home/ViewModel/RecommendViewModel.swift
1
4102
// // RecommendViewModel.swift // ZhiBoSwift // // Created by 123 on 2017/10/30. // Copyright © 2017年 ct. All rights reserved. // import UIKit class RecommendViewModel : BaseViewModel { lazy var cycleModels : [CycleModel] = [CycleModel]() fileprivate lazy var bigDataGroup : AnchorGroup = AnchorGroup() fileprivate lazy var prettyGroup : AnchorGroup = AnchorGroup() } extension RecommendViewModel { func requestData(_ finishCallback : @escaping () -> ()) { // 1.定义参数 let parameters = ["limit" : "4", "offset" : "0", "time" : Date.getCurrentTime()] // 2.创建Group let dGroup = DispatchGroup() // 3.请求第一部分推荐数据 dGroup.enter() NetworkTools.requestData(.get, URLString: "http://capi.douyucdn.cn/api/v1/getbigDataRoom", parameters: ["time" : Date.getCurrentTime()]) { (result) in // 1.将result转成字典类型 guard let resultDict = result as? [String : NSObject] else { return } // 2.根据data该key,获取数组 guard let dataArray = resultDict["data"] as? [[String : NSObject]] else { return } // 3.遍历字典,并且转成模型对象 // 3.1.设置组的属性 self.bigDataGroup.tag_name = "热门" self.bigDataGroup.icon_name = "home_header_hot" // 3.2.获取主播数据 for dict in dataArray { let anchor = AnchorModel(dict: dict) self.bigDataGroup.anchors.append(anchor) } // 3.3.离开组 dGroup.leave() } // 4.请求第二部分颜值数据 dGroup.enter() NetworkTools.requestData(.get, URLString: "http://capi.douyucdn.cn/api/v1/getVerticalRoom", parameters: parameters) { (result) in // 1.将result转成字典类型 guard let resultDict = result as? [String : NSObject] else { return } // 2.根据data该key,获取数组 guard let dataArray = resultDict["data"] as? [[String : NSObject]] else { return } // 3.遍历字典,并且转成模型对象 // 3.1.设置组的属性 self.prettyGroup.tag_name = "颜值" self.prettyGroup.icon_name = "home_header_phone" // 3.2.获取主播数据 for dict in dataArray { let anchor = AnchorModel(dict: dict) self.prettyGroup.anchors.append(anchor) } // 3.3.离开组 dGroup.leave() } // 5.请求2-12部分游戏数据 dGroup.enter() // http://capi.douyucdn.cn/api/v1/getHotCate?limit=4&offset=0&time=1474252024 loadAnchorData(isGroupData: true, URLString: "http://capi.douyucdn.cn/api/v1/getHotCate", parameters: parameters) { dGroup.leave() } // 6.所有的数据都请求到,之后进行排序 dGroup.notify(queue: DispatchQueue.main) { self.anchorGroups.insert(self.prettyGroup, at: 0) self.anchorGroups.insert(self.bigDataGroup, at: 0) finishCallback() } } // 请求无线轮播的数据 func requestCycleData(_ finishCallback : @escaping () -> ()) { NetworkTools.requestData(.get, URLString: "http://www.douyutv.com/api/v1/slide/6", parameters: ["version" : "2.300"]) { (result) in // 1.获取整体字典数据 guard let resultDict = result as? [String : NSObject] else { return } // 2.根据data的key获取数据 guard let dataArray = resultDict["data"] as? [[String : NSObject]] else { return } // 3.字典转模型对象 for dict in dataArray { self.cycleModels.append(CycleModel(dict: dict)) } finishCallback() } } }
mit
4c94fcf98170f5fe803166551f96cb1c
32.633929
158
0.533581
4.527644
false
false
false
false
spaceelephant/SESlideTableViewCell
SESlideTableViewCell/SESwiftTableViewController.swift
1
16479
// // SESwiftTableViewController.swift // slidetableviewcell // // Created by letdown on 2014/07/15. // Copyright (c) 2014 Space Elephant. All rights reserved. // import UIKit enum CellIndex : Int { case rightButtons case rightButtonsAndDisclosureIndicator case rightLongButtons case threeRightButtons case rightImageButton case rightImageTextButton case leftRightButtons case leftButtons case backgroundColor case contentUpdate case slideElasticity case count } class SESwiftTableViewController: UITableViewController, SESlideTableViewCellDelegate { var collation: UILocalizedIndexedCollation? var rightButtonDisabled: Bool = false var leftButtonDisabled: Bool = false var value: Int = 0 override func viewDidLoad() { super.viewDidLoad() let button = UIBarButtonItem(title: "Index", style: .plain, target:self, action: #selector(SESwiftTableViewController.indexButtonDidTap(_:))) navigationItem.rightBarButtonItem = button let segmentedControl = UISegmentedControl(items: ["L" as NSString, "R" as NSString]) segmentedControl.isMomentary = true segmentedControl.addTarget(self, action: #selector(SESwiftTableViewController.toggleLeftAndRightButtons(_:)), for: .valueChanged) self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: segmentedControl) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } //MARK - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { if collation != nil { return collation!.sectionIndexTitles.count } else { return 1 } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return CellIndex.count.rawValue } override func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int { if collation != nil { return collation!.section(forSectionIndexTitle: index) } return index } override func sectionIndexTitles(for tableView: UITableView) -> [String]? { return collation?.sectionIndexTitles } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if collation != nil { return collation!.sectionTitles[section] } return nil } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellIndex = CellIndex(rawValue: (indexPath as NSIndexPath).row) switch cellIndex! { case .rightButtons: let CELL_ID = "Cell0" var cell = tableView.dequeueReusableCell(withIdentifier: CELL_ID) as? SESlideTableViewCell if cell == nil { cell = SESlideTableViewCell(style: .default, reuseIdentifier: CELL_ID) cell!.selectionStyle = .none cell!.delegate = self cell!.textLabel!.text = "Cell with Right Buttons" cell!.addRightButton(withText: "Hello", textColor: UIColor.white, backgroundColor: UIColor(hue: 0.0/360.0, saturation: 0.8, brightness: 0.9, alpha: 1.0)) cell!.addRightButton(withText: "World!!", textColor: UIColor.white, backgroundColor: UIColor(hue: 180.0/360.0, saturation: 0.8, brightness: 0.9, alpha: 1.0)) } cell!.showsLeftSlideIndicator = !leftButtonDisabled cell!.showsRightSlideIndicator = !rightButtonDisabled return cell! case .rightButtonsAndDisclosureIndicator: let CELL_ID = "Cell1" var cell = tableView.dequeueReusableCell(withIdentifier: CELL_ID) as? SESlideTableViewCell if cell == nil { cell = SESlideTableViewCell(style: .default, reuseIdentifier: CELL_ID) cell!.selectionStyle = .none cell!.delegate = self cell!.textLabel!.text = "Cell with Right Buttons and Disclosure Indicator" cell!.addRightButton(withText: "Hello", textColor: UIColor.white, backgroundColor: UIColor(hue: 0.0/360.0, saturation: 0.8, brightness: 0.9, alpha: 1.0)) cell!.addRightButton(withText: "World!!", textColor: UIColor.white, backgroundColor: UIColor(hue: 180.0/360.0, saturation: 0.8, brightness: 0.9, alpha: 1.0)) cell!.accessoryType = .disclosureIndicator } cell!.showsLeftSlideIndicator = !leftButtonDisabled cell!.showsRightSlideIndicator = !rightButtonDisabled return cell! case .rightLongButtons: let CELL_ID = "Cell2" var cell = tableView.dequeueReusableCell(withIdentifier: CELL_ID) as? SESlideTableViewCell if cell == nil { cell = SESlideTableViewCell(style: .default, reuseIdentifier: CELL_ID) cell!.selectionStyle = .none cell!.delegate = self cell!.textLabel!.text = "Cell with Right Buttons" cell!.addRightButton(withText: "Hello", textColor: UIColor.white, backgroundColor: UIColor(hue: 0.0/360.0, saturation: 0.8, brightness: 0.9, alpha: 1.0)) cell!.addRightButton(withText: "World with Love", textColor: UIColor.white, backgroundColor: UIColor(hue: 180.0/360.0, saturation: 0.8, brightness: 0.9, alpha: 1.0), font:UIFont.boldSystemFont(ofSize: 24)) } cell!.showsLeftSlideIndicator = !leftButtonDisabled cell!.showsRightSlideIndicator = !rightButtonDisabled return cell! case .threeRightButtons: let CELL_ID = "Cell3" var cell = tableView.dequeueReusableCell(withIdentifier: CELL_ID) as? SESlideTableViewCell if cell == nil { cell = SESlideTableViewCell(style: .default, reuseIdentifier: CELL_ID) cell!.selectionStyle = .none cell!.delegate = self cell!.textLabel!.text = "Cell with three Right Buttons" cell!.addRightButton(withText: "Hello", textColor: UIColor.white, backgroundColor: UIColor(hue: 0.0/360.0, saturation: 0.8, brightness: 0.9, alpha: 1.0)) cell!.addRightButton(withText: "World", textColor: UIColor.white, backgroundColor: UIColor(hue: 180.0/360.0, saturation: 0.8, brightness: 0.9, alpha: 1.0)) cell!.addRightButton(withText: "Again", textColor: UIColor.white, backgroundColor: UIColor(hue: 120.0/360.0, saturation: 0.8, brightness: 0.9, alpha: 1.0)) } cell!.showsLeftSlideIndicator = !leftButtonDisabled cell!.showsRightSlideIndicator = !rightButtonDisabled return cell! case .rightImageButton: let CELL_ID = "Cell4" var cell = tableView.dequeueReusableCell(withIdentifier: CELL_ID) as? SESlideTableViewCell if cell == nil { cell = SESlideTableViewCell(style: .default, reuseIdentifier: CELL_ID) cell!.selectionStyle = .none cell!.delegate = self cell!.textLabel!.text = "Cell with a Right Image Button" cell!.addRightButton(with: UIImage(named: "image-cloud"), backgroundColor: UIColor(hue: 0.0/360.0, saturation: 0.8, brightness: 0.9, alpha: 1.0)) } cell!.showsLeftSlideIndicator = !leftButtonDisabled cell!.showsRightSlideIndicator = !rightButtonDisabled return cell! case .rightImageTextButton: let CELL_ID = "CellRightImageTextButton" var cell = tableView.dequeueReusableCell(withIdentifier: CELL_ID) as? SESlideTableViewCell if cell == nil { cell = SESlideTableViewCell(style: .default, reuseIdentifier: CELL_ID) cell!.selectionStyle = .none cell!.delegate = self cell!.textLabel!.text = "Cell with a Right Image Text Button" cell!.addRightButton(with: UIImage(named: "image-cloud-small"), text: "Hello", textColor: UIColor.white, font: nil, backgroundColor: UIColor(hue: 0.0/360.0, saturation: 0.8, brightness: 0.9, alpha: 1.0)) } cell!.showsLeftSlideIndicator = !leftButtonDisabled cell!.showsRightSlideIndicator = !rightButtonDisabled return cell! case .leftRightButtons: let CELL_ID = "Cell5" var cell = tableView.dequeueReusableCell(withIdentifier: CELL_ID) as? SESlideTableViewCell if cell == nil { cell = SESlideTableViewCell(style: .default, reuseIdentifier: CELL_ID) cell!.selectionStyle = .none cell!.delegate = self cell!.textLabel!.text = "Cell with Left and Right Buttons" cell!.addRightButton(withText: "Hello", textColor: UIColor.white, backgroundColor: UIColor(hue: 0.0/360.0, saturation: 0.8, brightness: 0.9, alpha: 1.0)) cell!.addRightButton(withText: "Right World!!", textColor: UIColor.white, backgroundColor: UIColor(hue: 180.0/360.0, saturation: 0.8, brightness: 0.9, alpha: 1.0)) cell!.addLeftButton(withText: "Hello", textColor: UIColor.white, backgroundColor: UIColor(hue: 0.0/360.0, saturation: 0.8, brightness: 0.9, alpha: 1.0)) cell!.addLeftButton(withText: "Left World!!", textColor: UIColor.white, backgroundColor: UIColor(hue: 180.0/360.0, saturation: 0.8, brightness: 0.9, alpha: 1.0)) } cell!.showsLeftSlideIndicator = !leftButtonDisabled cell!.showsRightSlideIndicator = !rightButtonDisabled return cell! case .leftButtons: let CELL_ID = "Cell6" var cell = tableView.dequeueReusableCell(withIdentifier: CELL_ID) as? SESlideTableViewCell if cell == nil { cell = SESlideTableViewCell(style: .default, reuseIdentifier: CELL_ID) cell!.selectionStyle = .none cell!.delegate = self cell!.textLabel!.text = "Cell with Left Buttons" cell!.addLeftButton(withText: "Hello", textColor: UIColor.white, backgroundColor: UIColor(hue: 0.0/360.0, saturation: 0.8, brightness: 0.9, alpha: 1.0)) cell!.addLeftButton(withText: "World!!", textColor: UIColor.white, backgroundColor: UIColor(hue: 180.0/360.0, saturation: 0.8, brightness: 0.9, alpha: 1.0)) cell!.accessoryType = .disclosureIndicator } cell!.showsLeftSlideIndicator = !leftButtonDisabled cell!.showsRightSlideIndicator = !rightButtonDisabled return cell! case .backgroundColor: let CELL_ID = "Cell7" var cell = tableView.dequeueReusableCell(withIdentifier: CELL_ID) as? SESlideTableViewCell if cell == nil { cell = SESlideTableViewCell(style: .default, reuseIdentifier: CELL_ID) cell!.selectionStyle = .none cell!.delegate = self let bgColor = UIColor(hue: 210/360.0, saturation: 0.1, brightness: 0.9, alpha: 1.0) cell!.backgroundColor = bgColor cell!.slideBackgroundColor = bgColor cell!.indicatorColor = UIColor(hue: 12/360.0, saturation: 0.8, brightness: 0.9, alpha: 1.0) cell!.textLabel!.text = "Cell with Background Color" cell!.addRightButton(withText: "Hello", textColor: UIColor.white, backgroundColor: UIColor(hue: 0/360.0, saturation: 0.8, brightness: 0.9, alpha: 1.0)) cell!.addRightButton(withText: "World!!", textColor: UIColor.white, backgroundColor: UIColor(hue: 180/360.0, saturation: 0.8, brightness: 0.9, alpha: 1.0)) } cell!.showsLeftSlideIndicator = !leftButtonDisabled cell!.showsRightSlideIndicator = !rightButtonDisabled return cell! case .contentUpdate: let CELL_ID = "Cell8" var cell = tableView.dequeueReusableCell(withIdentifier: CELL_ID) as? SESlideTableViewCell if cell == nil { cell = SESlideTableViewCell(style: .default, reuseIdentifier: CELL_ID) cell!.selectionStyle = .none cell!.delegate = self cell!.addRightButton(withText: "-", textColor: UIColor.white, backgroundColor: UIColor(hue: 180.0/360.0, saturation: 0.8, brightness: 0.9, alpha: 1.0)) cell!.addRightButton(withText: "+", textColor: UIColor.white, backgroundColor: UIColor(hue: 0.0/360.0, saturation: 0.8, brightness: 0.9, alpha: 1.0)) } configureCell(cell, atIndex: (indexPath as NSIndexPath).row) cell!.showsLeftSlideIndicator = !leftButtonDisabled cell!.showsRightSlideIndicator = !rightButtonDisabled return cell! case .slideElasticity: let CELL_ID = "CellSlideElasticity" var cell = tableView.dequeueReusableCell(withIdentifier: CELL_ID) as? SESlideTableViewCell if cell == nil { cell = SESlideTableViewCell(style: .default, reuseIdentifier: CELL_ID) cell!.selectionStyle = .none cell!.slideElasticity = .hard cell!.delegate = self cell!.textLabel!.text = "Cell with Hard Elasticity" cell!.addRightButton(withText: "Hello", textColor: UIColor.white, backgroundColor: UIColor(hue: 180.0/360.0, saturation: 0.8, brightness: 0.9, alpha: 1.0)) cell!.addLeftButton(withText: "Hello", textColor: UIColor.white, backgroundColor: UIColor(hue: 0.0/360.0, saturation: 0.8, brightness: 0.9, alpha: 1.0)) } cell!.showsLeftSlideIndicator = !leftButtonDisabled cell!.showsRightSlideIndicator = !rightButtonDisabled return cell! default: let CELL_ID = "Cell" var cell = tableView.dequeueReusableCell(withIdentifier: CELL_ID) as? SESlideTableViewCell if cell == nil { cell = SESlideTableViewCell(style: .default, reuseIdentifier: CELL_ID) cell!.selectionStyle = .none } return cell! } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let cell = tableView.cellForRow(at: indexPath) as! SESlideTableViewCell? switch cell!.slideState { case .center: cell?.setSlideState(.right, animated:true) default: cell?.setSlideState(.center, animated:true) } } // #pragma mark - func slideTableViewCell(_ cell: SESlideTableViewCell!, didTriggerLeftButton buttonIndex: NSInteger) { let indexPath = tableView.indexPath(for: cell) print("left button \(buttonIndex) tapped in cell \(String(describing: (indexPath as NSIndexPath?)?.section)) - \(String(describing: (indexPath as NSIndexPath?)?.row))") } func slideTableViewCell(_ cell: SESlideTableViewCell!, didTriggerRightButton buttonIndex: NSInteger) { let indexPath = tableView.indexPath(for: cell) print("right button \(buttonIndex) tapped in cell \(String(describing: (indexPath as NSIndexPath?)?.section)) - \(String(describing: (indexPath as NSIndexPath?)?.row))") if (indexPath as NSIndexPath?)?.row == CellIndex.contentUpdate.rawValue { switch buttonIndex { case 0: value -= 1 case 1: value += 1 default: break } self.configureCell(cell, atIndex: (indexPath! as NSIndexPath).row) cell.updateContentViewSnapshot() } } func slideTableViewCell(_ cell: SESlideTableViewCell!, canSlideTo slideState: SESlideTableViewCellSlideState) -> Bool { switch (slideState) { case .left: return !leftButtonDisabled case .right: return !rightButtonDisabled default: break } return true } func slideTableViewCell(_ cell: SESlideTableViewCell!, willSlideTo slideState: SESlideTableViewCellSlideState) { if let indexPath = tableView.indexPath(for: cell) { print("cell at \((indexPath as NSIndexPath).section) - \((indexPath as NSIndexPath).row) will slide to state \(slideState.rawValue)") } } func slideTableViewCell(_ cell: SESlideTableViewCell!, didSlideTo slideState: SESlideTableViewCellSlideState) { if let indexPath = tableView.indexPath(for: cell) { print("cell at \((indexPath as NSIndexPath).section) - \((indexPath as NSIndexPath).row) did slide to state \(slideState.rawValue)") } } func slideTableViewCell(_ cell: SESlideTableViewCell!, wilShowButtonsOf side: SESlideTableViewCellSide) { if let indexPath = tableView.indexPath(for: cell) { print("cell at \((indexPath as NSIndexPath).section) - \((indexPath as NSIndexPath).row) will show buttons of side \(side.rawValue)") } } func configureCell(_ cell: SESlideTableViewCell!, atIndex index:Int) { if index == CellIndex.contentUpdate.rawValue { cell.textLabel?.text = "Cell with value \(value)" } } // #pragma mark - @objc func indexButtonDidTap(_ sender: AnyObject!) { if collation != nil { collation = nil } else { collation = UILocalizedIndexedCollation.current() } tableView.reloadData() } @objc func toggleLeftAndRightButtons(_ sender: UISegmentedControl!) { switch (sender.selectedSegmentIndex) { case 0: leftButtonDisabled = !leftButtonDisabled self.tableView.reloadData() let message = leftButtonDisabled ? "Disabled" : "Enabled" let alertController = UIAlertController(title: "Left Button", message: message, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: {(action:UIAlertAction!) -> Void in alertController.dismiss(animated: true, completion: nil)})) present(alertController, animated: true, completion: nil) case 1: rightButtonDisabled = !rightButtonDisabled self.tableView.reloadData() let message = rightButtonDisabled ? "Disabled" : "Enabled" let alertController = UIAlertController(title: "Right Button", message: message, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: {(action:UIAlertAction!) -> Void in alertController.dismiss(animated: true, completion: nil)})) present(alertController, animated: true, completion: nil) default: break } } }
mit
080522e31cc8595aaa7f1068f5d6dac4
43.41779
209
0.729535
3.812818
false
false
false
false
KosyanMedia/Aviasales-iOS-SDK
AviasalesSDKTemplate/Source/HotelsSource/Map/Markers/RatingView.swift
1
873
@objcMembers class RatingView: UIView { let ratingLabel = UILabel() override func layoutSubviews() { super.layoutSubviews() let maskLayer = CAShapeLayer() let cornerSize = CGSize(width: 2.0, height: 2.0) maskLayer.path = UIBezierPath(roundedRect: bounds, byRoundingCorners: [.topLeft, .bottomLeft], cornerRadii: cornerSize).cgPath layer.mask = maskLayer } func setupWithHotel(_ hotel: HDKHotel) { clipsToBounds = true layer.cornerRadius = 1.0 backgroundColor = JRColorScheme.ratingColor(hotel.rating) ratingLabel.textColor = UIColor.white ratingLabel.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium) ratingLabel.text = StringUtils.shortRatingString(hotel.rating) addSubview(ratingLabel) ratingLabel.autoCenterInSuperview() } }
mit
95dc10d45f8bc1f0e4d7ed1f243eeef0
33.92
134
0.682703
4.877095
false
false
false
false
laurennicoleroth/Tindergram
Tindergram/ViewController.swift
1
2149
import UIKit let pageController = ViewController(transitionStyle: .Scroll, navigationOrientation: .Horizontal, options: nil) class ViewController: UIPageViewController { let cardsVC: UIViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("CardsNavController") as! UIViewController let profileVC: UIViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("ProfileNavController") as! UIViewController let matchesVC: UIViewController! = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("MatchesNavController") as! UIViewController override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.whiteColor() dataSource = self setViewControllers([cardsVC], direction: .Forward, animated: true, completion: nil) } func goToNextVC() { let nextVC = pageViewController(self, viewControllerAfterViewController: viewControllers[0] as! UIViewController)! setViewControllers([nextVC], direction: .Forward, animated: true, completion: nil) } func goToPreviousVC() { let previousVC = pageViewController(self, viewControllerBeforeViewController: viewControllers[0] as! UIViewController)! setViewControllers([previousVC], direction: .Reverse, animated: true, completion: nil) } } // MARK - UIPageViewControllerDataSource extension ViewController: UIPageViewControllerDataSource { func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? { switch viewController { case cardsVC: return profileVC case profileVC: return nil case matchesVC: return cardsVC default: return nil } } func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? { switch viewController { case cardsVC: return matchesVC case profileVC: return cardsVC default: return nil } } }
mit
17a5d0d266fdada02955ff1142aece25
33.66129
161
0.757096
5.792453
false
false
false
false
Mazy-ma/DemoBySwift
ComplexLoadingAnimation/ComplexLoadingAnimation/TriangleLayer.swift
1
3733
// // TriangleLayer.swift // ComplexLoadingAnimation // // Created by Mazy on 2017/6/30. // Copyright © 2017年 Mazy. All rights reserved. // import UIKit class TriangleLayer: CAShapeLayer { let innerPadding: CGFloat = 30.0 override init() { super.init() fillColor = Colors.red.cgColor strokeColor = Colors.red.cgColor lineWidth = 7.0 lineCap = kCALineCapRound lineJoin = kCALineJoinRound path = trianglePathSmall.cgPath } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var trianglePathSmall: UIBezierPath { let trianglePath = UIBezierPath() trianglePath.move(to: CGPoint(x: 5.0+innerPadding, y: 95)) trianglePath.addLine(to: CGPoint(x: 50.0, y: 12.5+innerPadding)) trianglePath.addLine(to: CGPoint(x: 95-innerPadding, y: 95)) trianglePath.close() return trianglePath } var trianglePathLeftExtension: UIBezierPath { let trianglePath = UIBezierPath() trianglePath.move(to: CGPoint(x: 5, y: 95)) trianglePath.addLine(to: CGPoint(x: 50, y: 12.5+innerPadding)) trianglePath.addLine(to: CGPoint(x: 95 - innerPadding, y: 95)) trianglePath.close() return trianglePath } var trianglePathRightExtension: UIBezierPath { let trianglePath = UIBezierPath() trianglePath.move(to: CGPoint(x: 5, y: 95)) trianglePath.addLine(to: CGPoint(x: 50, y: 12.5+innerPadding)) trianglePath.addLine(to: CGPoint(x: 95, y: 95)) trianglePath.close() return trianglePath } var trianglePathTopExtension: UIBezierPath { let trianglePath = UIBezierPath() trianglePath.move(to: CGPoint(x: 5, y: 95)) trianglePath.addLine(to: CGPoint(x: 50, y: 12.5)) trianglePath.addLine(to: CGPoint(x: 95, y: 95)) trianglePath.close() return trianglePath } func animate() { // 1 let triangleAnimationLeft: CABasicAnimation = CABasicAnimation(keyPath: "path") triangleAnimationLeft.fromValue = trianglePathSmall.cgPath triangleAnimationLeft.toValue = trianglePathLeftExtension.cgPath triangleAnimationLeft.beginTime = 0.0 triangleAnimationLeft.duration = 0.3 // 2 let triangleAnimationRight: CABasicAnimation = CABasicAnimation(keyPath: "path") triangleAnimationRight.fromValue = trianglePathLeftExtension.cgPath triangleAnimationRight.toValue = trianglePathRightExtension.cgPath triangleAnimationRight.beginTime = triangleAnimationLeft.beginTime + triangleAnimationLeft.duration triangleAnimationRight.duration = 0.25 // 3 let triangleAnimationTop: CABasicAnimation = CABasicAnimation(keyPath: "path") triangleAnimationTop.fromValue = trianglePathRightExtension.cgPath triangleAnimationTop.toValue = trianglePathTopExtension.cgPath triangleAnimationTop.beginTime = triangleAnimationRight.beginTime + triangleAnimationRight.duration triangleAnimationTop.duration = 0.20 // 4 let triangleAnimationGroup: CAAnimationGroup = CAAnimationGroup() triangleAnimationGroup.animations = [triangleAnimationLeft, triangleAnimationRight, triangleAnimationTop] triangleAnimationGroup.duration = triangleAnimationTop.beginTime + triangleAnimationTop.duration triangleAnimationGroup.fillMode = kCAFillModeForwards triangleAnimationGroup.isRemovedOnCompletion = false add(triangleAnimationGroup, forKey: nil) } }
apache-2.0
d84e5927c3cda4054be8d65db9e50eb9
37.453608
107
0.672654
5.328571
false
false
false
false
TG908/iOS
TUM Campus App/TumOnlineWebServices.swift
1
906
// // TumOnlineWebServices.swift // TUM Campus App // // Created by Mathias Quintero on 12/6/15. // Copyright © 2015 LS1 TUM. All rights reserved. // import Foundation enum TUMOnlineWebServices: String { case BaseUrl = "https://campus.tum.de/tumonline/wbservicesbasic." case PersonSearch = "personenSuche" case TokenRequest = "requestToken" case TokenConfirmation = "isTokenConfirmed" case TokenParameter = "pToken" case IDParameter = "pIdentNr" case LectureIDParameter = "pLVNr" case TuitionStatus = "studienbeitragsstatus" case Calendar = "kalender" case PersonDetails = "personenDetails" case Identity = "id" case PersonalLectures = "veranstaltungenEigene" case PersonalGrades = "noten" case LectureSearch = "veranstaltungenSuche" case LectureDetails = "veranstaltungenDetails" case Home = "https://campus.tum.de/tumonline/" }
gpl-3.0
f290e1f2e7efe2af0bdaad303935647e
30.206897
69
0.714917
3.494208
false
false
false
false
Zero-Xiong/Recipe
Recipe/RecipeModel.swift
1
1039
// // RecipeModel.swift // Recipe // // Created by xiong on 22/4/16. // Copyright © 2016 Zero Inc. All rights reserved. // import UIKit class RecipeModel: NSObject, NSCoding { var Title: String? var Content: String? init(_title: String?, _content: String?) { self.Title = _title self.Content = _content } override init() { super.init() } required init?(coder aDecoder: NSCoder) { if let titleDecoded = aDecoder.decodeObjectForKey("title") { self.Title = titleDecoded as? String } if let contentDecoded = aDecoder.decodeObjectForKey("content") { self.Content = contentDecoded as? String } } func encodeWithCoder(aCoder: NSCoder) { if let titleEncoded = self.Title { aCoder.encodeObject(titleEncoded, forKey: "title") } if let contentEncoded = self.Content { aCoder.encodeObject(contentEncoded, forKey: "content") } } }
gpl-3.0
97ef2acb7f6b7e5e2e2d3f83cee18c5e
23.139535
72
0.579961
4.417021
false
false
false
false
bluesnap/bluesnap-ios
BluesnapSDK/BluesnapSDK/BSCountryViewController.swift
1
3832
// // BSCountryViewController.swift // BluesnapSDK // // Created by Shevie Chen on 23/04/2017. // Copyright © 2017 Bluesnap. All rights reserved. // import Foundation class BSCountryViewController : BSBaseListController { // MARK: private properties fileprivate var countries : [(name: String, code: String)] = [] fileprivate var filteredItems : [(name: String, code: String)] = [] // the callback function that gets called when a country is selected; // this is just a default fileprivate var updateFunc : (String, String)->Void = { countryCode, countryName in NSLog("Country \(countryCode):\(countryName) was selected") } // MARK: init func initCountries(selectedCode: String!, updateFunc: @escaping (String, String) -> Void) { let countryManager = BSCountryManager.getInstance() self.updateFunc = updateFunc if let countryName = countryManager.getCountryName(countryCode: selectedCode) { self.selectedItem = (name: countryName, code: selectedCode) } // Get country data let countryCodes = countryManager.getCountryCodes() for countryCode in countryCodes { if let countryName = countryManager.getCountryName(countryCode: countryCode) { countries.append((name: countryName, code: countryCode)) } } } // MARK: Override functions of BSBaseListController override func setTitle() { self.title = BSLocalizedStrings.getString(BSLocalizedString.Title_Country_Screen) } override func doFilter(_ searchText : String) { if searchText == "" { self.filteredItems = self.countries } else { filteredItems = countries.filter{(x) -> Bool in (x.name.uppercased().range(of:searchText.uppercased())) != nil } } generateGroups() self.tableView.reloadData() } override func selectItem(newItem: (name: String, code: String)) { updateFunc(newItem.code, newItem.name) } override func createTableViewCell(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let reusableCell = tableView.dequeueReusableCell(withIdentifier: "CountryTableViewCell", for: indexPath) let cell = reusableCell as! BSCountryTableViewCell let firstLetter = groupSections[indexPath.section] if let country = groups[firstLetter]?[indexPath.row] { cell.itemNameUILabel.text = country.name cell.checkMarkImageView.image = nil if (country.code == selectedItem.code) { if let image = BSViewsManager.getImage(imageName: "blue_check_mark") { cell.checkMarkImageView.image = image } } // load the flag image cell.flagImageView.image = nil if let image = BSViewsManager.getImage(imageName: country.code.uppercased()) { cell.flagImageView.image = image } } return cell } // MARK: private functions private func generateGroups() { groups = [String: [(name: String, code: String)]]() for country: (name: String, code: String) in filteredItems { let name = country.name let firstLetter = "\(name[name.startIndex])".uppercased() if var countriesByFirstLetter = groups[firstLetter] { countriesByFirstLetter.append(country) groups[firstLetter] = countriesByFirstLetter } else { groups[firstLetter] = [country] } } groupSections = [String](groups.keys) groupSections = groupSections.sorted() } }
mit
73416051d604d20071b035cf9187d857
33.827273
124
0.6142
5.047431
false
false
false
false
LeoMobileDeveloper/MDTable
MDTableExample/ColumnTitle.swift
1
710
// // NMHomeColumnCell.swift // MDTableExample // // Created by Leo on 2017/7/6. // Copyright © 2017年 Leo Huang. All rights reserved. // import UIKit import MDTable class NMColumnTitleRow: ReactiveRow{ let columnTitle:String init(title:String) { columnTitle = title super.init() self.rowHeight = 45.0 self.initalType = .xib(xibName: "NMColumnTitleCell") } } class NMColumnTitleCell: MDTableViewCell{ @IBOutlet weak var columnTitleLabel: UILabel! override func render(with row: RowConvertable) { guard let _row = row as? NMColumnTitleRow else { return } self.columnTitleLabel.text = _row.columnTitle } }
mit
745f48662734310389eceb3c80e73ede
21.806452
60
0.652051
3.760638
false
false
false
false
tiger8888/LayerPlayer
LayerPlayer/CALayerViewController.swift
3
1452
// // CALayerViewController.swift // LayerPlayer // // Created by Scott Gardner on 11/10/14. // Copyright (c) 2014 Scott Gardner. All rights reserved. // import UIKit class CALayerViewController: UIViewController { @IBOutlet weak var viewForLayer: UIView! let layer = CALayer() let star = UIImage(named: "star")?.CGImage // MARK: - Quick reference func setUpLayer() { layer.frame = viewForLayer.bounds layer.contents = star layer.contentsGravity = kCAGravityCenter layer.geometryFlipped = false layer.cornerRadius = 100.0 layer.borderWidth = 12.0 layer.borderColor = UIColor.whiteColor().CGColor layer.backgroundColor = UIColor(red: 11/255.0, green: 86/255.0, blue: 14/255.0, alpha: 1.0).CGColor layer.shadowOpacity = 0.75 layer.shadowOffset = CGSize(width: 0, height: 3) layer.shadowRadius = 3.0 layer.magnificationFilter = kCAFilterLinear } // MARK: - View life cycle override func viewDidLoad() { super.viewDidLoad() setUpLayer() viewForLayer.layer.addSublayer(layer) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let identifier = segue.identifier { switch identifier { case "DisplayLayerControls": let controller = segue.destinationViewController as CALayerControlsViewController controller.layerViewController = self default: break } } } }
mit
5c19ee7d8ba15ac52c51a9145aecc5b6
25.4
103
0.68595
4.283186
false
false
false
false
GoogleCloudPlatform/ios-docs-samples
text-to-speech/Swift/TextToSpeech/TextToSpeech/TextToSpeechService.swift
1
2638
// // Copyright 2019 Google Inc. 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 import googleapis import AVFoundation class TextToSpeechRecognitionService { private var client : TextToSpeech! private var writer : GRXBufferedPipe! private var call : GRPCProtoCall! static let sharedInstance = TextToSpeechRecognitionService() func textToSpeech(text:String, completionHandler: @escaping (_ audioData: Data) -> Void) { client = TextToSpeech(host: ApplicationConstants.Host) writer = GRXBufferedPipe() let synthesisInput = SynthesisInput() synthesisInput.text = text let voiceSelectionParams = VoiceSelectionParams() voiceSelectionParams.languageCode = ApplicationConstants.languageCode voiceSelectionParams.ssmlGender = SsmlVoiceGender.neutral let audioConfig = AudioConfig() audioConfig.audioEncoding = AudioEncoding.mp3 let speechRequest = SynthesizeSpeechRequest() speechRequest.audioConfig = audioConfig speechRequest.input = synthesisInput speechRequest.voice = voiceSelectionParams call = client.rpcToSynthesizeSpeech(with: speechRequest, handler: { (synthesizeSpeechResponse, error) in if error != nil { print(error?.localizedDescription ?? "No error description available") return } guard let response = synthesizeSpeechResponse else { print("No response received") return } print("Text to speech response\(response)") guard let audioData = response.audioContent else { print("no audio data received") return } completionHandler(audioData) }) call.requestHeaders.setObject(NSString(string:ApplicationConstants.API_KEY), forKey:NSString(string:"X-Goog-Api-Key")) // if the API key has a bundle ID restriction, specify the bundle ID like this call.requestHeaders.setObject(NSString(string:Bundle.main.bundleIdentifier!), forKey:NSString(string:"X-Ios-Bundle-Identifier")) print("HEADERS:\(String(describing: call.requestHeaders))") call.start() } }
apache-2.0
f8af5be617f31c0379f0b2332c44734a
33.710526
132
0.726687
4.710714
false
true
false
false
xiexinze/SwiftHTTP
Upload.swift
1
3474
// // Upload.swift // SwiftHTTP // // Created by Dalton Cherry on 6/5/14. // Copyright (c) 2014 Vluxe. All rights reserved. // import Foundation #if os(iOS) import MobileCoreServices #endif /** Upload errors */ enum HTTPUploadError: ErrorType { case NoFileUrl } /** This is how to upload files in SwiftHTTP. The upload object represents a file to upload by either a data blob or a url (which it reads off disk). */ public class Upload: NSObject, NSCoding { var fileUrl: NSURL? { didSet { getMimeType() } } var mimeType: String? var data: NSData? var fileName: String? /** Tries to determine the mime type from the fileUrl extension. */ func getMimeType() { mimeType = "application/octet-stream" guard let url = fileUrl else { return } if let ext = url.pathExtension { guard let UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, ext, nil) else { return } guard let str = UTTypeCopyPreferredTagWithClass(UTI.takeRetainedValue(), kUTTagClassMIMEType) else { return } mimeType = str.takeRetainedValue() as String } } /** Reads the data from disk or from memory. Throws an error if no data or file is found. */ public func getData() throws -> NSData { if let d = data { return d } guard let url = fileUrl else { throw HTTPUploadError.NoFileUrl } fileName = url.lastPathComponent let d = try NSData(contentsOfURL: url, options: NSDataReadingOptions.DataReadingMappedIfSafe) data = d return d } /** Standard NSCoder support */ public func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(self.fileUrl, forKey: "fileUrl") aCoder.encodeObject(self.mimeType, forKey: "mimeType") aCoder.encodeObject(self.fileName, forKey: "fileName") aCoder.encodeObject(self.data, forKey: "data") } /** Required for NSObject support (because of NSCoder, it would be a struct otherwise!) */ public override init() { super.init() } required public convenience init(coder aDecoder: NSCoder) { self.init() fileUrl = aDecoder.decodeObjectForKey("fileUrl") as? NSURL mimeType = aDecoder.decodeObjectForKey("mimeType") as? String fileName = aDecoder.decodeObjectForKey("fileName") as? String data = aDecoder.decodeObjectForKey("data") as? NSData } /** Initializes a new Upload object with a fileUrl. The fileName and mimeType will be infered. -parameter fileUrl: The fileUrl is a standard url path to a file. */ public convenience init(fileUrl: NSURL) { self.init() self.fileUrl = fileUrl } /** Initializes a new Upload object with a data blob. -parameter data: The data is a NSData representation of a file's data. -parameter fileName: The fileName is just that. The file's name. -parameter mimeType: The mimeType is just that. The mime type you would like the file to uploaded as. */ ///upload a file from a a data blob. Must add a filename and mimeType as that can't be infered from the data public convenience init(data: NSData, fileName: String, mimeType: String) { self.init() self.data = data self.fileName = fileName self.mimeType = mimeType } }
apache-2.0
bcfb7b879f9766690f0ff2b9cca43cd1
30.017857
145
0.643926
4.688259
false
false
false
false
kaunteya/KSView
KSView.swift
1
1159
// // KSView.swift // KSView // // Created by Kauntey Suryawanshi on 17/08/15. // Copyright (c) 2015 Kauntey Suryawanshi. All rights reserved. // import Foundation import Cocoa @IBDesignable public class KSView: NSView { @IBInspectable public var backgroundColor: NSColor = NSColor.clear { didSet { self.layer!.backgroundColor = backgroundColor.cgColor } } @IBInspectable public var cornerRadius: CGFloat = 2 { didSet { self.layer?.cornerRadius = cornerRadius } } @IBInspectable public var borderWidth: CGFloat = 1 { didSet { self.layer?.borderWidth = borderWidth } } @IBInspectable public var borderColor: NSColor = NSColor.black { didSet { self.layer?.borderColor = borderColor.cgColor } } required public init?(coder: NSCoder) { super.init(coder: coder) self.wantsLayer = true self.layer?.backgroundColor = NSColor.purple.cgColor // TODO: All subview will be drawn in parent views layer // self.canDrawSubviewsIntoLayer = true } }
mit
8e63f5061fdb30201213115045220248
24.195652
72
0.614323
4.509728
false
false
false
false
ragnar/VindsidenApp
VindsidenApp/RHCSettingsViewController.swift
1
4024
// // RHCSettingsViewController.swift // VindsidenApp // // Created by Ragnar Henriksen on 15/10/14. // Copyright (c) 2014 RHC. All rights reserved. // import UIKit import VindsidenKit @objc(RHCSettingsDelegate) protocol RHCSettingsDelegate { func rhcSettingsDidFinish( _ controller : RHCSettingsViewController, shouldDismiss: Bool) -> Void } @objc class RHCSettingsViewController: UITableViewController { @objc var delegate: RHCSettingsDelegate? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.tableView.reloadData() } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 2 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "SettingsCell", for: indexPath) as UITableViewCell if indexPath.row == 0 { cell.textLabel?.text = NSLocalizedString("Stations", comment: "") cell.detailTextLabel?.text = "\(CDStation.numberOfVisibleStationsInManagedObjectContext(DataManager.shared.viewContext()))" } else { let unit = SpeedConvertion(rawValue: AppConfig.sharedConfiguration.applicationUserDefaults.integer(forKey: "selectedUnit")) cell.textLabel?.text = NSLocalizedString("Units", comment: "") cell.detailTextLabel?.text = NSNumber.shortUnitNameString(unit!) } return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.row == 0 { performSegue(withIdentifier: "ShowStationPicker", sender: self) } else { performSegue(withIdentifier: "ShowUnitSelector", sender: self) } } override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { let tv = UITextView(frame: CGRect.zero) let appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as! String let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String let appBuild = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as! String let version = NSString(format: NSLocalizedString("%@ version %@.%@", comment: "Version string in settings view") as NSString, appName, appVersion, appBuild) tv.text = NSLocalizedString("LABEL_PERMIT", comment: "Værdata hentet med tillatelse fra\nhttp://vindsiden.no\n\n") + (version as String) tv.isEditable = false tv.textAlignment = .center tv.backgroundColor = UIColor.clear tv.dataDetectorTypes = .link tv.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body) tv.textColor = .secondaryLabel tv.sizeToFit() return tv } override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { let tv = self.tableView(tableView, viewForFooterInSection: section) let height = tv?.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height return height! } //MARK: - Actions @IBAction func done( _ sender: AnyObject ) { if let delegate = self.delegate { delegate.rhcSettingsDidFinish(self, shouldDismiss: true) } else { self.dismiss( animated: true, completion: nil) } } } extension RHCSettingsViewController: UIAdaptivePresentationControllerDelegate { func presentationControllerDidDismiss(_ presentationController: UIPresentationController) { guard let delegate = self.delegate else { return } delegate.rhcSettingsDidFinish(self, shouldDismiss: false) } }
bsd-2-clause
87ae177d24a49838eb78df8969be1d0a
34.60177
164
0.688541
5.092405
false
false
false
false
yrchen/edx-app-ios
Libraries/TZStackView/TZStackView.swift
1
26124
// // TZStackView.swift // TZStackView // // Created by Tom van Zummeren on 10/06/15. // Copyright © 2015 Tom van Zummeren. All rights reserved. // import UIKit public enum TZStackViewAlignment: Int { case Fill case Center case Leading case Top case Trailing case Bottom case FirstBaseline } public enum TZStackViewDistribution: Int { case Fill case FillEqually case FillProportionally case EqualSpacing case EqualCentering } private struct TZAnimationDidStopQueueEntry: Equatable { let view: UIView let hidden: Bool } private func ==(lhs: TZAnimationDidStopQueueEntry, rhs: TZAnimationDidStopQueueEntry) -> Bool { return lhs.view === rhs.view } public class TZStackView: UIView { public var distribution: TZStackViewDistribution = .Fill { didSet { setNeedsUpdateConstraints() } } public var axis: UILayoutConstraintAxis = .Horizontal { didSet { setNeedsUpdateConstraints() } } public var alignment: TZStackViewAlignment = .Fill public var spacing: CGFloat = 0 public var layoutMarginsRelativeArrangement = false public private(set) var arrangedSubviews: [UIView] = [] { didSet { setNeedsUpdateConstraints() registerHiddenListeners(oldValue) } } private var kvoContext = UInt8() private var stackViewConstraints = [NSLayoutConstraint]() private var subviewConstraints = [NSLayoutConstraint]() private var spacerViews = [UIView]() private var animationDidStopQueueEntries = [TZAnimationDidStopQueueEntry]() private var registeredKvoSubviews = [UIView]() private var animatingToHiddenViews = [UIView]() public init(arrangedSubviews: [UIView] = []) { super.init(frame: CGRectZero) for arrangedSubview in arrangedSubviews { arrangedSubview.translatesAutoresizingMaskIntoConstraints = false addSubview(arrangedSubview) } // Closure to invoke didSet() { self.arrangedSubviews = arrangedSubviews }() } deinit { // This removes `hidden` value KVO observers using didSet() { self.arrangedSubviews = [] }() } private func registerHiddenListeners(previousArrangedSubviews: [UIView]) { for subview in previousArrangedSubviews { self.removeHiddenListener(subview) } for subview in arrangedSubviews { self.addHiddenListener(subview) } } private func addHiddenListener(view: UIView) { view.addObserver(self, forKeyPath: "hidden", options: [.Old, .New], context: &kvoContext) registeredKvoSubviews.append(view) } private func removeHiddenListener(view: UIView) { if let index = registeredKvoSubviews.indexOf(view) { view.removeObserver(self, forKeyPath: "hidden", context: &kvoContext) registeredKvoSubviews.removeAtIndex(index) } } public override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if let view = object as? UIView, change = change where keyPath == "hidden" { let hidden = view.hidden let previousValue = change["old"] as! Bool if hidden == previousValue { return } if hidden { animatingToHiddenViews.append(view) } // Perform the animation setNeedsUpdateConstraints() setNeedsLayout() layoutIfNeeded() removeHiddenListener(view) view.hidden = false if let _ = view.layer.animationKeys() { UIView.setAnimationDelegate(self) animationDidStopQueueEntries.insert(TZAnimationDidStopQueueEntry(view: view, hidden: hidden), atIndex: 0) UIView.setAnimationDidStopSelector("hiddenAnimationStopped") } else { didFinishSettingHiddenValue(view, hidden: hidden) } } } private func didFinishSettingHiddenValue(arrangedSubview: UIView, hidden: Bool) { arrangedSubview.hidden = hidden if let index = animatingToHiddenViews.indexOf(arrangedSubview) { animatingToHiddenViews.removeAtIndex(index) } addHiddenListener(arrangedSubview) } func hiddenAnimationStopped() { var queueEntriesToRemove = [TZAnimationDidStopQueueEntry]() for entry in animationDidStopQueueEntries { let view = entry.view if view.layer.animationKeys() == nil { didFinishSettingHiddenValue(view, hidden: entry.hidden) queueEntriesToRemove.append(entry) } } for entry in queueEntriesToRemove { if let index = animationDidStopQueueEntries.indexOf(entry) { animationDidStopQueueEntries.removeAtIndex(index) } } } public func addArrangedSubview(view: UIView) { view.translatesAutoresizingMaskIntoConstraints = false addSubview(view) arrangedSubviews.append(view) } public func removeArrangedSubview(view: UIView) { if let index = arrangedSubviews.indexOf(view) { arrangedSubviews.removeAtIndex(index) } } public func insertArrangedSubview(view: UIView, atIndex stackIndex: Int) { view.translatesAutoresizingMaskIntoConstraints = false addSubview(view) arrangedSubviews.insert(view, atIndex: stackIndex) } override public func willRemoveSubview(subview: UIView) { removeArrangedSubview(subview) } override public func updateConstraints() { removeConstraints(stackViewConstraints) stackViewConstraints.removeAll() for arrangedSubview in arrangedSubviews { arrangedSubview.removeConstraints(subviewConstraints) } subviewConstraints.removeAll() for arrangedSubview in arrangedSubviews { if alignment != .Fill { let guideConstraint: NSLayoutConstraint switch axis { case .Horizontal: guideConstraint = constraint(item: arrangedSubview, attribute: .Height, toItem: nil, attribute: .NotAnAttribute, constant: 0, priority: 25) case .Vertical: guideConstraint = constraint(item: arrangedSubview, attribute: .Width, toItem: nil, attribute: .NotAnAttribute, constant: 0, priority: 25) } subviewConstraints.append(guideConstraint) arrangedSubview.addConstraint(guideConstraint) } if isHidden(arrangedSubview) { let hiddenConstraint: NSLayoutConstraint switch axis { case .Horizontal: hiddenConstraint = constraint(item: arrangedSubview, attribute: .Width, toItem: nil, attribute: .NotAnAttribute, constant: 0) case .Vertical: hiddenConstraint = constraint(item: arrangedSubview, attribute: .Height, toItem: nil, attribute: .NotAnAttribute, constant: 0) } subviewConstraints.append(hiddenConstraint) arrangedSubview.addConstraint(hiddenConstraint) } } for spacerView in spacerViews { spacerView.removeFromSuperview() } spacerViews.removeAll() if arrangedSubviews.count > 0 { let visibleArrangedSubviews = arrangedSubviews.filter({!self.isHidden($0)}) switch distribution { case .FillEqually, .Fill, .FillProportionally: if alignment != .Fill || layoutMarginsRelativeArrangement { addSpacerView() } stackViewConstraints += createMatchEdgesContraints(arrangedSubviews) stackViewConstraints += createFirstAndLastViewMatchEdgesContraints() if alignment == .FirstBaseline && axis == .Horizontal { stackViewConstraints.append(constraint(item: self, attribute: .Height, toItem: nil, attribute: .NotAnAttribute, priority: 49)) } if distribution == .FillEqually { stackViewConstraints += createFillEquallyConstraints(arrangedSubviews) } if distribution == .FillProportionally { stackViewConstraints += createFillProportionallyConstraints(arrangedSubviews) } stackViewConstraints += createFillConstraints(arrangedSubviews, constant: spacing) case .EqualSpacing: var views = [UIView]() var index = 0 for arrangedSubview in arrangedSubviews { if isHidden(arrangedSubview) { continue } if index > 0 { views.append(addSpacerView()) } views.append(arrangedSubview) index++ } if spacerViews.count == 0 { addSpacerView() } stackViewConstraints += createMatchEdgesContraints(arrangedSubviews) stackViewConstraints += createFirstAndLastViewMatchEdgesContraints() switch axis { case .Horizontal: stackViewConstraints.append(constraint(item: self, attribute: .Width, toItem: nil, attribute: .NotAnAttribute, priority: 49)) if alignment == .FirstBaseline { stackViewConstraints.append(constraint(item: self, attribute: .Height, toItem: nil, attribute: .NotAnAttribute, priority: 49)) } case .Vertical: stackViewConstraints.append(constraint(item: self, attribute: .Height, toItem: nil, attribute: .NotAnAttribute, priority: 49)) } stackViewConstraints += createFillConstraints(views, constant: 0) stackViewConstraints += createFillEquallyConstraints(spacerViews) stackViewConstraints += createFillConstraints(arrangedSubviews, relatedBy: .GreaterThanOrEqual, constant: spacing) case .EqualCentering: for (index, _) in visibleArrangedSubviews.enumerate() { if index > 0 { addSpacerView() } } if spacerViews.count == 0 { addSpacerView() } stackViewConstraints += createMatchEdgesContraints(arrangedSubviews) stackViewConstraints += createFirstAndLastViewMatchEdgesContraints() switch axis { case .Horizontal: stackViewConstraints.append(constraint(item: self, attribute: .Width, toItem: nil, attribute: .NotAnAttribute, priority: 49)) if alignment == .FirstBaseline { stackViewConstraints.append(constraint(item: self, attribute: .Height, toItem: nil, attribute: .NotAnAttribute, priority: 49)) } case .Vertical: stackViewConstraints.append(constraint(item: self, attribute: .Height, toItem: nil, attribute: .NotAnAttribute, priority: 49)) } var previousArrangedSubview: UIView? for (index, arrangedSubview) in visibleArrangedSubviews.enumerate() { if let previousArrangedSubview = previousArrangedSubview { let spacerView = spacerViews[index - 1] switch axis { case .Horizontal: stackViewConstraints.append(constraint(item: previousArrangedSubview, attribute: .CenterX, toItem: spacerView, attribute: .Leading)) stackViewConstraints.append(constraint(item: arrangedSubview, attribute: .CenterX, toItem: spacerView, attribute: .Trailing)) case .Vertical: stackViewConstraints.append(constraint(item: previousArrangedSubview, attribute: .CenterY, toItem: spacerView, attribute: .Top)) stackViewConstraints.append(constraint(item: arrangedSubview, attribute: .CenterY, toItem: spacerView, attribute: .Bottom)) } } previousArrangedSubview = arrangedSubview } stackViewConstraints += createFillEquallyConstraints(spacerViews, priority: 150) stackViewConstraints += createFillConstraints(arrangedSubviews, relatedBy: .GreaterThanOrEqual, constant: spacing) } if spacerViews.count > 0 { stackViewConstraints += createSurroundingSpacerViewConstraints(spacerViews[0], views: visibleArrangedSubviews) } if layoutMarginsRelativeArrangement { if spacerViews.count > 0 { stackViewConstraints.append(constraint(item: self, attribute: .BottomMargin, toItem: spacerViews[0])) stackViewConstraints.append(constraint(item: self, attribute: .LeftMargin, toItem: spacerViews[0])) stackViewConstraints.append(constraint(item: self, attribute: .RightMargin, toItem: spacerViews[0])) stackViewConstraints.append(constraint(item: self, attribute: .TopMargin, toItem: spacerViews[0])) } } addConstraints(stackViewConstraints) } super.updateConstraints() } required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! } private func addSpacerView() -> UIView { let spacerView = UIView() spacerView.translatesAutoresizingMaskIntoConstraints = false spacerViews.append(spacerView) insertSubview(spacerView, atIndex: 0) return spacerView } private func createSurroundingSpacerViewConstraints(spacerView: UIView, views: [UIView]) -> [NSLayoutConstraint] { if alignment == .Fill { return [] } var topPriority: Float = 1000 var topRelation: NSLayoutRelation = .LessThanOrEqual var bottomPriority: Float = 1000 var bottomRelation: NSLayoutRelation = .GreaterThanOrEqual if alignment == .Top || alignment == .Leading { topPriority = 999.5 topRelation = .Equal } if alignment == .Bottom || alignment == .Trailing { bottomPriority = 999.5 bottomRelation = .Equal } var constraints = [NSLayoutConstraint]() for view in views { switch axis { case .Horizontal: constraints.append(constraint(item: spacerView, attribute: .Top, relatedBy: topRelation, toItem: view, priority: topPriority)) constraints.append(constraint(item: spacerView, attribute: .Bottom, relatedBy: bottomRelation, toItem: view, priority: bottomPriority)) case .Vertical: constraints.append(constraint(item: spacerView, attribute: .Leading, relatedBy: topRelation, toItem: view, priority: topPriority)) constraints.append(constraint(item: spacerView, attribute: .Trailing, relatedBy: bottomRelation, toItem: view, priority: bottomPriority)) } } switch axis { case .Horizontal: constraints.append(constraint(item: spacerView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, constant: 0, priority: 51)) case .Vertical: constraints.append(constraint(item: spacerView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, constant: 0, priority: 51)) } return constraints } private func createFillProportionallyConstraints(views: [UIView]) -> [NSLayoutConstraint] { var constraints = [NSLayoutConstraint]() var totalSize: CGFloat = 0 var totalCount = 0 for arrangedSubview in views { if isHidden(arrangedSubview) { continue } switch axis { case .Horizontal: totalSize += arrangedSubview.intrinsicContentSize().width case .Vertical: totalSize += arrangedSubview.intrinsicContentSize().height } totalCount++ } totalSize += (CGFloat(totalCount - 1) * spacing) var priority: Float = 1000 let countDownPriority = (views.filter({!self.isHidden($0)}).count > 1) for arrangedSubview in views { if countDownPriority { priority-- } if isHidden(arrangedSubview) { continue } switch axis { case .Horizontal: let multiplier = arrangedSubview.intrinsicContentSize().width / totalSize constraints.append(constraint(item: arrangedSubview, attribute: .Width, toItem: self, multiplier: multiplier, priority: priority)) case .Vertical: let multiplier = arrangedSubview.intrinsicContentSize().height / totalSize constraints.append(constraint(item: arrangedSubview, attribute: .Height, toItem: self, multiplier: multiplier, priority: priority)) } } return constraints } // Matchs all Width or Height attributes of all given views private func createFillEquallyConstraints(views: [UIView], priority: Float = 1000) -> [NSLayoutConstraint] { switch axis { case .Horizontal: return equalAttributes(views: views.filter({ !self.isHidden($0) }), attribute: .Width, priority: priority) case .Vertical: return equalAttributes(views: views.filter({ !self.isHidden($0) }), attribute: .Height, priority: priority) } } // Chains together the given views using Leading/Trailing or Top/Bottom private func createFillConstraints(views: [UIView], priority: Float = 1000, relatedBy relation: NSLayoutRelation = .Equal, constant: CGFloat) -> [NSLayoutConstraint] { var constraints = [NSLayoutConstraint]() var previousView: UIView? for view in views { if let previousView = previousView { var c: CGFloat = 0 if !isHidden(previousView) && !isHidden(view) { c = constant } else if isHidden(previousView) && !isHidden(view) && views.first != previousView { c = (constant / 2) } else if isHidden(view) && !isHidden(previousView) && views.last != view { c = (constant / 2) } switch axis { case .Horizontal: constraints.append(constraint(item: view, attribute: .Leading, relatedBy: relation, toItem: previousView, attribute: .Trailing, constant: c, priority: priority)) case .Vertical: constraints.append(constraint(item: view, attribute: .Top, relatedBy: relation, toItem: previousView, attribute: .Bottom, constant: c, priority: priority)) } } previousView = view } return constraints } // Matches all Bottom/Top or Leading Trailing constraints of te given views and matches those attributes of the first/last view to the container private func createMatchEdgesContraints(views: [UIView]) -> [NSLayoutConstraint] { var constraints = [NSLayoutConstraint]() switch axis { case .Horizontal: switch alignment { case .Fill: constraints += equalAttributes(views: views, attribute: .Bottom) constraints += equalAttributes(views: views, attribute: .Top) case .Center: constraints += equalAttributes(views: views, attribute: .CenterY) case .Leading, .Top: constraints += equalAttributes(views: views, attribute: .Top) case .Trailing, .Bottom: constraints += equalAttributes(views: views, attribute: .Bottom) case .FirstBaseline: constraints += equalAttributes(views: views, attribute: .FirstBaseline) } case .Vertical: switch alignment { case .Fill: constraints += equalAttributes(views: views, attribute: .Leading) constraints += equalAttributes(views: views, attribute: .Trailing) case .Center: constraints += equalAttributes(views: views, attribute: .CenterX) case .Leading, .Top: constraints += equalAttributes(views: views, attribute: .Leading) case .Trailing, .Bottom: constraints += equalAttributes(views: views, attribute: .Trailing) case .FirstBaseline: constraints += [] } } return constraints } private func createFirstAndLastViewMatchEdgesContraints() -> [NSLayoutConstraint] { var constraints = [NSLayoutConstraint]() let visibleViews = arrangedSubviews.filter({!self.isHidden($0)}) let firstView = visibleViews.first let lastView = visibleViews.last var topView = arrangedSubviews.first! var bottomView = arrangedSubviews.first! if spacerViews.count > 0 { if alignment == .Center { topView = spacerViews[0] bottomView = spacerViews[0] } else if alignment == .Top || alignment == .Leading { bottomView = spacerViews[0] } else if alignment == .Bottom || alignment == .Trailing { topView = spacerViews[0] } else if alignment == .FirstBaseline { switch axis { case .Horizontal: bottomView = spacerViews[0] case .Vertical: topView = spacerViews[0] bottomView = spacerViews[0] } } } let firstItem = layoutMarginsRelativeArrangement ? spacerViews[0] : self switch axis { case .Horizontal: if let firstView = firstView { constraints.append(constraint(item: firstItem, attribute: .Leading, toItem: firstView)) } if let lastView = lastView { constraints.append(constraint(item: firstItem, attribute: .Trailing, toItem: lastView)) } constraints.append(constraint(item: firstItem, attribute: .Top, toItem: topView)) constraints.append(constraint(item: firstItem, attribute: .Bottom, toItem: bottomView)) if alignment == .Center { constraints.append(constraint(item: firstItem, attribute: .CenterY, toItem: arrangedSubviews.first!)) } case .Vertical: if let firstView = firstView { constraints.append(constraint(item: firstItem, attribute: .Top, toItem: firstView)) } if let lastView = lastView { constraints.append(constraint(item: firstItem, attribute: .Bottom, toItem: lastView)) } constraints.append(constraint(item: firstItem, attribute: .Leading, toItem: topView)) constraints.append(constraint(item: firstItem, attribute: .Trailing, toItem: bottomView)) if alignment == .Center { constraints.append(constraint(item: firstItem, attribute: .CenterX, toItem: arrangedSubviews.first!)) } } return constraints } private func equalAttributes(views views: [UIView], attribute: NSLayoutAttribute, priority: Float = 1000) -> [NSLayoutConstraint] { var currentPriority = priority var constraints = [NSLayoutConstraint]() if views.count > 0 { var firstView: UIView? let countDownPriority = (currentPriority < 1000) for view in views { if let firstView = firstView { constraints.append(constraint(item: firstView, attribute: attribute, toItem: view, priority: currentPriority)) } else { firstView = view } if countDownPriority { currentPriority-- } } } return constraints } // Convenience method to help make NSLayoutConstraint in a less verbose way private func constraint(item view1: AnyObject, attribute attr1: NSLayoutAttribute, relatedBy relation: NSLayoutRelation = .Equal, toItem view2: AnyObject?, attribute attr2: NSLayoutAttribute? = nil, multiplier: CGFloat = 1, constant c: CGFloat = 0, priority: Float = 1000) -> NSLayoutConstraint { let attribute2 = attr2 != nil ? attr2! : attr1 let constraint = NSLayoutConstraint(item: view1, attribute: attr1, relatedBy: relation, toItem: view2, attribute: attribute2, multiplier: multiplier, constant: c) constraint.priority = priority return constraint } private func isHidden(view: UIView) -> Bool { if view.hidden { return true } return animatingToHiddenViews.indexOf(view) != nil } }
apache-2.0
7d523005ab98ee7301c63435d503fa9f
40.663477
300
0.593462
5.662909
false
false
false
false
csnu17/My-Swift-learning
MVVMSwiftExample/MVVMSwiftExample/GameScoreboardEditorViewModelFromGame.swift
1
3982
// // GameScoreboardEditorViewModelFromGame.swift // MVVMSwiftExample // // Created by Phetrungnapha, K. on 7/5/2560 BE. // Copyright © 2560 Toptal. All rights reserved. // import Foundation class GameScoreboardEditorViewModelFromGame: GameScoreboardEditorViewModel { let game: Game struct Formatter { static let durationFormatter: DateComponentsFormatter = { let dateFormatter = DateComponentsFormatter() dateFormatter.unitsStyle = .positional return dateFormatter }() } // MARK: - GameScoreboardEditorViewModel protocol let homePlayers: [PlayerScoreboardMoveEditorViewModel] let awayPlayers: [PlayerScoreboardMoveEditorViewModel] let homeTeam: String let awayTeme: String let time: Dynamic<String> let score: Dynamic<String> let isFinished: Dynamic<Bool> let isPaused: Dynamic<Bool> func togglePause() { if isPaused.value { startTimer() } else { pauseTimer() } isPaused.value = !isPaused.value } // MARK: - Init init(withGame game: Game) { self.game = game homeTeam = game.homeTeam.name awayTeme = game.awayTeam.name time = Dynamic(GameScoreboardEditorViewModelFromGame.timeRemainingPretty(for: game)) score = Dynamic(GameScoreboardEditorViewModelFromGame.scorePretty(for: game)) isFinished = Dynamic(game.isFinished) isPaused = Dynamic(true) homePlayers = GameScoreboardEditorViewModelFromGame.playerViewModels(from: game.homeTeam.players, game: game) awayPlayers = GameScoreboardEditorViewModelFromGame.playerViewModels(from: game.awayTeam.players, game: game) subscribeToNotifications() } deinit { unsubscribeFromNotifications() } // MARK: Notifications (Private) private func subscribeToNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(gameScoreDidChangeNotification(_:)), name: NSNotification.Name(rawValue: GameNotifications.GameScoreDidChangeNotification), object: game) } private func unsubscribeFromNotifications() { NotificationCenter.default.removeObserver(self) } @objc private func gameScoreDidChangeNotification(_ notification: NSNotification) { self.score.value = GameScoreboardEditorViewModelFromGame.scorePretty(for: game) if game.isFinished { self.isFinished.value = true } } // MARK: - Private private var gameTimer: Timer? private func startTimer() { let interval: TimeInterval = 0.001 gameTimer = Timer.schedule(repeatInterval: interval) { timer in self.game.time += interval self.time.value = GameScoreboardEditorViewModelFromGame.timeRemainingPretty(for: self.game) } } private static func playerViewModels(from players: [Player], game: Game) -> [PlayerScoreboardMoveEditorViewModel] { var playerViewModels: [PlayerScoreboardMoveEditorViewModel] = [PlayerScoreboardMoveEditorViewModel]() for player in players { playerViewModels.append(PlayerScoreboardMoveEditorViewModelFromPlayer(withGame: game, player: player)) } return playerViewModels } private func pauseTimer() { gameTimer?.invalidate() gameTimer = nil } // MARK: - String Utils private static func timeFormatted(totalMillis: Int) -> String { let millis = totalMillis % 1000 / 100 // "/ 100" <- because we want only 1 digit let totalSeconds = totalMillis / 1000 let seconds = totalSeconds % 60 let minutes = totalSeconds / 60 return String(format: "%02d:%02d.%d", minutes, seconds, millis) } private static func timeRemainingPretty(for game: Game) -> String { return timeFormatted(totalMillis: Int(game.time * 1000)) } private static func scorePretty(for game: Game) -> String { return "\(game.homeTeamScore) - \(game.awayTeamScore)" } }
mit
fc8e20ede92fe44f0c260a9804810b42
29.159091
129
0.694047
4.596998
false
false
false
false
ZackTvZ/CasToDictionary
CasToDictionary/CasToDictionaryExtension.swift
1
2305
// // CasToDictionaryExtension.swift // CasToDictionary // // Created by ZackTvZ on 11/01/2017. // Copyright © 2017 ZackTvZ. All rights reserved. // import UIKit public extension NSObject{ func castToDictionary() -> NSMutableDictionary{ let objectDIC: NSMutableDictionary = NSMutableDictionary() let mirror = Mirror(reflecting: self) print(mirror) for child in mirror.children { guard let key = child.label else { continue } let value = child.value as Any switch value { case is Data: break case is UIImage: break case is Collection: let objects = child.value as! Array<Any> objectDIC.setValue(objects.castToDictionary(), forKey: key) break; case is String: objectDIC.setValue(child.value, forKey: key) break case is Int: objectDIC.setValue(child.value, forKey: key) break case is NSDictionary: objectDIC.setValue(child.value, forKey: key) break case is NSObject: let object = child.value as! NSObject objectDIC.setValue(object.castToDictionary(), forKey: key) break default: break } } return objectDIC } } public extension Collection{ func castToDictionary() -> [Any]{ var objectDICs: [Any] = [] for object in self{ let value = object as Any switch value { case is Collection: let objects = value as! Self objectDICs.append(objects.castToDictionary()) break; case is NSDictionary: objectDICs.append(value) break case is NSObject: let object = value as! NSObject objectDICs.append(object.castToDictionary()) break default: break } } return objectDICs } } class CasToDictionaryExtension: NSObject { }
mit
34901767be7ba1f5391ff3ed63eb0a8d
25.790698
75
0.503038
5.189189
false
false
false
false
arvedviehweger/swift
test/Sema/typo_correction.swift
4
3960
// RUN: %target-typecheck-verify-swift // RUN: not %target-swift-frontend -typecheck -disable-typo-correction %s 2>&1 | %FileCheck %s -check-prefix=DISABLED // RUN: not %target-swift-frontend -typecheck -DIMPORT_FAIL %s 2>&1 | %FileCheck %s -check-prefix=DISABLED // DISABLED-NOT: did you mean #if IMPORT_FAIL import NoSuchModule #endif // This is close enough to get typo-correction. func test_short_and_close() { let foo = 4 // expected-note {{did you mean 'foo'?}} let bab = fob + 1 // expected-error {{use of unresolved identifier}} } // This is not. func test_too_different() { let moo = 4 let bbb = mbb + 1 // expected-error {{use of unresolved identifier}} } struct Whatever {} func *(x: Whatever, y: Whatever) {} // This works even for single-character identifiers. func test_very_short() { // Note that we don't suggest operators. let x = 0 // expected-note {{did you mean 'x'?}} let longer = y // expected-error {{use of unresolved identifier 'y'}} } // It does not trigger in a variable's own initializer. func test_own_initializer() { let x = y // expected-error {{use of unresolved identifier 'y'}} } // Report candidates that are the same distance in different ways. func test_close_matches() { let match1 = 0 // expected-note {{did you mean 'match1'?}} let match22 = 0 // expected-note {{did you mean 'match22'?}} let x = match2 // expected-error {{use of unresolved identifier 'match2'}} } // Report not-as-good matches if they're still close enough to the best. func test_keep_if_not_too_much_worse() { let longmatch1 = 0 // expected-note {{did you mean 'longmatch1'?}} let longmatch22 = 0 // expected-note {{did you mean 'longmatch22'?}} let x = longmatch // expected-error {{use of unresolved identifier 'longmatch'}} } // Report not-as-good matches if they're still close enough to the best. func test_drop_if_too_different() { let longlongmatch1 = 0 // expected-note {{did you mean 'longlongmatch1'?}} let longlongmatch2222 = 0 let x = longlongmatch // expected-error {{use of unresolved identifier 'longlongmatch'}} } // Candidates are suppressed if we have too many that are the same distance. func test_too_many_same() { let match1 = 0 let match2 = 0 let match3 = 0 let match4 = 0 let match5 = 0 let match6 = 0 let x = match // expected-error {{use of unresolved identifier 'match'}} } // But if some are better than others, just drop the worse tier. func test_too_many_but_some_better() { let mtch1 = 0 // expected-note {{did you mean 'mtch1'?}} let mtch2 = 0 // expected-note {{did you mean 'mtch2'?}} let match3 = 0 let match4 = 0 let match5 = 0 let match6 = 0 let x = mtch // expected-error {{use of unresolved identifier 'mtch'}} } // rdar://problem/28387684 // Don't crash performing typo correction on bound generic types with // type variables. _ = [Any]().withUnsafeBufferPointer { (buf) -> [Any] in guard let base = buf.baseAddress else { return [] } return (base ..< base + buf.count).m // expected-error {{value of type 'CountableRange<_>' has no member 'm'}} } // Typo correction with class-bound archetypes. class SomeClass { func match1() {} // expected-note@-1 {{did you mean 'match1'?}} } func takesSomeClassArchetype<T : SomeClass>(_ t: T) { t.match0() // expected-error@-1 {{value of type 'T' has no member 'match0'}} } // Typo correction of unqualified lookup from generic context. struct Generic<T> { func match1() {} // expected-note@-1 {{did you mean 'match1'?}} class Inner { func doStuff() { match0() // expected-error@-1 {{use of unresolved identifier 'match0'}} } } } // Typo correction with AnyObject. func takesAnyObject(_ t: AnyObject) { _ = t.rawPointer // expected-error@-1 {{value of type 'AnyObject' has no member 'rawPointer'}} } func takesAnyObjectArchetype<T : AnyObject>(_ t: T) { _ = t.rawPointer // expected-error@-1 {{value of type 'T' has no member 'rawPointer'}} }
apache-2.0
b6af03e6913556f95d83e98245d5d6cd
31.727273
117
0.67702
3.455497
false
true
false
false
oliveroneill/FeedCollectionViewController
ImageFeedCollectionViewController/Classes/ImageFeedCollectionViewController.swift
1
4749
// // ImageFeedCollectionViewController.swift // ImageFeedCollectionViewController // // Created by Oliver ONeill on 17/12/2016. // // import FeedCollectionViewController import OOPhotoBrowser private extension Collection { subscript (safe index: Index) -> Element? { return indices.contains(index) ? self[index] : nil } } /** Subclass this for an infinite scrolling image feed with image browser built in. You should set `imageFeedSource` here as opposed to `feedDataSource` from `FeedCollectionViewController`. NOTE: do not set `feedDelegate` within this class, it is used to display the photo browser. You can access selection events via `browserDelegate`. */ open class ImageFeedCollectionViewController: FeedCollectionViewController { // Keep strong references here that will be given to // `FeedCollectionViewController` private var wrappedDataSource: WrappedFeedDataSource? private var wrappedDelegate: WrappedFeedDelegate? private let defaultPresenter = DefaultImageFeedPresenter() /// Required to specify a data source open weak var imageFeedSource: ImageFeedDataSource? { didSet { // When this is created we wrap the underlying data source in it. // This allows us to use delegate methods that point to the // `ImageCellData` type if let source = imageFeedSource { wrappedDataSource = WrappedFeedDataSource(imageSource: source) feedDataSource = wrappedDataSource } else { // deallocate these when set to nil wrappedDataSource = nil feedDataSource = nil } } } /// Use this to specify a custom image view for the image browser open weak var imageFeedPresenter: ImageFeedPresenter? /// Use this to receive events regarding the photo browser open weak var browserDelegate: PhotoBrowserDelegate? private var browser:IDMPhotoBrowser? open override func viewDidLoad() { super.viewDidLoad() wrappedDelegate = WrappedFeedDelegate(presenter: self) // TODO: wrapping this delegate means that users of the library // cannot use it themselves feedDelegate = wrappedDelegate // Ensure a default is set imageFeedPresenter = imageFeedPresenter ?? defaultPresenter } // Add new views to the photo browser that will hide on tap open func addToolbarView(view: UIView) { browser?.addToolbarView(view) } } extension ImageFeedCollectionViewController: PhotoBrowserPresenter { func showPhotoBrowser(index: Int) { guard let browser = IDMPhotoBrowser(dataSource: self) else { return } browser.setInitialPageIndex(UInt(index)) browser.delegate = self self.browser = browser self.present(browser, animated: true, completion: {}) } } // MARK: IDMPhotoDataSource methods extension ImageFeedCollectionViewController: IDMPhotoDataSource { public func photo(at index: UInt) -> IDMPhotoProtocol? { return cells[Int(index)] as? ImageCellData } public func numberOfPhotos() -> Int32 { return Int32(cells.count) } public func loadMoreImages(_ browser: IDMBrowserDelegate?) { var cellBrowser:IDMCellBrowser? = nil if let b = browser { cellBrowser = IDMCellBrowser(browser: b) } super.loadMoreCells(loadDelegate: cellBrowser) } } // MARK: IDMPhotoBrowserDelegate methods extension ImageFeedCollectionViewController: IDMPhotoBrowserDelegate { public func photoBrowser(_ photoBrowser: IDMPhotoBrowser, captionViewForPhotoAt index: UInt) -> IDMCaptionView? { if let cell = cells[safe: Int(index)] as? ImageCellData { if cell.caption != nil { return imageFeedPresenter?.getSingleImageView(cell: cell) } } return nil } public func photoBrowser(_ photoBrowser: IDMPhotoBrowser, imageFailed index: UInt, imageView: IDMTapDetectingImageView) { if let cell = cells[safe: Int(index)] as? ImageCellData { browserDelegate?.imageDidFail(cell: cell, imageView:imageView) } } public func photoBrowser(_ photoBrowser: IDMPhotoBrowser, setupToolbar index: UInt, toolbar: UIToolbar) { if let cell = cells[safe: Int(index)] as? ImageCellData { browserDelegate?.setupToolbar(toolbar: toolbar, cell: cell) } } public func photoBrowser(_ photoBrowser: IDMPhotoBrowser, didShowPhotoAt index: UInt) { if let cell = cells[safe: Int(index)] as? ImageCellData { browserDelegate?.didShowPhoto(cell: cell) } } }
mit
cc84ba7fcc676b8a5368285665c35fc8
35.813953
125
0.678669
4.865779
false
false
false
false
creister/SwiftCharts
SwiftCharts/Axis/ChartAxisXLayerDefault.swift
3
5121
// // ChartAxisXLayerDefault.swift // SwiftCharts // // Created by ischuetz on 25/04/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit class ChartAxisXLayerDefault: ChartAxisLayerDefault { override var width: CGFloat { return self.p2.x - self.p1.x } lazy var labelsTotalHeight: CGFloat = { return self.rowHeights.reduce(0) {sum, height in sum + height + self.settings.labelsSpacing } }() lazy var rowHeights: [CGFloat] = { return self.calculateRowHeights() }() override var height: CGFloat { return self.labelsTotalHeight + self.settings.axisStrokeWidth + self.settings.labelsToAxisSpacingX + self.settings.axisTitleLabelsToLabelsSpacing + self.axisTitleLabelsHeight } override var length: CGFloat { return p2.x - p1.x } override func chartViewDrawing(context context: CGContextRef, chart: Chart) { super.chartViewDrawing(context: context, chart: chart) } override func generateLineDrawer(offset offset: CGFloat) -> ChartLineDrawer { let p1 = CGPointMake(self.p1.x, self.p1.y + offset) let p2 = CGPointMake(self.p2.x, self.p2.y + offset) return ChartLineDrawer(p1: p1, p2: p2, color: self.settings.lineColor, strokeWidth: self.settings.axisStrokeWidth) } override func generateAxisTitleLabelsDrawers(offset offset: CGFloat) -> [ChartLabelDrawer] { return self.generateAxisTitleLabelsDrawers(self.axisTitleLabels, spacingLabelAxisX: self.settings.labelsToAxisSpacingX, spacingLabelBetweenAxis: self.settings.labelsSpacing, offset: offset) } private func generateAxisTitleLabelsDrawers(labels: [ChartAxisLabel], spacingLabelAxisX: CGFloat, spacingLabelBetweenAxis: CGFloat, offset: CGFloat) -> [ChartLabelDrawer] { let rowHeights = self.rowHeightsForRows(labels.map { [$0] }) return labels.enumerate().map{(index, label) in let rowY = self.calculateRowY(rowHeights: rowHeights, rowIndex: index, spacing: spacingLabelBetweenAxis) let labelWidth = ChartUtils.textSize(label.text, font: label.settings.font).width let x = (self.p2.x - self.p1.x) / 2 + self.p1.x - labelWidth / 2 let y = self.p1.y + offset + rowY let drawer = ChartLabelDrawer(text: label.text, screenLoc: CGPointMake(x, y), settings: label.settings) drawer.hidden = label.hidden return drawer } } override func screenLocForScalar(scalar: Double, firstAxisScalar: Double) -> CGFloat { return self.p1.x + self.innerScreenLocForScalar(scalar, firstAxisScalar: firstAxisScalar) } // calculate row heights (max text height) for each row private func calculateRowHeights() -> [CGFloat] { // organize labels in rows let maxRowCount = self.axisValues.reduce(-1) {maxCount, axisValue in max(maxCount, axisValue.labels.count) } let rows:[[ChartAxisLabel?]] = (0..<maxRowCount).map {row in self.axisValues.map {axisValue in let labels = axisValue.labels return row < labels.count ? labels[row] : nil } } return self.rowHeightsForRows(rows) } override func generateLabelDrawers(offset offset: CGFloat) -> [ChartLabelDrawer] { let spacingLabelBetweenAxis = self.settings.labelsSpacing let rowHeights = self.rowHeights // generate all the label drawers, in a flat list return self.axisValues.flatMap {axisValue in return Array(axisValue.labels.enumerate()).map {index, label in let rowY = self.calculateRowY(rowHeights: rowHeights, rowIndex: index, spacing: spacingLabelBetweenAxis) let x = self.screenLocForScalar(axisValue.scalar) let y = self.p1.y + offset + rowY let labelSize = ChartUtils.textSize(label.text, font: label.settings.font) let labelX = x - (labelSize.width / 2) let labelDrawer = ChartLabelDrawer(text: label.text, screenLoc: CGPointMake(labelX, y), settings: label.settings) labelDrawer.hidden = label.hidden return labelDrawer } } } // Get the y offset of row relative to the y position of the first row private func calculateRowY(rowHeights rowHeights: [CGFloat], rowIndex: Int, spacing: CGFloat) -> CGFloat { return Array(0..<rowIndex).reduce(0) {y, index in y + rowHeights[index] + spacing } } // Get max text height for each row of axis values private func rowHeightsForRows(rows: [[ChartAxisLabel?]]) -> [CGFloat] { return rows.map { row in row.flatMap { $0 }.reduce(-1) { maxHeight, label in return max(maxHeight, label.textSize.height) } } } }
apache-2.0
d452abca12e3a1b6bc161941f87ec572
38.392308
197
0.626831
4.655455
false
false
false
false
salesforce-ux/design-system-ios
Demo-Swift/slds-sample-app/library/model/IconObject.swift
1
2517
// Copyright (c) 2015-present, salesforce.com, inc. All rights reserved // Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license import UIKit enum IconObjectType : String { case action = "Action" case custom = "Custom" case standard = "Standard" case utility = "Utility" } struct IconObject { var type : IconObjectType var index: NSInteger var size : CGFloat = 0.0 //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– var method : String { switch self.type { case .action : return "sldsActionIcon" case .custom : return "sldsCustomIcon" case .standard : return "sldsStandardIcon" case .utility : return "sldsUtilityIcon" } } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– var name : String { return NSString.sldsIconName(index) } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– func getImage() -> UIImage? { switch self.type { case .action : if let value = SLDSActionIconType.init(rawValue: self.index) { return UIImage.sldsActionIcon(value, withSize: self.size) } case .custom : if let value = SLDSCustomIconType.init(rawValue: self.index) { return UIImage.sldsCustomIcon(value, withSize: self.size) } case .standard : if let value = SLDSStandardIconType.init(rawValue: index) { return UIImage.sldsStandardIcon(value, withSize: self.size) } case .utility : if let value = SLDSUtilityIconType.init(rawValue: self.index) { return UIImage.sldsUtilityIcon(value, with: UIColor.sldsFill(.brandActive), andSize: self.size) } } return nil } }
bsd-3-clause
b9f8c381558ccb9c8df47b930d542261
27.859155
111
0.48121
5.174242
false
false
false
false
ymkil/LKImagePicker
LKImagePickerExample/LKImagePickerExample/LKTestCell.swift
1
1195
// // LKTestCell.swift // LKImagePicker // // Created by Mkil on 11/01/2017. // Copyright © 2017 黎宁康. All rights reserved. // import UIKit class LKTestCell: UICollectionViewCell { lazy var imageView: UIImageView = { [unowned self] in let imageView = UIImageView() imageView.frame = self.bounds imageView.backgroundColor = UIColor.init(white: 1.000, alpha: 0.500) imageView.contentMode = .scaleAspectFit return imageView }() lazy var deleteBtn: UIButton = { [unowned self] in let deleteBtn = UIButton(type: .custom) deleteBtn.frame = CGRect(x: self.frame.size.width - 36, y: 0, width: 36, height: 36) deleteBtn.imageEdgeInsets = UIEdgeInsetsMake(-10, 0, 0, -10) deleteBtn.setImage(UIImage(named: "photo_delete"), for: .normal) deleteBtn.alpha = 0.6 return deleteBtn }() override init(frame: CGRect) { super.init(frame: frame) [imageView,deleteBtn].forEach { addSubview($0) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
0cf7ffeb59353b33e4f4fa4cca888390
26
92
0.606061
4.153846
false
false
false
false
tardieu/swift
test/SILGen/partial_apply_protocol.swift
1
14285
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -emit-silgen %s | %FileCheck %s protocol Clonable { func clone() -> Self func maybeClone() -> Self? func cloneMetatype() -> Self.Type func getCloneFn() -> () -> Self func genericClone<T>(t: T) -> Self func genericGetCloneFn<T>(t: T) -> () -> Self } //===----------------------------------------------------------------------===// // Partial apply of methods returning Self-derived types //===----------------------------------------------------------------------===// // CHECK-LABEL: sil hidden @_T022partial_apply_protocol12testClonableyAA0E0_p1c_tF : $@convention(thin) (@in Clonable) -> () func testClonable(c: Clonable) { // CHECK: [[THUNK_FN:%.*]] = function_ref @_T0xIxr_22partial_apply_protocol8Clonable_pIxr_AaBRzlTR : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @out τ_0_0) -> @out Clonable // CHECK: [[THUNK:%.*]] = partial_apply [[THUNK_FN]]<@opened("{{.*}}") Clonable>({{.*}}) : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @out τ_0_0) -> @out Clonable let _: () -> Clonable = c.clone // CHECK: [[THUNK_FN:%.*]] = function_ref @_T0xSgIxr_22partial_apply_protocol8Clonable_pSgIxr_AaBRzlTR : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @out Optional<τ_0_0>) -> @out Optional<Clonable> // CHECK: [[THUNK:%.*]] = partial_apply [[THUNK_FN]]<@opened("{{.*}}") Clonable>({{.*}}) : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @out Optional<τ_0_0>) -> @out Optional<Clonable> let _: () -> Clonable? = c.maybeClone // CHECK: [[THUNK_FN:%.*]] = function_ref @_T0xXMTIxd_22partial_apply_protocol8Clonable_pXmTIxd_AaBRzlTR : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @thick τ_0_0.Type) -> @thick Clonable.Type // CHECK: [[THUNK:%.*]] = partial_apply [[THUNK_FN]]<@opened("{{.*}}") Clonable>({{.*}}) : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @thick τ_0_0.Type) -> @thick Clonable.Type let _: () -> Clonable.Type = c.cloneMetatype // CHECK: [[METHOD_FN:%.*]] = witness_method $@opened("{{.*}}") Clonable, #Clonable.getCloneFn!1 : {{.*}}, {{.*}} : $*@opened("{{.*}}") Clonable : $@convention(witness_method) <τ_0_0 where τ_0_0 : Clonable> (@in_guaranteed τ_0_0) -> @owned @callee_owned () -> @out τ_0_0 // CHECK: [[RESULT:%.*]] = apply [[METHOD_FN]]<@opened("{{.*}}") Clonable>({{.*}}) : $@convention(witness_method) <τ_0_0 where τ_0_0 : Clonable> (@in_guaranteed τ_0_0) -> @owned @callee_owned () -> @out τ_0_0 // CHECK: [[THUNK_FN:%.*]] = function_ref @_T0xIxr_22partial_apply_protocol8Clonable_pIxr_AaBRzlTR : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @out τ_0_0) -> @out Clonable // CHECK: [[THUNK:%.*]] = partial_apply [[THUNK_FN]]<@opened("{{.*}}") Clonable>([[RESULT]]) : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @out τ_0_0) -> @out Clonable let _: () -> Clonable = c.getCloneFn() // CHECK: [[THUNK_FN:%.*]] = function_ref @_T0xIxr_Ixo_22partial_apply_protocol8Clonable_pIxr_Ixo_AaBRzlTR : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @owned @callee_owned () -> @out τ_0_0) -> @owned @callee_owned () -> @out Clonable // CHECK: [[THUNK:%.*]] = partial_apply [[THUNK_FN]]<@opened("{{.*}}") Clonable>({{.*}}) : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @owned @callee_owned () -> @out τ_0_0) -> @owned @callee_owned () -> @out Clonable let _: () -> () -> Clonable = c.getCloneFn } // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_T0xIxr_22partial_apply_protocol8Clonable_pIxr_AaBRzlTR : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @out τ_0_0) -> @out Clonable // CHECK: bb0(%0 : $*Clonable, %1 : $@callee_owned () -> @out τ_0_0): // CHECK-NEXT: [[INNER_RESULT:%.*]] = alloc_stack $τ_0_0 // CHECK-NEXT: apply %1([[INNER_RESULT]]) // CHECK-NEXT: [[OUTER_RESULT:%.*]] = init_existential_addr %0 // CHECK-NEXT: copy_addr [take] [[INNER_RESULT]] to [initialization] [[OUTER_RESULT]] // CHECK-NEXT: [[EMPTY:%.*]] = tuple () // CHECK-NEXT: dealloc_stack [[INNER_RESULT]] // CHECK-NEXT: return [[EMPTY]] // FIXME: This is horribly inefficient, too much alloc_stack / copy_addr! // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_T0xSgIxr_22partial_apply_protocol8Clonable_pSgIxr_AaBRzlTR : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @out Optional<τ_0_0>) -> @out Optional<Clonable> // CHECK: bb0(%0 : $*Optional<Clonable>, %1 : $@callee_owned () -> @out Optional<τ_0_0>): // CHECK-NEXT: [[INNER_RESULT:%.*]] = alloc_stack $Optional<τ_0_0> // CHECK-NEXT: apply %1([[INNER_RESULT]]) // CHECK-NEXT: [[OUTER_RESULT:%.*]] = alloc_stack $Optional<Clonable> // CHECK: [[IS_SOME:%.*]] = select_enum_addr [[INNER_RESULT]] // CHECK-NEXT: cond_br [[IS_SOME]], bb1, bb2 // CHECK: bb1: // CHECK-NEXT: [[INNER_RESULT_ADDR:%.*]] = unchecked_take_enum_data_addr [[INNER_RESULT]] // CHECK-NEXT: [[SOME_PAYLOAD:%.*]] = alloc_stack $Clonable // CHECK-NEXT: [[SOME_PAYLOAD_ADDR:%.*]] = init_existential_addr [[SOME_PAYLOAD]] // CHECK-NEXT: copy_addr [take] [[INNER_RESULT_ADDR]] to [initialization] [[SOME_PAYLOAD_ADDR]] // CHECK-NEXT: [[OUTER_RESULT_ADDR:%.*]] = init_enum_data_addr [[OUTER_RESULT]] // CHECK-NEXT: copy_addr [take] [[SOME_PAYLOAD]] to [initialization] [[OUTER_RESULT_ADDR]] // CHECK-NEXT: inject_enum_addr [[OUTER_RESULT]] // CHECK-NEXT: dealloc_stack [[SOME_PAYLOAD]] // CHECK-NEXT: br bb3 // CHECK: bb2: // CHECK-NEXT: inject_enum_addr [[OUTER_RESULT]] // CHECK-NEXT: br bb3 // CHECK: bb3: // CHECK-NEXT: copy_addr [take] [[OUTER_RESULT]] to [initialization] %0 // CHECK-NEXT: [[EMPTY:%.*]] = tuple () // CHECK-NEXT: dealloc_stack [[OUTER_RESULT]] // CHECK-NEXT: dealloc_stack [[INNER_RESULT]] // CHECK-NEXT: return [[EMPTY]] // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_T0xXMTIxd_22partial_apply_protocol8Clonable_pXmTIxd_AaBRzlTR : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @thick τ_0_0.Type) -> @thick Clonable.Type // CHECK: bb0(%0 : $@callee_owned () -> @thick τ_0_0.Type): // CHECK-NEXT: [[INNER_RESULT:%.*]] = apply %0() // CHECK-NEXT: [[OUTER_RESULT:%.*]] = init_existential_metatype [[INNER_RESULT]] // CHECK-NEXT: return [[OUTER_RESULT]] // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_T0xIxr_Ixo_22partial_apply_protocol8Clonable_pIxr_Ixo_AaBRzlTR : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @owned @callee_owned () -> @out τ_0_0) -> @owned @callee_owned () -> @out Clonable // CHECK: bb0(%0 : $@callee_owned () -> @owned @callee_owned () -> @out τ_0_0): // CHECK-NEXT: [[INNER_RESULT:%.*]] = apply %0() // CHECK: [[THUNK_FN:%.*]] = function_ref @_T0xIxr_22partial_apply_protocol8Clonable_pIxr_AaBRzlTR // CHECK-NEXT: [[OUTER_RESULT:%.*]] = partial_apply [[THUNK_FN]]<τ_0_0>([[INNER_RESULT]]) // CHECK-NEXT: return [[OUTER_RESULT]] //===----------------------------------------------------------------------===// // Partial apply of methods returning Self-derived types from generic context // // Make sure the thunk only has the context generic parameters if needed! //===----------------------------------------------------------------------===// // CHECK-LABEL: sil hidden @_T022partial_apply_protocol28testClonableInGenericContextyAA0E0_p1c_x1ttlF : $@convention(thin) <T> (@in Clonable, @in T) -> () func testClonableInGenericContext<T>(c: Clonable, t: T) { // CHECK: [[THUNK_FN:%.*]] = function_ref @_T0xIxr_22partial_apply_protocol8Clonable_pIxr_AaBRzlTR : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @out τ_0_0) -> @out Clonable // CHECK: [[THUNK:%.*]] = partial_apply [[THUNK_FN]]<@opened("{{.*}}") Clonable>({{.*}}) : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @out τ_0_0) -> @out Clonable let _: () -> Clonable = c.clone // CHECK: [[THUNK_FN:%.*]] = function_ref @_T0xSgIxr_22partial_apply_protocol8Clonable_pSgIxr_AaBRzlTR : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @out Optional<τ_0_0>) -> @out Optional<Clonable> // CHECK: [[THUNK:%.*]] = partial_apply [[THUNK_FN]]<@opened("{{.*}}") Clonable>({{.*}}) : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @out Optional<τ_0_0>) -> @out Optional<Clonable> let _: () -> Clonable? = c.maybeClone // CHECK: [[THUNK_FN:%.*]] = function_ref @_T0xXMTIxd_22partial_apply_protocol8Clonable_pXmTIxd_AaBRzlTR : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @thick τ_0_0.Type) -> @thick Clonable.Type // CHECK: [[THUNK:%.*]] = partial_apply [[THUNK_FN]]<@opened("{{.*}}") Clonable>({{.*}}) : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @thick τ_0_0.Type) -> @thick Clonable.Type let _: () -> Clonable.Type = c.cloneMetatype // CHECK: [[METHOD_FN:%.*]] = witness_method $@opened("{{.*}}") Clonable, #Clonable.getCloneFn!1 : {{.*}}, {{.*}} : $*@opened("{{.*}}") Clonable : $@convention(witness_method) <τ_0_0 where τ_0_0 : Clonable> (@in_guaranteed τ_0_0) -> @owned @callee_owned () -> @out τ_0_0 // CHECK: [[RESULT:%.*]] = apply [[METHOD_FN]]<@opened("{{.*}}") Clonable>({{.*}}) : $@convention(witness_method) <τ_0_0 where τ_0_0 : Clonable> (@in_guaranteed τ_0_0) -> @owned @callee_owned () -> @out τ_0_0 // CHECK: [[THUNK_FN:%.*]] = function_ref @_T0xIxr_22partial_apply_protocol8Clonable_pIxr_AaBRzlTR : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @out τ_0_0) -> @out Clonable // CHECK: [[THUNK:%.*]] = partial_apply [[THUNK_FN]]<@opened("{{.*}}") Clonable>([[RESULT]]) : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @out τ_0_0) -> @out Clonable let _: () -> Clonable = c.getCloneFn() // CHECK: [[THUNK_FN:%.*]] = function_ref @_T0xIxr_Ixo_22partial_apply_protocol8Clonable_pIxr_Ixo_AaBRzlTR : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @owned @callee_owned () -> @out τ_0_0) -> @owned @callee_owned () -> @out Clonable // CHECK: [[THUNK:%.*]] = partial_apply [[THUNK_FN]]<@opened("{{.*}}") Clonable>({{.*}}) : $@convention(thin) <τ_0_0 where τ_0_0 : Clonable> (@owned @callee_owned () -> @owned @callee_owned () -> @out τ_0_0) -> @owned @callee_owned () -> @out Clonable let _: () -> () -> Clonable = c.getCloneFn // CHECK: [[THUNK_FN:%.*]] = function_ref @_T0xqd__Ixir_x22partial_apply_protocol8Clonable_pIxir_AaBRd__r__lTR : $@convention(thin) <τ_0_0><τ_1_0 where τ_1_0 : Clonable> (@in τ_0_0, @owned @callee_owned (@in τ_0_0) -> @out τ_1_0) -> @out Clonable // CHECK: [[THUNK:%.*]] = partial_apply [[THUNK_FN]]<T, @opened("{{.*}}") Clonable>({{.*}}) : $@convention(thin) <τ_0_0><τ_1_0 where τ_1_0 : Clonable> (@in τ_0_0, @owned @callee_owned (@in τ_0_0) -> @out τ_1_0) -> @out Clonable let _: (T) -> Clonable = c.genericClone // CHECK: [[THUNK_FN:%.*]] = function_ref @_T0xqd__Ixr_Ixio_x22partial_apply_protocol8Clonable_pIxr_Ixio_AaBRd__r__lTR : $@convention(thin) <τ_0_0><τ_1_0 where τ_1_0 : Clonable> (@in τ_0_0, @owned @callee_owned (@in τ_0_0) -> @owned @callee_owned () -> @out τ_1_0) -> @owned @callee_owned () -> @out Clonable // CHECK: [[THUNK:%.*]] = partial_apply [[THUNK_FN]]<T, @opened("{{.*}}") Clonable>({{.*}}) : $@convention(thin) <τ_0_0><τ_1_0 where τ_1_0 : Clonable> (@in τ_0_0, @owned @callee_owned (@in τ_0_0) -> @owned @callee_owned () -> @out τ_1_0) -> @owned @callee_owned () -> @out Clonable let _: (T) -> () -> Clonable = c.genericGetCloneFn } // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_T0xqd__Ixir_x22partial_apply_protocol8Clonable_pIxir_AaBRd__r__lTR : $@convention(thin) <τ_0_0><τ_1_0 where τ_1_0 : Clonable> (@in τ_0_0, @owned @callee_owned (@in τ_0_0) -> @out τ_1_0) -> @out Clonable // CHECK: bb0(%0 : $*Clonable, %1 : $*τ_0_0, %2 : $@callee_owned (@in τ_0_0) -> @out τ_1_0): // CHECK-NEXT: [[INNER_RESULT:%.*]] = alloc_stack $τ_1_0 // CHECK-NEXT: apply %2([[INNER_RESULT]], %1) // CHECK-NEXT: [[OUTER_RESULT:%.*]] = init_existential_addr %0 // CHECK-NEXT: copy_addr [take] [[INNER_RESULT]] to [initialization] [[OUTER_RESULT]] // CHECK-NEXT: [[EMPTY:%.*]] = tuple () // CHECK-NEXT: dealloc_stack [[INNER_RESULT]] // CHECK-NEXT: return [[EMPTY]] // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_T0xqd__Ixr_Ixio_x22partial_apply_protocol8Clonable_pIxr_Ixio_AaBRd__r__lTR : $@convention(thin) <τ_0_0><τ_1_0 where τ_1_0 : Clonable> (@in τ_0_0, @owned @callee_owned (@in τ_0_0) -> @owned @callee_owned () -> @out τ_1_0) -> @owned @callee_owned () -> @out Clonable // CHECK: bb0(%0 : $*τ_0_0, %1 : $@callee_owned (@in τ_0_0) -> @owned @callee_owned () -> @out τ_1_0): // CHECK-NEXT: apply %1(%0) // CHECK: [[THUNK_FN:%.*]] = function_ref @_T0qd__Ixr_22partial_apply_protocol8Clonable_pIxr_AaBRd__r__lTR // CHECK-NEXT: [[RESULT:%.*]] = partial_apply [[THUNK_FN]]<τ_0_0, τ_1_0>(%2) // CHECK-NEXT: return [[RESULT]] // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_T0qd__Ixr_22partial_apply_protocol8Clonable_pIxr_AaBRd__r__lTR : $@convention(thin) <τ_0_0><τ_1_0 where τ_1_0 : Clonable> (@owned @callee_owned () -> @out τ_1_0) -> @out Clonable { // CHECK: bb0(%0 : $*Clonable, %1 : $@callee_owned () -> @out τ_1_0): // CHECK-NEXT: [[INNER_RESULT:%.*]] = alloc_stack $τ_1_0 // CHECK-NEXT: apply %1([[INNER_RESULT]]) // CHECK-NEXT: [[OUTER_RESULT:%.*]] = init_existential_addr %0 // CHECK-NEXT: copy_addr [take] [[INNER_RESULT]] to [initialization] [[OUTER_RESULT]] // CHECK-NEXT: [[EMPTY:%.*]] = tuple () // CHECK-NEXT: dealloc_stack [[INNER_RESULT:%.*]] // CHECK-NEXT: return [[EMPTY]]
apache-2.0
fb59b7ff9526030d9c26a2f186b4daa5
88.487342
329
0.596435
3.046542
false
false
false
false
siquare/taml
Timetable/MyPlayground.playground/section-1.swift
1
14078
// // SWXMLHash.swift // // Copyright (c) 2014 David Mohundro // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation let rootElementName = "SWXMLHash_Root_Element" /// Simple XML parser. public class SWXMLHash { /** Method to parse XML passed in as a string. :param: xml The XML to be parsed :returns: An XMLIndexer instance that is used to look up elements in the XML */ class public func parse(xml: String) -> XMLIndexer { return parse((xml as NSString).dataUsingEncoding(NSUTF8StringEncoding)!) } /** Method to parse XML passed in as an NSData instance. :param: xml The XML to be parsed :returns: An XMLIndexer instance that is used to look up elements in the XML */ class public func parse(data: NSData) -> XMLIndexer { var parser = XMLParser() return parser.parse(data) } class public func lazy(xml: String) -> XMLIndexer { return lazy((xml as NSString).dataUsingEncoding(NSUTF8StringEncoding)!) } class public func lazy(data: NSData) -> XMLIndexer { var parser = LazyXMLParser() return parser.parse(data) } } struct Stack<T> { var items = [T]() mutating func push(item: T) { items.append(item) } mutating func pop() -> T { return items.removeLast() } mutating func removeAll() { items.removeAll(keepCapacity: false) } func top() -> T { return items[items.count - 1] } } class LazyXMLParser: NSObject, NSXMLParserDelegate { override init() { super.init() } var root = XMLElement(name: rootElementName) var parentStack = Stack<XMLElement>() var elementStack = Stack<String>() var data: NSData? var ops: [IndexOp] = [] func parse(data: NSData) -> XMLIndexer { self.data = data return XMLIndexer(self) } func startParsing(ops: [IndexOp]) { // clear any prior runs of parse... expected that this won't be necessary, but you never know parentStack.removeAll() root = XMLElement(name: rootElementName) parentStack.push(root) self.ops = ops let parser = NSXMLParser(data: data!) parser.delegate = self parser.parse() } func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [NSObject : AnyObject]) { elementStack.push(elementName) if !onMatch() { return } let currentNode = parentStack.top().addElement(elementName, withAttributes: attributeDict) parentStack.push(currentNode) } func parser(parser: NSXMLParser, foundCharacters string: String?) { if !onMatch() { return } let current = parentStack.top() if current.text == nil { current.text = "" } parentStack.top().text! += string! } func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { let match = onMatch() elementStack.pop() if match { parentStack.pop() } } func onMatch() -> Bool { // we typically want to compare against the elementStack to see if it matches ops, *but* // if we're on the first element, we'll instead compare the other direction. if elementStack.items.count > ops.count { return startsWith(elementStack.items, ops.map { $0.key }) } else { return startsWith(ops.map { $0.key }, elementStack.items) } } } /// The implementation of NSXMLParserDelegate and where the parsing actually happens. class XMLParser: NSObject, NSXMLParserDelegate { override init() { super.init() } var root = XMLElement(name: rootElementName) var parentStack = Stack<XMLElement>() func parse(data: NSData) -> XMLIndexer { // clear any prior runs of parse... expected that this won't be necessary, but you never know parentStack.removeAll() parentStack.push(root) let parser = NSXMLParser(data: data) parser.delegate = self parser.parse() return XMLIndexer(root) } func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [NSObject : AnyObject]) { let currentNode = parentStack.top().addElement(elementName, withAttributes: attributeDict) parentStack.push(currentNode) } func parser(parser: NSXMLParser, foundCharacters string: String?) { let current = parentStack.top() if current.text == nil { current.text = "" } parentStack.top().text! += string! } func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { parentStack.pop() } } public class IndexOp { var index: Int let key: String init(_ key: String) { self.key = key self.index = -1 } func toString() -> String { if index >= 0 { return key + " " + index.description } return key } } public class IndexOps { var ops: [IndexOp] = [] let parser: LazyXMLParser init(parser: LazyXMLParser) { self.parser = parser } func findElements() -> XMLIndexer { parser.startParsing(ops) let indexer = XMLIndexer(parser.root) var childIndex = indexer for op in ops { childIndex = childIndex[op.key] if op.index >= 0 { childIndex = childIndex[op.index] } } ops.removeAll(keepCapacity: false) return childIndex } func stringify() -> String { var s = "" for op in ops { s += "[" + op.toString() + "]" } return s } } /// Returned from SWXMLHash, allows easy element lookup into XML data. public enum XMLIndexer: SequenceType { case Element(XMLElement) case List([XMLElement]) case Stream(IndexOps) case Error(NSError) /// The underlying XMLElement at the currently indexed level of XML. public var element: XMLElement? { switch self { case .Element(let elem): return elem case .Stream(let ops): let list = ops.findElements() return list.element default: return nil } } /// All elements at the currently indexed level public var all: [XMLIndexer] { switch self { case .List(let list): var xmlList = [XMLIndexer]() for elem in list { xmlList.append(XMLIndexer(elem)) } return xmlList case .Element(let elem): return [XMLIndexer(elem)] case .Stream(let ops): let list = ops.findElements() return list.all default: return [] } } /// All child elements from the currently indexed level public var children: [XMLIndexer] { var list = [XMLIndexer]() for elem in all.map({ $0.element! }) { for elem in elem.children { list.append(XMLIndexer(elem)) } } return list } /** Allows for element lookup by matching attribute values. :param: attr should the name of the attribute to match on :param: _ should be the value of the attribute to match on :returns: instance of XMLIndexer */ public func withAttr(attr: String, _ value: String) -> XMLIndexer { let attrUserInfo = [NSLocalizedDescriptionKey: "XML Attribute Error: Missing attribute [\"\(attr)\"]"] let valueUserInfo = [NSLocalizedDescriptionKey: "XML Attribute Error: Missing attribute [\"\(attr)\"] with value [\"\(value)\"]"] switch self { case .Stream(let opStream): opStream.stringify() let match = opStream.findElements() return match.withAttr(attr, value) case .List(let list): if let elem = list.filter({$0.attributes[attr] == value}).first { return .Element(elem) } return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: valueUserInfo)) case .Element(let elem): if let attr = elem.attributes[attr] { if attr == value { return .Element(elem) } return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: valueUserInfo)) } return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: attrUserInfo)) default: return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: attrUserInfo)) } } /** Initializes the XMLIndexer :param: _ should be an instance of XMLElement, but supports other values for error handling :returns: instance of XMLIndexer */ public init(_ rawObject: AnyObject) { switch rawObject { case let value as XMLElement: self = .Element(value) case let value as LazyXMLParser: self = .Stream(IndexOps(parser: value)) default: self = .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: nil)) } } /** Find an XML element at the current level by element name :param: key The element name to index by :returns: instance of XMLIndexer to match the element (or elements) found by key */ public subscript(key: String) -> XMLIndexer { let userInfo = [NSLocalizedDescriptionKey: "XML Element Error: Incorrect key [\"\(key)\"]"] switch self { case .Stream(let opStream): let op = IndexOp(key) opStream.ops.append(op) return .Stream(opStream) case .Element(let elem): let match = elem.children.filter({ $0.name == key }) if match.count > 0 { if match.count == 1 { return .Element(match[0]) } else { return .List(match) } } return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: userInfo)) default: return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: userInfo)) } } /** Find an XML element by index within a list of XML Elements at the current level :param: index The 0-based index to index by :returns: instance of XMLIndexer to match the element (or elements) found by key */ public subscript(index: Int) -> XMLIndexer { let userInfo = [NSLocalizedDescriptionKey: "XML Element Error: Incorrect index [\"\(index)\"]"] switch self { case .Stream(let opStream): opStream.ops[opStream.ops.count - 1].index = index return .Stream(opStream) case .List(let list): if index <= list.count { return .Element(list[index]) } return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: userInfo)) case .Element(let elem): if index == 0 { return .Element(elem) } else { return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: userInfo)) } default: return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: userInfo)) } } typealias GeneratorType = XMLIndexer public func generate() -> IndexingGenerator<[XMLIndexer]> { return all.generate() } } /// XMLIndexer extensions extension XMLIndexer: BooleanType { /// True if a valid XMLIndexer, false if an error type public var boolValue: Bool { switch self { case .Error: return false default: return true } } } extension XMLIndexer: Printable { public var description: String { switch self { case .List(let list): return "\n".join(list.map { $0.description }) case .Element(let elem): if elem.name == rootElementName { return "\n".join(elem.children.map { $0.description }) } return elem.description default: return "" } } } /// Models an XML element, including name, text and attributes public class XMLElement { /// The name of the element public let name: String /// The inner text of the element, if it exists public var text: String? /// The attributes of the element public var attributes = [String:String]() var children = [XMLElement]() var count: Int = 0 var index: Int /** Initialize an XMLElement instance :param: name The name of the element to be initialized :returns: a new instance of XMLElement */ init(name: String, index: Int = 0) { self.name = name self.index = index } /** Adds a new XMLElement underneath this instance of XMLElement :param: name The name of the new element to be added :param: withAttributes The attributes dictionary for the element being added :returns: The XMLElement that has now been added */ func addElement(name: String, withAttributes attributes: NSDictionary) -> XMLElement { let element = XMLElement(name: name, index: count) count++ children.append(element) for (keyAny,valueAny) in attributes { if let key = keyAny as? String, let value = valueAny as? String { element.attributes[key] = value } } return element } } extension XMLElement: Printable { public var description: String { var attributesStringList = [String]() if !attributes.isEmpty { for (key, val) in attributes { attributesStringList.append("\(key)=\"\(val)\"") } } var attributesString = " ".join(attributesStringList) if !attributesString.isEmpty { attributesString = " " + attributesString } if children.count > 0 { var xmlReturn = [String]() xmlReturn.append("<\(name)\(attributesString)>") for child in children { xmlReturn.append(child.description) } xmlReturn.append("</\(name)>") return "\n".join(xmlReturn) } if text != nil { return "<\(name)\(attributesString)>\(text!)</\(name)>" } else { return "<\(name)\(attributesString)/>" } } } let myData = "<root>" + "<catalog>" + "<book><author>Bob</author></book>" + "<book><author>John</author></book>" + "<book><author>Mark</author></book>" + "</catalog>" + "</root>" var myXML = SWXMLHash.parse(myData) myXML["root"]["catalog"]["book"].all for x in myXML["root"]["catalog"]["book"].all { print(x["author"].element!.text!) }
mit
b29599e5698941725cd4cc844cc0ecbc
24.689781
175
0.686532
3.642432
false
false
false
false
HackerEdu/Lijingrui
First day/Prime /Prime Number/ViewController.swift
1
1242
// // ViewController.swift // Prime Number // // Created by apple on 15/2/2. // Copyright (c) 2015年 apple. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } @IBOutlet weak var Numbertyped: UITextField! @IBOutlet weak var Result: UILabel! @IBAction func Check(sender: AnyObject) { var number = Numbertyped.text.toInt() if number != nil { if number > 3{ for var i = 2 ; i * i <= number ; i++ { if Int(number!) % i == 0 { Result.text = "composite" break } else { } Result.text = "prime" } } else { Result.text = "prime" } } else { Result.text = "error" } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
4fcf9d97418e87e2007e9e6f28bd8480
23.8
80
0.473387
4.862745
false
false
false
false
codestergit/swift
test/SILGen/nested_generics.swift
2
14521
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-silgen -parse-as-library %s | %FileCheck %s // RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-sil -parse-as-library %s > /dev/null // RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-sil -O -parse-as-library %s > /dev/null // RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-ir -parse-as-library %s > /dev/null // TODO: // - test generated SIL -- mostly we're just testing mangling here // - class_method calls // - witness_method calls // - inner generic parameters on protocol requirements // - generic parameter list on method in nested type // - types nested inside unconstrained extensions of generic types protocol Pizza : class { associatedtype Topping } protocol HotDog { associatedtype Condiment } protocol CuredMeat {} // Generic nested inside generic struct Lunch<T : Pizza> where T.Topping : CuredMeat { struct Dinner<U : HotDog> where U.Condiment == Deli<Pepper>.Mustard { let firstCourse: T let secondCourse: U? var leftovers: T var transformation: (T) -> U func coolCombination(t: T.Topping, u: U.Condiment) { func nestedGeneric<X, Y>(x: X, y: Y) -> (X, Y) { return (x, y) } _ = nestedGeneric(x: t, y: u) } } } // CHECK-LABEL: // nested_generics.Lunch.Dinner.coolCombination (t : A.Topping, u : nested_generics.Deli<nested_generics.Pepper>.Mustard) -> () // CHECK-LABEL: sil hidden @_T015nested_generics5LunchV6DinnerV15coolCombinationy7ToppingQz1t_AA4DeliC7MustardOyAA6PepperV_G1utF : $@convention(method) <T where T : Pizza, T.Topping : CuredMeat><U where U : HotDog, U.Condiment == Deli<Pepper>.Mustard> (@in T.Topping, Deli<Pepper>.Mustard, @in_guaranteed Lunch<T>.Dinner<U>) -> () // CHECK-LABEL: // nested_generics.Lunch.Dinner.(coolCombination (t : A.Topping, u : nested_generics.Deli<nested_generics.Pepper>.Mustard) -> ()).(nestedGeneric #1) <A><A1><A2, B2 where A: nested_generics.Pizza, A1: nested_generics.HotDog, A.Topping: nested_generics.CuredMeat, A1.Condiment == nested_generics.Deli<nested_generics.Pepper>.Mustard> (x : A2, y : B2) -> (A2, B2) // CHECK-LABEL: sil private @_T015nested_generics5LunchV6DinnerV15coolCombinationy7ToppingQz1t_AA4DeliC7MustardOyAA6PepperV_G1utF0A7GenericL_qd0___qd0_0_tqd0__1x_qd0_0_1ytAA5PizzaRzAA6HotDogRd__AA9CuredMeatAHRQAP9CondimentRtd__r__0_lF : $@convention(thin) <T where T : Pizza, T.Topping : CuredMeat><U where U : HotDog, U.Condiment == Deli<Pepper>.Mustard><X, Y> (@in X, @in Y) -> (@out X, @out Y) // CHECK-LABEL: // nested_generics.Lunch.Dinner.init (firstCourse : A, secondCourse : Swift.Optional<A1>, leftovers : A, transformation : (A) -> A1) -> nested_generics.Lunch<A>.Dinner<A1> // CHECK-LABEL: sil hidden @_T015nested_generics5LunchV6DinnerVAEyx_qd__Gx11firstCourse_qd__Sg06secondF0x9leftoversqd__xc14transformationtcfC : $@convention(method) <T where T : Pizza, T.Topping : CuredMeat><U where U : HotDog, U.Condiment == Deli<Pepper>.Mustard> (@owned T, @in Optional<U>, @owned T, @owned @callee_owned (@owned T) -> @out U, @thin Lunch<T>.Dinner<U>.Type) -> @out Lunch<T>.Dinner<U> // Non-generic nested inside generic class Deli<Spices> : CuredMeat { class Pepperoni : CuredMeat {} struct Sausage : CuredMeat {} enum Mustard { case Yellow case Dijon case DeliStyle(Spices) } } // CHECK-LABEL: // nested_generics.Deli.Pepperoni.init () -> nested_generics.Deli<A>.Pepperoni // CHECK-LABEL: sil hidden @_T015nested_generics4DeliC9PepperoniCAEyx_Gycfc : $@convention(method) <Spices> (@owned Deli<Spices>.Pepperoni) -> @owned Deli<Spices>.Pepperoni // Typealiases referencing outer generic parameters struct Pizzas<Spices> { class NewYork : Pizza { typealias Topping = Deli<Spices>.Pepperoni } class DeepDish : Pizza { typealias Topping = Deli<Spices>.Sausage } } class HotDogs { struct Bratwurst : HotDog { typealias Condiment = Deli<Pepper>.Mustard } struct American : HotDog { typealias Condiment = Deli<Pepper>.Mustard } } // Local type in extension of type in another module extension String { func foo() { // CHECK-LABEL: // (extension in nested_generics):Swift.String.(foo () -> ()).(Cheese #1).init (material : A) -> (extension in nested_generics):Swift.String.(foo () -> ()).(Cheese #1)<A> // CHECK-LABEL: sil private @_T0SS15nested_genericsE3fooyyF6CheeseL_VADyxGx8material_tcfC struct Cheese<Milk> { let material: Milk } let _ = Cheese(material: "cow") } } // Local type in extension of type in same module extension HotDogs { func applyRelish() { // CHECK-LABEL: // nested_generics.HotDogs.(applyRelish () -> ()).(Relish #1).init (material : A) -> nested_generics.HotDogs.(applyRelish () -> ()).(Relish #1)<A> // CHECK-LABEL: sil private @_T015nested_generics7HotDogsC11applyRelishyyF0F0L_VAFyxGx8material_tcfC struct Relish<Material> { let material: Material } let _ = Relish(material: "pickles") } } struct Pepper {} struct ChiliFlakes {} // CHECK-LABEL: // nested_generics.eatDinnerGeneric <A, B where A: nested_generics.Pizza, B: nested_generics.HotDog, A.Topping: nested_generics.CuredMeat, B.Condiment == nested_generics.Deli<nested_generics.Pepper>.Mustard> (d : inout nested_generics.Lunch<A>.Dinner<B>, t : A.Topping, u : nested_generics.Deli<nested_generics.Pepper>.Mustard) -> () // CHECK-LABEL: sil hidden @_T015nested_generics16eatDinnerGenericyAA5LunchV0D0Vyx_q_Gz1d_7ToppingQz1tAA4DeliC7MustardOyAA6PepperV_G1utAA5PizzaRzAA6HotDogR_AA9CuredMeatAJRQAR9CondimentRt_r0_lF : $@convention(thin) <T, U where T : Pizza, U : HotDog, T.Topping : CuredMeat, U.Condiment == Deli<Pepper>.Mustard> (@inout Lunch<T>.Dinner<U>, @in T.Topping, Deli<Pepper>.Mustard) -> () func eatDinnerGeneric<T, U>(d: inout Lunch<T>.Dinner<U>, t: T.Topping, u: U.Condiment) { // Method call _ = d.coolCombination(t: t, u: u) // Read a let, store into var d.leftovers = d.firstCourse // Read a var let _ = d.secondCourse // Call property of function type _ = d.transformation(d.leftovers) } // Overloading concrete function with different bound generic arguments in parent type // CHECK-LABEL: // nested_generics.eatDinnerConcrete (d : inout nested_generics.Lunch<nested_generics.Pizzas<nested_generics.ChiliFlakes>.NewYork>.Dinner<nested_generics.HotDogs.American>, t : nested_generics.Deli<nested_generics.ChiliFlakes>.Pepperoni, u : nested_generics.Deli<nested_generics.Pepper>.Mustard) -> () // CHECK-LABEL: sil hidden @_T015nested_generics17eatDinnerConcreteyAA5LunchV0D0VyAA6PizzasV7NewYorkCyAA11ChiliFlakesV_G_AA7HotDogsC8AmericanVGz1d_AA4DeliC9PepperoniCyAL_G1tAU7MustardOyAA6PepperV_G1utF : $@convention(thin) (@inout Lunch<Pizzas<ChiliFlakes>.NewYork>.Dinner<HotDogs.American>, @owned Deli<ChiliFlakes>.Pepperoni, Deli<Pepper>.Mustard) -> () func eatDinnerConcrete(d: inout Lunch<Pizzas<ChiliFlakes>.NewYork>.Dinner<HotDogs.American>, t: Deli<ChiliFlakes>.Pepperoni, u: Deli<Pepper>.Mustard) { // Method call _ = d.coolCombination(t: t, u: u) // Read a let, store into var d.leftovers = d.firstCourse // Read a var let _ = d.secondCourse // Call property of function type _ = d.transformation(d.leftovers) } // CHECK-LABEL: // reabstraction thunk helper from @callee_owned (@owned nested_generics.Pizzas<nested_generics.ChiliFlakes>.NewYork) -> (@out nested_generics.HotDogs.American) to @callee_owned (@owned nested_generics.Pizzas<nested_generics.ChiliFlakes>.NewYork) -> (@unowned nested_generics.HotDogs.American) // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T015nested_generics6PizzasV7NewYorkCyAA11ChiliFlakesV_GAA7HotDogsC8AmericanVIxxr_AhLIxxd_TR : $@convention(thin) (@owned Pizzas<ChiliFlakes>.NewYork, @owned @callee_owned (@owned Pizzas<ChiliFlakes>.NewYork) -> @out HotDogs.American) -> HotDogs.American // CHECK-LABEL: // nested_generics.eatDinnerConcrete (d : inout nested_generics.Lunch<nested_generics.Pizzas<nested_generics.Pepper>.NewYork>.Dinner<nested_generics.HotDogs.American>, t : nested_generics.Deli<nested_generics.Pepper>.Pepperoni, u : nested_generics.Deli<nested_generics.Pepper>.Mustard) -> () // CHECK-LABEL: sil hidden @_T015nested_generics17eatDinnerConcreteyAA5LunchV0D0VyAA6PizzasV7NewYorkCyAA6PepperV_G_AA7HotDogsC8AmericanVGz1d_AA4DeliC9PepperoniCyAL_G1tAU7MustardOyAL_G1utF : $@convention(thin) (@inout Lunch<Pizzas<Pepper>.NewYork>.Dinner<HotDogs.American>, @owned Deli<Pepper>.Pepperoni, Deli<Pepper>.Mustard) -> () func eatDinnerConcrete(d: inout Lunch<Pizzas<Pepper>.NewYork>.Dinner<HotDogs.American>, t: Deli<Pepper>.Pepperoni, u: Deli<Pepper>.Mustard) { // Method call _ = d.coolCombination(t: t, u: u) // Read a let, store into var d.leftovers = d.firstCourse // Read a var let _ = d.secondCourse // Call property of function type _ = d.transformation(d.leftovers) } // CHECK-LABEL: // reabstraction thunk helper from @callee_owned (@owned nested_generics.Pizzas<nested_generics.Pepper>.NewYork) -> (@out nested_generics.HotDogs.American) to @callee_owned (@owned nested_generics.Pizzas<nested_generics.Pepper>.NewYork) -> (@unowned nested_generics.HotDogs.American) // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T015nested_generics6PizzasV7NewYorkCyAA6PepperV_GAA7HotDogsC8AmericanVIxxr_AhLIxxd_TR : $@convention(thin) (@owned Pizzas<Pepper>.NewYork, @owned @callee_owned (@owned Pizzas<Pepper>.NewYork) -> @out HotDogs.American) -> HotDogs.American // CHECK-LABEL: // nested_generics.(calls () -> ()).(closure #1) // CHECK-LABEL: sil private @_T015nested_generics5callsyyFAA7HotDogsC8AmericanVAA6PizzasV7NewYorkCyAA6PepperV_GcfU_ : $@convention(thin) (@owned Pizzas<Pepper>.NewYork) -> HotDogs.American func calls() { let firstCourse = Pizzas<Pepper>.NewYork() let secondCourse = HotDogs.American() var dinner = Lunch<Pizzas<Pepper>.NewYork>.Dinner<HotDogs.American>( firstCourse: firstCourse, secondCourse: secondCourse, leftovers: firstCourse, transformation: { _ in HotDogs.American() }) let topping = Deli<Pepper>.Pepperoni() let condiment1 = Deli<Pepper>.Mustard.Dijon let condiment2 = Deli<Pepper>.Mustard.DeliStyle(Pepper()) eatDinnerGeneric(d: &dinner, t: topping, u: condiment1) eatDinnerConcrete(d: &dinner, t: topping, u: condiment2) } protocol ProtocolWithGenericRequirement { associatedtype T associatedtype U func method<V>(t: T, u: U, v: V) -> (T, U, V) } class OuterRing<T> { class InnerRing<U> : ProtocolWithGenericRequirement { func method<V>(t: T, u: U, v: V) -> (T, U, V) { return (t, u, v) } } } class SubclassOfInner<T, U> : OuterRing<T>.InnerRing<U> { override func method<V>(t: T, u: U, v: V) -> (T, U, V) { return super.method(t: t, u: u, v: v) } } // CHECK-LABEL: // reabstraction thunk helper from @callee_owned (@owned nested_generics.Pizzas<nested_generics.Pepper>.NewYork) -> (@unowned nested_generics.HotDogs.American) to @callee_owned (@owned nested_generics.Pizzas<nested_generics.Pepper>.NewYork) -> (@out nested_generics.HotDogs.American) // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T015nested_generics6PizzasV7NewYorkCyAA6PepperV_GAA7HotDogsC8AmericanVIxxd_AhLIxxr_TR : $@convention(thin) (@owned Pizzas<Pepper>.NewYork, @owned @callee_owned (@owned Pizzas<Pepper>.NewYork) -> HotDogs.American) -> @out HotDogs.American // CHECK-LABEL: sil private [transparent] [thunk] @_T015nested_generics9OuterRingC05InnerD0Cyx_qd__GAA30ProtocolWithGenericRequirementAAr__lAaGP6method1TQz_1UQzqd__tAK1t_AM1uqd__1vtlFTW : $@convention(witness_method) <τ_0_0><τ_1_0><τ_2_0> (@in τ_0_0, @in τ_1_0, @in τ_2_0, @in_guaranteed OuterRing<τ_0_0>.InnerRing<τ_1_0>) -> (@out τ_0_0, @out τ_1_0, @out τ_2_0) { // CHECK: bb0([[T:%[0-9]+]] : $*τ_0_0, [[U:%[0-9]+]] : $*τ_1_0, [[V:%[0-9]+]] : $*τ_2_0, [[TOut:%[0-9]+]] : $*τ_0_0, [[UOut:%[0-9]+]] : $*τ_1_0, [[VOut:%[0-9]+]] : $*τ_2_0, [[SELF:%[0-9]+]] : $*OuterRing<τ_0_0>.InnerRing<τ_1_0>): // CHECK: [[SELF_COPY:%[0-9]+]] = alloc_stack $OuterRing<τ_0_0>.InnerRing<τ_1_0> // CHECK: copy_addr [[SELF]] to [initialization] [[SELF_COPY]] : $*OuterRing<τ_0_0>.InnerRing<τ_1_0> // CHECK: [[SELF_COPY_VAL:%[0-9]+]] = load [take] [[SELF_COPY]] : $*OuterRing<τ_0_0>.InnerRing<τ_1_0> // CHECK: [[BORROWED_SELF_COPY_VAL:%.*]] = begin_borrow [[SELF_COPY_VAL]] // CHECK: [[METHOD:%[0-9]+]] = class_method [[BORROWED_SELF_COPY_VAL]] : $OuterRing<τ_0_0>.InnerRing<τ_1_0>, #OuterRing.InnerRing.method!1 : <T><U><V> (OuterRing<T>.InnerRing<U>) -> (T, U, V) -> (T, U, V), $@convention(method) <τ_0_0><τ_1_0><τ_2_0> (@in τ_0_0, @in τ_1_0, @in τ_2_0, @guaranteed OuterRing<τ_0_0>.InnerRing<τ_1_0>) -> (@out τ_0_0, @out τ_1_0, @out τ_2_0) // CHECK: apply [[METHOD]]<τ_0_0, τ_1_0, τ_2_0>([[T]], [[U]], [[V]], [[TOut]], [[UOut]], [[VOut]], [[BORROWED_SELF_COPY_VAL]]) : $@convention(method) <τ_0_0><τ_1_0><τ_2_0> (@in τ_0_0, @in τ_1_0, @in τ_2_0, @guaranteed OuterRing<τ_0_0>.InnerRing<τ_1_0>) -> (@out τ_0_0, @out τ_1_0, @out τ_2_0) // CHECK: [[RESULT:%[0-9]+]] = tuple () // CHECK: end_borrow [[BORROWED_SELF_COPY_VAL]] from [[SELF_COPY_VAL]] // CHECK: destroy_value [[SELF_COPY_VAL]] : $OuterRing<τ_0_0>.InnerRing<τ_1_0> // CHECK: dealloc_stack [[SELF_COPY]] : $*OuterRing<τ_0_0>.InnerRing<τ_1_0> // CHECK: return [[RESULT]] : $() // CHECK: sil_witness_table hidden <Spices> Deli<Spices>.Pepperoni: CuredMeat module nested_generics { // CHECK: } // CHECK: sil_witness_table hidden <Spices> Deli<Spices>.Sausage: CuredMeat module nested_generics { // CHECK: } // CHECK: sil_witness_table hidden <Spices> Deli<Spices>: CuredMeat module nested_generics { // CHECK: } // CHECK: sil_witness_table hidden <Spices> Pizzas<Spices>.NewYork: Pizza module nested_generics { // CHECK: associated_type Topping: Deli<Spices>.Pepperoni // CHECK: } // CHECK: sil_witness_table hidden <Spices> Pizzas<Spices>.DeepDish: Pizza module nested_generics { // CHECK: associated_type Topping: Deli<Spices>.Sausage // CHECK: } // CHECK: sil_witness_table hidden HotDogs.Bratwurst: HotDog module nested_generics { // CHECK: associated_type Condiment: Deli<Pepper>.Mustard // CHECK: } // CHECK: sil_witness_table hidden HotDogs.American: HotDog module nested_generics { // CHECK: associated_type Condiment: Deli<Pepper>.Mustard // CHECK: }
apache-2.0
bec743a46f62178648ce230e97831087
53.584906
403
0.702247
3.226634
false
false
false
false
menlatin/jalapeno
digeocache/mobile/iOS/diGeo/diGeo/DrawerController/AnimatedMenuButton.swift
3
5543
// Copyright (c) 2014 evolved.io (http://evolved.io) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import QuartzCore import UIKit public class AnimatedMenuButton : UIButton { let top: CAShapeLayer = CAShapeLayer() let middle: CAShapeLayer = CAShapeLayer() let bottom: CAShapeLayer = CAShapeLayer() // MARK: - Constants let animationDuration: CFTimeInterval = 8.0 let shortStroke: CGPath = { let path = CGPathCreateMutable() CGPathMoveToPoint(path, nil, 2, 2) CGPathAddLineToPoint(path, nil, 30 - 2 * 2, 2) return path }() // MARK: - Initializers required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame:frame) self.top.path = shortStroke; self.middle.path = shortStroke; self.bottom.path = shortStroke; for layer in [ self.top, self.middle, self.bottom ] { layer.fillColor = nil layer.strokeColor = UIColor.grayColor().CGColor layer.lineWidth = 4 layer.miterLimit = 2 layer.lineCap = kCALineCapRound layer.masksToBounds = true let strokingPath = CGPathCreateCopyByStrokingPath(layer.path, nil, 4, kCGLineCapRound, kCGLineJoinMiter, 4) layer.bounds = CGPathGetPathBoundingBox(strokingPath) layer.actions = [ "opacity": NSNull(), "transform": NSNull() ] self.layer.addSublayer(layer) } self.top.anchorPoint = CGPoint(x: 1, y: 0.5) self.top.position = CGPoint(x: 30 - 1, y: 5) self.middle.position = CGPoint(x: 15, y: 15) self.bottom.anchorPoint = CGPoint(x: 1, y: 0.5) self.bottom.position = CGPoint(x: 30 - 1, y: 25) } // MARK: - Animations public func animateWithPercentVisible(percentVisible:CGFloat, drawerSide: DrawerSide) { if drawerSide == DrawerSide.Left { self.top.anchorPoint = CGPoint(x: 1, y: 0.5) self.top.position = CGPoint(x: 30 - 1, y: 5) self.middle.position = CGPoint(x: 15, y: 15) self.bottom.anchorPoint = CGPoint(x: 1, y: 0.5) self.bottom.position = CGPoint(x: 30 - 1, y: 25) } else if drawerSide == DrawerSide.Right { self.top.anchorPoint = CGPoint(x: 0, y: 0.5) self.top.position = CGPoint(x: 1, y: 5) self.middle.position = CGPoint(x: 15, y: 15) self.bottom.anchorPoint = CGPoint(x: 0, y: 0.5) self.bottom.position = CGPoint(x: 1, y: 25) } let middleTransform = CABasicAnimation(keyPath: "opacity") middleTransform.duration = animationDuration let topTransform = CABasicAnimation(keyPath: "transform") topTransform.timingFunction = CAMediaTimingFunction(controlPoints: 0.5, -0.8, 0.5, 1.85) topTransform.duration = animationDuration topTransform.fillMode = kCAFillModeBackwards let bottomTransform = topTransform.copy() as CABasicAnimation middleTransform.toValue = 1 - percentVisible let translation = CATransform3DMakeTranslation(-4 * percentVisible, 0, 0) let sideInverter: CGFloat = drawerSide == DrawerSide.Left ? -1 : 1 topTransform.toValue = NSValue(CATransform3D: CATransform3DRotate(translation, 1.0 * sideInverter * ((CGFloat)(45.0 * M_PI / 180.0) * percentVisible), 0, 0, 1)) bottomTransform.toValue = NSValue(CATransform3D: CATransform3DRotate(translation, (-1.0 * sideInverter * (CGFloat)(45.0 * M_PI / 180.0) * percentVisible), 0, 0, 1)) topTransform.beginTime = CACurrentMediaTime() bottomTransform.beginTime = CACurrentMediaTime() self.top.addAnimation(topTransform, forKey: topTransform.keyPath) self.middle.addAnimation(middleTransform, forKey: middleTransform.keyPath) self.bottom.addAnimation(bottomTransform, forKey: bottomTransform.keyPath) self.top.setValue(topTransform.toValue, forKey: topTransform.keyPath) self.middle.setValue(middleTransform.toValue, forKey: middleTransform.keyPath) self.bottom.setValue(bottomTransform.toValue, forKey: bottomTransform.keyPath) } }
mit
1959a3918d8c2bb57bffe91fc54fb8aa
41
172
0.639906
4.466559
false
false
false
false
kperryua/swift
test/Parse/operator_decl.swift
3
3318
// RUN: %target-parse-verify-swift prefix operator +++ {} // expected-warning {{operator should no longer be declared with body}} {{20-23=}} postfix operator +++ {} // expected-warning {{operator should no longer be declared with body}} {{21-24=}} infix operator +++ {} // expected-warning {{operator should no longer be declared with body}} {{19-22=}} infix operator +++* { // expected-warning {{operator should no longer be declared with body; use a precedence group instead}} {{none}} associativity right } infix operator +++*+ : A { } // expected-warning {{operator should no longer be declared with body}} {{25-29=}} prefix operator +++** : A { } // expected-error@-1 {{only infix operators may declare a precedence}} {{23-27=}} // expected-warning@-2 {{operator should no longer be declared with body}} {{26-30=}} prefix operator ++*++ : A // expected-error@-1 {{only infix operators may declare a precedence}} {{23-26=}} postfix operator ++*+* : A { } // expected-error@-1 {{only infix operators may declare a precedence}} {{24-28=}} // expected-warning@-2 {{operator should no longer be declared with body}} {{27-31=}} postfix operator ++**+ : A // expected-error@-1 {{only infix operators may declare a precedence}} {{24-27=}} operator ++*** : A // expected-error@-1 {{operator must be declared as 'prefix', 'postfix', or 'infix'}} operator +*+++ { } // expected-error@-1 {{operator must be declared as 'prefix', 'postfix', or 'infix'}} // expected-warning@-2 {{operator should no longer be declared with body}} {{15-19=}} operator +*++* : A { } // expected-error@-1 {{operator must be declared as 'prefix', 'postfix', or 'infix'}} // expected-warning@-2 {{operator should no longer be declared with body}} {{19-23=}} prefix operator // expected-error {{expected operator name in operator declaration}} ; prefix operator %%+ prefix operator ?? postfix operator ?? // expected-error {{expected operator name in operator declaration}} prefix operator !! postfix operator !! // expected-error {{expected operator name in operator declaration}} infix operator +++= infix operator *** : A infix operator --- : ; precedencegroup { // expected-error {{expected identifier after 'precedencegroup'}} associativity: right } precedencegroup A { associativity right // expected-error {{expected colon after attribute name in precedence group}} } precedencegroup B { precedence 123 // expected-error {{'precedence' is not a valid precedence group attribute}} } precedencegroup C { associativity: sinister // expected-error {{expected 'none', 'left', or 'right' after 'associativity'}} } precedencegroup D { assignment: no // expected-error {{expected 'true' or 'false' after 'assignment'}} } precedencegroup E { higherThan: } // expected-error {{expected name of related precedence group after 'higherThan'}} precedencegroup F { higherThan: A, B, C } precedencegroup BangBangBang { associativity: none associativity: left // expected-error{{'associativity' attribute for precedence group declared multiple times}} } precedencegroup CaretCaretCaret { assignment: true assignment: false // expected-error{{'assignment' attribute for precedence group declared multiple times}} } class Foo { infix operator ||| // expected-error{{'operator' may only be declared at file scope}} }
apache-2.0
a7bafe54b8b4129a49e9f3725f2cccde
37.137931
134
0.70434
4.21601
false
false
false
false
Acidburn0zzz/firefox-ios
Client/Frontend/Home/ASLibraryCell.swift
1
2644
/* 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 Shared import SnapKit class ASLibraryCell: UICollectionViewCell, Themeable { var mainView = UIStackView() struct LibraryPanel { let title: String let image: UIImage? let color: UIColor } var libraryButtons: [LibraryShortcutView] = [] let bookmarks = LibraryPanel(title: Strings.AppMenuBookmarksTitleString, image: UIImage.templateImageNamed("menu-Bookmark"), color: UIColor.Photon.Blue50) let history = LibraryPanel(title: Strings.AppMenuHistoryTitleString, image: UIImage.templateImageNamed("menu-panel-History"), color: UIColor.Photon.Orange50) let readingList = LibraryPanel(title: Strings.AppMenuReadingListTitleString, image: UIImage.templateImageNamed("menu-panel-ReadingList"), color: UIColor.Photon.Teal60) let downloads = LibraryPanel(title: Strings.AppMenuDownloadsTitleString, image: UIImage.templateImageNamed("menu-panel-Downloads"), color: UIColor.Photon.Magenta60) let syncedTabs = LibraryPanel(title: Strings.AppMenuSyncedTabsTitleString, image: UIImage.templateImageNamed("menu-sync"), color: UIColor.Photon.Purple70) override init(frame: CGRect) { super.init(frame: frame) mainView.distribution = .fillEqually mainView.spacing = 10 addSubview(mainView) mainView.snp.makeConstraints { make in make.edges.equalTo(self) } [bookmarks, readingList, downloads, syncedTabs].forEach { item in let view = LibraryShortcutView() view.button.setImage(item.image, for: .normal) view.title.text = item.title let words = view.title.text?.components(separatedBy: NSCharacterSet.whitespacesAndNewlines).count view.title.numberOfLines = words == 1 ? 1 :2 view.button.backgroundColor = item.color view.button.setTitleColor(UIColor.theme.homePanel.topSiteDomain, for: .normal) view.accessibilityLabel = item.title mainView.addArrangedSubview(view) libraryButtons.append(view) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func applyTheme() { libraryButtons.forEach { button in button.title.textColor = UIColor.theme.homePanel.activityStreamCellTitle } } override func prepareForReuse() { super.prepareForReuse() applyTheme() } }
mpl-2.0
dea682ca0852425bad284cc1d6d6af15
40.968254
171
0.694024
4.721429
false
false
false
false
webventil/OpenSport
OpenSport/OpenSport/GPXManager.swift
1
12612
// // GPXManager.swift // OpenSport // // Created by Arne Tempelhof on 31/07/14. // Copyright (c) 2014 Arne Tempelhof. All rights reserved. // import Foundation import CoreLocation public class GPXManager: NSObject, NSXMLParserDelegate { let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate var parser = NSXMLParser() var element = "" var activity: SportActivity? var trackSegment: TrackSegment? var latitude: Double = 0.0 var longitude: Double = 0.0 var altitude: Double = 0.0 var speed: Double = 0.0 var activityType = "" let kGPXManagerImportFinishedNotification = "kGPXManagerImportFinishedNotification" internal class func exportGPX(sportActivity: SportActivity?) -> (String, NSURL) { if let trackpoints = sportActivity?.sortedTrackpoints { var dateFromatter: NSDateFormatter = NSDateFormatter() dateFromatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'" var fileNameDateFormatter: NSDateFormatter = NSDateFormatter() fileNameDateFormatter.dateFormat = "yyyy_MM_dd-HH_mm_ss" var filename = "OpenSport_Activity_" + fileNameDateFormatter.stringFromDate(sportActivity!.startTime) + ".gpx" var firstDate = dateFromatter.stringFromDate(sportActivity!.startTime) var type = "" if let activityType = sportActivity?.activityType { type = "<type>\(activityType)</type>" } var gpxString: String = "" gpxString += "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>\n" gpxString += "<gpx version=\"1.1\" creator=\"OpenSport\">\n" gpxString += "<trk>\n" gpxString += "<name><![CDATA[Activity]]></name>\n" gpxString += "<time>\(firstDate)</time>\n" for segment in sportActivity!.trackSegments.array { gpxString += "<trkseg>\n" for trackpoint in (segment as TrackSegment).trackpoints.array { var iso8601Date = dateFromatter.stringFromDate((trackpoint as Trackpoint).timestamp) gpxString += "<trkpt lat=\"\((trackpoint as Trackpoint).latitude.doubleValue)\" lon=\"\((trackpoint as Trackpoint).longitude.doubleValue)\"><ele>\((trackpoint as Trackpoint).altitude.doubleValue)</ele><speed>\((trackpoint as Trackpoint).speed.doubleValue)</speed>\(type)<time>\(iso8601Date)</time></trkpt>\n" } gpxString += "</trkseg>\n" } gpxString += "</trk>\n" gpxString += "</gpx>\n" let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String var filePath = documentsPath.stringByAppendingPathComponent(filename) var error: NSError? gpxString.writeToFile(filePath, atomically: true, encoding: NSUTF8StringEncoding, error: &error) return (filename, NSURL.fileURLWithPath(filePath)!) } return ("", NSURL()) } public func importGpx(xmlUrl: NSURL) { parser = NSXMLParser(contentsOfURL: xmlUrl)! parser.shouldProcessNamespaces = false parser.shouldReportNamespacePrefixes = false parser.shouldResolveExternalEntities = false parser.delegate = self parser.parse() } public func parserDidStartDocument(parser: NSXMLParser!) { activity = DatabaseManager.shared().createActivity() } public func parserDidEndDocument(parser: NSXMLParser!) { improveData(activity!) activity = GPXManager.finalizeActivity(activity!) HealthManager.shared().saveActivityToHealthKit(activity!) if let moc = activity?.managedObjectContext { moc.save(nil) NSNotificationCenter.defaultCenter().postNotificationName(kGPXManagerImportFinishedNotification, object: nil) } } func improveData(sportActivity: SportActivity) { // set activity Type sportActivity.activityType = activityType let trackpoints = sportActivity.sortedTrackpoints if trackpoints.count > 0 { var latitude = 0.0 var longitude = 0.0 var totalDistance = 0.0 for var i = 0; i < trackpoints.count; i++ { if i == 0 { var firstTrackpoint: Trackpoint = trackpoints[i] firstTrackpoint.currentDistance = 0 } else { var lastLocation: Trackpoint = trackpoints[i - 1] let trackpoint: Trackpoint = trackpoints[i] var oldCoordinate = CLLocation(latitude: Double(lastLocation.latitude), longitude: Double(lastLocation.longitude)) var newCoordinate = CLLocation(latitude: trackpoint.latitude.doubleValue, longitude: trackpoint.longitude.doubleValue) var oldDate: NSDate = lastLocation.timestamp var newDate: NSDate = trackpoint.timestamp var time = newDate.timeIntervalSinceDate(oldDate) var speed: Double = newCoordinate.distanceFromLocation(oldCoordinate) / (time * 1.0) totalDistance += newCoordinate.distanceFromLocation(oldCoordinate) if trackpoint.speed == 0.0 { trackpoint.speed == speed } trackpoint.currentDistance = totalDistance } } if let firstPoint: AnyObject = trackpoints.first { sportActivity.startTime = (firstPoint as Trackpoint).timestamp trackSegment?.startTime = sportActivity.startTime } if let lastPoint: AnyObject = trackpoints.last { sportActivity.endTime = (lastPoint as Trackpoint).timestamp sportActivity.distance = (lastPoint as Trackpoint).currentDistance trackSegment?.endTime = sportActivity.endTime trackSegment?.distance = sportActivity.distance } if (sportActivity.duration == NSNumber(int: 0)) { sportActivity.duration = sportActivity.endTime.timeIntervalSinceDate(sportActivity.startTime) trackSegment?.duration = sportActivity.duration } } } class func finalizeActivity(sportActivity: SportActivity) -> SportActivity { for segment in sportActivity.trackSegments.array { improveSegment(segment as TrackSegment) } // update information to sport activity from first if let firstSegment: TrackSegment = sportActivity.trackSegments.firstObject as? TrackSegment { sportActivity.startTime = (firstSegment.trackpoints.firstObject as Trackpoint).timestamp } if sportActivity.trackSegments.count >= 1 { if let lastSegment: TrackSegment = sportActivity.trackSegments.lastObject as? TrackSegment { sportActivity.endTime = (lastSegment.trackpoints.lastObject as Trackpoint).timestamp // sum durations from track segments var duration = 0 for segment in sportActivity.trackSegments.array { duration += Int((segment as TrackSegment).duration) } sportActivity.duration = duration sportActivity.distance = (lastSegment.trackpoints.lastObject as Trackpoint).currentDistance var sumSpeed = 0.0 for segment in sportActivity.trackSegments.array { sumSpeed = (segment as TrackSegment).avgSpeed.doubleValue } sportActivity.avgSpeed = sumSpeed / Double(sportActivity.trackSegments.count) } } // calculate distance markes for miles var distance = 1609; for var i: Int = distance; i < sportActivity.distance.integerValue; { var distanceMarkerTrackpoint = DatabaseManager.shared().getClosestTrackpoint(sportActivity, distance: i) distanceMarkerTrackpoint.isMileMark = true i += distance } // calculate distance markes for km distance = 1000; for var i: Int = distance; i < sportActivity.distance.integerValue; { var distanceMarkerTrackpoint = DatabaseManager.shared().getClosestTrackpoint(sportActivity, distance: i) distanceMarkerTrackpoint.isKilometerMark = true i += distance } return sportActivity } class func improveSegment(segment: TrackSegment) { if let firstPoint: Trackpoint = segment.trackpoints.firstObject as? Trackpoint { // set start time of first segment and from sport activity with first recorded point segment.startTime = firstPoint.timestamp } if let lastPoint: Trackpoint = segment.trackpoints.lastObject as? Trackpoint { // set end time of first segment with the last recorded point segment.endTime = lastPoint.timestamp segment.duration = segment.endTime.timeIntervalSinceDate(segment.startTime) segment.distance = lastPoint.currentDistance } if let trackpoints = segment.trackpoints.array as? [Trackpoint] { var averagePace = 0.0 var sumSpeed = 0.0 for trackpoint in trackpoints { sumSpeed += trackpoint.speed.doubleValue } var averageSpeed = sumSpeed / Double(trackpoints.count) segment.avgSpeed = averageSpeed } } public func parser(_parser: NSXMLParser!, parseErrorOccurred parseError: NSError!) { } public func parser(parser: NSXMLParser!, didStartElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!, attributes attributeDict: [NSObject:AnyObject]!) { if (elementName as NSString).isEqualToString("trkseg") { // new tracksegment trackSegment = nil element = "" } else if (elementName as NSString).isEqualToString("trkpt") { var lat = attributeDict["lat"] as NSString var lon = attributeDict["lon"] as NSString latitude = lat.doubleValue longitude = lon.doubleValue } else if (elementName as NSString).isEqualToString("ele") { element = elementName } else if (elementName as NSString).isEqualToString("speed") { element = elementName } else if (elementName as NSString).isEqualToString("time") { element = elementName } else if (elementName as NSString).isEqualToString("type") { element = elementName } else { element = "" } } public func parser(parser: NSXMLParser!, didEndElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!) { element = "" } public func parser(parser: NSXMLParser!, foundCharacters string: String!) { if (element == "ele") { var alt = string as NSString altitude = alt.doubleValue } else if (element == "speed") { var sp = string as NSString speed = sp.doubleValue } else if (element == "time") { var time = string as NSString var dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'" var date: NSDate = dateFormatter.dateFromString(time)! var trackpoint: Trackpoint = DatabaseManager.shared().createTrackpoint() trackpoint.latitude = latitude trackpoint.longitude = longitude trackpoint.altitude = altitude trackpoint.speed = speed trackpoint.timestamp = date var error: NSError? if (latitude == 0 && longitude == 0) { return } if let segment = trackSegment? { // no need to do anything since tracksegment is already } else { trackSegment = DatabaseManager.shared().createSegment() var trackSegments = activity!.mutableOrderedSetValueForKey("trackSegments") trackSegments.addObject(trackSegment!) } var trackpoints = trackSegment!.mutableOrderedSetValueForKey("trackpoints") trackpoints.addObject(trackpoint) } else if (element == "type") { activityType = string } } }
mit
1cde97c3ccd419b27502110c8173bb63
38.660377
328
0.616318
5.25719
false
false
false
false
nathawes/swift
test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1ancestor-1distinct_use-1st_ancestor_generic-1argument-1st_argument_subclass_argument.swift
5
12511
// RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment --check-prefix=CHECK --check-prefix=CHECK-%target-vendor // REQUIRES: VENDOR=apple || OS=linux-gnu // UNSUPPORTED: CPU=i386 && OS=ios // UNSUPPORTED: CPU=armv7 && OS=ios // UNSUPPORTED: CPU=armv7s && OS=ios // CHECK: @"$s4main9Ancestor1[[UNIQUE_ID_1:[A-Za-z_0-9]+]]CySiGMf" = linkonce_odr hidden // CHECK-apple: global // CHECK-unknown: constant // : <{ // : void (%T4main9Ancestor1[[UNIQUE_ID_1]]C*)*, // : i8**, // : i64, // : %objc_class*, // : %swift.opaque*, // : %swift.opaque*, // : i64, // : i32, // : i32, // : i32, // : i16, // : i16, // : i32, // : i32, // : %swift.type_descriptor*, // : i8*, // : %swift.type*, // : i64, // : %T4main9Ancestor1[[UNIQUE_ID_1]]C* (%swift.opaque*, %swift.type*)* // : }> <{ // : void (%T4main9Ancestor1[[UNIQUE_ID_1]]C*)* // : @"$s4main9Ancestor1[[UNIQUE_ID_1]]CfD", // : i8** @"$sBoWV", // : i64 ptrtoint ( // : %objc_class* @"$s4main9Ancestor1[[UNIQUE_ID_1]]CySiGMM" to i64 // : ), // : %objc_class* @"OBJC_CLASS_$__TtCs12_SwiftObject", // : %swift.opaque* @_objc_empty_cache, // : %swift.opaque* null, // : i64 add ( // : i64 ptrtoint ( // : { // : i32, // : i32, // : i32, // : i32, // : i8*, // : i8*, // : i8*, // : i8*, // : { // : i32, // : i32, // : [1 x { i64*, i8*, i8*, i32, i32 }] // : }*, // : i8*, // : i8* // : }* @_DATA__TtC4mainP33_496329636AC05466637A72F247DC6ABC9Ancestor1 to i64 // : ), // : i64 2 // : ), // : i32 26, // : i32 0, // : i32 16, // : i16 7, // : i16 0, // : i32 120, // : i32 16, // : %swift.type_descriptor* bitcast ( // : <{ // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i16, // : i16, // : i16, // : i16, // : i8, // : i8, // : i8, // : i8, // : i32, // : i32, // : %swift.method_descriptor // : }>* @"$s4main9Ancestor1[[UNIQUE_ID_1]]CMn" // : to %swift.type_descriptor* // : ), // : i8* null, // : %swift.type* @"$sSiN", // : i64 16, // : %T4main9Ancestor1[[UNIQUE_ID_1]]C* (%swift.opaque*, %swift.type*)* // : @"$s4main9Ancestor1[[UNIQUE_ID_1]]C5firstADyxGx_tcfC" // : }>, align [[ALIGNMENT]] // CHECK: @"$s4main5Value[[UNIQUE_ID_1]]CySiGMf" = linkonce_odr hidden // CHECK-apple-SAME: global // CHECK-unknown-SAME: constant // CHECK-SAME: <{ // CHECK-SAME: void (%T4main5Value[[UNIQUE_ID_1]]C*)*, // CHECK-SAME: i8**, // : [[INT]], // CHECK-SAME: %swift.type*, // CHECK-apple-SAME: %swift.opaque*, // CHECK-apple-SAME: %swift.opaque*, // CHECK-apple-SAME: [[INT]], // CHECK-SAME: i32, // CHECK-SAME: i32, // CHECK-SAME: i32, // CHECK-SAME: i16, // CHECK-SAME: i16, // CHECK-SAME: i32, // CHECK-SAME: i32, // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: void (%T4main5Value[[UNIQUE_ID_1]]C*)*, // CHECK-SAME: %swift.type*, // CHECK-SAME: [[INT]], // CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]C* (%swift.opaque*, %swift.type*)*, // CHECK-SAME: %swift.type*, // CHECK-SAME: [[INT]] // CHECK-SAME: }> <{ // CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]CfD // CHECK-SAME: $sBoWV // CHECK-apple-SAME: $s4main5Value[[UNIQUE_ID_1]]CySiGMM // CHECK-unknown-SAME: [[INT]] 0, // : %swift.type* getelementptr inbounds ( // : %swift.full_heapmetadata, // : %swift.full_heapmetadata* bitcast ( // : <{ // : void (%T4main9Ancestor1[[UNIQUE_ID_1]]C*)*, // : i8**, // : [[INT]], // : %objc_class*, // : %swift.type*, // : %swift.opaque*, // : %swift.opaque*, // : [[INT]], // : i32, // : i32, // : i32, // : i16, // : i16, // : i32, // : i32, // : %swift.type_descriptor*, // : i8*, // : %swift.type*, // : [[INT]], // : %T4main9Ancestor1[[UNIQUE_ID_1]]C* (%swift.opaque*, %swift.type*)* // : }>* @"$s4main9Ancestor1[[UNIQUE_ID_1]]CySiGMf" // : to %swift.full_heapmetadata* // : ), // : i32 0, // : i32 2 // : ), // CHECK-apple-SAME: %swift.opaque* @_objc_empty_cache, // CHECK-apple-SAME: %swift.opaque* null, // CHECK-apple-SAME: [[INT]] add ( // CHECK-apple-SAME: [[INT]] ptrtoint ( // CHECK-apple-SAME: { // CHECK-apple-SAME: i32, // CHECK-apple-SAME: i32, // CHECK-apple-SAME: i32, // : i32, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: { // CHECK-apple-SAME: i32, // CHECK-apple-SAME: i32, // CHECK-apple-SAME: [1 x { [[INT]]*, i8*, i8*, i32, i32 }] // CHECK-apple-SAME: }*, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: i8* // CHECK-apple-SAME: }* @_DATA__TtC4mainP33_496329636AC05466637A72F247DC6ABC5Value to [[INT]] // CHECK-apple-SAME: ), // CHECK-apple-SAME: [[INT]] 2 // CHECK-apple-SAME: ), // CHECK-SAME: i32 26, // CHECK-SAME: i32 0, // CHECK-SAME: i32 {{(32|16)}}, // CHECK-SAME: i16 {{(7|3)}}, // CHECK-SAME: i16 0, // CHECK-apple-SAME: i32 {{(136|80)}}, // CHECK-unknown-SAME: i32 112, // CHECK-SAME: i32 {{(16|8)}}, // : %swift.type_descriptor* bitcast ( // : <{ // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i16, // : i16, // : i16, // : i16, // : i8, // : i8, // : i8, // : i8, // : i32, // : %swift.method_override_descriptor // : }>* @"$s4main5Value[[UNIQUE_ID_1]]CMn" // : to %swift.type_descriptor* // : ), // CHECK-SAME: void (%T4main5Value[[UNIQUE_ID_1]]C*)* // CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]CfE // CHECK-SAME: %swift.type* @"$sSiN", // CHECK-SAME: [[INT]] {{(16|8)}}, // CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]C* (%swift.opaque*, %swift.type*)* // CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]C5firstADyxGx_tcfC // CHECK-SAME: %swift.type* @"$sSiN", // CHECK-SAME: [[INT]] {{(24|12)}} // CHECK-SAME: }>, align [[ALIGNMENT]] fileprivate class Ancestor1<First> { let first_Ancestor1: First init(first: First) { self.first_Ancestor1 = first } } fileprivate class Value<First> : Ancestor1<First> { let first_Value: First override init(first: First) { self.first_Value = first super.init(first: first) } } @inline(never) func consume<T>(_ t: T) { withExtendedLifetime(t) { t in } } func doit() { consume( Value(first: 13) ) } doit() // CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]CySiGMb" // CHECK-NEXT: entry: // CHECK: [[SUPER_CLASS_METADATA:%[0-9]+]] = call swiftcc %swift.metadata_response @"$s4main9Ancestor1[[UNIQUE_ID_1]]CySiGMb"([[INT]] 0) // CHECK-apple: [[THIS_CLASS_METADATA:%[0-9]+]] = call %objc_class* @objc_opt_self( // CHECK-apple: %objc_class* bitcast ( // CHECK-unknown: ret // : %objc_class* bitcast ( // : %swift.type* getelementptr inbounds ( // : %swift.full_heapmetadata, // : %swift.full_heapmetadata* bitcast ( // : <{ // : void (%T4main5Value[[UNIQUE_ID_1]]C*)*, // : i8**, // : i64, // : %swift.type*, // : %swift.opaque*, // : %swift.opaque*, // : i64, // : i32, // : i32, // : i32, // : i16, // : i16, // : i32, // : i32, // : %swift.type_descriptor*, // : void (%T4main5Value[[UNIQUE_ID_1]]C*)*, // : %swift.type*, // : i64, // : %T4main5Value[[UNIQUE_ID_1]]C* (%swift.opaque*, %swift.type*)*, // : %swift.type*, // : i64 // : }>* // CHECK-SAME: @"$s4main5Value[[UNIQUE_ID_1]]CySiGMf" // : to %swift.full_heapmetadata* // : ), // : i32 0, // : i32 2 // : ) to %objc_class* // : ) // : ) // CHECK-apple: [[THIS_TYPE_METADATA:%[0-9]+]] = bitcast %objc_class* [[THIS_CLASS_METADATA]] to %swift.type* // CHECK-apple: [[RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response undef, %swift.type* [[THIS_TYPE_METADATA]], 0 // CHECK-apple: [[COMPLETE_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response [[RESPONSE]], [[INT]] 0, 1 // CHECK-apple: ret %swift.metadata_response [[COMPLETE_RESPONSE]] // CHECK: } // CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main9Ancestor1[[UNIQUE_ID_1]]CySiGMb"
apache-2.0
f5c730f4e8f0ca23fd856dac4785402a
38.843949
214
0.356726
3.236999
false
false
false
false
actframework/FrameworkBenchmarks
frameworks/Swift/kitura/Sources/TechEmpowerKueryMustache/main.swift
2
5105
/* * Copyright IBM Corporation 2018 * * 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 Kitura import LoggerAPI import HeliumLogger import SwiftKuery import SwiftKueryPostgreSQL import KituraMustache Log.logger = HeliumLogger(.info) let router = Router() router.add(templateEngine: MustacheTemplateEngine()) // // TechEmpower test 6: plaintext // router.get("/plaintext") { request, response, next in response.headers["Server"] = "Kitura" response.headers["Content-Type"] = "text/plain" try response.status(.OK).send("Hello, world!").end() } // // TechEmpower test 1: JSON serialization // router.get("/json") { request, response, next in response.headers["Server"] = "Kitura" let result = ["message":"Hello, World!"] try response.status(.OK).send(json: result).end() } // // TechEmpower test 2: Single database query (raw, no ORM) // router.get("/db") { request, response, next in response.headers["Server"] = "Kitura" let result = getRandomRow() guard let dict = result.0 else { guard let err = result.1 else { Log.error("Unknown Error") try response.status(.badRequest).send("Unknown error").end() return } Log.error("\(err)") try response.status(.badRequest).send("Error: \(err)").end() return } try response.status(.OK).send(json: dict).end() } // // TechEmpower test 3: Multiple database queries (raw, no ORM) // Get param provides number of queries: /queries?queries=N // router.get("/queries") { request, response, next in response.headers["Server"] = "Kitura" let queriesParam = request.queryParameters["queries"] ?? "1" let numQueries = max(1, min(Int(queriesParam) ?? 1, 500)) // Snap to range of 1-500 as per test spec var results: [[String:Int]] = [] for _ in 1...numQueries { let result = getRandomRow() guard let dict = result.0 else { guard let err = result.1 else { Log.error("Unknown Error") try response.status(.badRequest).send("Unknown error").end() return } Log.error("\(err)") try response.status(.badRequest).send("Error: \(err)").end() return } results.append(dict) } // Return JSON representation of array of results try response.status(.OK).send(json: results).end() } // // TechEmpower test 4: fortunes (raw, no ORM) // router.get("/fortunes") { request, response, next in response.headers["Server"] = "Kitura" response.headers["Content-Type"] = "text/html; charset=UTF-8" let result = getFortunes() guard var fortunes = result.0 else { guard let err = result.1 else { Log.error("Unknown Error") try response.status(.badRequest).send("Unknown error").end() return } Log.error("\(err)") try response.status(.badRequest).send("Error: \(err)").end() return } fortunes.append(Fortune(id: 0, message: "Additional fortune added at request time.")) do { try response.render("fortunes.mustache", context: ["fortunes": fortunes.sorted()]).end() } catch { print("Error: \(error)") } } // // TechEmpower test 5: updates (raw, no ORM) // router.get("/updates") { request, response, next in response.headers["Server"] = "Kitura" let queriesParam = request.queryParameters["queries"] ?? "1" let numQueries = max(1, min(Int(queriesParam) ?? 1, 500)) // Snap to range of 1-500 as per test spec var results: [[String:Int]] = [] for _ in 1...numQueries { let result = getRandomRow() guard let dict = result.0 else { guard let err = result.1 else { Log.error("Unknown Error") try response.status(.badRequest).send("Unknown error").end() return } Log.error("\(err)") try response.status(.badRequest).send("Error: \(err)").end() return } do { var error: AppError? try error = updateRow(id: dict["id"]!) if let appError = error { throw appError } } catch let err as AppError { try response.status(.badRequest).send("Error: \(err)").end() return } results.append(dict) } // Return JSON representation of array of results try response.status(.OK).send(json: results).end() } Kitura.addHTTPServer(onPort: 8080, with: router) Kitura.run()
bsd-3-clause
b03d355fe32aaec1788ed69560b8dedd
30.319018
109
0.608031
3.985168
false
false
false
false
yoichitgy/swipe
core/SwipeViewController.swift
1
23222
// // SwipeViewController.swift // Swipe // // Created by satoshi on 6/3/15. // Copyright (c) 2015 Satoshi Nakajima. All rights reserved. // #if os(OSX) import Cocoa public typealias UIViewController = NSViewController public typealias UIScrollView = NSScrollView #else import UIKit #endif import AVFoundation private func MyLog(_ text:String, level:Int = 0) { let s_verbosLevel = 0 if level <= s_verbosLevel { NSLog(text) } } class SwipeViewController: UIViewController, UIScrollViewDelegate, SwipeDocumentViewer, SwipeBookDelegate { var book:SwipeBook! weak var delegate:SwipeDocumentViewerDelegate? private var fAdvancing = true private let notificationManager = SNNotificationManager() #if os(tvOS) // scrollingTarget has an index to the target page during the scrolling animation // as the result of swiping private var scrollingTarget:Int? private var scrollingCount = 0 // number of pending animations #endif lazy var scrollView:UIScrollView = { let scrollView = UIScrollView() #if os(iOS) scrollView.isPagingEnabled = true // paging is not available for tvOS #endif scrollView.delegate = self return scrollView }() // // Computed Properties (private) // private var scrollPos:CGFloat { return pagePosition(self.scrollView.contentOffset) } private var scrollIndex:Int { return Int(self.scrollPos + 0.5) } private func pagePosition(_ offset:CGPoint) -> CGFloat { let size = self.scrollView.frame.size return self.book.horizontal ? offset.x / size.width : offset.y / size.height } deinit { #if os(tvOS) MyLog("SWView deinit c=\(scrollingCount)", level:1) #endif // Even though book is unwrapped, there is a rare case that book is nil // (during the construction). if self.book != nil && self.book.pages.count > 0 { self.book.currentPage.willLeave(false) self.book.currentPage.didLeave(false) // PARANOIA for i in -2...2 { removeViewAtIndex(self.book.pageIndex - i) } } } // <SwipeDocumentViewerDelegate> method func tapped() { self.delegate?.tapped() } // <SwipeDocumentViewer> method func documentTitle() -> String? { return self.book.title } // <SwipeDocumentViewer> method func loadDocument(_ document:[String:Any], size:CGSize, url:URL?, state:[String:Any]?, callback:@escaping (Float, NSError?)->(Void)) throws { self.book = SwipeBook(bookInfo: document, url: url, delegate: self) if let languages = self.book.languages(), let langId = SwipeParser.preferredLangId(in: languages) { self.book.langId = langId } if book.viewstate { if let pageIndex = state?["page"] as? Int, pageIndex < self.book.pages.count { self.book.pageIndex = pageIndex } if let langId = state?["langId"] as? String { self.book.langId = langId } } var urlsAll = [URL:String]() for page in self.book.pages { let urls = page.resourceURLs for (url, prefix) in urls { urlsAll[url as URL] = prefix } } //NSLog("SVC urlsAll = \(urlsAll)") let prefetcher = SwipePrefetcher(urls: urlsAll) prefetcher.start { (completed:Bool, _:[URL], _:[NSError]) -> Void in callback(prefetcher.progress, nil) } } // <SwipeDocumentViewer> method func setDelegate(_ delegate:SwipeDocumentViewerDelegate) { self.delegate = delegate } // <SwipeDocumentViewer> method func hideUI() -> Bool { return true } // <SwipeDocumentViewer> method func landscape() -> Bool { return self.book.landscape } // <SwipeDocumentViewer> method func becomeZombie() { notificationManager.clear() } // <SwipeDocumentViewer> method func saveState() -> [String:Any]? { return ["page":self.book.pageIndex, "langId":self.book.langId] } // <SwipeDocumentViewer> method func languages() -> [[String:Any]]? { return self.book.languages() } // <SwipeDocumentViewer> method func reloadWithLanguageId(_ langId:String) { self.book.langId = langId self.adjustIndex(self.book.pageIndex, fForced: true) } override func viewDidLoad() { super.viewDidLoad() self.view.addSubview(self.scrollView) self.view.layer.backgroundColor = book.backgroundColor #if os(tvOS) // Since the paging is not enabled on tvOS, we handle PanGesture directly at this view instead. // scrollView.panGestureRecognizer.allowedTouchTypes = [UITouchType.Indirect.rawValue, UITouchType.Direct.rawValue] //scrollView.panGestureRecognizer.enabled = false let pan = UIPanGestureRecognizer(target: self, action: #selector(SwipeViewController.handlePan(recognizer:))) self.view.addGestureRecognizer(pan) let tap = UITapGestureRecognizer(target: self, action: #selector(SwipeViewController.handlePlayButton(recognizer:))) tap.allowedPressTypes = [NSNumber(value: UIPressType.playPause.rawValue)] self.view.addGestureRecognizer(tap) #endif notificationManager.addObserver(forName: .UIApplicationDidBecomeActive, object: nil, queue: OperationQueue.main) { [unowned self] (_:Notification!) -> Void in MyLog("SWView DidBecomeActive") // iOS & tvOS removes all the animations associated with CALayers when the app becomes the background mode. // Therefore, we need to recreate all the pages. // // Without this delay, the manual animation won't work after putting the app in the background once. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(300 * NSEC_PER_MSEC)) / Double(NSEC_PER_SEC)) { self.adjustIndex(self.book.pageIndex, fForced: true) } } } #if os(tvOS) // No need to give the focus to the scrollView becfause we handle the PanGesture at this view level. //override weak var preferredFocusedView: UIView? { return self.scrollView } #endif override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() // // This is the best place to know the actual view size. See the following Q&A in stackoverflow. // http://stackoverflow.com/questions/6757018/why-am-i-having-to-manually-set-my-views-frame-in-viewdidload // // var frame = self.view.bounds let ratioView = frame.size.height / frame.size.width let dimension = book.dimension let ratioBook = dimension.height / dimension.width if ratioBook > ratioView { frame.size.width = frame.size.height / ratioBook frame.origin.x = (self.view.bounds.size.width - frame.size.width) / 2 } else { frame.size.height = frame.size.width * ratioBook frame.origin.y = (self.view.bounds.size.height - frame.size.height) / 2 } scrollView.frame = frame var size = frame.size book.viewSize = size if book.horizontal { size.width *= CGFloat(book.pages.count) } else { size.height *= CGFloat(book.pages.count) } if scrollView.contentSize != size { scrollView.contentSize = size adjustIndex(self.book.pageIndex, fForced: true, fDeferredEnter: true) let offset = self.book.horizontal ? CGPoint(x: (CGFloat(self.book.pageIndex)) * frame.size.width, y: 0) : CGPoint(x: 0, y: (CGFloat(self.book.pageIndex)) * frame.size.height) self.scrollView.contentOffset = offset } } /* override func shouldAutorotate() -> Bool { return false } */ // Debugging only func tagsString() -> String { let tags = scrollView.subviews.map({ subview in return "\(subview.tag)" }) return "\(tags)" } func scrollViewDidScroll(_ scrollView: UIScrollView) { let pos = self.scrollPos let index = Int(pos) if index >= 0 { let pagePrev = self.book.pages[index] if pagePrev.fixed { if let viewPrev = pagePrev.view { var rc = viewPrev.frame rc.origin = self.scrollView.contentOffset viewPrev.frame = rc } } } if index+1 < self.book.pages.count { let pageNext = self.book.pages[index + 1] if let viewNext = pageNext.view { let offset = pos - CGFloat(index) pageNext.setTimeOffsetWhileDragging(offset) if pageNext.fixed { if offset > 0.0 && pageNext.replace { viewNext.alpha = 1.0 } else { viewNext.alpha = offset } var rc = viewNext.frame rc.origin = self.scrollView.contentOffset viewNext.frame = rc } } } if index+2 < self.book.pages.count { let pageNext2 = self.book.pages[index + 2] if pageNext2.fixed { if let viewNext2 = pageNext2.view { viewNext2.alpha = 0.0 } } } } #if os(iOS) func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { let _:CGFloat, index:Int = self.scrollIndex //MyLog("SwipeVCWillBeginDragging, \(self.book.pageIndex) to \(index)") if self.adjustIndex(index) { MyLog("SWView detected continuous scrolling to @\(self.book.pageIndex)") } } func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { let pt = targetContentOffset.pointee let target = Int(pagePosition(pt) + 0.5) if target != self.book.pageIndex { // Forward paging was just initiated by the user's dragging //MyLog("SWView willEndDragging \(self.book.pageIndex) \(target)") self.book.currentPage.willLeave(fAdvancing) let page = self.book.pages[target] fAdvancing = target > self.book.pageIndex page.willEnter(fAdvancing) } else { let page = self.book.currentPage let size = self.scrollView.frame.size if !page.isPlaying() && (self.book.horizontal && scrollView.contentOffset.x < -size.width/8.0 || !self.book.horizontal && scrollView.contentOffset.y < -size.height/8.0) { MyLog("SWView EndDragging underscrolling detected \(scrollView.contentOffset)", level:1) page.willLeave(false) page.willEnter(true) page.didEnter(true) } } } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { let index = self.scrollIndex if !self.adjustIndex(index) { MyLog("SWView didEndDecelerating same", level: 1) } self.fAdvancing = false } #elseif os(tvOS) func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { let index = self.scrollIndex self.scrollingCount -= 1 MyLog("SWView didEndScrolling \(index), \(scrollingTarget), c=\(scrollingCount)", level: 1) if self.scrollingCount > 0 { return } self.scrollingTarget = nil /* if let target = scrollingTarget { if target == index { MyLog("SWView didEndScrolling processing \(index), \(scrollingTarget)", level: 1) scrollingTarget = nil } else { MyLog("SWView didEndScrolling ignoring \(index), \(scrollingTarget) ###", level: 1) return } } else { MyLog("SWView didEndScrolling no scrollingTarget \(index) ???", level: 1) } */ if !self.adjustIndex(index) { MyLog("SWView didEndScrolling same", level: 1) } self.fAdvancing = false } func handlePlayButton(recognizer:UITapGestureRecognizer) { let page = self.book.currentPage let fPlaying = page.isPlaying() MyLog("SWView handlePlayButton \(fPlaying)", level: 1) if fPlaying { page.pause(false) } else { page.play() } /* page.willLeave(false) page.didLeave(false) page.willEnter(!fPlaying) page.didEnter(!fPlaying) */ } func handlePan(recognizer:UIPanGestureRecognizer) { if self.book.pages.count == 1 { return } let translation = recognizer.translation(in: self.view) let velocity = recognizer.velocity(in: self.view) let size = self.scrollView.frame.size var ratio = self.book.horizontal ? -translation.x / size.width : -translation.y / size.height ratio = min(max(ratio, -0.99), 0.99) if let target = self.scrollingTarget { MyLog("SWView handlePan continuous \(self.book.pageIndex) to \(target) [\(recognizer.state.rawValue)]", level:1) self.adjustIndex(target) self.fAdvancing = false self.scrollingTarget = nil } else { MyLog("SWView handlePan normal \(self.book.pageIndex) [\(recognizer.state.rawValue)]", level:2) } let offset = self.book.horizontal ? CGPoint(x: (CGFloat(self.book.pageIndex) + ratio) * size.width, y: 0) : CGPoint(x: 0, y: (CGFloat(self.book.pageIndex) + ratio) * size.height) //MyLog("SwiftVC handlePan: \(recognizer.state.rawValue), \(ratio)") switch(recognizer.state) { case .began: break case .ended: //MyLog("SwiftVC handlePan: \(recognizer.velocityInView(self.view))") scrollView.contentOffset = offset var target = self.scrollIndex if target == self.book.pageIndex { let factor = CGFloat(0.3) if self.book.horizontal { let extra = offset.x - CGFloat(target) * size.width - velocity.x * factor if extra > size.width / 2.0 { target += 1 } else if extra > 0 - size.width / 2 { target -= 1 } } else { let extra = offset.y - CGFloat(target) * size.height - velocity.y * factor //MyLog("SwiftVC handlePan: \(Int(offset.y - CGFloat(target) * size.height)) - \(Int(velocity.y)) * \(factor) = \(Int(extra))") if extra > size.height / 2 { target += 1 } else if extra < 0 - size.height / 2 { target -= 1 } } } target = min(max(target, 0), self.book.pages.count - 1) let offsetAligned = self.book.horizontal ? CGPoint(x: size.width * CGFloat(target), y: 0) : CGPoint(x: 0, y: size.height * CGFloat(target)) if target != self.book.pageIndex { // Paging was initiated by the swiping (forward or backward) self.book.currentPage.willLeave(fAdvancing) let page = self.book.pages[target] fAdvancing = target > self.book.pageIndex page.willEnter(fAdvancing) scrollingTarget = target MyLog("SWView handlePan paging \(self.book.pageIndex) to \(target), c=\(scrollingCount+1)", level:1) } else { if !self.book.horizontal && offset.y < -size.height/8.0 || self.book.horizontal && offset.x < -size.width/8.0 { MyLog("SWView underscrolling detected \(offset.x), \(offset.y)", level:1) let page = self.book.currentPage page.willLeave(false) page.willEnter(true) page.didEnter(true) } else { MyLog("SWView scrolling back c=\(scrollingCount+1)", level:1) } } self.scrollingCount += 1 MyLog("SWView scrollling to \(offsetAligned)", level:1) scrollView.setContentOffset(offsetAligned, animated: true) break case .changed: MyLog("SWView scrolls to \(offset)", level:1) scrollView.contentOffset = offset break case .cancelled: break default: break } } func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { MyLog("SWView scrollViewWillBeginDragging was called") } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { MyLog("SWView scrollViewDidEndDragging was called") } func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) { MyLog("SWView scrollViewWillBeginDecelerating was called") } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { MyLog("SWView scrollViewDidEndDecelerating was called") } func scrollViewShouldScrollToTop(_ scrollView: UIScrollView) -> Bool { MyLog("SWView scrollViewShouldScrollToTop was called") return true } #endif private func removeViewAtIndex(_ index:Int) { if index >= 0 && index < book.pages.count { let page = book.pages[index] page.unloadView() } } @discardableResult private func adjustIndex(_ newPageIndex:Int, fForced:Bool = false, fDeferredEnter:Bool = false) -> Bool { if self.book.pages.count == 0 { print("SwipeVC ### No Pages") return false } if newPageIndex == self.book.pageIndex && !fForced { return false } if !fForced { let pagePrev = self.book.currentPage pagePrev.didLeave(newPageIndex < self.book.pageIndex) } for i in -2...2 { let index = self.book.pageIndex - i if index < newPageIndex - 2 || index > newPageIndex + 2 || fForced { removeViewAtIndex(index) } } self.book.pageIndex = newPageIndex self.preparePages { (index:Int) -> (Void) in if fDeferredEnter && newPageIndex == index && newPageIndex == self.book.pageIndex { //print("SwipeVC index=\(index)") if fForced { self.book.currentPage.willEnter(true) } self.book.currentPage.didEnter(self.fAdvancing || fForced) } } if !fDeferredEnter { if fForced { self.book.currentPage.willEnter(true) } self.book.currentPage.didEnter(fAdvancing || fForced) } return true } private func preparePages(_ callback:((Int)->(Void))?) { func preparePage(_ index:Int, frame:CGRect) { if index < 0 || index >= book.pages.count { return } let page = self.book.pages[index] var above:UIView? if index > 0 { let pagePrev = self.book.pages[index-1] above = pagePrev.view } if let view = page.view { if let aboveSubview = above { scrollView.insertSubview(view, aboveSubview: aboveSubview) } } else { let view = page.loadView({ (Void) -> (Void) in callback?(index) }) view.frame = frame if let aboveSubview = above { scrollView.insertSubview(view, aboveSubview: aboveSubview) } else { scrollView.addSubview(view) } } page.prepare() } var rc = scrollView.bounds let d = book.horizontal ? CGPoint(x: rc.size.width, y: 0.0) : CGPoint(x: 0.0, y: rc.size.height) rc.origin = CGPoint(x: d.x * CGFloat(self.book.pageIndex), y: d.y * CGFloat(self.book.pageIndex)) for i in -2...2 { preparePage(self.book.pageIndex + i, frame: rc.offsetBy(dx: CGFloat(i) * d.x, dy: CGFloat(i) * d.y)) } //MyLog("SWView tags=\(tags), \(pageIndex)") self.book.setActivePage(self.book.currentPage) // debugging _ = tagsString() } // // EXPERIMENTAL: Public interface, which allows applications to scroll it to a particular scrolling position. Notice that it will play "scroll" animations, but not "auto" animations. // func scrollTo(_ amount:CGFloat) { let pageIndex = Int(amount) if pageIndex < self.book.pages.count { let frame = scrollView.frame let rem = amount - CGFloat(pageIndex) adjustIndex(pageIndex, fForced: false, fDeferredEnter: false) let offset = self.book.horizontal ? CGPoint(x: (CGFloat(self.book.pageIndex) + rem) * frame.size.width, y: 0) : CGPoint(x: 0, y: (CGFloat(self.book.pageIndex) + rem) * frame.size.height) scrollView.contentOffset = offset } } func moveToPageAt(index:Int) { if index < self.book.pages.count { self.moveTo(pageIndex: index) } } func pageIndex() -> Int? { return self.book.pageIndex } func pageCount() -> Int? { return self.book.pages.count } private func moveTo(pageIndex:Int, fAdvancing:Bool = true) { if pageIndex < self.book.pages.count && pageIndex != self.book.pageIndex { let frame = scrollView.frame scrollView.contentOffset = self.book.horizontal ? CGPoint(x: (CGFloat(pageIndex)-0.5) * frame.size.width, y: 0) : CGPoint(x: 0, y: (CGFloat(pageIndex)-0.5) * frame.size.height) self.scrollViewDidScroll(scrollView) scrollView.contentOffset = self.book.horizontal ? CGPoint(x: (CGFloat(pageIndex)) * frame.size.width, y: 0) : CGPoint(x: 0, y: (CGFloat(pageIndex)) * frame.size.height) self.scrollViewDidScroll(scrollView) self.fAdvancing = fAdvancing let page = self.book.pages[pageIndex] //print("moveTo", pageIndex, page.fixed); page.willEnter(true) adjustIndex(pageIndex, fForced: false, fDeferredEnter: false) } } }
mit
15ec611abf144c969aabf6acb2198df5
36.636953
198
0.573379
4.554226
false
false
false
false
rshankras/WordPress-iOS
WordPress/Classes/ViewRelated/Reader/WPStyleGuide+Reader.swift
1
9163
import Foundation /** A WPStyleGuide extension with styles and methods specific to the Reader feature. */ extension WPStyleGuide { // MARK: Original Post/Site Attribution Styles. public class func originalAttributionParagraphAttributes() -> [NSObject: AnyObject] { let fontSize = originalAttributionFontSize() let font = WPFontManager.openSansRegularFontOfSize(fontSize) let lineHeight:CGFloat = Cards.defaultLineHeight let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.minimumLineHeight = lineHeight paragraphStyle.maximumLineHeight = lineHeight return [ NSParagraphStyleAttributeName : paragraphStyle, NSFontAttributeName : font, NSForegroundColorAttributeName: grey(), ] } public class func siteAttributionParagraphAttributes() -> [NSObject: AnyObject] { let attributes = NSMutableDictionary(dictionary: originalAttributionParagraphAttributes()) attributes.setValue(mediumBlue(), forKey: NSForegroundColorAttributeName) return attributes as [NSObject: AnyObject] } public class func originalAttributionFontSize() -> CGFloat { return Cards.contentFontSize } // MARK: - Reader Card Styles // MARK: - Custom Colors public class func readerCardCellBorderColor() -> UIColor { return UIColor(red: 215.0/255.0, green: 227.0/255.0, blue: 235.0/255.0, alpha: 1.0) } public class func readerCardCellHighlightedBorderColor() -> UIColor { // #87a6bc return UIColor(red: 135/255.0, green: 166/255.0, blue: 188/255.0, alpha: 1.0) } // MARK: - Card Attributed Text Attributes public class func readerCardTitleAttributes() -> [NSObject: AnyObject] { let fontSize = Cards.titleFontSize let font = WPFontManager.merriweatherBoldFontOfSize(fontSize) let lineHeight = Cards.titleLineHeight var paragraphStyle = NSMutableParagraphStyle() paragraphStyle.minimumLineHeight = lineHeight paragraphStyle.maximumLineHeight = lineHeight return [ NSParagraphStyleAttributeName: paragraphStyle, NSFontAttributeName: font ] } public class func readerCardSummaryAttributes() -> [NSObject: AnyObject] { let fontSize = Cards.contentFontSize let font = WPFontManager.merriweatherRegularFontOfSize(fontSize) let lineHeight = Cards.defaultLineHeight var paragraphStyle = NSMutableParagraphStyle() paragraphStyle.minimumLineHeight = lineHeight paragraphStyle.maximumLineHeight = lineHeight return [ NSParagraphStyleAttributeName: paragraphStyle, NSFontAttributeName: font ] } public class func readerCardWordCountAttributes() -> [NSObject: AnyObject] { let fontSize = Cards.contentFontSize let font = WPFontManager.openSansRegularFontOfSize(fontSize) let lineHeight = Cards.defaultLineHeight var paragraphStyle = NSMutableParagraphStyle() paragraphStyle.minimumLineHeight = lineHeight paragraphStyle.maximumLineHeight = lineHeight return [ NSParagraphStyleAttributeName: paragraphStyle, NSFontAttributeName: font, NSForegroundColorAttributeName: greyLighten10() ] } public class func readerCardReadingTimeAttributes() -> [NSObject: AnyObject] { let fontSize:CGFloat = UIDevice.isPad() ? 14.0 : 12.0 let font = WPFontManager.openSansRegularFontOfSize(fontSize) let lineHeight = Cards.defaultLineHeight var paragraphStyle = NSMutableParagraphStyle() paragraphStyle.minimumLineHeight = lineHeight paragraphStyle.maximumLineHeight = lineHeight return [ NSParagraphStyleAttributeName: paragraphStyle, NSFontAttributeName: font, NSForegroundColorAttributeName: greyLighten10() ] } // MARK: - Stream Header Attributed Text Attributes public class func readerStreamHeaderDescriptionAttributes() -> [NSObject: AnyObject] { let fontSize = Cards.contentFontSize let font = WPFontManager.merriweatherRegularFontOfSize(fontSize) let lineHeight = Cards.defaultLineHeight var paragraphStyle = NSMutableParagraphStyle() paragraphStyle.minimumLineHeight = lineHeight paragraphStyle.maximumLineHeight = lineHeight return [ NSParagraphStyleAttributeName: paragraphStyle, NSFontAttributeName: font ] } // MARK: - Apply Card Styles public class func applyReaderCardSiteButtonStyle(button:UIButton) { let fontSize = Cards.buttonFontSize button.titleLabel!.font = WPFontManager.openSansRegularFontOfSize(fontSize) button.setTitleColor(mediumBlue(), forState: .Normal) button.setTitleColor(lightBlue(), forState: .Highlighted) button.setTitleColor(greyDarken20(), forState: .Disabled) } public class func applyReaderCardBylineLabelStyle(label:UILabel) { let fontSize:CGFloat = 12.0 label.font = WPFontManager.openSansRegularFontOfSize(fontSize) label.textColor = grey() } public class func applyReaderCardTitleLabelStyle(label:UILabel) { label.textColor = darkGrey() } public class func applyReaderCardSummaryLabelStyle(label:UILabel) { label.textColor = darkGrey() } public class func applyReaderCardTagButtonStyle(button:UIButton) { let fontSize = Cards.buttonFontSize button.setTitleColor(mediumBlue(), forState: .Normal) button.setTitleColor(lightBlue(), forState: .Highlighted) button.titleLabel?.font = WPFontManager.openSansRegularFontOfSize(fontSize) } public class func applyReaderCardActionButtonStyle(button:UIButton) { let fontSize = Cards.buttonFontSize button.setTitleColor(grey(), forState: .Normal) button.setTitleColor(lightBlue(), forState: .Highlighted) button.titleLabel?.font = WPFontManager.openSansRegularFontOfSize(fontSize) } // MARK: - Apply Stream Header Styles public class func applyReaderStreamHeaderTitleStyle(label:UILabel) { let fontSize:CGFloat = 14.0 label.font = WPFontManager.openSansRegularFontOfSize(fontSize) label.textColor = grey() } public class func applyReaderStreamHeaderDetailStyle(label:UILabel) { let fontSize:CGFloat = 12.0 label.font = WPFontManager.openSansRegularFontOfSize(fontSize) label.textColor = grey() } public class func applyReaderStreamHeaderFollowingStyle(button:UIButton) { let fontSize = Cards.buttonFontSize let title = NSLocalizedString("Following", comment: "Gerund. A button label indicating the user is currently subscribed to a topic or site in ther eader. Tapping unsubscribes the user.") button.setTitle(title, forState: .Normal) button.setTitle(title, forState: .Highlighted) button.setTitleColor(validGreen(), forState: .Normal) button.setTitleColor(lightBlue(), forState: .Highlighted) button.titleLabel?.font = WPFontManager.openSansRegularFontOfSize(fontSize) button.setImage(UIImage(named: "icon-reader-following"), forState: .Normal) button.setImage(UIImage(named: "icon-reader-follow-highlight"), forState: .Highlighted) } public class func applyReaderStreamHeaderNotFollowingStyle(button:UIButton) { let fontSize = Cards.buttonFontSize let title = NSLocalizedString("Follow", comment: "Verb. A button label. Tapping subscribes the user to a topic or site in the reader") button.setTitle(title, forState: .Normal) button.setTitle(title, forState: .Highlighted) button.setTitleColor(greyLighten10(), forState: .Normal) button.setTitleColor(lightBlue(), forState: .Highlighted) button.titleLabel?.font = WPFontManager.openSansRegularFontOfSize(fontSize) button.setImage(UIImage(named: "icon-reader-follow"), forState: .Normal) button.setImage(UIImage(named: "icon-reader-follow-highlight"), forState: .Highlighted) } public class func applyReaderSiteStreamDescriptionStyle(label:UILabel) { let fontSize = Cards.contentFontSize label.font = WPFontManager.merriweatherRegularFontOfSize(fontSize) label.textColor = darkGrey() } public class func applyReaderSiteStreamCountStyle(label:UILabel) { let fontSize:CGFloat = 12.0 label.font = WPFontManager.openSansRegularFontOfSize(fontSize) label.textColor = grey() } // MARK: - Metrics public struct Cards { public static let defaultLineHeight:CGFloat = UIDevice.isPad() ? 24.0 : 21.0 public static let titleFontSize:CGFloat = UIDevice.isPad() ? 24.0 : 16.0 public static let titleLineHeight:CGFloat = UIDevice.isPad() ? 32.0 : 21.0 public static let contentFontSize:CGFloat = UIDevice.isPad() ? 16.0 : 14.0 public static let buttonFontSize:CGFloat = 14.0 } }
gpl-2.0
1f76a7d3306c5b0a713a78a7a379e3a2
37.179167
194
0.700098
5.355348
false
false
false
false
Harry-L/5-3-1
ios-charts-master/Charts/ChartsTests/BarChartTests.swift
6
2028
import XCTest import FBSnapshotTestCase @testable import Charts class BarChartTests: FBSnapshotTestCase { var chart: BarChartView! var dataSet: BarChartDataSet! override func setUp() { super.setUp() // Set to `true` to re-capture all snapshots self.recordMode = false // Sample data let values: [Double] = [8, 104, 81, 93, 52, 44, 97, 101, 75, 28, 76, 25, 20, 13, 52, 44, 57, 23, 45, 91, 99, 14, 84, 48, 40, 71, 106, 41, 45, 61] var entries: [ChartDataEntry] = Array() var xValues: [String] = Array() for (i, value) in values.enumerate() { entries.append(BarChartDataEntry.init(value: value, xIndex: i)) xValues.append("\(i)") } dataSet = BarChartDataSet(yVals: entries, label: "Bar chart unit test data") chart = BarChartView(frame: CGRectMake(0, 0, 480, 350)) chart.data = BarChartData(xVals: xValues, dataSet: dataSet) } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testDefaultValues() { FBSnapshotVerifyView(chart) } func testHidesValues() { dataSet.drawValuesEnabled = false FBSnapshotVerifyView(chart) } func testHideLeftAxis() { chart.leftAxis.enabled = false FBSnapshotVerifyView(chart) } func testHideRightAxis() { chart.rightAxis.enabled = false FBSnapshotVerifyView(chart) } func testHideHorizontalGridlines() { chart.leftAxis.drawGridLinesEnabled = false chart.rightAxis.drawGridLinesEnabled = false FBSnapshotVerifyView(chart) } func testHideVerticalGridlines() { chart.xAxis.drawGridLinesEnabled = false FBSnapshotVerifyView(chart) } }
mit
c00f97c2e1c116f6e11e3b562025f30f
24.670886
111
0.584813
4.794326
false
true
false
false
liukunpengiOS/PaperHouse
PaperHouse/PHAnnotation.swift
1
1605
// // PHAnnotations.swift // PaperHouse // // Created by DRex on 2017/6/15. // Copyright © 2017年 liukunpeng. All rights reserved. // import Foundation //import Alamofire class PHAnnotation { //构造方法 init() { } //获取数据之后封装成MAPointAnnotation并存入数组并返回 class func getAnnotationsFormServer() -> Array<MAPointAnnotation>{ var annotations = [MAPointAnnotation]() let pointAnnotation1 = MAPointAnnotation() pointAnnotation1.coordinate = CLLocationCoordinate2DMake(34.7511, 113.70) let pointAnnotation2 = MAPointAnnotation() pointAnnotation2.coordinate = CLLocationCoordinate2DMake(34.761, 113.71) let pointAnnotation3 = MAPointAnnotation() pointAnnotation3.coordinate = CLLocationCoordinate2DMake(34.77, 113.75) let pointAnnotation4 = MAPointAnnotation() pointAnnotation4.coordinate = CLLocationCoordinate2DMake(34.78, 113.78) let pointAnnotation5 = MAPointAnnotation() pointAnnotation5.coordinate = CLLocationCoordinate2DMake(34.66, 113.73) annotations.append(pointAnnotation1) annotations.append(pointAnnotation2) annotations.append(pointAnnotation3) annotations.append(pointAnnotation4) annotations.append(pointAnnotation5) // Alamofire.request("https://api.500px.com/v1/photos", method: .get).responseJSON { // response in // guard let JSON = response.result.value else { return } // print("JSON: \(JSON)") // } return annotations } }
mit
b1c8f0349a4f52c326d5d302f501d983
34.454545
91
0.680769
4.419263
false
false
false
false
cpoutfitters/cpoutfitters
CPOutfitters/OutfitSelectionViewController.swift
1
9046
// // OutfitSelectionViewController.swift // CPOutfitters // // Created by Aditya Purandare on 03/04/16. // Copyright © 2016 SnazzyLLama. All rights reserved. // import UIKit import Parse let kselectTopSegueIdentifier = "selectTop" let kselectBottomSegueIdentifier = "selectBottom" let kselectFootwearSegueIdentifier = "selectFootwear" class OutfitSelectionViewController: UIViewController, ArticleSelectDelegate { @IBOutlet weak var saveButton: UIButton! @IBOutlet weak var topButton: UIButton! @IBOutlet weak var bottomButton: UIButton! @IBOutlet weak var footwearButton: UIButton! @IBOutlet weak var favoriteButton: UIButton! var attire: String = "" var articles: [[Article]] = [[],[],[]] var isTopSelected: Bool = false var isBottomSelected: Bool = false var isFootwearSelected: Bool = false var outfit: Outfit! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. // Attach shake gesture /* API Call for getting an outfit ParseClient.sharedInstance.suggestOutfit(["attire":attire]) */ ParseClient.sharedInstance.fetchArticles(["type":"top", "occasion":attire]) { (articleObjects:[Article]?, error: NSError?) in if let articleObjects = articleObjects { self.articles[0] = articleObjects } else { let errorString = error!.userInfo["error"] as? NSString print("Error message: \(errorString)") } } ParseClient.sharedInstance.fetchArticles(["type":"bottom", "occasion":attire]) { (articleObjects:[Article]?, error: NSError?) in if let articleObjects = articleObjects { self.articles[1] = articleObjects } else { let errorString = error!.userInfo["error"] as? NSString print("Error message: \(errorString)") } } ParseClient.sharedInstance.fetchArticles(["type":"footwear", "occasion":attire]) { (articleObjects:[Article]?, error: NSError?) in if let articleObjects = articleObjects { self.articles[2] = articleObjects } else { let errorString = error!.userInfo["error"] as? NSString print("Error message: \(errorString)") } } saveButton.enabled = false loadOutfit() } override func viewDidAppear(animated: Bool) { becomeFirstResponder() } @IBAction func onRecommendMe(sender: AnyObject) { print("OutfitSelectionViewController: onRecommend Button click") ParseClient.sharedInstance.getRecommendedOutfit(["occasion": attire]) { (type: String, article: Article?, error:NSError?) in if let error = error { print("OutfitSelectionViewController: \(error.localizedDescription)") } else { switch (type) { case "top": self.outfit.topComponent = article if article == nil { self.topButton.setTitle("No tops found!", forState: .Normal) } self.loadTop() case "bottom": self.outfit.bottomComponent = article if article == nil { self.bottomButton.setTitle("No bottoms found!", forState: .Normal) } self.loadBottom() default: self.outfit.footwearComponent = article if article == nil { self.footwearButton.setTitle("No footwear found!", forState: .Normal) } self.loadFootwear() } } } } func loadOutfit() { loadTop() loadBottom() loadFootwear() self.favoriteButton.selected = false } func loadTop() { if let topImage = outfit.topComponent?.mediaImage { topImage.getDataInBackgroundWithBlock({ (imageData:NSData?, error: NSError?) in if let imageData = imageData { let image = UIImage(data: imageData) self.topButton.setBackgroundImage(image, forState: .Normal) } }) } } func loadBottom() { if let bottomImage = outfit.bottomComponent?.mediaImage { bottomImage.getDataInBackgroundWithBlock({ (imageData:NSData?, error: NSError?) in if let imageData = imageData { let image = UIImage(data: imageData) self.bottomButton.setBackgroundImage(image, forState: .Normal) } }) } } func loadFootwear() { if let footwearImage = outfit.footwearComponent?.mediaImage { footwearImage.getDataInBackgroundWithBlock({ (imageData:NSData?, error: NSError?) in if let imageData = imageData { let image = UIImage(data: imageData) self.footwearButton.setBackgroundImage(image, forState: .Normal) } }) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { var articleArray: [Article] = [] let destinationViewController = segue.destinationViewController if let articleSelectionViewController = destinationViewController as? ArticleSelectionViewController { if segue.identifier == kselectTopSegueIdentifier { articleArray = articles[0] } else if segue.identifier == kselectBottomSegueIdentifier { articleArray = articles[1] } else if segue.identifier == kselectFootwearSegueIdentifier { articleArray = articles[2] } articleSelectionViewController.articles = articleArray articleSelectionViewController.delegate = self } else if let articleViewController = segue.destinationViewController as? ArticleViewController { } if let postViewController = destinationViewController as? PostViewController { postViewController.outfit = outfit } } func articleSelected(article: Article) { //Add component to outfit let image = article.mediaImage image.getDataInBackgroundWithBlock({ (imageData:NSData?, error: NSError?) in if let imageData = imageData { let articleImage = UIImage(data: imageData) //Get type of article let articleType = article.type var articleIndex = -1 var button: UIButton switch(articleType) { case "top": button = self.topButton; self.outfit.topComponent = article; self.isTopSelected = true case "bottom": button = self.bottomButton; self.outfit.bottomComponent = article; self.isBottomSelected = true default: button = self.footwearButton; self.outfit.footwearComponent = article; self.isFootwearSelected = true } button.setTitle("", forState: .Normal) button.setBackgroundImage(articleImage, forState: .Normal) if self.isTopSelected && self.isBottomSelected && self.isFootwearSelected { self.saveButton.enabled = true } } }) } @IBAction func onCancel(sender: AnyObject) { self.presentingViewController?.dismissViewControllerAnimated(true, completion: nil) } @IBAction func onSave(sender: AnyObject) { ParseClient.sharedInstance.saveOutfit(outfit) { (success, error) in if success { self.dismissViewControllerAnimated(true, completion: nil) print("outfit saved") } else { print(error?.localizedDescription) } } } override func canBecomeFirstResponder() -> Bool { return true } override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent?) { if motion == .MotionShake { onRecommendMe(self) } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
06d839793fae536a11ed0d65a3f8ba5f
35.768293
138
0.578773
5.4
false
false
false
false
Tsiems/mobile-sensing-apps
AirDrummer/AIToolbox/DeepChannel.swift
1
8656
// // DeepChannel.swift // AIToolbox // // Created by Kevin Coble on 6/25/16. // Copyright © 2016 Kevin Coble. All rights reserved. // import Foundation public struct DeepChannelSize { public let numDimensions : Int public var dimensions : [Int] public init(dimensionCount: Int, dimensionValues: [Int]) { numDimensions = dimensionCount dimensions = dimensionValues } public var totalSize: Int { get { var result = 1 for i in 0..<numDimensions { result *= dimensions[i] } return result } } public func asString() ->String { var result = "\(numDimensions)D - [" if (numDimensions > 0) { result += "\(dimensions[0])" } if (numDimensions > 1) { for i in 1..<numDimensions { result += ", \(dimensions[i])" } } result += "]" return result } } /// Class for a single channel of a deep layer /// A deep channel manages a network topology for a single data-stream within a deep layer /// It contains an ordered array of 'network operators' that manipulate the channel data (convolutions, poolings, feedforward nets, etc.) final public class DeepChannel : MLPersistence { public let idString : String // The string ID for the channel. i.e. "red component" public private(set) var sourceChannelID : String // ID of the channel that is the source for this channel from the previous layer public private(set) var resultSize : DeepChannelSize // Size of the result of this channel var networkOperators : [DeepNetworkOperator] = [] fileprivate var inputErrorGradient : [Float] = [] public init(identifier: String, sourceChannel: String) { idString = identifier sourceChannelID = sourceChannel resultSize = DeepChannelSize(dimensionCount: 1, dimensionValues: [0]) } public init?(fromDictionary: [String: AnyObject]) { // Init for nil return (hopefully Swift 3 removes this need) resultSize = DeepChannelSize(dimensionCount: 1, dimensionValues: [0]) // Get the id string type let id = fromDictionary["idString"] as? NSString if id == nil { return nil } idString = id! as String // Get the source ID let source = fromDictionary["sourceChannelID"] as? NSString if source == nil { return nil } sourceChannelID = source! as String // Get the array of network operators let networkOpArray = fromDictionary["networkOperators"] as? NSArray if (networkOpArray == nil) { return nil } for item in networkOpArray! { let element = item as? [String: AnyObject] if (element == nil) { return nil } let netOperator = DeepNetworkOperatorType.getDeepNetworkOperatorFromDict(element!) if (netOperator == nil) { return nil } networkOperators.append(netOperator!) } } /// Function to add a network operator to the channel public func addNetworkOperator(_ newOperator: DeepNetworkOperator) { networkOperators.append(newOperator) } /// Function to get the number of defined operators public var numOperators: Int { get { return networkOperators.count } } /// Function to get a network operator at the specified index public func getNetworkOperator(_ operatorIndex: Int) ->DeepNetworkOperator? { if (operatorIndex >= 0 && operatorIndex < networkOperators.count) { return networkOperators[operatorIndex] } return nil } /// Function to replace a network operator at the specified index public func replaceNetworkOperator(_ operatorIndex: Int, newOperator: DeepNetworkOperator) { if (operatorIndex >= 0 && operatorIndex < networkOperators.count) { networkOperators[operatorIndex] = newOperator } } /// Functions to remove a network operator from the channel public func removeNetworkOperator(_ operatorIndex: Int) { if (operatorIndex >= 0 && operatorIndex < networkOperators.count) { networkOperators.remove(at: operatorIndex) } } // Method to determine the output size based on the input size and the operation layers func updateOutputSize(_ inputSize : DeepChannelSize) { // Iterate through each operator, adjusting the size var currentSize = inputSize for networkOperator in networkOperators { currentSize = networkOperator.getResultingSize(currentSize) } resultSize = currentSize } func getResultRange() ->(minimum: Float, maximum: Float) { if let lastOperator = networkOperators.last { return lastOperator.getResultRange() } return (minimum: 0.0, maximum: 1.0) } public func initializeParameters() { for networkOperator in networkOperators { networkOperator.initializeParameters() } } // Method to feed values forward through the channel func feedForward(_ inputSource: DeepNetworkInputSource) { // Get the inputs from the previous layer var inputs = inputSource.getValuesForID(sourceChannelID) var inputSize = inputSource.getInputDataSize(sourceChannelID) if (inputSize == nil) { return } // Process each operator for networkOperator in networkOperators { inputs = networkOperator.feedForward(inputs, inputSize: inputSize!) inputSize = networkOperator.getResultSize() } } // Function to clear weight-change accumulations for the start of a batch public func startBatch() { for networkOperator in networkOperators { networkOperator.startBatch() } } func backPropagate(_ gradientSource: DeepNetworkOutputDestination) { // Get the gradients from the previous layer inputErrorGradient = gradientSource.getGradientForSource(idString) // Process the gradient backwards through all the operators for operatorIndex in stride(from: (networkOperators.count - 1), through: 0, by: -1) { inputErrorGradient = networkOperators[operatorIndex].backPropogateGradient(inputErrorGradient) } } public func updateWeights(_ trainingRate : Float, weightDecay: Float) { for networkOperator in networkOperators { networkOperator.updateWeights(trainingRate, weightDecay: weightDecay) } } public func gradientCheck(ε: Float, Δ: Float, network: DeepNetwork) -> Bool { // Have each operator check var result = true for operatorIndex in 0..<networkOperators.count { if (!networkOperators[operatorIndex].gradientCheck(ε: ε, Δ: Δ, network: network)) { result = false } } return result } func getGradient() -> [Float] { return inputErrorGradient } /// Function to get the result of the last operation public func getFinalResult() -> [Float] { if let lastOperator = networkOperators.last { return lastOperator.getResults() } return [] } public func getResultOfItem(_ operatorIndex: Int) ->(values : [Float], size: DeepChannelSize)? { if (operatorIndex >= 0 && operatorIndex < networkOperators.count) { let values = networkOperators[operatorIndex].getResults() let size = networkOperators[operatorIndex].getResultSize() return (values : values, size: size) } return nil } public func getPersistenceDictionary() -> [String: AnyObject] { var resultDictionary : [String: AnyObject] = [:] // Set the id string type resultDictionary["idString"] = idString as AnyObject? // Set the source ID resultDictionary["sourceChannelID"] = sourceChannelID as AnyObject? // Set the array of network operators var operationsArray : [[String: AnyObject]] = [] for networkOperator in networkOperators { operationsArray.append(networkOperator.getOperationPersistenceDictionary()) } resultDictionary["networkOperators"] = operationsArray as AnyObject? return resultDictionary } }
mit
98e88550e6588f08374009c406d752c3
32.917647
138
0.62354
4.931015
false
false
false
false
richardpiazza/SOSwift
Sources/SOSwift/OrganizationOrPerson.swift
1
1834
import Foundation import CodablePlus public enum OrganizationOrPerson: Codable { case organization(value: Organization) case person(value: Person) public init(_ value: Organization) { self = .organization(value: value) } public init(_ value: Person) { self = .person(value: value) } public init(from decoder: Decoder) throws { let jsonContainer = try decoder.container(keyedBy: DictionaryKeys.self) let dictionary = try jsonContainer.decode(Dictionary<String, Any>.self) guard let type = dictionary[SchemaKeys.type.rawValue] as? String else { throw SchemaError.typeDecodingError } let container = try decoder.singleValueContainer() switch type { case Organization.schemaName: let value = try container.decode(Organization.self) self = .organization(value: value) case Person.schemaName: let value = try container.decode(Person.self) self = .person(value: value) default: throw SchemaError.typeDecodingError } } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() switch self { case .organization(let value): try container.encode(value) case .person(let value): try container.encode(value) } } public var organization: Organization? { switch self { case .organization(let value): return value default: return nil } } public var person: Person? { switch self { case .person(let value): return value default: return nil } } }
mit
dcbd97f49fef20d3a11e8744d4e434df
26.787879
79
0.581243
5.038462
false
false
false
false
jtbandes/swift
test/sil-func-extractor/basic.swift
3
4206
// Passing demangled name // RUN: %target-swift-frontend %s -g -module-name basic -emit-sib -o - | %target-sil-func-extractor -module-name basic -func="basic.foo" | %FileCheck %s -check-prefix=EXTRACT-FOO // RUN: %target-swift-frontend %s -g -module-name basic -emit-sib -o - | %target-sil-func-extractor -module-name basic -func="basic.X.test" | %FileCheck %s -check-prefix=EXTRACT-TEST // RUN: %target-swift-frontend %s -g -module-name basic -emit-sib -o - | %target-sil-func-extractor -module-name basic -func="basic.Vehicle.init" | %FileCheck %s -check-prefix=EXTRACT-INIT // RUN: %target-swift-frontend %s -g -module-name basic -emit-sib -o - | %target-sil-func-extractor -module-name basic -func="basic.Vehicle.now" | %FileCheck %s -check-prefix=EXTRACT-NOW // Passing mangled name // RUN: %target-swift-frontend %s -g -module-name basic -emit-sib -o - | %target-sil-func-extractor -module-name basic -func="_T05basic3fooSiyF" | %FileCheck %s -check-prefix=EXTRACT-FOO // RUN: %target-swift-frontend %s -g -module-name basic -emit-sib -o - | %target-sil-func-extractor -module-name basic -func="_T05basic1XV4testyyF" | %FileCheck %s -check-prefix=EXTRACT-TEST // RUN: %target-swift-frontend %s -g -module-name basic -emit-sib -o - | %target-sil-func-extractor -module-name basic -func="_T05basic7VehicleCACSi1n_tcfc" | %FileCheck %s -check-prefix=EXTRACT-INIT // RUN: %target-swift-frontend %s -g -module-name basic -emit-sib -o - | %target-sil-func-extractor -module-name basic -func="_T05basic7VehicleC3nowSiyF" | %FileCheck %s -check-prefix=EXTRACT-NOW // EXTRACT-FOO-NOT: sil hidden @_T05basic1XV4testyyF : $@convention(method) (X) -> () { // EXTRACT-FOO-NOT: sil hidden @_T05basic7VehicleCACSi1n_tcfc : $@convention(method) (Int, @guaranteed Vehicle) -> @owned Vehicle { // EXTRACT-FOO-NOT: sil hidden @_T05basic7VehicleC3nowSiyF : $@convention(method) (@guaranteed Vehicle) -> Int { // EXTRACT-FOO-LABEL: sil hidden @_T05basic3fooSiyF : $@convention(thin) () -> Int { // EXTRACT-FOO: bb0: // EXTRACT-FOO-NEXT: %0 = integer_literal // EXTRACT-FOO: %[[POS:.*]] = struct $Int // EXTRACT-FOO-NEXT: return %[[POS]] : $Int // EXTRACT-TEST-NOT: sil hidden @_T05basic3fooSiyF : $@convention(thin) () -> Int { // EXTRACT-TEST-NOT: sil hidden @_T05basic7VehicleCACSi1n_tcfc : $@convention(method) (Int, @guaranteed Vehicle) -> @owned Vehicle { // EXTRACT-TEST-NOT: sil hidden @_T05basic7VehicleC3nowSiyF : $@convention(method) (@guaranteed Vehicle) -> Int { // EXTRACT-TEST-LABEL: sil hidden @_T05basic1XV4testyyF : $@convention(method) (X) -> () { // EXTRACT-TEST: bb0(%0 : $X): // EXTRACT-TEST-NEXT: function_ref // EXTRACT-TEST-NEXT: function_ref @_T05basic3fooSiyF : $@convention(thin) () -> Int // EXTRACT-TEST-NEXT: apply // EXTRACT-TEST-NEXT: tuple // EXTRACT-TEST-NEXT: return // EXTRACT-INIT-NOT: sil hidden @_T05basic3fooSiyF : $@convention(thin) () -> Int { // EXTRACT-INIT-NOT: sil hidden @_T05basic1XV4testyyF : $@convention(method) (X) -> () { // EXTRACT-INIT-NOT: sil hidden @_T05basic7VehicleC3nowSiyF : $@convention(method) (@owned Vehicle) -> Int { // EXTRACT-INIT-LABEL: sil hidden @_T05basic7VehicleCACSi1n_tcfc : $@convention(method) (Int, @owned Vehicle) -> @owned Vehicle { // EXTRACT-INIT: bb0 // EXTRACT-INIT-NEXT: ref_element_addr // EXTRACT-INIT-NEXT: store // EXTRACT-INIT-NEXT: return // EXTRACT-NOW-NOT: sil hidden @_T05basic3fooSiyF : $@convention(thin) () -> Int { // EXTRACT-NOW-NOT: sil hidden @_T05basic1XV4testyyF : $@convention(method) (X) -> () { // EXTRACT-NOW-NOT: sil hidden @_T05basic7VehicleCACSi1n_tcfc : $@convention(method) (Int, @guaranteed Vehicle) -> @owned Vehicle { // EXTRACT-NOW-LABEL: sil hidden @_T05basic7VehicleC3nowSiyF : $@convention(method) (@guaranteed Vehicle) -> Int { // EXTRACT-NOW: bb0 // EXTRACT-NOW: ref_element_addr // EXTRACT-NOW-NEXT: load // EXTRACT-NOW-NEXT: return struct X { func test() { foo() } } class Vehicle { var numOfWheels: Int init(n: Int) { numOfWheels = n } func now() -> Int { return numOfWheels } } @discardableResult func foo() -> Int { return 7 }
apache-2.0
6eb73ccb786dad151bf61e1b1c05c178
50.292683
199
0.67689
3.05225
false
true
false
false
mnito/alt-file
info/functions/filePermissions.swift
1
364
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) import Darwin #else import Glibc #endif public func filePermissions(path: String) -> FilePermissions { var fPerm = FilePermissions() if(access(path, R_OK) == 0) { fPerm.read = true } if(access(path, W_OK) == 0) { fPerm.write = true } if(access(path, X_OK) == 0) { fPerm.read = true } return fPerm }
mit
e22b79c56b11d739aadcb2ad537f6dc5
27
62
0.634615
2.866142
false
false
false
false
happylance/MacKey
MacKeyUnit/Domain/HostInfo.swift
1
742
// // HostInfo.swift // MacKey // // Created by Liu Liang on 15/01/2017. // Copyright © 2017 Liu Liang. All rights reserved. // struct HostInfo: CustomStringConvertible { var alias = "" var host = "" var user = "" var password = "" var requireTouchID = true var description: String { return "(\(alias),\(host),\(user),\(requireTouchID))" } } extension HostInfo: Equatable { static func ==(lhs: HostInfo, rhs: HostInfo) -> Bool { let areEqual = (lhs.alias == rhs.alias && lhs.host == rhs.host && lhs.user == rhs.user && lhs.password == rhs.password && lhs.requireTouchID == rhs.requireTouchID) return areEqual } }
mit
a58cc8ae2a9fb9639c8e68903005c800
22.903226
61
0.560054
4.027174
false
false
false
false
AssistoLab/FloatingLabel
FloatingLabel/src/input/FloatingField+InputField.swift
2
3175
// // FloatingField+UITextField.swift // FloatingLabel // // Created by Kevin Hirsch on 15/07/15. // Copyright (c) 2015 Kevin Hirsch. All rights reserved. // import UIKit //MARK: - Properties public extension FloatingField { @IBInspectable var text: String? { get { return input.__text } set { if newValue != text { input.__text = newValue hasBeenEdited = true updateUI(animated: true) } } } @IBInspectable var placeholder: String? { get { return input.__placeholder } set { input.__placeholder = newValue floatingLabel.text = newValue } } var textAlignment: NSTextAlignment { get { return input.__textAlignment } set { input.__textAlignment = newValue floatingLabel.textAlignment = newValue helperLabel.textAlignment = newValue } } } public extension FloatingTextField { var minimumFontSize: CGFloat { get { return textField.minimumFontSize } set { textField.minimumFontSize = newValue } } var adjustsFontSizeToFitWidth: Bool { get { return textField.adjustsFontSizeToFitWidth } set { textField.adjustsFontSizeToFitWidth = newValue } } var rightView: UIView? { get { return textField.rightView } set { textField.rightView = newValue } } var rightViewMode: UITextFieldViewMode { get { return textField.rightViewMode } set { textField.rightViewMode = newValue } } } //MARK: - Responder public extension FloatingField { override func canBecomeFirstResponder() -> Bool { return input.canBecomeFirstResponder() } override func becomeFirstResponder() -> Bool { return input.becomeFirstResponder() } override func resignFirstResponder() -> Bool { return input.resignFirstResponder() } override func isFirstResponder() -> Bool { return input.isFirstResponder() } override func canResignFirstResponder() -> Bool { return input.canResignFirstResponder() } } //MARK: - UITextInputTraits extension FloatingField: UITextInputTraits { public var autocapitalizationType: UITextAutocapitalizationType { get { return input.__autocapitalizationType } set { input.__autocapitalizationType = newValue } } public var autocorrectionType: UITextAutocorrectionType { get { return input.__autocorrectionType } set { input.__autocorrectionType = newValue } } public var spellCheckingType: UITextSpellCheckingType { get { return input.__spellCheckingType } set { input.__spellCheckingType = newValue } } public var keyboardType: UIKeyboardType { get { return input.__keyboardType } set { input.__keyboardType = newValue } } public var keyboardAppearance: UIKeyboardAppearance { get { return input.__keyboardAppearance } set { input.__keyboardAppearance = newValue } } public var returnKeyType: UIReturnKeyType { get { return input.__returnKeyType } set { input.__returnKeyType = newValue } } public var enablesReturnKeyAutomatically: Bool { get { return input.__enablesReturnKeyAutomatically } set { input.__enablesReturnKeyAutomatically = newValue } } public var passwordModeEnabled: Bool { get { return input.__secureTextEntry } set { input.__secureTextEntry = newValue } } }
mit
9165c48973cb8c16b2d53c899d13f5fe
20.903448
66
0.718425
4.302168
false
false
false
false
dzenbot/Iconic
Vendor/SwiftGen/GenumKit/Parsers/AssetsCatalogParser.swift
2
750
// // GenumKit // Copyright (c) 2015 Olivier Halligon // MIT Licence // import Foundation public final class AssetsCatalogParser { var imageNames = [String]() public init() {} public func addImageName(name: String) -> Bool { if imageNames.contains(name) { return false } else { imageNames.append(name) return true } } public func parseDirectory(path: String) { if let dirEnum = NSFileManager.defaultManager().enumeratorAtPath(path) { while let path = dirEnum.nextObject() as? NSString { if path.pathExtension == "imageset" { let imageName = (path.lastPathComponent as NSString).stringByDeletingPathExtension self.addImageName(imageName) } } } } }
mit
cdd922906e91471e6842860b816e7249
21.727273
92
0.650667
4.491018
false
false
false
false
swiftdetut/10-Taschenrechner
Taschenrechner/Taschenrechner2/MainInterfaceVC.swift
2
1895
// // MainInterfaceVC.swift // Taschenrechner2 // // Created by Benjamin Herzog on 29.06.14. // Copyright (c) 2014 Benjamin Herzog. All rights reserved. // import UIKit class MainInterfaceVC: UIViewController, UITextFieldDelegate { @IBOutlet var zahl1TF: UITextField! @IBOutlet var zahl2TF: UITextField! @IBOutlet var operatorSC: UISegmentedControl! @IBOutlet var ergebnisLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() zahl1TF.delegate = self zahl2TF.delegate = self } func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool { //textField.text = textField.text.bridgeToObjectiveC().stringByReplacingCharactersInRange(range, withString: string) textField.text = (textField.text as NSString).stringByReplacingCharactersInRange(range, withString: string) refreshUIElements() return false } @IBAction func operatorChanged() { refreshUIElements() } func refreshUIElements() { if zahl1TF.text.lengthOfBytesUsingEncoding(NSASCIIStringEncoding) == 0 || zahl2TF.text.lengthOfBytesUsingEncoding(NSASCIIStringEncoding) == 0 { ergebnisLabel?.text = "Bitte geben Sie beide Zahlen an!" return } let zahl1 = NSString(string:zahl1TF.text).doubleValue let zahl2 = NSString(string:zahl2TF.text).doubleValue switch operatorSC.selectedSegmentIndex { case 0: ergebnisLabel.text = "Ergebnis: \(zahl1 + zahl2)" case 1: ergebnisLabel.text = "Ergebnis: \(zahl1 - zahl2)" case 2: ergebnisLabel.text = "Ergebnis: \(zahl1 * zahl2)" case 3: ergebnisLabel.text = "Ergebnis: \(zahl1 / zahl2)" default: ergebnisLabel.text = "Fehler!" } } }
gpl-2.0
a5d602dce84e22b3b32d9e1fcd52543e
34.092593
134
0.662269
4.101732
false
false
false
false
bitjammer/swift
benchmark/single-source/Sim2DArray.swift
21
1089
//===--- Sim2DArray.swift -------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// struct Array2D { var storage : [Int] let rows : Int let cols: Int init(numRows: Int, numCols: Int) { storage = [Int](repeating: 0, count: numRows * numCols) rows = numRows cols = numCols } } @inline(never) func workload_2DArrayTest(_ A: inout Array2D) { for _ in 0 ..< 10 { for r in 0 ..< A.rows { for c in 0 ..< A.cols { A.storage[r*A.cols+c] = 1 } } } } @inline(never) public func run_Sim2DArray(_ N: Int) { for _ in 0 ..< N { var A = Array2D(numRows:2048, numCols:32) workload_2DArrayTest(&A) } }
apache-2.0
ddb34050155df200db96a9d5daa2a3ee
24.928571
80
0.553719
3.704082
false
false
false
false
whitepixelstudios/Material
Sources/iOS/Grid.swift
1
10026
/* * Copyright (C) 2015 - 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit import Motion @objc(GridAxisDirection) public enum GridAxisDirection: Int { case any case horizontal case vertical } public struct GridAxis { /// The direction the grid lays its views out. public var direction = GridAxisDirection.horizontal /// The rows size. public var rows: Int /// The columns size. public var columns: Int /** Initializer. - Parameter rows: The number of rows, vertical axis the grid will use. - Parameter columns: The number of columns, horizontal axis the grid will use. */ internal init(rows: Int = 12, columns: Int = 12) { self.rows = rows self.columns = columns } } public struct GridOffset { /// The rows size. public var rows: Int /// The columns size. public var columns: Int /** Initializer. - Parameter rows: The number of rows, vertical axis the grid will use. - Parameter columns: The number of columns, horizontal axis the grid will use. */ internal init(rows: Int = 0, columns: Int = 0) { self.rows = rows self.columns = columns } } public struct Grid { /// Context view. internal weak var context: UIView? /// Defer the calculation. public var deferred = false /// Number of rows. public var rows: Int { didSet { reload() } } /// Number of columns. public var columns: Int { didSet { reload() } } /// Offsets for rows and columns. public var offset = GridOffset() { didSet { reload() } } /// The axis in which the Grid is laying out its views. public var axis = GridAxis() { didSet { reload() } } /// Preset inset value for grid. public var layoutEdgeInsetsPreset = EdgeInsetsPreset.none { didSet { layoutEdgeInsets = EdgeInsetsPresetToValue(preset: contentEdgeInsetsPreset) } } /// Insets value for grid. public var layoutEdgeInsets = EdgeInsets.zero { didSet { reload() } } /// Preset inset value for grid. public var contentEdgeInsetsPreset = EdgeInsetsPreset.none { didSet { contentEdgeInsets = EdgeInsetsPresetToValue(preset: contentEdgeInsetsPreset) } } /// Insets value for grid. public var contentEdgeInsets = EdgeInsets.zero { didSet { reload() } } /// A preset wrapper for interim space. public var interimSpacePreset = InterimSpacePreset.none { didSet { interimSpace = InterimSpacePresetToValue(preset: interimSpacePreset) } } /// The space between grid rows and columnss. public var interimSpace: InterimSpace { didSet { reload() } } /// An Array of UIButtons. public var views = [UIView]() { didSet { for v in oldValue { v.removeFromSuperview() } reload() } } /** Initializer. - Parameter rows: The number of rows, vertical axis the grid will use. - Parameter columns: The number of columns, horizontal axis the grid will use. - Parameter interimSpace: The interim space between rows or columns. */ internal init(context: UIView?, rows: Int = 0, columns: Int = 0, interimSpace: InterimSpace = 0) { self.context = context self.rows = rows self.columns = columns self.interimSpace = interimSpace } /// Begins a deferred block. public mutating func begin() { deferred = true } /// Completes a deferred block. public mutating func commit() { deferred = false reload() } /// Reload the button layout. public func reload() { guard !deferred else { return } guard let canvas = context else { return } for v in views { if canvas != v.superview { v.removeFromSuperview() canvas.addSubview(v) } } let count = views.count guard 0 < count else { return } guard 0 < canvas.bounds.width && 0 < canvas.bounds.height else { return } var n = 0 var i = 0 for v in views { // Forces the view to adjust accordingly to size changes, ie: UILabel. (v as? UILabel)?.sizeToFit() switch axis.direction { case .horizontal: let c = 0 == v.grid.columns ? axis.columns / count : v.grid.columns let co = v.grid.offset.columns let w = (canvas.bounds.width - contentEdgeInsets.left - contentEdgeInsets.right - layoutEdgeInsets.left - layoutEdgeInsets.right + interimSpace) / CGFloat(axis.columns) v.frame.origin.x = CGFloat(i + n + co) * w + contentEdgeInsets.left + layoutEdgeInsets.left v.frame.origin.y = contentEdgeInsets.top + layoutEdgeInsets.top v.frame.size.width = w * CGFloat(c) - interimSpace v.frame.size.height = canvas.bounds.height - contentEdgeInsets.top - contentEdgeInsets.bottom - layoutEdgeInsets.top - layoutEdgeInsets.bottom n += c + co - 1 case .vertical: let r = 0 == v.grid.rows ? axis.rows / count : v.grid.rows let ro = v.grid.offset.rows let h = (canvas.bounds.height - contentEdgeInsets.top - contentEdgeInsets.bottom - layoutEdgeInsets.top - layoutEdgeInsets.bottom + interimSpace) / CGFloat(axis.rows) v.frame.origin.x = contentEdgeInsets.left + layoutEdgeInsets.left v.frame.origin.y = CGFloat(i + n + ro) * h + contentEdgeInsets.top + layoutEdgeInsets.top v.frame.size.width = canvas.bounds.width - contentEdgeInsets.left - contentEdgeInsets.right - layoutEdgeInsets.left - layoutEdgeInsets.right v.frame.size.height = h * CGFloat(r) - interimSpace n += r + ro - 1 case .any: let r = 0 == v.grid.rows ? axis.rows / count : v.grid.rows let ro = v.grid.offset.rows let c = 0 == v.grid.columns ? axis.columns / count : v.grid.columns let co = v.grid.offset.columns let w = (canvas.bounds.width - contentEdgeInsets.left - contentEdgeInsets.right - layoutEdgeInsets.left - layoutEdgeInsets.right + interimSpace) / CGFloat(axis.columns) let h = (canvas.bounds.height - contentEdgeInsets.top - contentEdgeInsets.bottom - layoutEdgeInsets.top - layoutEdgeInsets.bottom + interimSpace) / CGFloat(axis.rows) v.frame.origin.x = CGFloat(co) * w + contentEdgeInsets.left + layoutEdgeInsets.left v.frame.origin.y = CGFloat(ro) * h + contentEdgeInsets.top + layoutEdgeInsets.top v.frame.size.width = w * CGFloat(c) - interimSpace v.frame.size.height = h * CGFloat(r) - interimSpace } i += 1 } } } fileprivate var AssociatedInstanceKey: UInt8 = 0 extension UIView { /// Grid reference. public var grid: Grid { get { return AssociatedObject.get(base: self, key: &AssociatedInstanceKey) { return Grid(context: self) } } set(value) { AssociatedObject.set(base: self, key: &AssociatedInstanceKey, value: value) } } /// A reference to grid's layoutEdgeInsetsPreset. open var layoutEdgeInsetsPreset: EdgeInsetsPreset { get { return grid.layoutEdgeInsetsPreset } set(value) { grid.layoutEdgeInsetsPreset = value } } /// A reference to grid's layoutEdgeInsets. @IBInspectable open var layoutEdgeInsets: EdgeInsets { get { return grid.layoutEdgeInsets } set(value) { grid.layoutEdgeInsets = value } } }
bsd-3-clause
a890d91704543a4ea7a4d1cf860ffd54
31.980263
184
0.592559
4.801724
false
false
false
false
Den-Ree/InstagramAPI
src/InstagramAPI/Pods/AlamofireImage/Source/UIButton+AlamofireImage.swift
2
20423
// // UIButton+AlamofireImage.swift // // Copyright (c) 2015-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Alamofire import Foundation #if os(iOS) || os(tvOS) import UIKit extension UIButton { // MARK: - Private - AssociatedKeys private struct AssociatedKey { static var imageDownloader = "af_UIButton.ImageDownloader" static var sharedImageDownloader = "af_UIButton.SharedImageDownloader" static var imageReceipts = "af_UIButton.ImageReceipts" static var backgroundImageReceipts = "af_UIButton.BackgroundImageReceipts" } // MARK: - Properties /// The instance image downloader used to download all images. If this property is `nil`, the `UIButton` will /// fallback on the `af_sharedImageDownloader` for all downloads. The most common use case for needing to use a /// custom instance image downloader is when images are behind different basic auth credentials. public var af_imageDownloader: ImageDownloader? { get { return objc_getAssociatedObject(self, &AssociatedKey.imageDownloader) as? ImageDownloader } set { objc_setAssociatedObject(self, &AssociatedKey.imageDownloader, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /// The shared image downloader used to download all images. By default, this is the default `ImageDownloader` /// instance backed with an `AutoPurgingImageCache` which automatically evicts images from the cache when the memory /// capacity is reached or memory warning notifications occur. The shared image downloader is only used if the /// `af_imageDownloader` is `nil`. public class var af_sharedImageDownloader: ImageDownloader { get { guard let downloader = objc_getAssociatedObject(self, &AssociatedKey.sharedImageDownloader) as? ImageDownloader else { return ImageDownloader.default } return downloader } set { objc_setAssociatedObject(self, &AssociatedKey.sharedImageDownloader, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } private var imageRequestReceipts: [UInt: RequestReceipt] { get { guard let receipts = objc_getAssociatedObject(self, &AssociatedKey.imageReceipts) as? [UInt: RequestReceipt] else { return [:] } return receipts } set { objc_setAssociatedObject(self, &AssociatedKey.imageReceipts, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } private var backgroundImageRequestReceipts: [UInt: RequestReceipt] { get { guard let receipts = objc_getAssociatedObject(self, &AssociatedKey.backgroundImageReceipts) as? [UInt: RequestReceipt] else { return [:] } return receipts } set { objc_setAssociatedObject(self, &AssociatedKey.backgroundImageReceipts, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } // MARK: - Image Downloads /// Asynchronously downloads an image from the specified URL and sets it once the request is finished. /// /// If the image is cached locally, the image is set immediately. Otherwise the specified placehoder image will be /// set immediately, and then the remote image will be set once the image request is finished. /// /// - parameter state: The control state of the button to set the image on. /// - parameter url: The URL used for your image request. /// - parameter placeholderImage: The image to be set initially until the image request finished. If `nil`, the /// image will not change its image until the image request finishes. Defaults /// to `nil`. /// - parameter filter: The image filter applied to the image after the image request is finished. /// Defaults to `nil`. /// - parameter progress: The closure to be executed periodically during the lifecycle of the request. /// Defaults to `nil`. /// - parameter progressQueue: The dispatch queue to call the progress closure on. Defaults to the main queue. /// - parameter completion: A closure to be executed when the image request finishes. The closure takes a /// single response value containing either the image or the error that occurred. If /// the image was returned from the image cache, the response will be `nil`. Defaults /// to `nil`. public func af_setImage( for state: UIControlState, url: URL, placeholderImage: UIImage? = nil, filter: ImageFilter? = nil, progress: ImageDownloader.ProgressHandler? = nil, progressQueue: DispatchQueue = DispatchQueue.main, completion: ((DataResponse<UIImage>) -> Void)? = nil) { af_setImage( for: state, urlRequest: urlRequest(with: url), placeholderImage: placeholderImage, filter: filter, progress: progress, progressQueue: progressQueue, completion: completion ) } /// Asynchronously downloads an image from the specified URL request and sets it once the request is finished. /// /// If the image is cached locally, the image is set immediately. Otherwise the specified placehoder image will be /// set immediately, and then the remote image will be set once the image request is finished. /// /// - parameter state: The control state of the button to set the image on. /// - parameter urlRequest: The URL request. /// - parameter placeholderImage: The image to be set initially until the image request finished. If `nil`, the /// image will not change its image until the image request finishes. Defaults /// to `nil`. /// - parameter filter: The image filter applied to the image after the image request is finished. /// Defaults to `nil`. /// - parameter progress: The closure to be executed periodically during the lifecycle of the request. /// Defaults to `nil`. /// - parameter progressQueue: The dispatch queue to call the progress closure on. Defaults to the main queue. /// - parameter completion: A closure to be executed when the image request finishes. The closure takes a /// single response value containing either the image or the error that occurred. If /// the image was returned from the image cache, the response will be `nil`. Defaults /// to `nil`. public func af_setImage( for state: UIControlState, urlRequest: URLRequestConvertible, placeholderImage: UIImage? = nil, filter: ImageFilter? = nil, progress: ImageDownloader.ProgressHandler? = nil, progressQueue: DispatchQueue = DispatchQueue.main, completion: ((DataResponse<UIImage>) -> Void)? = nil) { guard !isImageURLRequest(urlRequest, equalToActiveRequestURLForState: state) else { return } af_cancelImageRequest(for: state) let imageDownloader = af_imageDownloader ?? UIButton.af_sharedImageDownloader let imageCache = imageDownloader.imageCache // Use the image from the image cache if it exists if let request = urlRequest.urlRequest, let image = imageCache?.image(for: request, withIdentifier: filter?.identifier) { let response = DataResponse<UIImage>( request: urlRequest.urlRequest, response: nil, data: nil, result: .success(image) ) completion?(response) setImage(image, for: state) return } // Set the placeholder since we're going to have to download if let placeholderImage = placeholderImage { setImage(placeholderImage, for: state) } // Generate a unique download id to check whether the active request has changed while downloading let downloadID = UUID().uuidString // Download the image, then set the image for the control state let requestReceipt = imageDownloader.download( urlRequest, receiptID: downloadID, filter: filter, progress: progress, progressQueue: progressQueue, completion: { [weak self] response in guard let strongSelf = self else { return } completion?(response) guard strongSelf.isImageURLRequest(response.request, equalToActiveRequestURLForState: state) && strongSelf.imageRequestReceipt(for: state)?.receiptID == downloadID else { return } if let image = response.result.value { strongSelf.setImage(image, for: state) } strongSelf.setImageRequestReceipt(nil, for: state) } ) setImageRequestReceipt(requestReceipt, for: state) } /// Cancels the active download request for the image, if one exists. public func af_cancelImageRequest(for state: UIControlState) { guard let receipt = imageRequestReceipt(for: state) else { return } let imageDownloader = af_imageDownloader ?? UIButton.af_sharedImageDownloader imageDownloader.cancelRequest(with: receipt) setImageRequestReceipt(nil, for: state) } // MARK: - Background Image Downloads /// Asynchronously downloads an image from the specified URL and sets it once the request is finished. /// /// If the image is cached locally, the image is set immediately. Otherwise the specified placehoder image will be /// set immediately, and then the remote image will be set once the image request is finished. /// /// - parameter state: The control state of the button to set the image on. /// - parameter url: The URL used for the image request. /// - parameter placeholderImage: The image to be set initially until the image request finished. If `nil`, the /// background image will not change its image until the image request finishes. /// Defaults to `nil`. /// - parameter filter: The image filter applied to the image after the image request is finished. /// Defaults to `nil`. /// - parameter progress: The closure to be executed periodically during the lifecycle of the request. /// Defaults to `nil`. /// - parameter progressQueue: The dispatch queue to call the progress closure on. Defaults to the main queue. /// - parameter completion: A closure to be executed when the image request finishes. The closure takes a /// single response value containing either the image or the error that occurred. If /// the image was returned from the image cache, the response will be `nil`. Defaults /// to `nil`. public func af_setBackgroundImage( for state: UIControlState, url: URL, placeholderImage: UIImage? = nil, filter: ImageFilter? = nil, progress: ImageDownloader.ProgressHandler? = nil, progressQueue: DispatchQueue = DispatchQueue.main, completion: ((DataResponse<UIImage>) -> Void)? = nil) { af_setBackgroundImage( for: state, urlRequest: urlRequest(with: url), placeholderImage: placeholderImage, filter: filter, progress: progress, progressQueue: progressQueue, completion: completion ) } /// Asynchronously downloads an image from the specified URL request and sets it once the request is finished. /// /// If the image is cached locally, the image is set immediately. Otherwise the specified placehoder image will be /// set immediately, and then the remote image will be set once the image request is finished. /// /// - parameter state: The control state of the button to set the image on. /// - parameter urlRequest: The URL request. /// - parameter placeholderImage: The image to be set initially until the image request finished. If `nil`, the /// background image will not change its image until the image request finishes. /// Defaults to `nil`. /// - parameter filter: The image filter applied to the image after the image request is finished. /// Defaults to `nil`. /// - parameter progress: The closure to be executed periodically during the lifecycle of the request. /// Defaults to `nil`. /// - parameter progressQueue: The dispatch queue to call the progress closure on. Defaults to the main queue. /// - parameter completion: A closure to be executed when the image request finishes. The closure takes a /// single response value containing either the image or the error that occurred. If /// the image was returned from the image cache, the response will be `nil`. Defaults /// to `nil`. public func af_setBackgroundImage( for state: UIControlState, urlRequest: URLRequestConvertible, placeholderImage: UIImage? = nil, filter: ImageFilter? = nil, progress: ImageDownloader.ProgressHandler? = nil, progressQueue: DispatchQueue = DispatchQueue.main, completion: ((DataResponse<UIImage>) -> Void)? = nil) { guard !isImageURLRequest(urlRequest, equalToActiveRequestURLForState: state) else { return } af_cancelBackgroundImageRequest(for: state) let imageDownloader = af_imageDownloader ?? UIButton.af_sharedImageDownloader let imageCache = imageDownloader.imageCache // Use the image from the image cache if it exists if let request = urlRequest.urlRequest, let image = imageCache?.image(for: request, withIdentifier: filter?.identifier) { let response = DataResponse<UIImage>( request: urlRequest.urlRequest, response: nil, data: nil, result: .success(image) ) completion?(response) setBackgroundImage(image, for: state) return } // Set the placeholder since we're going to have to download if let placeholderImage = placeholderImage { self.setBackgroundImage(placeholderImage, for: state) } // Generate a unique download id to check whether the active request has changed while downloading let downloadID = UUID().uuidString // Download the image, then set the image for the control state let requestReceipt = imageDownloader.download( urlRequest, receiptID: downloadID, filter: nil, progress: progress, progressQueue: progressQueue, completion: { [weak self] response in guard let strongSelf = self else { return } completion?(response) guard strongSelf.isBackgroundImageURLRequest(response.request, equalToActiveRequestURLForState: state) && strongSelf.backgroundImageRequestReceipt(for: state)?.receiptID == downloadID else { return } if let image = response.result.value { strongSelf.setBackgroundImage(image, for: state) } strongSelf.setBackgroundImageRequestReceipt(nil, for: state) } ) setBackgroundImageRequestReceipt(requestReceipt, for: state) } /// Cancels the active download request for the background image, if one exists. public func af_cancelBackgroundImageRequest(for state: UIControlState) { guard let receipt = backgroundImageRequestReceipt(for: state) else { return } let imageDownloader = af_imageDownloader ?? UIButton.af_sharedImageDownloader imageDownloader.cancelRequest(with: receipt) setBackgroundImageRequestReceipt(nil, for: state) } // MARK: - Internal - Image Request Receipts func imageRequestReceipt(for state: UIControlState) -> RequestReceipt? { guard let receipt = imageRequestReceipts[state.rawValue] else { return nil } return receipt } func setImageRequestReceipt(_ receipt: RequestReceipt?, for state: UIControlState) { var receipts = imageRequestReceipts receipts[state.rawValue] = receipt imageRequestReceipts = receipts } // MARK: - Internal - Background Image Request Receipts func backgroundImageRequestReceipt(for state: UIControlState) -> RequestReceipt? { guard let receipt = backgroundImageRequestReceipts[state.rawValue] else { return nil } return receipt } func setBackgroundImageRequestReceipt(_ receipt: RequestReceipt?, for state: UIControlState) { var receipts = backgroundImageRequestReceipts receipts[state.rawValue] = receipt backgroundImageRequestReceipts = receipts } // MARK: - Private - URL Request Helpers private func isImageURLRequest( _ urlRequest: URLRequestConvertible?, equalToActiveRequestURLForState state: UIControlState) -> Bool { if let currentURL = imageRequestReceipt(for: state)?.request.task?.originalRequest?.url, let requestURL = urlRequest?.urlRequest?.url, currentURL == requestURL { return true } return false } private func isBackgroundImageURLRequest( _ urlRequest: URLRequestConvertible?, equalToActiveRequestURLForState state: UIControlState) -> Bool { if let currentRequestURL = backgroundImageRequestReceipt(for: state)?.request.task?.originalRequest?.url, let requestURL = urlRequest?.urlRequest?.url, currentRequestURL == requestURL { return true } return false } private func urlRequest(with url: URL) -> URLRequest { var urlRequest = URLRequest(url: url) for mimeType in DataRequest.acceptableImageContentTypes { urlRequest.addValue(mimeType, forHTTPHeaderField: "Accept") } return urlRequest } } #endif
mit
f573819a5892f59e921d2587b9c9f530
44.083885
128
0.626402
5.584632
false
false
false
false
hanhailong/practice-swift
Games/TextShooter/TextShooter/PlayerNode.swift
2
2426
// // PlayerNode.swift // TextShooter // // Created by Domenico on 01/05/15. // Copyright (c) 2015 Domenico. All rights reserved. // import UIKit import SpriteKit import Foundation class PlayerNode: SKNode { override init() { super.init() name = "Player \(self)" initNodeGraph() initPhysicsBody() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } private func initNodeGraph() { let label = SKLabelNode(fontNamed: "Courier") label.fontColor = SKColor.darkGrayColor() label.fontSize = 40 label.text = "v" label.zRotation = CGFloat(M_PI) label.name = "label" self.addChild(label) } func moveToward(location: CGPoint) { removeActionForKey("movement") removeActionForKey("wobbling") let distance = pointDistance(position, location) let screenWidth = UIScreen.mainScreen().bounds.size.width let duration = NSTimeInterval(2 * distance/screenWidth) runAction(SKAction.moveTo(location, duration: duration), withKey:"movement") // Wobble actions let wobbleTime = 0.3 let halfWobbleTime = wobbleTime/2 let wobbling = SKAction.sequence([ SKAction.scaleXTo(0.2, duration: halfWobbleTime), SKAction.scaleXTo(1.0, duration: halfWobbleTime) ]) let wobbleCount = Int(duration/wobbleTime) runAction(SKAction.repeatAction(wobbling, count: wobbleCount), withKey:"wobbling") } private func initPhysicsBody() { let body = SKPhysicsBody(rectangleOfSize: CGSizeMake(20, 20)) body.affectedByGravity = false body.categoryBitMask = PlayerCategory body.contactTestBitMask = EnemyCategory body.collisionBitMask = 0 // Not affected from gravity body.fieldBitMask = 0 physicsBody = body } override func receiveAttacker(attacker: SKNode, contact: SKPhysicsContact) { let path = NSBundle.mainBundle().pathForResource("EnemyExplosion", ofType: "sks") let explosion = NSKeyedUnarchiver.unarchiveObjectWithFile(path!) as! SKEmitterNode explosion.numParticlesToEmit = 50 explosion.position = contact.contactPoint scene!.addChild(explosion) } }
mit
dfb3d7805c61d3a17f7fbb0687cfdc40
29.708861
80
0.62366
4.78501
false
false
false
false
sachin004/firefox-ios
Storage/ThirdParty/SwiftData.swift
1
33513
/* 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/. */ /* * This is a heavily modified version of SwiftData.swift by Ryan Fowler * This has been enhanced to support custom files, correct binding, versioning, * and a streaming results via Cursors. The API has also been changed to use NSError, Cursors, and * to force callers to request a connection before executing commands. Database creation helpers, savepoint * helpers, image support, and other features have been removed. */ // SwiftData.swift // // Copyright (c) 2014 Ryan Fowler // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import UIKit import Shared import XCGLogger private let DatabaseBusyTimeout: Int32 = 3 * 1000 private let log = Logger.syncLogger /** * Handle to a SQLite database. * Each instance holds a single connection that is shared across all queries. */ public class SwiftData { let filename: String static var EnableWAL = true static var EnableForeignKeys = true /// Used to keep track of the corrupted databases we've logged. static var corruptionLogsWritten = Set<String>() /// Used for testing. static var ReuseConnections = true /// For thread-safe access to the shared connection. private let sharedConnectionQueue: dispatch_queue_t /// Shared connection to this database. private var sharedConnection: SQLiteDBConnection? private var key: String? = nil private var prevKey: String? = nil init(filename: String, key: String? = nil, prevKey: String? = nil) { self.filename = filename self.sharedConnectionQueue = dispatch_queue_create("SwiftData queue: \(filename)", DISPATCH_QUEUE_SERIAL) // Ensure that multi-thread mode is enabled by default. // See https://www.sqlite.org/threadsafe.html assert(sqlite3_threadsafe() == 2) self.key = key self.prevKey = prevKey } private func getSharedConnection() -> SQLiteDBConnection? { var connection: SQLiteDBConnection? dispatch_sync(sharedConnectionQueue) { if self.sharedConnection == nil { log.debug(">>> Creating shared SQLiteDBConnection for \(self.filename) on thread \(NSThread.currentThread()).") self.sharedConnection = SQLiteDBConnection(filename: self.filename, flags: SwiftData.Flags.ReadWriteCreate.toSQL(), key: self.key, prevKey: self.prevKey) } connection = self.sharedConnection } return connection } /** * The real meat of all the execute methods. This is used internally to open and * close a database connection and run a block of code inside it. */ public func withConnection(flags: SwiftData.Flags, synchronous: Bool=true, cb: (db: SQLiteDBConnection) -> NSError?) -> NSError? { let conn: SQLiteDBConnection? if SwiftData.ReuseConnections { conn = getSharedConnection() } else { log.debug(">>> Creating non-shared SQLiteDBConnection for \(self.filename) on thread \(NSThread.currentThread()).") conn = SQLiteDBConnection(filename: filename, flags: flags.toSQL(), key: self.key, prevKey: self.prevKey) } guard let connection = conn else { return NSError(domain: "mozilla", code: 0, userInfo: [NSLocalizedDescriptionKey: "Could not create a connection"]) } if synchronous { var error: NSError? = nil dispatch_sync(connection.queue) { error = cb(db: connection) } return error } dispatch_async(connection.queue) { cb(db: connection) } return nil } public func transaction(transactionClosure: (db: SQLiteDBConnection) -> Bool) -> NSError? { return self.transaction(synchronous: true, transactionClosure: transactionClosure) } /** * Helper for opening a connection, starting a transaction, and then running a block of code inside it. * The code block can return true if the transaction should be committed. False if we should roll back. */ public func transaction(synchronous synchronous: Bool=true, transactionClosure: (db: SQLiteDBConnection) -> Bool) -> NSError? { return withConnection(SwiftData.Flags.ReadWriteCreate, synchronous: synchronous) { db in if let err = db.executeChange("BEGIN EXCLUSIVE") { log.warning("BEGIN EXCLUSIVE failed.") return err } if transactionClosure(db: db) { log.verbose("Op in transaction succeeded. Committing.") if let err = db.executeChange("COMMIT") { log.error("COMMIT failed. Rolling back.") db.executeChange("ROLLBACK") return err } } else { log.debug("Op in transaction failed. Rolling back.") if let err = db.executeChange("ROLLBACK") { return err } } return nil } } func close() { dispatch_sync(sharedConnectionQueue) { if self.sharedConnection != nil { self.sharedConnection?.closeCustomConnection() } self.sharedConnection = nil } } public enum Flags { case ReadOnly case ReadWrite case ReadWriteCreate private func toSQL() -> Int32 { switch self { case .ReadOnly: return SQLITE_OPEN_READONLY case .ReadWrite: return SQLITE_OPEN_READWRITE case .ReadWriteCreate: return SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE } } } } /** * Wrapper class for a SQLite statement. * This class helps manage the statement lifecycle. By holding a reference to the SQL connection, we ensure * the connection is never deinitialized while the statement is active. This class is responsible for * finalizing the SQL statement once it goes out of scope. */ private class SQLiteDBStatement { var pointer: COpaquePointer = nil private let connection: SQLiteDBConnection init(connection: SQLiteDBConnection, query: String, args: [AnyObject?]?) throws { self.connection = connection let status = sqlite3_prepare_v2(connection.sqliteDB, query, -1, &pointer, nil) if status != SQLITE_OK { throw connection.createErr("During: SQL Prepare \(query)", status: Int(status)) } if let args = args, let bindError = bind(args) { throw bindError } } /// Binds arguments to the statement. private func bind(objects: [AnyObject?]) -> NSError? { let count = Int(sqlite3_bind_parameter_count(pointer)) if (count < objects.count) { return connection.createErr("During: Bind", status: 202) } if (count > objects.count) { return connection.createErr("During: Bind", status: 201) } for (index, obj) in objects.enumerate() { var status: Int32 = SQLITE_OK // Doubles also pass obj as Int, so order is important here. if obj is Double { status = sqlite3_bind_double(pointer, Int32(index+1), obj as! Double) } else if obj is Int { status = sqlite3_bind_int(pointer, Int32(index+1), Int32(obj as! Int)) } else if obj is Bool { status = sqlite3_bind_int(pointer, Int32(index+1), (obj as! Bool) ? 1 : 0) } else if obj is String { typealias CFunction = @convention(c) (UnsafeMutablePointer<()>) -> Void let transient = unsafeBitCast(-1, CFunction.self) status = sqlite3_bind_text(pointer, Int32(index+1), (obj as! String).cStringUsingEncoding(NSUTF8StringEncoding)!, -1, transient) } else if obj is NSData { status = sqlite3_bind_blob(pointer, Int32(index+1), (obj as! NSData).bytes, -1, nil) } else if obj is NSDate { let timestamp = (obj as! NSDate).timeIntervalSince1970 status = sqlite3_bind_double(pointer, Int32(index+1), timestamp) } else if obj === nil { status = sqlite3_bind_null(pointer, Int32(index+1)) } if status != SQLITE_OK { return connection.createErr("During: Bind", status: Int(status)) } } return nil } func close() { if nil != self.pointer { sqlite3_finalize(self.pointer) self.pointer = nil } } deinit { if nil != self.pointer { sqlite3_finalize(self.pointer) } } } public class SQLiteDBConnection { private var sqliteDB: COpaquePointer = nil private let filename: String private let debug_enabled = false private let queue: dispatch_queue_t public var version: Int { get { let res = executeQueryUnsafe("PRAGMA user_version", factory: IntFactory) return res[0] ?? 0 } set { executeChange("PRAGMA user_version = \(newValue)") } } private func setKey(key: String?) -> NSError? { sqlite3_key(sqliteDB, key ?? "", Int32((key ?? "").characters.count)) let cursor = executeQuery("SELECT count(*) FROM sqlite_master;", factory: IntFactory, withArgs: nil) if cursor.status != .Success { return NSError(domain: "mozilla", code: 0, userInfo: [NSLocalizedDescriptionKey: "Invalid key"]) } return nil } private func reKey(oldKey: String?, newKey: String?) -> NSError? { sqlite3_key(sqliteDB, oldKey ?? "", Int32((oldKey ?? "").characters.count)) sqlite3_rekey(sqliteDB, newKey ?? "", Int32((newKey ?? "").characters.count)) // Check that the new key actually works sqlite3_key(sqliteDB, newKey ?? "", Int32((newKey ?? "").characters.count)) let cursor = executeQuery("SELECT count(*) FROM sqlite_master;", factory: IntFactory, withArgs: nil) if cursor.status != .Success { return NSError(domain: "mozilla", code: 0, userInfo: [NSLocalizedDescriptionKey: "Rekey failed"]) } return nil } func interrupt() { log.debug("Interrupt") sqlite3_interrupt(sqliteDB) } private func pragma<T: Equatable>(pragma: String, expected: T?, factory: SDRow -> T, message: String) { let cursorResult = self.pragma(pragma, factory: factory) assert(cursorResult == expected, message) } private func pragma<T>(pragma: String, factory: SDRow -> T) -> T? { let cursor = executeQueryUnsafe("PRAGMA \(pragma)", factory: factory) return cursor[0] } init?(filename: String, flags: Int32, key: String? = nil, prevKey: String? = nil) { log.debug("Opening connection to \(filename).") self.filename = filename self.queue = dispatch_queue_create("SQLite connection: \(filename)", DISPATCH_QUEUE_SERIAL) if let failure = openWithFlags(flags) { log.warning("Opening connection to \(filename) failed: \(failure).") return nil } // Setting the key need to be the first thing done with the database. if let _ = setKey(key) { closeCustomConnection() if let _ = openWithFlags(flags) { return nil } if let _ = reKey(prevKey, newKey: key) { log.error("Unable to encrypt database") return nil } } // // For where these values come from, see Bug 1213623. // let currentPageSize = executeQueryUnsafe("PRAGMA page_size", factory: IntFactory)[0] let desiredPageSize = 32 * 1024 // This has to be done without WAL, so we always hop into rollback/delete journal mode. if currentPageSize != desiredPageSize { pragma("journal_mode=DELETE", expected: "delete", factory: StringFactory, message: "delete journal mode set") pragma("page_size=\(desiredPageSize)", expected: nil, factory: IntFactory, message: "Page size set") log.info("Vacuuming to alter database page size from \(currentPageSize) to \(desiredPageSize).") if let err = self.vacuum() { log.error("Vacuuming failed: \(err).") } else { log.debug("Vacuuming succeeded.") } } if SwiftData.EnableWAL { log.info("Enabling WAL mode.") let desiredPagesPerJournal = 16 let desiredCheckpointSize = desiredPagesPerJournal * desiredPageSize let desiredJournalSizeLimit = 3 * desiredCheckpointSize pragma("journal_mode=WAL", expected: "wal", factory: StringFactory, message: "WAL journal mode set") pragma("wal_autocheckpoint=\(desiredPagesPerJournal)", expected: desiredPagesPerJournal, factory: IntFactory, message: "WAL autocheckpoint set") pragma("journal_size_limit=\(desiredJournalSizeLimit)", expected: desiredJournalSizeLimit, factory: IntFactory, message: "WAL journal size limit set") } if SwiftData.EnableForeignKeys { executeQueryUnsafe("PRAGMA foreign_keys=ON", factory: IntFactory) } // Retry queries before returning locked errors. sqlite3_busy_timeout(sqliteDB, DatabaseBusyTimeout) } deinit { log.debug("deinit: closing connection on thread \(NSThread.currentThread()).") closeCustomConnection() } var lastInsertedRowID: Int { return Int(sqlite3_last_insert_rowid(sqliteDB)) } var numberOfRowsModified: Int { return Int(sqlite3_changes(sqliteDB)) } /** * Blindly attempts a WAL checkpoint on all attached databases. */ func checkpoint(mode: Int32 = SQLITE_CHECKPOINT_PASSIVE) { guard sqliteDB != nil else { log.warning("Trying to checkpoint a nil DB!") return } log.debug("Running WAL checkpoint on \(self.filename) on thread \(NSThread.currentThread()).") sqlite3_wal_checkpoint_v2(sqliteDB, nil, mode, nil, nil) log.debug("WAL checkpoint done on \(self.filename).") } func vacuum() -> NSError? { return self.executeChange("VACUUM") } /// Creates an error from a sqlite status. Will print to the console if debug_enabled is set. /// Do not call this unless you're going to return this error. private func createErr(description: String, status: Int) -> NSError { var msg = SDError.errorMessageFromCode(status) if (debug_enabled) { log.debug("SwiftData Error -> \(description)") log.debug(" -> Code: \(status) - \(msg)") } if let errMsg = String.fromCString(sqlite3_errmsg(sqliteDB)) { msg += " " + errMsg if (debug_enabled) { log.debug(" -> Details: \(errMsg)") } } return NSError(domain: "org.mozilla", code: status, userInfo: [NSLocalizedDescriptionKey: msg]) } /// Open the connection. This is called when the db is created. You should not call it yourself. private func openWithFlags(flags: Int32) -> NSError? { let status = sqlite3_open_v2(filename.cStringUsingEncoding(NSUTF8StringEncoding)!, &sqliteDB, flags, nil) if status != SQLITE_OK { return createErr("During: Opening Database with Flags", status: Int(status)) } return nil } /// Closes a connection. This is called via deinit. Do not call this yourself. private func closeCustomConnection() -> NSError? { log.debug("Closing custom connection for \(self.filename) on \(NSThread.currentThread()).") // Make sure we don't try to call sqlite3_close multiple times. // TODO: add a lock here? guard self.sqliteDB != nil else { log.warning("Connection was nil.") return nil } let status = sqlite3_close(self.sqliteDB) log.debug("Closed \(self.filename).") self.sqliteDB = nil if status != SQLITE_OK { log.error("Got \(status) while closing.") return createErr("During: closing database with flags", status: Int(status)) } return nil } /// Executes a change on the database. func executeChange(sqlStr: String, withArgs args: [AnyObject?]? = nil) -> NSError? { var error: NSError? let statement: SQLiteDBStatement? do { statement = try SQLiteDBStatement(connection: self, query: sqlStr, args: args) } catch let error1 as NSError { error = error1 statement = nil } if let error = error { // Special case: Write additional info to the database log in the case of a database corruption. if error.code == Int(SQLITE_CORRUPT) { writeCorruptionInfoForDBNamed(filename, toLogger: Logger.corruptLogger) } log.error("SQL error: \(error.localizedDescription) for SQL \(sqlStr).") statement?.close() return error } let status = sqlite3_step(statement!.pointer) if status != SQLITE_DONE && status != SQLITE_OK { error = createErr("During: SQL Step \(sqlStr)", status: Int(status)) } statement?.close() return error } /// Queries the database. /// Returns a cursor pre-filled with the complete result set. func executeQuery<T>(sqlStr: String, factory: ((SDRow) -> T), withArgs args: [AnyObject?]? = nil) -> Cursor<T> { var error: NSError? let statement: SQLiteDBStatement? do { statement = try SQLiteDBStatement(connection: self, query: sqlStr, args: args) } catch let error1 as NSError { error = error1 statement = nil } if let error = error { // Special case: Write additional info to the database log in the case of a database corruption. if error.code == Int(SQLITE_CORRUPT) { writeCorruptionInfoForDBNamed(filename, toLogger: Logger.corruptLogger) } log.error("SQL error: \(error.localizedDescription).") return Cursor<T>(err: error) } let cursor = FilledSQLiteCursor<T>(statement: statement!, factory: factory) // Close, not reset -- this isn't going to be reused, and the cursor has // consumed everything. statement?.close() return cursor } func writeCorruptionInfoForDBNamed(dbFilename: String, toLogger logger: XCGLogger) { dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { guard !SwiftData.corruptionLogsWritten.contains(dbFilename) else { return } logger.error("Corrupt DB Detected! - DB Filename: \(dbFilename)") let dbFileSize = ("file://\(dbFilename)".asURL)?.allocatedFileSize() ?? 0 logger.error("DB file size: \(dbFileSize) bytes") if let message = self.pragma("integrity_check", factory: StringFactory) { logger.error("Integrity check message: \(message)") } // Write call stack logger.error("Call stack: \(NSThread.callStackSymbols())") // Write open file handles let openDescriptors = FSUtils.openFileDescriptors() logger.error("Open file descriptors: \(openDescriptors)") SwiftData.corruptionLogsWritten.insert(dbFilename) } } /** * Queries the database. * Returns a live cursor that holds the query statement and database connection. * Instances of this class *must not* leak outside of the connection queue! */ func executeQueryUnsafe<T>(sqlStr: String, factory: ((SDRow) -> T), withArgs args: [AnyObject?]? = nil) -> Cursor<T> { var error: NSError? let statement: SQLiteDBStatement? do { statement = try SQLiteDBStatement(connection: self, query: sqlStr, args: args) } catch let error1 as NSError { error = error1 statement = nil } if let error = error { return Cursor(err: error) } return LiveSQLiteCursor(statement: statement!, factory: factory) } } /// Helper for queries that return a single integer result. func IntFactory(row: SDRow) -> Int { return row[0] as! Int } /// Helper for queries that return a single String result. func StringFactory(row: SDRow) -> String { return row[0] as! String } /// Wrapper around a statement for getting data from a row. This provides accessors for subscript indexing /// and a generator for iterating over columns. class SDRow: SequenceType { // The sqlite statement this row came from. private let statement: SQLiteDBStatement // The columns of this database. The indices of these are assumed to match the indices // of the statement. private let columnNames: [String] private init(statement: SQLiteDBStatement, columns: [String]) { self.statement = statement self.columnNames = columns } // Return the value at this index in the row private func getValue(index: Int) -> AnyObject? { let i = Int32(index) let type = sqlite3_column_type(statement.pointer, i) var ret: AnyObject? = nil switch type { case SQLITE_NULL, SQLITE_INTEGER: ret = NSNumber(longLong: sqlite3_column_int64(statement.pointer, i)) case SQLITE_TEXT: let text = UnsafePointer<Int8>(sqlite3_column_text(statement.pointer, i)) ret = String.fromCString(text) case SQLITE_BLOB: let blob = sqlite3_column_blob(statement.pointer, i) if blob != nil { let size = sqlite3_column_bytes(statement.pointer, i) ret = NSData(bytes: blob, length: Int(size)) } case SQLITE_FLOAT: ret = Double(sqlite3_column_double(statement.pointer, i)) default: log.warning("SwiftData Warning -> Column: \(index) is of an unrecognized type, returning nil") } return ret } // Accessor getting column 'key' in the row subscript(key: Int) -> AnyObject? { return getValue(key) } // Accessor getting a named column in the row. This (currently) depends on // the columns array passed into this Row to find the correct index. subscript(key: String) -> AnyObject? { get { if let index = columnNames.indexOf(key) { return getValue(index) } return nil } } // Allow iterating through the row. This is currently broken. func generate() -> AnyGenerator<Any> { let nextIndex = 0 return anyGenerator() { // This crashes the compiler. Yay! if (nextIndex < self.columnNames.count) { return nil // self.getValue(nextIndex) } return nil } } } /// Helper for pretty printing SQL (and other custom) error codes. private struct SDError { private static func errorMessageFromCode(errorCode: Int) -> String { switch errorCode { case -1: return "No error" // SQLite error codes and descriptions as per: http://www.sqlite.org/c3ref/c_abort.html case 0: return "Successful result" case 1: return "SQL error or missing database" case 2: return "Internal logic error in SQLite" case 3: return "Access permission denied" case 4: return "Callback routine requested an abort" case 5: return "The database file is busy" case 6: return "A table in the database is locked" case 7: return "A malloc() failed" case 8: return "Attempt to write a readonly database" case 9: return "Operation terminated by sqlite3_interrupt()" case 10: return "Some kind of disk I/O error occurred" case 11: return "The database disk image is malformed" case 12: return "Unknown opcode in sqlite3_file_control()" case 13: return "Insertion failed because database is full" case 14: return "Unable to open the database file" case 15: return "Database lock protocol error" case 16: return "Database is empty" case 17: return "The database schema changed" case 18: return "String or BLOB exceeds size limit" case 19: return "Abort due to constraint violation" case 20: return "Data type mismatch" case 21: return "Library used incorrectly" case 22: return "Uses OS features not supported on host" case 23: return "Authorization denied" case 24: return "Auxiliary database format error" case 25: return "2nd parameter to sqlite3_bind out of range" case 26: return "File opened that is not a database file" case 27: return "Notifications from sqlite3_log()" case 28: return "Warnings from sqlite3_log()" case 100: return "sqlite3_step() has another row ready" case 101: return "sqlite3_step() has finished executing" // Custom SwiftData errors // Binding errors case 201: return "Not enough objects to bind provided" case 202: return "Too many objects to bind provided" // Custom connection errors case 301: return "A custom connection is already open" case 302: return "Cannot open a custom connection inside a transaction" case 303: return "Cannot open a custom connection inside a savepoint" case 304: return "A custom connection is not currently open" case 305: return "Cannot close a custom connection inside a transaction" case 306: return "Cannot close a custom connection inside a savepoint" // Index and table errors case 401: return "At least one column name must be provided" case 402: return "Error extracting index names from sqlite_master" case 403: return "Error extracting table names from sqlite_master" // Transaction and savepoint errors case 501: return "Cannot begin a transaction within a savepoint" case 502: return "Cannot begin a transaction within another transaction" // Unknown error default: return "Unknown error" } } } /// Provides access to the result set returned by a database query. /// The entire result set is cached, so this does not retain a reference /// to the statement or the database connection. private class FilledSQLiteCursor<T>: ArrayCursor<T> { private init(statement: SQLiteDBStatement, factory: (SDRow) -> T) { var status = CursorStatus.Success var statusMessage = "" let data = FilledSQLiteCursor.getValues(statement, factory: factory, status: &status, statusMessage: &statusMessage) super.init(data: data, status: status, statusMessage: statusMessage) } /// Return an array with the set of results and release the statement. private class func getValues(statement: SQLiteDBStatement, factory: (SDRow) -> T, inout status: CursorStatus, inout statusMessage: String) -> [T] { var rows = [T]() var count = 0 status = CursorStatus.Success statusMessage = "Success" var columns = [String]() let columnCount = sqlite3_column_count(statement.pointer) for i in 0..<columnCount { let columnName = String.fromCString(sqlite3_column_name(statement.pointer, i))! columns.append(columnName) } while true { let sqlStatus = sqlite3_step(statement.pointer) if sqlStatus != SQLITE_ROW { if sqlStatus != SQLITE_DONE { // NOTE: By setting our status to failure here, we'll report our count as zero, // regardless of how far we've read at this point. status = CursorStatus.Failure statusMessage = SDError.errorMessageFromCode(Int(sqlStatus)) } break } count++ let row = SDRow(statement: statement, columns: columns) let result = factory(row) rows.append(result) } return rows } } /// Wrapper around a statement to help with iterating through the results. private class LiveSQLiteCursor<T>: Cursor<T> { private var statement: SQLiteDBStatement! // Function for generating objects of type T from a row. private let factory: (SDRow) -> T // Status of the previous fetch request. private var sqlStatus: Int32 = 0 // Number of rows in the database // XXX - When Cursor becomes an interface, this should be a normal property, but right now // we can't override the Cursor getter for count with a stored property. private var _count: Int = 0 override var count: Int { get { if status != .Success { return 0 } return _count } } private var position: Int = -1 { didSet { // If we're already there, shortcut out. if (oldValue == position) { return } var stepStart = oldValue // If we're currently somewhere in the list after this position // we'll have to jump back to the start. if (position < oldValue) { sqlite3_reset(self.statement.pointer) stepStart = -1 } // Now step up through the list to the requested position for _ in stepStart..<position { sqlStatus = sqlite3_step(self.statement.pointer) } } } init(statement: SQLiteDBStatement, factory: (SDRow) -> T) { self.factory = factory self.statement = statement // The only way I know to get a count. Walk through the entire statement to see how many rows there are. var count = 0 self.sqlStatus = sqlite3_step(statement.pointer) while self.sqlStatus != SQLITE_DONE { count++ self.sqlStatus = sqlite3_step(statement.pointer) } sqlite3_reset(statement.pointer) self._count = count super.init(status: .Success, msg: "success") } // Helper for finding all the column names in this statement. private lazy var columns: [String] = { // This untangles all of the columns and values for this row when its created let columnCount = sqlite3_column_count(self.statement.pointer) var columns = [String]() for var i: Int32 = 0; i < columnCount; ++i { let columnName = String.fromCString(sqlite3_column_name(self.statement.pointer, i))! columns.append(columnName) } return columns }() override subscript(index: Int) -> T? { get { if status != .Success { return nil } self.position = index if self.sqlStatus != SQLITE_ROW { return nil } let row = SDRow(statement: statement, columns: self.columns) return self.factory(row) } } override func close() { statement = nil super.close() } }
mpl-2.0
0337a3562c739f949fa9a970de218546
35.787047
169
0.603587
4.771892
false
false
false
false
Sweebi/tvProgress
tvProgress/Events/tvProgress+Events.swift
1
2266
// // tvProgress+Events.swift // tvProgress // // Created by Antoine Cormery on 09/05/2016. // Copyright © 2016 tvProgress. All rights reserved. // import Foundation extension tvProgress { public var menuButtonDidPress: (() -> Void)? { get { return self._menuButtonPressClosure } set { self._menuButtonPressClosure = newValue } } public var playPauseButtonDidPress: (() -> Void)? { get { return self._playPauseButtonPressClosure } set { self._playPauseButtonPressClosure = newValue } } internal func menuButtonDidPress(_: AnyObject) -> Void { self._menuButtonPressClosure?() } internal func playPauseButtonDidPress(_: AnyObject) -> Void { self._playPauseButtonPressClosure?() } fileprivate func getEventCatch(_ events: [AnyObject]? = .none, getter: ((_ events: [AnyObject]) -> Void)? = .none) -> Void { struct __ { static var events: [AnyObject] = [] } if getter != nil { getter?(__.events) } if events != nil { __.events = events! } } internal func setEventCatch() -> Void { let tapMenuGesture: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tvProgress.menuButtonDidPress(_:))) tapMenuGesture.allowedPressTypes = [NSNumber(value: (UIPressType.menu.rawValue))] self.addGestureRecognizer(tapMenuGesture) let tapPlayPauseGesture: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tvProgress.playPauseButtonDidPress(_:))) tapPlayPauseGesture.allowedPressTypes = [NSNumber(value: (UIPressType.playPause.rawValue))] self.addGestureRecognizer(tapPlayPauseGesture) self.getEventCatch([tapMenuGesture, tapPlayPauseGesture]) } internal func removeEventCatch() -> Void { self.getEventCatch([]) { (events: [AnyObject]) -> Void in for event in events where event is UITapGestureRecognizer { self.removeGestureRecognizer(event as! UITapGestureRecognizer) } } } }
mit
15a7e95707f70de6c9d0388752c1509a
30.901408
153
0.609272
5.033333
false
false
false
false
tuanphung/ATSwiftKit
Source/Classes/IBDesignables/ATSImageView.swift
1
1730
// // ATSImageView.swift // // Copyright (c) 2015 PHUNG ANH TUAN. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit @IBDesignable public class IBDesignableImageView: UIImageView { @IBInspectable var cornerRadius: CGFloat = 0.0 { didSet{ layer.cornerRadius = cornerRadius } } @IBInspectable var borderColor: UIColor = UIColor.blackColor() { didSet{ layer.borderColor = borderColor.CGColor } } @IBInspectable var borderWidth: CGFloat = 0.0 { didSet{ layer.borderWidth = borderWidth } } } public class ATSImageView: IBDesignableImageView { }
mit
2c37dba96d086a7c0b264bd301d84fd7
33.62
80
0.709827
4.726776
false
false
false
false
ksco/swift-algorithm-club-cn
Brute-Force String Search/BruteForceStringSearch.swift
1
478
/* Brute-force string search */ extension String { func indexOf(pattern: String) -> String.Index? { for i in self.startIndex ..< self.endIndex { var j = i var found = true for p in pattern.startIndex ..< pattern.endIndex { if j == self.endIndex || self[j] != pattern[p] { found = false break } else { j = j.successor() } } if found { return i } } return nil } }
mit
d140b37340201ecc758019921917eef3
19.782609
56
0.502092
3.983333
false
false
false
false
younata/Ra
Tests/RaTests/InjectorTests.swift
1
8909
import Foundation import Nimble import Quick import Ra class SomeObject : NSObject { override init() { fatalError("Should not happen") } init(object: ()) { super.init() } } class AnObject : NSObject { var someObject : NSObject? = nil var someOtherObject : NSObject? = nil init(object: NSObject) { self.someObject = object super.init() } init(otherObject: NSObject) { self.someOtherObject = otherObject super.init() } override init() { super.init() } } class InjectableObject : Injectable { var wasInjected : Bool = false required init(injector: Injector) { wasInjected = true } init() {} } class InjectableNSObject : NSObject, Injectable { var wasInjector : Bool = false required init(injector: Injector) { wasInjector = true super.init() } } protocol aProtocol {} struct aStruct : aProtocol { var someInstance : Int = 0 } class InjectorTests: QuickSpec { override func spec() { var subject: Injector! = nil beforeEach { subject = Ra.Injector() } describe("initting with modules") { class SomeModule : InjectorModule { func configureInjector(injector: Injector) { injector.bind("hello", to: NSObject()) } } beforeEach { subject = Injector(module: SomeModule()) } it("should configure it") { expect(subject.create("hello") is NSObject) == true } } describe("Creating objects") { describe("through classes") { describe("Creating objects using standard initializer") { it("Should create an object using the standard init()") { expect(subject.create(NSObject.self)).to(beAKindOf(NSObject.self)) } } describe("Creating objects using a custom initializer") { beforeEach { subject.bind(SomeObject.self, to: SomeObject(object: ())) } it("should use the custom initializer") { expect(subject.create(SomeObject.self)).to(beAKindOf(SomeObject.self)) } } describe("Creating objects conforming to Injectable") { it("should use the init(injector:) initializer") { let obj = subject.create(InjectableObject.self) expect(obj?.wasInjected) == true } } } describe("through strings") { it("should return nil if there is not an existing creation method for a string") { expect(subject.create("Sholvah!")).to(beNil()) } it("should return an instance of a class if there is an existing creation method for the string") { let initialObject = NSDictionary() subject.bind("I die free", to: initialObject) if let obj = subject.create("I die free") as? NSDictionary { expect(obj).to(beIdenticalTo(initialObject)) } else { fail("No") } } it("should allow structs and such to be created") { subject.bind("Hammond of Texas", to: aStruct()) expect(subject.create("Hammond of Texas")).toNot(beNil()) var theStruct = aStruct() var receivedInjector: Injector? = nil subject.bind("Hammond of Texas") { receivedInjector = $0 return theStruct } theStruct.someInstance = 100 expect((subject.create("Hammond of Texas") as? aStruct)?.someInstance) == 100 expect(receivedInjector === subject) == true } } it("does not cache created objects unless otherwise specified") { expect(subject.create(InjectableObject.self)) !== subject.create(InjectableObject.self) expect(subject.create(InjectableNSObject.self)) !== subject.create(InjectableNSObject.self) expect(subject.create(NSObject.self)) !== subject.create(NSObject.self) subject.bind(NSObject.self, to: NSDictionary()) expect(subject.create(NSObject.self)) === subject.create(NSObject.self) } } describe("Setting creation methods") { context("when given a class") { beforeEach { subject.bind(AnObject.self, to: AnObject(object: NSObject())) } it("should set a custom creation method") { expect(subject.create(AnObject.self)?.someObject).toNot(beNil()) expect(subject.create(AnObject.self)?.someOtherObject).to(beNil()) } it("should write over any existing creation method") { subject.bind(AnObject.self) { _ in return AnObject(otherObject: NSObject()) } expect(subject.create(AnObject.self)?.someObject).to(beNil()) expect(subject.create(AnObject.self)?.someOtherObject).toNot(beNil()) } it("should allow the user to delete any existing creation method") { subject.removeBinding(kind: AnObject.self) expect(subject.create(AnObject.self)?.someObject).to(beNil()) expect(subject.create(AnObject.self)?.someOtherObject).to(beNil()) } it("should have no effect when trying to remove an object not registered") { subject.removeBinding(kind: NSObject.self) expect(subject.create(NSObject.self)).toNot(beNil()) } it("should use this method even when the object conforms to Injectable") { let obj = InjectableObject() subject.bind(InjectableObject.self, to: obj) expect(subject.create(InjectableObject.self)?.wasInjected) == false } } context("when given a protocol") { beforeEach { subject.bind(aProtocol.self, to: aStruct()) } it("should set the creation method") { expect(subject.create(aProtocol.self) is aStruct) == true } } context("when given a string") { beforeEach { subject.bind("Indeed", to: AnObject(object: NSObject())) } it("should set a custom creation method") { expect((subject.create("Indeed") as! AnObject).someObject).toNot(beNil()) expect((subject.create("Indeed") as! AnObject).someOtherObject).to(beNil()) } it("should write over any existing creation method") { subject.bind("Indeed", to: AnObject(otherObject: NSObject())) subject.bind("Indeed") { _ in AnObject(otherObject: NSObject()) } expect((subject.create("Indeed") as! AnObject).someObject).to(beNil()) expect((subject.create("Indeed") as! AnObject).someOtherObject).toNot(beNil()) } it("should allow the user to delete any existing creation method") { subject.removeBinding("Indeed") expect(subject.create("Indeed")).to(beNil()) } } } describe("somewhat complex cases") { class BaseStruct: Injectable { required init(injector: Injector) { } } struct DependingStruct: Injectable { let baseStruct: BaseStruct? init(injector: Injector) { self.baseStruct = injector.create(BaseStruct.self) } } it("creates somewhat complex cases without blowing up") { let depending = subject.create(DependingStruct.self) expect(depending).toNot(beNil()) expect(depending?.baseStruct).toNot(beNil()) } } } }
mit
7d10d58aafba9b2caa28dacb06b1f70c
35.068826
115
0.502189
5.360409
false
false
false
false
zning1994/practice
Swift学习/code4xcode6/ch14/14.1.1默认构造器.playground/section-1.swift
1
1016
// 本书网站:http://www.51work6.com/swift.php // 智捷iOS课堂在线课堂:http://v.51work6.com // 智捷iOS课堂新浪微博:http://weibo.com/u/3215753973 // 智捷iOS课堂微信公共账号:智捷iOS课堂 // 作者微博:http://weibo.com/516inc // 官方csdn博客:http://blog.csdn.net/tonny_guan // Swift语言QQ讨论群:362298485 联系QQ:1575716557 邮箱:[email protected] class Rectangle { var width : Double = 0.0 var height : Double = 0.0 // init() { // // } // init(width : Double, height : Double) { // self.width = width // self.height = height // } } /* struct Rectangle { var width : Double = 0.0 var height : Double = 0.0 // init() { // // } // init(width : Double, height : Double) { // self.width = width // self.height = height // } } */ var rect = Rectangle() rect.width = 320.0 rect.height = 480.0 println("长方形:\(rect.width) x \(rect.height)")
gpl-2.0
3224161be4217ca9cd9392ce11ae3594
18.347826
62
0.566292
2.763975
false
false
false
false
OscarSwanros/swift
test/IDE/print_omit_needless_words.swift
9
13830
// RUN: %empty-directory(%t) // REQUIRES: objc_interop // FIXME: this is failing on simulators // REQUIRES: OS=macosx // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules-without-ns/ObjectiveC.swift // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules-without-ns/CoreGraphics.swift // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules-without-ns/Foundation.swift // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -print-module -source-filename %s -module-to-print=ObjectiveC -function-definitions=false -prefer-type-repr=true > %t.ObjectiveC.txt // RUN: %FileCheck %s -check-prefix=CHECK-OBJECTIVEC -strict-whitespace < %t.ObjectiveC.txt // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -print-module -source-filename %s -module-to-print=Foundation -function-definitions=false -prefer-type-repr=true -skip-unavailable -skip-parameter-names > %t.Foundation.txt // RUN: %FileCheck %s -check-prefix=CHECK-FOUNDATION -strict-whitespace < %t.Foundation.txt // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t -I %S/../ClangImporter/Inputs/custom-modules) -print-module -source-filename %s -module-to-print=CoreCooling -function-definitions=false -prefer-type-repr=true -skip-parameter-names > %t.CoreCooling.txt // RUN: %FileCheck %s -check-prefix=CHECK-CORECOOLING -strict-whitespace < %t.CoreCooling.txt // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t -I %S/Inputs/custom-modules) -print-module -source-filename %s -module-to-print=OmitNeedlessWords -function-definitions=false -prefer-type-repr=true -skip-parameter-names > %t.OmitNeedlessWords.txt 2> %t.OmitNeedlessWords.diagnostics.txt // RUN: %FileCheck %s -check-prefix=CHECK-OMIT-NEEDLESS-WORDS -strict-whitespace < %t.OmitNeedlessWords.txt // RUN: %FileCheck %s -check-prefix=CHECK-OMIT-NEEDLESS-WORDS-DIAGS -strict-whitespace < %t.OmitNeedlessWords.diagnostics.txt // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -print-module -source-filename %s -module-to-print=errors -function-definitions=false -prefer-type-repr=true -skip-parameter-names > %t.errors.txt // RUN: %FileCheck %s -check-prefix=CHECK-ERRORS -strict-whitespace < %t.errors.txt // Note: SEL -> "Selector" // CHECK-FOUNDATION: func makeObjectsPerform(_: Selector) // Note: "with" parameters. // CHECK-FOUNDATION: func makeObjectsPerform(_: Selector, with: Any?) // CHECK-FOUNDATION: func makeObjectsPerform(_: Selector, with: Any?, with: Any?) // Note: don't prefix-strip swift_bridged classes or their subclasses. // CHECK-FOUNDATION: func mutableCopy() -> NSMutableArray // Note: id -> "Object". // CHECK-FOUNDATION: func index(of: Any) -> Int // Note: Class -> "Class" // CHECK-OBJECTIVEC: func isKind(of aClass: AnyClass) -> Bool // Note: Pointer-to-struct name matching; preposition splitting. // // CHECK-FOUNDATION: func copy(with: NSZone? = nil) -> Any! // Note: Objective-C type parameter names. // CHECK-FOUNDATION: func object(forKey: NSCopying) -> Any? // CHECK-FOUNDATION: func removeObject(forKey: NSCopying) // Note: Don't drop the name of the first parameter in an initializer entirely. // CHECK-FOUNDATION: init(array: [Any]) // Note: struct name matching; don't drop "With". // CHECK-FOUNDATION: func withRange(_: NSRange) -> NSValue // Note: built-in types. // CHECK-FOUNDATION: func add(_: Double) -> NSNumber // Note: built-in types. // CHECK-FOUNDATION: func add(_: Bool) -> NSNumber // Note: builtin-types. // CHECK-FOUNDATION: func add(_: UInt16) -> NSNumber // Note: builtin-types. // CHECK-FOUNDATION: func add(_: Int32) -> NSNumber // Note: Typedefs with a "_t" suffix". // CHECK-FOUNDATION: func subtract(_: Int32) -> NSNumber // Note: Respect the getter name for BOOL properties. // CHECK-FOUNDATION: var isMakingHoney: Bool // Note: multi-word enum name matching; "with" splits the first piece. // CHECK-FOUNDATION: func someMethod(deprecatedOptions: NSDeprecatedOptions = []) // Note: class name matching; don't drop "With". // CHECK-FOUNDATION: func withString(_: String!) -> Self! // Note: lowercasing enum constants. // CHECK-FOUNDATION: enum CountStyle : Int { // CHECK-FOUNDATION: case file // CHECK-FOUNDATION-NEXT: case memory // CHECK-FOUNDATION-NEXT: case decimal // CHECK-FOUNDATION-NEXT: case binary // Note: Make sure NSURL works in various places // CHECK-FOUNDATION: open(_: NSURL!, completionHandler: ((Bool) -> Void)!) // Note: property name stripping property type. // CHECK-FOUNDATION: var uppercased: String // Note: ok to map base name down to a keyword. // CHECK-FOUNDATION: func `do`(_: Selector!) // Note: Strip names preceded by a gerund. // CHECK-FOUNDATION: func startSquashing(_: Bee) // CHECK-FOUNDATION: func startSoothing(_: Bee) // CHECK-FOUNDATION: func startShopping(_: Bee) // Note: Removing plural forms when working with collections // CHECK-FOUNDATION: func add(_: [Any]) // Note: Int and Index match. // CHECK-FOUNDATION: func slice(from: Int, to: Int) -> String // Note: <context type>By<gerund> --> <gerund>. // CHECK-FOUNDATION: func appending(_: String) -> String // Note: <context type>By<gerund> --> <gerund>. // CHECK-FOUNDATION: func withString(_: String) -> String // Note: Noun phrase puts preposition inside. // CHECK-FOUNDATION: func url(withAddedString: String) -> NSURL? // Note: NSCalendarUnits is not a set of "Options". // CHECK-FOUNDATION: func forCalendarUnits(_: NSCalendar.Unit) -> String! // Note: <property type>By<gerund> --> <gerund>. // CHECK-FOUNDATION: var deletingLastPathComponent: NSURL? { get } // Note: <property type><preposition> --> <preposition>. // CHECK-FOUNDATION: var withHTTPS: NSURL { get } // Note: lowercasing option set values // CHECK-FOUNDATION: struct NSEnumerationOptions // CHECK-FOUNDATION: static var concurrent: NSEnumerationOptions // CHECK-FOUNDATION: static var reverse: NSEnumerationOptions // Note: usingBlock -> body // CHECK-FOUNDATION: func enumerateObjects(_: ((Any?, Int, UnsafeMutablePointer<ObjCBool>?) -> Void)!) // CHECK-FOUNDATION: func enumerateObjects(options: NSEnumerationOptions = [], using: ((Any?, Int, UnsafeMutablePointer<ObjCBool>?) -> Void)!) // Note: WithBlock -> body, nullable closures default to nil. // CHECK-FOUNDATION: func enumerateObjectsRandomly(block: ((Any?, Int, UnsafeMutablePointer<ObjCBool>?) -> Void)? = nil) // Note: id<Proto> treated as "Proto". // CHECK-FOUNDATION: func doSomething(with: NSCopying) // Note: NSObject<Proto> treated as "Proto". // CHECK-FOUNDATION: func doSomethingElse(with: NSCopying & NSObjectProtocol) // Note: Function type -> "Function". // CHECK-FOUNDATION: func sort(_: @escaping @convention(c) (AnyObject, AnyObject) -> Int) // Note: Plural: NSArray without type arguments -> "Objects". // CHECK-FOUNDATION: func remove(_: [Any]) // Note: Skipping "Type" suffix. // CHECK-FOUNDATION: func doSomething(with: NSUnderlyingType) // Don't introduce default arguments for lone parameters to setters. // CHECK-FOUNDATION: func setDefaultEnumerationOptions(_: NSEnumerationOptions) // CHECK-FOUNDATION: func normalizingXMLPreservingComments(_: Bool) // Collection element types. // CHECK-FOUNDATION: func adding(_: Any) -> Set<AnyHashable> // Boolean properties follow the getter. // CHECK-FOUNDATION: var empty: Bool { get } // CHECK-FOUNDATION: func nonEmpty() -> Bool // CHECK-FOUNDATION: var isStringSet: Bool { get } // CHECK-FOUNDATION: var wantsAUnion: Bool { get } // CHECK-FOUNDATION: var watchesItsLanguage: Bool { get } // CHECK-FOUNDATION: var appliesForAJob: Bool { get } // CHECK-FOUNDATION: var setShouldBeInfinite: Bool { get } // "UTF8" initialisms. // CHECK-FOUNDATION: init?(utf8String: UnsafePointer<Int8>!) // Don't strip prefixes from globals. // CHECK-FOUNDATION: let NSGlobalConstant: String // CHECK-FOUNDATION: func NSGlobalFunction() // Cannot strip because we end up with something that isn't an identifier // CHECK-FOUNDATION: func NS123() // CHECK-FOUNDATION: func NSYELLING() // CHECK-FOUNDATION: func NS_SCREAMING() // CHECK-FOUNDATION: func NS_() // CHECK-FOUNDATION: let NSHTTPRequestKey: String // Lowercasing initialisms with plurals. // CHECK-FOUNDATION: var urlsInText: [NSURL] { get } // Don't strip prefixes from macro names. // CHECK-FOUNDATION: var NSTimeIntervalSince1970: Double { get } // CHECK-FOUNDATION: var NS_DO_SOMETHING: Int // Note: no lowercasing of initialisms when there might be a prefix. // CHECK-CORECOOLING: func CFBottom() -> // Note: Skipping over "Ref" // CHECK-CORECOOLING: func replace(_: CCPowerSupply!) // CHECK-OMIT-NEEDLESS-WORDS: struct OMWWobbleOptions // CHECK-OMIT-NEEDLESS-WORDS: static var sideToSide: OMWWobbleOptions // CHECK-OMIT-NEEDLESS-WORDS: static var backAndForth: OMWWobbleOptions // CHECK-OMIT-NEEDLESS-WORDS: static var toXMLHex: OMWWobbleOptions // CHECK-OMIT-NEEDLESS-WORDS: func jump(to: NSURL) // CHECK-OMIT-NEEDLESS-WORDS: func objectIs(compatibleWith: Any) -> Bool // CHECK-OMIT-NEEDLESS-WORDS: func insetBy(x: Int, y: Int) // CHECK-OMIT-NEEDLESS-WORDS: func setIndirectlyToValue(_: Any) // CHECK-OMIT-NEEDLESS-WORDS: func jumpToTop(_: Any) // CHECK-OMIT-NEEDLESS-WORDS: func removeWithNoRemorse(_: Any) // CHECK-OMIT-NEEDLESS-WORDS: func bookmark(with: [NSURL]) // CHECK-OMIT-NEEDLESS-WORDS: func save(to: NSURL, forSaveOperation: Int) // CHECK-OMIT-NEEDLESS-WORDS: func index(withItemNamed: String) // CHECK-OMIT-NEEDLESS-WORDS: func methodAndReturnError(_: AutoreleasingUnsafeMutablePointer<NSError?>!) // CHECK-OMIT-NEEDLESS-WORDS: func type(of: String) // CHECK-OMIT-NEEDLESS-WORDS: func type(ofNamedString: String) // CHECK-OMIT-NEEDLESS-WORDS: func type(ofTypeNamed: String) // Look for preposition prior to "of". // CHECK-OMIT-NEEDLESS-WORDS: func append(withContentsOf: String) // Leave subscripts alone // CHECK-OMIT-NEEDLESS-WORDS: subscript(_: UInt) -> Any { get } // CHECK-OMIT-NEEDLESS-WORDS: func objectAtIndexedSubscript(_: UInt) -> Any // CHECK-OMIT-NEEDLESS-WORDS: func exportPresets(bestMatching: String) // CHECK-OMIT-NEEDLESS-WORDS: func `is`(compatibleWith: String) // CHECK-OMIT-NEEDLESS-WORDS: func add(_: Any) // CHECK-OMIT-NEEDLESS-WORDS: func slobbering(_: String) -> OmitNeedlessWords // Elements of C array types // CHECK-OMIT-NEEDLESS-WORDS: func drawPolygon(with: UnsafePointer<NSPoint>!, count: Int) // Typedef ending in "Array". // CHECK-OMIT-NEEDLESS-WORDS: func drawFilledPolygon(with: NSPointArray!, count: Int) // Non-parameterized Objective-C class ending in "Array". // CHECK-OMIT-NEEDLESS-WORDS: func draw(_: SEGreebieArray) // "bound by" // CHECK-OMIT-NEEDLESS-WORDS: func doSomething(boundBy: Int) // "separated by" // CHECK-OMIT-NEEDLESS-WORDS: func doSomething(separatedBy: Int) // "Property"-like stripping for "set" methods. // CHECK-OMIT-NEEDLESS-WORDS: class func current() -> OmitNeedlessWords // CHECK-OMIT-NEEDLESS-WORDS: class func setCurrent(_: OmitNeedlessWords) // Don't split "PlugIn". // CHECK-OMIT-NEEDLESS-WORDS: func compilerPlugInValue(_: Int) // Don't strip away argument label completely when there is a default // argument. // CHECK-OMIT-NEEDLESS-WORDS: func wobble(options: OMWWobbleOptions = []) // Property-name sensitivity in the base name "Self" stripping. // CHECK-OMIT-NEEDLESS-WORDS: func addDoodle(_: ABCDoodle) // Protocols as contexts // CHECK-OMIT-NEEDLESS-WORDS-LABEL: protocol OMWLanding { // CHECK-OMIT-NEEDLESS-WORDS-NEXT: func flip() // Verify that we get the Swift name from the original declaration. // CHECK-OMIT-NEEDLESS-WORDS-LABEL: protocol OMWWiggle // CHECK-OMIT-NEEDLESS-WORDS-NEXT: func joinSub() // CHECK-OMIT-NEEDLESS-WORDS-NEXT: func wiggle1() // CHECK-OMIT-NEEDLESS-WORDS-NEXT: @available(swift, obsoleted: 3, renamed: "wiggle1()") // CHECK-OMIT-NEEDLESS-WORDS-NEXT: func conflicting1() // CHECK-OMIT-NEEDLESS-WORDS-NEXT: var wiggleProp1: Int { get } // CHECK-OMIT-NEEDLESS-WORDS-NEXT: @available(swift, obsoleted: 3, renamed: "wiggleProp1") // CHECK-OMIT-NEEDLESS-WORDS-NEXT: var conflictingProp1: Int { get } // CHECK-OMIT-NEEDLESS-WORDS-LABEL: protocol OMWWaggle // CHECK-OMIT-NEEDLESS-WORDS-NEXT: func waggle1() // CHECK-OMIT-NEEDLESS-WORDS-NEXT: @available(swift, obsoleted: 3, renamed: "waggle1()") // CHECK-OMIT-NEEDLESS-WORDS-NEXT: func conflicting1() // CHECK-OMIT-NEEDLESS-WORDS-NEXT: var waggleProp1: Int { get } // CHECK-OMIT-NEEDLESS-WORDS-NEXT: @available(swift, obsoleted: 3, renamed: "waggleProp1") // CHECK-OMIT-NEEDLESS-WORDS-NEXT: var conflictingProp1: Int { get } // CHECK-OMIT-NEEDLESS-WORDS-LABEL: class OMWSuper // CHECK-OMIT-NEEDLESS-WORDS-NEXT: func jump() // CHECK-OMIT-NEEDLESS-WORDS-NEXT: @available(swift, obsoleted: 3, renamed: "jump()") // CHECK-OMIT-NEEDLESS-WORDS-NEXT: func jumpSuper() // CHECK-OMIT-NEEDLESS-WORDS-NEXT: var wiggleProp1: Int { get } // CHECK-OMIT-NEEDLESS-WORDS-LABEL: class OMWSub // CHECK-OMIT-NEEDLESS-WORDS-NEXT: func jump() // CHECK-OMIT-NEEDLESS-WORDS-NEXT: @available(swift, obsoleted: 3, renamed: "jump()") // CHECK-OMIT-NEEDLESS-WORDS-NEXT: func jumpSuper() // CHECK-OMIT-NEEDLESS-WORDS-NEXT: func joinSub() // CHECK-OMIT-NEEDLESS-WORDS-DIAGS: inconsistent Swift name for Objective-C method 'conflicting1' in 'OMWSub' ('waggle1()' in 'OMWWaggle' vs. 'wiggle1()' in 'OMWWiggle') // CHECK-OMIT-NEEDLESS-WORDS-DIAGS: inconsistent Swift name for Objective-C property 'conflictingProp1' in 'OMWSub' ('waggleProp1' in 'OMWWaggle' vs. 'wiggleProp1' in 'OMWSuper') // Don't drop the 'error'. // CHECK-ERRORS: func tryAndReturnError(_: ()) throws
apache-2.0
4b3fb8adc74a2a1a2f46c3f5f4576c3e
45.1
322
0.733116
3.268731
false
false
false
false
rahul-apple/XMPP-Zom_iOS
Zom/Zom/Classes/View Controllers/Login View Controllers/ZomBaseLoginViewController.swift
1
8391
// // ZomBaseLoginViewController.swift // Zom // // Created by N-Pex on 2015-11-13. // // import UIKit import OTRAssets import BButton var ZomBaseLoginController_associatedObject1: UInt8 = 0 var ZomBaseLoginController_associatedObject2: UInt8 = 1 var ZomBaseLoginController_associatedObject3: UInt8 = 2 extension OTRBaseLoginViewController { public override class func initialize() { struct Static { static var token: dispatch_once_t = 0 } // make sure this isn't a subclass if self !== OTRBaseLoginViewController.self { return } dispatch_once(&Static.token) { ZomUtil.swizzle(self, originalSelector: #selector(OTRBaseLoginViewController.viewDidLoad), swizzledSelector:#selector(OTRBaseLoginViewController.zom_viewDidLoad)) } } public func zom_viewDidLoad() { object_setClass(self, ZomBaseLoginViewController.self) self.zom_viewDidLoad() (self as! ZomBaseLoginViewController).setupTableView() } } public class ZomBaseLoginViewController: OTRBaseLoginViewController { public override func viewDidLoad() { super.viewDidLoad() setupTableView() if (onlyShowInfo) { self.title = "Account information" } if (self.createNewAccount) { if let nickname = self.form.formRowWithTag(kOTRXLFormNicknameTextFieldTag) { nickname.title = "" } } } public var onlyShowInfo:Bool { get { return objc_getAssociatedObject(self, &ZomBaseLoginController_associatedObject1) as? Bool ?? false } set { objc_setAssociatedObject(self, &ZomBaseLoginController_associatedObject1, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } private var existingAccount:Bool { get { return objc_getAssociatedObject(self, &ZomBaseLoginController_associatedObject2) as? Bool ?? false } set { objc_setAssociatedObject(self, &ZomBaseLoginController_associatedObject2, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } public var createNewAccount:Bool { get { return objc_getAssociatedObject(self, &ZomBaseLoginController_associatedObject3) as? Bool ?? false } set { objc_setAssociatedObject(self, &ZomBaseLoginController_associatedObject3, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } private func setupTableView() -> Void { let nib:UINib = UINib(nibName: "ZomTableViewSectionHeader", bundle: nil) self.tableView.registerNib(nib, forHeaderFooterViewReuseIdentifier: "zomTableSectionHeader") } public override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let header:ZomTableViewSectionHeader = tableView.dequeueReusableHeaderFooterViewWithIdentifier("zomTableSectionHeader") as! ZomTableViewSectionHeader header.labelView.text = super.tableView(tableView, titleForHeaderInSection: section) return header } public override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { let title:String? = super.tableView(tableView, titleForHeaderInSection: section) if (title == nil || title!.isEmpty) { return 0 } return 50 } public override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return nil } public override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = super.tableView(tableView, cellForRowAtIndexPath: indexPath) if (onlyShowInfo) { cell.userInteractionEnabled = false } if let desc = self.form.formRowAtIndex(indexPath) { if (desc.tag == kOTRXLFormPasswordTextFieldTag) { let font:UIFont? = UIFont(name: kFontAwesomeFont, size: 30) if (font != nil) { let button = UIButton(type: UIButtonType.Custom) button.titleLabel?.font = font button.setTitle(NSString.fa_stringForFontAwesomeIcon(FAIcon.FAEye), forState: UIControlState.Normal) //if let appDelegate = UIApplication.sharedApplication().delegate as? ZomAppDelegate { // button.setTitleColor(appDelegate.theme.mainThemeColor, forState: UIControlState.Normal) //} else { button.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal) //} button.frame = CGRectMake(0, 0, 44, 44) button.addTarget(self, action: #selector(self.didPressEyeIcon(_:withEvent:)), forControlEvents: UIControlEvents.TouchUpInside) cell.accessoryView = button } else { cell.accessoryType = UITableViewCellAccessoryType.DetailButton } cell.userInteractionEnabled = true if let xlCell = cell as? XLFormTextFieldCell { xlCell.textField.userInteractionEnabled = !onlyShowInfo } } } return cell } func didPressEyeIcon(sender: UIControl!, withEvent: UIEvent!) { let indexPath = self.tableView.indexPathForRowAtPoint((withEvent.touchesForView(sender)?.first?.locationInView(self.tableView))!) if (indexPath != nil) { self.tableView.delegate?.tableView!(self.tableView, accessoryButtonTappedForRowWithIndexPath: indexPath!) } } public override func textFieldShouldReturn(textField: UITextField) -> Bool { if let usernameRow:XLFormRowDescriptor = self.form.formRowWithTag(kOTRXLFormNicknameTextFieldTag) { if let editCell = usernameRow.cellForFormController(self) as? XLFormTextFieldCell { if (editCell.textField == textField) { if let text = textField.text?.characters.count { if (text > 0) { if let advancedRow:XLFormRowDescriptor = self.form.formRowWithTag(kOTRXLFormShowAdvancedTag) { if (advancedRow.value as? Bool == false) { // Ok, if we are not showing advanced tab, enter means "go" self.loginButtonPressed(self.navigationItem.rightBarButtonItem) return true } } } } } } } return super.textFieldShouldReturn(textField) } override public func loginButtonPressed(sender: AnyObject!) { if (onlyShowInfo) { dismissViewControllerAnimated(true, completion: nil) return } existingAccount = (self.account != nil) super.loginButtonPressed(sender) } // If creating a new account, we may need to set display name to what // was originally entered override public func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) if (self.createNewAccount) { if let nicknameRow:XLFormRowDescriptor = self.form.formRowWithTag(kOTRXLFormNicknameTextFieldTag) { if let editCell = nicknameRow.cellForFormController(self) as? XLFormTextFieldCell { if (editCell.textField.text != nil && nicknameRow.value != nil) { if (editCell.textField.text!.compare(nicknameRow.value as! String) != NSComparisonResult.OrderedSame) { self.account.displayName = editCell.textField.text } } } } } } override public func pushInviteViewController() { if (existingAccount) { dismissViewControllerAnimated(true, completion: nil) } else { super.pushInviteViewController() } } }
mpl-2.0
56f5a208e8808a9d169a5a0b92c4723d
40.746269
174
0.612799
5.452242
false
false
false
false
fousa/gpxkit
Sources/Models/Route.swift
1
1677
// // GKRoute.swift // Pods // // Created by Jelle Vandebeeck on 15/03/16. // // import Foundation import AEXML /** An ordered list of waypoints representing a series of turn points leading to a destination. */ public final class Route { /// GPS name of route. public var name: String? /// GPS comment for route. public var comment: String? /// Text description of route for user. Not sent to GPS. public var description: String? /// Source of data. Included to give user some idea of reliability and accuracy of data. public var source: String? /// Links to external information about the route. public var link: Link? /// GPS route number. public var number: Int? /// Type (classification) of route. public var type: String? /// A list of route points. public var points: [Point]? } extension Route: Mappable { convenience init?(fromElement element: AEXMLElement) { // When the element is an error, don't create the instance. if let _ = element.error { return nil } // When there are not route points, don't create the instance. var routePoints: [Point]? = nil routePoints <~ element["rtept"].all if routePoints == nil { return nil } self.init() name <~ element["name"] comment <~ element["cmt"] description <~ element["desc"] source <~ element["src"] number <~ element["number"] type <~ element["type"] link <~ element["link"] points = routePoints } }
mit
526bff6910deeeba7dbea4905445e375
23.676471
92
0.579606
4.508065
false
false
false
false
ktatroe/MPA-Horatio
Horatio/Horatio/Classes/Operations/ReachabilityCondition.swift
2
3152
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: This file shows an example of implementing the OperationCondition protocol. */ import Foundation import SystemConfiguration /** This is a condition that performs a very high-level reachability check. It does *not* perform a long-running reachability check, nor does it respond to changes in reachability. Reachability is evaluated once when the operation to which this is attached is asked about its readiness. */ public struct ReachabilityCondition: OperationCondition { public static let hostKey = "Host" public static let name = "Reachability" public static let isMutuallyExclusive = false let host: URL public init(host: URL) { self.host = host } public func dependencyForOperation(_ operation: Operation) -> Foundation.Operation? { return nil } public func evaluateForOperation(_ operation: Operation, completion: @escaping (OperationConditionResult) -> Void) { ReachabilityController.requestReachability(host) { reachable in if reachable { completion(.satisfied) } else { let error = NSError(code: .conditionFailed, userInfo: [ OperationConditionKey: type(of: self).name, type(of: self).hostKey: self.host ]) completion(.failed(error)) } } } } /// A private singleton that maintains a basic cache of `SCNetworkReachability` objects. private class ReachabilityController { static var reachabilityRefs = [String: SCNetworkReachability]() static let reachabilityQueue = DispatchQueue(label: "Operations.Reachability", attributes: []) static func requestReachability(_ url: URL, completionHandler: @escaping (Bool) -> Void) { if let host = url.host { reachabilityQueue.async { var ref = self.reachabilityRefs[host] if ref == nil { let hostString = host as NSString ref = SCNetworkReachabilityCreateWithName(nil, hostString.utf8String!) } if let ref = ref { self.reachabilityRefs[host] = ref var reachable = false var flags: SCNetworkReachabilityFlags = [] if SCNetworkReachabilityGetFlags(ref, &flags) { /* Note that this is a very basic "is reachable" check. Your app may choose to allow for other considerations, such as whether or not the connection would require VPN, a cellular connection, etc. */ reachable = flags.contains(.reachable) } completionHandler(reachable) } else { completionHandler(false) } } } else { completionHandler(false) } } }
mit
8afac33896ccaba715b65721e297c0d9
34
120
0.589524
5.706522
false
false
false
false
mercadopago/px-ios
MercadoPagoSDK/MercadoPagoSDK/Flows/OneTap/UI/PXSmallSummaryView.swift
1
3111
import Foundation final class PXSmallSummaryView: PXComponentView { private var props: [PXSummaryRowProps] = [PXSummaryRowProps]() private var backColor: UIColor? private lazy var heightForAnimation: CGFloat = 0 private var constraintForAnimation: NSLayoutConstraint? init(withProps: [PXSummaryRowProps], backgroundColor: UIColor?=nil) { super.init() props = withProps backColor = backgroundColor } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension PXSmallSummaryView: PXComponentizable { func render() -> UIView { return UIView() } func oneTapRender() -> UIView { return oneTapLayout() } } extension PXSmallSummaryView { private func oneTapLayout() -> UIView { translatesAutoresizingMaskIntoConstraints = false var dynamicHeight: CGFloat = 0 for prop in props { let newRowView = getRowComponentView(prop: prop) addSubviewToBottom(newRowView) PXLayout.pinLeft(view: newRowView).isActive = true PXLayout.pinRight(view: newRowView).isActive = true layoutIfNeeded() dynamicHeight = newRowView.frame.height > 0 ? newRowView.frame.height : dynamicHeight } backgroundColor = backColor layer.cornerRadius = 4 layer.masksToBounds = true dynamicHeight *= CGFloat(props.count) heightForAnimation = dynamicHeight constraintForAnimation = PXLayout.setHeight(owner: self, height: dynamicHeight) constraintForAnimation?.isActive = true return self } private func getRowComponentView(prop: PXSummaryRowProps) -> UIView { return PXOneTapSummaryRowRenderer(withProps: prop).renderXib() } } // MARK: Toggle expand/colapse support. extension PXSmallSummaryView { func toggle() { if let heighConst = self.constraintForAnimation?.constant, frame.height == 0 && heighConst == 0 { expand() } else { colapse() } } func hide() { let colapseFrame = CGRect(x: self.frame.origin.x, y: self.frame.origin.y, width: self.frame.width, height: 0) frame = colapseFrame constraintForAnimation?.constant = 0 } private func expand() { let expandFrame = CGRect(x: self.frame.origin.x, y: self.frame.origin.y, width: self.frame.width, height: heightForAnimation) UIView.animate(withDuration: 0.5) { [weak self] in if let height = self?.heightForAnimation { self?.frame = expandFrame self?.constraintForAnimation?.constant = height } } } private func colapse() { let colapseFrame = CGRect(x: self.frame.origin.x, y: self.frame.origin.y, width: self.frame.width, height: 0) UIView.animate(withDuration: 0.4, animations: { [weak self] in self?.frame = colapseFrame }, completion: { [weak self] _ in self?.constraintForAnimation?.constant = 0 }) } }
mit
3d3e18464e00e3be66c0af6be0a6219a
33.186813
133
0.641594
4.476259
false
false
false
false
rockgarden/swift_language
Playground/Swift Standard Library.playground/Pages/Understanding Sequence and Collection Protocols.xcplaygroundpage/Contents.swift
1
16433
/*: [Table of Contents](Table%20of%20Contents) | [Previous](@previous) | [Next](@next) **** # Understanding Sequence and Collection Protocols The best way to understand how sequence and collection protocols work in the standard library is to implement your own conforming type. Let's build a daily photo app that allows users to capture the most important moment of every day and view these moments in a timeline. To implement the model layer, we'll create a custom collection type that represents a continuous range of dates and associated images. Here's what the finished app looks like: */ import UIKit let app = finishedApp /*: ## Model Architecture When you model your app's storage, it's important to consider the required behaviors and expected performance characteristics. This is true whether you implement your own custom storage or use a combination of standard library data types. For the timeline app, there are three areas to consider: 1. Each date can be associated with an image 2. The timeline displays a continuous, ordered series of days 3. Dates can be incremented arbitrarily and compared in constant time When you look at the sum of these considerations, the built-in collection types can be ruled out. Dictionaries provide adequate representation for pairs of dates and images and support fast retrieval of values using keys, but are not ordered and cannot contain keys that do not have associated values. On the other hand, arrays are ordered but cannot quickly retrieve values using keys. Additionally, there are application-specific constraints and behaviors that could be modeled at a higher level, but would be simpler to maintain in the storage itself. A collection type that is not generic, but instead understands the qualities of the types it contains may provide considerable benefits. Let's examine the second and third areas more closely. The timeline displays a _ordered_ series of days. With a collection that has knowledge of the type of the elements, this is trivial to implement–dates have a natural, well defined order. The series is _continuous_ as well–even if a day is not associated with an image, it is still present in the collection and displayed in the timeline. Therefore, in addition to order, the indexes are trivially knowable and can be generated as needed. This means the collection can represent an infinite series of every date–without using an infinite amount of memory. Finally, because dates can be incremented and compared in constant time, indexing by date can be implemented in constant time. Therefore, a collection with a date 100 years in the past and 100 years in the future should be just as performance and memory efficient as a collection containing two consecutive dates. With this information, the shape of our collection comes into focus: A collection called TimelineCollection with the behaviors and performance characteristics of an array, but with an API that–in some important cases–mirrors that of a dictionary. ## Implementing the Index Before we implement the collection, let's implement the collection's index type–the type you use to iterate over and subscript into the collection. In our TimelineCollection type, the indexes into the array are dates. To be used as a collection index, a type must implement basic behavior to support operations like subscripting and for-in style iteration. At a minimum, an index type must adopt the `ForwardIndexType` protocol. Rather than use the `NSDate` class itself as the collection's index type, let's wrap the `NSDate` class in a `DateIndex` type where we can implement additional behavior, starting with this simple structure: */ struct DateIndex { let date: NSDate } /*: The `NSDate` class doesn't just store the date–it also stores the time down to the millisecond. Recall that the timeline app is designed to capture and display the most important moment in a user's day. The particular time of day isn't important, and every time a user takes a new photo on the same day it should replace the current photo for that day if one exists. To make it easy to step through and look up images for particular days, the `DateIndex` type needs to normalize the date when one is created. In the extension below, the `DateIndex` structure is extended with a new initializer that uses the `startOfDayForDate` method on the user's current calendar to shift the provided date to the first moment in that date's day. As long as the rest of the collection implementation traffics in `DateIndex` objects rather than directly in `NSDate` objects, we can be sure that the time of day of a date will not impact comparison, iteration, or image lookup. */ private let calendar = NSCalendar.currentCalendar() extension DateIndex { init (_ date: NSDate) { self.date = calendar.startOfDayForDate(date) } } /*: After you write the basic implementation of a type, it's useful to adopt the `CustomDebugStringConvertible` protocol. Whenever you use the type in a playground or as an argument to the `debugPrint` function, the `debugDescription` property is used to print a description of the type. You can read more about custom descriptions in [Customizing Textual Representations](Customizing%20Textual%20Representations). In the code below, the `DateIndex` structure conforms to `CustomDebugStringConvertible` and returns the stored date as a simple string containing the month and the day. */ let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = NSDateFormatter.dateFormatFromTemplate("MMMM d", options: 0, locale: NSLocale.currentLocale()) extension DateIndex: CustomDebugStringConvertible { var debugDescription: String { return dateFormatter.stringFromDate(date) } } /*: Now that instances of `DateIndex` are normalized and debuggable, the next step is to adopt the `ForwardIndexType` protocol. There are two requirements in the `ForwardIndexType` protocol: computing successive indexes and testing for equality. In addition to syntactically defined requirements, there are also _semantic_ and _performance_ requirements. These are requirements that cannot be expressed in code–but are still equally important. The `ForwardIndexType` protocol documentation contains two such requirements: 1. The successor of an index must be well-defined. In other words, you must consistently return the same successor for a given index. 2. Computing the successor must be a constant-time (`O(1)`) operation. Otherwise, generic collection algorithms would have inconsistent or unexpected performance characteristics. The following extension on `DateIndex` adopts the `ForwardIndexType` type and implements the `successor` method. The `NSCalendar` class includes an efficient method to increment a date by any value, so the method implementation below simply creates a new date by incrementing index's date by one day and then returns a new `DateIndex` instance with the new date. Because successive dates are consistently producible can be computed in constant time, we have satisfied both additional documented requirements. */ extension DateIndex: ForwardIndexType { typealias Distance = Int func successor() -> DateIndex { let nextDay = calendar.dateByAddingUnit(.Day, value: 1, toDate: self.date, options: [])! return DateIndex(nextDay) } } /*: The `ForwardIndexType` protocol inherits from the `Equatable` protocol. The `NSDate` class already implements the `==` operator (by implementing the `isEqual:` method), so the operator implementation below simply compares the indexes' dates. After implementing this operator, the `DateIndex` structure completely adopts the `ForwardIndexType` protocol. */ func == (lhs: DateIndex, rhs: DateIndex) -> Bool { return lhs.date == rhs.date } extension DateIndex: Equatable { } /*: The `TimelineCollection` structure–which we'll implement in the following section–stores `DateIndex` instances as keys in a dictionary. Keys in a dictionary must be hashable, so the code example below extends `DateIndex` to conform to the `Hashable` protocol. */ extension DateIndex: Hashable { var hashValue: Int { return date.hashValue } } /*: ## Implementing the Collection To implement a type that conforms to the `CollectionType` protocol, you implement–at a minimum–three requirements of the protocol: 1. A property called `startIndex` that returns the first index in the collection. 2. A property called `endIndex` that returns the index one past the end. 3. A subscript that accepts an index and returns an element in the collection. From these three requirements, the remaining requirements in the `CollectionType` protocol, such as `generate()`, `isEmpty`, and `count` are implemented for you using default implementations in protocol extensions. For example, the `isEmpty` property has a default implementation expressed terms of the `startIndex` and `endIndex`: if the `startIndex` and `endIndex` are equal, then there are no elements in the collection. In the code below, we implement the `TimelineCollection` structure and the minimum syntactic, semantic, and performance requirements to act as a collection. The timeline collection implements its underlying storage as a dictionary of `DateIndex`-`UIImage` pairs for performance and efficiency, but provides access to this storage through `DateIndex` APIs to maintain our high level constraints. This achieves performance characteristics and API influenced by both `Array` and `Dictionary`–while maintaining higher level application constraints like order. */ struct TimelineCollection: CollectionType { private var storage: [DateIndex: UIImage] = [:] var startIndex = DateIndex(NSDate.distantPast()) // Placeholder date var endIndex = DateIndex(NSDate.distantPast()) // Placeholder date subscript (i: DateIndex) -> UIImage? { get { return storage[i] } set { storage[i] = newValue // The `TimelineCollection` expands dynamically to include the earliest and latest dates. // To implement this functionality, any time a new date-image pair is stored using this // subscript, we check to see if the date is before the `startIndex` or after the `endIndex`. // Additionally, if the `startIndex` is one of the placeholder dates, we adjust the `startIndex` // upwards to the passed-in date. if startIndex == DateIndex(NSDate.distantPast()) || i.date.compare(startIndex.date) == .OrderedAscending { startIndex = i } let endIndexComparison = i.date.compare(endIndex.date) if endIndexComparison == .OrderedDescending || endIndexComparison == .OrderedSame { // The `endIndex` is always one past the end so that iteration and `count` know when // to stop, so compute the successor before storing the new `endIndex`. endIndex = i.successor() } } } } /*: We'll also implement a subscript and range operators that take `NSDate` objects and wrap them up as `DateIndex` instances. While the collection uses normalized `DateIndex` objects in its implementation, it surfaces those implementation details as little as possible as they are not semantically important. */ extension TimelineCollection { subscript (date: NSDate) -> UIImage? { get { return self[DateIndex(date)] } set { self[DateIndex(date)] = newValue } } } func ... (lhs: NSDate, rhs: NSDate) -> Range<DateIndex> { return DateIndex(lhs)...DateIndex(rhs) } func ..< (lhs: NSDate, rhs: NSDate) -> Range<DateIndex> { return DateIndex(lhs)..<DateIndex(rhs) } /*: At this point, we've implemented everything that's required for the `TimelineCollection` to conform to the `CollectionType` protocol. The Swift standard library includes default implementations that use the methods and properties we've defined so far to implement the remaining `CollectionType` requirements like `count`, `map`, `reverse`, and efficient slicing. Let's take a look at the timeline collection in action: */ var timeline = TimelineCollection() timeline.count for elem in loadElements() { timeline[elem.date] = elem.image } maySeventh let image = timeline[maySeventh] let view = UIView(frame: CGRect(x: 0, y: 0, width: timeline.count * 75, height: 75)) for (position, image) in timeline.enumerate() { let imageView = UIImageView(frame: CGRect(x: position * 75, y: 0, width: 75, height: 75)) imageView.image = image ?? UIImage(named: "NoImage.jpg") view.addSubview(imageView) } view /*: ## Refining the Index The timeline collection sufficiently implements the syntactic, semantic, and performance requirements of the `CollectionType` protocol. However, we've missed out on some easy performance enhancements and additional functionality. By continually refining the `DateIndex` structure, we can drastically improve performance and opt in to additional functionality. The first of these refinements is the `BidirectionalIndexType` protocol. The `BidirectionalIndexType` protocol inherits from the `ForwardIndexType` protocol and adds one method, `predecessor()`. The `predecessor` method mirrors the `successor` method–including the semantic and performance requirements–and decrements the index by one. Using the same constant time `NSCalendar` method, the extension below adopts `BidirectionalIndexType` and implements the `predecessor` method. By adopting the `BidirectionalIndexType` protocol, the timeline collection gains access to the default implementation of `reverse()`, which provides an efficient reverse view into the collection. */ extension DateIndex: BidirectionalIndexType { func predecessor() -> DateIndex { let previousDay = calendar.dateByAddingUnit(.Day, value: -1, toDate: date, options: [])! return DateIndex(previousDay) } } /*: The current default implementation for `count` that is applied to the timeline collection retrieves the `startIndex` and then counts how many times `successor()` must be invoked on the index to reach the `endIndex` of the collection. This is a reasonable `O(n)` implementation, but offers poor performance in the case where dates with images are spread far apart. It's also a problem that's easily resolved with a constant time implementation because dates are used as indexes. The `RandomAccessIndexType` protocol can be adopted by index types that are able to compute the distance between two indexes and advance multiple positions in constant time. For example, the `Array` structure's index type is `Int`. `Int` conforms to `RandomAccessIndexType` because you can add an offset to a position represented by an integer in constant time. When you adopt the `RandomAccessIndexType` protocol, a more specific, faster default implementation for collection APIs like `count` is used instead. To adopt the `RandomAccessIndexType`, the code below implements its two requirements in terms of `NSCalendar` methods that compute and compare dates. */ extension DateIndex: RandomAccessIndexType { func distanceTo(other: DateIndex) -> Int { return calendar.components(.Day, fromDate: self.date, toDate: other.date, options: []).day } func advancedBy(n: Int) -> DateIndex { let advancedDate = calendar.dateByAddingUnit(.Day, value: n, toDate: self.date, options: [])! return DateIndex(advancedDate) } } let fastCount = timeline.count /*: Here is the completed photo memory app: */ visualize(timeline) /*: **Checkpoint:** At this point you've processed and sliced collections using generic algorithms, and you've learned how standard library protocols combine to define collections and sequences. The concepts you've learned on this page apply whether or not you plan to implement your own custom collection type. By understanding how the standard library divides functionality into small protocols that work together to define many different types, you can write generic code that is flexible and expressive. More generally, the design patterns used by the standard library apply to your own code–consider reaching first for protocols and structures to improve how you reason about your code. [Table of Contents](Table%20of%20Contents) | [Previous](@previous) | [Next](@next) */
mit
63fd0accfedac9c593a2acd7fd84addc
76.363208
923
0.765624
4.839481
false
false
false
false
cardstream/iOS-SDK
cardstream-ios-sdk/CryptoSwift-0.7.2/Sources/CryptoSwift/Checksum.swift
7
8307
// // Checksum.swift // CryptoSwift // // Copyright (C) 2014-2017 Marcin Krzyżanowski <[email protected]> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. // /// CRC - cyclic redundancy check code. public final class Checksum { private static let table32: Array<UInt32> = [ 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d, ] private static let table16: Array<UInt16> = [ 0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241, 0xc601, 0x06c0, 0x0780, 0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440, 0xcc01, 0x0cc0, 0x0d80, 0xcd41, 0x0f00, 0xcfc1, 0xce81, 0x0e40, 0x0a00, 0xcac1, 0xcb81, 0x0b40, 0xc901, 0x09c0, 0x0880, 0xc841, 0xd801, 0x18c0, 0x1980, 0xd941, 0x1b00, 0xdbc1, 0xda81, 0x1a40, 0x1e00, 0xdec1, 0xdf81, 0x1f40, 0xdd01, 0x1dc0, 0x1c80, 0xdc41, 0x1400, 0xd4c1, 0xd581, 0x1540, 0xd701, 0x17c0, 0x1680, 0xd641, 0xd201, 0x12c0, 0x1380, 0xd341, 0x1100, 0xd1c1, 0xd081, 0x1040, 0xf001, 0x30c0, 0x3180, 0xf141, 0x3300, 0xf3c1, 0xf281, 0x3240, 0x3600, 0xf6c1, 0xf781, 0x3740, 0xf501, 0x35c0, 0x3480, 0xf441, 0x3c00, 0xfcc1, 0xfd81, 0x3d40, 0xff01, 0x3fc0, 0x3e80, 0xfe41, 0xfa01, 0x3ac0, 0x3b80, 0xfb41, 0x3900, 0xf9c1, 0xf881, 0x3840, 0x2800, 0xe8c1, 0xe981, 0x2940, 0xeb01, 0x2bc0, 0x2a80, 0xea41, 0xee01, 0x2ec0, 0x2f80, 0xef41, 0x2d00, 0xedc1, 0xec81, 0x2c40, 0xe401, 0x24c0, 0x2580, 0xe541, 0x2700, 0xe7c1, 0xe681, 0x2640, 0x2200, 0xe2c1, 0xe381, 0x2340, 0xe101, 0x21c0, 0x2080, 0xe041, 0xa001, 0x60c0, 0x6180, 0xa141, 0x6300, 0xa3c1, 0xa281, 0x6240, 0x6600, 0xa6c1, 0xa781, 0x6740, 0xa501, 0x65c0, 0x6480, 0xa441, 0x6c00, 0xacc1, 0xad81, 0x6d40, 0xaf01, 0x6fc0, 0x6e80, 0xae41, 0xaa01, 0x6ac0, 0x6b80, 0xab41, 0x6900, 0xa9c1, 0xa881, 0x6840, 0x7800, 0xb8c1, 0xb981, 0x7940, 0xbb01, 0x7bc0, 0x7a80, 0xba41, 0xbe01, 0x7ec0, 0x7f80, 0xbf41, 0x7d00, 0xbdc1, 0xbc81, 0x7c40, 0xb401, 0x74c0, 0x7580, 0xb541, 0x7700, 0xb7c1, 0xb681, 0x7640, 0x7200, 0xb2c1, 0xb381, 0x7340, 0xb101, 0x71c0, 0x7080, 0xb041, 0x5000, 0x90c1, 0x9181, 0x5140, 0x9301, 0x53c0, 0x5280, 0x9241, 0x9601, 0x56c0, 0x5780, 0x9741, 0x5500, 0x95c1, 0x9481, 0x5440, 0x9c01, 0x5cc0, 0x5d80, 0x9d41, 0x5f00, 0x9fc1, 0x9e81, 0x5e40, 0x5a00, 0x9ac1, 0x9b81, 0x5b40, 0x9901, 0x59c0, 0x5880, 0x9841, 0x8801, 0x48c0, 0x4980, 0x8941, 0x4b00, 0x8bc1, 0x8a81, 0x4a40, 0x4e00, 0x8ec1, 0x8f81, 0x4f40, 0x8d01, 0x4dc0, 0x4c80, 0x8c41, 0x4400, 0x84c1, 0x8581, 0x4540, 0x8701, 0x47c0, 0x4680, 0x8641, 0x8201, 0x42c0, 0x4380, 0x8341, 0x4100, 0x81c1, 0x8081, 0x4040, ] func crc32(_ message: Array<UInt8>, seed: UInt32? = nil, reflect: Bool = true) -> UInt32 { var crc: UInt32 = seed != nil ? seed! : 0xffffffff for chunk in message.batched(by: 256) { for b in chunk { let idx = Int((crc ^ UInt32(reflect ? b : reversed(b))) & 0xff) crc = (crc >> 8) ^ Checksum.table32[idx] } } return (reflect ? crc : reversed(crc)) ^ 0xffffffff } func crc16(_ message: Array<UInt8>, seed: UInt16? = nil) -> UInt16 { var crc: UInt16 = seed != nil ? seed! : 0x0000 for chunk in message.batched(by: 256) { for b in chunk { crc = (crc >> 8) ^ Checksum.table16[Int((crc ^ UInt16(b)) & 0xff)] } } return crc } } // MARK: Public interface public extension Checksum { /// Calculate CRC32 /// /// - parameter message: Message /// - parameter seed: Seed value (Optional) /// - parameter reflect: is reflect (default true) /// /// - returns: Calculated code static func crc32(_ message: Array<UInt8>, seed: UInt32? = nil, reflect: Bool = true) -> UInt32 { return Checksum().crc32(message, seed: seed, reflect: reflect) } /// Calculate CRC16 /// /// - parameter message: Message /// - parameter seed: Seed value (Optional) /// /// - returns: Calculated code static func crc16(_ message: Array<UInt8>, seed: UInt16? = nil) -> UInt16 { return Checksum().crc16(message, seed: seed) } }
gpl-3.0
6504c9e50914d6a394eca9e1a0d45f05
60.985075
217
0.695882
2.106518
false
false
false
false
moosamir68/MMRequest
MMRequest/Classes/MMUserAgent.swift
1
1005
// // MMUserAgent.swift // DonerKabab // // Created by iOSDeveloper on 7/8/17. // Copyright © 2017 EnoOne. All rights reserved. // public class MMUserAgent: NSObject { public static func userAgent() ->NSString{ let version:NSString = (Bundle.main.infoDictionary! as NSDictionary).object(forKey: "CFBundleShortVersionString") as! NSString let build:NSString = (Bundle.main.infoDictionary! as NSDictionary).object(forKey: "CFBundleVersion") as! NSString let deviceModel:NSString = UIDevice.current.model as NSString let deviceSystemName:NSString = UIDevice.current.systemName as NSString let deviceSystemVersion:NSString = UIDevice.current.systemVersion as NSString let locale:NSString = NSLocale.current.identifier as NSString let userAgent = String(format:"com.frikadell.Frikadell.ios.iphone/%@ (%@; %@; %@; %@; %@)", version, build, deviceModel, deviceSystemName, deviceSystemVersion, locale) return userAgent as NSString } }
mit
0eddeacc75546410925239eea688e991
49.2
175
0.721116
4.365217
false
false
false
false
ReSwift/ReSwift-Todo-Example
ReSwift-Todo/DateConverter.swift
1
1479
// // DateConverter.swift // ReSwift-Todo // // Created by Christian Tietze on 13/09/16. // Copyright © 2016 ReSwift. All rights reserved. // import Foundation extension Calendar { func dateFromISOComponents(year: Int, month: Int, day: Int) -> Date? { // Without custom checks, "12-945-23" does work. guard (1...12).contains(month) && (1...31).contains(day) else { return nil } var components = DateComponents() components.year = year components.month = month components.day = day return self.date(from: components) } } class DateConverter { init() { } /// Expects `isoDateString` to start with `2016-09-13` /// (YYYY-MM-DD) and extracts these values. func date(isoDateString string: String, calendar: Calendar = Calendar.autoupdatingCurrent) -> Date? { let parts = string.split(separator: "-") .map(String.init) .compactMap { Int($0) } guard parts.count >= 3 else { return nil } return calendar.dateFromISOComponents(year: parts[0], month: parts[1], day: parts[2]) } static var isoFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" formatter.locale = Locale(identifier: "en_US_POSIX") return formatter }() func string(date: Date) -> String { return DateConverter.isoFormatter.string(from: date) } }
mit
870c1d46c132815336f5ccfdbdb9b308
24.482759
105
0.610284
4.016304
false
false
false
false
RoverPlatform/rover-ios-beta
Sources/UI/Views/Extensions/LargestRemainder.swift
2
3652
// // LargestRemainder.swift // Rover // // Created by Andrew Clunis on 2019-08-01. // Copyright © 2019 Rover Labs Inc. All rights reserved. // import os // MARK: Largest Remainder Method extension Dictionary where Value == Int, Key: Comparable { /// Calculates percentages for each Value in the Dictionary, given the total as denominator. Yields whole-number percentages as the result. Uses the Largest Remainder Method to ensure they evenly add up to 100%. Operates on values associated in a dictionary, allowing you to track which percentage value is associated with which input value. func percentagesWithDistributedRemainder() -> [Key: Int] { // Largest Remainder Method in order to enable us to produce nice integer percentage values for each option that all add up to 100%. let counts = self.map { $1 } let totalVotes = counts.reduce(0, +) if(totalVotes == 0) { os_log("Cannot perform largest remainder method when total is 0. Defaulting to zero percentages.", log: .rover, type: .fault) return self.mapValues { _ in 0 } } let asExactPercentages = self.mapValues { votes in (Double(votes) / Double(totalVotes)) * 100 } let withRoundedDownPercentages: [Key:(Double, Int)] = asExactPercentages.mapValues { exactPercentage in return (exactPercentage, Int(exactPercentage.rounded(.down))) } let asRoundedDownPercentages: [Key: Int] = withRoundedDownPercentages.mapValues { $1 } let totalWithoutRemainders = asRoundedDownPercentages.values.reduce(0, +) let remainder = 100 - totalWithoutRemainders // before we sort the options by the decimal, which is the standard procedure for LRM, we'll pre-sort them by the string key (id) for each option in order to make the distribution of the remainder amongst the options in the last step more deterministic in the event of equal remainders between options. let optionsSortedById = withRoundedDownPercentages.sorted { (firstOption, secondOption) -> Bool in let (firstKey, (_, _)) = firstOption let (secondKey, (_, _)) = secondOption return firstKey < secondKey } let optionsSortedByDecimal = optionsSortedById.sorted { (firstOption, secondOption) -> Bool in let (_, (firstPercentage, firstRoundedDownPercentage)) = firstOption let (_, (secondPercentage, secondRoundedDownPercentage)) = secondOption let firstRemainder = firstPercentage - Double(firstRoundedDownPercentage) let secondRemainder = secondPercentage - Double(secondRoundedDownPercentage) return firstRemainder > secondRemainder } // now to distribute the remainder (as whole integers) across the options: let distributed = optionsSortedByDecimal.enumerated().map { tuple -> (Key, Int) in let (offset, keyWithPercentages) = tuple let (key, percentages) = keyWithPercentages let (_, roundedDownPercentage) = percentages if offset < remainder { return (key, roundedDownPercentage + 1) } else { return (key, roundedDownPercentage) } } // and turn it back into a dictionary: return distributed.reduce(into: [Key: Int]()) { (dictionary, optionIdAndCount) in let (optionID, voteCount) = optionIdAndCount dictionary[optionID] = voteCount } } }
mit
6b4e2bb4acd8b744ec74df3927683427
47.039474
348
0.645577
4.822985
false
false
false
false
Baglan/MCResource
Classes/MCResource.swift
1
3667
// // MCResourceLoader.swift // MCResourceLoader // // Created by Baglan on 28/10/2016. // Copyright © 2016 Mobile Creators. All rights reserved. // import Foundation protocol MCResourceSource: class { var priority: Int { get } var fractionCompleted: Double { get } func beginAccessing(completionHandler: @escaping (URL?, Error?) -> Void) func endAccessing() } class MCResource: ErrorSource { var localURL: URL? private var sources = [MCResourceSource]() func add(source: MCResourceSource) { sources.append(source) } private var currentSource: MCResourceSource? private var batch = [MCResourceSource]() private var isAccessing = false private var completionHandler: ((URL?, Error?) -> Void)? private var queueHelper = OperationQueueHelper() var fractionCompleted: Double { if let currentSource = currentSource { return currentSource.fractionCompleted } else { return 0 } } func beginAccessing(completionHandler: @escaping (URL?, Error?) -> Void) { guard !isAccessing else { completionHandler(nil, ErrorHelper.error(for: ErrorCodes.AlreadyAccessing.rawValue, source: self)) return } guard sources.count > 0 else { completionHandler(nil, ErrorHelper.error(for: ErrorCodes.NoSourcesAvailable.rawValue, source: self)) return } isAccessing = true self.completionHandler = completionHandler queueHelper.preferred = OperationQueue.current // Copy sources to batch in reversed order batch.removeAll() batch.append( contentsOf: sources.sorted { (a, b) -> Bool in return a.priority <= b.priority } ) tryNextSource() } func tryNextSource() { currentSource?.endAccessing() guard let source = batch.popLast() else { if let completionHandler = completionHandler { queueHelper.queue.addOperation { [unowned self] in completionHandler(nil, ErrorHelper.error(for: ErrorCodes.RunOutOfSources.rawValue, source: self)) } } return } currentSource = source NSLog("[MCResource] trying \(String(describing: type(of: source)))") source.beginAccessing { [unowned self] (url, error) in guard self.isAccessing else { return } if let error = error { NSLog("[Error] \(error)") self.tryNextSource() } else { self.localURL = url if let completionHandler = self.completionHandler { self.queueHelper.queue.addOperation { completionHandler(url, nil) } } } } } func endAccessing() { if isAccessing { currentSource?.endAccessing() localURL = nil isAccessing = false } } deinit { endAccessing() } // MARK: - Errors static let errorDomain = "MCResourceErrorDomain" enum ErrorCodes: Int { case AlreadyAccessing case NoSourcesAvailable case RunOutOfSources } static let errorDescriptions: [Int: String] = [ ErrorCodes.AlreadyAccessing.rawValue: "Already accessing", ErrorCodes.NoSourcesAvailable.rawValue: "No sources available", ErrorCodes.RunOutOfSources.rawValue: "All sources failed" ] }
mit
3f1fa497825ae23592a4022c008ae032
28.564516
117
0.579651
5.070539
false
false
false
false
artursDerkintis/YouTube
YouTube/SearchResultsProvider.swift
1
8672
// // SearchResultsProvider.swift // YouTube // // Created by Arturs Derkintis on 12/30/15. // Copyright © 2015 Starfly. All rights reserved. // import UIKit import Alamofire import SwiftyJSON let kYoutubeKey = "AIzaSyCa6PZpINllRHja2Pac31oYxSLbIqIF3JU" class SearchResultsProvider: NSObject { func getSearchResults(string : String, pageToken : String?, completion:(nextPageToken : String?, items : [Item]) -> Void){ let url = "https://www.googleapis.com/youtube/v3/search?part=snippet&q=\(string)&key=\(kYoutubeKey)&type=video,channel" var params = Dictionary<String, AnyObject>() params["maxResults"] = 30 if let pageToken = pageToken{ params["pageToken"] = pageToken } let setCH = NSCharacterSet.URLQueryAllowedCharacterSet() Alamofire.request(.GET, url.stringByAddingPercentEncodingWithAllowedCharacters(setCH)!, parameters : params).validate().responseJSON { response in switch response.result { case .Success: if let value = response.result.value { let json = JSON(value) print("JSON: \(json)") if let array = json["items"].array{ self.parseItems(array, completion: { (items) -> Void in let nextpagetoken = json["nextPageToken"].string completion(nextPageToken: nextpagetoken, items: items) }) } } case .Failure(let error): print(error) } } } func parseItems(objects : [JSON], completion : (items : [Item]) -> Void){ var items = [Item]() for object in objects{ let item = Item() items.append(item) self.parseItem(object, item: item, completion: { (item) -> Void in let amount = items.filter({ (item) -> Bool in return item.type != .None }) if amount.count == objects.count{ completion(items: items) } }) } } func parseItem(object : JSON, item : Item, completion : (item : Item) -> Void){ if let kind = object["id"]["kind"].string{ switch kind{ case "youtube#channel": let channelId = object["snippet"]["channelId"].string let channel = Channel() channel.getChannelDetails(channelId!, completion: { (channelDetails) -> Void in channel.channelDetails = channelDetails item.channel = channel completion (item: item) }) break case "youtube#video": let videoId = object["id"]["videoId"].string let video = Video() video.getVideoDetails(videoId!, completion: { (videoDetails) -> Void in video.videoDetails = videoDetails item.video = video completion(item: item) }) break default: item.type = .Unrecognized break } } } func getSearchSuggestions(string : String, completion : (strings : [String]) -> Void){ let url = "https://suggestqueries.google.com/complete/search?client=youtube&ds=yt&client=firefox&q=\(string)" let setCH = NSCharacterSet.URLQueryAllowedCharacterSet() Alamofire.request(.GET, url.stringByAddingPercentEncodingWithAllowedCharacters(setCH)!).validate().responseJSON { response in switch response.result { case .Success: if let value = response.result.value { let json = JSON(value) if let array = json[1].array{ var stringArray = [String]() for value in array where value.string != nil{ if stringArray.count < 6{ stringArray.append(value.string!) } } completion(strings: stringArray) } } case .Failure(let error): print(error) } } } } enum ItemType{ case Video case Channel case Unrecognized case None //more } public class Item : NSObject{ var channel : Channel?{ didSet{ if channel != nil{ self.type = .Channel } } } var video : Video?{ didSet{ if video != nil{ self.type = .Video } } } var type : ItemType = .None } class Channel : NSObject{ var channelDetails : ChannelDetails? var subscribed : Bool? func getChannelDetails(id: String, completion : (channelDetails : ChannelDetails) -> Void){ let url = "https://www.googleapis.com/youtube/v3/channels?id=\(id)&key=\(kYoutubeKey)&part=snippet,statistics" let setCH = NSCharacterSet.URLQueryAllowedCharacterSet() Alamofire.request(.GET, url.stringByAddingPercentEncodingWithAllowedCharacters(setCH)!).validate().responseJSON { response in switch response.result { case .Success: if let value = response.result.value { let json = JSON(value) if let array = json["items"].array{ for object in array{ if let channelD = parseChannel(object){ completion(channelDetails: channelD) } } } } case .Failure(let error): print(error) } } } } class Video : NSObject{ var videoDetails : VideoDetails? var channel : ChannelDetails? func getVideoDetails(id : String, completion : (videoDetails : VideoDetails) -> Void){ let url = "https://www.googleapis.com/youtube/v3/videos?id=\(id)&key=\(kYoutubeKey)&part=snippet,contentDetails,statistics,status" let setCH = NSCharacterSet.URLQueryAllowedCharacterSet() Alamofire.request(.GET, url.stringByAddingPercentEncodingWithAllowedCharacters(setCH)!).validate().responseJSON { response in switch response.result { case .Success: if let value = response.result.value { let json = JSON(value) if let array = json["items"].array{ for object in array{ if let channelId = object["snippet"]["channelId"].string{ self.getChannelDetails(channelId, completion: { (channelDetails) -> Void in self.channel = channelDetails }) } if let videoDetails = parseVideo(object){ completion(videoDetails: videoDetails) } } } } case .Failure(let error): print(error) } } } func getChannelDetails(id: String, completion : (channelDetails : ChannelDetails) -> Void){ let url = "https://www.googleapis.com/youtube/v3/channels?id=\(id)&key=\(kYoutubeKey)&part=snippet,statistics" let setCH = NSCharacterSet.URLQueryAllowedCharacterSet() Alamofire.request(.GET, url.stringByAddingPercentEncodingWithAllowedCharacters(setCH)!).validate().responseJSON { response in switch response.result { case .Success: if let value = response.result.value { let json = JSON(value) if let array = json["items"].array{ for object in array{ if let channelD = parseChannel(object){ completion(channelDetails: channelD) } } } } case .Failure(let error): print(error) } } } }
mit
6f0aebf1def497894eec948c4149a77c
35.280335
154
0.495329
5.519414
false
false
false
false
vimask/ClientCodeGen
ClientCodeGen/ViewController.swift
1
22010
// // ViewController.swift // ClientCodeGen // // Created by Vinh Vo on 6/13/17. // Copyright © 2017 Vinh Vo. All rights reserved. // import Cocoa class ViewController: NSViewController, NSUserNotificationCenterDelegate, NSTableViewDelegate, NSTableViewDataSource, NSTextViewDelegate { //Shows the list of files' preview @IBOutlet weak var tableView: NSTableView! //Connected to the status label @IBOutlet weak var statusLabel: NSTextField! //Connected to the save button @IBOutlet weak var saveButton: NSButton! //Connected to the JSON input text view @IBOutlet var sourceText: NSTextView! //Connected to the scroll view which wraps the sourceText @IBOutlet weak var scrollView: NSScrollView! //Connected to Constructors check box @IBOutlet weak var generateConstructors: NSButtonCell! //Connected to Utility Methods check box @IBOutlet weak var generateUtilityMethods: NSButtonCell! //Connected to root class name field @IBOutlet weak var classNameField: NSTextFieldCell! //Connected to parent class name field @IBOutlet weak var parentClassName: NSTextField! //Connected to class prefix field @IBOutlet weak var classPrefixField: NSTextField! //Connected to the first line statement field @IBOutlet weak var firstLineField: NSTextField! //Connected to the languages pop up @IBOutlet weak var languagesPopup: NSPopUpButton! //Connected to the http method pop up @IBOutlet weak var httpMethodPopup: NSPopUpButton! //Connected to the request url field @IBOutlet weak var requestUrlField: NSTextField! //Connected to the header input text view @IBOutlet weak var headerText: NSTextView! //Connected to the body input text view @IBOutlet weak var bodyText: NSTextView! //Holds the currently selected language var selectedLang : LangModel! //Returns the title of the selected language in the languagesPopup var selectedLanguageName : String = "" //Returns the title of the selected method in the httpMethodPopup var selectedMethodName : String { return httpMethodPopup.titleOfSelectedItem! } //Should hold list of supported languages, where the key is the language name and the value is LangModel instance var langs : [String : LangModel] = [String : LangModel]() //Holds list of the generated files var files : [FileRepresenter] = [FileRepresenter]() override func viewDidLoad() { super.viewDidLoad() saveButton.isEnabled = false sourceText.isAutomaticQuoteSubstitutionEnabled = false headerText.isAutomaticQuoteSubstitutionEnabled = false bodyText.isAutomaticQuoteSubstitutionEnabled = false loadSupportedLanguages() setupNumberedTextView() setHttpMethodPopup() setLanguagesSelection() loadLastSelectedLanguage() loadLastUrl() loadLastHeaders() loadLastBody() updateUIFieldsForSelectedLanguage() self.selectedLanguageName = languagesPopup.titleOfSelectedItem ?? "" } /** Sets the values of httpMethodPopup items' titles */ func setHttpMethodPopup() { for method in iterateEnum(HttpMethod.self) { httpMethodPopup.addItem(withTitle: method.rawValue) } } /** Sets the values of languagesPopup items' titles */ func setLanguagesSelection() { let langNames = Array(langs.keys).sorted() languagesPopup.removeAllItems() languagesPopup.addItems(withTitles: langNames) } /** Sets the needed configurations for show the line numbers in the input text view */ func setupNumberedTextView() { let lineNumberView = NoodleLineNumberView(scrollView: scrollView) scrollView.hasHorizontalRuler = false scrollView.hasVerticalRuler = true scrollView.verticalRulerView = lineNumberView scrollView.rulersVisible = true sourceText.font = NSFont.userFixedPitchFont(ofSize: NSFont.smallSystemFontSize) headerText.font = NSFont.userFixedPitchFont(ofSize: NSFont.smallSystemFontSize) bodyText.font = NSFont.userFixedPitchFont(ofSize: NSFont.smallSystemFontSize) } /** Updates the visible fields according to the selected language */ func updateUIFieldsForSelectedLanguage() { loadSelectedLanguageModel() if selectedLang.supportsFirstLineStatement != nil && selectedLang.supportsFirstLineStatement!{ firstLineField.isHidden = false firstLineField.placeholderString = selectedLang.firstLineHint }else{ firstLineField.isHidden = true } if selectedLang.modelDefinitionWithParent != nil || selectedLang.headerFileData?.modelDefinitionWithParent != nil{ parentClassName.isHidden = false }else{ parentClassName.isHidden = true } } /** Loads last selected language by user */ func loadLastSelectedLanguage() { guard let lastSelectedLanguage = UserDefaults.standard.value(forKey: "selectedLanguage") as? String else{ return } if langs[lastSelectedLanguage] != nil{ self.selectedLanguageName = languagesPopup.titleOfSelectedItem ?? "" languagesPopup.selectItem(withTitle: lastSelectedLanguage) } } func loadLastUrl() { guard let urlString = UserDefaults.standard.value(forKey: "url") as? String else{ return } self.requestUrlField.stringValue = urlString } func loadLastHeaders() { guard let headerString = UserDefaults.standard.value(forKey: "header") as? String else{ return } self.headerText.string = headerString } func loadLastBody() { guard let bodyString = UserDefaults.standard.value(forKey: "body") as? String else{ return } self.bodyText.string = bodyString } //MARK: - Handling pre defined languages func loadSupportedLanguages() { if let langFiles = Bundle.main.urls(forResourcesWithExtension: "json", subdirectory: nil) as [URL]!{ for langFile in langFiles{ if let data = try? Data(contentsOf: langFile), let langDictionary = (try? JSONSerialization.jsonObject(with: data, options: [])) as? NSDictionary{ let lang = LangModel(fromDictionary: langDictionary) if langs[lang.displayLangName] != nil{ continue } langs[lang.displayLangName] = lang } } } } // MARK: - parse the json file func parseJSONData(jsonData: Data!) { let jsonString = String(data: jsonData, encoding: .utf8) sourceText.string = jsonString! } //MARK: - Handlind events // @IBAction func openJSONFiles(sender: AnyObject) // { // let oPanel: NSOpenPanel = NSOpenPanel() // oPanel.canChooseDirectories = false // oPanel.canChooseFiles = true // oPanel.allowsMultipleSelection = false // oPanel.allowedFileTypes = ["json","JSON"] // oPanel.prompt = "Choose JSON file" // // oPanel.beginSheetModal(for: self.view.window!, completionHandler: {(result) in // if result == NSApplication.ModalResponse.OK { // // let jsonPath = oPanel.urls.first!.path // let fileHandle = FileHandle(forReadingAtPath: jsonPath) // let urlStr:String = oPanel.urls.first!.lastPathComponent // self.classNameField.stringValue = urlStr.replacingOccurrences(of: ".json", with: "") // self.parseJSONData(jsonData: (fileHandle!.readDataToEndOfFile() as NSData!) as Data!) // // } // }) // } @IBAction func httpMethodChanged(_ sender: AnyObject) { print("selected method: \(self.selectedMethodName)") switch self.selectedMethodName { case HttpMethod.get.rawValue: self.bodyText.isEditable = false self.bodyText.isHidden = true break default: self.bodyText.isEditable = true self.bodyText.isHidden = false break } } @IBAction func sendRequestAction(_ sender: Any) { self.showErrorStatus("") var header:[String:Any]? var params:[String:Any]? //check user inputed url if self.requestUrlField.stringValue.trimmingCharacters(in: .whitespacesAndNewlines).characters.count == 0{ self.showErrorStatus("please input request Url") return } UserDefaults.standard.set(self.requestUrlField.stringValue, forKey: "url") var strHeader = headerText.string if strHeader.characters.count != 0{ strHeader = stringByRemovingControlCharacters(strHeader) if let data = strHeader.data(using: String.Encoding.utf8){ do { let jsonData : Any = try JSONSerialization.jsonObject(with: data, options: []) if jsonData is NSDictionary{ header = jsonData as? [String : Any] }else{ self.showErrorStatus("It seems your header JSON is not valid!") return } } catch let error1 as NSError { print(error1) self.showErrorStatus("It seems your header JSON is not valid!") return } catch { fatalError() } } } UserDefaults.standard.set(strHeader, forKey: "header") var strParams = bodyText.string if strParams.characters.count != 0{ strParams = stringByRemovingControlCharacters(strParams) if let data = strParams.data(using: String.Encoding.utf8){ do { let jsonData : Any = try JSONSerialization.jsonObject(with: data, options: []) if jsonData is NSDictionary{ params = jsonData as? [String : Any] }else{ self.showErrorStatus("It seems your params JSON is not valid!") return } } catch let error1 as NSError { print(error1) self.showErrorStatus("It seems your params JSON is not valid!") return } catch { fatalError() } } } UserDefaults.standard.set(strParams, forKey: "body") switch self.selectedMethodName { case HttpMethod.get.rawValue: self.get(url: self.requestUrlField.stringValue, header: header) break case HttpMethod.post.rawValue: self.post(url: self.requestUrlField.stringValue, params: params, header: header) break case HttpMethod.put.rawValue: self.put(url: self.requestUrlField.stringValue, params: params, header: header) break case HttpMethod.detele.rawValue: self.delete(url: self.requestUrlField.stringValue, params: params, header: header) break default: break } } @IBAction func toggleConstructors(_ sender: AnyObject) { generateClasses() } @IBAction func toggleUtilities(_ sender: AnyObject) { generateClasses() } @IBAction func rootClassNameChanged(_ sender: AnyObject) { generateClasses() } @IBAction func parentClassNameChanged(_ sender: AnyObject) { generateClasses() } @IBAction func classPrefixChanged(_ sender: AnyObject) { generateClasses() } @IBAction func selectedLanguageChanged(_ sender: AnyObject) { self.selectedLanguageName = languagesPopup.titleOfSelectedItem ?? "" updateUIFieldsForSelectedLanguage() generateClasses() UserDefaults.standard.set(self.languagesPopup.titleOfSelectedItem, forKey: "selectedLanguage") } @IBAction func firstLineChanged(_ sender: AnyObject) { generateClasses() } //MARK: - Call HTTP Request func get(url:String, header:[String:Any]?) { ApiClient().makeGetRequest(strURL: url, headers: header) { (success, responseString) in self.sourceText.string = responseString ?? "" if success { self.generateClasses() } } } func post(url:String, params:[String:Any]?, header:[String:Any]?) { ApiClient().makePostRequest(strURL: url, body: params, headers: header) { (success, responseString) in self.sourceText.string = responseString ?? "" if success { self.generateClasses() } } } func put(url:String, params:[String:Any]?, header:[String:Any]?) { ApiClient().makePutRequest(strURL: url, body: params, headers: header) { (success, responseString) in self.sourceText.string = responseString ?? "" if success { self.generateClasses() } } } func delete(url:String, params:[String:Any]?, header:[String:Any]?) { ApiClient().makeDeleteRequest(strURL: url, body: params!, headers: header) { (success, responseString) in self.sourceText.string = responseString ?? "" if success { self.generateClasses() } } } //MARK: - NSTextDelegate func textDidChange(_ notification: Notification) { generateClasses() } //MARK: - Language selection handling func loadSelectedLanguageModel() { selectedLang = langs[self.selectedLanguageName] } //MARK: - NSUserNotificationCenterDelegate func userNotificationCenter(_ center: NSUserNotificationCenter, shouldPresent notification: NSUserNotification) -> Bool { return true } //MARK: - Showing the open panel and save files @IBAction func saveFiles(_ sender: AnyObject) { let openPanel = NSOpenPanel() openPanel.allowsOtherFileTypes = false openPanel.treatsFilePackagesAsDirectories = false openPanel.canChooseFiles = false openPanel.canChooseDirectories = true openPanel.canCreateDirectories = true openPanel.prompt = "Choose" openPanel.beginSheetModal(for: self.view.window!, completionHandler: {(result) in if result == NSApplication.ModalResponse.OK { self.saveToPath(openPanel.url!.path) self.showDoneSuccessfully() } }) } /** Saves all the generated files in the specified path - parameter path: in which to save the files */ func saveToPath(_ path : String) { var error : NSError? for file in files{ var fileContent = file.fileContent if fileContent == ""{ fileContent = file.toString() } var fileExtension = selectedLang.fileExtension if file is HeaderFileRepresenter{ fileExtension = selectedLang.headerFileData.headerFileExtension } let filePath = "\(path)/\(file.className).\(fileExtension)" do { try fileContent.write(toFile: filePath, atomically: false, encoding: String.Encoding.utf8) } catch let error1 as NSError { error = error1 } if error != nil{ showError(error!) break } } } //MARK: - Messages /** Shows the top right notification. Call it after saving the files successfully */ func showDoneSuccessfully() { let notification = NSUserNotification() notification.title = "Success!" notification.informativeText = "Your \(selectedLang.langName) model files have been generated successfully." notification.deliveryDate = Date() let center = NSUserNotificationCenter.default center.delegate = self center.deliver(notification) } /** Shows an NSAlert for the passed error */ func showError(_ error: NSError!) { if error == nil{ return; } let alert = NSAlert(error: error) alert.runModal() } /** Shows the passed error status message */ func showErrorStatus(_ errorMessage: String) { statusLabel.textColor = NSColor.red statusLabel.stringValue = errorMessage } /** Shows the passed success status message */ func showSuccessStatus(_ successMessage: String) { statusLabel.textColor = NSColor.green statusLabel.stringValue = successMessage } //MARK: - Generate files content /** Validates the sourceText string input, and takes any needed action to generate the model classes and view them in the preview panel */ func generateClasses() { saveButton.isEnabled = false var str = sourceText.string if str.characters.count == 0{ //Nothing to do, just clear any generated files files.removeAll(keepingCapacity: false) tableView.reloadData() return; } var rootClassName = classNameField.stringValue if rootClassName.characters.count == 0{ rootClassName = "RootClass" } sourceText.isEditable = false //Do the lengthy process in background, it takes time with more complicated JSONs // runOnBackground { str = stringByRemovingControlCharacters(str) if let data = str.data(using: String.Encoding.utf8){ var error : NSError? do { let jsonData : Any = try JSONSerialization.jsonObject(with: data, options: []) var json : NSDictionary! if jsonData is NSDictionary{ //fine nothing to do json = jsonData as! NSDictionary }else{ json = unionDictionaryFromArrayElements(jsonData as! NSArray) } self.loadSelectedLanguageModel() self.files.removeAll(keepingCapacity: false) let fileGenerator = self.prepareAndGetFilesBuilder() fileGenerator.addFileWithName(&rootClassName, jsonObject: json, files: &self.files) fileGenerator.fixReferenceMismatches(inFiles: self.files) self.files = Array(self.files.reversed()) runOnUiThread{ self.sourceText.isEditable = true self.showSuccessStatus("Valid JSON structure") self.saveButton.isEnabled = true self.tableView.reloadData() } } catch let error1 as NSError { error = error1 runOnUiThread({ () -> Void in self.sourceText.isEditable = true self.saveButton.isEnabled = false if error != nil{ print(error!) } self.showErrorStatus("It seems your JSON object is not valid!") }) } catch { fatalError() } } // } } /** Creates and returns an instance of FilesContentBuilder. It also configure the values from the UI components to the instance. I.e includeConstructors - returns: instance of configured FilesContentBuilder */ func prepareAndGetFilesBuilder() -> FilesContentBuilder { let filesBuilder = FilesContentBuilder.instance filesBuilder.includeConstructors = (self.generateConstructors.state == NSControl.StateValue.offState) filesBuilder.includeUtilities = (self.generateUtilityMethods.state == NSControl.StateValue.offState) filesBuilder.firstLine = self.firstLineField.stringValue filesBuilder.lang = self.selectedLang! filesBuilder.classPrefix = self.classPrefixField.stringValue filesBuilder.parentClassName = self.parentClassName.stringValue return filesBuilder } //MARK: - NSTableViewDataSource func numberOfRows(in tableView: NSTableView) -> Int { return files.count } //MARK: - NSTableViewDelegate func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "fileCell"), owner: self) as! FilePreviewCell let file = files[row] cell.file = file return cell } }
mit
fc4dd799443957cea3a57a50db172fa4
31.800298
162
0.585624
5.399657
false
false
false
false
ithree1113/LocationTalk
LocationTalk/FirebaseAuth.swift
1
2836
// // Authentication.swift // LocationTalk // // Created by 鄭宇翔 on 2017/1/4. // Copyright © 2017年 鄭宇翔. All rights reserved. // import Foundation import Firebase class FirebaseAuth: AuthObject, AccountProtocol { var ref: FIRDatabaseReference! required init() { self.ref = FIRDatabase.database().reference() } deinit { print("Authentication deinit") } override func currentUser() -> MyUser? { if let user = FIRAuth.auth()?.currentUser { let myUser = MyUser.init(email: user.email!, username: user.displayName!) return myUser } return nil } override func login(email: String, password: String) { FIRAuth.auth()?.signIn(withEmail: email, password: password, completion: { [weak self] (user, error) in guard let strongSelf = self else {return} strongSelf.delagate?.authDidLogin(error: error) }) } override func signUp(email: String, password: String, username: String) { FIRAuth.auth()?.createUser(withEmail: email, password: password, completion: { [weak self] (user, error) in guard let strongSelf = self else {return} if error == nil { strongSelf.setDisplayName(user!, displayname: username) let userInfo = [Constants.FirebaseKey.email: email, Constants.FirebaseKey.password: password, Constants.FirebaseKey.username: username] let node = strongSelf.emailToNode(email) strongSelf.ref.child(node).setValue(userInfo) } strongSelf.delagate?.authDidSignUp(error: error) }) } func setDisplayName(_ user: FIRUser, displayname: String) { let changeRequest = user.profileChangeRequest() changeRequest.displayName = displayname changeRequest.commitChanges(){ (error) in if let error = error { print(error.localizedDescription) return } } } func signOut() { do { try FIRAuth.auth()?.signOut() MyProfile.shared.signedOut() } catch { print("Error signing out: \(error.localizedDescription)") } } override func inputErrorAlert() { // Called upon signup error to let the user know signup didn't work. let alert = UIAlertController(title: Constants.ErrorAlert.alertTitle, message: Constants.ErrorAlert.loginMissingMessage, preferredStyle: UIAlertControllerStyle.alert) let action = UIAlertAction(title: "OK", style: .default, handler: nil) alert.addAction(action) if let vc = self.delagate as? UIViewController { vc.present(alert, animated: true, completion: nil) } } }
mit
6ad6a3cb810ddb8904a62716a1e648d9
33.82716
174
0.610776
4.693844
false
false
false
false
folio3/SocialNetwork
FacebookDemo/FacebookDemo/FacebookClasses/AlbumTableViewController.swift
1
3085
// // AlbumTableViewController.swift // FacebookDemo // // Created by Hamza Azad on 30/01/2016. // Copyright (c) 2014–2016 Folio3 Pvt Ltd (http://www.folio3.com/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit class AlbumTableViewController: UITableViewController { private let parser = FBAlbumParser() private var albums = [FacebookAlbum]() override func viewDidLoad() { AppDelegate.facebookHandler.getUserAlbums(1, pageId: nil, pageType: .Next) { (result, error) -> Void in self.parser.parse(FBAlbumParser.ParseType.Albums.rawValue, object: result, completion: { (result, error) -> Void in if let albums = result as? [FacebookAlbum] { self.albums = albums.sort { $0.name.localizedCaseInsensitiveCompare($1.name) == NSComparisonResult.OrderedAscending } } self.tableView.reloadData() }) } } // MARK: Table view delegate override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) } func objectAtIndexPath(indexPath: NSIndexPath) -> FacebookAlbum? { var album: FacebookAlbum? album = self.albums[indexPath.row] return album } // MARK: Table view datasource override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.albums.count ?? 0 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let identifier = "albumCell" let cell = tableView.dequeueReusableCellWithIdentifier(identifier) let album = self.objectAtIndexPath(indexPath) cell?.textLabel?.text = album!.name return cell! } }
mit
3b2ce238244ad30dd98bdca497df7ecd
38.025316
137
0.685047
4.817188
false
false
false
false
A-Kod/vkrypt
Pods/SwiftyVK/Library/Sources/Utils/KeychainProvider.swift
2
1910
class KeychainProvider<EntityType> { let serviceKey: String init(serviceKey: String) { self.serviceKey = serviceKey } func save(_ entity: EntityType, for sessionId: String) throws { let keychainQuery = keychainParamsFor(sessionId: sessionId) keychainQuery.setObject( NSKeyedArchiver.archivedData(withRootObject: entity), forKey: NSString(format: kSecValueData) ) removeFor(sessionId: sessionId) let keychainCode = SecItemAdd(keychainQuery, nil) guard keychainCode == 0 else { throw VKError.cantSaveToKeychain(keychainCode) } } func getFor(sessionId: String) -> EntityType? { let keychainQuery = keychainParamsFor(sessionId: sessionId) keychainQuery.setObject(kCFBooleanTrue, forKey: NSString(format: kSecReturnData)) keychainQuery.setObject(kSecMatchLimitOne, forKey: NSString(format: kSecMatchLimit)) var keychainResult: AnyObject? guard SecItemCopyMatching(keychainQuery, &keychainResult) == 0 else { return nil } guard let data = keychainResult as? Data else { return nil } guard let entity = NSKeyedUnarchiver.unarchiveObject(with: data) as? EntityType else { return nil } return entity } func removeFor(sessionId: String) { SecItemDelete(keychainParamsFor(sessionId: sessionId)) } private func keychainParamsFor(sessionId: String) -> NSMutableDictionary { return [ kSecAttrAccessible: kSecAttrAccessibleAlways, kSecClass: kSecClassGenericPassword, kSecAttrService: serviceKey, kSecAttrAccount: "SVK" + sessionId ] as NSMutableDictionary } }
apache-2.0
ebcac24e6b2739a4fd41edd1717405d8
30.311475
94
0.615183
5.823171
false
false
false
false
rnystrom/GitHawk
FreetimeWatch Extension/InboxDataController.swift
1
1886
// // InboxDataController.swift // FreetimeWatch Extension // // Created by Ryan Nystrom on 4/29/18. // Copyright © 2018 Ryan Nystrom. All rights reserved. // import Foundation import GitHubAPI protocol InboxDataControllerDelegate: class { func didUpdate(dataController: InboxDataController) } final class InboxDataController { weak var delegate: InboxDataControllerDelegate? typealias NotificationGroup = (repo: V3Repository, notifications: [V3Notification]) private var readRepos = Set<V3Repository>() private var _groupedNotifications = [NotificationGroup]() var unreadNotifications: [NotificationGroup] { return _groupedNotifications.filter { !readRepos.contains($0.repo) } } func read(repository: V3Repository) { readRepos.insert(repository) delegate?.didUpdate(dataController: self) } func unread(repository: V3Repository) { readRepos.remove(repository) delegate?.didUpdate(dataController: self) } func readAll() { _groupedNotifications.forEach { readRepos.insert($0.repo) } delegate?.didUpdate(dataController: self) } func unreadAll() { _groupedNotifications.forEach { readRepos.remove($0.repo) } delegate?.didUpdate(dataController: self) } func supply(notifications: [V3Notification]) { var map = [V3Repository: [V3Notification]]() for n in notifications { var arr = map[n.repository] ?? [] arr.append(n) map[n.repository] = arr } _groupedNotifications.removeAll() let repos = map.keys.sorted { $0.name.lowercased() < $1.name.lowercased() } for r in repos { guard let notes = map[r] else { continue } _groupedNotifications.append((r, notes)) } delegate?.didUpdate(dataController: self) } }
mit
28ceecab57101215d06d9443bdcd1973
27.134328
87
0.656233
4.383721
false
false
false
false
quangvu1994/Exchange
Exchange/AppDelegate.swift
1
7918
// // AppDelegate.swift // Exchange // // Created by Quang Vu on 7/3/17. // Copyright © 2017 Quang Vu. All rights reserved. // import UIKit import CoreData import Firebase import FirebaseAuthUI import FBSDKCoreKit import FBSDKLoginKit import GoogleSignIn import OneSignal @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { FirebaseApp.configure() GIDSignIn.sharedInstance().clientID = FirebaseApp.app()?.options.clientID // Invoked for proper use of Facebook SDK - In other words, setting up Facebook SDK FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions) let onesignalInitSettings = [kOSSettingsKeyAutoPrompt: false] OneSignal.initWithLaunchOptions(launchOptions, appId: "6a56a34f-6f38-4abf-9702-4be5da23dce7", handleNotificationAction: nil, settings: onesignalInitSettings) OneSignal.inFocusDisplayType = OSNotificationDisplayType.notification; OneSignal.add(self as OSSubscriptionObserver) configureInitialRootViewController(for: window) return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack @available(iOS 10.0, *) lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "Exchange") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { if #available(iOS 10.0, *) { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } else { // Fallback on earlier versions } } } extension AppDelegate: OSSubscriptionObserver { /** This method handle any URL that direct back to our application */ func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { // Call the mimic application(_:open url:options:) method from FBSDKApplicationDelegate to redirect back to our App if url.scheme == "fb1937120849899485" { let handled = FBSDKApplicationDelegate.sharedInstance().application(app, open: url, options: options) return handled } else { return GIDSignIn.sharedInstance().handle(url, sourceApplication:options[UIApplicationOpenURLOptionsKey.sourceApplication] as? String, annotation: [:]) } } func configureInitialRootViewController(for window: UIWindow?) { let defaults = UserDefaults.standard let initialViewController: UIViewController if Auth.auth().currentUser != nil, let userData = defaults.object(forKey: Constants.UserDefaults.currentUser) as? Data, let user = NSKeyedUnarchiver.unarchiveObject(with: userData) as? User { User.setCurrentUser(user) initialViewController = UIStoryboard.initialViewController(type: .main) } else { initialViewController = UIStoryboard.initialViewController(type: .login) } window?.rootViewController = initialViewController window?.makeKeyAndVisible() } // After you add the observer on didFinishLaunching, this method will be called when the notification subscription property changes. func onOSSubscriptionChanged(_ stateChanges: OSSubscriptionStateChanges!) { // If the user allow push notification if !stateChanges.from.subscribed && stateChanges.to.subscribed { //The player id is inside stateChanges if let playerId = stateChanges.to.userId { // Store the userID inside firebase print("Current playerId \(playerId)") } } } }
mit
d1a3f64a23a142a0345e2a3d5701bf67
45.846154
285
0.661362
5.881872
false
false
false
false
julienbodet/wikipedia-ios
Wikipedia/Code/ShareAFactViewController.swift
1
5819
import UIKit class ShareAFactViewController: UIViewController { @IBOutlet weak var articleTitleLabel: UILabel! @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var backgroundImageView: UIImageView! @IBOutlet weak var separatorView: UIView! @IBOutlet weak var imageContainerView: UIView! @IBOutlet weak var textLabel: UILabel! @IBOutlet weak var articleLicenseView: LicenseView! @IBOutlet weak var imageLicenseView: LicenseView! @IBOutlet weak var imageGradientView: WMFGradientView! @IBOutlet weak var imageWordmarkView: UIImageView! @IBOutlet weak var imageMadeWithLabel: UILabel! @IBOutlet weak var textWordmarkView: UIImageView! @IBOutlet weak var textMadeWithLabel: UILabel! @IBOutlet weak var articleTitleTrailingToTextWordmarkConstraint: NSLayoutConstraint! @IBOutlet weak var imageMadeWithLabelBottomConstraint: NSLayoutConstraint! @IBOutlet weak var imageViewTrailingConstraint: NSLayoutConstraint! @IBOutlet weak var imageViewWidthConstraint: NSLayoutConstraint! @IBOutlet var imageViewLetterboxConstraints: [NSLayoutConstraint]! override func viewDidLoad() { let theme = Theme.standard //always use the standard theme for now view.backgroundColor = theme.colors.paperBackground articleTitleLabel.textColor = theme.colors.primaryText separatorView.backgroundColor = theme.colors.border textLabel.textColor = theme.colors.primaryText articleLicenseView.tintColor = theme.colors.secondaryText imageLicenseView.tintColor = .white textMadeWithLabel.text = WMFLocalizedString("share-a-fact-made-with", value: "Made with the Wikipedia app", comment: "Indicates that the share-a-fact card was made with the Wikipedia app") imageMadeWithLabel.text = textMadeWithLabel.text imageGradientView.gradientLayer.colors = [UIColor.clear.cgColor, UIColor(white: 0, alpha: 0.1).cgColor, UIColor(white: 0, alpha: 0.4).cgColor] imageGradientView.gradientLayer.locations = [NSNumber(value: 0.0), NSNumber(value: 0.5), NSNumber(value: 1.0)] imageGradientView.gradientLayer.startPoint = CGPoint(x: 0.5, y: 0) imageGradientView.gradientLayer.endPoint = CGPoint(x: 0.5, y: 1) } public func update(with articleURL: URL, articleTitle: String?, text: String?, image: UIImage?, imageLicense: MWKLicense?) { view.semanticContentAttribute = MWLanguageInfo.semanticContentAttribute(forWMFLanguage: articleURL.wmf_language) textLabel.semanticContentAttribute = view.semanticContentAttribute articleTitleLabel.semanticContentAttribute = view.semanticContentAttribute imageContainerView.semanticContentAttribute = view.semanticContentAttribute imageLicenseView.semanticContentAttribute = view.semanticContentAttribute articleLicenseView.semanticContentAttribute = view.semanticContentAttribute let text = text ?? "" imageView.image = image isImageViewHidden = image == nil let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineSpacing = 7 textLabel.attributedText = NSAttributedString(string: text, attributes: [NSAttributedStringKey.paragraphStyle: paragraphStyle]) textLabel.font = UIFont.systemFont(ofSize: 20, weight: .medium) let width = isImageViewHidden ? view.bounds.size.width : round(0.5 * view.bounds.size.width) let size = textLabel.sizeThatFits(CGSize(width: width, height: view.bounds.size.height)) if size.height > 0.6 * view.bounds.size.height { textLabel.font = UIFont.systemFont(ofSize: 14) textLabel.attributedText = nil // without this line, the ellipsis wasn't being added at the end of the truncated text textLabel.text = text } articleTitleLabel.text = articleTitle let codes: [String] = imageLicense?.code?.lowercased().components(separatedBy: "-") ?? [] if codes.count == 0 { imageLicenseView.licenseCodes = ["generic"] if let shortDescription = imageLicense?.shortDescription { let label = UILabel() label.font = imageMadeWithLabel.font label.textColor = imageMadeWithLabel.textColor label.text = " " + shortDescription + " " imageLicenseView.addArrangedSubview(label) } } else { imageLicenseView.licenseCodes = codes } imageLicenseView.spacing = 0 articleLicenseView.licenseCodes = ["cc", "by", "sa"] articleLicenseView.spacing = 0 guard let image = image else { return } guard image.size.width > image.size.height else { return } let aspect = image.size.height / image.size.width let height = round(imageViewWidthConstraint.constant * aspect) let remainder = round(0.5 * (view.bounds.size.height - height)) guard remainder > ((view.bounds.size.height - imageWordmarkView.frame.origin.y) + imageMadeWithLabelBottomConstraint.constant) else { return } backgroundImageView.image = image for letterboxConstraint in imageViewLetterboxConstraints { letterboxConstraint.constant = remainder } } var isImageViewHidden: Bool = false { didSet { imageViewTrailingConstraint.constant = isImageViewHidden ? imageViewWidthConstraint.constant : 0 articleTitleTrailingToTextWordmarkConstraint.isActive = !isImageViewHidden textWordmarkView.isHidden = !isImageViewHidden textMadeWithLabel.isHidden = !isImageViewHidden } } }
mit
68343838b371f793aa88eb2f34131a3a
46.308943
196
0.692043
5.232914
false
false
false
false
parkera/swift-corelibs-foundation
Foundation/NSDecimalNumber.swift
1
18028
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // /*************** Exceptions ***********/ public struct NSExceptionName : RawRepresentable, Equatable, Hashable { public private(set) var rawValue: String public init(_ rawValue: String) { self.rawValue = rawValue } public init(rawValue: String) { self.rawValue = rawValue } public var hashValue: Int { return self.rawValue.hashValue } public static func ==(_ lhs: NSExceptionName, _ rhs: NSExceptionName) -> Bool { return lhs.rawValue == rhs.rawValue } } extension NSExceptionName { public static let decimalNumberExactnessException = NSExceptionName(rawValue: "NSDecimalNumberExactnessException") public static let decimalNumberOverflowException = NSExceptionName(rawValue: "NSDecimalNumberOverflowException") public static let decimalNumberUnderflowException = NSExceptionName(rawValue: "NSDecimalNumberUnderflowException") public static let decimalNumberDivideByZeroException = NSExceptionName(rawValue: "NSDecimalNumberDivideByZeroException") } /*************** Rounding and Exception behavior ***********/ // Rounding policies : // Original // value 1.2 1.21 1.25 1.35 1.27 // Plain 1.2 1.2 1.3 1.4 1.3 // Down 1.2 1.2 1.2 1.3 1.2 // Up 1.2 1.3 1.3 1.4 1.3 // Bankers 1.2 1.2 1.2 1.4 1.3 /*************** Type definitions ***********/ extension NSDecimalNumber { public enum RoundingMode : UInt { case plain // Round up on a tie case down // Always down == truncate case up // Always up case bankers // on a tie round so last digit is even } public enum CalculationError : UInt { case noError case lossOfPrecision // Result lost precision case underflow // Result became 0 case overflow // Result exceeds possible representation case divideByZero } } public protocol NSDecimalNumberBehaviors { func roundingMode() -> NSDecimalNumber.RoundingMode func scale() -> Int16 } // Receiver can raise, return a new value, or return nil to ignore the exception. fileprivate func handle(_ error: NSDecimalNumber.CalculationError, _ handler: NSDecimalNumberBehaviors) { // handle the error condition, such as throwing an error for over/underflow } /*************** NSDecimalNumber: the class ***********/ open class NSDecimalNumber : NSNumber { fileprivate let decimal: Decimal public convenience init(mantissa: UInt64, exponent: Int16, isNegative: Bool) { var d = Decimal(mantissa) d._exponent += Int32(exponent) d._isNegative = isNegative ? 1 : 0 self.init(decimal: d) } public init(decimal dcm: Decimal) { self.decimal = dcm super.init() } public convenience init(string numberValue: String?) { self.init(decimal: Decimal(string: numberValue ?? "") ?? Decimal.nan) } public convenience init(string numberValue: String?, locale: Any?) { self.init(decimal: Decimal(string: numberValue ?? "", locale: locale as? Locale) ?? Decimal.nan) } public required init?(coder: NSCoder) { guard coder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } let exponent:Int32 = coder.decodeInt32(forKey: "NS.exponent") let length:UInt32 = UInt32(coder.decodeInt32(forKey: "NS.length")) let isNegative:UInt32 = UInt32(coder.decodeBool(forKey: "NS.negative") ? 1 : 0) let isCompact:UInt32 = UInt32(coder.decodeBool(forKey: "NS.compact") ? 1 : 0) // let byteOrder:UInt32 = UInt32(coder.decodeInt32(forKey: "NS.bo")) guard let mantissaData: Data = coder.decodeObject(forKey: "NS.mantissa") as? Data else { return nil // raise "Critical NSDecimalNumber archived data is missing" } guard mantissaData.count == Int(NSDecimalMaxSize * 2) else { return nil // raise "Critical NSDecimalNumber archived data is wrong size" } // Byte order? let mantissa:(UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16) = ( UInt16(mantissaData[0]) << 8 & UInt16(mantissaData[1]), UInt16(mantissaData[2]) << 8 & UInt16(mantissaData[3]), UInt16(mantissaData[4]) << 8 & UInt16(mantissaData[5]), UInt16(mantissaData[6]) << 8 & UInt16(mantissaData[7]), UInt16(mantissaData[8]) << 8 & UInt16(mantissaData[9]), UInt16(mantissaData[10]) << 8 & UInt16(mantissaData[11]), UInt16(mantissaData[12]) << 8 & UInt16(mantissaData[13]), UInt16(mantissaData[14]) << 8 & UInt16(mantissaData[15]) ) self.decimal = Decimal(_exponent: exponent, _length: length, _isNegative: isNegative, _isCompact: isCompact, _reserved: 0, _mantissa: mantissa) super.init() } public init(value: Int) { decimal = Decimal(value) super.init() } public init(value: UInt) { decimal = Decimal(value) super.init() } public init(value: Int8) { decimal = Decimal(value) super.init() } public init(value: UInt8) { decimal = Decimal(value) super.init() } public init(value: Int16) { decimal = Decimal(value) super.init() } public init(value: UInt16) { decimal = Decimal(value) super.init() } public init(value: Int32) { decimal = Decimal(value) super.init() } public init(value: UInt32) { decimal = Decimal(value) super.init() } public init(value: Int64) { decimal = Decimal(value) super.init() } public init(value: UInt64) { decimal = Decimal(value) super.init() } public init(value: Bool) { decimal = Decimal(value ? 1 : 0) super.init() } public init(value: Float) { decimal = Decimal(Double(value)) super.init() } public init(value: Double) { decimal = Decimal(value) super.init() } public required convenience init(floatLiteral value: Double) { self.init(decimal:Decimal(value)) } public required convenience init(booleanLiteral value: Bool) { if value { self.init(integerLiteral: 1) } else { self.init(integerLiteral: 0) } } public required convenience init(integerLiteral value: Int) { self.init(decimal:Decimal(value)) } public required convenience init(bytes buffer: UnsafeRawPointer, objCType type: UnsafePointer<Int8>) { NSRequiresConcreteImplementation() } open override var description: String { return self.decimal.description } open override func description(withLocale locale: Locale?) -> String { guard locale == nil else { fatalError("Locale not supported: \(locale!)") } return self.decimal.description } open class var zero: NSDecimalNumber { return NSDecimalNumber(integerLiteral: 0) } open class var one: NSDecimalNumber { return NSDecimalNumber(integerLiteral: 1) } open class var minimum: NSDecimalNumber { return NSDecimalNumber(decimal:Decimal.leastFiniteMagnitude) } open class var maximum: NSDecimalNumber { return NSDecimalNumber(decimal:Decimal.greatestFiniteMagnitude) } open class var notANumber: NSDecimalNumber { return NSDecimalNumber(decimal: Decimal.nan) } open func adding(_ other: NSDecimalNumber) -> NSDecimalNumber { return adding(other, withBehavior: nil) } open func adding(_ other: NSDecimalNumber, withBehavior b: NSDecimalNumberBehaviors?) -> NSDecimalNumber { var result = Decimal() var left = self.decimal var right = other.decimal let behavior = b ?? NSDecimalNumber.defaultBehavior let roundingMode = behavior.roundingMode() let error = NSDecimalAdd(&result, &left, &right, roundingMode) handle(error,behavior) return NSDecimalNumber(decimal: result) } open func subtracting(_ other: NSDecimalNumber) -> NSDecimalNumber { return subtracting(other, withBehavior: nil) } open func subtracting(_ other: NSDecimalNumber, withBehavior b: NSDecimalNumberBehaviors?) -> NSDecimalNumber { var result = Decimal() var left = self.decimal var right = other.decimal let behavior = b ?? NSDecimalNumber.defaultBehavior let roundingMode = behavior.roundingMode() let error = NSDecimalSubtract(&result, &left, &right, roundingMode) handle(error,behavior) return NSDecimalNumber(decimal: result) } open func multiplying(by other: NSDecimalNumber) -> NSDecimalNumber { return multiplying(by: other, withBehavior: nil) } open func multiplying(by other: NSDecimalNumber, withBehavior b: NSDecimalNumberBehaviors?) -> NSDecimalNumber { var result = Decimal() var left = self.decimal var right = other.decimal let behavior = b ?? NSDecimalNumber.defaultBehavior let roundingMode = behavior.roundingMode() let error = NSDecimalMultiply(&result, &left, &right, roundingMode) handle(error,behavior) return NSDecimalNumber(decimal: result) } open func dividing(by other: NSDecimalNumber) -> NSDecimalNumber { return dividing(by: other, withBehavior: nil) } open func dividing(by other: NSDecimalNumber, withBehavior b: NSDecimalNumberBehaviors?) -> NSDecimalNumber { var result = Decimal() var left = self.decimal var right = other.decimal let behavior = b ?? NSDecimalNumber.defaultBehavior let roundingMode = behavior.roundingMode() let error = NSDecimalDivide(&result, &left, &right, roundingMode) handle(error,behavior) return NSDecimalNumber(decimal: result) } open func raising(toPower power: Int) -> NSDecimalNumber { return raising(toPower:power, withBehavior: nil) } open func raising(toPower power: Int, withBehavior b: NSDecimalNumberBehaviors?) -> NSDecimalNumber { var result = Decimal() var input = self.decimal let behavior = b ?? NSDecimalNumber.defaultBehavior let roundingMode = behavior.roundingMode() let error = NSDecimalPower(&result, &input, power, roundingMode) handle(error,behavior) return NSDecimalNumber(decimal: result) } open func multiplying(byPowerOf10 power: Int16) -> NSDecimalNumber { return multiplying(byPowerOf10: power, withBehavior: nil) } open func multiplying(byPowerOf10 power: Int16, withBehavior b: NSDecimalNumberBehaviors?) -> NSDecimalNumber { var result = Decimal() var input = self.decimal let behavior = b ?? NSDecimalNumber.defaultBehavior let roundingMode = behavior.roundingMode() let error = NSDecimalPower(&result, &input, Int(power), roundingMode) handle(error,behavior) return NSDecimalNumber(decimal: result) } // Round to the scale of the behavior. open func rounding(accordingToBehavior b: NSDecimalNumberBehaviors?) -> NSDecimalNumber { var result = Decimal() var input = self.decimal let behavior = b ?? NSDecimalNumber.defaultBehavior let roundingMode = behavior.roundingMode() let scale = behavior.scale() NSDecimalRound(&result, &input, Int(scale), roundingMode) return NSDecimalNumber(decimal: result) } // compare two NSDecimalNumbers open override func compare(_ decimalNumber: NSNumber) -> ComparisonResult { if let num = decimalNumber as? NSDecimalNumber { return decimal.compare(to:num.decimal) } else { return decimal.compare(to:Decimal(decimalNumber.doubleValue)) } } open class var defaultBehavior: NSDecimalNumberBehaviors { return NSDecimalNumberHandler.defaultBehavior } // One behavior per thread - The default behavior is // rounding mode: NSRoundPlain // scale: No defined scale (full precision) // ignore exactnessException // raise on overflow, underflow and divide by zero. static let OBJC_TYPE = "d".utf8CString open override var objCType: UnsafePointer<Int8> { return NSDecimalNumber.OBJC_TYPE.withUnsafeBufferPointer{ $0.baseAddress! } } // return 'd' for double open override var int8Value: Int8 { return Int8(truncatingIfNeeded: decimal.int64Value) } open override var uint8Value: UInt8 { return UInt8(truncatingIfNeeded: decimal.uint64Value) } open override var int16Value: Int16 { return Int16(truncatingIfNeeded: decimal.int64Value) } open override var uint16Value: UInt16 { return UInt16(truncatingIfNeeded: decimal.uint64Value) } open override var int32Value: Int32 { return Int32(truncatingIfNeeded: decimal.int64Value) } open override var uint32Value: UInt32 { return UInt32(truncatingIfNeeded: decimal.uint64Value) } open override var int64Value: Int64 { return decimal.int64Value } open override var uint64Value: UInt64 { return decimal.uint64Value } open override var floatValue: Float { return Float(decimal.doubleValue) } open override var doubleValue: Double { return decimal.doubleValue } open override var boolValue: Bool { return !decimal.isZero } open override var intValue: Int { return Int(truncatingIfNeeded: decimal.int64Value) } open override var uintValue: UInt { return UInt(truncatingIfNeeded: decimal.uint64Value) } open override func isEqual(_ value: Any?) -> Bool { guard let other = value as? NSDecimalNumber else { return false } return self.decimal == other.decimal } override var _swiftValueOfOptimalType: Any { return decimal } } // return an approximate double value /*********** A class for defining common behaviors *******/ open class NSDecimalNumberHandler : NSObject, NSDecimalNumberBehaviors, NSCoding { static let defaultBehavior = NSDecimalNumberHandler() let _roundingMode: NSDecimalNumber.RoundingMode let _scale:Int16 let _raiseOnExactness: Bool let _raiseOnOverflow: Bool let _raiseOnUnderflow: Bool let _raiseOnDivideByZero: Bool public override init() { _roundingMode = .plain _scale = Int16(NSDecimalNoScale) _raiseOnExactness = false _raiseOnOverflow = true _raiseOnUnderflow = true _raiseOnDivideByZero = true } public required init?(coder: NSCoder) { guard coder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } _roundingMode = NSDecimalNumber.RoundingMode(rawValue: UInt(coder.decodeInteger(forKey: "NS.roundingMode")))! if coder.containsValue(forKey: "NS.scale") { _scale = Int16(coder.decodeInteger(forKey: "NS.scale")) } else { _scale = Int16(NSDecimalNoScale) } _raiseOnExactness = coder.decodeBool(forKey: "NS.raise.exactness") _raiseOnOverflow = coder.decodeBool(forKey: "NS.raise.overflow") _raiseOnUnderflow = coder.decodeBool(forKey: "NS.raise.underflow") _raiseOnDivideByZero = coder.decodeBool(forKey: "NS.raise.dividebyzero") } open func encode(with coder: NSCoder) { guard coder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } if _roundingMode != .plain { coder.encode(Int(_roundingMode.rawValue), forKey: "NS.roundingmode") } if _scale != Int16(NSDecimalNoScale) { coder.encode(_scale, forKey:"NS.scale") } if _raiseOnExactness { coder.encode(_raiseOnExactness, forKey:"NS.raise.exactness") } if _raiseOnOverflow { coder.encode(_raiseOnOverflow, forKey:"NS.raise.overflow") } if _raiseOnUnderflow { coder.encode(_raiseOnUnderflow, forKey:"NS.raise.underflow") } if _raiseOnDivideByZero { coder.encode(_raiseOnDivideByZero, forKey:"NS.raise.dividebyzero") } } open class var `default`: NSDecimalNumberHandler { return defaultBehavior } // rounding mode: NSRoundPlain // scale: No defined scale (full precision) // ignore exactnessException (return nil) // raise on overflow, underflow and divide by zero. public init(roundingMode: NSDecimalNumber.RoundingMode, scale: Int16, raiseOnExactness exact: Bool, raiseOnOverflow overflow: Bool, raiseOnUnderflow underflow: Bool, raiseOnDivideByZero divideByZero: Bool) { _roundingMode = roundingMode _scale = scale _raiseOnExactness = exact _raiseOnOverflow = overflow _raiseOnUnderflow = underflow _raiseOnDivideByZero = divideByZero } open func roundingMode() -> NSDecimalNumber.RoundingMode { return _roundingMode } // The scale could return NoScale for no defined scale. open func scale() -> Int16 { return _scale } } extension NSNumber { public var decimalValue: Decimal { if let d = self as? NSDecimalNumber { return d.decimal } else { return Decimal(self.doubleValue) } } }
apache-2.0
4dbf196fb251aaabdabe8ee1b0eb6342
33.339048
211
0.646494
4.764271
false
false
false
false
gcolema/tapnotes
TapNotes/AppDelegate.swift
1
6098
// // AppDelegate.swift // TapNotes // // Created by Georgina Coleman on 11/15/15. // Copyright © 2015 Georgina Coleman. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "coleman.TapNotes" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("TapNotes", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
mit
0ce9a7a19579f2d1b9d3864b2da0a62f
53.927928
291
0.719862
5.885135
false
false
false
false
MellongLau/CocoRongPullToRefresh
CocoRongPullToRefresh/CocoRongPullToRefresh.swift
1
12370
// // Copyright (c) 2017 Mellong Lau // https://github.com/MellongLau/CocoRongPullToRefresh // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit public protocol LoadingView { func setup() func setProgress(progress: CGFloat) func reset() func startLoadingAnimation() func stopLoadingAnimation() } public final class CocoRongPullToRefresh<Base> { fileprivate let base: Base public init(_ base: Base) { self.base = base } } public protocol CocoRongPullToRefreshCompatible { associatedtype CompatibleType var cr: CompatibleType { get } } public extension CocoRongPullToRefreshCompatible { public var cr: CocoRongPullToRefresh<Self> { get { return CocoRongPullToRefresh(self) } } } // MARK: - Core Implementation private var kIsPullRefreshable: Void? private var kPullRefreshView: Void? private var kCompletion: Void? private var kTintColor: Void? struct CRCongfiguration { public static var radius: CGFloat = 10.0 public static var offsetTop: CGFloat = 80.0 public static var maxHeight: CGFloat = 50.0 } /// Const string struct CRKVOKey { public static var contentOffset: String = "contentOffset" public static var panGestureRecognizerState: String = "panGestureRecognizer.state" public static var contentInset: String = "contentInset" } extension CocoRongPullToRefresh where Base: UITableView { private var pullRefreshView: PullToRefreshView? { get { return objc_getAssociatedObject(base, &kPullRefreshView) as? PullToRefreshView } set { objc_setAssociatedObject(base, &kPullRefreshView, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } public var tintColor: UIColor? { get { return objc_getAssociatedObject(base, &kTintColor) as? UIColor } set { objc_setAssociatedObject(base, &kTintColor, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) pullRefreshView?.tintColor = newValue pullRefreshView?.updateTintColor() } } /// Manual start refresh public func startRefresh() { pullRefreshView?.startRefresh() } /// Finish refresh public func stopRefresh() { guard let pullRefreshView = pullRefreshView else { return } pullRefreshView.stopLoading() } public func remove() { removeAllObservers() } private func removeAllObservers() { guard let pullRefreshView = pullRefreshView else { return } base.removeObserver(pullRefreshView, forKeyPath: CRKVOKey.contentInset) base.removeObserver(pullRefreshView, forKeyPath: CRKVOKey.contentOffset) base.removeObserver(pullRefreshView, forKeyPath: CRKVOKey.panGestureRecognizerState) } /// Enable pull to refresh feature. /// /// - Parameter didStartLoadClosure: the closure to be executed when pull refresh did start loading. public func enablePullRefresh(didStartLoadClosure: @escaping () -> Void) { enablePullRefresh(loadingView: LoadingCircleView(), didStartLoadClosure: didStartLoadClosure) } public func enablePullRefresh(loadingView: LoadingView, didStartLoadClosure: @escaping () -> Void) { isPullRefreshable = true let pullRefreshView = PullToRefreshView(loadingView: loadingView) pullRefreshView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 0) self.base.insertSubview(pullRefreshView, at: 0) pullRefreshView.setup() pullRefreshView.startLoadClosure = didStartLoadClosure self.pullRefreshView = pullRefreshView } private var isPullRefreshable: Bool { get { return objc_getAssociatedObject(base, &kIsPullRefreshable) as? Bool ?? false } set { objc_setAssociatedObject(base, &kIsPullRefreshable, newValue, .OBJC_ASSOCIATION_ASSIGN) } } } extension UIScrollView: CocoRongPullToRefreshCompatible { } // MARK: Animation and logic public class PullToRefreshView: UIView { var startLoadClosure: (() -> Void)? var isStartLoading: Bool = false var isDragging: Bool = false var shouldObserve: Bool = true var isManualRefresh: Bool = false var currentContentTop: CGFloat? var isFinishLoading: Bool = false var loadingCircleView: LoadingView init(loadingView: LoadingView) { self.loadingCircleView = loadingView super.init(frame: CGRect.zero) } private func addObservers() { scrollView.addObserver(self, forKeyPath: CRKVOKey.contentOffset, options: .new, context: nil) scrollView.addObserver(self, forKeyPath: CRKVOKey.contentInset, options: .new, context: nil) scrollView.addObserver(self, forKeyPath: CRKVOKey.panGestureRecognizerState, options: .new, context: nil) } fileprivate func setup() { guard let view = loadingCircleView as? UIView else { fatalError("Loading view is not a subclass of UIView") } addSubview(view) addObservers() let centerX = UIScreen.main.bounds.size.width/2.0 let centerY = CRCongfiguration.maxHeight / 2.0 view.center = CGPoint(x: centerX, y: centerY) updateTintColor() print(self.frame.origin.y) loadingCircleView.setup() } fileprivate func updateTintColor() { backgroundColor = tintColor } fileprivate var scrollView: UIScrollView { get { return superview as! UIScrollView } } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /// Manual start refresh. public func startRefresh() { if isManualRefresh { print("Error: pull refresh already running!") return } isManualRefresh = true scrollView.setContentOffset(CGPoint(x: 0, y: scrollView.contentOffset.y - CRCongfiguration.maxHeight), animated: true) disableAnimation { loadingCircleView.setProgress(progress: 1.0) } loadingCircleView.startLoadingAnimation() scrollView.isScrollEnabled = false startLoadClosure?() } public func stopLoading() { shouldObserve = true isStartLoading = false loadCompletion() isManualRefresh = false } public func disableAnimation(closure: () -> Void) { CATransaction.begin() CATransaction.setDisableActions(true) closure() CATransaction.commit() } private func handleContentOffset(change: [NSKeyValueChangeKey : Any]?) { if let contentOffset = change?[.newKey] { let y = (contentOffset as AnyObject).cgPointValue.y // End dragging if isStartLoading { // Use shouldObserve flag to call startLoadClosure() once, call the network request first. if let startLoadClosure = startLoadClosure, shouldObserve { startLoadClosure() } shouldObserve = false if let top = currentContentTop { let isReachMaxHeightOffsetY = (y >= -top - CRCongfiguration.maxHeight) if !isDragging && isReachMaxHeightOffsetY && scrollView.isScrollEnabled { scrollView.contentInset.top = top + CRCongfiguration.maxHeight // Disable scrollable of the scroll view when contentOffset reach the pullRefreshView max height. scrollView.isScrollEnabled = false loadingCircleView.startLoadingAnimation() } } } // Keep updating the progress status when is dragging. if isDragging { let progress = getCurrentProgress() disableAnimation { loadingCircleView.reset() let result = (progress >= 1.0 ? 1.0 : progress) loadingCircleView.setProgress(progress: result) } } // Restore back to the original state when refresh is finish if isFinishLoading { if let top = currentContentTop, y == -top { scrollView.contentInset.top = currentContentTop! scrollView.isScrollEnabled = true } } } } public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { updateLayout() if isManualRefresh { return } if keyPath == CRKVOKey.contentOffset { handleContentOffset(change: change) }else if keyPath == CRKVOKey.panGestureRecognizerState { let newState = scrollView.panGestureRecognizer.state if newState == .began { isDragging = true isFinishLoading = false isStartLoading = false } if newState == .ended && isDragging { let progress = getCurrentProgress() // Ignore dragging up case. if scrollView.contentOffset.y > -scrollView.contentInset.top { return } if progress >= 1.0 && scrollView.contentOffset.y != 0 { isStartLoading = true isDragging = false } } }else if keyPath == CRKVOKey.contentInset && currentContentTop == nil { if let contentOffset = change?[.newKey] { currentContentTop = (contentOffset as! UIEdgeInsets).top } } } private func getCurrentProgress() -> CGFloat { let factor: CGFloat = 1.5 return frame.size.height / (CRCongfiguration.maxHeight * factor) } private func loadCompletion() { loadingCircleView.stopLoadingAnimation() disableAnimation { loadingCircleView.reset() } updateLayout() isFinishLoading = true scrollView.setContentOffset(CGPoint(x: 0, y: -(currentContentTop ?? 0)), animated: true) } /// Update PullToRefreshView layout. private func updateLayout() { let height = -scrollView.contentOffset.y - (currentContentTop ?? 0.0) frame.size.height = height < 0 ? 0: height frame.origin.y = -frame.size.height } public override func layoutSubviews() { super.layoutSubviews() updateLayout() } }
mit
e055b9a4e457609e0fbf4b3a09a1c263
31.552632
126
0.604689
5.361942
false
false
false
false
naokits/my-programming-marathon
NCMB_iOSAppDemo/NCMB_iOSAppDemo/AppDelegate.swift
1
5642
// // AppDelegate.swift // NCMB_iOSAppDemo // // Created by Naoki Tsutsui on 1/30/16. // Copyright © 2016 Naoki Tsutsui. All rights reserved. // import UIKit import NCMB @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { // MARK: - Properties var window: UIWindow? // MARK: - Application Cycle func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. let splitViewController = self.window!.rootViewController as! UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem() splitViewController.delegate = self setups() return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // MARK: - Remote Notification func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) { //端末情報を扱うNCMBInstallationのインスタンスを作成 let installation = NCMBInstallation.currentInstallation() installation.setDeviceTokenFromData(deviceToken) installation.channels = ["global"] installation.saveInBackgroundWithBlock { error in if let e = error { print("端末情報の保存失敗: \(e)") } else { print("端末情報の保存成功") } } } /// プッシュ通知時とプッシュ通知からタッチして起動したとき両方とも呼ばれる func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) { print("UserInfo: \(userInfo)") if (application.applicationState == UIApplicationState.Inactive){ // 通知タップ時の起動処理 } else if (application.applicationState == UIApplicationState.Active) { // 起動時 } else { // バックグラウンド? } } // MARK: - Split view func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool { guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false } guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false } if topAsDetailController.detailItem == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } return false } // MARK: - Setups func setups() { setupBaaS() setupRemoteNotification() } // MARK: - Setup Notification func setupRemoteNotification() { let types:UIUserNotificationType = ([.Alert, .Sound, .Badge]) let settings:UIUserNotificationSettings = UIUserNotificationSettings(forTypes: types, categories: nil) let application = UIApplication.sharedApplication() application.registerUserNotificationSettings(settings) application.registerForRemoteNotifications() } // 他の記述方法 func setupRemoteNotification2() { let category = UIMutableUserNotificationCategory() let categories = NSSet(object: category) as! Set<UIUserNotificationCategory> let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: categories) UIApplication.sharedApplication().registerUserNotificationSettings(settings) } }
mit
639d813407f5edc0dd6ca2d209b172a6
44.358333
285
0.720191
5.76589
false
false
false
false
Olinguito/QuidiOS
createRoute/WireFrame/createRouteWireFrame.swift
1
2367
// // Created by VIPER // Copyright (c) 2015 VIPER. All rights reserved. // import Foundation import UIKit class createRouteWireFrame: NSObject, createRouteWireFrameProtocol, UIViewControllerTransitioningDelegate { class func presentcreateRouteModule(fromView view: UIViewController) { // Generating module components let view2: createRouteViewProtocol = createRouteView() let presenter: protocol<createRoutePresenterProtocol, createRouteInteractorOutputProtocol> = createRoutePresenter() let interactor: createRouteInteractorInputProtocol = createRouteInteractor() let APIDataManager: createRouteAPIDataManagerInputProtocol = createRouteAPIDataManager() let localDataManager: createRouteLocalDataManagerInputProtocol = createRouteLocalDataManager() let wireFrame: createRouteWireFrameProtocol = createRouteWireFrame() // Connecting view2.presenter = presenter presenter.view = view2 presenter.wireFrame = wireFrame presenter.interactor = interactor interactor.presenter = presenter interactor.APIDataManager = APIDataManager interactor.localDatamanager = localDataManager (view2 as! UIViewController).modalPresentationStyle = .Custom (view2 as! UIViewController).modalTransitionStyle = .CrossDissolve (view2 as! UIViewController).transitioningDelegate = self as! UIViewControllerTransitioningDelegate view.presentViewController(view2 as! UIViewController, animated: true, completion: nil) } func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { print("dsfsdfsdf") return createRouteTransition() } func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { print("Concha de tu abuela") return createRouteTransition() } }
gpl-2.0
dff1dd4e683c059a3e071833debe0f8a
46.36
217
0.664977
7.002959
false
false
false
false
richeterre/jumu-nordost-ios
JumuNordost/Application/ContestFormatter.swift
1
991
// // ContestFormatter.swift // JumuNordost // // Created by Martin Richter on 24/02/16. // Copyright © 2016 Martin Richter. All rights reserved. // import Foundation struct FormattedContest { let name: String let dates: String } class ContestFormatter { private static let dateIntervalFormatter: NSDateIntervalFormatter = { let formatter = NSDateIntervalFormatter() formatter.dateStyle = .LongStyle formatter.timeStyle = .NoStyle formatter.locale = NSLocale.localeMatchingAppLanguage() return formatter }() // MARK: - Formatting static func formattedContest(contest: Contest) -> FormattedContest { dateIntervalFormatter.timeZone = contest.timeZone // TODO: Eliminate this state return FormattedContest( name: "\(contest.hostCountry.toCountryFlag()) \(contest.name)", dates: dateIntervalFormatter.stringFromDate(contest.startDate, toDate: contest.endDate) ) } }
mit
c497fa4087616b6e272407083a4c2f57
25.756757
99
0.687879
4.583333
false
true
false
false
shepting/AppleToast
Billboard/Toast/ToastView.swift
1
1519
// // ToastView.swift // Toast // // Created by Steven Hepting on 9/10/16. // Copyright © 2016 Hepting. All rights reserved. // import UIKit class ToastView: UIView { // let defaultFrame = CGRect(x: 100, y: 50, width: 200, height: 100) var stackView = UIStackView() let spinner = UIActivityIndicatorView() let mainLabel = UILabel() let detailLabel = UILabel() let image = UIImage() let button = UIButton() } extension ToastView { convenience init<T: Toastable>(message: T) { self.init() backgroundColor = .black layer.cornerRadius = 4 // Main mainLabel.textColor = .white mainLabel.text = message.mainMessage() // Detail detailLabel.textColor = .lightGray detailLabel.text = message.detailMessage() // Stack View stackView = UIStackView(arrangedSubviews: [mainLabel, detailLabel]) stackView.isLayoutMarginsRelativeArrangement = true stackView.addArrangedSubview(mainLabel) stackView.addArrangedSubview(detailLabel) stackView.axis = .vertical stackView.frame = self.bounds addSubview(stackView) stackView.spacing = 10 stackView.layoutMargins = UIEdgeInsetsMake(10, 10, 10, 10) stackView.translatesAutoresizingMaskIntoConstraints = false stackView.fillSuperview() } override func didMoveToSuperview() { translatesAutoresizingMaskIntoConstraints = false constrainNearTop() } }
mit
50246726a7af6c77e2b2dcacc849fcc6
24.728814
75
0.656785
4.993421
false
false
false
false
icecrystal23/ios-charts
ChartsDemo-iOS/Swift/Demos/AnotherBarChartViewController.swift
1
3018
// // AnotherBarChartViewController.swift // ChartsDemo-iOS // // Created by Jacob Christie on 2017-07-09. // Copyright © 2017 jc. All rights reserved. // import UIKit import Charts class AnotherBarChartViewController: DemoBaseViewController { @IBOutlet var chartView: BarChartView! @IBOutlet var sliderX: UISlider! @IBOutlet var sliderY: UISlider! @IBOutlet var sliderTextX: UITextField! @IBOutlet var sliderTextY: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.title = "Another Bar Chart" self.options = [.toggleValues, .toggleHighlight, .animateX, .animateY, .animateXY, .saveToGallery, .togglePinchZoom, .toggleData, .toggleBarBorders] chartView.delegate = self chartView.chartDescription?.enabled = false chartView.maxVisibleCount = 60 chartView.pinchZoomEnabled = false chartView.drawBarShadowEnabled = false let xAxis = chartView.xAxis xAxis.labelPosition = .bottom chartView.legend.enabled = false sliderX.value = 10 sliderY.value = 100 self.slidersValueChanged(nil) } override func updateChartData() { if self.shouldHideData { chartView.data = nil return } self.setDataCount(Int(sliderX.value) + 1, range: Double(sliderY.value)) } func setDataCount(_ count: Int, range: Double) { let yVals = (0..<count).map { (i) -> BarChartDataEntry in let mult = range + 1 let val = Double(arc4random_uniform(UInt32(mult))) + mult/3 return BarChartDataEntry(x: Double(i), y: val) } var set1: BarChartDataSet! = nil if let set = chartView.data?.dataSets.first as? BarChartDataSet { set1 = set set1?.values = yVals chartView.data?.notifyDataChanged() chartView.notifyDataSetChanged() } else { set1 = BarChartDataSet(values: yVals, label: "Data Set") set1.colors = ChartColorTemplates.vordiplom() set1.drawValuesEnabled = false let data = BarChartData(dataSet: set1) chartView.data = data chartView.fitBars = true } chartView.setNeedsDisplay() } override func optionTapped(_ option: Option) { super.handleOption(option, forChartView: chartView) } // MARK: - Actions @IBAction func slidersValueChanged(_ sender: Any?) { sliderTextX.text = "\(Int(sliderX.value))" sliderTextY.text = "\(Int(sliderY.value))" self.updateChartData() } }
apache-2.0
fb192422ff85bcccc8fbf3617adb50b6
29.17
79
0.560491
5.201724
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/WordPressTest/Services/PostCoordinatorFailedPostsFetcherTests.swift
1
3007
import Nimble import XCTest @testable import WordPress class PostCoordinatorFailedPostsFetcherTests: CoreDataTestCase { private var fetcher: PostCoordinator.FailedPostsFetcher! override func setUp() { super.setUp() fetcher = PostCoordinator.FailedPostsFetcher(mainContext) } override func tearDown() { super.tearDown() fetcher = nil } func testItReturnsPostsThatCanBeAutoUploadedOrAutoSaved() { // Arrange let expectedPosts = [ createPost(status: .draft), createPost(status: .draft), createPost(status: .draft), createPost(status: .publish), createPost(status: .draft, hasRemote: true), createPost(status: .publish, hasRemote: true), createPost(status: .publishPrivate), createPost(status: .publishPrivate, hasRemote: true), createPost(status: .scheduled), createPost(status: .scheduled, hasRemote: true), createPost(status: .pending), createPost(status: .pending, hasRemote: true), ] let unexpectedPosts = [ createPost(status: .trash), createPost(status: .trash, hasRemote: true), // Local draft that we never attempted to upload so it never failed createPost(status: .draft, remoteStatus: .local) ] // Act let posts = fetcher.getPostsToRetrySync() // Assert expect(posts).to(haveCount(expectedPosts.count)) expect(posts).to(contain(expectedPosts)) expect(posts).notTo(contain(unexpectedPosts)) } } private extension PostCoordinatorFailedPostsFetcherTests { func createPost(status: BasePost.Status, remoteStatus: AbstractPostRemoteStatus = .failed, hasRemote: Bool = false, blog: Blog? = nil) -> Post { let post = Post(context: mainContext) post.status = status post.remoteStatus = remoteStatus if hasRemote { post.postID = NSNumber(value: Int.random(in: 1...Int.max)) } if let blog = blog { post.blog = blog } else { post.blog = createBlog(supportsWPComAPI: true) } return post } func createBlog(supportsWPComAPI: Bool) -> Blog { let blog = NSEntityDescription.insertNewObject(forEntityName: "Blog", into: mainContext) as! Blog if supportsWPComAPI { blog.supportsWPComAPI() } return blog } } private extension PostCoordinator.FailedPostsFetcher { func getPostsToRetrySync() -> [AbstractPost] { var result = [AbstractPost]() waitUntil(timeout: DispatchTimeInterval.seconds(5)) { done in self.postsAndRetryActions { postsAndActions in result = Array(postsAndActions.filter { $1 != .nothing }.keys) done() } } return result } }
gpl-2.0
6cec8983934af3df97a813fc72fc245b
30
105
0.601596
4.8112
false
true
false
false
j-pk/grub-api
Sources/App/Controllers/GrubController.swift
1
4805
// // GrubController.swift // GrubAPI // // Created by Jameson Kirby on 1/31/17. // // import Vapor import HTTP import VaporPostgreSQL import Foundation final class GrubController { func addRoutes(drop: Droplet) { let grubapi_v1 = drop.grouped("v1").grouped(TokenAuthMiddleware()) grubapi_v1.get("version", handler: version) grubapi_v1.post("places/search", handler: search_grub) grubapi_v1.get("places/random", handler: random) grubapi_v1.post("places/location/search", handler: search_google) grubapi_v1.get("places/genre/:id", handler: place_genre) grubapi_v1.post("details", handler: place_details) } func version(request: Request) throws -> ResponseRepresentable { if let db = drop.database?.driver as? PostgreSQLDriver { let db_version = try db.raw("SELECT version()") let grubapi_version = try Node(node: ["API Version": "1.0"]) return try JSON(node: [grubapi_version, db_version]) } else { return "Database Connection Failed" } } //search Grub_DB func search_grub(request: Request) throws -> ResponseRepresentable { guard let name = request.data["name"]?.string else { throw Abort.badRequest } return try JSON(node: Place.query().filter("name", contains: name).all()) } func place_genre(request: Request) throws -> ResponseRepresentable { guard let genre = request.parameters["id"]?.int else { throw Abort.badRequest } return try JSON(node: Place.query().filter("genre", .equals, genre).all()) } //search Google_Places func search_google(request: Request) throws -> ResponseRepresentable { guard let location_latitude = request.data["latitude"]?.double, let location_longitude = request.data["longitude"]?.double, var search_radius = request.data["radius"]?.int, let search_name = request.data["name"]?.string else { throw Abort.custom(status: .badRequest, message: "Latitude, Longitude require double values. Radius requires an int.") } do { search_radius = try search_radius.validated(by: Count.max(50000)).value } catch { throw Abort.custom(status: .badRequest, message: "Radius exceeds maxium allowed meters") } let place_json = try drop.client.get(google_place_api_url + "nearbysearch/json?", query: ["location": "\(location_latitude),\(location_longitude)", "radius": search_radius, "type": "restaurant", "keyword": search_name, "key": key]) return try parse_google_json(response: place_json) } func parse_google_json(response: Response) throws -> JSON { guard let places = response.data["results"]?.array else { throw Abort.custom(status: .badRequest, message: "No results") } var place_array = [Place]() do { try places.forEach({ place in guard let name = place.object?["name"]?.string else { throw Abort.custom(status: .expectationFailed, message: "Failed to parse name") } guard let location = place.object?["vicinity"]?.string else { throw Abort.custom(status: .expectationFailed, message: "Failed to parse location") } let cost = place.object?["price_level"]?.int != nil ? (place.object?["price_level"]?.int)! - 1 : nil place_array.append(Place.init(name: name, location: location, cost: cost)) }) } return try place_array.makeJSON() } func place_details(request: Request) throws -> ResponseRepresentable { guard let place_id = request.data["google_place_id"]?.string else { throw Abort.custom(status: .badRequest, message: "Invalid place_id") } return try drop.client.get(google_place_api_url + "details/json?", query: ["placeid": place_id, "key": key]) } func random(request: Request) throws -> ResponseRepresentable { let places = try Place.all() var randomIndex: Int = 0 #if os(Linux) let time = UInt32(NSDate().timeIntervalSinceReferenceDate) srand(time) randomIndex = Int(rand() % Int32(places.count)) #else randomIndex = Int(arc4random_uniform(UInt32(places.count))) #endif return places[randomIndex] } }
mit
1c73d40b77d82cde3210381c1d93f0d2
39.041667
163
0.573153
4.444958
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/Models/Blog+Post.swift
1
3891
import Foundation // MARK: - Lookup posts extension Blog { /// Lookup a post in the blog. /// /// - Parameter postID: The ID associated with the post. /// - Returns: The `AbstractPost` associated with the given post ID. @objc(lookupPostWithID:inContext:) func lookupPost(withID postID: NSNumber, in context: NSManagedObjectContext) -> AbstractPost? { lookupPost(withID: postID.int64Value, in: context) } /// Lookup a post in the blog. /// /// - Parameter postID: The ID associated with the post. /// - Returns: The `AbstractPost` associated with the given post ID. func lookupPost(withID postID: Int, in context: NSManagedObjectContext) -> AbstractPost? { lookupPost(withID: Int64(postID), in: context) } /// Lookup a post in the blog. /// /// - Parameter postID: The ID associated with the post. /// - Returns: The `AbstractPost` associated with the given post ID. func lookupPost(withID postID: Int64, in context: NSManagedObjectContext) -> AbstractPost? { let request = NSFetchRequest<AbstractPost>(entityName: NSStringFromClass(AbstractPost.self)) request.predicate = NSPredicate(format: "blog = %@ AND original = NULL AND postID = %ld", self, postID) return (try? context.fetch(request))?.first } } // MARK: - Create posts extension Blog { /// Create a post in the blog. @objc func createPost() -> Post { guard let context = managedObjectContext else { fatalError("The `Blog` instance is not associated with an `NSManagedObjectContext`") } let post = NSEntityDescription.insertNewObject(forEntityName: NSStringFromClass(Post.self), into: context) as! Post post.blog = self post.remoteStatus = .sync if let categoryID = settings?.defaultCategoryID, categoryID.intValue != PostCategoryUncategorized, let category = PostCategoryService(managedObjectContext: context).find(withBlogObjectID: objectID, andCategoryID: categoryID) { post.addCategoriesObject(category) } post.postFormat = settings?.defaultPostFormat post.postType = Post.typeDefaultIdentifier if let userID = userID, let author = getAuthorWith(id: userID) { post.authorID = author.userID post.author = author.displayName } try? context.obtainPermanentIDs(for: [post]) precondition(!post.objectID.isTemporaryID, "The new post for this blog must have a permanent ObjectID") return post } /// Create a draft post in the blog. func createDraftPost() -> Post { let post = createPost() markAsDraft(post) return post } /// Create a page in the blog. @objc func createPage() -> Page { guard let context = managedObjectContext else { fatalError("The `Blog` instance is not associated with a `NSManagedObjectContext`") } let page = NSEntityDescription.insertNewObject(forEntityName: NSStringFromClass(Page.self), into: context) as! Page page.blog = self page.date_created_gmt = Date() page.remoteStatus = .sync if let userID = userID, let author = getAuthorWith(id: userID) { page.authorID = author.userID page.author = author.displayName } try? context.obtainPermanentIDs(for: [page]) precondition(!page.objectID.isTemporaryID, "The new page for this blog must have a permanent ObjectID") return page } /// Create a draft page in the blog. func createDraftPage() -> Page { let page = createPage() markAsDraft(page) return page } private func markAsDraft(_ post: AbstractPost) { post.remoteStatus = .local post.dateModified = Date() post.status = .draft } }
gpl-2.0
7ac591b84ed9cb01456c2ecf08eb7457
34.054054
138
0.647648
4.710654
false
false
false
false