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
QuarkWorks/RealmModelGenerator
RealmModelGenerator/BaseContentGenerator.swift
1
3745
// // BaseContentGenerator.swift // RealmModelGenerator // // Created by Zhaolong Zhong on 3/14/16. // Copyright ยฉ 2016 QuarkWorks. All rights reserved. // import Foundation import AddressBook class BaseContentGenerator { // MARK: - Check if entity is valid or not func isValidEntity(entity: Entity) -> Bool { do { return try validEntity(entity: entity) } catch GeneratorError.InvalidAttributeType(let attribute){ Tools.popupAlert(messageText: "Error", buttonTitle: "OK", informativeText: "Entity \(entity.name) attribute \(attribute.name) has an unknown type.") } catch GeneratorError.InvalidRelationshipDestination(let relationship) { Tools.popupAlert(messageText: "Error", buttonTitle: "OK", informativeText: "Entity \(entity.name) relationship \(relationship.name) has an unknown destination.") } catch { Tools.popupAlert(messageText: "Error", buttonTitle: "OK", informativeText: "Invalid entity \(entity.name)") } return false } func validEntity(entity: Entity) throws -> Bool { // Check unknown attribute for attribute in entity.attributes { if attribute.type == .Unknown { throw GeneratorError.InvalidAttributeType(attribute: attribute) } } // Check unknown relationship destination for relationship in entity.relationships { guard let _: Entity = relationship.destination else { throw GeneratorError.InvalidRelationshipDestination(relationship: relationship) } } return true } // MARK: - Get header comments func getHeaderComments(entity: Entity, fileExtension: String) -> String { var content = "" content += "/**\n" content += " *\t" + entity.name + "." + fileExtension + "\n" content += " *\tModel version: " + entity.model.version + "\n" if let me = ABAddressBook.shared()?.me(){ if let firstName = me.value(forProperty: kABFirstNameProperty as String) as? String{ content += " *\tCreate by \(firstName)" if let lastName = me.value(forProperty: kABLastNameProperty as String) as? String{ content += " \(lastName)" } } content += " on \(getTodayFormattedDay())\n *\tCopyright ยฉ \(getYear())" if let organization = me.value(forProperty: kABOrganizationProperty as String) as? String{ content += " \(organization)" } else { content += " QuarkWorks" } content += ". All rights reserved.\n" } content += " *\tModel file Generated using Realm Model Generator.\n" content += " */\n\n" return content } // Returns the current year as String func getYear() -> String { return "\(Calendar.current.component(.year, from: Date()))" } // Returns today date in the format dd/mm/yyyy func getTodayFormattedDay() -> String { let components = Calendar.current.dateComponents([.day, .month, .year], from: Date()) return "\(components.day!)/\(components.month!)/\(components.year!)" } // MARK: - Get all capitalized key name func getAllCapitalizedKeyName(name: String) -> String { var result = "" for c in name { if ("A"..."Z").contains(c) { result.append("_") } result.append(c) } return result.uppercased() } }
mit
8f522e258229525d0df42bf8148aa605
34.647619
173
0.567459
4.89281
false
false
false
false
mohammadalijf/UnderLineTextField
Example/UnderLineTextField-Example/KeyboardObserver.swift
1
2247
// // KeyboardObserver.swift // UnderLineTextField-Example // // Created by Mohammad Ali Jafarian on 8/18/18. // Copyright ยฉ 2018 Mohammad Ali Jafarian. All rights reserved. // import UIKit /// Handles Keyboard for scrollViews class KeyboardObserver { weak var constraint: NSLayoutConstraint! weak var view: UIView! deinit { NotificationCenter.default.removeObserver(self) } init(view: UIView, constraint: NSLayoutConstraint?) { self.constraint = constraint self.view = view } /// add notificaiton observer for keyboard changes func addNotification() { NotificationCenter.default .addObserver(self, selector: #selector(self.keyboardNotification(notification:)), name: UIResponder.keyboardWillChangeFrameNotification, object: nil) } } @objc extension KeyboardObserver { //================== // MARK: - Selectors //================== private func keyboardNotification(notification: NSNotification) { if let userInfo = notification.userInfo { let endFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue let duration: TimeInterval = (userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0 let animationCurveRawNSN = userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? NSNumber let animationCurveRaw = animationCurveRawNSN?.uintValue ?? UIView.AnimationOptions.curveEaseInOut.rawValue let animationCurve: UIView.AnimationOptions = UIView.AnimationOptions(rawValue: animationCurveRaw) if (endFrame?.origin.y)! >= UIScreen.main.bounds.size.height { self.constraint.constant = 0.0 } else { self.constraint.constant = endFrame?.size.height ?? 0.0 } UIView.animate(withDuration: duration, delay: TimeInterval(0), options: animationCurve, animations: { self.view.layoutIfNeeded() }, completion: nil) } } }
mit
87bb1c7524431eee3f84a08133e1159d
34.09375
132
0.617097
5.729592
false
false
false
false
okerivy/AlgorithmLeetCode
AlgorithmLeetCode/AlgorithmLeetCode/M_142_LinkedListCycleII.swift
1
2959
// // M_142_LinkedListCycleII.swift // AlgorithmLeetCode // // Created by okerivy on 2017/3/22. // Copyright ยฉ 2017ๅนด okerivy. All rights reserved. // https://leetcode.com/problems/linked-list-cycle-ii import Foundation // MARK: - ้ข˜็›ฎๅ็งฐ: 142. Linked List Cycle II /* MARK: - ๆ‰€ๅฑž็ฑปๅˆซ: ๆ ‡็ญพ: Linked List, Two Pointers ็›ธๅ…ณ้ข˜็›ฎ: (E) Linked List Cycle (M) Find the Duplicate Number */ /* MARK: - ้ข˜็›ฎ่‹ฑๆ–‡: Given a linked list, return the node where the cycle begins. If there is no cycle, return null. Note: Do not modify the linked list. Follow up: Can you solve it without using extra space? */ /* MARK: - ้ข˜็›ฎ็ฟป่ฏ‘: ็ป™ๅฎšไธ€ไธชLINKED LIST๏ผŒ่ฟ”ๅ›ž็š„่Š‚็‚นๅœจๅพช็Žฏๅผ€ๅง‹ใ€‚ๅฆ‚ๆžœๆฒกๆœ‰๏ผŒ่ฟ”ๅ›žnullใ€‚ ๆณจ๏ผšไธ่ฆไฟฎๆ”น็š„้“พ่กจใ€‚ ้š่ฎฟ๏ผš ไฝ ๅฏไปฅ็ปƒไน ๏ผŒๅฎƒๆฒกๆœ‰ไฝฟ็”จ้ขๅค–็š„็ฉบ้—ด๏ผŸ */ /* MARK: - ่งฃ้ข˜ๆ€่ทฏ: ่ฟ™้ข˜ไธๅ…‰่ฆๆฑ‚ๅ‡บๆ˜ฏๅฆๆœ‰็Žฏ๏ผŒ่€Œไธ”่ฟ˜้œ€่ฆๅพ—ๅˆฐ่ฟ™ไธช็Žฏๅผ€ๅง‹็š„่Š‚็‚นใ€‚่ญฌๅฆ‚ไธ‹้ข่ฟ™ไธช๏ผŒ่ตท็‚นๅฐฑๆ˜ฏn2ใ€‚ n6-----------n5 | | n1--- n2---n3--- n4-| ๆˆ‘ไปฌไป็„ถๅฏไปฅไฝฟ็”จไธคไธชๆŒ‡้’ˆfastๅ’Œslow๏ผŒfast่ตฐไธคๆญฅ๏ผŒslow่ตฐไธ€ๆญฅ๏ผŒๅˆคๆ–ญๆ˜ฏๅฆๆœ‰็Žฏ๏ผŒๅฝ“ๆœ‰็Žฏ้‡ๅˆไน‹ๅŽ๏ผŒ่ญฌๅฆ‚ไธŠ้ขๅœจn5้‡ๅˆไบ†๏ผŒ้‚ฃไนˆๅฆ‚ไฝ•ๅพ—ๅˆฐn2ๅ‘ข๏ผŸ ้ฆ–ๅ…ˆๆˆ‘ไปฌ็Ÿฅ้“๏ผŒfastๆฏๆฌกๆฏ”slowๅคš่ตฐไธ€ๆญฅ๏ผŒๆ‰€ไปฅ้‡ๅˆ็š„ๆ—ถๅ€™๏ผŒfast็งปๅŠจ็š„่ท็ฆปๆ˜ฏslot็š„ไธคๅ€๏ผŒๆˆ‘ไปฌๅ‡่ฎพn1ๅˆฐn2่ท็ฆปไธบa๏ผŒn2ๅˆฐn5่ท็ฆปไธบb๏ผŒn5ๅˆฐn2่ท็ฆปไธบc๏ผŒfast่ตฐๅŠจ่ท็ฆปไธบa + b + c + b๏ผŒ่€Œslowไธบa + b๏ผŒๆœ‰ๆ–น็จ‹a + b + c + b = 2 x (a + b)๏ผŒๅฏไปฅ็Ÿฅ้“a = c๏ผŒ ๆ‰€ไปฅๆˆ‘ไปฌๅช้œ€่ฆๅœจ้‡ๅˆไน‹ๅŽ๏ผŒไธ€ไธชๆŒ‡้’ˆไปŽn1๏ผŒ่€Œๅฆไธ€ไธชๆŒ‡้’ˆไปŽn5๏ผŒ้ƒฝๆฏๆฌก่ตฐไธ€ๆญฅ๏ผŒ้‚ฃไนˆๅฐฑๅฏไปฅๅœจn2้‡ๅˆไบ†ใ€‚ */ /* MARK: - ๅคๆ‚ๅบฆๅˆ†ๆž: */ // MARK: - ไปฃ็ : private class Solution { func detectCycle(_ head: SinglyListNode?) -> SinglyListNode? { if head == nil || head?.next == nil { return nil } var fast: SinglyListNode? = head var slow: SinglyListNode? = head while fast?.next != nil && fast?.next?.next != nil { fast = fast?.next?.next slow = slow?.next // ๆœ‰็Žฏ if fast === slow { // ๆ‰พ่ตท็‚น slow = head while fast !== slow { fast = fast?.next slow = slow?.next } return slow } } return nil } } // MARK: - ๆต‹่ฏ•ไปฃ็ : func LinkedListCycleII() { // ๅ•้“พ่กจ let head1 = CreatSinglyList().convertArrayToSinglyList([1, 2, 3, 4, 5, 6, 7, 8]) let head2 = CreatSinglyList().convertArrayToSinglyListCycle([1, 2, 3, 4, 5, 6, 7, 8], 2) let ans1 = Solution().detectCycle(head1) let ans2 = Solution().detectCycle(head2) print(ans1?.val ?? "ๆฒกๆœ‰ๆ‰พๅˆฐ") print(ans2?.val ?? "ๆฒกๆœ‰ๆ‰พๅˆฐ") }
mit
dbd3e9486913ce7111a37f03a9474d81
18.880342
160
0.563199
2.896638
false
false
false
false
NUKisZ/MyTools
MyTools/MyTools/Class/FirstVC/Controllers/UIFontViewController.swift
1
2471
// // UIFontViewController.swift // MyTools // // Created by gongrong on 2017/5/11. // Copyright ยฉ 2017ๅนด zhangk. All rights reserved. // import UIKit class UIFontViewController: TableViewBaseController { lazy var seDataArray = NSMutableArray() lazy var plDataArray = NSMutableArray() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. automaticallyAdjustsScrollViewInsets = false createTableView(frame: CGRect(x: 0, y: 64, w: kScreenWidth, h: kScreenHeight-64), style: .grouped, separatorStyle: .none) for name in UIFont.familyNames{ seDataArray.add(name) let array = NSMutableArray() for font in UIFont.fontNames(forFamilyName: name){ array.add(font) } plDataArray.add(array) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } extension UIFontViewController{ func numberOfSections(in tableView: UITableView) -> Int { return seDataArray.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (plDataArray[section] as! NSMutableArray).count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let id = "UIFontViewController" var cell = tableView.dequeueReusableCell(withIdentifier: id) if (cell == nil){ cell = UITableViewCell(style: .default, reuseIdentifier: id) } let font = (plDataArray[indexPath.section] as! NSMutableArray)[indexPath.row] as! String cell?.textLabel?.font = UIFont(name: font, size: 14) cell?.textLabel?.text = "็–ฏ็‹‚่ฎฉๅˆฉ็ฅž็ง˜ๅผ€ๅฏ"+font return cell! } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return seDataArray[section] as? String } }
mit
53e0b740239c551cb97b54c8359688fe
33.055556
129
0.653752
4.84585
false
false
false
false
salesforce-ux/design-system-ios
Demo-Swift/slds-sample-app/library/controllers/LibraryListViewController.swift
1
6777
// 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 struct TableData { var sectionTitle: String var rows: [(name:String,type:UIViewController.Type)] } class LibraryListViewController: UITableViewController { var tableData : [TableData] { return [ TableData(sectionTitle: "Icons", rows: [(IconObjectType.action.rawValue, IconListViewController.self), (IconObjectType.custom.rawValue, IconListViewController.self), (IconObjectType.standard.rawValue, IconListViewController.self), (IconObjectType.utility.rawValue, IconListViewController.self)]), TableData(sectionTitle: "Colors", rows: [(ColorObjectType.background.rawValue, ColorListViewController.self), (ColorObjectType.border.rawValue, ColorListViewController.self), (ColorObjectType.fill.rawValue, ColorListViewController.self), (ColorObjectType.text.rawValue, ColorListViewController.self)]), TableData(sectionTitle: "Fonts", rows: [(FontObjectType.salesforceSans.rawValue, FontListViewController.self), (FontObjectType.lato.rawValue, FontListViewController.self)]) ] } //โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“ override func viewDidLoad() { super.viewDidLoad() self.title = "Library" self.view.backgroundColor = UIColor.white self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell") } //โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“ override func viewWillAppear(_ animated: Bool) { UIFont.sldsUseDefaultFonts() navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white, NSFontAttributeName: UIFont.sldsFont(.regular, with: .medium)] navigationItem.backBarButtonItem?.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.white, NSFontAttributeName: UIFont.sldsFont(.regular, with: .medium)], for: UIControlState.normal) super.viewWillAppear(animated) } //โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“ override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 36.0 } //โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“ override func numberOfSections(in tableView: UITableView) -> Int { return tableData.count } //โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“ override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tableData[section].rows.count } //โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“ override func tableView(_ tableView: UITableView, indentationLevelForRowAt indexPath: IndexPath) -> Int { return 2 } //โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“ override func tableView (_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView { return SectionHeaderView() } //โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“ override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return tableData[section].sectionTitle } //โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“ override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator if let label = cell.textLabel { label.font = UIFont.sldsFont(.regular, with: .medium) label.text = tableData[indexPath.section].rows[indexPath.row].name label.accessibilityLabel = label.text! + tableData[indexPath.section].sectionTitle } return cell } //โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“โ€“ override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let controllerClass = tableData[indexPath.section].rows[indexPath.row].type let controller = controllerClass.init() controller.title = tableData[indexPath.section].rows[indexPath.row].name self.navigationController?.show(controller, sender: self) } }
bsd-3-clause
ec9dd7219fc00076b12dc1c1ba05e2b2
45.168142
129
0.526356
6.928287
false
false
false
false
niunaruto/DeDaoAppSwift
testSwift/Pods/YPImagePicker/Source/Helpers/YPLoadingView.swift
2
1294
// // YPLoadingView.swift // YPImagePicker // // Created by Sacha DSO on 24/04/2018. // Copyright ยฉ 2018 Yummypets. All rights reserved. // import UIKit import Stevia class YPLoadingView: UIView { let spinner = UIActivityIndicatorView(style: .whiteLarge) let processingLabel = UILabel() convenience init() { self.init(frame: .zero) // View Hiearachy let stack = UIStackView(arrangedSubviews: [spinner, processingLabel]) stack.axis = .vertical stack.spacing = 20 sv( stack ) // Layout stack.centerInContainer() processingLabel.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 751), for: .horizontal) // Style backgroundColor = UIColor.ypLabel.withAlphaComponent(0.8) processingLabel.textColor = .ypSystemBackground spinner.hidesWhenStopped = true // Content processingLabel.text = YPConfig.wordings.processing spinner.startAnimating() } func toggleLoading() { if !spinner.isAnimating { spinner.startAnimating() alpha = 1 } else { spinner.stopAnimating() alpha = 0 } } }
mit
12d6f0004c4798628ccf4e78f505e233
23.865385
114
0.594741
5.011628
false
false
false
false
adib/Core-ML-Playgrounds
Photo-Explorations/EnlargeImages.playground/Sources/CGImage+RunModel.swift
1
5585
// // UIImage+RunModel.swift // waifu2x-ios // // Created by xieyi on 2017/9/14. // Copyright ยฉ 2017ๅนด xieyi. All rights reserved. // import Foundation import AppKit import CoreML /// The output block size. /// It is dependent on the model. /// Do not modify it until you are sure your model has a different number. var block_size = 128 /// The difference of output and input block size let shrink_size = 7 extension CGImage { public func run(model: Model, scale: CGFloat = 1) -> CGImage? { let startTime = Date.timeIntervalSinceReferenceDate let width = Int(self.width) let height = Int(self.height) switch model { case .anime_noise0, .anime_noise1, .anime_noise2, .anime_noise3, .photo_noise0, .photo_noise1, .photo_noise2, .photo_noise3: block_size = 128 default: block_size = 142 } let rects = getCropRects() // Prepare for output pipeline // Merge arrays into one array let normalize = { (input: Double) -> Double in let output = input * 255 if output > 255 { return 255 } if output < 0 { return 0 } return output } let out_block_size = block_size * Int(scale) let out_width = width * Int(scale) let out_height = height * Int(scale) let bufferSize = out_block_size * out_block_size * 3 var imgData = [UInt8].init(repeating: 0, count: out_width * out_height * 3) let out_pipeline = BackgroundPipeline<MLMultiArray>("out_pipeline", count: rects.count) { (index, array) in let startTime = Date.timeIntervalSinceReferenceDate let rect = rects[index] let origin_x = Int(rect.origin.x * scale) let origin_y = Int(rect.origin.y * scale) let dataPointer = UnsafeMutableBufferPointer(start: array.dataPointer.assumingMemoryBound(to: Double.self), count: bufferSize) var dest_x: Int var dest_y: Int var src_index: Int var dest_index: Int for channel in 0..<3 { for src_y in 0..<out_block_size { for src_x in 0..<out_block_size { dest_x = origin_x + src_x dest_y = origin_y + src_y src_index = src_y * out_block_size + src_x + out_block_size * out_block_size * channel dest_index = (dest_y * out_width + dest_x) * 3 + channel imgData[dest_index] = UInt8(normalize(dataPointer[src_index])) } } } let endTime = Date.timeIntervalSinceReferenceDate print("pipeline-normalize-data: ",endTime - startTime) } // Prepare for model pipeline // Run prediction on each block let mlmodel = model.getMLModel() let model_pipeline = BackgroundPipeline<MLMultiArray>("model_pipeline", count: rects.count) { (index, array) in let startTime = Date.timeIntervalSinceReferenceDate let result = try! mlmodel.prediction(input: array) let endTime = Date.timeIntervalSinceReferenceDate print("pipeline-prediction: ",endTime - startTime) out_pipeline.appendObject(result) } // Start running model let expwidth = Int(self.width) + 2 * shrink_size let expheight = Int(self.height) + 2 * shrink_size let expanded = expand() for rect in rects { let x = Int(rect.origin.x) let y = Int(rect.origin.y) let multi = try! MLMultiArray(shape: [3, NSNumber(value: block_size + 2 * shrink_size), NSNumber(value: block_size + 2 * shrink_size)], dataType: .float32) var x_new: Int var y_new: Int for y_exp in y..<(y + block_size + 2 * shrink_size) { for x_exp in x..<(x + block_size + 2 * shrink_size) { x_new = x_exp - x y_new = y_exp - y multi[y_new * (block_size + 2 * shrink_size) + x_new] = NSNumber(value: expanded[y_exp * expwidth + x_exp]) multi[y_new * (block_size + 2 * shrink_size) + x_new + (block_size + 2 * shrink_size) * (block_size + 2 * shrink_size)] = NSNumber(value: expanded[y_exp * expwidth + x_exp + expwidth * expheight]) multi[y_new * (block_size + 2 * shrink_size) + x_new + (block_size + 2 * shrink_size) * (block_size + 2 * shrink_size) * 2] = NSNumber(value: expanded[y_exp * expwidth + x_exp + expwidth * expheight * 2]) } } model_pipeline.appendObject(multi) } model_pipeline.wait() out_pipeline.wait() let cfbuffer = CFDataCreate(nil, &imgData, out_width * out_height * 3)! let dataProvider = CGDataProvider(data: cfbuffer)! let colorSpace = CGColorSpaceCreateDeviceRGB() let bitmapInfo = CGBitmapInfo.byteOrder32Big let cgImage = CGImage(width: out_width, height: out_height, bitsPerComponent: 8, bitsPerPixel: 24, bytesPerRow: out_width * 3, space: colorSpace, bitmapInfo: bitmapInfo, provider: dataProvider, decode: nil, shouldInterpolate: true, intent: CGColorRenderingIntent.defaultIntent) let endTime = Date.timeIntervalSinceReferenceDate print("run-model: ",endTime - startTime) return cgImage } }
bsd-3-clause
1b24813743d840b901aa32a200cbf064
43.656
285
0.568793
4.153274
false
false
false
false
wireapp/wire-ios-data-model
Source/Model/Connection/ZMConnection+Fetch.swift
1
3565
// // Wire // Copyright (C) 2020 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation extension ZMConnection { @objc(connectionsInManagedObjectContext:) class func connections(inManagedObjectContext moc: NSManagedObjectContext) -> [NSFetchRequestResult] { let request = sortedFetchRequest() let result = moc.fetchOrAssert(request: request) return result } public static func fetchOrCreate(userID: UUID, domain: String?, in context: NSManagedObjectContext) -> ZMConnection { guard let connection = fetch(userID: userID, domain: domain, in: context) else { return create(userID: userID, domain: domain, in: context) } return connection } public static func create(userID: UUID, domain: String?, in context: NSManagedObjectContext) -> ZMConnection { require(context.zm_isSyncContext, "Connections are only allowed to be created on sync context") let connection = ZMConnection.insertNewObject(in: context) connection.to = ZMUser.fetchOrCreate(with: userID, domain: domain, in: context) connection.existsOnBackend = true return connection } public static func fetch(userID: UUID, domain: String?, in context: NSManagedObjectContext) -> ZMConnection? { let localDomain = ZMUser.selfUser(in: context).domain let isSearchingLocalDomain = domain == nil || localDomain == nil || localDomain == domain return internalFetch(userID: userID, domain: domain ?? localDomain, searchingLocalDomain: isSearchingLocalDomain, in: context) } static func internalFetch(userID: UUID, domain: String?, searchingLocalDomain: Bool, in context: NSManagedObjectContext) -> ZMConnection? { let predicate: NSPredicate if searchingLocalDomain { if let domain = domain { predicate = NSPredicate(format: "to.remoteIdentifier_data == %@ AND (to.domain == %@ || to.domain == NULL)", userID.uuidData as NSData, domain) } else { predicate = NSPredicate(format: "to.remoteIdentifier_data == %@", userID.uuidData as NSData) } } else { predicate = NSPredicate(format: "to.remoteIdentifier_data == %@ AND to.domain == %@", userID.uuidData as NSData, domain ?? NSNull.init()) } let fetchRequest = ZMConnection.sortedFetchRequest(with: predicate) fetchRequest.fetchLimit = 2 // We only want 1, but want to check if there are too many. let result = context.fetchOrAssert(request: fetchRequest) require(result.count <= 1, "More than one connection with the same 'to'") return result.first as? ZMConnection } }
gpl-3.0
a73e0fc4729909dbede765e7302f588c
40.453488
159
0.643759
4.972106
false
false
false
false
belatrix/iOSAllStarsRemake
AllStars/AllStars/iPhone/Classes/Activity/ActivityViewController.swift
1
8169
// // Activity.swift // AllStars // // Created by Ricardo Hernan Herrera Valle on 7/25/16. // Copyright ยฉ 2016 Belatrix SF. All rights reserved. // import Foundation class ActivityViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate { // MARK: - IBOutlet @IBOutlet weak var viewHeader : UIView! @IBOutlet weak var backButton : UIButton! @IBOutlet weak var tableView : UITableView! @IBOutlet weak var viewLoading : UIView! @IBOutlet weak var lblErrorMessage : UILabel! @IBOutlet weak var activityActivities : UIActivityIndicatorView! // MARK: - Properties lazy var refreshControl : UIRefreshControl = { let refreshControl = UIRefreshControl() refreshControl.backgroundColor = .clearColor() refreshControl.tintColor = UIColor.belatrix() refreshControl.addTarget(self, action: #selector(ActivityViewController.listActivities), forControlEvents: .ValueChanged) return refreshControl }() var activities = [Activity]() { didSet{ if self.isViewLoaded() { tableView.reloadData() } } } var isDownload = false var nextPage : String? = nil // MARK: - Initialization override func viewDidLoad() { super.viewDidLoad() self.tableView.addSubview(self.refreshControl) setViews() listActivities() NSNotificationCenter.defaultCenter().addObserver(self, selector:#selector(ActivityViewController.listActivities), name: "applicationDidBecomeActive", object: nil) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.navigationController?.setNavigationBarHidden(true, animated: true) if let backButton = self.backButton { if let nav = self.navigationController where nav.viewControllers.count > 1 { backButton.hidden = false } else { backButton.hidden = true } } listActivities() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) if let rootVC = self.navigationController?.viewControllers.first where rootVC == self.tabBarController?.moreNavigationController.viewControllers.first { self.navigationController?.setNavigationBarHidden(false, animated: true) } self.refreshControl.endRefreshing() } deinit { NSNotificationCenter.defaultCenter().removeObserver(self, name: "applicationDidBecomeActive", object: nil) } // MARK: - UI func setViews() { viewHeader.layer.shadowOffset = CGSizeMake(0, 0) viewHeader.layer.shadowRadius = 2 viewHeader.layer.masksToBounds = false viewHeader.layer.shadowOpacity = 1 viewHeader.layer.shadowColor = UIColor.orangeColor().CGColor viewHeader.backgroundColor = UIColor.colorPrimary() self.tableView.rowHeight = UITableViewAutomaticDimension self.tableView.estimatedRowHeight = 71 } func updateActivityCell (cell: ActivityCell, activity: Activity) { if let datetime = activity.activity_dateTime { cell.activityDate.text = OSPDateManager.convertirFecha(datetime, alFormato: "dd MMM yyyy hh:mm a", locale: "en_US") } else { cell.activityDate.text = "No date" } cell.activityText.text = activity.activity_text if let avatarURL = activity.activity_avatarURL { if (activity.activity_avatarURL != "") { OSPImageDownloaded.descargarImagenEnURL(avatarURL, paraImageView: cell.senderImage, conPlaceHolder: UIImage(named: "placeholder_general.png")) { (correct : Bool, nameImage : String!, image : UIImage!) in if nameImage == avatarURL { cell.senderImage.image = image } } } else { cell.senderImage.image = UIImage(named: "server_icon") } } else { cell.senderImage.image = UIImage(named: "server_icon") } } // MARK: - UIScrollViewDelegate func scrollViewDidScroll(scrollView: UIScrollView) { if (self.nextPage != nil && self.isDownload == false && scrollView.contentOffset.y + scrollView.frame.size.height > scrollView.contentSize.height + 40) { self.listActivitiesInNextPage() } } // MARK: - UITableViewDelegate, UITableViewDataSource func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return activities.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCellWithIdentifier("activityCell") as? ActivityCell else { fatalError("activityCell does not exists")} let activity = activities[indexPath.row] self.updateActivityCell(cell, activity: activity) return cell } // MARK: - User Interaction @IBAction func goBack(sender: UIButton) { self.view.endEditing(true) self.navigationController?.popViewControllerAnimated(true) } // MARK: - Services func listActivities() { if (!self.isDownload) { self.isDownload = true let activityBC = ActivityBC() self.activityActivities.startAnimating() self.viewLoading.alpha = CGFloat(!Bool(self.activities.count)) self.lblErrorMessage.text = "Loading Activities" activityBC.listActivities { (arrayActivities, nextPage) in self.refreshControl.endRefreshing() self.nextPage = nextPage guard let activities = arrayActivities where activities.count > 0 else { return } self.activities = activities self.activityActivities.stopAnimating() self.viewLoading.alpha = CGFloat(!Bool(self.activities.count)) self.lblErrorMessage.text = "Activities not found" self.isDownload = false } } } func listActivitiesInNextPage() { if (!self.isDownload && self.nextPage != nil) { self.isDownload = true let activityBC = ActivityBC() self.activityActivities.startAnimating() self.viewLoading.alpha = CGFloat(!Bool(self.activities.count)) self.lblErrorMessage.text = "Loading activities" activityBC.listActivitiesToPage (self.nextPage!) { (arrayActivities, nextPage) in self.refreshControl.endRefreshing() self.nextPage = nextPage self.isDownload = false guard let activities = arrayActivities where activities.count > 0 else { return } self.activities.appendContentsOf(activities) self.activityActivities.stopAnimating() self.viewLoading.alpha = CGFloat(!Bool(self.activities.count)) self.lblErrorMessage.text = "Activities not found" } } } } class ActivityCell: UITableViewCell { @IBOutlet weak var senderImage: UIImageView! @IBOutlet weak var activityDate: UILabel! @IBOutlet weak var activityText: UILabel! }
mit
e25cf25abf2cfc4cf4df08b80304413c
34.055794
170
0.581538
5.739986
false
false
false
false
lorentey/swift
test/SILGen/generic_casts.swift
12
13260
// RUN: %target-swift-emit-silgen -swift-version 5 -module-name generic_casts -Xllvm -sil-full-demangle %s | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-%target-runtime %s protocol ClassBound : class {} protocol NotClassBound {} class C : ClassBound, NotClassBound {} struct S : NotClassBound {} struct Unloadable : NotClassBound { var x : NotClassBound } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts020opaque_archetype_to_c1_D0{{[_0-9a-zA-Z]*}}F func opaque_archetype_to_opaque_archetype <T:NotClassBound, U>(_ t:T) -> U { return t as! U // CHECK: bb0([[RET:%.*]] : $*U, {{%.*}}: $*T): // CHECK: unconditional_checked_cast_addr T in {{%.*}} : $*T to U in [[RET]] : $*U } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts020opaque_archetype_is_c1_D0{{[_0-9a-zA-Z]*}}F func opaque_archetype_is_opaque_archetype <T:NotClassBound, U>(_ t:T, u:U.Type) -> Bool { return t is U // CHECK: checked_cast_addr_br take_always T in [[VAL:%.*]] : $*T to U in [[DEST:%.*]] : $*U, [[YES:bb[0-9]+]], [[NO:bb[0-9]+]] // CHECK: [[YES]]: // CHECK: [[Y:%.*]] = integer_literal $Builtin.Int1, -1 // CHECK: destroy_addr [[DEST]] // CHECK: br [[CONT:bb[0-9]+]]([[Y]] : $Builtin.Int1) // CHECK: [[NO]]: // CHECK: [[N:%.*]] = integer_literal $Builtin.Int1, 0 // CHECK: br [[CONT]]([[N]] : $Builtin.Int1) // CHECK: [[CONT]]([[I1:%.*]] : $Builtin.Int1): // CHECK-NEXT: [[META:%.*]] = metatype $@thin Bool.Type // CHECK-NEXT: function_ref Swift.Bool.init(_builtinBooleanLiteral: Builtin.Int1) // CHECK-NEXT: [[BOOL:%.*]] = function_ref @$sSb22_builtinBooleanLiteralSbBi1__tcfC : // CHECK-NEXT: [[RES:%.*]] = apply [[BOOL]]([[I1]], [[META]]) // -- we don't consume the checked value // CHECK: return [[RES]] : $Bool } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts026opaque_archetype_to_class_D0{{[_0-9a-zA-Z]*}}F func opaque_archetype_to_class_archetype <T:NotClassBound, U:ClassBound> (_ t:T) -> U { return t as! U // CHECK: unconditional_checked_cast_addr T in {{%.*}} : $*T to U in [[DOWNCAST_ADDR:%.*]] : $*U // CHECK: [[DOWNCAST:%.*]] = load [take] [[DOWNCAST_ADDR]] : $*U // CHECK: return [[DOWNCAST]] : $U } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts026opaque_archetype_is_class_D0{{[_0-9a-zA-Z]*}}F func opaque_archetype_is_class_archetype <T:NotClassBound, U:ClassBound> (_ t:T, u:U.Type) -> Bool { return t is U // CHECK: copy_addr {{.*}} : $*T // CHECK: checked_cast_addr_br take_always T in [[VAL:%.*]] : {{.*}} to U } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts019class_archetype_to_c1_D0{{[_0-9a-zA-Z]*}}F func class_archetype_to_class_archetype <T:ClassBound, U:ClassBound>(_ t:T) -> U { return t as! U // Error bridging can change the identity of class-constrained archetypes. // CHECK: unconditional_checked_cast_addr T in {{%.*}} : $*T to U in [[DOWNCAST_ADDR:%.*]] : $*U // CHECK: [[DOWNCAST:%.*]] = load [take] [[DOWNCAST_ADDR]] // CHECK: return [[DOWNCAST]] : $U } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts019class_archetype_is_c1_D0{{[_0-9a-zA-Z]*}}F func class_archetype_is_class_archetype <T:ClassBound, U:ClassBound>(_ t:T, u:U.Type) -> Bool { return t is U // Error bridging can change the identity of class-constrained archetypes. // CHECK: checked_cast_addr_br {{.*}} T in {{%.*}} : $*T to U in {{%.*}} : $*U } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts38opaque_archetype_to_addr_only_concrete{{[_0-9a-zA-Z]*}}F func opaque_archetype_to_addr_only_concrete <T:NotClassBound> (_ t:T) -> Unloadable { return t as! Unloadable // CHECK: bb0([[RET:%.*]] : $*Unloadable, {{%.*}}: $*T): // CHECK: unconditional_checked_cast_addr T in {{%.*}} : $*T to Unloadable in [[RET]] : $*Unloadable } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts38opaque_archetype_is_addr_only_concrete{{[_0-9a-zA-Z]*}}F func opaque_archetype_is_addr_only_concrete <T:NotClassBound> (_ t:T) -> Bool { return t is Unloadable // CHECK: checked_cast_addr_br take_always T in [[VAL:%.*]] : {{.*}} to Unloadable in } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts37opaque_archetype_to_loadable_concrete{{[_0-9a-zA-Z]*}}F func opaque_archetype_to_loadable_concrete <T:NotClassBound>(_ t:T) -> S { return t as! S // CHECK: unconditional_checked_cast_addr T in {{%.*}} : $*T to S in [[DOWNCAST_ADDR:%.*]] : $*S // CHECK: [[DOWNCAST:%.*]] = load [trivial] [[DOWNCAST_ADDR]] : $*S // CHECK: return [[DOWNCAST]] : $S } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts37opaque_archetype_is_loadable_concrete{{[_0-9a-zA-Z]*}}F func opaque_archetype_is_loadable_concrete <T:NotClassBound>(_ t:T) -> Bool { return t is S // CHECK: checked_cast_addr_br take_always T in {{%.*}} : $*T to S in } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts019class_archetype_to_C0{{[_0-9a-zA-Z]*}}F func class_archetype_to_class <T:ClassBound>(_ t:T) -> C { return t as! C // CHECK: [[DOWNCAST:%.*]] = unconditional_checked_cast {{%.*}} to C // CHECK: return [[DOWNCAST]] : $C } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts019class_archetype_is_C0{{[_0-9a-zA-Z]*}}F func class_archetype_is_class <T:ClassBound>(_ t:T) -> Bool { return t is C // CHECK: checked_cast_br {{%.*}} to C } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts022opaque_existential_to_C10_archetype{{[_0-9a-zA-Z]*}}F func opaque_existential_to_opaque_archetype <T:NotClassBound>(_ p:NotClassBound) -> T { return p as! T // CHECK: bb0([[RET:%.*]] : $*T, [[ARG:%.*]] : $*NotClassBound): // CHECK: [[TEMP:%.*]] = alloc_stack $NotClassBound // CHECK-NEXT: copy_addr [[ARG]] to [initialization] [[TEMP]] // CHECK-NEXT: unconditional_checked_cast_addr NotClassBound in [[TEMP]] : $*NotClassBound to T in [[RET]] : $*T // CHECK-NEXT: dealloc_stack [[TEMP]] // CHECK-NEXT: [[T0:%.*]] = tuple () // CHECK-NEXT: return [[T0]] } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts022opaque_existential_is_C10_archetype{{[_0-9a-zA-Z]*}}F func opaque_existential_is_opaque_archetype <T:NotClassBound>(_ p:NotClassBound, _: T) -> Bool { return p is T // CHECK: checked_cast_addr_br take_always NotClassBound in [[CONTAINER:%.*]] : {{.*}} to T in } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts37opaque_existential_to_class_archetype{{[_0-9a-zA-Z]*}}F func opaque_existential_to_class_archetype <T:ClassBound>(_ p:NotClassBound) -> T { return p as! T // CHECK: unconditional_checked_cast_addr NotClassBound in {{%.*}} : $*NotClassBound to T in [[DOWNCAST_ADDR:%.*]] : $*T // CHECK: [[DOWNCAST:%.*]] = load [take] [[DOWNCAST_ADDR]] : $*T // CHECK: return [[DOWNCAST]] : $T } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts37opaque_existential_is_class_archetype{{[_0-9a-zA-Z]*}}F func opaque_existential_is_class_archetype <T:ClassBound>(_ p:NotClassBound, _: T) -> Bool { return p is T // CHECK: checked_cast_addr_br take_always NotClassBound in {{%.*}} : $*NotClassBound to T in } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts021class_existential_to_C10_archetype{{[_0-9a-zA-Z]*}}F func class_existential_to_class_archetype <T:ClassBound>(_ p:ClassBound) -> T { return p as! T // CHECK: unconditional_checked_cast_addr ClassBound in {{%.*}} : $*ClassBound to T in [[DOWNCAST_ADDR:%.*]] : $*T // CHECK: [[DOWNCAST:%.*]] = load [take] [[DOWNCAST_ADDR]] // CHECK: return [[DOWNCAST]] : $T } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts021class_existential_is_C10_archetype{{[_0-9a-zA-Z]*}}F func class_existential_is_class_archetype <T:ClassBound>(_ p:ClassBound, _: T) -> Bool { return p is T // CHECK: checked_cast_addr_br {{.*}} ClassBound in {{%.*}} : $*ClassBound to T in {{%.*}} : $*T } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts40opaque_existential_to_addr_only_concrete{{[_0-9a-zA-Z]*}}F func opaque_existential_to_addr_only_concrete(_ p: NotClassBound) -> Unloadable { return p as! Unloadable // CHECK: bb0([[RET:%.*]] : $*Unloadable, {{%.*}}: $*NotClassBound): // CHECK: unconditional_checked_cast_addr NotClassBound in {{%.*}} : $*NotClassBound to Unloadable in [[RET]] : $*Unloadable } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts40opaque_existential_is_addr_only_concrete{{[_0-9a-zA-Z]*}}F func opaque_existential_is_addr_only_concrete(_ p: NotClassBound) -> Bool { return p is Unloadable // CHECK: checked_cast_addr_br take_always NotClassBound in {{%.*}} : $*NotClassBound to Unloadable in } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts39opaque_existential_to_loadable_concrete{{[_0-9a-zA-Z]*}}F func opaque_existential_to_loadable_concrete(_ p: NotClassBound) -> S { return p as! S // CHECK: unconditional_checked_cast_addr NotClassBound in {{%.*}} : $*NotClassBound to S in [[DOWNCAST_ADDR:%.*]] : $*S // CHECK: [[DOWNCAST:%.*]] = load [trivial] [[DOWNCAST_ADDR]] : $*S // CHECK: return [[DOWNCAST]] : $S } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts39opaque_existential_is_loadable_concrete{{[_0-9a-zA-Z]*}}F func opaque_existential_is_loadable_concrete(_ p: NotClassBound) -> Bool { return p is S // CHECK: checked_cast_addr_br take_always NotClassBound in {{%.*}} : $*NotClassBound to S in } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts021class_existential_to_C0{{[_0-9a-zA-Z]*}}F func class_existential_to_class(_ p: ClassBound) -> C { return p as! C // CHECK: [[DOWNCAST:%.*]] = unconditional_checked_cast {{%.*}} to C // CHECK: return [[DOWNCAST]] : $C } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts021class_existential_is_C0{{[_0-9a-zA-Z]*}}F func class_existential_is_class(_ p: ClassBound) -> Bool { return p is C // CHECK: checked_cast_br {{%.*}} to C } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts27optional_anyobject_to_classyAA1CCSgyXlSgF func optional_anyobject_to_class(_ p: AnyObject?) -> C? { return p as? C // CHECK: checked_cast_br {{%.*}} : $AnyObject to C } // The below tests are to ensure we don't dig into an optional operand when // casting to a non-class archetype, as it could dynamically be an optional type. // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts32optional_any_to_opaque_archetype{{[_0-9a-zA-Z]*}}F func optional_any_to_opaque_archetype<T>(_ x: Any?) -> T { return x as! T // CHECK: bb0([[RET:%.*]] : $*T, {{%.*}} : $*Optional<Any>): // CHECK: unconditional_checked_cast_addr Optional<Any> in {{%.*}} : $*Optional<Any> to T in [[RET]] : $*T } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts46optional_any_conditionally_to_opaque_archetype{{[_0-9a-zA-Z]*}}F func optional_any_conditionally_to_opaque_archetype<T>(_ x: Any?) -> T? { return x as? T // CHECK: checked_cast_addr_br take_always Optional<Any> in {{%.*}} : $*Optional<Any> to T in {{%.*}} : $*T } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts32optional_any_is_opaque_archetype{{[_0-9a-zA-Z]*}}F func optional_any_is_opaque_archetype<T>(_ x: Any?, _: T) -> Bool { return x is T // CHECK: checked_cast_addr_br take_always Optional<Any> in {{%.*}} : $*Optional<Any> to T in {{%.*}} : $*T } // But we can dig into at most one layer of the operand if it's // an optional archetype... // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts016optional_any_to_C17_opaque_archetype{{[_0-9a-zA-Z]*}}F func optional_any_to_optional_opaque_archetype<T>(_ x: Any?) -> T? { return x as! T? // CHECK: unconditional_checked_cast_addr Any in {{%.*}} : $*Any to T in {{%.*}} : $*T } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts030optional_any_conditionally_to_C17_opaque_archetype{{[_0-9a-zA-Z]*}}F func optional_any_conditionally_to_optional_opaque_archetype<T>(_ x: Any?) -> T?? { return x as? T? // CHECK: checked_cast_addr_br take_always Any in {{%.*}} : $*Any to T in {{%.*}} : $*T } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts016optional_any_is_C17_opaque_archetype{{[_0-9a-zA-Z]*}}F func optional_any_is_optional_opaque_archetype<T>(_ x: Any?, _: T) -> Bool { return x is T? // Because the levels of optional are the same, 'is' doesn't transform into an 'as?', // so we just cast directly without digging into the optional operand. // CHECK: checked_cast_addr_br take_always Optional<Any> in {{%.*}} : $*Optional<Any> to Optional<T> in {{%.*}} : $*Optional<T> } // And we can dig into the operand when casting to a class archetype, as it // cannot dynamically be optional... // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts31optional_any_to_class_archetype{{[_0-9a-zA-Z]*}}F func optional_any_to_class_archetype<T : AnyObject>(_ x: Any?) -> T { return x as! T // CHECK: unconditional_checked_cast_addr Any in {{%.*}} : $*Any to T in {{%.*}} : $*T } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts45optional_any_conditionally_to_class_archetype{{[_0-9a-zA-Z]*}}F func optional_any_conditionally_to_class_archetype<T : AnyObject>(_ x: Any?) -> T? { return x as? T // CHECK: checked_cast_addr_br take_always Any in {{%.*}} : $*Any to T in {{%.*}} : $*T } // CHECK-LABEL: sil hidden [ossa] @$s13generic_casts31optional_any_is_class_archetype{{[_0-9a-zA-Z]*}}F func optional_any_is_class_archetype<T : AnyObject>(_ x: Any?, _: T) -> Bool { return x is T // CHECK: checked_cast_addr_br take_always Any in {{%.*}} : $*Any to T in {{%.*}} : $*T }
apache-2.0
d0d49de29db5c7d59e70d0e6328be8ea
45.690141
180
0.644118
3.157143
false
false
false
false
craftsmanship-toledo/katangapp-ios
Katanga/ViewControllers/RouteDetailViewController.swift
1
3561
/** * Copyright 2016-today Software Craftmanship Toledo * * 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. */ /*! @author Vรญctor Galรกn */ import RxCocoa import RxSwift import UIKit class RouteDetailViewController: UIViewController, DataListTableView { typealias Model = BusStop typealias CellType = BusStopCell public var viewModel: RouteDetailViewModelProtocol? @IBOutlet private weak var tableView: UITableView! { didSet { tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 200 } } @IBOutlet private weak var toolbar: UIToolbar! { didSet { toolbar.tintColor = .katangaYellow } } private lazy var mapViewController: UIViewController = { let storyboard = UIStoryboard(name: "Main", bundle: nil) let mapVC = storyboard.instantiateViewController(withIdentifier: "mapVC") as! MapViewController mapVC.viewModel = self.viewModel return mapVC }() private lazy var linesViewController: UIViewController = { let storyboard = UIStoryboard(name: "Main", bundle: nil) let linesVC = storyboard.instantiateViewController(withIdentifier: "linesVC") as! RouteStopsViewController linesVC.viewModel = self.viewModel return linesVC }() override func viewDidLoad() { super.viewDidLoad() add(viewController: mapViewController) viewModel?.routeId() .drive(rx.title) .disposed(by: rx_disposeBag) } func fillCell(row: Int, element: Model, cell: CellType) { cell.busStopName = element.address } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let busStop = sender as? BusStop else { return } let viewModel = NearBusStopIdViewModel(busStopId: busStop.id) let vc = segue.destination as? NearBusStopsViewController vc?.viewModel = viewModel } @IBAction func segmentedControlValueChanged(_ sender: UISegmentedControl) { if sender.selectedSegmentIndex == 0 { add(viewController: mapViewController) remove(viewController: linesViewController) } else { add(viewController: linesViewController) remove(viewController: mapViewController) } } private func add(viewController: UIViewController) { addChildViewController(viewController) view.addSubview(viewController.view) viewController.view.translatesAutoresizingMaskIntoConstraints = false viewController.view.topAnchor.constraint(equalTo: self.toolbar.bottomAnchor).isActive = true viewController.view.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true viewController.view.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true viewController.view.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true viewController.didMove(toParentViewController: self) } private func remove(viewController: UIViewController) { viewController.willMove(toParentViewController: nil) viewController.view.removeFromSuperview() viewController.removeFromParentViewController() } }
apache-2.0
629b5324f812eb2df3b194fb4c2b3e08
28.172131
108
0.747963
4.57455
false
false
false
false
Look-ARound/LookARound2
lookaround2/Views/PlaceMainCell.swift
1
4213
// // PlaceMainCell.swift // lookaround2 // // Created by Angela Yu on 11/15/17. // Copyright ยฉ 2017 Angela Yu. All rights reserved. // import UIKit @objc protocol PlaceMainCellDelegate { @objc optional func getDirections(for place: Place) func addPlace(on viewController: AddPlaceViewController) } class PlaceMainCell: UITableViewCell { @IBOutlet private var nameLabel: UILabel! @IBOutlet private var categoryLabel: UILabel! @IBOutlet private var checkinsCountLabel: UILabel! @IBOutlet private var friendsCountLabel: UILabel! @IBOutlet private var checkInImageView: UIImageView! @IBOutlet private var likeImageView: UIImageView! @IBOutlet private var placeImageView: UIImageView! @IBOutlet weak var addListButton: UIButton! @IBOutlet private var directionsButton: UIButton! internal var delegate: PlaceMainCellDelegate? internal var place: Place? internal var imageURLString: String? { didSet { self.placeImageView.image = #imageLiteral(resourceName: "placeholder") if let imageURLString = imageURLString { if let imageURL = URL(string: imageURLString) { self.placeImageView.setImageWith(imageURL, placeholderImage: #imageLiteral(resourceName: "placeholder")) } } } } internal func setupViews() { guard let place = place else { print("nil place") return } nameLabel.text = place.name checkinsCountLabel.text = "\(place.checkins ?? 0) checkins" categoryLabel.text = place.category imageURLString = place.picture setupThemeColors() setupFriendsCountLabel(contextCount: place.contextCount ?? 0) //self.contentView.layoutIfNeeded() //self.layoutIfNeeded() //self.layoutSubviews() //self.contentView.layoutSubviews() } private func setupThemeColors() { nameLabel.textColor = UIColor.LABrand.standard categoryLabel.textColor = UIColor.LABrand.detail checkinsCountLabel.textColor = UIColor.LABrand.detail friendsCountLabel.textColor = UIColor.LABrand.accent checkInImageView.tintColor = UIColor.LABrand.detail likeImageView.tintColor = UIColor.LABrand.detail addListButton.tintColor = UIColor.LABrand.primary let tintedImage = #imageLiteral(resourceName: "walking").withRenderingMode(.alwaysTemplate) directionsButton.setImage(tintedImage, for: .normal) directionsButton.tintColor = UIColor.LABrand.primary } private func setupFriendsCountLabel(contextCount: Int) { switch contextCount { case 1: friendsCountLabel.text = "\(contextCount) friend likes this" friendsCountLabel.isHidden = false likeImageView.isHidden = false case _ where contextCount > 1: friendsCountLabel.text = "\(contextCount) friends like this" friendsCountLabel.isHidden = false likeImageView.isHidden = false case 0: friendsCountLabel.isHidden = true likeImageView.isHidden = true default: friendsCountLabel.isHidden = true likeImageView.isHidden = true } } @IBAction func onDirectionsButton(_ sender: Any) { guard let place = place else { print("nil place") return } delegate?.getDirections?(for: place) } // On "Add List" button @IBAction func onAddLIst(_ sender: Any) { let dStoryboard = UIStoryboard(name: "Detail", bundle: nil) let addPlaceVC = dStoryboard.instantiateViewController(withIdentifier: "AddPlaceViewController") as! AddPlaceViewController guard let place = place else { print ("nil place") return } addPlaceVC.place = place delegate?.addPlace(on: addPlaceVC) } override func awakeFromNib() { super.awakeFromNib() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
apache-2.0
df3de70b63e2ee60b113591e0ac651f2
34.1
131
0.656695
5.068592
false
false
false
false
PiXeL16/PasswordTextField
PasswordTextField/SecureTextToggleButton.swift
1
3932
// // SecureTextToggleButton.swift // PasswordTextField // // Created by Chris Jimenez on 2/10/16. // Copyright ยฉ 2016 Chris Jimenez. All rights reserved. // import Foundation /// The Segure text button toggle shown in the right side of the textfield open class SecureTextToggleButton: UIButton { fileprivate let RightMargin:CGFloat = 10.0 fileprivate let Width:CGFloat = 20.0 fileprivate let Height:CGFloat = 20.0 /// Sets the value for the secure or note secure toggle and @objc dynamic open var isSecure:Bool = true{ didSet{ if isSecure{ setVisibilityOn() } else { setVisibilityOff() } } } /// Image to shown when the visibility is on open var showSecureTextImage:UIImage = UIImage(named: "visibility_on", in:BundleUtil.bundle, compatibleWith: nil)!{ didSet{ self.setImage(showSecureTextImage.withRenderingMode(UIImage.RenderingMode.alwaysTemplate),for: UIControl.State()) } } /// Image to shown when the visibility is off open var hideSecureTextImage:UIImage = UIImage(named: "visibility_off", in:BundleUtil.bundle, compatibleWith: nil)! /// Tint of the image open var imageTint:UIColor = UIColor.gray{ didSet{ self.tintColor = imageTint } } /** Convenience init that can be set to initialize the object with visible on image visible off image and image tint - parameter visibilityOnImage: Visible on Image - parameter visibilityOffImage: Visible off Image - parameter imageTint: The tint of the image - returns: */ public convenience init(showSecureTextImage:UIImage = UIImage(named: "visibility_on", in:BundleUtil.bundle, compatibleWith: nil)! , hideSecureTextImage:UIImage = UIImage(named: "visibility_off", in: BundleUtil.bundle, compatibleWith: nil)! , imageTint:UIColor = UIColor.gray) { self.init(frame:CGRect.zero) self.showSecureTextImage = showSecureTextImage self.hideSecureTextImage = hideSecureTextImage self.imageTint = imageTint } public override init(frame: CGRect) { super.init(frame: frame) setup() } public required init?(coder: NSCoder) { super.init(coder: coder) setup() } /** Initialize properties and values */ func setup() { //Initialize the frame and adds a right margin self.frame = CGRect(x: 0, y: -0, width: showSecureTextImage.size.width+RightMargin, height: showSecureTextImage.size.height) //Sets the tint color self.tintColor = imageTint //Sets the aspect fit of the image self.contentMode = UIView.ContentMode.scaleAspectFit self.backgroundColor = UIColor.clear //Initialize the component with the secure state isSecure = true //Sets the button target self.addTarget(self, action: #selector(SecureTextToggleButton.buttonTouch), for: .touchUpInside) } /** Updates the image and the set the visibility on icon */ func setVisibilityOn() { self.setImage(showSecureTextImage.withRenderingMode(UIImage.RenderingMode.alwaysTemplate),for: UIControl.State()) } /** Update teh image and sets the visibility off icon */ func setVisibilityOff() { self.setImage(hideSecureTextImage.withRenderingMode(UIImage.RenderingMode.alwaysTemplate),for: UIControl.State()) } /** Toggle the icon */ @objc open func buttonTouch() { self.isSecure = !self.isSecure } }
mit
53c682341bf89e840c5617ba2e9ea13a
26.110345
279
0.61104
4.969659
false
false
false
false
robzimpulse/mynurzSDK
Example/mynurzSDK/GoogleMapViewController.swift
1
907
// // GoogleMapViewController.swift // mynurzSDK // // Created by Robyarta on 6/10/17. // Copyright ยฉ 2017 CocoaPods. All rights reserved. // import UIKit import GoogleMaps import mynurzSDK class GoogleMapViewController: UIViewController { let sdk = MynurzSDK.sharedInstance override func viewDidLoad() { super.viewDidLoad() GMSServices.provideAPIKey(sdk.googleMapKey) let camera = GMSCameraPosition.camera(withLatitude: -6.1930799,longitude: 106.7742516,zoom: 14) let mapView = GMSMapView.map(withFrame: .zero, camera: camera) let marker = GMSMarker() marker.position = camera.target marker.snippet = "Hello World" marker.appearAnimation = GMSMarkerAnimation.pop marker.map = mapView view = mapView } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
mit
8f9953df8fee5e7eb199d6a346ad0b41
25.647059
103
0.681015
4.622449
false
false
false
false
jmcd/AvoidMegaController
DemoApp/UIKitTools.swift
1
3573
import UIKit extension UIView { func constraintsMaximizingInView(view: UIView, topLayoutGuide: UILayoutSupport? = nil, bottomLayoutGuide: UILayoutSupport? = nil, insets: UIEdgeInsets = UIEdgeInsetsZero) -> [NSLayoutConstraint] { return [ self.constraintWithAttribute(.Top, toItem: topLayoutGuide ?? view, itemAttribute: topLayoutGuide == nil ? .Top : .Bottom, constant: insets.top), self.constraintWithAttribute(.Bottom, toItem: bottomLayoutGuide ?? view, itemAttribute: bottomLayoutGuide == nil ? .Bottom : .Top, constant: insets.bottom), self.constraintWithAttribute(.Left, toItem: view, constant: insets.left), self.constraintWithAttribute(.Right, toItem: view, constant: insets.right), ] } func constraintWithAttribute(attribute: NSLayoutAttribute, relatedBy: NSLayoutRelation = .Equal, toItem: AnyObject?, multiplier: CGFloat = 1.0, constant: CGFloat = 0.0) -> NSLayoutConstraint { return NSLayoutConstraint(item: self, attribute: attribute, relatedBy: relatedBy, toItem: toItem, attribute: attribute, multiplier: multiplier, constant: constant) } func constraintWithAttribute(attribute: NSLayoutAttribute, relatedBy: NSLayoutRelation = .Equal, toItem: AnyObject?, itemAttribute: NSLayoutAttribute, multiplier: CGFloat = 1.0, constant: CGFloat = 0.0) -> NSLayoutConstraint { return NSLayoutConstraint(item: self, attribute: attribute, relatedBy: relatedBy, toItem: toItem, attribute: itemAttribute, multiplier: multiplier, constant: constant) } func constraintWithAttribute(attribute: NSLayoutAttribute, relatedBy: NSLayoutRelation, constant: CGFloat) -> NSLayoutConstraint { return NSLayoutConstraint(item: self, attribute: attribute, relatedBy: relatedBy, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: constant) } } extension UIView { func addSubviews(subviews: [UIView], translatesAutoresizingMaskIntoConstraints: Bool = false) { for sv in subviews { addSubview(sv) sv.translatesAutoresizingMaskIntoConstraints = translatesAutoresizingMaskIntoConstraints } } } class NSLayoutConstraintBuilder { var views = Dictionary<String, AnyObject>() var constraints = Array<NSLayoutConstraint>() func usingViews(nameToViewOrLayoutGuide:[String:AnyObject]) -> NSLayoutConstraintBuilder { for kvp in nameToViewOrLayoutGuide { let obj = kvp.1 if let v = obj as? UIView { v.translatesAutoresizingMaskIntoConstraints = false } self.views[kvp.0] = obj } return self; } func createConstraintsWithVisualFormat(format:String) -> NSLayoutConstraintBuilder { let cs = NSLayoutConstraint.constraintsWithVisualFormat(format, options: NSLayoutFormatOptions(), metrics: nil, views: self.views) self.constraints.appendContentsOf(cs) return self } func createConstraintsWithVisualFormats(formats:Array<String>) -> NSLayoutConstraintBuilder { for f in formats { self.createConstraintsWithVisualFormat(f) } return self } func addConstraintsToView(view: UIView) -> NSLayoutConstraintBuilder { view.addConstraints(self.constraints) self.constraints = Array<NSLayoutConstraint>() return self } } extension UIEdgeInsets { static func uniform(value: CGFloat) -> UIEdgeInsets { return UIEdgeInsets(top: value, left: value, bottom: -value, right: -value) } } class MinimalView: UIView { convenience init() { self.init(frame: CGRectZero) } override init(frame: CGRect) { super.init(frame: frame) boot() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func boot() { } }
apache-2.0
d7add881f8bdf4971eb4dca254cc8090
34.376238
227
0.759306
4.394834
false
false
false
false
jamesbond12/actor-platform
actor-apps/app-ios/ActorApp/Controllers/Dialogs/DialogsViewController.swift
1
9125
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import UIKit class DialogsViewController: EngineListController, UISearchBarDelegate, UISearchDisplayDelegate { var tableView: UITableView! var searchView: UISearchBar? var searchDisplay: UISearchDisplayController? var searchSource: DialogsSearchSource? var binder = Binder() init() { super.init(contentSection: 0) tabBarItem = UITabBarItem( title: localized("TabMessages"), image: UIImage(named: "TabIconChats")?.styled("tab.icon"), selectedImage: UIImage(named: "TabIconChatsHighlighted")?.styled("tab.icon.selected")) binder.bind(Actor.getAppState().getGlobalCounter(), closure: { (value: JavaLangInteger?) -> () in if value != nil { if value!.integerValue > 0 { self.tabBarItem.badgeValue = "\(value!.integerValue)" } else { self.tabBarItem.badgeValue = nil } } else { self.tabBarItem.badgeValue = nil } }) if (!MainAppTheme.tab.showText) { tabBarItem.imageInsets = UIEdgeInsetsMake(6, 0, -6, 0); } } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func loadView() { super.loadView() self.extendedLayoutIncludesOpaqueBars = true tableView = UITableView() tableView.separatorStyle = UITableViewCellSeparatorStyle.None tableView.rowHeight = 76 tableView.backgroundColor = MainAppTheme.list.bgColor view.addSubview(tableView) // view = tableView } override func buildDisplayList() -> ARBindedDisplayList { return Actor.getDialogsDisplayList() } func isTableEditing() -> Bool { return self.tableView.editing; } override func viewDidLoad() { bindTable(tableView, fade: true); searchView = UISearchBar() searchView!.delegate = self searchView!.frame = CGRectMake(0, 0, 320, 44) searchView!.keyboardAppearance = MainAppTheme.common.isDarkKeyboard ? UIKeyboardAppearance.Dark : UIKeyboardAppearance.Light MainAppTheme.search.styleSearchBar(searchView!) searchDisplay = UISearchDisplayController(searchBar: searchView!, contentsController: self) searchDisplay?.searchResultsDelegate = self searchDisplay?.searchResultsTableView.rowHeight = 76 searchDisplay?.searchResultsTableView.separatorStyle = UITableViewCellSeparatorStyle.None searchDisplay?.searchResultsTableView.backgroundColor = MainAppTheme.list.bgColor searchDisplay?.searchResultsTableView.frame = tableView.frame let header = TableViewHeader(frame: CGRectMake(0, 0, 320, 44)) header.addSubview(searchDisplay!.searchBar) tableView.tableHeaderView = header searchSource = DialogsSearchSource(searchDisplay: searchDisplay!) super.viewDidLoad(); navigationItem.title = NSLocalizedString("TabMessages", comment: "Messages Title") navigationItem.leftBarButtonItem = editButtonItem() navigationItem.leftBarButtonItem!.title = NSLocalizedString("NavigationEdit", comment: "Edit Title"); navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Compose, target: self, action: "navigateToCompose") placeholder.setImage( UIImage(named: "chat_list_placeholder"), title: NSLocalizedString("Placeholder_Dialogs_Title", comment: "Placeholder Title"), subtitle: NSLocalizedString("Placeholder_Dialogs_Message", comment: "Placeholder Message")) binder.bind(Actor.getAppState().getIsDialogsEmpty(), closure: { (value: Any?) -> () in if let empty = value as? JavaLangBoolean { if Bool(empty.booleanValue()) == true { self.navigationItem.leftBarButtonItem = nil self.showPlaceholder() } else { self.hidePlaceholder() self.navigationItem.leftBarButtonItem = self.editButtonItem() } } }) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) Actor.onDialogsOpen(); } override func viewDidDisappear(animated: Bool) { Actor.onDialogsClosed(); } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // SearchBar hack let searchBar = searchDisplay!.searchBar let superView = searchBar.superview if !(superView is UITableView) { searchBar.removeFromSuperview() superView?.addSubview(searchBar) } // Header hack tableView.tableHeaderView?.setNeedsLayout() tableView.tableFooterView?.setNeedsLayout() // tableView.frame = CGRectMake(0, 0, view.frame.width, view.frame.height) if (searchDisplay != nil && searchDisplay!.active) { MainAppTheme.search.applyStatusBar() } else { MainAppTheme.navigation.applyStatusBar() } } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() tableView.frame = CGRectMake(0, 0, view.frame.width, view.frame.height) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) searchDisplay?.setActive(false, animated: animated) } // MARK: - // MARK: Setters override func setEditing(editing: Bool, animated: Bool) { super.setEditing(editing, animated: animated) tableView.setEditing(editing, animated: animated) if (editing) { self.navigationItem.leftBarButtonItem!.title = NSLocalizedString("NavigationDone", comment: "Done Title"); self.navigationItem.leftBarButtonItem!.style = UIBarButtonItemStyle.Done; navigationItem.rightBarButtonItem = nil } else { self.navigationItem.leftBarButtonItem!.title = NSLocalizedString("NavigationEdit", comment: "Edit Title"); self.navigationItem.leftBarButtonItem!.style = UIBarButtonItemStyle.Bordered; navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Compose, target: self, action: "navigateToCompose") } if editing == true { navigationItem.rightBarButtonItem = nil } else { navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Compose, target: self, action: "navigateToCompose") } } // MARK: - // MARK: UITableView func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if (editingStyle == UITableViewCellEditingStyle.Delete) { let dialog = objectAtIndexPath(indexPath) as! ACDialog execute(Actor.deleteChatCommandWithPeer(dialog.getPeer())); } } override func buildCell(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, item: AnyObject?) -> UITableViewCell { let reuseKey = "cell_dialog"; var cell = tableView.dequeueReusableCellWithIdentifier(reuseKey) as! DialogCell?; if (cell == nil){ cell = DialogCell(reuseIdentifier: reuseKey); cell?.awakeFromNib(); } return cell!; } override func bindCell(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, item: AnyObject?, cell: UITableViewCell) { let dialog = item as! ACDialog; let isLast = indexPath.row == tableView.numberOfRowsInSection(indexPath.section) - 1; (cell as! DialogCell).bindDialog(dialog, isLast: isLast); } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if (tableView == self.tableView) { let dialog = objectAtIndexPath(indexPath) as! ACDialog navigateToMessagesWithPeer(dialog.getPeer()) } else { let searchEntity = searchSource!.objectAtIndexPath(indexPath) as! ACSearchEntity navigateToMessagesWithPeer(searchEntity.getPeer()) } // tableView.deselectRowAtIndexPath(indexPath, animated: true) } // MARK: - // MARK: Navigation func navigateToCompose() { navigateDetail(ComposeController()) } private func navigateToMessagesWithPeer(peer: ACPeer) { navigateDetail(ConversationViewController(peer: peer)) MainAppTheme.navigation.applyStatusBar() } }
mit
880eb53b17be25702aa44281f0bbf466
36.55144
158
0.634301
5.778974
false
false
false
false
joerocca/GitHawk
Classes/Search/SearchRecentStore.swift
2
961
// // SearchRecentStore.swift // Freetime // // Created by Ryan Nystrom on 9/4/17. // Copyright ยฉ 2017 Ryan Nystrom. All rights reserved. // import Foundation class SearchRecentStore: Store { typealias Model = SearchQuery let key = "com.freetime.SearchRecentStore.results" let defaults = UserDefaults.standard var values: [SearchQuery] var listeners: [ListenerWrapper] = [] let encoder = JSONEncoder() let decoder = JSONDecoder() init() { if let data = defaults.object(forKey: key) as? Data, let array = try? decoder.decode([SearchQuery].self, from: data) { values = array } else { values = [] } } // MARK: Public API func add(_ value: SearchQuery) { remove(value) values.insert(value, at: 0) // keep recents trimmed while values.count > 15 { values.removeLast() } save() } }
mit
d01167ea0a991a80e3c8bd87f7ef4cf2
19.425532
77
0.582292
4.173913
false
false
false
false
vonholst/deeplearning_example_kog
HotdogOrNohotdog/HotdogOrNohotdog/ViewController.swift
1
4573
// // ViewController.swift // HotdogOrNohotdog // // Created by Michael Jasinski on 2017-10-25. // Copyright ยฉ 2017 HiQ. All rights reserved. // import UIKit import CoreML import Vision import AVFoundation class ViewController: UIViewController, AVCaptureVideoDataOutputSampleBufferDelegate { // Connect UI to code @IBOutlet weak var classificationText: UILabel! @IBOutlet weak var cameraView: UIView! private var requests = [VNRequest]() private lazy var cameraLayer: AVCaptureVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: self.captureSession) private lazy var captureSession: AVCaptureSession = { let session = AVCaptureSession() session.sessionPreset = AVCaptureSession.Preset.photo guard let backCamera = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back), let input = try? AVCaptureDeviceInput(device: backCamera) else { return session } session.addInput(input) return session }() var player: AVAudioPlayer? override func viewDidLoad() { super.viewDidLoad() self.cameraView?.layer.addSublayer(self.cameraLayer) let videoOutput = AVCaptureVideoDataOutput() videoOutput.setSampleBufferDelegate(self, queue: DispatchQueue(label: "MyQueue")) self.captureSession.addOutput(videoOutput) self.captureSession.startRunning() setupVision() self.classificationText.text = "" cameraView.bringSubview(toFront: self.classificationText) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() self.cameraLayer.frame = self.cameraView?.bounds ?? .zero } func setupVision() { guard let visionModel = try? VNCoreMLModel(for: hotdog_classifier().model) else { fatalError("Can't load VisionML model") } let classificationRequest = VNCoreMLRequest(model: visionModel, completionHandler: handleClassifications) classificationRequest.imageCropAndScaleOption = VNImageCropAndScaleOption.centerCrop self.requests = [classificationRequest] } func handleClassifications(request: VNRequest, error: Error?) { guard let observations = request.results as? [VNClassificationObservation] else { print("no results: \(error!)"); return } guard let best = observations.first else { fatalError("can't get best result") } print("\(best.identifier), \(best.confidence)") // latch to hotdog / no-hotdog if best.confidence > 0.9 && best.identifier == "hotdog" { DispatchQueue.main.async { if self.classificationText.text == "" { self.playSound() } self.classificationText.text = "๐ŸŒญ" } } else if best.confidence > 0.6 && best.identifier == "non_hotdog" { DispatchQueue.main.async { self.classificationText.text = "" } } } func playSound() { guard let url = Bundle.main.url(forResource: "hotdog", withExtension: "wav") else { return } do { try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) try AVAudioSession.sharedInstance().setActive(true) player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.wav.rawValue) guard let player = player else { return } player.play() } catch let error { print(error.localizedDescription) } } func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) { guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return } var requestOptions:[VNImageOption : Any] = [:] if let cameraIntrinsicData = CMGetAttachment(sampleBuffer, kCMSampleBufferAttachmentKey_CameraIntrinsicMatrix, nil) { requestOptions = [.cameraIntrinsics:cameraIntrinsicData] } let imageRequestHandler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, orientation: CGImagePropertyOrientation(rawValue: 1)!, options: requestOptions) do { try imageRequestHandler.perform(self.requests) } catch { print(error) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
mit
bcab1642484bd3a4a00d6dd71b399ae8
37.720339
163
0.650252
5.269896
false
false
false
false
TopCoderChallenge/FlowerBed
FlowerBed/PickerImage.swift
1
3768
// // PickerImage.swift // ScribbleKeys // // Created by Matthias Schlemm on 12/06/15. // Copyright (c) 2015 Sixpolys. All rights reserved. // import UIKit import ImageIO public class PickerImage { var provider:CGDataProvider! var imageSource:CGImageSource? var image:UIImage? var mutableData:CFMutableDataRef var width:Int var height:Int private func createImageFromData(width:Int, height:Int) { let colorSpace = CGColorSpaceCreateDeviceRGB() let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedFirst.rawValue) provider = CGDataProviderCreateWithCFData(mutableData) imageSource = CGImageSourceCreateWithDataProvider(provider, nil) let cgimg = CGImageCreate(Int(width), Int(height), Int(8), Int(32), Int(width) * Int(4), colorSpace, bitmapInfo, provider!, nil as UnsafePointer<CGFloat>, true, CGColorRenderingIntent.RenderingIntentDefault) image = UIImage(CGImage: cgimg!) } func changeSize(width:Int, height:Int) { self.width = width self.height = height let size:Int = width * height * 4 CFDataSetLength(mutableData, size) createImageFromData(width, height: height) } init(width:Int, height:Int) { self.width = width self.height = height let size:Int = width * height * 4 mutableData = CFDataCreateMutable(kCFAllocatorDefault, size) createImageFromData(width, height: height) } public func writeColorData(h:CGFloat, a:CGFloat) { let d = CFDataGetMutableBytePtr(self.mutableData) if width == 0 || height == 0 { return } var i:Int = 0 let h360:CGFloat = ((h == 1 ? 0 : h) * 360) / 60.0 let sector:Int = Int(floor(h360)) let f:CGFloat = h360 - CGFloat(sector) let f1:CGFloat = 1.0 - f var p:CGFloat = 0.0 var q:CGFloat = 0.0 var t:CGFloat = 0.0 let sd:CGFloat = 1.0 / CGFloat(width) let vd:CGFloat = 1 / CGFloat(height) var double_s:CGFloat = 0 var pf:CGFloat = 0 let v_range = 0..<height let s_range = 0..<width for v in v_range { pf = 255 * CGFloat(v) * vd for s in s_range { i = (v * width + s) * 4 d[i] = UInt8(255) if s == 0 { q = pf d[i+1] = UInt8(q) d[i+2] = UInt8(q) d[i+3] = UInt8(q) continue } double_s = CGFloat(s) * sd p = pf * (1.0 - double_s) q = pf * (1.0 - double_s * f) t = pf * ( 1.0 - double_s * f1) switch(sector) { case 0: d[i+1] = UInt8(pf) d[i+2] = UInt8(t) d[i+3] = UInt8(p) case 1: d[i+1] = UInt8(q) d[i+2] = UInt8(pf) d[i+3] = UInt8(p) case 2: d[i+1] = UInt8(p) d[i+2] = UInt8(pf) d[i+3] = UInt8(t) case 3: d[i+1] = UInt8(p) d[i+2] = UInt8(q) d[i+3] = UInt8(pf) case 4: d[i+1] = UInt8(t) d[i+2] = UInt8(p) d[i+3] = UInt8(pf) default: d[i+1] = UInt8(pf) d[i+2] = UInt8(p) d[i+3] = UInt8(q) } } } } }
mit
3a4abbdcb0567ef469b20610c723a314
30.408333
131
0.464703
3.868583
false
false
false
false
legendecas/Rocket.Chat.iOS
Test.Shared/WebSocketMock.swift
1
4533
// // WebSocketMock.swift // Rocket.Chat // // Created by Lucas Woo on 8/5/17. // Copyright ยฉ 2017 Rocket.Chat. All rights reserved. // import Foundation import ObjectiveC import SwiftyJSON @testable import Starscream typealias SendMessage = (JSON) -> Void typealias OnJSONReceived = (JSON, SendMessage) -> Void class WebSocketMock: WebSocket { var onJSONReceived = [OnJSONReceived]() var mockConnected = false // MARK: - Mock Middlewares func use(_ middlewares: OnJSONReceived...) { onJSONReceived.append(contentsOf: middlewares) } // MARK: - Mocks override var isConnected: Bool { return mockConnected } convenience init() { guard let url = URL(string: "http://doesnt.matter") else { self.init() return } self.init(url: url) } /** Connect to the WebSocket server on a background thread. */ override func connect() { DispatchQueue.global(qos: .background).async { self.mockConnected = true self.onConnect?() self.delegate?.websocketDidConnect(socket: self) } } /** Disconnect from the server. I send a Close control frame to the server, then expect the server to respond with a Close control frame and close the socket from its end. I notify my delegate once the socket has been closed. If you supply a non-nil `forceTimeout`, I wait at most that long (in seconds) for the server to close the socket. After the timeout expires, I close the socket and notify my delegate. If you supply a zero (or negative) `forceTimeout`, I immediately close the socket (without sending a Close control frame) and notify my delegate. - Parameter forceTimeout: Maximum time to wait for the server to close the socket. - Parameter closeCode: The code to send on disconnect. The default is the normal close code for cleanly disconnecting a webSocket. */ override func disconnect(forceTimeout: TimeInterval? = nil, closeCode: UInt16 = CloseCode.normal.rawValue) { DispatchQueue.global(qos: .background).async { self.mockConnected = false self.onDisconnect?(nil) self.delegate?.websocketDidDisconnect(socket: self, error: nil) } } /** Write a string to the websocket. This sends it as a text frame. If you supply a non-nil completion block, I will perform it when the write completes. - parameter string: The string to write. - parameter completion: The (optional) completion handler. */ override func write(string: String, completion: (() -> Void)? = nil) { let send: SendMessage = { json in DispatchQueue.global(qos: .background).async { guard let string = json.rawString() else { return } self.onText?(string) self.delegate?.websocketDidReceiveMessage(socket: self, text: string) } } if let data = string.data(using: .utf8) { let json = JSON(data: data) if json.exists() { DispatchQueue.global(qos: .background).async { self.onJSONReceived.forEach { $0(json, send) } } completion?() } } } /** Write binary data to the websocket. This sends it as a binary frame. If you supply a non-nil completion block, I will perform it when the write completes. - parameter data: The data to write. - parameter completion: The (optional) completion handler. */ override func write(data: Data, completion: (() -> Void)? = nil) { let send: SendMessage = { json in DispatchQueue.global(qos: .background).async { guard let string = json.rawString() else { return } self.onText?(string) self.delegate?.websocketDidReceiveMessage(socket: self, text: string) } } let json = JSON(data: data) if json.exists() { DispatchQueue.global(qos: .background).async { self.onJSONReceived.forEach { $0(json, send) } } completion?() } } /** Write a ping to the websocket. This sends it as a control frame. Yodel a sound to the planet. This sends it as an astroid. http://youtu.be/Eu5ZJELRiJ8?t=42s */ override func write(ping: Data, completion: (() -> Void)? = nil) { completion?() } }
mit
6a4519c7dfb65ce740dc47f62ab1f51d
33.333333
226
0.615181
4.541082
false
false
false
false
artemstepanenko/Dekoter
Dekoter/Classes/UserDefaults+Dekoter.swift
1
3650
// // UserDefaults+Dekoter.swift // Dekoter // // Created by Artem Stepanenko on 16/01/17. // Copyright (c) 2016 Artem Stepanenko <[email protected]> // // 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 /// A handy `UserDefaults` extension to save/load objects which implement the `Koting` protocol. public extension UserDefaults { /// Sets the value of the specified default key to the specified object which implements the `Koting` protocol. /// /// - Parameters: /// - value: The object which implements the `Koting` protocol to store in the defaults database. /// - defaultName: The key with which to associate with the value. public func de_set(_ value: Koting?, forKey defaultName: String) { var data: Data? = nil if let value = value { data = NSKeyedArchiver.de_archivedData(withRootObject: value) } set(data, forKey: defaultName) } /// Sets the value of the specified default key to the specified array of objects /// which implement the `Koting` protocol. /// /// - Parameters: /// - value: The array of objects which implement the `Koting` protocol to store in the defaults database. /// - defaultName: The key with which to associate with the array. public func de_set(_ value: [Koting]?, forKey defaultName: String) { var data: Data? = nil if let value = value { data = NSKeyedArchiver.de_archivedData(withRootObject: value) } set(data, forKey: defaultName) } /// Returns the object which implements the `Koting` protocol associated with the specified key. /// /// - Parameter defaultName: A key in the current user's defaults database. /// - Returns: The object which implements the `Koting` protocol. public func de_object<T: Koting>(forKey defaultName: String) -> T? { guard let data = object(forKey: defaultName) as? Data else { return nil } return NSKeyedUnarchiver.de_unarchiveObject(with: data) } /// Returns the array of objects which implement the `Koting` protocol associated with the specified key. /// /// - Parameter defaultName: A key in the current user's defaults database. /// - Returns: The array of objects which implement the `Koting` protocol. public func de_object<T: Koting>(forKey defaultName: String) -> [T]? { guard let data = object(forKey: defaultName) as? Data else { return nil } return NSKeyedUnarchiver.de_unarchiveObject(with: data) } }
mit
3764886684fb289f85d896505b6d3e90
45.202532
115
0.686027
4.440389
false
false
false
false
mightydeveloper/swift
validation-test/compiler_crashers_fixed/1385-swift-typedecl-getdeclaredtype.swift
12
1586
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func d<b.g == A: A : $0) { enum A { func c: A { S.C(v: c: [T) -> e(AnyObject, T) } } t: a { i<C } class A where Optional<Int print() { } } typealias R } var d = .e { func a(.Type) -> (g<h.init(A, AnyObject> { return g(self.b class a()) } convenience init() } import Foundation } for (bytes: e(() } return { class func b<T>(self.B return d: B<l : Any) -> T, self.C(object1, range: ()(Any, object2: 1]], f: A, (h.Element == [T { typealias b { return " } extension A { } return { _, x } } let n1: A { var b = B<T) -> S) { _, T -> V, e: (a) } func d.join(c { self.c = a<I : 1) switch x = a<T? { protocol d = [c: T? { } class a { struct c : () return b(T, length: S<d: b = nil func a<c() { case c>())) return nil } var d, A { struct c { func c() -> { typealias h>(.count](a<3)) } return true class d b, x = 1) } private let n1: d : a<d(n: Any) as [self.B == "".advance(mx : NSObject { init()) } func d: T } typealias e = [unowned self.init() enum S) { } self] in class a<Q<T) -> V { } } } class a { case s() class A.Generator.count] } enum A : String { func d<h : [unowned self.E == compose<T] = [c() } typealias A { } let c in return S.join() { protocol a { } b return d.B struct e { func g(range: H) -> () } var d>(c = { } } assert() -> : A? { return b: String { typealias e == Swift.init(a: Hashable> String { class A { print(s(self.startIndex)"foobar"") } let start = b<T
apache-2.0
b7dfcd33c183940b492b333dd4ee758d
14.104762
96
0.584489
2.417683
false
false
false
false
niunaruto/DeDaoAppSwift
testSwift/Pods/RxAlamofire/Sources/RxAlamofire.swift
2
36376
// // RxAlamofire.swift // RxAlamofire // // Created by Junior B. (@bontojr) on 23/08/15. // Developed with the kind help of Krunoslav Zaher (@KrunoslavZaher) // // Updated by Ivan ฤikiฤ‡ for the latest version of Alamofire(3) and RxSwift(2) on 21/10/15 // Updated by Krunoslav Zaher to better wrap Alamofire (3) on 1/10/15 // // Copyright ยฉ 2015 Bonto.ch. All rights reserved. // import Foundation import Alamofire import RxSwift /// Default instance of unknown error public let RxAlamofireUnknownError = NSError(domain: "RxAlamofireDomain", code: -1, userInfo: nil) // MARK: Convenience functions /** Creates a NSMutableURLRequest using all necessary parameters. - parameter method: Alamofire method object - parameter url: An object adopting `URLConvertible` - parameter parameters: A dictionary containing all necessary options - parameter encoding: The kind of encoding used to process parameters - parameter header: A dictionary containing all the additional headers - returns: An instance of `NSMutableURLRequest` */ public func urlRequest(_ method: Alamofire.HTTPMethod, _ url: URLConvertible, parameters: [String: Any]? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: [String: String]? = nil) throws -> Foundation.URLRequest { var mutableURLRequest = Foundation.URLRequest(url: try url.asURL()) mutableURLRequest.httpMethod = method.rawValue if let headers = headers { for (headerField, headerValue) in headers { mutableURLRequest.setValue(headerValue, forHTTPHeaderField: headerField) } } if let parameters = parameters { mutableURLRequest = try encoding.encode(mutableURLRequest, with: parameters) } return mutableURLRequest } // MARK: Request /** Creates an observable of the generated `Request`. - parameter method: Alamofire method object - parameter url: An object adopting `URLConvertible` - parameter parameters: A dictionary containing all necessary options - parameter encoding: The kind of encoding used to process parameters - parameter header: A dictionary containing all the additional headers - returns: An observable of a the `Request` */ public func request(_ method: Alamofire.HTTPMethod, _ url: URLConvertible, parameters: [String: Any]? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: [String: String]? = nil) -> Observable<DataRequest> { return SessionManager.default.rx.request(method, url, parameters: parameters, encoding: encoding, headers: headers) } /** Creates an observable of the generated `Request`. - parameter urlRequest: An object adopting `URLRequestConvertible` - returns: An observable of a the `Request` */ public func request(_ urlRequest: URLRequestConvertible) -> Observable<DataRequest> { return SessionManager.default.rx.request(urlRequest: urlRequest) } // MARK: data /** Creates an observable of the `(NSHTTPURLResponse, NSData)` instance. - parameter method: Alamofire method object - parameter url: An object adopting `URLConvertible` - parameter parameters: A dictionary containing all necessary options - parameter encoding: The kind of encoding used to process parameters - parameter header: A dictionary containing all the additional headers - returns: An observable of a tuple containing `(NSHTTPURLResponse, NSData)` */ public func requestData(_ method: Alamofire.HTTPMethod, _ url: URLConvertible, parameters: [String: Any]? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: [String: String]? = nil) -> Observable<(HTTPURLResponse, Data)> { return SessionManager.default.rx.responseData(method, url, parameters: parameters, encoding: encoding, headers: headers) } /** Creates an observable of the `(NSHTTPURLResponse, NSData)` instance. - parameter urlRequest: An object adopting `URLRequestConvertible` - returns: An observable of a tuple containing `(NSHTTPURLResponse, NSData)` */ public func requestData(_ urlRequest: URLRequestConvertible) -> Observable<(HTTPURLResponse, Data)> { return request(urlRequest).flatMap { $0.rx.responseData() } } /** Creates an observable of the returned data. - parameter method: Alamofire method object - parameter url: An object adopting `URLConvertible` - parameter parameters: A dictionary containing all necessary options - parameter encoding: The kind of encoding used to process parameters - parameter header: A dictionary containing all the additional headers - returns: An observable of `NSData` */ public func data(_ method: Alamofire.HTTPMethod, _ url: URLConvertible, parameters: [String: Any]? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: [String: String]? = nil) -> Observable<Data> { return SessionManager.default.rx.data(method, url, parameters: parameters, encoding: encoding, headers: headers) } // MARK: string /** Creates an observable of the returned decoded string and response. - parameter method: Alamofire method object - parameter url: An object adopting `URLConvertible` - parameter parameters: A dictionary containing all necessary options - parameter encoding: The kind of encoding used to process parameters - parameter header: A dictionary containing all the additional headers - returns: An observable of the tuple `(NSHTTPURLResponse, String)` */ public func requestString(_ method: Alamofire.HTTPMethod, _ url: URLConvertible, parameters: [String: Any]? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: [String: String]? = nil) -> Observable<(HTTPURLResponse, String)> { return SessionManager.default.rx.responseString(method, url, parameters: parameters, encoding: encoding, headers: headers) } /** Creates an observable of the returned decoded string and response. - parameter urlRequest: An object adopting `URLRequestConvertible` - returns: An observable of the tuple `(NSHTTPURLResponse, String)` */ public func requestString(_ urlRequest: URLRequestConvertible) -> Observable<(HTTPURLResponse, String)> { return request(urlRequest).flatMap { $0.rx.responseString() } } /** Creates an observable of the returned decoded string. - parameter method: Alamofire method object - parameter url: An object adopting `URLConvertible` - parameter parameters: A dictionary containing all necessary options - parameter encoding: The kind of encoding used to process parameters - parameter header: A dictionary containing all the additional headers - returns: An observable of `String` */ public func string(_ method: Alamofire.HTTPMethod, _ url: URLConvertible, parameters: [String: Any]? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: [String: String]? = nil) -> Observable<String> { return SessionManager.default.rx.string(method, url, parameters: parameters, encoding: encoding, headers: headers) } // MARK: JSON /** Creates an observable of the returned decoded JSON as `AnyObject` and the response. - parameter method: Alamofire method object - parameter url: An object adopting `URLConvertible` - parameter parameters: A dictionary containing all necessary options - parameter encoding: The kind of encoding used to process parameters - parameter header: A dictionary containing all the additional headers - returns: An observable of the tuple `(NSHTTPURLResponse, AnyObject)` */ public func requestJSON(_ method: Alamofire.HTTPMethod, _ url: URLConvertible, parameters: [String: Any]? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: [String: String]? = nil) -> Observable<(HTTPURLResponse, Any)> { return SessionManager.default.rx.responseJSON(method, url, parameters: parameters, encoding: encoding, headers: headers) } /** Creates an observable of the returned decoded JSON as `AnyObject` and the response. - parameter urlRequest: An object adopting `URLRequestConvertible` - returns: An observable of the tuple `(NSHTTPURLResponse, AnyObject)` */ public func requestJSON(_ urlRequest: URLRequestConvertible) -> Observable<(HTTPURLResponse, Any)> { return request(urlRequest).flatMap { $0.rx.responseJSON() } } /** Creates an observable of the returned decoded JSON. - parameter method: Alamofire method object - parameter url: An object adopting `URLConvertible` - parameter parameters: A dictionary containing all necessary options - parameter encoding: The kind of encoding used to process parameters - parameter header: A dictionary containing all the additional headers - returns: An observable of the decoded JSON as `Any` */ public func json(_ method: Alamofire.HTTPMethod, _ url: URLConvertible, parameters: [String: Any]? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: [String: String]? = nil) -> Observable<Any> { return SessionManager.default.rx.json(method, url, parameters: parameters, encoding: encoding, headers: headers) } // MARK: Upload /** Returns an observable of a request using the shared manager instance to upload a specific file to a specified URL. The request is started immediately. - parameter urlRequest: The request object to start the upload. - paramenter file: An instance of NSURL holding the information of the local file. - returns: The observable of `UploadRequest` for the created request. */ public func upload(_ file: URL, urlRequest: URLRequestConvertible) -> Observable<UploadRequest> { return SessionManager.default.rx.upload(file, urlRequest: urlRequest) } /** Returns an observable of a request using the shared manager instance to upload any data to a specified URL. The request is started immediately. - parameter urlRequest: The request object to start the upload. - paramenter data: An instance of NSData holdint the data to upload. - returns: The observable of `UploadRequest` for the created request. */ public func upload(_ data: Data, urlRequest: URLRequestConvertible) -> Observable<UploadRequest> { return SessionManager.default.rx.upload(data, urlRequest: urlRequest) } /** Returns an observable of a request using the shared manager instance to upload any stream to a specified URL. The request is started immediately. - parameter urlRequest: The request object to start the upload. - paramenter stream: The stream to upload. - returns: The observable of `Request` for the created upload request. */ public func upload(_ stream: InputStream, urlRequest: URLRequestConvertible) -> Observable<UploadRequest> { return SessionManager.default.rx.upload(stream, urlRequest: urlRequest) } // MARK: Download /** Creates a download request using the shared manager instance for the specified URL request. - parameter urlRequest: The URL request. - parameter destination: The closure used to determine the destination of the downloaded file. - returns: The observable of `DownloadRequest` for the created download request. */ public func download(_ urlRequest: URLRequestConvertible, to destination: @escaping DownloadRequest.DownloadFileDestination) -> Observable<DownloadRequest> { return SessionManager.default.rx.download(urlRequest, to: destination) } // MARK: Resume Data /** Creates a request using the shared manager instance for downloading from the resume data produced from a previous request cancellation. - parameter resumeData: The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask` when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional information. - parameter destination: The closure used to determine the destination of the downloaded file. - returns: The observable of `Request` for the created download request. */ public func download(resumeData: Data, to destination: @escaping DownloadRequest.DownloadFileDestination) -> Observable<DownloadRequest> { return SessionManager.default.rx.download(resumeData: resumeData, to: destination) } // MARK: Manager - Extension of Manager extension SessionManager: ReactiveCompatible {} protocol RxAlamofireRequest { func responseWith(completionHandler: @escaping (RxAlamofireResponse) -> Void) func resume() func cancel() } protocol RxAlamofireResponse { var error: Error? { get } } extension DefaultDataResponse: RxAlamofireResponse {} extension DefaultDownloadResponse: RxAlamofireResponse {} extension DataRequest: RxAlamofireRequest { func responseWith(completionHandler: @escaping (RxAlamofireResponse) -> Void) { response { response in completionHandler(response) } } } extension DownloadRequest: RxAlamofireRequest { func responseWith(completionHandler: @escaping (RxAlamofireResponse) -> Void) { response { response in completionHandler(response) } } } extension Reactive where Base: SessionManager { // MARK: Generic request convenience /** Creates an observable of the DataRequest. - parameter createRequest: A function used to create a `Request` using a `Manager` - returns: A generic observable of created data request */ func request<R: RxAlamofireRequest>(_ createRequest: @escaping (SessionManager) throws -> R) -> Observable<R> { return Observable.create { observer -> Disposable in let request: R do { request = try createRequest(self.base) observer.on(.next(request)) request.responseWith(completionHandler: { response in if let error = response.error { observer.on(.error(error)) } else { observer.on(.completed) } }) if !self.base.startRequestsImmediately { request.resume() } return Disposables.create { request.cancel() } } catch { observer.on(.error(error)) return Disposables.create() } } } /** Creates an observable of the `Request`. - parameter method: Alamofire method object - parameter url: An object adopting `URLConvertible` - parameter parameters: A dictionary containing all necessary options - parameter encoding: The kind of encoding used to process parameters - parameter header: A dictionary containing all the additional headers - returns: An observable of the `Request` */ public func request(_ method: Alamofire.HTTPMethod, _ url: URLConvertible, parameters: [String: Any]? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: [String: String]? = nil) -> Observable<DataRequest> { return request { manager in manager.request(url, method: method, parameters: parameters, encoding: encoding, headers: headers) } } /** Creates an observable of the `Request`. - parameter URLRequest: An object adopting `URLRequestConvertible` - parameter parameters: A dictionary containing all necessary options - parameter encoding: The kind of encoding used to process parameters - parameter header: A dictionary containing all the additional headers - returns: An observable of the `Request` */ public func request(urlRequest: URLRequestConvertible) -> Observable<DataRequest> { return request { manager in manager.request(urlRequest) } } // MARK: data /** Creates an observable of the data. - parameter url: An object adopting `URLConvertible` - parameter parameters: A dictionary containing all necessary options - parameter encoding: The kind of encoding used to process parameters - parameter header: A dictionary containing all the additional headers - returns: An observable of the tuple `(NSHTTPURLResponse, NSData)` */ public func responseData(_ method: Alamofire.HTTPMethod, _ url: URLConvertible, parameters: [String: Any]? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: [String: String]? = nil) -> Observable<(HTTPURLResponse, Data)> { return request(method, url, parameters: parameters, encoding: encoding, headers: headers).flatMap { $0.rx.responseData() } } /** Creates an observable of the data. - parameter URLRequest: An object adopting `URLRequestConvertible` - parameter parameters: A dictionary containing all necessary options - parameter encoding: The kind of encoding used to process parameters - parameter header: A dictionary containing all the additional headers - returns: An observable of `NSData` */ public func data(_ method: Alamofire.HTTPMethod, _ url: URLConvertible, parameters: [String: Any]? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: [String: String]? = nil) -> Observable<Data> { return request(method, url, parameters: parameters, encoding: encoding, headers: headers).flatMap { $0.rx.data() } } // MARK: string /** Creates an observable of the tuple `(NSHTTPURLResponse, String)`. - parameter url: An object adopting `URLRequestConvertible` - parameter parameters: A dictionary containing all necessary options - parameter encoding: The kind of encoding used to process parameters - parameter header: A dictionary containing all the additional headers - returns: An observable of the tuple `(NSHTTPURLResponse, String)` */ public func responseString(_ method: Alamofire.HTTPMethod, _ url: URLConvertible, parameters: [String: Any]? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: [String: String]? = nil) -> Observable<(HTTPURLResponse, String)> { return request(method, url, parameters: parameters, encoding: encoding, headers: headers).flatMap { $0.rx.responseString() } } /** Creates an observable of the data encoded as String. - parameter url: An object adopting `URLConvertible` - parameter parameters: A dictionary containing all necessary options - parameter encoding: The kind of encoding used to process parameters - parameter header: A dictionary containing all the additional headers - returns: An observable of `String` */ public func string(_ method: Alamofire.HTTPMethod, _ url: URLConvertible, parameters: [String: Any]? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: [String: String]? = nil) -> Observable<String> { return request(method, url, parameters: parameters, encoding: encoding, headers: headers) .flatMap { (request) -> Observable<String> in request.rx.string() } } // MARK: JSON /** Creates an observable of the data decoded from JSON and processed as tuple `(NSHTTPURLResponse, AnyObject)`. - parameter url: An object adopting `URLRequestConvertible` - parameter parameters: A dictionary containing all necessary options - parameter encoding: The kind of encoding used to process parameters - parameter header: A dictionary containing all the additional headers - returns: An observable of the tuple `(NSHTTPURLResponse, AnyObject)` */ public func responseJSON(_ method: Alamofire.HTTPMethod, _ url: URLConvertible, parameters: [String: Any]? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: [String: String]? = nil) -> Observable<(HTTPURLResponse, Any)> { return request(method, url, parameters: parameters, encoding: encoding, headers: headers).flatMap { $0.rx.responseJSON() } } /** Creates an observable of the data decoded from JSON and processed as `AnyObject`. - parameter URLRequest: An object adopting `URLRequestConvertible` - parameter parameters: A dictionary containing all necessary options - parameter encoding: The kind of encoding used to process parameters - parameter header: A dictionary containing all the additional headers - returns: An observable of `AnyObject` */ public func json(_ method: Alamofire.HTTPMethod, _ url: URLConvertible, parameters: [String: Any]? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: [String: String]? = nil) -> Observable<Any> { return request(method, url, parameters: parameters, encoding: encoding, headers: headers).flatMap { $0.rx.json() } } // MARK: Upload /** Returns an observable of a request using the shared manager instance to upload a specific file to a specified URL. The request is started immediately. - parameter urlRequest: The request object to start the upload. - paramenter file: An instance of NSURL holding the information of the local file. - returns: The observable of `AnyObject` for the created request. */ public func upload(_ file: URL, urlRequest: URLRequestConvertible) -> Observable<UploadRequest> { return request { manager in manager.upload(file, with: urlRequest) } } /** Returns an observable of a request using the shared manager instance to upload any data to a specified URL. The request is started immediately. - parameter urlRequest: The request object to start the upload. - paramenter data: An instance of Data holdint the data to upload. - returns: The observable of `UploadRequest` for the created request. */ public func upload(_ data: Data, urlRequest: URLRequestConvertible) -> Observable<UploadRequest> { return request { manager in manager.upload(data, with: urlRequest) } } /** Returns an observable of a request using the shared manager instance to upload any stream to a specified URL. The request is started immediately. - parameter urlRequest: The request object to start the upload. - paramenter stream: The stream to upload. - returns: The observable of `(NSData?, RxProgress)` for the created upload request. */ public func upload(_ stream: InputStream, urlRequest: URLRequestConvertible) -> Observable<UploadRequest> { return request { manager in manager.upload(stream, with: urlRequest) } } // MARK: Download /** Creates a download request using the shared manager instance for the specified URL request. - parameter urlRequest: The URL request. - parameter destination: The closure used to determine the destination of the downloaded file. - returns: The observable of `(NSData?, RxProgress)` for the created download request. */ public func download(_ urlRequest: URLRequestConvertible, to destination: @escaping DownloadRequest.DownloadFileDestination) -> Observable<DownloadRequest> { return request { manager in manager.download(urlRequest, to: destination) } } /** Creates a request using the shared manager instance for downloading with a resume data produced from a previous request cancellation. - parameter resumeData: The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask` when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional information. - parameter destination: The closure used to determine the destination of the downloaded file. - returns: The observable of `(NSData?, RxProgress)` for the created download request. */ public func download(resumeData: Data, to destination: @escaping DownloadRequest.DownloadFileDestination) -> Observable<DownloadRequest> { return request { manager in manager.download(resumingWith: resumeData, to: destination) } } } // MARK: Request - Common Response Handlers extension ObservableType where Element == DataRequest { public func responseJSON() -> Observable<DataResponse<Any>> { return flatMap { $0.rx.responseJSON() } } public func json(options: JSONSerialization.ReadingOptions = .allowFragments) -> Observable<Any> { return flatMap { $0.rx.json(options: options) } } public func responseString(encoding: String.Encoding? = nil) -> Observable<(HTTPURLResponse, String)> { return flatMap { $0.rx.responseString(encoding: encoding) } } public func string(encoding: String.Encoding? = nil) -> Observable<String> { return flatMap { $0.rx.string(encoding: encoding) } } public func responseData() -> Observable<(HTTPURLResponse, Data)> { return flatMap { $0.rx.responseData() } } public func data() -> Observable<Data> { return flatMap { $0.rx.data() } } public func responsePropertyList(options: PropertyListSerialization.ReadOptions = PropertyListSerialization.ReadOptions()) -> Observable<(HTTPURLResponse, Any)> { return flatMap { $0.rx.responsePropertyList(options: options) } } public func propertyList(options: PropertyListSerialization.ReadOptions = PropertyListSerialization.ReadOptions()) -> Observable<Any> { return flatMap { $0.rx.propertyList(options: options) } } public func progress() -> Observable<RxProgress> { return flatMap { $0.rx.progress() } } } // MARK: Request - Validation extension ObservableType where Element == DataRequest { public func validate<S: Sequence>(statusCode: S) -> Observable<Element> where S.Element == Int { return map { $0.validate(statusCode: statusCode) } } public func validate() -> Observable<Element> { return map { $0.validate() } } public func validate<S: Sequence>(contentType acceptableContentTypes: S) -> Observable<Element> where S.Iterator.Element == String { return map { $0.validate(contentType: acceptableContentTypes) } } public func validate(_ validation: @escaping DataRequest.Validation) -> Observable<Element> { return map { $0.validate(validation) } } } extension Request: ReactiveCompatible {} extension Reactive where Base: DataRequest { // MARK: Defaults /// - returns: A validated request based on the status code func validateSuccessfulResponse() -> DataRequest { return base.validate(statusCode: 200..<300) } /** Transform a request into an observable of the response and serialized object. - parameter queue: The dispatch queue to use. - parameter responseSerializer: The the serializer. - returns: The observable of `(NSHTTPURLResponse, T.SerializedObject)` for the created download request. */ public func responseResult<T: DataResponseSerializerProtocol>(queue: DispatchQueue? = nil, responseSerializer: T) -> Observable<(HTTPURLResponse, T.SerializedObject)> { return Observable.create { observer in let dataRequest = self.base .response(queue: queue, responseSerializer: responseSerializer) { (packedResponse) -> Void in switch packedResponse.result { case let .success(result): if let httpResponse = packedResponse.response { observer.on(.next((httpResponse, result))) observer.on(.completed) } else { observer.on(.error(RxAlamofireUnknownError)) } case let .failure(error): observer.on(.error(error as Error)) } } return Disposables.create { dataRequest.cancel() } } } public func responseJSON() -> Observable<DataResponse<Any>> { return Observable.create { observer in let request = self.base request.responseJSON { response in if let error = response.result.error { observer.on(.error(error)) } else { observer.on(.next(response)) observer.on(.completed) } } return Disposables.create { request.cancel() } } } /** Transform a request into an observable of the serialized object. - parameter queue: The dispatch queue to use. - parameter responseSerializer: The the serializer. - returns: The observable of `T.SerializedObject` for the created download request. */ public func result<T: DataResponseSerializerProtocol>(queue: DispatchQueue? = nil, responseSerializer: T) -> Observable<T.SerializedObject> { return Observable.create { observer in let dataRequest = self.validateSuccessfulResponse() .response(queue: queue, responseSerializer: responseSerializer) { (packedResponse) -> Void in switch packedResponse.result { case let .success(result): if let _ = packedResponse.response { observer.on(.next(result)) observer.on(.completed) } else { observer.on(.error(RxAlamofireUnknownError)) } case let .failure(error): observer.on(.error(error as Error)) } } return Disposables.create { dataRequest.cancel() } } } /** Returns an `Observable` of NSData for the current request. - parameter cancelOnDispose: Indicates if the request has to be canceled when the observer is disposed, **default:** `false` - returns: An instance of `Observable<NSData>` */ public func responseData() -> Observable<(HTTPURLResponse, Data)> { return responseResult(responseSerializer: DataRequest.dataResponseSerializer()) } public func data() -> Observable<Data> { return result(responseSerializer: DataRequest.dataResponseSerializer()) } /** Returns an `Observable` of a String for the current request - parameter encoding: Type of the string encoding, **default:** `nil` - returns: An instance of `Observable<String>` */ public func responseString(encoding: String.Encoding? = nil) -> Observable<(HTTPURLResponse, String)> { return responseResult(responseSerializer: Base.stringResponseSerializer(encoding: encoding)) } public func string(encoding: String.Encoding? = nil) -> Observable<String> { return result(responseSerializer: Base.stringResponseSerializer(encoding: encoding)) } /** Returns an `Observable` of a serialized JSON for the current request. - parameter options: Reading options for JSON decoding process, **default:** `.AllowFragments` - returns: An instance of `Observable<AnyObject>` */ public func responseJSON(options: JSONSerialization.ReadingOptions = .allowFragments) -> Observable<(HTTPURLResponse, Any)> { return responseResult(responseSerializer: Base.jsonResponseSerializer(options: options)) } /** Returns an `Observable` of a serialized JSON for the current request. - parameter options: Reading options for JSON decoding process, **default:** `.AllowFragments` - returns: An instance of `Observable<AnyObject>` */ public func json(options: JSONSerialization.ReadingOptions = .allowFragments) -> Observable<Any> { return result(responseSerializer: Base.jsonResponseSerializer(options: options)) } /** Returns and `Observable` of a serialized property list for the current request. - parameter options: Property list reading options, **default:** `NSPropertyListReadOptions()` - returns: An instance of `Observable<AnyData>` */ public func responsePropertyList(options: PropertyListSerialization.ReadOptions = PropertyListSerialization.ReadOptions()) -> Observable<(HTTPURLResponse, Any)> { return responseResult(responseSerializer: Base.propertyListResponseSerializer(options: options)) } public func propertyList(options: PropertyListSerialization.ReadOptions = PropertyListSerialization.ReadOptions()) -> Observable<Any> { return result(responseSerializer: Base.propertyListResponseSerializer(options: options)) } } extension Reactive where Base: Request { // MARK: Request - Upload and download progress /** Returns an `Observable` for the current progress status. Parameters on observed tuple: 1. bytes written so far. 1. total bytes to write. - returns: An instance of `Observable<RxProgress>` */ public func progress() -> Observable<RxProgress> { return Observable.create { observer in let handler: Request.ProgressHandler = { progress in let rxProgress = RxProgress(bytesWritten: progress.completedUnitCount, totalBytes: progress.totalUnitCount) observer.on(.next(rxProgress)) if rxProgress.bytesWritten >= rxProgress.totalBytes { observer.on(.completed) } } // Try in following order: // - UploadRequest (Inherits from DataRequest, so we test the discrete case first) // - DownloadRequest // - DataRequest if let uploadReq = self.base as? UploadRequest { uploadReq.uploadProgress(closure: handler) } else if let downloadReq = self.base as? DownloadRequest { downloadReq.downloadProgress(closure: handler) } else if let dataReq = self.base as? DataRequest { dataReq.downloadProgress(closure: handler) } return Disposables.create() } // warm up a bit :) .startWith(RxProgress(bytesWritten: 0, totalBytes: 0)) } } // MARK: RxProgress public struct RxProgress { public let bytesWritten: Int64 public let totalBytes: Int64 public init(bytesWritten: Int64, totalBytes: Int64) { self.bytesWritten = bytesWritten self.totalBytes = totalBytes } } extension RxProgress { public var bytesRemaining: Int64 { return totalBytes - bytesWritten } public var completed: Float { if totalBytes > 0 { return Float(bytesWritten) / Float(totalBytes) } else { return 0 } } } extension RxProgress: Equatable {} public func ==(lhs: RxProgress, rhs: RxProgress) -> Bool { return lhs.bytesWritten == rhs.bytesWritten && lhs.totalBytes == rhs.totalBytes }
mit
f85a207d249c99eba01d52a29a90efc2
36.191207
164
0.661535
5.227508
false
false
false
false
autentia/planning-poker-ios
Views/QuestionView/QuestionViewController.swift
1
1939
// // QuestionViewController.swift // AutentiaScrumCards // // Created by Anton Zuev on 29/01/2019. // import UIKit class QuestionViewController: UIViewController { @IBOutlet weak var questionLabel: UILabel! @IBOutlet weak var shirtSizesButton: UIButton! @IBOutlet weak var fibonacciButton: UIButton! var mainFrame: MainFrameProtocol! override func viewDidLoad() { super.viewDidLoad() self.questionLabel.text = "EstimationQuestion".localized self.shirtSizesButton.setTitle("ShirtSizes".localized, for: UIControl.State.normal) self.fibonacciButton.setTitle("Fibonacci".localized, for: UIControl.State.normal) mainFrame = MainFrame() } override func viewWillAppear(_ animated: Bool) { let navigationBar = self.navigationController?.navigationBar //remove one pixel line in the navigation bar navigationBar?.setBackgroundImage(UIImage(), for: UIBarPosition.any, barMetrics: UIBarMetrics.default) navigationBar?.shadowImage = UIImage() //customize navigation item self.navigationItem.title = "Title".localized self.navigationItem.backBarButtonItem?.title = "Menu".localized self.navigationItem.backBarButtonItem?.setTitleTextAttributes([NSAttributedString.Key.font: UIFont(name: "Montserrat-SemiBold", size: 18)!], for: UIControl.State.normal) } override func viewWillDisappear(_ animated: Bool) { //self.navigationController?.isNavigationBarHidden = false //Show } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. mainFrame.showCardsViewController(for: segue) } }
gpl-3.0
1d50140a2e53c82bc12026f5d185896b
37.78
177
0.711191
4.971795
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/RDSDataService/RDSDataService_Shapes.swift
1
30571
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import Foundation import SotoCore extension RDSDataService { // MARK: Enums public enum DecimalReturnType: String, CustomStringConvertible, Codable { case doubleOrLong = "DOUBLE_OR_LONG" case string = "STRING" public var description: String { return self.rawValue } } public enum TypeHint: String, CustomStringConvertible, Codable { case date = "DATE" case decimal = "DECIMAL" case time = "TIME" case timestamp = "TIMESTAMP" public var description: String { return self.rawValue } } // MARK: Shapes public class ArrayValue: AWSEncodableShape & AWSDecodableShape { /// An array of arrays. public let arrayValues: [ArrayValue]? /// An array of Boolean values. public let booleanValues: [Bool]? /// An array of integers. public let doubleValues: [Double]? /// An array of floating point numbers. public let longValues: [Int64]? /// An array of strings. public let stringValues: [String]? public init(arrayValues: [ArrayValue]? = nil, booleanValues: [Bool]? = nil, doubleValues: [Double]? = nil, longValues: [Int64]? = nil, stringValues: [String]? = nil) { self.arrayValues = arrayValues self.booleanValues = booleanValues self.doubleValues = doubleValues self.longValues = longValues self.stringValues = stringValues } private enum CodingKeys: String, CodingKey { case arrayValues case booleanValues case doubleValues case longValues case stringValues } } public struct BatchExecuteStatementRequest: AWSEncodableShape { /// The name of the database. public let database: String? /// The parameter set for the batch operation. The SQL statement is executed as many times as the number of parameter sets provided. To execute a SQL statement with no parameters, use one of the following options: Specify one or more empty parameter sets. Use the ExecuteStatement operation instead of the BatchExecuteStatement operation. Array parameters are not supported. public let parameterSets: [[SqlParameter]]? /// The Amazon Resource Name (ARN) of the Aurora Serverless DB cluster. public let resourceArn: String /// The name of the database schema. public let schema: String? /// The name or ARN of the secret that enables access to the DB cluster. public let secretArn: String /// The SQL statement to run. public let sql: String /// The identifier of a transaction that was started by using the BeginTransaction operation. Specify the transaction ID of the transaction that you want to include the SQL statement in. If the SQL statement is not part of a transaction, don't set this parameter. public let transactionId: String? public init(database: String? = nil, parameterSets: [[SqlParameter]]? = nil, resourceArn: String, schema: String? = nil, secretArn: String, sql: String, transactionId: String? = nil) { self.database = database self.parameterSets = parameterSets self.resourceArn = resourceArn self.schema = schema self.secretArn = secretArn self.sql = sql self.transactionId = transactionId } public func validate(name: String) throws { try self.validate(self.database, name: "database", parent: name, max: 64) try self.validate(self.database, name: "database", parent: name, min: 0) try self.validate(self.resourceArn, name: "resourceArn", parent: name, max: 100) try self.validate(self.resourceArn, name: "resourceArn", parent: name, min: 11) try self.validate(self.schema, name: "schema", parent: name, max: 64) try self.validate(self.schema, name: "schema", parent: name, min: 0) try self.validate(self.secretArn, name: "secretArn", parent: name, max: 100) try self.validate(self.secretArn, name: "secretArn", parent: name, min: 11) try self.validate(self.sql, name: "sql", parent: name, max: 65536) try self.validate(self.sql, name: "sql", parent: name, min: 0) try self.validate(self.transactionId, name: "transactionId", parent: name, max: 192) try self.validate(self.transactionId, name: "transactionId", parent: name, min: 0) } private enum CodingKeys: String, CodingKey { case database case parameterSets case resourceArn case schema case secretArn case sql case transactionId } } public struct BatchExecuteStatementResponse: AWSDecodableShape { /// The execution results of each batch entry. public let updateResults: [UpdateResult]? public init(updateResults: [UpdateResult]? = nil) { self.updateResults = updateResults } private enum CodingKeys: String, CodingKey { case updateResults } } public struct BeginTransactionRequest: AWSEncodableShape { /// The name of the database. public let database: String? /// The Amazon Resource Name (ARN) of the Aurora Serverless DB cluster. public let resourceArn: String /// The name of the database schema. public let schema: String? /// The name or ARN of the secret that enables access to the DB cluster. public let secretArn: String public init(database: String? = nil, resourceArn: String, schema: String? = nil, secretArn: String) { self.database = database self.resourceArn = resourceArn self.schema = schema self.secretArn = secretArn } public func validate(name: String) throws { try self.validate(self.database, name: "database", parent: name, max: 64) try self.validate(self.database, name: "database", parent: name, min: 0) try self.validate(self.resourceArn, name: "resourceArn", parent: name, max: 100) try self.validate(self.resourceArn, name: "resourceArn", parent: name, min: 11) try self.validate(self.schema, name: "schema", parent: name, max: 64) try self.validate(self.schema, name: "schema", parent: name, min: 0) try self.validate(self.secretArn, name: "secretArn", parent: name, max: 100) try self.validate(self.secretArn, name: "secretArn", parent: name, min: 11) } private enum CodingKeys: String, CodingKey { case database case resourceArn case schema case secretArn } } public struct BeginTransactionResponse: AWSDecodableShape { /// The transaction ID of the transaction started by the call. public let transactionId: String? public init(transactionId: String? = nil) { self.transactionId = transactionId } private enum CodingKeys: String, CodingKey { case transactionId } } public struct ColumnMetadata: AWSDecodableShape { /// The type of the column. public let arrayBaseColumnType: Int? /// A value that indicates whether the column increments automatically. public let isAutoIncrement: Bool? /// A value that indicates whether the column is case-sensitive. public let isCaseSensitive: Bool? /// A value that indicates whether the column contains currency values. public let isCurrency: Bool? /// A value that indicates whether an integer column is signed. public let isSigned: Bool? /// The label for the column. public let label: String? /// The name of the column. public let name: String? /// A value that indicates whether the column is nullable. public let nullable: Int? /// The precision value of a decimal number column. public let precision: Int? /// The scale value of a decimal number column. public let scale: Int? /// The name of the schema that owns the table that includes the column. public let schemaName: String? /// The name of the table that includes the column. public let tableName: String? /// The type of the column. public let type: Int? /// The database-specific data type of the column. public let typeName: String? public init(arrayBaseColumnType: Int? = nil, isAutoIncrement: Bool? = nil, isCaseSensitive: Bool? = nil, isCurrency: Bool? = nil, isSigned: Bool? = nil, label: String? = nil, name: String? = nil, nullable: Int? = nil, precision: Int? = nil, scale: Int? = nil, schemaName: String? = nil, tableName: String? = nil, type: Int? = nil, typeName: String? = nil) { self.arrayBaseColumnType = arrayBaseColumnType self.isAutoIncrement = isAutoIncrement self.isCaseSensitive = isCaseSensitive self.isCurrency = isCurrency self.isSigned = isSigned self.label = label self.name = name self.nullable = nullable self.precision = precision self.scale = scale self.schemaName = schemaName self.tableName = tableName self.type = type self.typeName = typeName } private enum CodingKeys: String, CodingKey { case arrayBaseColumnType case isAutoIncrement case isCaseSensitive case isCurrency case isSigned case label case name case nullable case precision case scale case schemaName case tableName case type case typeName } } public struct CommitTransactionRequest: AWSEncodableShape { /// The Amazon Resource Name (ARN) of the Aurora Serverless DB cluster. public let resourceArn: String /// The name or ARN of the secret that enables access to the DB cluster. public let secretArn: String /// The identifier of the transaction to end and commit. public let transactionId: String public init(resourceArn: String, secretArn: String, transactionId: String) { self.resourceArn = resourceArn self.secretArn = secretArn self.transactionId = transactionId } public func validate(name: String) throws { try self.validate(self.resourceArn, name: "resourceArn", parent: name, max: 100) try self.validate(self.resourceArn, name: "resourceArn", parent: name, min: 11) try self.validate(self.secretArn, name: "secretArn", parent: name, max: 100) try self.validate(self.secretArn, name: "secretArn", parent: name, min: 11) try self.validate(self.transactionId, name: "transactionId", parent: name, max: 192) try self.validate(self.transactionId, name: "transactionId", parent: name, min: 0) } private enum CodingKeys: String, CodingKey { case resourceArn case secretArn case transactionId } } public struct CommitTransactionResponse: AWSDecodableShape { /// The status of the commit operation. public let transactionStatus: String? public init(transactionStatus: String? = nil) { self.transactionStatus = transactionStatus } private enum CodingKeys: String, CodingKey { case transactionStatus } } public struct ExecuteSqlRequest: AWSEncodableShape { /// The Amazon Resource Name (ARN) of the secret that enables access to the DB cluster. public let awsSecretStoreArn: String /// The name of the database. public let database: String? /// The ARN of the Aurora Serverless DB cluster. public let dbClusterOrInstanceArn: String /// The name of the database schema. public let schema: String? /// One or more SQL statements to run on the DB cluster. You can separate SQL statements from each other with a semicolon (;). Any valid SQL statement is permitted, including data definition, data manipulation, and commit statements. public let sqlStatements: String public init(awsSecretStoreArn: String, database: String? = nil, dbClusterOrInstanceArn: String, schema: String? = nil, sqlStatements: String) { self.awsSecretStoreArn = awsSecretStoreArn self.database = database self.dbClusterOrInstanceArn = dbClusterOrInstanceArn self.schema = schema self.sqlStatements = sqlStatements } public func validate(name: String) throws { try self.validate(self.awsSecretStoreArn, name: "awsSecretStoreArn", parent: name, max: 100) try self.validate(self.awsSecretStoreArn, name: "awsSecretStoreArn", parent: name, min: 11) try self.validate(self.database, name: "database", parent: name, max: 64) try self.validate(self.database, name: "database", parent: name, min: 0) try self.validate(self.dbClusterOrInstanceArn, name: "dbClusterOrInstanceArn", parent: name, max: 100) try self.validate(self.dbClusterOrInstanceArn, name: "dbClusterOrInstanceArn", parent: name, min: 11) try self.validate(self.schema, name: "schema", parent: name, max: 64) try self.validate(self.schema, name: "schema", parent: name, min: 0) try self.validate(self.sqlStatements, name: "sqlStatements", parent: name, max: 65536) try self.validate(self.sqlStatements, name: "sqlStatements", parent: name, min: 0) } private enum CodingKeys: String, CodingKey { case awsSecretStoreArn case database case dbClusterOrInstanceArn case schema case sqlStatements } } public struct ExecuteSqlResponse: AWSDecodableShape { /// The results of the SQL statement or statements. public let sqlStatementResults: [SqlStatementResult]? public init(sqlStatementResults: [SqlStatementResult]? = nil) { self.sqlStatementResults = sqlStatementResults } private enum CodingKeys: String, CodingKey { case sqlStatementResults } } public struct ExecuteStatementRequest: AWSEncodableShape { /// A value that indicates whether to continue running the statement after the call times out. By default, the statement stops running when the call times out. For DDL statements, we recommend continuing to run the statement after the call times out. When a DDL statement terminates before it is finished running, it can result in errors and possibly corrupted data structures. public let continueAfterTimeout: Bool? /// The name of the database. public let database: String? /// A value that indicates whether to include metadata in the results. public let includeResultMetadata: Bool? /// The parameters for the SQL statement. Array parameters are not supported. public let parameters: [SqlParameter]? /// The Amazon Resource Name (ARN) of the Aurora Serverless DB cluster. public let resourceArn: String /// Options that control how the result set is returned. public let resultSetOptions: ResultSetOptions? /// The name of the database schema. public let schema: String? /// The name or ARN of the secret that enables access to the DB cluster. public let secretArn: String /// The SQL statement to run. public let sql: String /// The identifier of a transaction that was started by using the BeginTransaction operation. Specify the transaction ID of the transaction that you want to include the SQL statement in. If the SQL statement is not part of a transaction, don't set this parameter. public let transactionId: String? public init(continueAfterTimeout: Bool? = nil, database: String? = nil, includeResultMetadata: Bool? = nil, parameters: [SqlParameter]? = nil, resourceArn: String, resultSetOptions: ResultSetOptions? = nil, schema: String? = nil, secretArn: String, sql: String, transactionId: String? = nil) { self.continueAfterTimeout = continueAfterTimeout self.database = database self.includeResultMetadata = includeResultMetadata self.parameters = parameters self.resourceArn = resourceArn self.resultSetOptions = resultSetOptions self.schema = schema self.secretArn = secretArn self.sql = sql self.transactionId = transactionId } public func validate(name: String) throws { try self.validate(self.database, name: "database", parent: name, max: 64) try self.validate(self.database, name: "database", parent: name, min: 0) try self.validate(self.resourceArn, name: "resourceArn", parent: name, max: 100) try self.validate(self.resourceArn, name: "resourceArn", parent: name, min: 11) try self.validate(self.schema, name: "schema", parent: name, max: 64) try self.validate(self.schema, name: "schema", parent: name, min: 0) try self.validate(self.secretArn, name: "secretArn", parent: name, max: 100) try self.validate(self.secretArn, name: "secretArn", parent: name, min: 11) try self.validate(self.sql, name: "sql", parent: name, max: 65536) try self.validate(self.sql, name: "sql", parent: name, min: 0) try self.validate(self.transactionId, name: "transactionId", parent: name, max: 192) try self.validate(self.transactionId, name: "transactionId", parent: name, min: 0) } private enum CodingKeys: String, CodingKey { case continueAfterTimeout case database case includeResultMetadata case parameters case resourceArn case resultSetOptions case schema case secretArn case sql case transactionId } } public struct ExecuteStatementResponse: AWSDecodableShape { /// Metadata for the columns included in the results. public let columnMetadata: [ColumnMetadata]? /// Values for fields generated during the request. &lt;note&gt; &lt;p&gt;The &lt;code&gt;generatedFields&lt;/code&gt; data isn't supported by Aurora PostgreSQL. To get the values of generated fields, use the &lt;code&gt;RETURNING&lt;/code&gt; clause. For more information, see &lt;a href=&quot;https://www.postgresql.org/docs/10/dml-returning.html&quot;&gt;Returning Data From Modified Rows&lt;/a&gt; in the PostgreSQL documentation.&lt;/p&gt; &lt;/note&gt; public let generatedFields: [Field]? /// The number of records updated by the request. public let numberOfRecordsUpdated: Int64? /// The records returned by the SQL statement. public let records: [[Field]]? public init(columnMetadata: [ColumnMetadata]? = nil, generatedFields: [Field]? = nil, numberOfRecordsUpdated: Int64? = nil, records: [[Field]]? = nil) { self.columnMetadata = columnMetadata self.generatedFields = generatedFields self.numberOfRecordsUpdated = numberOfRecordsUpdated self.records = records } private enum CodingKeys: String, CodingKey { case columnMetadata case generatedFields case numberOfRecordsUpdated case records } } public struct Field: AWSEncodableShape & AWSDecodableShape { /// An array of values. public let arrayValue: ArrayValue? /// A value of BLOB data type. public let blobValue: Data? /// A value of Boolean data type. public let booleanValue: Bool? /// A value of double data type. public let doubleValue: Double? /// A NULL value. public let isNull: Bool? /// A value of long data type. public let longValue: Int64? /// A value of string data type. public let stringValue: String? public init(arrayValue: ArrayValue? = nil, blobValue: Data? = nil, booleanValue: Bool? = nil, doubleValue: Double? = nil, isNull: Bool? = nil, longValue: Int64? = nil, stringValue: String? = nil) { self.arrayValue = arrayValue self.blobValue = blobValue self.booleanValue = booleanValue self.doubleValue = doubleValue self.isNull = isNull self.longValue = longValue self.stringValue = stringValue } private enum CodingKeys: String, CodingKey { case arrayValue case blobValue case booleanValue case doubleValue case isNull case longValue case stringValue } } public struct Record: AWSDecodableShape { /// The values returned in the record. public let values: [Value]? public init(values: [Value]? = nil) { self.values = values } private enum CodingKeys: String, CodingKey { case values } } public struct ResultFrame: AWSDecodableShape { /// The records in the result set. public let records: [Record]? /// The result-set metadata in the result set. public let resultSetMetadata: ResultSetMetadata? public init(records: [Record]? = nil, resultSetMetadata: ResultSetMetadata? = nil) { self.records = records self.resultSetMetadata = resultSetMetadata } private enum CodingKeys: String, CodingKey { case records case resultSetMetadata } } public struct ResultSetMetadata: AWSDecodableShape { /// The number of columns in the result set. public let columnCount: Int64? /// The metadata of the columns in the result set. public let columnMetadata: [ColumnMetadata]? public init(columnCount: Int64? = nil, columnMetadata: [ColumnMetadata]? = nil) { self.columnCount = columnCount self.columnMetadata = columnMetadata } private enum CodingKeys: String, CodingKey { case columnCount case columnMetadata } } public struct ResultSetOptions: AWSEncodableShape { /// A value that indicates how a field of DECIMAL type is represented in the response. The value of STRING, the default, specifies that it is converted to a String value. The value of DOUBLE_OR_LONG specifies that it is converted to a Long value if its scale is 0, or to a Double value otherwise. Conversion to Double or Long can result in roundoff errors due to precision loss. We recommend converting to String, especially when working with currency values. public let decimalReturnType: DecimalReturnType? public init(decimalReturnType: DecimalReturnType? = nil) { self.decimalReturnType = decimalReturnType } private enum CodingKeys: String, CodingKey { case decimalReturnType } } public struct RollbackTransactionRequest: AWSEncodableShape { /// The Amazon Resource Name (ARN) of the Aurora Serverless DB cluster. public let resourceArn: String /// The name or ARN of the secret that enables access to the DB cluster. public let secretArn: String /// The identifier of the transaction to roll back. public let transactionId: String public init(resourceArn: String, secretArn: String, transactionId: String) { self.resourceArn = resourceArn self.secretArn = secretArn self.transactionId = transactionId } public func validate(name: String) throws { try self.validate(self.resourceArn, name: "resourceArn", parent: name, max: 100) try self.validate(self.resourceArn, name: "resourceArn", parent: name, min: 11) try self.validate(self.secretArn, name: "secretArn", parent: name, max: 100) try self.validate(self.secretArn, name: "secretArn", parent: name, min: 11) try self.validate(self.transactionId, name: "transactionId", parent: name, max: 192) try self.validate(self.transactionId, name: "transactionId", parent: name, min: 0) } private enum CodingKeys: String, CodingKey { case resourceArn case secretArn case transactionId } } public struct RollbackTransactionResponse: AWSDecodableShape { /// The status of the rollback operation. public let transactionStatus: String? public init(transactionStatus: String? = nil) { self.transactionStatus = transactionStatus } private enum CodingKeys: String, CodingKey { case transactionStatus } } public struct SqlParameter: AWSEncodableShape { /// The name of the parameter. public let name: String? /// A hint that specifies the correct object type for data type mapping. Values: DECIMAL - The corresponding String parameter value is sent as an object of DECIMAL type to the database. TIMESTAMP - The corresponding String parameter value is sent as an object of TIMESTAMP type to the database. The accepted format is YYYY-MM-DD HH:MM:SS[.FFF]. TIME - The corresponding String parameter value is sent as an object of TIME type to the database. The accepted format is HH:MM:SS[.FFF]. DATE - The corresponding String parameter value is sent as an object of DATE type to the database. The accepted format is YYYY-MM-DD. public let typeHint: TypeHint? /// The value of the parameter. public let value: Field? public init(name: String? = nil, typeHint: TypeHint? = nil, value: Field? = nil) { self.name = name self.typeHint = typeHint self.value = value } private enum CodingKeys: String, CodingKey { case name case typeHint case value } } public struct SqlStatementResult: AWSDecodableShape { /// The number of records updated by a SQL statement. public let numberOfRecordsUpdated: Int64? /// The result set of the SQL statement. public let resultFrame: ResultFrame? public init(numberOfRecordsUpdated: Int64? = nil, resultFrame: ResultFrame? = nil) { self.numberOfRecordsUpdated = numberOfRecordsUpdated self.resultFrame = resultFrame } private enum CodingKeys: String, CodingKey { case numberOfRecordsUpdated case resultFrame } } public struct StructValue: AWSDecodableShape { /// The attributes returned in the record. public let attributes: [Value]? public init(attributes: [Value]? = nil) { self.attributes = attributes } private enum CodingKeys: String, CodingKey { case attributes } } public struct UpdateResult: AWSDecodableShape { /// Values for fields generated during the request. public let generatedFields: [Field]? public init(generatedFields: [Field]? = nil) { self.generatedFields = generatedFields } private enum CodingKeys: String, CodingKey { case generatedFields } } public class Value: AWSDecodableShape { /// An array of column values. public let arrayValues: [Value]? /// A value for a column of big integer data type. public let bigIntValue: Int64? /// A value for a column of BIT data type. public let bitValue: Bool? /// A value for a column of BLOB data type. public let blobValue: Data? /// A value for a column of double data type. public let doubleValue: Double? /// A value for a column of integer data type. public let intValue: Int? /// A NULL value. public let isNull: Bool? /// A value for a column of real data type. public let realValue: Float? /// A value for a column of string data type. public let stringValue: String? /// A value for a column of STRUCT data type. public let structValue: StructValue? public init(arrayValues: [Value]? = nil, bigIntValue: Int64? = nil, bitValue: Bool? = nil, blobValue: Data? = nil, doubleValue: Double? = nil, intValue: Int? = nil, isNull: Bool? = nil, realValue: Float? = nil, stringValue: String? = nil, structValue: StructValue? = nil) { self.arrayValues = arrayValues self.bigIntValue = bigIntValue self.bitValue = bitValue self.blobValue = blobValue self.doubleValue = doubleValue self.intValue = intValue self.isNull = isNull self.realValue = realValue self.stringValue = stringValue self.structValue = structValue } private enum CodingKeys: String, CodingKey { case arrayValues case bigIntValue case bitValue case blobValue case doubleValue case intValue case isNull case realValue case stringValue case structValue } } }
apache-2.0
b38196c3ea3eddcef23040c698a8efd7
43.56414
638
0.631906
4.900769
false
false
false
false
forgo/BabySync
bbsync/mobile/iOS/Baby Sync/Baby Sync/SelectIconViewController.swift
1
3869
// // SelectIconViewController.swift // Baby Sync // // Created by Elliott Richerson on 10/4/15. // Copyright ยฉ 2015 Elliott Richerson. All rights reserved. // import UIKit class SelectIconViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate { var iconAssets: [String] = ["Air Balloon","Angel","Apple","Baby Monitor","Ball","Balloon","Bathtub","Bear","Bee","Bib","Bird","Boat","Bottle","Boy","Butterfly","Button","Cake","Candy","Car","Castle","Cat","Cherries","Chick","Clown","Cow","Crab","Cutlery","Diaper Pin","Diaper","Dice","Dog","Doll","Doughnut","Duck","Elephant","Feet","Fish","Flower","Food","Frog","Gift Tie","Gift","Gingerbread Man","Giraffe","Girl","Guitar","Heart","Helicopter","Hippo","Horse","Ice Cream","Jellyfish","Kite","Ladybug","Lion","Lollipop","Magic Hat","Monkey","Mouse","Notebook","Nursing","Owl Sleeping","Owl","Pacifier","Pail and Shovel","Paint Kit","Panda","Penguin","Pig","Plane","Pram","Pumping","Rabbit","Rattle","Reindeer","Rocket","Rocking Horse","Saturn","Seahorse","Sheep","Shoes","Sleep","Sleeping Baby","Sleepsuit","Slice of Cake","Smiling Boy","Smiling Girl","Snail","Socks","Star","Strawberry","Submarine","Tooth","Tower Toy","Train","Walruses","Watering Can","Whale","Whipping-top","Winter Cap"] var selectedIconAsset: String? @IBOutlet weak var collectionIcons: UICollectionView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // UICollectionViewDataSource func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if (collectionView == self.collectionIcons) { return self.iconAssets.count } else { return 0 } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if(collectionView == self.collectionIcons) { let cell: IconCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "IconCell", for: indexPath) as! IconCollectionViewCell cell.asset = self.iconAssets[(indexPath as NSIndexPath).row] cell.imageIcon.layer.masksToBounds = true cell.imageIcon.image = UIImage(named: self.iconAssets[(indexPath as NSIndexPath).row]) if(cell.isSelected) { cell.backgroundColor = UIColor.orange } return cell } else { return UICollectionViewCell(); } } func numberOfSections(in collectionView: UICollectionView) -> Int { if (collectionView == self.collectionIcons) { return 1 } else { return 0 } } // UICollectionViewDelegate // func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { // if (collectionView == self.collectionIcons) { // let cell: IconCollectionViewCell = collectionView.cellForItemAtIndexPath(indexPath) as! IconCollectionViewCell // self.performSegueWithIdentifier("UnwindSegueSelectIcon", sender: cell) // } // } // Segues override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if (segue.identifier == "UnwindSegueSelectIconToBaby") { let babyVC: BabyViewController = segue.destination as! BabyViewController let selectedCell: IconCollectionViewCell = sender as! IconCollectionViewCell babyVC.imageView.image = selectedCell.imageIcon.image } } }
mit
2e0bae0e6d54fe920a1e92adb1dcaa3c
42.460674
995
0.648914
4.76942
false
false
false
false
netguru/inbbbox-ios
Unit Tests/UserSpec.swift
1
5333
// // UserSpec.swift // Inbbbox // // Created by Patryk Kaczmarek on 05/01/16. // Copyright ยฉ 2016 Netguru Sp. z o.o. All rights reserved. // import Quick import Nimble import SwiftyJSON @testable import Inbbbox class UserSpec: QuickSpec { override func spec() { it("should support secure coding") { expect(User.supportsSecureCoding).to(beTruthy()) } var sut: User! afterEach { sut = nil } describe("when mapping user") { beforeEach { sut = User.fixtureUser() } it("user should exist") { expect(sut).toNot(beNil()) } it("user's username should be properly mapped") { expect(sut.username).to(equal("fixture.username")) } it("user's name should be properly mapped") { expect(sut.name).to(equal("fixture.name")) } it("user's avatar url should be properly mapped") { expect(sut.avatarURL).to(equal(URL(string: "fixture.avatar.url"))) } it("user's id should be properly mapped") { expect(sut.identifier).to(equal("fixture.identifier")) } it("user's shots count should be properly mapped") { expect(sut.shotsCount).to(equal(1)) } it("user's buckets count should be properly mapped") { expect(sut.bucketsCount).to(equal(1)) } it("user's followers count should be properly mapped") { expect(sut.followersCount).to(equal(1)) } it("user's followings count should be properly mapped") { expect(sut.followingsCount).to(equal(1)) } it("user's projects count should be properly mapped") { expect(sut.projectsCount).to(equal(1)) } it("user's pro indicator should be properly mapped") { expect(sut.isPro).to(beTruthy()) } it("user's bio should be properly mapped") { expect(sut.bio).to(equal("fixture.bio")) } it("user's location should be properly mapped") { expect(sut.location).to(equal("fixture.location")) } } describe("when encoding user") { var data: Data! beforeEach { sut = User.fixtureUser() data = NSKeyedArchiver.archivedData(withRootObject: sut) } it("data should not be nil") { expect(data).toNot(beNil()) } context("and decoding data") { var decodedUser: User? beforeEach { decodedUser = NSKeyedUnarchiver.unarchiveObject(with: data) as? User } it("user should not be nil") { expect(decodedUser).toNot(beNil()) } it("user's username should be properly decoded") { expect(sut.username).to(equal(decodedUser!.username)) } it("user's name should be properly decoded") { expect(sut.name).to(equal(decodedUser!.name)) } it("user's avatar url should be properly decoded") { expect(sut.avatarURL).to(equal(decodedUser!.avatarURL)) } it("user's id should be properly decoded") { expect(sut.identifier).to(equal(decodedUser!.identifier)) } it("user's shots count should be properly mapped") { expect(sut.shotsCount).to(equal(decodedUser!.shotsCount)) } it("user's buckets count should be properly mapped") { expect(sut.bucketsCount).to(equal(decodedUser!.bucketsCount)) } it("user's followers count should be properly mapped") { expect(sut.followersCount).to(equal(decodedUser!.followersCount)) } it("user's followings count should be properly mapped") { expect(sut.followingsCount).to(equal(decodedUser!.followingsCount)) } it("user's projects count should be properly mapped") { expect(sut.projectsCount).to(equal(decodedUser!.projectsCount)) } it("user's pro indicator should be properly mapped") { expect(sut.isPro).to(equal(decodedUser!.isPro)) } it("user's bio should be properly mapped") { expect(sut.bio).to(equal(decodedUser!.bio)) } it("user's location should be properly mapped") { expect(sut.location).to(equal(decodedUser!.location)) } } } } }
gpl-3.0
673bcb020e913dfe15521c58735a1a65
31.91358
88
0.477494
5.232581
false
false
false
false
breadwallet/breadwallet-ios
breadwalletTests/AssetCollectionTests.swift
1
7620
// // AssetCollectionTests.swift // breadwalletTests // // Created by Adrian Corscadden on 2018-04-18. // Copyright ยฉ 2018-2019 Breadwinner AG. All rights reserved. // import XCTest @testable import breadwallet class AssetCollectionTests: XCTestCase { // uid, code static var testTokenData = [("bitcoin-mainnet:__native__", "btc"), ("bitcoincash-mainnet:__native__", "bch"), ("ethereum-mainnet:__native__", "eth"), ("ethereum-mainnet:0x558ec3152e2eb2174905cd19aea4e34a23de9ad6", "brd"), ("ethereum-mainnet:0x89d24a6b4ccb1b6faa2625fe562bdd9a23260359", "dai"), ("ethereum-mainnet:0x0000000000085d4780B73119b644AE5ecd22b376", "tusd"), ("ripple-mainnet:__native__", "xrp"), ("ethereum-mainnet:0x86fa049857e0209aa7d9e616f7eb3b3b78ecfdb0", "eos"), ("ethereum-mainnet:0xE41d2489571d322189246DaFA5ebDe1F4699F498", "zrx"), ("ethereum-mainnet:0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", "usdc")] .map { (CurrencyId(rawValue: $0.0), $0.1) } var allTokens: [CurrencyId: CurrencyMetaData] { return Dictionary(uniqueKeysWithValues: AssetCollectionTests.testTokenData.map { (uid, code) -> (CurrencyId, CurrencyMetaData) in return (uid, CurrencyMetaData(uid: uid, code: code)) }) } var defaultAssets: [CurrencyMetaData] = AssetIndex.defaultCurrencyIds.map { CurrencyMetaData(uid: $0, code: $0.rawValue) } var availableAssets: [CurrencyMetaData] { return AssetCollectionTests.testTokenData .filter { !AssetIndex.defaultCurrencyIds.contains($0.0) } .map { CurrencyMetaData(uid: $0.0, code: $0.1) } } private var client: BRAPIClient? private var keyStore: KeyStore! private var kvStore: BRReplicatedKVStore! { guard let kv = client?.kv else { XCTFail("KV store should exist"); return nil } return kv } override func setUp() { super.setUp() clearKeychain() deleteKvStoreDb() keyStore = try! KeyStore.create() _ = setupNewAccount(keyStore: keyStore) Backend.connect(authenticator: keyStore) client = Backend.apiClient } override func tearDown() { super.tearDown() try! BRReplicatedKVStore.rmdb() keyStore.destroy() clearKeychain() } func testInitWithDefaultAssets() { let collection = AssetCollection(kvStore: kvStore, allTokens: allTokens, changeHandler: nil) XCTAssertEqual(collection.allAssets, allTokens) XCTAssertEqual(Set(collection.availableAssets), Set(availableAssets)) } func testMigrationFromOldIndex() { //TODO:CRYPTO } func testModifyingAssetList() { let collection = AssetCollection(kvStore: kvStore, allTokens: allTokens, changeHandler: nil) let asset1 = collection.availableAssets.first! let asset2 = collection.availableAssets.last! XCTAssertNil(collection.displayOrder(for: asset1)) // add collection.add(asset: asset1) XCTAssertFalse(collection.availableAssets.contains(asset1)) XCTAssertEqual(collection.displayOrder(for: asset1), collection.enabledAssets.count-1) collection.add(asset: asset2) XCTAssertFalse(collection.availableAssets.contains(asset2)) XCTAssertEqual(collection.displayOrder(for: asset2), collection.enabledAssets.count-1) // move let asset1Index = collection.displayOrder(for: asset1) XCTAssert(asset1Index != nil) collection.moveAsset(from: asset1Index!, to: 0) XCTAssertEqual(collection.displayOrder(for: asset1), 0) // remove collection.remove(asset: asset1) XCTAssertNil(collection.displayOrder(for: asset1)) XCTAssertTrue(collection.availableAssets.contains(asset1)) // re-add collection.add(asset: asset1) XCTAssertEqual(collection.displayOrder(for: asset1), collection.enabledAssets.count-1) XCTAssertFalse(collection.availableAssets.contains(asset1)) } func testRevertChanges() { let collection = AssetCollection(kvStore: kvStore, allTokens: allTokens, changeHandler: nil) XCTAssertEqual(Set(collection.availableAssets), Set(availableAssets)) var numAdded = 0 for asset in collection.availableAssets { collection.add(asset: asset) numAdded += 1 } for asset in collection.enabledAssets { collection.remove(asset: asset) } XCTAssertEqual(collection.enabledAssets.count, 0) XCTAssertEqual(collection.availableAssets.count, allTokens.count) collection.revertChanges() XCTAssertEqual(Set(collection.availableAssets), Set(availableAssets)) } func testResetToDefault() { let collection = AssetCollection(kvStore: kvStore, allTokens: allTokens, changeHandler: nil) XCTAssertEqual(Set(collection.availableAssets), Set(availableAssets)) collection.removeAsset(at: 0) collection.resetToDefaultCollection() XCTAssertEqual(collection.enabledAssets.map { $0.uid }, AssetIndex.defaultCurrencyIds) } func testGetCurrencyMetaData() { let e = expectation(description: "Should receive currency metadata") clearCurrenciesCache() //1st fetch without cache client?.getCurrencyMetaData(completion: { metadata in let tokens = metadata.values.filter { ($0.tokenAddress != nil) && !$0.tokenAddress!.isEmpty } let tokensByAddress = Dictionary(uniqueKeysWithValues: tokens.map { ($0.tokenAddress!, $0) }) XCTAssert(metadata.count > 0) XCTAssert(tokens.count > 0) XCTAssert(tokensByAddress.count > 0) //2nd fetch should hit cache self.client?.getCurrencyMetaData(completion: { metadata in let tokens = metadata.values.filter { ($0.tokenAddress != nil) && !$0.tokenAddress!.isEmpty } let tokensByAddress = Dictionary(uniqueKeysWithValues: tokens.map { ($0.tokenAddress!, $0) }) XCTAssert(metadata.count > 0) XCTAssert(tokens.count > 0) XCTAssert(tokensByAddress.count > 0) e.fulfill() }) }) waitForExpectations(timeout: 5.0, handler: nil) } private func clearCurrenciesCache() { let fm = FileManager.default guard let documentsDir = try? fm.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) else { return assertionFailure() } let currenciesPath = documentsDir.appendingPathComponent("currencies.json").path if fm.fileExists(atPath: currenciesPath) { try? fm.removeItem(atPath: currenciesPath) } } } extension CurrencyMetaData { init(uid: CurrencyId, code: String, tokenAddress: String? = nil) { self.init(uid: uid, code: code, isSupported: true, colors: (UIColor.black, UIColor.black), name: "test currency", tokenAddress: tokenAddress, decimals: 0, alternateCode: nil) } }
mit
0d4190d739f5237dac69232d5dac2bb9
39.743316
161
0.622129
4.452951
false
true
false
false
fruitcoder/PlayButton
PlayButton/Classes/PlayButton.swift
1
19356
// // PlayButton.swift // Pods // // Created by Alexander Hรผllmandel on 06/06/16. // // import UIKit public enum PlayAction { case Pause case Play /// `.Pause` when self is `.Play`, .Play when `self` is `.Pause` public var reverseAction: PlayAction { return self == .Play ? .Pause : .Play } } @IBDesignable public class PlayButton: UIButton { public private(set) var buttonAction = PlayAction.Play /// The ratio between the width of the pause line and the width of the button. Defaults to `0.27`. @IBInspectable public var pauseLineWidthRatio: CGFloat = 0.27 /// Returns how wide the pause line is for the current bounds public var pauseLineWidth: CGFloat{ return CGRectGetWidth(bounds) * pauseLineWidthRatio } /// This property determines how much the pause shape will be scaled in relation to the bounds. Defaults to `0.5`. @IBInspectable public var pauseScale: CGFloat = 0.5 /// Returns how wide the pause line is during the scaling animation. public var scaledPauseLineWidth: CGFloat { return pauseScale * pauseLineWidth } /// Determines how long the animation will take. Defaults to `1.05` public var animationDuration: CFTimeInterval = 1.05 // defaults to 1.05 public override init(frame: CGRect) { super.init(frame: frame) setup() } /// Initializes and returns a newly allocated `PlayButton` object with the specified parameters. /// /// - parameter origin: The origin of the button /// - parameter width: The width of the button, which will also be used as its height. Defaults to `30.0` /// - parameter initialAction: The initial button action, that the button represents. Defaults to `.Play` /// /// - returns: An initialized `PlayButton` object public convenience init(origin: CGPoint, width: CGFloat = 30.0, initialAction: PlayAction = .Play) { self.init(frame: CGRect(origin: origin, size: CGSize(width: width, height: width))) self.buttonAction = initialAction setup() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } public override var tintColor: UIColor! { didSet { leftShapeLayer.fillColor = tintColor.CGColor rightShapeLayer.fillColor = tintColor.CGColor } } private enum Animation: String { case LeftPlayToPause, RightPlayToPause, LeftPauseToPlay, RightPauseToPlay var key: String { return self.rawValue } var keyTimes: [Float] { switch self { case .LeftPauseToPlay: return [0.0, 0.143, 0.486, 0.486, 0.714, 0.714, 0.811, 0.908, 1.0] case .RightPauseToPlay: return [0.0, 0.143, 0.429, 0.543, 0.629, 0.657, 0.714, 0.714, 1.0] case .LeftPlayToPause: return [0.0, 0.097, 0.194, 0.286, 0.857, 1.0] case .RightPlayToPause: return [0.0, 0.286, 0.286, 0.571, 0.686, 0.771, 0.8, 0.857, 1.0] } } var timingFunctions: [CAMediaTimingFunction]? { switch self { case .LeftPauseToPlay: return [ CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn), CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault), // ignored, because interpolated paths are the same CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault), // ignored, because the keyTimes between the frames are the same -> instant change CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault), // ignored, because interpolated paths are the same (zeroPath) CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault), // ignored, because the keyTimes between the frames are the same -> instant change CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear), CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear), CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn), ] case .RightPauseToPlay: return [ CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn), CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn), CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut), CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut), CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut), CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut), CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault), CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault), ] case .LeftPlayToPause: return [ CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn), CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear), CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear), CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear), CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn), ] case .RightPlayToPause: return [ // default CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault), // ignored, because interpolated paths are the same (zeroPath) CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault), // ignored, because the keyTimes between the frames are the same -> instant change CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn), CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut), CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut), CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut), CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut), CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn) ] } } func finalFrame(lineWidth: CGFloat, atScale scale: CGFloat, bounds: CGRect) -> CGPath { switch self { case .LeftPauseToPlay: return playPathAtScale(1.0, lineWidth: lineWidth, bounds: bounds) case .RightPauseToPlay: return zeroPath() case .LeftPlayToPause: return leftMorph2PlayPathAtScale(1.0, lineWidth: lineWidth, bounds: bounds) case .RightPlayToPause: return rightPausePathAtScale(1.0, lineWidth: lineWidth, bounds: bounds, xOffset: bounds.width - lineWidth, bending: 0.0) } } func keyframes(forLineWidth lineWidth: CGFloat, atScale scale: CGFloat, bounds: CGRect) -> [CGPath] { let scaledLineWidth = lineWidth * scale switch self { case .LeftPauseToPlay: return [ leftMorph2PlayPathAtScale(1.0, lineWidth: lineWidth, bounds: bounds), leftMorph2PlayPathAtScale(scale, lineWidth: scaledLineWidth, bounds: bounds), leftMorph2PlayPathAtScale(scale, lineWidth: scaledLineWidth, bounds: bounds), zeroPath(), // hide when right shape layer "rebounces" into left one zeroPath(), // stay hidden until right layer finished bouncing leftMorph2PlayPathAtScale(scale, lineWidth: scaledLineWidth, bounds: bounds), // appear again leftMorph1PlayPathAtScale(scale, lineWidth: scaledLineWidth, bounds: bounds), playPathAtScale(scale, lineWidth: scaledLineWidth, bounds: bounds), playPathAtScale(1.0, lineWidth: lineWidth, bounds: bounds) ] case .RightPauseToPlay: return [ rightPausePathAtScale(1.0, lineWidth: lineWidth, bounds: bounds, xOffset: bounds.width - lineWidth, bending: 0.0), rightPausePathAtScale(scale, lineWidth: scaledLineWidth, bounds: bounds, xOffset: scale*bounds.width - scaledLineWidth, bending: 0.0), rightPausePathAtScale(scale, lineWidth: scaledLineWidth, bounds: bounds, xOffset: 0.0, bending: 1.0), rightPausePathAtScale(scale, lineWidth: scaledLineWidth, bounds: bounds, xOffset: 0.0, bending: -0.7), rightPausePathAtScale(scale, lineWidth: scaledLineWidth, bounds: bounds, xOffset: 0.0, bending: 0.3), rightPausePathAtScale(scale, lineWidth: scaledLineWidth, bounds: bounds, xOffset: 0.0, bending: -0.15), rightPausePathAtScale(scale, lineWidth: scaledLineWidth, bounds: bounds, xOffset: 0.0, bending: 0.0), zeroPath(), // hide it ] case .LeftPlayToPause: return [ playPathAtScale(1.0, lineWidth: lineWidth, bounds: bounds), playPathAtScale(scale, lineWidth: lineWidth, bounds: bounds), leftMorph1PlayPathAtScale(scale, lineWidth: lineWidth, bounds: bounds), leftMorph2PlayPathAtScale(scale, lineWidth: scaledLineWidth, bounds: bounds), leftMorph2PlayPathAtScale(scale, lineWidth: scaledLineWidth, bounds: bounds), leftMorph2PlayPathAtScale(1.0, lineWidth: lineWidth, bounds: bounds), ] case .RightPlayToPause: return [ zeroPath(), zeroPath(), rightPausePathAtScale(scale, lineWidth: scaledLineWidth, bounds: bounds, xOffset: 0.0, bending: 0.0), rightPausePathAtScale(scale, lineWidth: scaledLineWidth, bounds: bounds, xOffset: scale*bounds.width - scaledLineWidth, bending: -1.0), rightPausePathAtScale(scale, lineWidth: scaledLineWidth, bounds: bounds, xOffset: scale*bounds.width - scaledLineWidth, bending: 0.7), rightPausePathAtScale(scale, lineWidth: scaledLineWidth, bounds: bounds, xOffset: scale*bounds.width - scaledLineWidth, bending: -0.3), rightPausePathAtScale(scale, lineWidth: scaledLineWidth, bounds: bounds, xOffset: scale*bounds.width - scaledLineWidth, bending: 0.15), rightPausePathAtScale(scale, lineWidth: scaledLineWidth, bounds: bounds, xOffset: scale*bounds.width - scaledLineWidth, bending: 0.0), rightPausePathAtScale(1.0, lineWidth: lineWidth, bounds: bounds, xOffset: bounds.width - lineWidth, bending: 0.0), ] } } /// Returns a keyframe animation with given parameters /// /// - parameter duration: how long the animation should take in total /// - parameter lineWidth: how thick the paused line is /// - parameter scale: how small the button is scaled during animation /// - parameter bounds: the bounds of the button /// /// - returns: Returns a keyframe animation with given parameters func keyframeAnimation(withDuration duration: CFTimeInterval, lineWidth: CGFloat, scale: CGFloat, bounds: CGRect) -> CAKeyframeAnimation { let animation = CAKeyframeAnimation(keyPath: "path") animation.duration = duration animation.values = keyframes(forLineWidth: lineWidth, atScale: scale, bounds: bounds) animation.keyTimes = self.keyTimes animation.timingFunctions = self.timingFunctions return animation } private func zeroPath() -> CGPath { let margin = 0.0 let playPath = UIBezierPath() playPath.moveToPoint(CGPoint(x: margin, y: margin)) playPath.closePath() return playPath.CGPath } private func playPathAtScale(scale: CGFloat, lineWidth: CGFloat, bounds: CGRect) -> CGPath { let margin = (1.0 - scale)/2.0 * CGRectGetWidth(bounds) let playPath = UIBezierPath() playPath.moveToPoint(CGPoint(x: margin, y: margin)) playPath.addLineToPoint(CGPoint(x: margin + lineWidth, y: margin + floor(lineWidth/sqrt(3)))) playPath.addLineToPoint(CGPoint(x: CGRectGetMaxX(bounds)-margin, y: CGRectGetMidY(bounds))) playPath.addLineToPoint(CGPoint(x: CGRectGetMaxX(bounds)-margin, y: CGRectGetMidY(bounds))) playPath.addLineToPoint(CGPoint(x: margin + lineWidth, y: CGRectGetMaxY(bounds) - margin - floor(lineWidth/sqrt(3)))) playPath.addLineToPoint(CGPoint(x: margin, y: CGRectGetMaxY(bounds) - margin)) playPath.closePath() return playPath.CGPath } private func leftMorph1PlayPathAtScale(scale: CGFloat, lineWidth: CGFloat, bounds: CGRect) -> CGPath { let margin = (1.0 - scale)/2.0 * CGRectGetWidth(bounds) let playPath = UIBezierPath() playPath.moveToPoint(CGPoint(x: margin, y: margin)) playPath.addLineToPoint(CGPoint(x: margin + lineWidth, y: margin + lineWidth/sqrt(3))) playPath.addLineToPoint(CGPoint(x: margin + lineWidth, y: margin + lineWidth/sqrt(3))) playPath.addLineToPoint(CGPoint(x: margin + lineWidth, y: CGRectGetMaxY(bounds) - margin - lineWidth/sqrt(3))) playPath.addLineToPoint(CGPoint(x: margin + lineWidth, y: CGRectGetMaxY(bounds) - margin - lineWidth/sqrt(3))) playPath.addLineToPoint(CGPoint(x: margin, y: CGRectGetMaxY(bounds) - margin)) playPath.closePath() return playPath.CGPath } private func leftMorph2PlayPathAtScale(scale: CGFloat, lineWidth: CGFloat, bounds: CGRect) -> CGPath { let margin = (1.0 - scale)/2.0 * CGRectGetWidth(bounds) let playPath = UIBezierPath() playPath.moveToPoint(CGPoint(x: margin, y: margin)) playPath.addLineToPoint(CGPoint(x: margin + lineWidth, y: margin)) playPath.addLineToPoint(CGPoint(x: margin + lineWidth, y: margin + lineWidth/sqrt(3))) playPath.addLineToPoint(CGPoint(x: margin + lineWidth, y: CGRectGetMaxY(bounds) - margin - lineWidth/sqrt(3))) playPath.addLineToPoint(CGPoint(x: margin + lineWidth, y: CGRectGetMaxY(bounds) - margin)) playPath.addLineToPoint(CGPoint(x: margin, y: CGRectGetMaxY(bounds) - margin)) playPath.closePath() return playPath.CGPath } private func rightPausePathAtScale(scale: CGFloat = 1.0, lineWidth: CGFloat, bounds: CGRect, xOffset: CGFloat = 0.0, bending: CGFloat = 0.0) -> CGPath { let margin = (1.0 - scale)/2.0 * CGRectGetWidth(bounds) let playPath = UIBezierPath() playPath.moveToPoint(CGPoint(x: margin + lineWidth + xOffset, y: margin)) playPath.addQuadCurveToPoint(CGPoint(x: margin + lineWidth + xOffset, y: CGRectGetMaxY(bounds) - margin), controlPoint: CGPoint(x: margin + lineWidth + xOffset - bending * lineWidth, y: CGRectGetMidY(bounds))) playPath.addLineToPoint(CGPoint(x: margin + xOffset, y: CGRectGetMaxY(bounds) - margin)) playPath.addQuadCurveToPoint(CGPoint(x: margin + xOffset, y: margin), controlPoint: CGPoint(x: margin + xOffset - bending * lineWidth, y: CGRectGetMidY(bounds))) playPath.closePath() return playPath.CGPath } } private let leftShapeLayer: CAShapeLayer = { $0.contentsScale = UIScreen.mainScreen().scale $0.fillColor = UIColor.blackColor().CGColor return $0 }(CAShapeLayer()) private let rightShapeLayer: CAShapeLayer = { $0.contentsScale = UIScreen.mainScreen().scale $0.fillColor = UIColor.blackColor().CGColor return $0 }(CAShapeLayer()) /// Set the button action for the button. If the `action` is the same as `buttonAction`, nothing happens. If `animated` is `true` the animation will take `animationDuration` seconds, when there is no animation currently going on. If `animated` is `false` or there is already an ongoing animation, the state will be immidiately set /// /// - parameter action: The new button action /// - parameter animated: Determines whether the state change should be animated (with duration `animationDuration`) public func setButtonAction(action: PlayAction, animated: Bool) { guard buttonAction != action else { return } buttonAction = action switch buttonAction { case .Pause: if !animated || leftShapeLayer.animationForKey(Animation.LeftPauseToPlay.key) != nil { // ongoing animation is cancelled setModelToFinalPath() } else { setModelToFinalPath() // left layer leftShapeLayer.addAnimation(Animation.LeftPlayToPause.keyframeAnimation(withDuration: animationDuration, lineWidth: pauseLineWidth, scale: pauseScale, bounds: bounds), forKey: Animation.LeftPlayToPause.key) // right layer rightShapeLayer.addAnimation(Animation.RightPlayToPause.keyframeAnimation(withDuration: animationDuration, lineWidth: pauseLineWidth, scale: pauseScale, bounds: bounds), forKey: Animation.RightPlayToPause.key) } case .Play: if !animated || leftShapeLayer.animationForKey(Animation.LeftPlayToPause.key) != nil { // ongoing animation is cancelled setModelToFinalPath() } else { setModelToFinalPath() // left layer leftShapeLayer.addAnimation(Animation.LeftPauseToPlay.keyframeAnimation(withDuration: animationDuration, lineWidth: pauseLineWidth, scale: pauseScale, bounds: bounds), forKey: Animation.LeftPauseToPlay.key) // right layer rightShapeLayer.addAnimation(Animation.RightPauseToPlay.keyframeAnimation(withDuration: animationDuration, lineWidth: pauseLineWidth, scale: pauseScale, bounds: bounds), forKey: Animation.RightPauseToPlay.key) } } } private func setModelToFinalPath() { switch buttonAction { case .Pause: leftShapeLayer.removeAllAnimations() rightShapeLayer.removeAllAnimations() leftShapeLayer.path = Animation.LeftPlayToPause.finalFrame(pauseLineWidth, atScale: 1.0, bounds: bounds) rightShapeLayer.path = Animation.RightPlayToPause.finalFrame(pauseLineWidth, atScale: 1.0, bounds: bounds) case .Play: leftShapeLayer.removeAllAnimations() rightShapeLayer.removeAllAnimations() leftShapeLayer.path = Animation.LeftPauseToPlay.finalFrame(pauseLineWidth, atScale: 1.0, bounds: bounds) rightShapeLayer.path = Animation.RightPauseToPlay.finalFrame(pauseLineWidth, atScale: 1.0, bounds: bounds) } } private func setup() { backgroundColor = .clearColor() tintColor = .blackColor() layer.addSublayer(leftShapeLayer) layer.addSublayer(rightShapeLayer) leftShapeLayer.path = Animation.LeftPauseToPlay.finalFrame(pauseLineWidth, atScale: pauseScale, bounds: bounds) rightShapeLayer.path = Animation.RightPauseToPlay.finalFrame(pauseLineWidth, atScale: pauseScale, bounds: bounds) } public override func layoutSublayersOfLayer(layer: CALayer) { super.layoutSublayersOfLayer(layer) leftShapeLayer.frame = bounds rightShapeLayer.frame = bounds switch buttonAction { case .Pause: leftShapeLayer.path = Animation.LeftPlayToPause.finalFrame(pauseLineWidth, atScale: 1.0, bounds: bounds) rightShapeLayer.path = Animation.RightPlayToPause.finalFrame(pauseLineWidth, atScale: 1.0, bounds: bounds) case .Play: leftShapeLayer.path = Animation.LeftPauseToPlay.finalFrame(pauseLineWidth, atScale: 1.0, bounds: bounds) rightShapeLayer.path = Animation.RightPauseToPlay.finalFrame(pauseLineWidth, atScale: 1.0, bounds: bounds) } } }
mit
c0d11b24e8c0e45ac3ff6825d62d65cd
47.511278
333
0.679514
4.734589
false
false
false
false
luinily/hOme
hOme/Model/CommandManager.swift
1
6121
// // CommandManager.swift // IRKitApp // // Created by Coldefy Yoann on 2015/12/03. // Copyright ยฉ 2015ๅนด YoannColdefy. All rights reserved. // import Foundation import CloudKit enum CommandManagerClassError: Error { case couldNotFindCommandDataInCK case clouldNotFindCommunicator case commandClassInvalid } class CommandManager: Manager, CloudKitObject { private var _commands: [String: CommandProtocol] private var _currentCKRecordName: String? init() { _commands = [String: CommandProtocol]() } init(ckRecordName: String) { _commands = [String: CommandProtocol]() _currentCKRecordName = ckRecordName } func createCommand(_ device: DeviceProtocol, name: String, commandType: CommandType?, getDevice: @escaping (_ deviceInternalName: String) -> DeviceProtocol?) -> CommandProtocol? { func createCommand(name: Name, device: DeviceProtocol, commandType: CommandType) -> DeviceCommand { var newCommand: DeviceCommand switch commandType { case .onOffCommand: newCommand = OnOffCommand(deviceInternalName: device.internalName, getDevice: getDevice) case .irkitCommand: newCommand = IRKitCommand(name: name, deviceInternalName: device.internalName, getDevice: getDevice, notifyDeviceOfExecution: device.notifyCommandExecution) } addCommand(newCommand) if newCommand is CloudKitObject { updateCloudKit() } return newCommand } let newName = Name(name: name, internalName: createNewUniqueName()) if let commandType = commandType { return createCommand(name: newName, device: device, commandType: commandType) } else if let commandType = device.commandType { return createCommand(name: newName, device: device, commandType: commandType) } return nil } func deleteCommand(_ command: CommandProtocol) { if let ckCommand = command as? CloudKitObject { _commands[command.internalName] = nil CloudKitHelper.sharedHelper.remove(ckCommand) updateCloudKit() } } func getCommands() -> [String: CommandProtocol] { return _commands } func getCommand(internalName: String) -> CommandProtocol? { return _commands[internalName] } func getCommandsOfDevice(deviceInternalName: String) -> [CommandProtocol] { return _commands.values.filter() { command in if let command = command as? DeviceCommand { return command.deviceInternalName == deviceInternalName } return false } } private func addCommand(_ command: CommandProtocol) { if _commands.index(forKey: command.internalName) == nil { _commands[command.internalName] = command } } func getCommandCountForDevice(deviceInternalName: String) -> Int { return getCommandsOfDevice(deviceInternalName: deviceInternalName).count } //MARK: - Manager func getUniqueNameBase() -> String { return "Command" } func isNameUnique(_ name: String) -> Bool { return _commands.index(forKey: name) == nil } //MARK: - CloudKitObject convenience init(ckRecord: CKRecord, getDevice: @escaping (_ internalName: String) -> DeviceProtocol?, getConnector: (_ deviceName: String) -> Connector?) throws { self.init(ckRecordName: ckRecord.recordID.recordName) if let commandList = ckRecord["commandData"] as? [String] { for recordName in commandList { importCommand(recordName, getDevice: getDevice) } } } private func importCommand(_ commandRecordName: String, getDevice: @escaping (_ internalName: String) -> DeviceProtocol?) { CloudKitHelper.sharedHelper.importRecord(commandRecordName) { (record) in do { if let record = record { guard let deviceInternalName = record["deviceInternalName"] as? String else { throw CommandManagerClassError.commandClassInvalid } var commandExecutionNotifier: ((_ sender: DeviceCommand) -> Void)? if let device = getDevice(deviceInternalName) { commandExecutionNotifier = device.notifyCommandExecution self.addOnOffCommand(deviceInternalName, getDevice: getDevice) //Adds the command only if it does not exist already } var command: DeviceCommand? = nil let commandType = try self.getCommandType(record) switch commandType { case .irkitCommand: if let commandExecutionNotifier = commandExecutionNotifier { command = try IRKitCommand(ckRecord: record, getDevice: getDevice, notifyDeviceOfExecution: commandExecutionNotifier) } default: command = nil } if let command = command { if self._commands.index(forKey: command.internalName) == nil { self._commands[command.internalName] = command } } } } catch { } } } private func getCommandType(_ record: CKRecord) throws -> CommandType { guard let commandTypeRawValue = record["type"] as? Int else { throw CommandManagerClassError.commandClassInvalid } guard let commandType = CommandType(rawValue: commandTypeRawValue) else { throw CommandManagerClassError.commandClassInvalid } return commandType } private func addOnOffCommand(_ deviceInternalName: String, getDevice: @escaping (_ internalName: String) -> DeviceProtocol?) { if _commands[deviceInternalName] == nil { let command = OnOffCommand(deviceInternalName: deviceInternalName, getDevice: getDevice) addCommand(command) } } func getNewCKRecordName() -> String { return "CommandManager" } func getCurrentCKRecordName() -> String? { return _currentCKRecordName } func setUpCKRecord(_ record: CKRecord) { _currentCKRecordName = record.recordID.recordName var commandList = [String]() for command in _commands.values { if let command = command as? CloudKitObject { commandList.append(command.getNewCKRecordName()) } } record["commandData"] = commandList as CKRecordValue? } func getCKRecordType() -> String { return "CommandManager" } func updateCloudKit() { CloudKitHelper.sharedHelper.export(self) _currentCKRecordName = getNewCKRecordName() } }
mit
21eaa9a6e37aea453f8a6fc8095abf37
27.455814
164
0.706603
4.046296
false
false
false
false
KarlWarfel/nutshell-ios
Nutshell/GraphView/Tidepool Graph/WizardGraphData.swift
1
6024
/* * Copyright (c) 2015, Tidepool Project * * This program is free software; you can redistribute it and/or modify it under * the terms of the associated License, which is identical to the BSD 2-Clause * License as published by the Open Source Initiative at opensource.org. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the License for more details. * * You should have received a copy of the License along with this program; if * not, you can obtain one from Tidepool Project at tidepool.org. */ import UIKit class WizardGraphDataType: GraphDataType { var bolusId: String? var recommendedNet: NSNumber? var bolusTopY: CGFloat? init(value: CGFloat, timeOffset: NSTimeInterval, bolusId: String?, recommendedNet: NSNumber?) { super.init(value: value, timeOffset: timeOffset) self.bolusId = bolusId self.recommendedNet = recommendedNet } override func typeString() -> String { return "wizard" } } class WizardGraphDataLayer: TidepoolGraphDataLayer { // vars for drawing datapoints of this type var pixelsPerValue: CGFloat = 0.0 let circleRadius: CGFloat = 9.0 var lastCircleDrawn = CGRectNull var context: CGContext? // Bolus drawing will store rects here. E.g., Wizard circles are drawn just over associated Bolus labels. var bolusRects: [CGRect] = [] private let kWizardCircleDiameter: CGFloat = 31.0 // // MARK: - Loading data // override func nominalPixelWidth() -> CGFloat { return kWizardCircleDiameter } override func typeString() -> String { return "wizard" } override func loadEvent(event: CommonData, timeOffset: NSTimeInterval) { if let event = event as? Wizard { let value = event.carbInput ?? 0.0 let floatValue = round(CGFloat(value)) dataArray.append(WizardGraphDataType(value: floatValue, timeOffset: timeOffset, bolusId: event.bolus, recommendedNet: event.recommendedNet)) // Let recommended bolus values figure into the bolus value scaling as well! if let recommended = event.recommendedNet { let recommendedValue = CGFloat(recommended) if recommendedValue > layout.maxBolus { layout.maxBolus = recommendedValue } } } } // // MARK: - Drawing data points // // override for any draw setup override func configureForDrawing() { self.pixelsPerValue = layout.yPixelsGlucose/layout.kGlucoseRange context = UIGraphicsGetCurrentContext() } // override! override func drawDataPointAtXOffset(xOffset: CGFloat, dataPoint: GraphDataType) { if dataPoint.value == 0.0 { // Don't plot nil or zero values - probably used for recommended bolus record! //NSLog("Skip plot of wizard with zero value!") return } if let wizard = dataPoint as? WizardGraphDataType { let centerX = xOffset let circleDiameter = kWizardCircleDiameter let value = round(dataPoint.value) // Carb circle should be centered at timeline let offsetX = centerX - (circleDiameter/2) var wizardRect = CGRect(x: offsetX, y: layout.yBottomOfWizard - circleDiameter, width: circleDiameter, height: circleDiameter) var yAtBolusTop = bolusYAtPosition(wizardRect) if wizard.bolusTopY != nil { yAtBolusTop = wizard.bolusTopY } if let yAtBolusTop = yAtBolusTop { wizardRect.origin.y = yAtBolusTop - circleDiameter } let wizardOval = UIBezierPath(ovalInRect: wizardRect) Styles.goldColor.setFill() wizardOval.fill() // Draw background colored border to separate the circle from other objects layout.backgroundColor.setStroke() wizardOval.lineWidth = 0.5 wizardOval.stroke() // Label Drawing let labelRect = wizardRect let labelText = String(Int(value)) let labelStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle labelStyle.alignment = .Center let labelAttrStr = NSMutableAttributedString(string: labelText, attributes: [NSFontAttributeName: Styles.smallSemiboldFont, NSForegroundColorAttributeName: Styles.darkPurpleColor, NSParagraphStyleAttributeName: labelStyle]) let labelTextHeight: CGFloat = ceil(labelAttrStr.boundingRectWithSize(CGSizeMake(labelRect.width, CGFloat.infinity), options: NSStringDrawingOptions.UsesLineFragmentOrigin, context: nil).size.height) CGContextSaveGState(context!) CGContextClipToRect(context!, labelRect); labelAttrStr.drawInRect(CGRectMake(labelRect.minX, labelRect.minY + (labelRect.height - labelTextHeight) / 2, labelRect.width, labelTextHeight)) CGContextRestoreGState(context!) } } // // MARK: - Tidepool specific utility functions // func bolusYAtPosition(rect: CGRect) -> CGFloat? { var result: CGFloat? let rectLeft = rect.origin.x let rectRight = rectLeft + rect.width for bolusRect in bolusRects { let bolusLeftX = bolusRect.origin.x let bolusRightX = bolusLeftX + bolusRect.width if bolusRightX > rectLeft && bolusLeftX < rectRight { if bolusRect.height > result { // return the bolusRect that is largest and intersects the x position of the target rect result = bolusRect.height } } } return result } }
bsd-2-clause
da27cefec60780d6ebc2808847024ec0
37.126582
235
0.641102
5.113752
false
false
false
false
leizh007/HiPDA
HiPDA/HiPDA/General/Views/ImagePicker/ImagePickerViewController.swift
1
9794
// // ImagePickerViewController.swift // HiPDA // // Created by leizh007 on 2017/6/15. // Copyright ยฉ 2017ๅนด HiPDA. All rights reserved. // import UIKit import Photos import AVFoundation import MobileCoreServices protocol ImagePickerDelegate: class { func imagePicker(_ imagePicker: ImagePickerViewController, didFinishUpload imageNumbers: [Int]) } private enum Constant { static let cameraIndex = 0 } class ImagePickerViewController: BaseViewController { fileprivate var viewModel: ImagePickerViewModel! @IBOutlet fileprivate weak var segmentedControl: UISegmentedControl! fileprivate var collectionView: UICollectionView! weak var delegate: ImagePickerDelegate? var pageURLPath: String! override func viewDidLoad() { super.viewDidLoad() title = "้€‰ๆ‹ฉๅ›พ็‰‡" segmentedControl.selectedSegmentIndex = ImageCompressType.original.rawValue segmentedControl.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.white], for: .selected) skinViewModel() skinCollectionView() NotificationCenter.default.addObserver(self, selector: #selector(didBecomeActive(_:)), name: Notification.Name.UIApplicationDidBecomeActive, object: nil) } deinit { NotificationCenter.default.removeObserver(self) } func didBecomeActive(_ notification: Notification) { viewModel.loadAssets() let allAssets = viewModel.getAssets() for asset in viewModel.imageAsstesCollection.getAssets() { if !allAssets.contains(asset) { viewModel.imageAsstesCollection.remove(asset) } } collectionView.reloadData() } override func configureApperance(of navigationBar: UINavigationBar) { navigationItem.leftBarButtonItem = UIBarButtonItem(title: "ๅ–ๆถˆ", style: .plain, target: self, action: #selector(cancel)) navigationItem.rightBarButtonItem = UIBarButtonItem(title: "็กฎๅฎš", style: .plain, target: self, action: #selector(confirm)) navigationBar.barTintColor = #colorLiteral(red: 0.1294117647, green: 0.137254902, blue: 0.1882352941, alpha: 1) navigationBar.isTranslucent = false navigationBar.setBackgroundImage(UIImage(), for: .default) navigationBar.shadowImage = UIImage() navigationBar.barStyle = .black navigationBar.titleTextAttributes = [ NSForegroundColorAttributeName: UIColor.white] } fileprivate func skinCollectionView() { let layout = UICollectionViewFlowLayout() layout.minimumLineSpacing = 1.0 layout.minimumInteritemSpacing = 0.5 layout.scrollDirection = .vertical layout.itemSize = CGSize(width: (C.UI.screenWidth - 3.0) / 4.0, height: (C.UI.screenWidth - 3.0) / 4.0) collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: C.UI.screenWidth, height: C.UI.screenHeight - 113.0), collectionViewLayout: layout) collectionView.backgroundColor = .clear collectionView.register(ImagePickerCollectionViewCell.self) collectionView.register(ImagePickerCameraCollectionViewCell.self) collectionView.delegate = self collectionView.dataSource = self view.addSubview(collectionView) view.sendSubview(toBack: collectionView) } fileprivate func skinViewModel() { viewModel = ImagePickerViewModel() viewModel.pageURLPath = pageURLPath viewModel.loadAssets() } @IBAction func segmentedControllValueChanged(_ sender: UISegmentedControl) { viewModel.imageCompressType = ImageCompressType(rawValue: sender.selectedSegmentIndex) ?? .original } @IBAction func promptButtonPressed(_ sender: UIButton) { showMessage(title: "ๆ็คบ", message: "GIFๅ›พ็‰‡ไธไผšๅŽ‹็ผฉ๏ผŒๅŽŸๅ›พไธŠไผ ") } } // MARK: - UICollectionViewDelegate extension ImagePickerViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { guard indexPath.row != Constant.cameraIndex else { camereCellPressed() return } let asset = viewModel.asset(at: indexPath.row) if asset.isDownloading { asset.cancelDownloading() } else if viewModel.imageAsstesCollection.has(asset) { viewModel.imageAsstesCollection.remove(asset) } else { asset.downloadAsset { [weak self, weak asset] result in guard let `self` = self, let asset = asset else { return } switch result { case .success(_): self.viewModel.imageAsstesCollection.add(asset) case .failure(let error): self.showPromptInformation(of: .failure(error.localizedDescription)) } } } } } // MARK: - UICollectionViewDataSource extension ImagePickerViewController: UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return viewModel.numberOfItems() } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell: UICollectionViewCell switch indexPath.row { case Constant.cameraIndex: let cameraCell = collectionView.dequeueReusableCell(for: indexPath) as ImagePickerCameraCollectionViewCell cameraCell.image = #imageLiteral(resourceName: "image_selector_camera") cell = cameraCell default: let imageCell = collectionView.dequeueReusableCell(for: indexPath) as ImagePickerCollectionViewCell imageCell.asset = viewModel.asset(at: indexPath.row) imageCell.assetsCollection = viewModel.imageAsstesCollection imageCell.imageView.contentMode = .scaleAspectFill imageCell.updateState() cell = imageCell } return cell } } // MARK: - Button Actions extension ImagePickerViewController { func cancel() { presentingViewController?.dismiss(animated: true, completion: nil) } func confirm() { showPromptInformation(of: .loading("ๆญฃๅœจไธŠไผ ...")) viewModel.uploadAssets { [weak self] result in guard let `self` = self else { return } self.hidePromptInformation() switch result { case let .success(imageNumbers): self.delegate?.imagePicker(self, didFinishUpload: imageNumbers) self.presentingViewController?.dismiss(animated: true, completion: nil) case let .failure(error): self.showPromptInformation(of: .failure(error.localizedDescription)) } } } func camereCellPressed() { if !UIImagePickerController.isSourceTypeAvailable(.camera) { showPromptInformation(of: .failure("ๆ‘„ๅƒๅคดไธๅฏ็”จ!")) } else { AVCaptureDevice.checkCameraPermission { [weak self] granted in if granted { self?.showCameraPicker() } else { self?.showPromptInformation(of: .failure("ๅทฒๆ‹’็ป็›ธๆœบ็š„่ฎฟ้—ฎ็”ณ่ฏท๏ผŒ่ฏทๅˆฐ่ฎพ็ฝฎไธญๅผ€ๅฏ็›ธๆœบ็š„่ฎฟ้—ฎๆƒ้™๏ผ")) } } } } fileprivate func showCameraPicker() { let cameraPicker = UIImagePickerController() cameraPicker.sourceType = .camera cameraPicker.mediaTypes = [kUTTypeImage as String] cameraPicker.delegate = self present(cameraPicker, animated: true, completion: nil) } } // MARK: - UIImagePickerControllerDelegate extension ImagePickerViewController: UIImagePickerControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { if let image = (info[UIImagePickerControllerOriginalImage] as? UIImage)?.fixOrientation() { var localId: String? PHPhotoLibrary.shared().performChanges({ let request = PHAssetChangeRequest.creationRequestForAsset(from: image) localId = request.placeholderForCreatedAsset?.localIdentifier }, completionHandler: { (success, error) in DispatchQueue.main.async { if let error = error { self.showPromptInformation(of: .failure(error.localizedDescription)) } else if let localId = localId { let result = PHAsset.fetchAssets(withLocalIdentifiers: [localId], options: nil) if let _ = result.objects(at: IndexSet(integersIn: 0..<result.count)).first { self.viewModel.loadAssets() self.collectionView.reloadData() self.collectionView(self.collectionView, didSelectItemAt: IndexPath(row: 1, section: 0)) } else { self.showPromptInformation(of: .failure("่Žทๅ–ไฟๅญ˜ๅŽ็š„ๅ›พ็‰‡ๅ‡บ้”™!")) } } } }) } dismiss(animated: true, completion: nil) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true, completion: nil) } } // MARK: - UINavigationControllerDelegate extension ImagePickerViewController: UINavigationControllerDelegate { } // MARK: - StoryboardLoadable extension ImagePickerViewController: StoryboardLoadable { }
mit
c407fc5f06af8c5332c85b6caf66b120
38.904959
161
0.65393
5.46829
false
false
false
false
temoki/Tortoise
Tortoise/Private/CommandDrawTortoise.swift
1
1574
// // CommandDrawTortoise.swift // Tortoise // // Created by temoki on 2016/08/10. // Copyright ยฉ 2016 temoki. All rights reserved. // import Foundation import CoreGraphics class CommandDrawTortoise: Command { func execute(context: Context) { context.bitmapContext.saveGState() if let image = context.tortoiseImage { // Draw tortoise image let imageSize = CGSize(width: image.width, height: image.height) let drawRect = CGRect(origin: CGPoint.zero, size: imageSize) context.bitmapContext.translateBy(x: context.posX, y: context.posY) context.bitmapContext.rotate(by: (context.heading-Context.defaultHeading).radian) context.bitmapContext.translateBy(x: -imageSize.width*0.5, y: -imageSize.height*0.5) context.bitmapContext.draw(image, in: drawRect) } else { // Dras triangle's 3 points. let transform = CGAffineTransform(translationX: context.posX, y: context.posY) .rotated(by: context.heading.radian) let pos1 = CGPoint(x: 10, y: 0).applying(transform) let pos2 = CGPoint(x: -10, y: 5).applying(transform) let pos3 = CGPoint(x: -10, y: -5).applying(transform) context.bitmapContext.move(to: pos1) context.bitmapContext.addLine(to: pos2) context.bitmapContext.addLine(to: pos3) context.bitmapContext.closePath() context.bitmapContext.fillPath() } context.bitmapContext.restoreGState() } }
mit
7e6bda0a256c66ef914ffb135f41c673
34.75
96
0.633821
4.085714
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureApp/Sources/FeatureAppUI/CoinView/CoinAdapterView.swift
1
17546
// Copyright ยฉ 2021 Blockchain Luxembourg S.A. All rights reserved. import AnalyticsKit import BlockchainComponentLibrary import BlockchainNamespace import Collections import Combine import ComposableArchitecture import DIKit import FeatureAppDomain import FeatureCoinData import FeatureCoinDomain import FeatureCoinUI import FeatureDashboardUI import FeatureInterestUI import FeatureKYCUI import FeatureNFTUI import FeatureTransactionUI import MoneyKit import NetworkKit import PlatformKit import PlatformUIKit import SwiftUI import ToolKit public struct CoinAdapterView: View { let app: AppProtocol let store: Store<CoinViewState, CoinViewAction> let cryptoCurrency: CryptoCurrency public init( cryptoCurrency: CryptoCurrency, app: AppProtocol = resolve(), userAdapter: UserAdapterAPI = resolve(), coincore: CoincoreAPI = resolve(), fiatCurrencyService: FiatCurrencyServiceAPI = resolve(), assetInformationRepository: AssetInformationRepositoryAPI = resolve(), historicalPriceRepository: HistoricalPriceRepositoryAPI = resolve(), ratesRepository: RatesRepositoryAPI = resolve(), watchlistRepository: WatchlistRepositoryAPI = resolve(), dismiss: @escaping () -> Void ) { self.cryptoCurrency = cryptoCurrency self.app = app store = Store<CoinViewState, CoinViewAction>( initialState: .init( currency: cryptoCurrency ), reducer: coinViewReducer, environment: CoinViewEnvironment( app: app, kycStatusProvider: { [userAdapter] in userAdapter.userState .compactMap { result -> UserState.KYCStatus? in guard case .success(let userState) = result else { return nil } return userState.kycStatus } .map(FeatureCoinDomain.KYCStatus.init) .eraseToAnyPublisher() }, accountsProvider: { [fiatCurrencyService, coincore] in fiatCurrencyService.displayCurrencyPublisher .setFailureType(to: Error.self) .flatMap { [coincore] fiatCurrency in app.modePublisher() .flatMap { _ in coincore.cryptoAccounts( for: cryptoCurrency, filter: app.currentMode.filter ) } .map { accounts in accounts .filter { !($0 is ExchangeAccount) } .map { Account($0, fiatCurrency) } } .eraseToAnyPublisher() } .eraseToAnyPublisher() }, assetInformationService: AssetInformationService( currency: cryptoCurrency, repository: assetInformationRepository ), historicalPriceService: HistoricalPriceService( base: cryptoCurrency, displayFiatCurrency: fiatCurrencyService.displayCurrencyPublisher, historicalPriceRepository: historicalPriceRepository ), interestRatesRepository: ratesRepository, explainerService: .init(app: app), watchlistService: WatchlistService( base: cryptoCurrency, watchlistRepository: watchlistRepository, app: app ), dismiss: dismiss ) ) } public var body: some View { PrimaryNavigationView { CoinView(store: store) .app(app) .context([blockchain.ux.asset.id: cryptoCurrency.code]) } } } // swiftlint:disable line_length public final class CoinViewObserver: Session.Observer { let app: AppProtocol let transactionsRouter: TransactionsRouterAPI let coincore: CoincoreAPI let kycRouter: KYCRouterAPI let defaults: UserDefaults let application: URLOpener let topViewController: TopMostViewControllerProviding let exchangeProvider: ExchangeProviding let accountsRouter: () -> AccountsRouting public init( app: AppProtocol, transactionsRouter: TransactionsRouterAPI = resolve(), coincore: CoincoreAPI = resolve(), kycRouter: KYCRouterAPI = resolve(), defaults: UserDefaults = .standard, application: URLOpener = resolve(), topViewController: TopMostViewControllerProviding = resolve(), exchangeProvider: ExchangeProviding = resolve(), accountsRouter: @escaping () -> AccountsRouting = { resolve() } ) { self.app = app self.transactionsRouter = transactionsRouter self.coincore = coincore self.kycRouter = kycRouter self.defaults = defaults self.application = application self.topViewController = topViewController self.exchangeProvider = exchangeProvider self.accountsRouter = accountsRouter } var observers: [BlockchainEventSubscription] { [ activity, buy, exchangeDeposit, exchangeWithdraw, explainerReset, kyc, receive, rewardsDeposit, rewardsSummary, rewardsWithdraw, select, sell, send, swap, website ] } public func start() { for observer in observers { observer.start() } } public func stop() { for observer in observers { observer.stop() } } lazy var select = app.on(blockchain.ux.asset.select) { @MainActor [unowned self] event in let cryptoCurrency = try event.reference.context.decode(blockchain.ux.asset.id) as CryptoCurrency let origin = try event.context.decode(blockchain.ux.asset.select.origin) as String app.state.transaction { state in state.set(blockchain.ux.asset.id, to: cryptoCurrency.code) state.set(blockchain.ux.asset[cryptoCurrency.code].select.origin, to: origin) } let isColorEnabled: Bool = await ( try? app.get(blockchain.ux.asset.chart.asset.color.is.enabled) ).or( try? app.get(blockchain.app.configuration.asset.chart.asset.color.is.enabled) ).or(false) var vc: UIViewController? vc = UIHostingController( rootView: CoinAdapterView( cryptoCurrency: cryptoCurrency, app: app, dismiss: { vc?.dismiss(animated: true) } ) .if(isColorEnabled) { coinView in coinView.lineGraphColor(cryptoCurrency.color) } ) if let vc = vc { topViewController.topMostViewController?.present( vc, animated: true ) } } lazy var buy = app.on(blockchain.ux.asset.buy, blockchain.ux.asset.account.buy) { @MainActor [unowned self] event in do { try await transactionsRouter.presentTransactionFlow( to: .buy(cryptoAccount(for: .buy, from: event)) ) } } lazy var sell = app.on(blockchain.ux.asset.sell, blockchain.ux.asset.account.sell) { @MainActor [unowned self] event in try await transactionsRouter.presentTransactionFlow( to: .sell(cryptoAccount(for: .sell, from: event)) ) } lazy var receive = app.on(blockchain.ux.asset.receive, blockchain.ux.asset.account.receive) { @MainActor [unowned self] event in try await transactionsRouter.presentTransactionFlow( to: .receive(cryptoAccount(for: .receive, from: event)) ) } lazy var send = app.on(blockchain.ux.asset.send, blockchain.ux.asset.account.send) { @MainActor [unowned self] event in try await transactionsRouter.presentTransactionFlow( to: .send(cryptoAccount(for: .send, from: event), nil) ) } lazy var swap = app.on(blockchain.ux.asset.account.swap) { @MainActor [unowned self] event in try await transactionsRouter.presentTransactionFlow( to: .swap(cryptoAccount(for: .swap, from: event)) ) } lazy var rewardsWithdraw = app.on(blockchain.ux.asset.account.rewards.withdraw) { @MainActor [unowned self] event in switch try await cryptoAccount(from: event) { case let account as CryptoInterestAccount: await transactionsRouter.presentTransactionFlow(to: .interestWithdraw(account)) default: throw blockchain.ux.asset.account.error[] .error(message: "Withdrawing from rewards requires CryptoInterestAccount") } } lazy var rewardsDeposit = app.on(blockchain.ux.asset.account.rewards.deposit) { @MainActor [unowned self] event in switch try await cryptoAccount(from: event) { case let account as CryptoInterestAccount: await transactionsRouter.presentTransactionFlow(to: .interestTransfer(account)) default: throw blockchain.ux.asset.account.error[] .error(message: "Transferring to rewards requires CryptoInterestAccount") } } lazy var rewardsSummary = app.on(blockchain.ux.asset.account.rewards.summary) { @MainActor [unowned self] event in let account = try await cryptoAccount(from: event) let interactor = InterestAccountDetailsScreenInteractor(account: account) let presenter = InterestAccountDetailsScreenPresenter(interactor: interactor) let controller = InterestAccountDetailsViewController(presenter: presenter) topViewController.topMostViewController?.present(controller, animated: true, completion: nil) } lazy var exchangeWithdraw = app.on(blockchain.ux.asset.account.exchange.withdraw) { @MainActor [unowned self] event in try await transactionsRouter.presentTransactionFlow( to: .send( cryptoAccount(for: .send, from: event), custodialAccount(CryptoTradingAccount.self, from: event) ) ) } lazy var exchangeDeposit = app.on(blockchain.ux.asset.account.exchange.deposit) { @MainActor [unowned self] event in try await transactionsRouter.presentTransactionFlow( to: .send( custodialAccount(CryptoTradingAccount.self, from: event), cryptoAccount(for: .send, from: event) ) ) } lazy var kyc = app.on(blockchain.ux.asset.account.require.KYC) { @MainActor [unowned self] _ in kycRouter.start(tier: .tier2, parentFlow: .coin) } lazy var activity = app.on(blockchain.ux.asset.account.activity) { @MainActor [unowned self] _ in self.topViewController.topMostViewController?.dismiss(animated: true) { self.app.post(event: blockchain.ux.home.tab[blockchain.ux.user.activity].select) } } lazy var website = app.on(blockchain.ux.asset.bio.visit.website) { @MainActor [application] event in try application.open(event.context.decode(blockchain.ux.asset.bio.visit.website.url, as: URL.self)) } lazy var explainerReset = app.on(blockchain.ux.asset.account.explainer.reset) { @MainActor [defaults] _ in defaults.removeObject(forKey: blockchain.ux.asset.account.explainer(\.id)) } // swiftlint:disable first_where func custodialAccount( _ type: BlockchainAccount.Type, from event: Session.Event ) async throws -> CryptoTradingAccount { try await coincore.cryptoAccounts( for: event.context.decode(blockchain.ux.asset.id), filter: .custodial ) .filter(CryptoTradingAccount.self) .first .or( throw: blockchain.ux.asset.error[] .error(message: "No trading account found for \(event.reference)") ) } func cryptoAccount( for action: AssetAction? = nil, from event: Session.Event ) async throws -> CryptoAccount { let accounts = try await coincore.cryptoAccounts( for: event.reference.context.decode(blockchain.ux.asset.id), supporting: action ) if let id = try? event.reference.context.decode(blockchain.ux.asset.account.id, as: String.self) { return try accounts.first(where: { account in account.identifier as? String == id }) .or( throw: blockchain.ux.asset.error[] .error(message: "No account found with id \(id)") ) } else { let appMode = app.currentMode switch appMode { case .legacy: return try(accounts.first(where: { account in account is TradingAccount }) ?? accounts.first(where: { account in account is NonCustodialAccount }) ) .or( throw: blockchain.ux.asset.error[] .error(message: "\(event) has no valid accounts for \(String(describing: action))") ) case .trading: return try(accounts.first(where: { account in account is TradingAccount })) .or( throw: blockchain.ux.asset.error[] .error(message: "\(event) has no valid accounts for \(String(describing: action))") ) case .defi: return try(accounts.first(where: { account in account is NonCustodialAccount })) .or( throw: blockchain.ux.asset.error[] .error(message: "\(event) has no valid accounts for \(String(describing: action))") ) } } } } extension FeatureCoinDomain.Account { init(_ account: CryptoAccount, _ fiatCurrency: FiatCurrency) { self.init( id: account.identifier, name: account.label, accountType: .init(account), cryptoCurrency: account.currencyType.cryptoCurrency!, fiatCurrency: fiatCurrency, receiveAddressPublisher: { account .receiveAddress .map(\.address) .eraseToAnyPublisher() }, actionsPublisher: { account.actions .map { actions in OrderedSet(actions.compactMap(Account.Action.init)) } .eraseToAnyPublisher() }, cryptoBalancePublisher: account.balance.ignoreFailure(), fiatBalancePublisher: account.fiatBalance(fiatCurrency: fiatCurrency).ignoreFailure() ) } } extension FeatureCoinDomain.Account.Action { // swiftlint:disable cyclomatic_complexity init?(_ action: AssetAction) { switch action { case .buy: self = .buy case .deposit: self = .exchange.deposit case .interestTransfer: self = .rewards.deposit case .interestWithdraw: self = .rewards.withdraw case .receive: self = .receive case .sell: self = .sell case .send: self = .send case .linkToDebitCard: return nil case .sign: return nil case .swap: self = .swap case .viewActivity: self = .activity case .withdraw: self = .exchange.withdraw } } } extension FeatureCoinDomain.Account.AccountType { init(_ account: CryptoAccount) { if account is TradingAccount { self = .trading } else if account is ExchangeAccount { self = .exchange } else if account is InterestAccount { self = .interest } else { self = .privateKey } } } extension FeatureCoinDomain.KYCStatus { init(_ kycStatus: UserState.KYCStatus) { switch kycStatus { case .unverified: self = .unverified case .inReview: self = .inReview case .silver: self = .silver case .silverPlus: self = .silverPlus case .gold: self = .gold } } } extension TransactionsRouterAPI { @discardableResult @MainActor func presentTransactionFlow(to action: TransactionFlowAction) async -> TransactionFlowResult? { try? await presentTransactionFlow(to: action).stream().next() } } extension CoincoreAPI { func cryptoAccounts( for cryptoCurrency: CryptoCurrency, supporting action: AssetAction? = nil, filter: AssetFilter = .all ) async throws -> [CryptoAccount] { try await cryptoAccounts(for: cryptoCurrency, supporting: action, filter: filter).stream().next() } }
lgpl-3.0
2fa5eea37a0b4ae15d9faed9732bd2f8
35.476091
132
0.58444
5.167894
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/BlockchainComponentLibrary/Sources/BlockchainComponentLibrary/3 - Compositions/PromoCard.swift
1
4766
// Copyright ยฉ Blockchain Luxembourg S.A. All rights reserved. import SwiftUI /// PromoCard from the Figma Component Library. /// /// # Figma /// /// [Cards](https://www.figma.com/file/nlSbdUyIxB64qgypxJkm74/03---iOS-%7C-Shared?node-id=209%3A7478) public struct PromoCard: View { private let title: String private let message: String private let icon: Icon private let control: Control? private let onCloseTapped: () -> Void /// Initialize a Promo Card /// - Parameters: /// - title: Title of the card /// - message: Message of the card /// - icon: Icon on top of the card /// - control: Control object containing the title and action of the Card's button /// - onCloseTapped: Closure executed when the user types the close icon public init( title: String, message: String, icon: Icon, control: Control? = nil, onCloseTapped: @escaping () -> Void ) { self.title = title self.message = message self.icon = icon self.control = control self.onCloseTapped = onCloseTapped } public var body: some View { VStack(alignment: .leading, spacing: 0) { HStack(alignment: .top) { icon .circle( backgroundColor: Color( light: .palette.blue000, dark: .palette.blue600 ) ) .accentColor( Color( light: .palette.blue600, dark: .palette.blue000 ) ) .frame(width: 32) Spacer() Button( action: onCloseTapped, label: { Icon.closev2 .circle( backgroundColor: Color( light: .semantic.medium, dark: .palette.grey800 ) ) .accentColor(.palette.grey400) .frame(width: 24) } ) } Spacer() .frame(height: 18) Text(title) .typography(.title3) .foregroundColor(.semantic.title) Spacer() .frame(height: control == nil ? 8 : 4) Text(message) .typography(.paragraph1) .foregroundColor(.semantic.title) .fixedSize(horizontal: false, vertical: true) if let control = control { Spacer() .frame(height: 16) PrimaryButton(title: control.title, action: control.action) } } .padding(Spacing.padding2) .background( RoundedRectangle(cornerRadius: Spacing.containerBorderRadius) .fill( Color( light: .semantic.background, dark: .palette.dark800 ) ) ) } } struct PromoCard_Previews: PreviewProvider { static var previews: some View { Group { PromoCard( title: "Welcome to Blockchain!", message: "This is your Portfolio view. Once you own and hold crypto, the balances display here.", icon: Icon.blockchain ) {} .previewLayout(.sizeThatFits) PromoCard( title: "Welcome to Blockchain!", message: "This is your Portfolio view. Once you own and hold crypto, the balances display here.", icon: Icon.blockchain ) {} .previewLayout(.sizeThatFits) .colorScheme(.dark) PromoCard( title: "Notify Me", message: "Get a notification when Uniswap is available to trade on Blockchain.com.", icon: Icon.notificationOn, control: Control(title: "Notify Me", action: {}) ) {} .previewLayout(.sizeThatFits) PromoCard( title: "Notify Me", message: "Get a notification when Uniswap is available to trade on Blockchain.com.", icon: Icon.notificationOn, control: Control(title: "Notify Me", action: {}) ) {} .previewLayout(.sizeThatFits) .colorScheme(.dark) } .frame(width: 375) } }
lgpl-3.0
2361906c28c9dec1c987f93bf4612d57
33.035714
113
0.466946
5.265193
false
false
false
false
itsaboutcode/WordPress-iOS
WordPressFlux/Sources/WordPressFlux/QueryStore.swift
2
6114
import Foundation private struct QueryRef<Query> { let query: Query let token = DispatchToken() init(_ query: Query) { self.query = query } } /// QueryStore provides a mechanism for Stores to keep track of queries by /// consumers and perform operations depending of those. /// /// A query in this context is a custom type that represents that a consumer is /// interested in a certain subset of the data that the store provides, and /// wants to get updates. The store can look at the activeQueries list and /// decide if it needs to fetch data from the network to satisfy those queries. /// /// Subclasses need to implement queriesChanged() and look at activeQueries and /// their internal state to decide if they need to act. /// /// If your `State` type confrorms to the `Codable` protocol, the `QueryStore` /// will transparently persist/load State and purge in-memory State when there are no /// longer any active `Queries` associated with the `Store`. //// /// You can also manually force writing out the state to disk by calling `persistState()`. /// open class QueryStore<State, Query>: StatefulStore<State>, Unsubscribable { private let initialState: State fileprivate var activeQueryReferences = [QueryRef<Query>]() { didSet { if activeQueryReferences.isEmpty, let encodableState = state as? Encodable, let url = try? type(of: self).persistenceURL() { // If we don't have any active queries, and the `state` conforms to `Encodable`, let's use this as our cue to persist the data // to disk and get rid of the in-memory cache. do { try encodableState.saveJSON(at: url) inMemoryState = nil } catch { logError("[\(type(of: self)) Error] \(error)") } } queriesChanged() } } /// In-memory storage for `state`. private var inMemoryState: State? /// Facade for the `state`. /// /// It allows for the lazy-loading of `state` from disk, when `State` conforms to `Codable`. override public final var state: State { get { // If the in-memory State is populated, just return that. if let inMemoryState = inMemoryState { return inMemoryState } // If we purged the in-memory `State` and the `Store` is being asked to do // work again, let's try to reinitialise it from disk. guard let codableInitialState = initialState as? Codable else { // If it's not `Codable`, there's nothing we can do. return initialState } do { let persistenceURL = try type(of: self).persistenceURL() if let persistedState = try type(of: codableInitialState).loadJSON(from: persistenceURL) as? State { // When reading from disk has succeeded, set the result as `inMemoryState` and return it. inMemoryState = persistedState return persistedState } else { // If there isn't a state for us to read from disk, but there wasn't any error thrown, // let's just return the initial state too. return initialState } } catch { // If reading persisted state fails, let's just fail over to `initialState`. logError("[\(type(of: self)) Error] \(error)") return initialState } } set { inMemoryState = newValue emitStateChange(old: state, new: newValue) } } /// A list of active queries. /// public var activeQueries: [Query] { return activeQueryReferences.map({ $0.query }) } override public init(initialState: State, dispatcher: ActionDispatcher = .global) { self.initialState = initialState super.init(initialState: initialState, dispatcher: dispatcher) } /// Registers a query with the store. /// /// The query will be active as long as the consumer keeps a reference to /// the Receipt. public func query(_ query: Query) -> Receipt { let queryRef = QueryRef(query) activeQueryReferences.append(queryRef) return Receipt(token: queryRef.token, owner: self) } /// Unregisters the query associated with the given Receipt. /// public func unsubscribe(receipt: Receipt) { guard let index = activeQueryReferences.firstIndex(where: { $0.token == receipt.token }) else { assertionFailure("Stopping a query that's not active") return } activeQueryReferences.remove(at: index) } /// This method is called when the activeQueries list changes. /// /// Subclasses should implement this method and perform any necessary /// operations here. /// open func queriesChanged() { // Subclasses should implement this } /// Closure used to log errors. /// Default implementation calls `NSLog`, subclasses may find it useful /// to override it to use a custom logging method. open func logError(_ error: String) { NSLog(error) } } private extension QueryStore { private static func persistenceURL() throws -> URL { let filename = "\(String(describing: self)).json" let documentsPath = try FileManager.default.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true) let targetURL = documentsPath.appendingPathComponent(filename) return targetURL } } extension QueryStore where State: Encodable { public func persistState() throws { guard let url = try? type(of: self).persistenceURL() else { return } try state.saveJSON(at: url) } }
gpl-2.0
95b1a1e85c0239d005e5206430d3c19d
34.964706
142
0.597808
4.950607
false
false
false
false
gavinpardoe/DEP-Enrolment
DEP-Enrolment/MainWindowController.swift
1
2166
// // MainWindowController.swift // DEP-Enrolment // // Created by Gavin on 05/11/2016. // Copyright ยฉ 2016 Trams Ltd. All rights reserved. // // Designed for Use with Jamf Pro. // // The MIT License (MIT) // // Copyright (c) 2016 Gavin Pardoe // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF // CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // import Cocoa class MainWindowController: NSWindowController { override func windowDidLoad() { super.windowDidLoad() // Set Window Background Colour as White window?.backgroundColor = NSColor.white // Get Screen Size as NSRect, Set Windows Size as Percent of Screen Size let screenSize: NSRect = (NSScreen.main()?.frame)! let percent: CGFloat = 1.0 let offset: CGFloat = (1.0-percent)/2.0 self.window!.setFrame(NSMakeRect(screenSize.size.width*offset, screenSize.size.height*offset, screenSize.size.width*percent, screenSize.size.height*percent), display: true) // Set Window Level self.window!.level = Int(CGWindowLevelForKey(.statusWindow)) self.window!.makeKeyAndOrderFront(nil) } }
mit
7f4e9546ae186ee7f1c505559372b5e8
41.45098
180
0.706697
4.529289
false
false
false
false
CGLueng/DYTV
DYZB/DYZB/Classes/Main/Controller/BasicAnchorViewController.swift
1
4170
// // BasicAnchorViewController.swift // DYZB // // Created by CGLueng on 2016/12/24. // Copyright ยฉ 2016ๅนด com.ruixing. All rights reserved. // import UIKit private let kItemMargin : CGFloat = 10 private let kItemW = (kScreenW - 3 * kItemMargin) * 0.5 private let kNormalItemH = kItemW * 3 / 4 private let kPrettyItemH = kItemW * 4 / 3 private let kheaderH : CGFloat = 50 private let kCycleViewH = kScreenW * 3 / 8 private let kGameViewH : CGFloat = 90 private let kNormalCellID = "kNormalCellID" private let kPrettyCellID = "kPrettyCellID" private let kHeaderViewID = "kHeaderViewID" class BasicAnchorViewController: UIViewController { // MARK:- ๅฎšไน‰ๅฑžๆ€ง var basicVM : BasicViewModel! lazy var collectionView : UICollectionView = {[unowned self] in //ๅˆ›ๅปบๅธƒๅฑ€ let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: kItemW, height: kNormalItemH) layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = kItemMargin layout.headerReferenceSize = CGSize(width: kScreenW, height: kheaderH) layout.sectionInset = UIEdgeInsets(top: 0, left: kItemMargin, bottom: 0, right: kItemMargin) //ๅˆ›ๅปบcollectionview let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout) collectionView.backgroundColor = UIColor.white collectionView.dataSource = self collectionView.delegate = self //ๅฎฝ้ซ˜้š็€็ˆถๆŽงไปถๆ‹‰ไผธ่€Œๆ‹‰ไผธ collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth] //ๆณจๅ†Œ cell // collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: kNormalCellID) collectionView.register(UINib(nibName: "CollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: kNormalCellID) collectionView.register(UINib(nibName: "CollectionPrettyCell", bundle: nil), forCellWithReuseIdentifier: kPrettyCellID) //ๆณจๅ†Œ็ป„ๅคด // collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID) collectionView.register(UINib(nibName: "HomeCollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID) return collectionView }() // MARK:- ็ณป็ปŸๅ›ž่ฐƒ override func viewDidLoad() { super.viewDidLoad() setupUI() loadData() } } // MARK:- ่ฎพ็ฝฎ UI extension BasicAnchorViewController { func setupUI() { view.addSubview(collectionView) } } // MARK:- ่ฏทๆฑ‚ๆ•ฐๆฎ extension BasicAnchorViewController { func loadData() { } } // MARK:- ้ตๅฎˆ UIcollectionview ็š„ๆ•ฐๆฎๆบ extension BasicAnchorViewController : UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return basicVM.anchorGroups.count } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return basicVM.anchorGroups[section].anchorArr.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalCellID, for: indexPath) as! CollectionNormalCell //่ฎพ็ฝฎๆ•ฐๆฎ cell.anchor = basicVM.anchorGroups[indexPath.section].anchorArr[indexPath.item] return cell; } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let headView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderViewID, for: indexPath) as! HomeCollectionHeaderView headView.group = basicVM.anchorGroups[indexPath.section] return headView } } // MARK:- ้ตๅฎˆ UIcollectionview ็š„ไปฃ็† extension BasicAnchorViewController : UICollectionViewDelegate { }
mit
0bf47197de60719b9d2fc07d07191f48
36.953271
190
0.721005
5.578297
false
false
false
false
zqw87699/FXViewContextSwift
Classes/Extension/FXLineView.swift
1
3819
// // FXLineView.swift // TTSwift // // Created by ๅผ ๅคงๅฎ— on 2017/5/26. // Copyright ยฉ 2017ๅนด ๅผ ๅคงๅฎ—. All rights reserved. // import Foundation import UIKit import FXCommonSwift /** * ็บฟๆก็ป˜ๅˆถไฝ็ฝฎ */ enum FXLineDrawPosition:Int { /** * ๅž‚็›ดๅฑ…ไธญ */ case FXLineDrawPositionVerticalCenter = 0 /** * ๆฐดๅนณๅฑ…ไธญ */ case FXLineDrawPositionHorizontalCenter = 1 /** * ๅบ•้ƒจ */ case FXLineDrawPositionBottom = 2 /** * ้กถ้ƒจ */ case FXLineDrawPositionTop = 3 /** * ๅทฆ่พน */ case FXLineDrawPositionLeft = 4 /** * ๅณ่พน */ case FXLineDrawPositionRight = 5 } /** * ็บฟๆกๆ ทๅผ */ enum FXLineStyle:Int { /** * ๅฎž็บฟ */ case FXLineStyleSolid = 0 /** * ่™š็บฟ */ case FXLineStyleDotted = 1 } /** * ็บฟๆก่ง†ๅ›พ */ class FXLineView:BaseFXView{ /** * ็บฟๆก้ขœ่‰ฒ */ var lineColor:UIColor = UIColor.gray{ didSet { self.setNeedsDisplay() } } /** * ๆ˜ฏๅฆๆฐดๅนณ */ var drawPosition:FXLineDrawPosition = .FXLineDrawPositionVerticalCenter{ didSet { self.setNeedsDisplay() } } /** * ็บฟๆกๆ ทๅผ */ var lineStyle:FXLineStyle = .FXLineStyleSolid /** * ็บฟๆกๅฎฝๅบฆ * default 1/scale */ var lineWidth:CGFloat = 1.0/UIScreen.main.scale{ didSet{ if self.lineWidth < 0{ self.lineWidth = 0 } self.setNeedsDisplay() } } override func fx_loadView() { super.fx_loadView() self.backgroundColor = UIColor.clear } override func draw(_ rect: CGRect) { let context = UIGraphicsGetCurrentContext() if context != nil { context?.setLineCap(CGLineCap.butt) //CGContext.setLineCap(context!) if self.lineStyle == FXLineStyle.FXLineStyleDotted { let lenghts:Array<CGFloat> = [5,5] context?.setLineDash(phase: 0, lengths: lenghts) } context?.setLineWidth(self.lineWidth) context?.setStrokeColor(self.lineColor.cgColor) context?.beginPath() switch self.drawPosition { case .FXLineDrawPositionVerticalCenter: context?.move(to: CGPoint.init(x: (self.bounds.size.width-self.lineWidth)/2.0, y: 0)) case .FXLineDrawPositionHorizontalCenter: context?.move(to: CGPoint.init(x: 0, y: (self.bounds.size.height-self.lineWidth)/2.0)) context?.addLine(to: CGPoint.init(x: self.bounds.size.width, y: (self.bounds.size.height-self.lineWidth)/2.0)) case .FXLineDrawPositionTop: context?.move(to: CGPoint.init(x: 0, y: self.lineWidth/2.0)) context?.addLine(to: CGPoint.init(x: self.bounds.size.width, y: self.lineWidth/2.0)) case .FXLineDrawPositionLeft: context?.move(to: CGPoint.init(x: self.lineWidth/2.0, y: 0)) context?.addLine(to: CGPoint.init(x: self.lineWidth/2.0, y: self.bounds.size.height)) case .FXLineDrawPositionRight: context?.move(to: CGPoint.init(x: self.bounds.size.width-self.lineWidth/2.0, y: 0)) context?.addLine(to: CGPoint.init(x: self.bounds.size.width-self.lineWidth/2.0, y: self.bounds.size.height)) case .FXLineDrawPositionBottom: context?.move(to: CGPoint.init(x: 0, y: self.bounds.size.height-self.lineWidth/2.0)) context?.addLine(to: CGPoint.init(x: self.bounds.size.width, y: self.bounds.size.height-self.lineWidth/2.0)) } context?.strokePath() } } }
mit
f4f4540898024603095fa3d02c5f0ead
26.036496
126
0.561015
3.752786
false
false
false
false
jdbateman/Lendivine
Lendivine/LoansTableViewController.swift
1
18168
// // LoansTableViewController.swift // Lendivine // // Created by john bateman on 11/12/15. // Copyright ยฉ 2015 John Bateman. All rights reserved. // // This table view controller displays a list of loans queried from the kiva REST API. import UIKit import CoreData import SafariServices class LoansTableViewController: DVNTableViewController, NSFetchedResultsControllerDelegate, SFSafariViewControllerDelegate { override func viewDidLoad() { super.viewDidLoad() CoreDataLoanHelper.cleanup() // Initialize the fetchResultsController from the core data store. let loanCount = fetchLoans() if loanCount == 0 { // There are no persisted loans. Let's request some new ones from Kiva. onAddLoansButtonTap() } // set the NSFetchedResultsControllerDelegate fetchedResultsController.delegate = self configureBarButtonItems() navigationItem.title = "Loans" navigationController?.navigationBar.barTintColor = UIColor(rgb:0xFFE8A1) navigationController?.navigationBar.translucent = false initRefreshControl() KivaCart.updateCartBadge(self) } /*! hide the status bar */ override func prefersStatusBarHidden() -> Bool { return true } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) //self.removeAllLoans() fetchedResultsController.delegate = nil } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: view setup /*! Setup the nav bar button items. */ func configureBarButtonItems() { // left bar button items let trashButton = UIBarButtonItem(barButtonSystemItem: .Trash, target: self, action: #selector(LoansTableViewController.onTrashButtonTap)) navigationItem.setLeftBarButtonItems([trashButton], animated: true) // right bar button items let mapButton = UIBarButtonItem(image: UIImage(named: "earth-america-7"), style: .Plain, target: self, action: #selector(LoansTableViewController.onMapButton)) let addLoansButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: #selector(LoansTableViewController.onAddLoansButtonTap)) navigationItem.setRightBarButtonItems([mapButton, addLoansButton], animated: true) } func initRefreshControl() { let refreshControl = UIRefreshControl() refreshControl.tintColor = UIColor.whiteColor() refreshControl.transform = CGAffineTransformMakeScale(2.0, 2.0) refreshControl.addTarget(self, action: #selector(LoansTableViewController.onPullToRefresh(_:)), forControlEvents: .ValueChanged) self.tableView.addSubview(refreshControl) self.tableView.alwaysBounceVertical = true } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 // return self.fetchedResultsController.sections?.count ?? 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let sectionInfo = self.fetchedResultsController.sections![section] let count = sectionInfo.numberOfObjects navigationItem.title = "\(count) Loans" return count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("LoansTableViewCellID", forIndexPath: indexPath) as! LoansTableViewCell // Configure the cell... configureCell(cell, indexPath: indexPath) cell.parentTableView = tableView cell.parentController = self return cell } // Initialize the contents of the cell. func configureCell(cell: LoansTableViewCell, indexPath: NSIndexPath) { let loan = self.fetchedResultsController.objectAtIndexPath(indexPath) as! KivaLoan if loan.id == -1 { CoreDataContext.sharedInstance().scratchContext.deleteObject(loan) return } if let name = loan.name { cell.nameLabel.text = name } if let sector = loan.sector { cell.sectorLabel.text = sector } var amountString = "$" if let loanAmount = loan.loanAmount { amountString.appendContentsOf(loanAmount.stringValue) } else { amountString.appendContentsOf("0") } cell.amountLabel.text = amountString if let _ = loan.country { cell.countryLabel.text = loan.country } // Set placeholder image cell.loanImageView.image = UIImage(named: "Download-50") // put rounded corners on loan image cell.loanImageView.layer.cornerRadius = 20 cell.loanImageView.layer.borderWidth = 0 cell.loanImageView.layer.borderColor = UIColor.clearColor().CGColor cell.loanImageView.clipsToBounds = true let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .WhiteLarge) activityIndicator.center = CGPointMake(cell.loanImageView.center.x - 8, cell.loanImageView.center.y - 20) cell.loanImageView.addSubview(activityIndicator) activityIndicator.startAnimating() loan.getImage(200, height:200, square:true) { success, error, image in dispatch_async(dispatch_get_main_queue()) { activityIndicator.stopAnimating() } if success { dispatch_async(dispatch_get_main_queue()) { cell.loanImageView!.image = image } } else { print("error retrieving image: \(error)") } } let cart = KivaCart.sharedInstance if let id = loan.id { cell.donatedImageView.hidden = cart.containsLoanId(id) ? false : true } } // MARK: - Fetched results controller lazy var fetchedResultsController: NSFetchedResultsController = { // Create the fetch request let fetchRequest = NSFetchRequest(entityName: KivaLoan.entityName) // Add a sort descriptor to enforce a sort order on the results. fetchRequest.sortDescriptors = [NSSortDescriptor(key: "id", ascending: false)] // Create the Fetched Results Controller let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: CoreDataContext.sharedInstance().scratchContext, sectionNameKeyPath: nil, cacheName: nil) // Return the fetched results controller. It will be the value of the lazy variable return fetchedResultsController } () /* Perform a fetch of Loan objects to update the fetchedResultsController with the current data from the core data store. */ func fetchLoans() -> Int { var error: NSError? = nil CoreDataContext.sharedInstance().scratchContext.reset() do { try fetchedResultsController.performFetch() } catch let error1 as NSError { error = error1 } if let error = error { LDAlert(viewController:self).displayErrorAlertView("Error retrieving loans", message: "Unresolved error in fetchedResultsController.performFetch \(error), \(error.userInfo)") } else { let sectionInfo = self.fetchedResultsController.sections![0] let count = sectionInfo.numberOfObjects navigationItem.title = "\(count) Loans" return count } return 0 } // MARK: NSFetchedResultsControllerDelegate // Any change to Core Data causes these delegate methods to be called. func controllerWillChangeContent(controller: NSFetchedResultsController) { // store up changes to the table until endUpdates() is called self.tableView.beginUpdates() } func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) { // Our project does not use sections. So we can ignore these invocations. } func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { switch type { case .Insert: tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade) case .Delete: tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) case .Update: self.configureCell(tableView.cellForRowAtIndexPath(indexPath!) as! LoansTableViewCell, indexPath: indexPath!) case .Move: tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade) } } func controllerDidChangeContent(controller: NSFetchedResultsController) { // Make the stored changes visible. self.tableView.endUpdates() } // MARK: Actions // OAuth button was selected. func onTrashButtonTap() { removeAllLoans() self.resetNextKivaPage() self.fetchLoans() self.tableView.reloadData() } // OAuth with Kiva.org. Login happens on Kiva website and is redirected to Lendivine app once an OAuth access token is granted. func doOAuth() { let kivaOAuth = KivaOAuth.sharedInstance // Do the oauth in a background queue. dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0)) { kivaOAuth.doOAuthKiva(self) {success, error, kivaAPI in if success { self.kivaAPI = kivaOAuth.kivaAPI } else { print("kivaOAuth failed. Unable to acquire kivaAPI handle.") } // Call oAuthCompleted on main queue. dispatch_async(dispatch_get_main_queue()) { self.oAuthCompleted(success) } } } } func oAuthCompleted(success: Bool) { print("OAuth completed with success = \(success)") } func onMapButton() { presentMapController() } func onCartButton() { // Display local Cart VC containing only the loans in the cart. let storyboard = UIStoryboard (name: "Main", bundle: nil) let controller: CartTableViewController = storyboard.instantiateViewControllerWithIdentifier("CartStoryboardID") as! CartTableViewController controller.kivaAPI = self.kivaAPI self.presentViewController(controller, animated: true, completion: nil) // 2. TODO - modify security keys in info.plist to get kiva.org cart to render correctly. currently <key>NSAllowsArbitraryLoads</key> <true/> is set to get around the security restriction. To fix look at http://stackoverflow.com/questions/30731785/how-do-i-load-an-http-url-with-app-transport-security-enabled-in-ios-9 and enable appropriate options then remove the workaround above. } /*! Display url in an embeded webkit browser. */ func showEmbeddedBrowser() { let controller = KivaCartViewController() if let _ = self.kivaAPI { controller.request = self.kivaAPI!.getKivaCartRequest() } self.presentViewController(controller, animated: true, completion: nil) } /*! See More Loans..." button was selected. */ @IBAction func seeMoreLoans(sender: AnyObject) { refreshLoans(nil) } /*! Refresh button was selected. */ func onAddLoansButtonTap() { refreshLoans(nil) } func onPullToRefresh(refreshControl: UIRefreshControl) { let myAttribute = [ NSFontAttributeName: UIFont(name: "Georgia", size: 10.0)! ] refreshControl.attributedTitle = NSAttributedString(string: "Searching for Loans...", attributes: myAttribute) refreshLoans() { success, error in refreshControl.endRefreshing() } } // MARK: Helpfer functions /*! @brief Get loans from Kiva.org. @discussion Loans are persisted to disk and refetched into the sharedContext. */ func refreshLoans(completionHandler: ((success: Bool, error: NSError?) -> Void)? ) { // Search Kiva.org for the next page of Loan results. self.populateLoans(LoansTableViewController.KIVA_LOAN_SEARCH_RESULTS_PER_PAGE) { success, error in // refetch irrespective or result. self.fetchLoans() self.tableView.reloadData() if success { dispatch_async(dispatch_get_main_queue()) { if let completionHandler = completionHandler { completionHandler(success:true, error: nil) } } } else { if (error != nil) && ((error?.code)! == -1009) && (error?.localizedDescription.containsString("offline"))! { LDAlert(viewController: self).displayErrorAlertView("No Internet Connection", message: (error?.localizedDescription)!) } print("failed to populate loans. error: \(error?.localizedDescription)") if let completionHandler = completionHandler { completionHandler(success:false, error: error) } } } } /*! Reload loans from Core Data. Note: placeholder. In future if we want to say fire a notification when items are removed from the cart we could respond here by refetching the loans and removing them from this scree. Chose not to implement this interaction flow with the data for the first version. */ // func reloadLoansFromCoreData() { // //TODO // } /*! Remove all loans from the scratch context. */ func removeAllLoans() { if let loans = self.fetchAllLoans() { let cart = KivaCart.sharedInstance var inCartCount = 0 for loan: KivaLoan in loans { if let id = loan.id where (cart.containsLoanId(id) == false) { CoreDataContext.sharedInstance().scratchContext.deleteObject(loan) } else { inCartCount += 1 } } CoreDataContext.sharedInstance().saveScratchContext() CoreDataLoanHelper.cleanup() if inCartCount > 0 { LDAlert(viewController:self).displayErrorAlertView("Loans in Cart", message: "Loans in the cart were not deleted.\n\n Once a loan is removed from the cart it can be removed from the Loans screen.") } } } /* @brief Perform a fetch of all the loan objects in the scratch context. Return array of KivaLoan instances, or an empty array if no results or query failed. @discussion Updates the fetchedResultsController with the matching data from the core data store. */ func fetchAllLoans() -> [KivaLoan]? { let error: NSErrorPointer = nil let fetchRequest = NSFetchRequest(entityName: KivaLoan.entityName) fetchRequest.sortDescriptors = [NSSortDescriptor(key: "id", ascending: false)] var results: [AnyObject]? do { results = try CoreDataContext.sharedInstance().scratchContext.executeFetchRequest(fetchRequest) as? [KivaLoan] } catch let error1 as NSError { error.memory = error1 print("Error in fetchAllLoans(): \(error)") return nil } // Check for Errors if error != nil { print("Error in fetchAllLoans(): \(error)") } return results as? [KivaLoan] ?? [KivaLoan]() } // MARK: Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "ShowDetail" { if let indexPath = self.tableView.indexPathForSelectedRow { let controller = segue.destinationViewController as! LoanDetailViewController if let loan = self.fetchedResultsController.objectAtIndexPath(indexPath) as? KivaLoan { controller.loan = loan } } } else if segue.identifier == "LoansToMapSegueId" { navigationItem.title = "Loans" let controller = segue.destinationViewController as! LoansMapViewController controller.sourceViewController = self // get list of loans displayed in this view controller if let loans = self.fetchAllLoans() { controller.loans = loans } } } /* Modally present the MapViewController on the main thread. */ func presentMapController() { dispatch_async(dispatch_get_main_queue()) { self.performSegueWithIdentifier("LoansToMapSegueId", sender: self) } } }
mit
2e686c73ecf71332d24b5dd456799dcc
36.305955
391
0.6192
5.424604
false
false
false
false
modulo-dm/modulo
Modules/ELFoundation/ELFoundationTests/NSObjectTests.swift
3
890
// // NSObjectTests.swift // ELFoundation // // Created by Sam Grover on 2/1/16. // Copyright ยฉ 2016 WalmartLabs. All rights reserved. // import XCTest import ELFoundation class NSObjectTests: XCTestCase { class Foo: NSObject { } override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testStaticBundle() { XCTAssertTrue("com.walmartlabs.ELFoundationTests" == Foo.bundle().bundleIdentifier!) } func testBundle() { let foo = Foo() XCTAssertTrue("com.walmartlabs.ELFoundationTests" == foo.bundle().bundleIdentifier!) } }
mit
e2f8bba1d2c8a0e9ff1bf544f857770b
23.027027
111
0.64117
4.37931
false
true
false
false
plus44/hcr-2016
app/Carthage/Checkouts/SwiftyJSON/Tests/SwiftyJSONTests/StringTests.swift
4
2457
// StringTests.swift // // Copyright (c) 2014 - 2016 Pinglin Tang // // 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 XCTest import SwiftyJSON class StringTests: XCTestCase { func testString() { //getter var json = JSON("abcdefg hijklmn;opqrst.?+_()") XCTAssertEqual(json.string!, "abcdefg hijklmn;opqrst.?+_()") XCTAssertEqual(json.stringValue, "abcdefg hijklmn;opqrst.?+_()") json.string = "12345?67890.@#" XCTAssertEqual(json.string!, "12345?67890.@#") XCTAssertEqual(json.stringValue, "12345?67890.@#") } func testURL() { let json = JSON("http://github.com") XCTAssertEqual(json.URL!, URL(string:"http://github.com")!) } func testBool() { let json = JSON("true") XCTAssertTrue(json.boolValue) } func testBoolWithY() { let json = JSON("Y") XCTAssertTrue(json.boolValue) } func testBoolWithT() { let json = JSON("T") XCTAssertTrue(json.boolValue) } func testURLPercentEscapes() { let emDash = "\\u2014" let urlString = "http://examble.com/unencoded" + emDash + "string" let encodedURLString = urlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) let json = JSON(urlString) XCTAssertEqual(json.URL!, URL(string: encodedURLString!)!, "Wrong unpacked ") } }
apache-2.0
76d5ee0c2b9c267e3ee3c5c183bbfeba
36.227273
115
0.677656
4.491773
false
true
false
false
lionheart/QuickTableView
Pod/Extensions/QuickTableViewRow.swift
1
2303
// // Copyright 2016 Lionheart Software LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit public extension QuickTableViewRow where Self: RawRepresentable, Self.RawValue == Int { init(at indexPath: IndexPath) { self.init(at: indexPath.row) } init(at row: Int) { self.init(rawValue: row)! } static var count: Int { return lastRow.rawValue + 1 } static var lastRow: Self { var row = Self(rawValue: 0)! for i in 0..<Int.max { guard let _row = Self(rawValue: i) else { return row } row = _row } return row } } public extension QuickTableViewRowWithConditions where Self: RawRepresentable, Self.RawValue == Int { init(at indexPath: IndexPath, container: Container) { self.init(at: indexPath.row, container: container) } init(at row: Int, container: Container) { var row = row let _conditionalRows = Self.conditionalRows(for: container) for (conditionalRow, test) in _conditionalRows { if row >= conditionalRow.rawValue && !test { row += 1 } } self.init(rawValue: row)! } static func index(row: Self, container: Container) -> Int? { for i in 0..<count(for: container) { if row == Self(at: i, container: container) { return i } } return nil } static func count(for container: Container) -> Int { var count = lastRow.rawValue + 1 let _conditionalRows = conditionalRows(for: container) for (_, test) in _conditionalRows { if !test { count -= 1 } } return count } }
apache-2.0
98336a56cde304f07915a714380e6b22
27.085366
101
0.594008
4.280669
false
false
false
false
BenedictC/SwiftJSONReader
JSONReader/JSONReader/JSONPath.swift
1
12365
// // JSONReader.swift // JSONReader // // Created by Benedict Cohen on 28/11/2015. // Copyright ยฉ 2015 Benedict Cohen. All rights reserved. // import Foundation //MARK:- JSONPath Definition /** JSONPath represents a path through a tree of JSON objects. TODO: Write a grammer of a path */ public struct JSONPath { public enum Component { case text(String) case numeric(Int64) case selfReference } public let components: [Component] //MARK: Instance life cycle public init(components: [Component]) { self.components = components } } //MARK:- Text Representation extension JSONPath.Component { public var textRepresentation: String { switch self { case .numeric(let i): return "[\(i)]" case .selfReference: return "[self]" case .text(let text): return encodeStringAsSubscriptRepresentation(text) } } private func encodeStringAsSubscriptRepresentation(_ text: String) -> String { let mutableText = NSMutableString(string: text) //Note that the order of the replacements is significant. We must replace '`' first otherwise our replacements will get replaced. mutableText.replaceOccurrences(of: "`", with: "``", options: [], range: NSRange(location: 0, length: mutableText.length)) mutableText.replaceOccurrences(of: "'", with: "`'", options: [], range: NSRange(location: 0, length: mutableText.length)) return "['\(mutableText)']" } } extension JSONPath { public var textRepresentation: String { var description = "" for component in components { switch component { case .text(let text): description += "['\(text)']" break case .numeric(let number): description += "[\(number)]" case .selfReference: description += "[self]" } } return description } } //MARK:- Equatable extension JSONPath: Equatable { } public func ==(lhs: JSONPath, rhs: JSONPath) -> Bool { return lhs.components == rhs.components } extension JSONPath.Component: Equatable { fileprivate func asTuple()-> (text: String?, number: Int64?, isSelfReference: Bool) { switch self { case .text(let text): return (text, nil, false) case .numeric(let number): return (nil, number, false) case .selfReference: return (nil, nil, true) } } } public func ==(lhs: JSONPath.Component, rhs: JSONPath.Component) -> Bool { let lhsValues = lhs.asTuple() let rhsValues = rhs.asTuple() return lhsValues.text == rhsValues.text && lhsValues.number == rhsValues.number && lhsValues.isSelfReference == rhsValues.isSelfReference } //MARK:- Debug Description extension JSONPath: CustomDebugStringConvertible, CustomStringConvertible { public var description: String { return textRepresentation } public var debugDescription: String { return textRepresentation } } extension JSONPath.Component: CustomDebugStringConvertible { public var description: String { return textRepresentation } public var debugDescription: String { return textRepresentation } } //MARK:- Path parsing extension JSONPath { public enum ParsingError: Error { //TODO: Add details to these errors (location, expect input etc) case expectedComponent case invalidSubscriptValue case expectedEndOfSubscript case unexpectedEndOfString } fileprivate static func componentsInPath(_ path: String) throws -> [Component] { var components = [Component]() try JSONPath.enumerateComponentsInPath(path) { component, componentIdx, stop in components.append(component) } return components } public static func enumerateComponentsInPath(_ JSONPath: String, enumerator: (_ component: Component, _ componentIdx: Int, _ stop: inout Bool) throws -> Void) throws { let scanner = Scanner(string: JSONPath) scanner.charactersToBeSkipped = nil //Don't skip whitespace! var componentIdx = 0 repeat { let component = try scanComponent(scanner) //Call the enumerator var stop = false try enumerator(component, componentIdx, &stop) if stop { return } //Prepare for next loop componentIdx += 1 } while !scanner.isAtEnd //Done without error } private static func scanComponent(_ scanner: Scanner) throws -> Component { if let component = try scanSubscriptComponent(scanner) { return component } if let component = try scanIdentifierComponent(scanner) { return component } throw ParsingError.expectedComponent } private static func scanSubscriptComponent(_ scanner: Scanner) throws -> Component? { let result: Component //Is it subscript? let isSubscript = scanner.scanString("[", into: nil) guard isSubscript else { return nil } //Scan the value var idx: Int64 = 0 var text: String = "" switch scanner { case (_) where scanner.scanInt64(&idx): result = .numeric(idx) case (_) where scanner.scanString("self", into: nil): result = .selfReference case (_) where try scanSingleQuoteDelimittedString(scanner, string: &text): result = .text(text) default: throw ParsingError.invalidSubscriptValue } //Close the subscript guard scanner.scanString("]", into: nil) else { throw ParsingError.expectedEndOfSubscript } consumeOptionalTraillingDot(scanner) return result } private static let headCharacters = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_") private static let bodyCharacters: CharacterSet = { let mutableCharacterSet = NSMutableCharacterSet(charactersIn: "0123456789") mutableCharacterSet.formUnion(with: headCharacters) return mutableCharacterSet as CharacterSet }() private static func scanIdentifierComponent(_ scanner: Scanner) throws -> Component? { //Technically there are a lot more unicode code points that are acceptable, but we go for 99+% of JSON keys. //See on https://mathiasbynens.be/notes/javascript-properties. var identifier = "" var headFragment: NSString? guard scanner.scanCharacters(from: headCharacters, into: &headFragment) else { return nil } identifier.append(headFragment as! String) var bodyFragment: NSString? if scanner.scanCharacters(from: bodyCharacters, into: &bodyFragment) { identifier.append(bodyFragment as! String) } consumeOptionalTraillingDot(scanner) return .text(identifier) } private static let dotCharacterSet = CharacterSet(charactersIn: ".") private static func consumeOptionalTraillingDot(_ scanner: Scanner) { scanner.scanCharacters(from: dotCharacterSet, into: nil) } private static let subScriptDelimiters = CharacterSet(charactersIn: "`'") private static func scanSingleQuoteDelimittedString(_ scanner: Scanner, string: inout String) throws -> Bool { guard scanner.scanString("'", into: nil) else { return false } var text = "" mainLoop: while !scanner.isAtEnd { //Scan normal text var fragment: NSString? let didScanFragment = scanner.scanUpToCharacters(from: subScriptDelimiters, into:&fragment) if didScanFragment, let fragment = fragment as? String { text.append(fragment) } //Scan escape sequences escapeSequenceLoop: while true { if scanner.scanString("`'", into: nil) { text.append("'") } else if scanner.scanString("``", into: nil) { text.append("`") } else if scanner.scanString("`", into: nil) { text.append("`") //This is technically an invalid escape sequence but we're forgiving. } else { break escapeSequenceLoop } } //Attempt to scan the closing delimiter if scanner.scanString("'", into: nil) { //Done! string = text return true } } throw JSONPath.ParsingError.unexpectedEndOfString } } //MARK:- Initialization from string extension JSONPath { //MARK: Component caching /// A cache of the values of each component of a path. //The key is the path and the value is an array of NSNumber, NSString and NSNull which represent .numeric, .text and .selfReference respectively. private static let componentsCache = NSCache<NSString, NSArray>() private static func componentsForStringRepresentation(_ string: String) -> [Component]? { guard let foundationComponents = JSONPath.componentsCache.object(forKey: string as NSString) as? [AnyObject] else { return nil } let components = foundationComponents.map({ object -> Component in //The cache can't store enums so we have to map back from AnyObject switch object { case is NSNumber: return Component.numeric(object.int64Value) case is NSString: return Component.text(object as! String) case is NSNull: return Component.selfReference default: fatalError("Unexpected type in component cache.") } }) return components } private static func setComponents(_ components: [Component], forStringRepresentation string: String) { //We can't store an array of enums in an NSCache so we map to an array of AnyObject. let foundationComponents = components.map({ component -> AnyObject in switch component { case .numeric(let number): return NSNumber(value: number) case .text(let text): return NSString(string: text) case .selfReference: return NSNull() } }) JSONPath.componentsCache.setObject(foundationComponents as NSArray, forKey: string as NSString) } //MARK: Initialization public init(path: String) throws { let components: [Component] //Attempt to read from cache... if let cachedComponents = JSONPath.componentsForStringRepresentation(path) { components = cachedComponents } else { //...create and update cache value if value not found in cache. components = try JSONPath.componentsInPath(path) JSONPath.setComponents(components, forStringRepresentation: path) } self.init(components: components) } } //MARK:- StringLiteralConvertible extension JSONPath: ExpressibleByStringLiteral { public init(stringLiteral path: StringLiteralType) { do { try self.init(path: path) } catch let error { fatalError("String literal does not represent a valid JSONPath. Error: \(error)") } } public typealias ExtendedGraphemeClusterLiteralType = StringLiteralType public init(extendedGraphemeClusterLiteral path: ExtendedGraphemeClusterLiteralType) { do { try self.init(path: path) } catch let error { fatalError("String literal does not represent a valid JSONPath. Error: \(error)") } } public typealias UnicodeScalarLiteralType = String public init(unicodeScalarLiteral path: UnicodeScalarLiteralType) { do { try self.init(path: "\(path)") } catch let error { fatalError("String literal does not represent a valid JSONPath. Error: \(error)") } } }
mit
a668581bf5bd6123671f8d4b555f96a8
27.422989
171
0.616952
5.162422
false
false
false
false
HesterJ14/ioscreator
SpriteKitSwiftScenesTutorial/SpriteKitSwiftScenesTutorial/GameScene.swift
4
1382
// // GameScene.swift // SpriteKitSwiftScenesTutorial // // Created by Arthur Knopper on 25/01/15. // Copyright (c) 2015 Arthur Knopper. All rights reserved. // import SpriteKit class GameScene: SKScene { override func didMoveToView(view: SKView) { /* Setup your scene here */ self.backgroundColor = SKColor(red: 0.15, green:0.15, blue:0.3, alpha: 1.0) var button = SKSpriteNode(imageNamed: "nextButton.png") button.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame)) button.name = "nextButton" self.addChild(button) } override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { var touch: UITouch = touches.anyObject() as UITouch var location = touch.locationInNode(self) var node = self.nodeAtPoint(location) // If next button is touched, start transition to second scene if (node.name == "nextButton") { var secondScene = SecondScene(size: self.size) var transition = SKTransition.flipVerticalWithDuration(1.0) secondScene.scaleMode = SKSceneScaleMode.AspectFill self.scene!.view?.presentScene(secondScene, transition: transition) } } override func update(currentTime: CFTimeInterval) { /* Called before each frame is rendered */ } }
mit
fd4a419cf66a1a8b20f9d98c717f7e41
34.435897
91
0.653401
4.487013
false
false
false
false
adela-chang/StringExtensionHTML
Example/StringExtensionHTML/ViewController.swift
1
2035
// // ViewController.swift // StringExtensionHTML // // Created by Adela on 02/15/2016. // Copyright (c) 2016 Adela. All rights reserved. // import UIKit import StringExtensionHTML class ViewController: UIViewController { @IBOutlet weak var stripTags: UIButton! @IBOutlet weak var decode: UIButton! @IBOutlet weak var sample1: UIButton! @IBOutlet weak var sample2: UIButton! @IBOutlet weak var sample3: UIButton! @IBOutlet weak var sampleText: UITextField! @IBOutlet weak var convertedResult: UITextField! @objc func sample1Click() { sampleText.text = "&#x22;That&#x27;s your d&#xE6;mon, Lyra.&#x22;" } @objc func sample2Click() { sampleText.text = "&lt;a href=&quot;mailto:[email protected]&quot;&gt;email&lt;/a&gt;" } @objc func sample3Click() { sampleText.text = "<h2>Try stripping <b>my</b> <a href=''><i>html</i></a> tags!</h2>" } @objc func stripTagsClick() { convertedResult.text = sampleText.text!.stringByStrippingHTMLTags } @objc func decodeClick() { convertedResult.text = sampleText.text!.stringByDecodingHTMLEntities } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. sampleText.becomeFirstResponder() sample1.addTarget(self, action: #selector(ViewController.sample1Click), for: .touchUpInside) sample2.addTarget(self, action: #selector(ViewController.sample2Click), for: .touchUpInside) sample3.addTarget(self, action: #selector(ViewController.sample3Click), for: .touchUpInside) stripTags.addTarget(self, action: #selector(ViewController.stripTagsClick), for: .touchUpInside) decode.addTarget(self, action: #selector(ViewController.decodeClick), for: .touchUpInside) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
4fad35a98002d138c64f1d8e50264771
31.822581
104
0.675676
4.144603
false
false
false
false
SoufianeLasri/Sisley
Sisley/NavigationView.swift
1
4167
// // NavigationView.swift // Sisley // // Created by Soufiane Lasri on 18/12/2015. // Copyright ยฉ 2015 Soufiane Lasri. All rights reserved. // import UIKit protocol NavigationViewDelegate: class { func navigationButtonTapped( type: String ) } class NavigationView: UIView { var openingState: Bool = false var buttons: [ NavigationButton ] = [] var items: [ [ String: String ] ] = [] var delegate: NavigationViewDelegate? override init( frame: CGRect ) { super.init( frame: frame ) self.items = [ [ "title" : "Mes soins Sisley", "image" : "soins.png" ], [ "title" : "Mon รฉvolution", "image" : "evolution.png" ], [ "title" : "Mon orchidรฉe", "image" : "orchidee.png" ], [ "title" : "Mon profil", "image" : "profil.png" ] ] self.backgroundColor = UIColor( red: 0.06, green: 0.08, blue: 0.32, alpha: 0.0 ) for var i = 0; i < self.items.count; i++ { let button = NavigationButton( frame: CGRect( x: 25, y: self.frame.height - CGFloat( 70 + 60 * ( i + 1 ) ), width: 50, height: 50 ), text: self.items[ i ][ "title" ]!, imageName: self.items[ i ][ "image" ]! ) self.buttons.append( button ) self.addSubview( button ) } let openCures = UITapGestureRecognizer( target: self, action: "openCures:" ) self.buttons[ 0 ].addGestureRecognizer( openCures ) let openEvolution = UITapGestureRecognizer( target: self, action: "openEvolution:" ) self.buttons[ 1 ].addGestureRecognizer( openEvolution ) let openFlower = UITapGestureRecognizer( target: self, action: "openFlower:" ) self.buttons[ 2 ].addGestureRecognizer( openFlower ) self.hidden = true } func openCures( sender: UITapGestureRecognizer ) { self.delegate?.navigationButtonTapped( "cures" ) } func openEvolution( sender: UITapGestureRecognizer ) { self.delegate?.navigationButtonTapped( "history" ) } func openFlower( sender: UITapGestureRecognizer ) { self.delegate?.navigationButtonTapped( "flower" ) } func toggleNavigationMenu() { self.openingState = !self.openingState if self.openingState == true { self.hidden = false var delay = 0.0 UIView.animateWithDuration( 0.3, delay: delay, options: UIViewAnimationOptions.TransitionNone, animations: { self.backgroundColor = UIColor( red: 0.06, green: 0.08, blue: 0.32, alpha: 0.7 ) }, completion: nil ) for item in self.buttons { UIView.animateWithDuration( 0.3, delay: delay, options: UIViewAnimationOptions.TransitionNone, animations: { item.toggleButton( self.openingState ) }, completion: nil ) delay += 0.1 } } else { // Calcul pour que le delais soit proportionnel au nombre d'item dans le menu // S'il y a 4 items, le delais sera de 0.3s // var delay = 0.3 var delay = Double( self.items.count ) / 10.0 - 0.1 UIView.animateWithDuration( 0.3, delay: delay, options: UIViewAnimationOptions.TransitionNone, animations: { self.backgroundColor = UIColor( red: 0.06, green: 0.08, blue: 0.32, alpha: 0.0 ) }, completion: { finished in self.hidden = true } ) for item in self.buttons { UIView.animateWithDuration( 0.3, delay: delay, options: UIViewAnimationOptions.TransitionNone, animations: { item.toggleButton( self.openingState ) }, completion: nil ) delay -= 0.1 } } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
34df8dd36ea8ebc3b2de01a93855a572
34.896552
221
0.547791
4.415695
false
false
false
false
cornerstonecollege/402
Younseo/GestureRecognizer/CustomViews/FirstCustomView.swift
1
1690
// // FirstCustomView.swift // CustomViews // // Created by hoconey on 2016/10/13. // Copyright ยฉ 2016ๅนด younseo. All rights reserved. // import UIKit class FirstCustomView: UIView { override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.red // default background color let label = UILabel() label.text = "Name" label.sizeToFit() label.center = CGPoint(x: self.frame.size.width/2, y:10) self.addSubview(label) let txtFrame = CGRect(x: ((self.frame.size.width) - 40)/2, y: 50, width: 40, height: 20) let textView = UITextField(frame: txtFrame) textView.backgroundColor = UIColor.white self.addSubview(textView) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { print("began") } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { print("moved") self.center = touches.first!.location(in: self.superview) } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { print("end") } }
gpl-3.0
262b197e9fce9db0bf2dfcb8701fffd2
29.672727
100
0.542383
4.738764
false
false
false
false
dduan/swift
validation-test/compiler_crashers_fixed/01497-swift-bracestmt-create.swift
11
873
// 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 http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse func g<T, c: a { protocol a { } protocol b { class A { } func b.Type) { } enum A : A : a { } } var b { protocol b { func b typealias e : e: C { } struct d>)-> String = T> d>(c<f == F>?) -> a { } } func f() -> e(_ c(Any) -> Any { } let c = a((a(v: P { } case C) -> Int = { extension A { } } get { func b() -> Bool { case A<1 { protocol b = b.a<T> T> String { } }("[1, length: Collection where d<Q<T -> (T> S.substringWithRange(T] in protocol a { } enum A : Hashable> Int { () { } }
apache-2.0
d663900d88cc7849e55fbce177d0442c
17.574468
78
0.619702
2.789137
false
false
false
false
tonilopezmr/Learning-Swift
Learning-Swift/Learning-Swift/strings.swift
1
894
// // strings.swift // Learning-Swift // // Created by Antonio Lรณpez Marรญn on 10/01/16. // Copyright ยฉ 2016 Antonio Lรณpez Marรญn. All rights reserved. // import Foundation class StringExamples: ExampleProtocol { func example() { print("Hello, World!") //Fundamentals, variables and String var hello: String = "Hello" //mutable variables! var world: String = "World" let helloSwift = "Hello Swift! :D" //inmutable variable! hello = hello.uppercaseString world = world.lowercaseString print(hello + " " + world) print(helloSwift) let today: String = "January 10th, 2016" let output: String = "I'm learning about swift \(today)" print(output) print("hola buenos dias que tal estais".capitalizedString) } }
apache-2.0
65f17607c0e7cbd7924821dd16eb322c
24.428571
66
0.579303
4.422886
false
false
false
false
ReactiveKit/Bond
Sources/Bond/Observable Collections/OrderedCollectionDiff+Strideable.swift
3
6394
// // The MIT License (MIT) // // Copyright (c) 2018 DeclarativeHub/Bond // // 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 extension OrderedCollectionDiff where Index: Strideable { /// Calculates diff from the given patch. /// - complexity: O(Nห†2) where N is the number of patch operations. public init<T>(from patch: [OrderedCollectionOperation<T, Index>]) { self.init(from: patch.map { $0.asAnyOrderedCollectionOperation }) } /// Calculates diff from the given patch. /// - complexity: O(Nห†2) where N is the number of patch operations. public init(from patch: [AnyOrderedCollectionOperation<Index>]) { self.init() guard !patch.isEmpty else { return } for patchSoFar in (1...patch.count).map({ patch.prefix(upTo: $0) }) { let patchToUndo = patchSoFar.dropLast() switch patchSoFar.last! { case .insert(let atIndex): recordInsertion(at: atIndex) case .delete(let atIndex): let sourceIndex = AnyOrderedCollectionOperation<Index>.undo(patch: patchToUndo, on: atIndex) recordDeletion(at: atIndex, sourceIndex: sourceIndex) case .update(let atIndex): let sourceIndex = AnyOrderedCollectionOperation<Index>.undo(patch: patchToUndo, on: atIndex) recordUpdate(at: atIndex, sourceIndex: sourceIndex) case .move(let fromIndex, let toIndex): let sourceIndex = AnyOrderedCollectionOperation<Index>.undo(patch: patchToUndo, on: fromIndex) recordMove(from: fromIndex, to: toIndex, sourceIndex: sourceIndex) } } } private mutating func recordInsertion(at insertionIndex: Index) { forEachDestinationIndex { (index) in if insertionIndex <= index { index = index.advanced(by: 1) } } inserts.append(insertionIndex) } private mutating func recordDeletion(at deletionIndex: Index, sourceIndex: Index?) { defer { forEachDestinationIndex { (index) in if deletionIndex <= index { index = index.advanced(by: -1) } } } // If deleting previously inserted element, undo insertion if let index = inserts.firstIndex(where: { $0 == deletionIndex }) { inserts.remove(at: index) return } // If deleting previously moved element, replace move with deletion if let index = moves.firstIndex(where: { $0.to == deletionIndex }) { let move = moves[index] moves.remove(at: index) deletes.append(move.from) return } // If we are deleting an update, just remove the update updates.removeAll(where: { $0 == sourceIndex }) deletes.append(sourceIndex!) } private mutating func recordUpdate(at updateIndex: Index, sourceIndex: Index?) { // If updating previously inserted index if inserts.contains(where: { $0 == updateIndex }) { return } // If updating previously updated index if updates.contains(where: { $0 == sourceIndex }) { return } // If updating previously moved index, replace move with delete+insert if let index = moves.firstIndex(where: { $0.to == updateIndex }) { let move = moves[index] moves.remove(at: index) deletes.append(move.from) inserts.append(move.to) return } updates.append(sourceIndex!) } private mutating func recordMove(from fromIndex: Index, to toIndex: Index, sourceIndex: Index?) { guard fromIndex != toIndex else { return } func adjustDestinationIndices() { forEachDestinationIndex { (index) in if fromIndex <= index { index = index.advanced(by: -1) } if toIndex <= index { index = index.advanced(by: 1) } } } // If moving previously inserted element, replace with the insertion at the new index if let _ = inserts.firstIndex(where: { $0 == fromIndex }) { recordDeletion(at: fromIndex, sourceIndex: sourceIndex) recordInsertion(at: toIndex) return } // If moving previously moved element, update move to index if let i = moves.firstIndex(where: { $0.to == fromIndex }) { adjustDestinationIndices() moves[i].to = toIndex return } // If moving previously updated element if let i = updates.firstIndex(where: { $0 == sourceIndex }) { updates.remove(at: i) recordDeletion(at: fromIndex, sourceIndex: sourceIndex) recordInsertion(at: toIndex) return } adjustDestinationIndices() moves.append((from: sourceIndex!, to: toIndex)) } private mutating func forEachDestinationIndex(apply: (inout Index) -> Void) { for i in 0..<inserts.count { apply(&inserts[i]) } for i in 0..<moves.count { apply(&moves[i].to) } } }
mit
b3e4e4e7c742c11f0c279384bfd05e5d
35.947977
110
0.605601
4.696547
false
false
false
false
feiin/CATransitionSwiftDemo
CATransitionSwiftDemo/ViewController.swift
1
6064
// // ViewController.swift // CATransitionSwiftDemo // // Created by yangyin on 14/12/26. // Copyright (c) 2014ๅนด swiftmi. All rights reserved. // import UIKit enum AnimationType:Int { case fade = 1, //ๆทกๅ…ฅๆทกๅ‡บ push, //ๆŽจๆŒค reveal, //ๆญๅผ€ moveIn, //่ฆ†็›– cube, //็ซ‹ๆ–นไฝ“ suckEffect, //ๅฎๅธ oglFlip, //็ฟป่ฝฌ rippleEffect, //ๆณข็บน pageCurl, //็ฟป้กต pageUnCurl, //ๅ็ฟป้กต cameraIrisHollowOpen, //ๅผ€้•œๅคด cameraIrisHollowClose, //ๅ…ณ้•œๅคด curlDown, //ไธ‹็ฟป้กต curlUp, //ไธŠ็ฟป้กต flipFromLeft, //ๅทฆ็ฟป่ฝฌ flipFromRight //ๅณ็ฟป่ฝฌ } class ViewController: UIViewController { let duration = 0.7 let image1 = "01.jpg" let image2 = "02.jpg" var imageType = 0 var _subtype = 0 override func viewDidLoad() { super.viewDidLoad() self.addBgImageWithImageName(image2) // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func tapButton(_ sender: AnyObject) { let button = sender as! UIButton let animationType = AnimationType(rawValue: button.tag)! var subTypeString:String switch(_subtype){ case 0: subTypeString = kCATransitionFromLeft case 1: subTypeString = kCATransitionFromBottom case 2: subTypeString = kCATransitionFromRight case 3: subTypeString = kCATransitionFromTop default: subTypeString = kCATransitionFromLeft } _subtype += 1 if(_subtype > 3){ _subtype = 0 } switch(animationType){ case .fade: self.transitionWithType(kCATransitionFade, withSubType: subTypeString, forView: self.view) case .push: self.transitionWithType(kCATransitionPush, withSubType: subTypeString, forView: self.view) case .reveal: self.transitionWithType(kCATransitionReveal, withSubType: subTypeString, forView: self.view) case .moveIn: self.transitionWithType(kCATransitionMoveIn, withSubType: subTypeString, forView: self.view) case .cube: self.transitionWithType("cube", withSubType: subTypeString, forView: self.view) case .suckEffect: self.transitionWithType("suckEffect", withSubType: subTypeString, forView: self.view) case .oglFlip: self.transitionWithType("oglFlip", withSubType: subTypeString, forView: self.view) case .rippleEffect: self.transitionWithType("rippleEffect", withSubType: subTypeString, forView: self.view) case .pageCurl: self.transitionWithType("pageCurl", withSubType: subTypeString, forView: self.view) case .pageUnCurl: self.transitionWithType("pageUnCurl", withSubType: subTypeString, forView: self.view) case .cameraIrisHollowOpen: self.transitionWithType("cameraIrisHollowOpen", withSubType: subTypeString, forView: self.view) case .cameraIrisHollowClose: self.transitionWithType("cameraIrisHollowClose", withSubType: subTypeString, forView: self.view) case .curlDown: self.animationWithView(self.view, withAnimationTransition: UIViewAnimationTransition.curlDown) case .curlUp: self.animationWithView(self.view, withAnimationTransition: UIViewAnimationTransition.curlUp) case .flipFromLeft: self.animationWithView(self.view, withAnimationTransition: UIViewAnimationTransition.flipFromLeft) case .flipFromRight: self.animationWithView(self.view, withAnimationTransition: UIViewAnimationTransition.flipFromRight) } if (imageType == 0) { self.addBgImageWithImageName(image1) imageType = 1 } else { self.addBgImageWithImageName(image2) imageType = 0 } } // MARK: CATransitionๅŠจ็”ปๅฎž็Žฐ func transitionWithType(_ type:String,withSubType subType:String,forView view:UIView){ //ๅˆ›ๅปบCATransitionๅฏน่ฑก let animation = CATransition() //่ฎพ็ฝฎ่ฟๅŠจๆ—ถ้—ด animation.duration = duration //่ฎพ็ฝฎ่ฟๅŠจtype animation.type = type; if (!subType.isEmpty) { //่ฎพ็ฝฎๅญ็ฑป animation.subtype = subType; } //่ฎพ็ฝฎ่ฟๅŠจ้€Ÿๅบฆ animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) view.layer.add(animation, forKey: "animation") } // MARK: UIViewๅฎž็ŽฐๅŠจ็”ป func animationWithView(_ view:UIView,withAnimationTransition transition:UIViewAnimationTransition){ UIView.animate(withDuration: duration, animations: { UIView.setAnimationCurve(UIViewAnimationCurve.easeInOut) UIView.setAnimationTransition(transition, for: view, cache: true) }) } // MARK: ็ป™ViewๆทปๅŠ ่ƒŒๆ™ฏๅ›พ func addBgImageWithImageName(_ imageName:String){ self.view.backgroundColor = UIColor(patternImage:UIImage(named: imageName)!) } }
mit
111f5cc77fc7acf681090c68b52e1283
28.658291
111
0.565232
5.087931
false
false
false
false
64characters/Telephone
Telephone/PresentationProduct.swift
1
1728
// // PresentationProduct.swift // Telephone // // Copyright ยฉ 2008-2016 Alexey Kuznetsov // Copyright ยฉ 2016-2022 64 Characters // // Telephone is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Telephone is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // import UseCases final class PresentationProduct: NSObject { let identifier: String @objc let name: String @objc let price: String init(identifier: String, name: String, price: String) { self.identifier = identifier self.name = name self.price = price } } extension PresentationProduct { override func isEqual(_ object: Any?) -> Bool { guard let product = object as? PresentationProduct else { return false } return isEqual(toProduct: product) } override var hash: Int { var hasher = Hasher() hasher.combine(identifier) hasher.combine(name) hasher.combine(price) return hasher.finalize() } func isEqual(toProduct product: PresentationProduct) -> Bool { return self.identifier == product.identifier && self.name == product.name && self.price == product.price } } extension PresentationProduct { convenience init(_ product: Product) { self.init(identifier: product.identifier, name: product.name, price: product.localizedPrice) } }
gpl-3.0
854e1ae0a073ab16bb375d29bd0400e3
29.821429
112
0.687138
4.347607
false
false
false
false
benlangmuir/swift
test/SILGen/keypath_application.swift
22
9302
// RUN: %target-swift-emit-silgen %s | %FileCheck %s class A {} class B {} protocol P {} protocol Q {} // CHECK-LABEL: sil hidden [ossa] @{{.*}}loadable func loadable(readonly: A, writable: inout A, value: B, kp: KeyPath<A, B>, wkp: WritableKeyPath<A, B>, rkp: ReferenceWritableKeyPath<A, B>) { // CHECK: [[ROOT_COPY:%.*]] = copy_value [[READONLY:%0]] : // CHECK: [[KP_COPY:%.*]] = copy_value [[KP:%3]] // CHECK: [[ROOT_TMP:%.*]] = alloc_stack $A // CHECK: store [[ROOT_COPY]] to [init] [[ROOT_TMP]] // CHECK: [[GET:%.*]] = function_ref @swift_getAtKeyPath : // CHECK: [[RESULT_TMP:%.*]] = alloc_stack $B // CHECK: apply [[GET]]<A, B>([[RESULT_TMP]], [[ROOT_TMP]], [[KP_COPY]]) // CHECK: [[RESULT:%.*]] = load [take] [[RESULT_TMP]] // CHECK: destroy_value [[RESULT]] _ = readonly[keyPath: kp] // CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[WRITABLE:%1]] : // CHECK: [[ROOT_COPY:%.*]] = load [copy] [[ACCESS]] // CHECK: end_access [[ACCESS]] // CHECK: [[KP_COPY:%.*]] = copy_value [[KP]] // CHECK: [[ROOT_TMP:%.*]] = alloc_stack $A // CHECK: store [[ROOT_COPY]] to [init] [[ROOT_TMP]] // CHECK: [[GET:%.*]] = function_ref @swift_getAtKeyPath : // CHECK: [[RESULT_TMP:%.*]] = alloc_stack $B // CHECK: apply [[GET]]<A, B>([[RESULT_TMP]], [[ROOT_TMP]], [[KP_COPY]]) // CHECK: [[RESULT:%.*]] = load [take] [[RESULT_TMP]] // CHECK: destroy_value [[RESULT]] _ = writable[keyPath: kp] // CHECK: [[ROOT_COPY:%.*]] = copy_value [[READONLY]] : // CHECK: [[KP_COPY:%.*]] = copy_value [[WKP:%4]] // CHECK: [[KP_UPCAST:%.*]] = upcast [[KP_COPY]] : $WritableKeyPath<A, B> to $KeyPath<A, B> // CHECK: [[ROOT_TMP:%.*]] = alloc_stack $A // CHECK: store [[ROOT_COPY]] to [init] [[ROOT_TMP]] // CHECK: [[GET:%.*]] = function_ref @swift_getAtKeyPath : // CHECK: [[RESULT_TMP:%.*]] = alloc_stack $B // CHECK: apply [[GET]]<A, B>([[RESULT_TMP]], [[ROOT_TMP]], [[KP_UPCAST]]) // CHECK: [[RESULT:%.*]] = load [take] [[RESULT_TMP]] // CHECK: destroy_value [[RESULT]] _ = readonly[keyPath: wkp] // CHECK: function_ref @swift_getAtKeyPath _ = writable[keyPath: wkp] // CHECK: function_ref @swift_getAtKeyPath _ = readonly[keyPath: rkp] // CHECK: function_ref @swift_getAtKeyPath _ = writable[keyPath: rkp] // CHECK: [[KP_COPY:%.*]] = copy_value [[WKP]] // CHECK-NEXT: [[VALUE_COPY:%.*]] = copy_value [[VALUE:%2]] : $B // CHECK-NEXT: [[ACCESS:%.*]] = begin_access [modify] [unknown] [[WRITABLE]] : // CHECK-NEXT: [[VALUE_TEMP:%.*]] = alloc_stack $B // CHECK-NEXT: store [[VALUE_COPY]] to [init] [[VALUE_TEMP]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[SET:%.*]] = function_ref @swift_setAtWritableKeyPath : // CHECK-NEXT: apply [[SET]]<A, B>([[ACCESS]], [[KP_COPY]], [[VALUE_TEMP]]) // CHECK-NEXT: end_access [[ACCESS]] // CHECK-NEXT: dealloc_stack [[VALUE_TEMP]] // CHECK-NEXT: destroy_value [[KP_COPY]] writable[keyPath: wkp] = value // CHECK-NEXT: [[ROOT_COPY:%.*]] = copy_value [[READONLY]] : // CHECK-NEXT: [[KP_COPY:%.*]] = copy_value [[RKP:%5]] // CHECK-NEXT: [[VALUE_COPY:%.*]] = copy_value [[VALUE]] : $B // CHECK-NEXT: [[ROOT_TEMP:%.*]] = alloc_stack $A // CHECK-NEXT: store [[ROOT_COPY]] to [init] [[ROOT_TEMP]] // CHECK-NEXT: [[VALUE_TEMP:%.*]] = alloc_stack $B // CHECK-NEXT: store [[VALUE_COPY]] to [init] [[VALUE_TEMP]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[SET:%.*]] = function_ref @swift_setAtReferenceWritableKeyPath : // CHECK-NEXT: apply [[SET]]<A, B>([[ROOT_TEMP]], [[KP_COPY]], [[VALUE_TEMP]]) // CHECK-NEXT: dealloc_stack [[VALUE_TEMP]] // CHECK-NEXT: destroy_addr [[ROOT_TEMP]] // CHECK-NEXT: dealloc_stack [[ROOT_TEMP]] // CHECK-NEXT: destroy_value [[KP_COPY]] readonly[keyPath: rkp] = value // CHECK-NEXT: [[ACCESS:%.*]] = begin_access [read] [unknown] [[WRITABLE]] : // CHECK-NEXT: [[ROOT_COPY:%.*]] = load [copy] [[ACCESS]] : // CHECK-NEXT: end_access [[ACCESS]] // CHECK-NEXT: [[KP_COPY:%.*]] = copy_value [[RKP:%5]] // CHECK-NEXT: [[VALUE_COPY:%.*]] = copy_value [[VALUE]] : $B // CHECK-NEXT: [[ROOT_TEMP:%.*]] = alloc_stack $A // CHECK-NEXT: store [[ROOT_COPY]] to [init] [[ROOT_TEMP]] // CHECK-NEXT: [[VALUE_TEMP:%.*]] = alloc_stack $B // CHECK-NEXT: store [[VALUE_COPY]] to [init] [[VALUE_TEMP]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[SET:%.*]] = function_ref @swift_setAtReferenceWritableKeyPath : // CHECK-NEXT: apply [[SET]]<A, B>([[ROOT_TEMP]], [[KP_COPY]], [[VALUE_TEMP]]) // CHECK-NEXT: dealloc_stack [[VALUE_TEMP]] // CHECK-NEXT: destroy_addr [[ROOT_TEMP]] // CHECK-NEXT: dealloc_stack [[ROOT_TEMP]] // CHECK-NEXT: destroy_value [[KP_COPY]] writable[keyPath: rkp] = value } // CHECK-LABEL: } // end sil function '{{.*}}loadable // CHECK-LABEL: sil hidden [ossa] @{{.*}}addressOnly func addressOnly(readonly: P, writable: inout P, value: Q, kp: KeyPath<P, Q>, wkp: WritableKeyPath<P, Q>, rkp: ReferenceWritableKeyPath<P, Q>) { // CHECK: function_ref @swift_getAtKeyPath : _ = readonly[keyPath: kp] // CHECK: function_ref @swift_getAtKeyPath : _ = writable[keyPath: kp] // CHECK: function_ref @swift_getAtKeyPath : _ = readonly[keyPath: wkp] // CHECK: function_ref @swift_getAtKeyPath : _ = writable[keyPath: wkp] // CHECK: function_ref @swift_getAtKeyPath : _ = readonly[keyPath: rkp] // CHECK: function_ref @swift_getAtKeyPath : _ = writable[keyPath: rkp] // CHECK: function_ref @swift_setAtWritableKeyPath : writable[keyPath: wkp] = value // CHECK: function_ref @swift_setAtReferenceWritableKeyPath : readonly[keyPath: rkp] = value // CHECK: function_ref @swift_setAtReferenceWritableKeyPath : writable[keyPath: rkp] = value } // CHECK-LABEL: sil hidden [ossa] @{{.*}}reabstracted func reabstracted(readonly: @escaping () -> (), writable: inout () -> (), value: @escaping (A) -> B, kp: KeyPath<() -> (), (A) -> B>, wkp: WritableKeyPath<() -> (), (A) -> B>, rkp: ReferenceWritableKeyPath<() -> (), (A) -> B>) { // CHECK: function_ref @swift_getAtKeyPath : _ = readonly[keyPath: kp] // CHECK: function_ref @swift_getAtKeyPath : _ = writable[keyPath: kp] // CHECK: function_ref @swift_getAtKeyPath : _ = readonly[keyPath: wkp] // CHECK: function_ref @swift_getAtKeyPath : _ = writable[keyPath: wkp] // CHECK: function_ref @swift_getAtKeyPath : _ = readonly[keyPath: rkp] // CHECK: function_ref @swift_getAtKeyPath : _ = writable[keyPath: rkp] // CHECK: function_ref @swift_setAtWritableKeyPath : writable[keyPath: wkp] = value // CHECK: function_ref @swift_setAtReferenceWritableKeyPath : readonly[keyPath: rkp] = value // CHECK: function_ref @swift_setAtReferenceWritableKeyPath : writable[keyPath: rkp] = value } // CHECK-LABEL: sil hidden [ossa] @{{.*}}partial func partial<A>(valueA: A, valueB: Int, pkpA: PartialKeyPath<A>, pkpB: PartialKeyPath<Int>, akp: AnyKeyPath) { // CHECK: [[PROJECT:%.*]] = function_ref @swift_getAtAnyKeyPath : // CHECK: apply [[PROJECT]]<A> _ = valueA[keyPath: akp] // CHECK: [[PROJECT:%.*]] = function_ref @swift_getAtPartialKeyPath : // CHECK: apply [[PROJECT]]<A> _ = valueA[keyPath: pkpA] // CHECK: [[PROJECT:%.*]] = function_ref @swift_getAtAnyKeyPath : // CHECK: apply [[PROJECT]]<Int> _ = valueB[keyPath: akp] // CHECK: [[PROJECT:%.*]] = function_ref @swift_getAtPartialKeyPath : // CHECK: apply [[PROJECT]]<Int> _ = valueB[keyPath: pkpB] } extension Int { var b: Int { get { return 0 } set { } } var u: Int { get { return 0 } set { } } var tt: Int { get { return 0 } set { } } } // CHECK-LABEL: sil hidden [ossa] @{{.*}}writebackNesting func writebackNesting(x: inout Int, y: WritableKeyPath<Int, Int>, z: WritableKeyPath<Int, Int>, w: Int) -> Int { // -- get 'b' // CHECK: function_ref @$sSi19keypath_applicationE1bSivg // -- apply keypath y // CHECK: [[PROJECT_FN:%.*]] = function_ref @swift_modifyAtWritableKeyPath : $@yield_once @convention(thin) <ฯ„_0_0, ฯ„_0_1> (@inout ฯ„_0_0, @guaranteed WritableKeyPath<ฯ„_0_0, ฯ„_0_1>) -> @yields @inout ฯ„_0_1 // CHECK: ([[Y_ADDR:%.*]], [[Y_TOKEN:%.*]]) = begin_apply [[PROJECT_FN]]<Int, Int> // -- get 'u' // CHECK: function_ref @$sSi19keypath_applicationE1uSivg // -- apply keypath z // CHECK: [[PROJECT_FN:%.*]] = function_ref @swift_modifyAtWritableKeyPath : $@yield_once @convention(thin) <ฯ„_0_0, ฯ„_0_1> (@inout ฯ„_0_0, @guaranteed WritableKeyPath<ฯ„_0_0, ฯ„_0_1>) -> @yields @inout ฯ„_0_1 // CHECK: ([[Z_ADDR:%.*]], [[Z_TOKEN:%.*]]) = begin_apply [[PROJECT_FN]]<Int, Int> // -- set 'tt' // CHECK: function_ref @$sSi19keypath_applicationE2ttSivs // -- destroy owner for keypath projection z // CHECK: end_apply [[Z_TOKEN]] // -- set 'u' // CHECK: function_ref @$sSi19keypath_applicationE1uSivs // -- destroy owner for keypath projection y // CHECK: end_apply [[Y_TOKEN]] // -- set 'b' // CHECK: function_ref @$sSi19keypath_applicationE1bSivs x.b[keyPath: y].u[keyPath: z].tt = w }
apache-2.0
77406419fc555b5940e9a1e7ae12e1f6
40.659193
206
0.584715
3.356214
false
false
false
false
whitepixelstudios/Material
Sources/iOS/TextField.swift
1
22788
/* * 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 @objc(TextFieldPlaceholderAnimation) public enum TextFieldPlaceholderAnimation: Int { case `default` case hidden } @objc(TextFieldDelegate) public protocol TextFieldDelegate: UITextFieldDelegate { /** A delegation method that is executed when the textField changed. - Parameter textField: A TextField. - Parameter didChange text: An optional String. */ @objc optional func textField(textField: TextField, didChange text: String?) /** A delegation method that is executed when the textField will clear. - Parameter textField: A TextField. - Parameter willClear text: An optional String. */ @objc optional func textField(textField: TextField, willClear text: String?) /** A delegation method that is executed when the textField is cleared. - Parameter textField: A TextField. - Parameter didClear text: An optional String. */ @objc optional func textField(textField: TextField, didClear text: String?) } open class TextField: UITextField { /// Default size when using AutoLayout. open override var intrinsicContentSize: CGSize { return CGSize(width: bounds.width, height: 32) } /// A Boolean that indicates if the placeholder label is animated. @IBInspectable open var isPlaceholderAnimated = true /// Set the placeholder animation value. open var placeholderAnimation = TextFieldPlaceholderAnimation.default { didSet { guard isEditing else { placeholderLabel.isHidden = !isEmpty && .hidden == placeholderAnimation return } placeholderLabel.isHidden = .hidden == placeholderAnimation } } /// A boolean indicating whether the text is empty. open var isEmpty: Bool { return 0 == text?.utf16.count } open override var text: String? { didSet { placeholderAnimation = { placeholderAnimation }() } } open override var leftView: UIView? { didSet { prepareLeftView() layoutSubviews() } } /// The leftView width value. open var leftViewWidth: CGFloat { guard nil != leftView else { return 0 } return leftViewOffset + bounds.height } /// The leftView offset value. open var leftViewOffset: CGFloat = 16 /// Placeholder normal text @IBInspectable open var leftViewNormalColor = Color.darkText.others { didSet { updateLeftViewColor() } } /// Placeholder active text @IBInspectable open var leftViewActiveColor = Color.blue.base { didSet { updateLeftViewColor() } } /// Divider normal height. @IBInspectable open var dividerNormalHeight: CGFloat = 1 { didSet { guard !isEditing else { return } dividerThickness = dividerNormalHeight } } /// Divider active height. @IBInspectable open var dividerActiveHeight: CGFloat = 2 { didSet { guard isEditing else { return } dividerThickness = dividerActiveHeight } } /// Divider normal color. @IBInspectable open var dividerNormalColor = Color.grey.lighten2 { didSet { guard !isEditing else { return } dividerColor = dividerNormalColor } } /// Divider active color. @IBInspectable open var dividerActiveColor = Color.blue.base { didSet { guard isEditing else { return } dividerColor = dividerActiveColor } } /// The placeholderLabel font value. @IBInspectable open override var font: UIFont? { didSet { placeholderLabel.font = font } } /// The placeholderLabel text value. @IBInspectable open override var placeholder: String? { get { return placeholderLabel.text } set(value) { if isEditing && isPlaceholderUppercasedWhenEditing { placeholderLabel.text = value?.uppercased() } else { placeholderLabel.text = value } layoutSubviews() } } /// The placeholder UILabel. @IBInspectable open let placeholderLabel = UILabel() /// Placeholder normal text @IBInspectable open var placeholderNormalColor = Color.darkText.others { didSet { updatePlaceholderLabelColor() } } /// Placeholder active text @IBInspectable open var placeholderActiveColor = Color.blue.base { didSet { updatePlaceholderLabelColor() } } /// This property adds a padding to placeholder y position animation @IBInspectable open var placeholderVerticalOffset: CGFloat = 0 /// This property adds a padding to placeholder y position animation @IBInspectable open var placeholderHorizontalOffset: CGFloat = 0 /// The scale of the active placeholder in relation to the inactive @IBInspectable open var placeholderActiveScale: CGFloat = 0.75 { didSet { layoutPlaceholderLabel() } } /// The detailLabel UILabel that is displayed. @IBInspectable open let detailLabel = UILabel() /// The detailLabel text value. @IBInspectable open var detail: String? { get { return detailLabel.text } set(value) { detailLabel.text = value layoutSubviews() } } /// Detail text @IBInspectable open var detailColor = Color.darkText.others { didSet { updateDetailLabelColor() } } /// Vertical distance for the detailLabel from the divider. @IBInspectable open var detailVerticalOffset: CGFloat = 8 { didSet { layoutDetailLabel() } } /// Handles the textAlignment of the placeholderLabel. open override var textAlignment: NSTextAlignment { get { return super.textAlignment } set(value) { super.textAlignment = value placeholderLabel.textAlignment = value detailLabel.textAlignment = value } } /// A reference to the clearIconButton. open fileprivate(set) var clearIconButton: IconButton? /// Enables the clearIconButton. @IBInspectable open var isClearIconButtonEnabled: Bool { get { return nil != clearIconButton } set(value) { guard value else { clearIconButton?.removeTarget(self, action: #selector(handleClearIconButton), for: .touchUpInside) clearIconButton = nil return } guard nil == clearIconButton else { return } clearIconButton = IconButton(image: Icon.cm.clear, tintColor: placeholderNormalColor) clearIconButton!.contentEdgeInsetsPreset = .none clearIconButton!.pulseAnimation = .none clearButtonMode = .never rightViewMode = .whileEditing rightView = clearIconButton isClearIconButtonAutoHandled = { isClearIconButtonAutoHandled }() layoutSubviews() } } /// Enables the automatic handling of the clearIconButton. @IBInspectable open var isClearIconButtonAutoHandled = true { didSet { clearIconButton?.removeTarget(self, action: #selector(handleClearIconButton), for: .touchUpInside) guard isClearIconButtonAutoHandled else { return } clearIconButton?.addTarget(self, action: #selector(handleClearIconButton), for: .touchUpInside) } } /// A reference to the visibilityIconButton. open fileprivate(set) var visibilityIconButton: IconButton? /// Enables the visibilityIconButton. @IBInspectable open var isVisibilityIconButtonEnabled: Bool { get { return nil != visibilityIconButton } set(value) { guard value else { visibilityIconButton?.removeTarget(self, action: #selector(handleVisibilityIconButton), for: .touchUpInside) visibilityIconButton = nil return } guard nil == visibilityIconButton else { return } visibilityIconButton = IconButton(image: Icon.visibility, tintColor: placeholderNormalColor.withAlphaComponent(isSecureTextEntry ? 0.38 : 0.54)) visibilityIconButton!.contentEdgeInsetsPreset = .none visibilityIconButton!.pulseAnimation = .none isSecureTextEntry = true clearButtonMode = .never rightViewMode = .whileEditing rightView = visibilityIconButton isVisibilityIconButtonAutoHandled = { isVisibilityIconButtonAutoHandled }() layoutSubviews() } } /// Enables the automatic handling of the visibilityIconButton. @IBInspectable open var isVisibilityIconButtonAutoHandled = true { didSet { visibilityIconButton?.removeTarget(self, action: #selector(handleVisibilityIconButton), for: .touchUpInside) guard isVisibilityIconButtonAutoHandled else { return } visibilityIconButton?.addTarget(self, action: #selector(handleVisibilityIconButton), for: .touchUpInside) } } @IBInspectable open var isPlaceholderUppercasedWhenEditing = false { didSet { updatePlaceholderTextToActiveState() } } /** An initializer that initializes the object with a NSCoder object. - Parameter aDecoder: A NSCoder instance. */ public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) prepare() } /** An initializer that initializes the object with a CGRect object. If AutoLayout is used, it is better to initilize the instance using the init() initializer. - Parameter frame: A CGRect instance. */ public override init(frame: CGRect) { super.init(frame: frame) prepare() } /// A convenience initializer. public convenience init() { self.init(frame: .zero) } open override func layoutSubviews() { super.layoutSubviews() layoutShape() layoutPlaceholderLabel() layoutDetailLabel() layoutButton(button: clearIconButton) layoutButton(button: visibilityIconButton) layoutDivider() layoutLeftView() } open override func becomeFirstResponder() -> Bool { layoutSubviews() return super.becomeFirstResponder() } /// EdgeInsets for text. open var textInset: CGFloat = 0 open override func textRect(forBounds bounds: CGRect) -> CGRect { var b = super.textRect(forBounds: bounds) b.origin.x += textInset b.size.width -= textInset return b } open override func editingRect(forBounds bounds: CGRect) -> CGRect { return textRect(forBounds: bounds) } /** Prepares the view instance when intialized. When subclassing, it is recommended to override the prepare method to initialize property values and other setup operations. The super.prepare method should always be called immediately when subclassing. */ open func prepare() { clipsToBounds = false borderStyle = .none backgroundColor = nil contentScaleFactor = Screen.scale font = RobotoFont.regular(with: 16) textColor = Color.darkText.primary prepareDivider() preparePlaceholderLabel() prepareDetailLabel() prepareTargetHandlers() prepareTextAlignment() } } fileprivate extension TextField { /// Prepares the divider. func prepareDivider() { dividerColor = dividerNormalColor } /// Prepares the placeholderLabel. func preparePlaceholderLabel() { placeholderNormalColor = Color.darkText.others placeholderLabel.backgroundColor = .clear addSubview(placeholderLabel) } /// Prepares the detailLabel. func prepareDetailLabel() { detailLabel.font = RobotoFont.regular(with: 12) detailLabel.numberOfLines = 0 detailColor = Color.darkText.others addSubview(detailLabel) } /// Prepares the leftView. func prepareLeftView() { leftView?.contentMode = .left leftViewMode = .always updateLeftViewColor() } /// Prepares the target handlers. func prepareTargetHandlers() { addTarget(self, action: #selector(handleEditingDidBegin), for: .editingDidBegin) addTarget(self, action: #selector(handleEditingChanged), for: .editingChanged) addTarget(self, action: #selector(handleEditingDidEnd), for: .editingDidEnd) } /// Prepares the textAlignment. func prepareTextAlignment() { textAlignment = .rightToLeft == Application.userInterfaceLayoutDirection ? .right : .left } } fileprivate extension TextField { /// Updates the leftView tint color. func updateLeftViewColor() { leftView?.tintColor = isEditing ? leftViewActiveColor : leftViewNormalColor } /// Updates the placeholderLabel text color. func updatePlaceholderLabelColor() { tintColor = placeholderActiveColor placeholderLabel.textColor = isEditing ? placeholderActiveColor : placeholderNormalColor } /// Update the placeholder text to the active state. func updatePlaceholderTextToActiveState() { guard isPlaceholderUppercasedWhenEditing else { return } guard isEditing || !isEmpty else { return } placeholderLabel.text = placeholderLabel.text?.uppercased() } /// Update the placeholder text to the normal state. func updatePlaceholderTextToNormalState() { guard isPlaceholderUppercasedWhenEditing else { return } guard isEmpty else { return } placeholderLabel.text = placeholderLabel.text?.capitalized } /// Updates the detailLabel text color. func updateDetailLabelColor() { detailLabel.textColor = detailColor } } fileprivate extension TextField { /// Layout the placeholderLabel. func layoutPlaceholderLabel() { let w = leftViewWidth + textInset let h = 0 == bounds.height ? intrinsicContentSize.height : bounds.height placeholderLabel.transform = CGAffineTransform.identity guard isEditing || !isEmpty || !isPlaceholderAnimated else { placeholderLabel.frame = CGRect(x: w, y: 0, width: bounds.width - leftViewWidth - 2 * textInset, height: h) return } placeholderLabel.frame = CGRect(x: w, y: 0, width: bounds.width - leftViewWidth - 2 * textInset, height: h) placeholderLabel.transform = CGAffineTransform(scaleX: placeholderActiveScale, y: placeholderActiveScale) switch textAlignment { case .left, .natural: placeholderLabel.frame.origin.x = w + placeholderHorizontalOffset case .right: placeholderLabel.frame.origin.x = (bounds.width * (1.0 - placeholderActiveScale)) - textInset + placeholderHorizontalOffset default:break } placeholderLabel.frame.origin.y = -placeholderLabel.bounds.height + placeholderVerticalOffset } /// Layout the detailLabel. func layoutDetailLabel() { let c = dividerContentEdgeInsets detailLabel.frame.size.height = detailLabel.sizeThatFits(CGSize(width: bounds.width, height: .greatestFiniteMagnitude)).height detailLabel.frame.origin.x = c.left detailLabel.frame.origin.y = bounds.height + detailVerticalOffset detailLabel.frame.size.width = bounds.width - c.left - c.right } /// Layout the a button. func layoutButton(button: UIButton?) { button?.frame = CGRect(x: bounds.width - bounds.height, y: 0, width: bounds.height, height: bounds.height) } /// Layout the leftView. func layoutLeftView() { guard let v = leftView else { return } let w = leftViewWidth v.frame = CGRect(x: 0, y: 0, width: w, height: bounds.height) dividerContentEdgeInsets.left = w } } fileprivate extension TextField { /// Handles the text editing did begin state. @objc func handleEditingDidBegin() { leftViewEditingBeginAnimation() placeholderEditingDidBeginAnimation() dividerEditingDidBeginAnimation() } // Live updates the textField text. @objc func handleEditingChanged(textField: UITextField) { (delegate as? TextFieldDelegate)?.textField?(textField: self, didChange: textField.text) } /// Handles the text editing did end state. @objc func handleEditingDidEnd() { leftViewEditingEndAnimation() placeholderEditingDidEndAnimation() dividerEditingDidEndAnimation() } /// Handles the clearIconButton TouchUpInside event. @objc func handleClearIconButton() { guard nil == delegate?.textFieldShouldClear || true == delegate?.textFieldShouldClear?(self) else { return } let t = text (delegate as? TextFieldDelegate)?.textField?(textField: self, willClear: t) text = nil (delegate as? TextFieldDelegate)?.textField?(textField: self, didClear: t) } /// Handles the visibilityIconButton TouchUpInside event. @objc func handleVisibilityIconButton() { isSecureTextEntry = !isSecureTextEntry if !isSecureTextEntry { super.font = nil font = placeholderLabel.font } visibilityIconButton?.tintColor = visibilityIconButton?.tintColor.withAlphaComponent(isSecureTextEntry ? 0.38 : 0.54) } } extension TextField { /// The animation for leftView when editing begins. fileprivate func leftViewEditingBeginAnimation() { updateLeftViewColor() } /// The animation for leftView when editing ends. fileprivate func leftViewEditingEndAnimation() { updateLeftViewColor() } /// The animation for the divider when editing begins. fileprivate func dividerEditingDidBeginAnimation() { dividerThickness = dividerActiveHeight dividerColor = dividerActiveColor } /// The animation for the divider when editing ends. fileprivate func dividerEditingDidEndAnimation() { dividerThickness = dividerNormalHeight dividerColor = dividerNormalColor } /// The animation for the placeholder when editing begins. fileprivate func placeholderEditingDidBeginAnimation() { guard .default == placeholderAnimation else { placeholderLabel.isHidden = true return } updatePlaceholderLabelColor() guard isPlaceholderAnimated else { updatePlaceholderTextToActiveState() return } guard isEmpty else { updatePlaceholderTextToActiveState() return } UIView.animate(withDuration: 0.15, animations: { [weak self] in guard let s = self else { return } s.placeholderLabel.transform = CGAffineTransform(scaleX: s.placeholderActiveScale, y: s.placeholderActiveScale) s.updatePlaceholderTextToActiveState() switch s.textAlignment { case .left, .natural: s.placeholderLabel.frame.origin.x = s.leftViewWidth + s.textInset + s.placeholderHorizontalOffset case .right: s.placeholderLabel.frame.origin.x = (s.bounds.width * (1.0 - s.placeholderActiveScale)) - s.textInset + s.placeholderHorizontalOffset default:break } s.placeholderLabel.frame.origin.y = -s.placeholderLabel.bounds.height + s.placeholderVerticalOffset }) } /// The animation for the placeholder when editing ends. fileprivate func placeholderEditingDidEndAnimation() { guard .default == placeholderAnimation else { placeholderLabel.isHidden = !isEmpty return } updatePlaceholderLabelColor() updatePlaceholderTextToNormalState() guard isPlaceholderAnimated else { return } guard isEmpty else { return } UIView.animate(withDuration: 0.15, animations: { [weak self] in guard let s = self else { return } s.placeholderLabel.transform = CGAffineTransform.identity s.placeholderLabel.frame.origin.x = s.leftViewWidth + s.textInset s.placeholderLabel.frame.origin.y = 0 }) } }
bsd-3-clause
d703bc85706c2a720192b03d040758b5
29.546917
156
0.641171
5.398721
false
false
false
false
yume190/CustomView
CustomViewKitExample/Pods/CustomView/CustomViewKit/CustomViewLight.swift
1
2375
// // CustomView2.swift // CustomViewTest // // Created by Yume on 2015/3/20. // Copyright (c) 2015ๅนด yume. All rights reserved. // import UIKit @IBDesignable public class CustomViewLight: UIView { public var view:UIView? override public init(frame: CGRect) { super.init(frame: frame) setup() } required public init(coder : NSCoder) { super.init(coder:coder) setup() } public func setup(){ instantiateWithXib() } deinit{ view = nil } } protocol CustomViewBundle { func frameworkBundle() -> NSBundle? func bundleIdentifier() -> String func className() -> String } // MARK: Bundle extension CustomViewLight: CustomViewBundle { public func frameworkBundle() -> NSBundle?{ return NSBundle(identifier: bundleIdentifier()) } public func bundleIdentifier() -> String{ //Bundle Identifier can be find at Target -> Your Framework -> Bundle Identifier return NSBundle.mainBundle().bundleIdentifier ?? "com.yume190.CustomViewSwift" } public func className() -> String{ return String.className(self.classForCoder) } private func instantiateWithXib(){ let bundle:NSBundle? = frameworkBundle() let nibUrl = bundle?.URLForResource(className(), withExtension: "nib") if bundle == nil || nibUrl == nil { insertBlankView() return } var nib:UINib = UINib(nibName: className(), bundle: bundle) var views = nib.instantiateWithOwner(self, options: nil) if count(views) >= 1 { if let view = views[0] as? UIView { matchTwoViewsUsingAutolayout(view) } } } private func insertBlankView(){ var view = UIView(frame: CGRectMake(0, 0, 0, 0)) matchTwoViewsUsingAutolayout(view) } private func matchTwoViewsUsingAutolayout(view:UIView) { self.view = view view.backgroundColor = UIColor.clearColor() view.setTranslatesAutoresizingMaskIntoConstraints(false) self.addSubview(view) self <- view.top == self.top self <- view.bottom == self.bottom self <- view.trailing == self.trailing self <- view.leading == self.leading } }
mit
34cd09f2bc431aa65016094446cb740b
24.516129
88
0.599663
4.680473
false
false
false
false
wtrumler/FluentSwiftAssertions
FluentSwiftAssertionsTests/FloatingPointExtensionTests.swift
1
1800
// // FloatingPointExtensionTests.swift // FluentSwiftAssertions // // Created by Wolfgang Trumler on 13.05.17. // Copyright ยฉ 2017 Wolfgang Trumler. All rights reserved. // import XCTest class FloatingPointExtensionTests: XCTestCase { var assertFunctionWasCalled = false override func setUp() { super.setUp() assertFunctionWasCalled = false } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func test_that_should_returns_the_object_itself() { // Given let value = 1.4 // When let returnValue = value.should // Then XCTAssertEqual(value, returnValue) } func test_that_beEqualToWithAccuracy_calls_the_Equal_assertion_function() { // Given let value = 1.5 // When value.beEqualTo(1.6, withAccuracy: 0.1, "", file: "file", line: 1, assertionFunction: assertionFunction) // Then XCTAssertTrue(assertFunctionWasCalled) } func test_that_beNotEqualToWithAccuracy_calls_the_Equal_assertion_function() { // Given let value = 1.5 // When value.notBeEqualTo(1.6, withAccuracy: 0.1, "", file: "file", line: 1, assertionFunction: assertionFunction) // Then XCTAssertTrue(assertFunctionWasCalled) } func assertionFunction<T : FloatingPoint>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, _ withAccuracy: T, _ message: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line) { assertFunctionWasCalled = true } }
mit
63dc455f3f3e81fca2562b73dc26a25d
26.257576
240
0.608671
4.56599
false
true
false
false
jonbalbarin/LibGroupMe
LibGroupMe/Storage.swift
1
3189
// // Storage.swift // LibGroupMe // // Created by Jon Balbarin on 6/16/15. // Copyright (c) 2015 Jon Balbarin. All rights reserved. // import Foundation public class Storage: NSObject { private(set) public var name: String! static public let sharedInstance = Storage(name:"lib-gm-database") /** - parameter name: - essentially a name for the .db file that will get created */ required public init(name: String) { self.name = name let fileManager = NSFileManager.defaultManager() let urls = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) if let documentDirectory: NSURL = urls.first as NSURL! { // This is where the database should be in the documents directory let databaseURL = documentDirectory.URLByAppendingPathComponent("\(name).db") databaseURL.checkResourceIsReachableAndReturnError(nil) } else { print("Couldn't get documents directory!") } super.init() } private func storeInDefault(array:Array<AnyObject>?, key:String!,completion:(() -> Void)) { completion() } private func fetchFromDefault(key:String!, completion:(Array<AnyObject>? -> Void)) { completion([]) } public func storePowerups(powerups: Array<Powerup>, completion:(() -> Void)) { self.storeInDefault(powerups, key: "powerups_index", completion: completion) } /** fetches `Powerup` objects asynchonously from the store - parameter completion: - the block to call back with the fetched powerups */ public func fetchPowerups(completion:(Array<Powerup>? -> Void)) { self.fetchFromDefault("powerups_index", completion:{(fetched: Array<AnyObject>?) -> Void in if let powerups = fetched as? Array<Powerup> { completion(powerups) } else { completion(nil) } }) } public func storeGroups(groups: Array<Group>, completion:(() -> Void)) { self.storeInDefault(groups, key: "groups_index", completion: completion) } public func fetchGroups(completion:(Array<Group>? -> Void)) { self.fetchFromDefault("groups_index", completion:{(fetched: Array<AnyObject>?) -> Void in if let g = fetched as? Array<Group> { completion(g) } else { completion(nil) } }) } public func storeUsers(users: Array<User>, completion:(() -> Void)) { self.storeInDefault(users, key: "users_index") { () -> Void in completion() } } public func fetchUsers(completion:(Array<User>? -> Void)) { self.fetchFromDefault("users_index", completion:{(fetched: Array<AnyObject>?) -> Void in if let u = fetched as? Array<User> { completion (u) } else { completion(nil) } }) } } extension Storage { public func storeTestData(done:(() -> Void)) { done() } public func fetchTestData(done: ((String?) -> Void)) { done(nil) } }
mit
e3547abfffe5ef05fa3088feaca88130
30.89
99
0.590154
4.516997
false
false
false
false
jphacks/TK_21
ios/jphack3/musicianToStart.swift
1
940
// // musicianToStart.swift // jphack3 // // Created by Shoma Saito on 2015/11/29. // Copyright ยฉ 2015ๅนด eyes,japan. All rights reserved. // import UIKit import Alamofire class musicianToStart: UIViewController { @IBOutlet weak var startLive: UIImageView! override func viewDidLoad() { super.viewDidLoad() startLive.userInteractionEnabled = true startLive.tag = 200 } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { let touch = touches.first if(touch!.view!.tag == 200){ moveToMapView() } } func moveToMapView(){ let view: UIViewController = storyboard!.instantiateViewControllerWithIdentifier("musicianStop") self.presentViewController(view, animated: false, completion: nil) } }
mit
c4f7233b07967fffb083bf1dda22ad19
24.351351
104
0.65635
4.615764
false
false
false
false
davidahouse/chute
chute/ChuteDetail/ChuteStyleSheet.swift
1
3330
// // ChuteStyleSheet.swift // chute // // Created by David House on 10/14/17. // Copyright ยฉ 2017 David House. All rights reserved. // import Foundation struct ChuteStyleColor: Codable { let red: CGFloat? let green: CGFloat? let blue: CGFloat? let white: CGFloat? let alpha: CGFloat var hexString: String { if let white = white { return String(format: "%02X%02X%02X", Int(white * 255), Int(white * 255), Int(white * 255)) } else if let red = red, let green = green, let blue = blue { return String(format: "%02X%02X%02X", Int(red * 255), Int(green * 255), Int(blue * 255)) } else { return "" } } } struct ChuteStyleSheet: Codable { let viewIdentifier: String let viewPath: String let backgroundColor: ChuteStyleColor? let textColor: ChuteStyleColor? let fontName: String? let fontSize: CGFloat? } extension ChuteStyleSheet { static func findStyleSheets(testSummary: TestSummary, rootPath: URL) -> [ChuteStyleSheet] { var results = [ChuteStyleSheet]() for summary in testSummary.testableSummaries { for test in summary.tests { results += findStyleSheets(testDetails: test, rootPath: rootPath) } } return results } private static func findStyleSheets(testDetails: TestDetails, rootPath: URL) -> [ChuteStyleSheet] { var results = [ChuteStyleSheet]() if let activities = testDetails.activitySummaries { for activity in activities { if let attachments = activity.attachments { for attachment in attachments.filter({ $0.uti == "chute.styleSheet" }) { let dataPath = rootPath.appendingPathComponent(attachment.filename!) do { let data = try Data(contentsOf: dataPath) let decoder = JSONDecoder() do { let styleSheet = try decoder.decode(Array<ChuteStyleSheet>.self, from: data) results += styleSheet } catch { print(error) } } catch { print("error loading stylesheet: \(error)") } } } } } if let subtests = testDetails.subtests { for subtest in subtests { results += findStyleSheets(testDetails: subtest, rootPath: rootPath) } } return results } static func encodedStyleSheets(from: [ChuteStyleSheet]) -> Data? { let encoder = JSONEncoder() if let data = try? encoder.encode(from) { return data } else { return nil } } static func decodedStyleSheets(path: URL) -> [ChuteStyleSheet] { let decoder = JSONDecoder() do { let data = try Data(contentsOf: path) let styleSheets = try decoder.decode(Array<ChuteStyleSheet>.self, from: data) return styleSheets } catch { print(error) return [] } } }
mit
3f6ecfcc23dd41dd3894d1560db54204
28.723214
108
0.53109
4.79683
false
true
false
false
DRybochkin/Spika.swift
Spika/Views/StickerView/CSStickerView.swift
1
6472
// // CSStickerView.swift // Spika // // Created by Dmitry Rybochkin on 25.02.17. // Copyright (c) 2015 Clover Studio. All rights reserved. // import UIKit class CSStickerView: UIView, UICollectionViewDataSource, UICollectionViewDelegate, CSStickerDelegate { var originalRect = CGRect.zero var selectedStickerCollection: Int = 0 weak var delegate: CSStickerDelegate? var stickerList: CSStickerListModel! { didSet { collectionView?.reloadData() categoryCollectionView?.reloadData() if (stickerList.stickers.count > 0) { selectedStickerCollection = 0 let selection = IndexPath(item: selectedStickerCollection, section: 0) categoryCollectionView?.selectItem(at: selection, animated: false, scrollPosition: .centeredHorizontally) } } } @IBOutlet weak var backgroundView: UIView! @IBOutlet var rootView: UIView! @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var categoryCollectionView: UICollectionView! @IBAction func onCancel(_ sender: Any) { animateHide() } init(parentView: UIView!, delegate: CSStickerDelegate?, stickers: CSStickerListModel!) { self.stickerList = stickers self.delegate = delegate super.init(frame: CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(parentView.frame.size.width), height: CGFloat(parentView.frame.size.height))) initFromNib() parentView.addSubview(self) } override init(frame: CGRect) { super.init(frame: frame) initFromNib() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initFromNib() } func initFromNib() { let view: UIView! = Bundle.main.loadNibNamed(String(describing: type(of: self)), owner: self, options: nil)![0] as! UIView view.frame = bounds addSubview(view!) backgroundView.layer.cornerRadius = 10 backgroundView.layer.masksToBounds = true originalRect = backgroundView.frame collectionView?.register(UINib(nibName: String(describing: CSStickerPageCollectionViewCell.self), bundle: nil), forCellWithReuseIdentifier: "page") categoryCollectionView.register(UINib(nibName: String(describing: CSStickerCategoryCollectionViewCell.self), bundle: nil), forCellWithReuseIdentifier: "cell") categoryCollectionView.allowsSelection = true collectionView?.allowsSelection = false if (stickerList != nil && stickerList.stickers.count > 0) { selectedStickerCollection = 0 let selection = IndexPath(item: selectedStickerCollection, section: 0) categoryCollectionView.selectItem(at: selection, animated: false, scrollPosition: .centeredHorizontally) } animateOpen() } func animateOpen() { backgroundView.alpha = 0.3 backgroundView.frame = CGRect(x: -originalRect.size.width, y: originalRect.size.height + originalRect.origin.y, width: CGFloat(0), height: CGFloat(0)) UIView.animate(withDuration: 0.3, delay: 0.0, options: .curveEaseOut, animations: {() -> Void in self.backgroundView.frame = self.originalRect self.backgroundView.alpha = 1.0 }, completion: {(_ success: Bool) -> Void in }) } func animateHide() { UIView.animate(withDuration: 0.3, delay: 0.0, options: .curveEaseOut, animations: {() -> Void in self.backgroundView.alpha = 0.3 self.backgroundView.frame = CGRect(x: -(self.backgroundView.frame.size.width + self.backgroundView.frame.origin.x), y: self.backgroundView.frame.origin.y + self.backgroundView.frame.size.height, width: CGFloat(0), height: CGFloat(0)) }, completion: {(_ success: Bool) -> Void in self.removeFromSuperview() }) } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return stickerList.stickers.count } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if (collectionView.tag == 0) { let cell: CSStickerPageCollectionViewCell! = collectionView.dequeueReusableCell(withReuseIdentifier: "page", for: indexPath) as! CSStickerPageCollectionViewCell let sticker: CSStickerPageModel! = stickerList.stickers[indexPath.row] cell.delegate = self cell.model = sticker return cell! } else if (collectionView.tag == 1) { let cell: CSStickerCategoryCollectionViewCell! = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CSStickerCategoryCollectionViewCell let sticker: CSStickerPageModel! = stickerList.stickers[indexPath.row] cell.imageView.sd_setImage(with: URL(string: sticker.mainPic)) return cell } return collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if (collectionView.tag == 0) { return collectionView.frame.size } else if (collectionView.tag == 1) { return CGSize(width: CGFloat(50), height: CGFloat(50)) } return CGSize(width: CGFloat(60), height: CGFloat(60)) } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if (collectionView.tag == 1) { collectionView.scrollToItem(at: IndexPath(row: indexPath.row, section: 0), at: .centeredHorizontally, animated: false) } } func scrollViewDidScroll(_ scrollView: UIScrollView) { if (scrollView.tag == 0) { selectedStickerCollection = Int(collectionView.contentOffset.x / collectionView.frame.size.width) let selection = IndexPath(item: selectedStickerCollection, section: 0) categoryCollectionView.selectItem(at: selection, animated: false, scrollPosition: .centeredHorizontally) } } func onSticker(_ stickerUrl: String) { delegate?.onSticker(stickerUrl) animateHide() } }
mit
0aa7f415f037530aca0004b4fb568d64
42.146667
245
0.672281
4.869827
false
false
false
false
Royal-J/TestKitchen1607
TestKitchen1607/TestKitchen1607/classes/ingredient(้ฃŸๆ)/recommend(ๆŽจ่)/mainไธป่ฆ/view/IngreRedPacketCell.swift
1
4984
// // IngreRedPacketCell.swift // TestKitchen1607 // // Created by HJY on 2016/10/26. // Copyright ยฉ 2016ๅนด HJY. All rights reserved. // import UIKit public typealias IngreJumpClosure = (String -> Void) class IngreRedPacketCell: UITableViewCell { //็‚นๅ‡ปไบ‹ไปถ var jumpClosure: IngreJumpClosure? //ๅฎนๅ™จๅญ่ง†ๅ›พ var containerView: UIView? @IBOutlet weak var scrollView: UIScrollView! //ๆ•ฐๆฎ var listModel: IngreRecommendWidgetList? { didSet { showData() } } //ๆ˜พ็คบๆ•ฐๆฎ func showData() { //ๅˆ ้™คไน‹ๅ‰็š„ๅญ่ง†ๅ›พ if containerView != nil { containerView?.removeFromSuperview() } if listModel?.widget_data?.count > 0 { //ๅฎนๅ™จ่ง†ๅ›พ containerView = UIView.createView() scrollView.addSubview(containerView!) containerView!.snp_makeConstraints(closure: { (make) in make.edges.equalToSuperview() make.height.equalToSuperview() }) //ไธŠไธ€ๆฌก็š„่ง†ๅ›พ var lastView: UIView? = nil let cnt = listModel?.widget_data?.count for i in 0..<cnt! { let data = listModel?.widget_data![i] if data?.type == "image" { //ๅˆ›ๅปบๅ›พ็‰‡ let url = NSURL(string: (data?.content)!) let tmpimageView = UIImageView() tmpimageView.kf_setImageWithURL(url, placeholderImage: UIImage(named: "sdefaultImage"), optionsInfo: nil, progressBlock: nil, completionHandler: nil) containerView!.addSubview(tmpimageView) //็‚นๅ‡ปไบ‹ไปถ tmpimageView.userInteractionEnabled = true tmpimageView.tag = 300+i let g = UITapGestureRecognizer(target: self, action: #selector(tapImage(_:))) tmpimageView.addGestureRecognizer(g) //็บฆๆŸ tmpimageView.snp_makeConstraints(closure: { (make) in make.top.bottom.equalToSuperview() make.width.equalTo(210) if i == 0 { //ๅฐ†ๆปšๅŠจ่ง†ๅ›พๆ˜พ็คบๅœจๆœ€ไธญ้—ด let x = (CGFloat(210*cnt!)-scrollView.bounds.size.width)/2 make.left.equalTo(containerView!).offset(-x) }else{ make.left.equalTo((lastView?.snp_right)!) } }) //่ฎพ็ฝฎไธŠไธ€ๅผ ๅ›พ็‰‡ lastView = tmpimageView } } //ไฟฎๆ”นๅฎนๅ™จ่ง†ๅ›พ็š„ๅฎฝๅบฆ containerView!.snp_makeConstraints(closure: { (make) in make.right.equalTo(lastView!) }) //่ฎพ็ฝฎไปฃ็† scrollView.delegate = self } } func tapImage(g: UIGestureRecognizer) { let index = (g.view?.tag)! - 300 let data = listModel?.widget_data![index] if jumpClosure != nil && data?.link != nil { jumpClosure!((data?.link)!) } } //ๅˆ›ๅปบcell็š„ๆ–นๆณ• class func createRedPacketCellFor(tableView: UITableView, atIndexPath indexPath: NSIndexPath, listModel: IngreRecommendWidgetList) -> IngreRedPacketCell { let cellId = "ingreRedPacketCellId" var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? IngreRedPacketCell if nil == cell { cell = NSBundle.mainBundle().loadNibNamed("IngreRedPacketCell", owner: nil, options: nil).last as? IngreRedPacketCell } //ๆ•ฐๆฎ cell?.listModel = listModel return cell! } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } } //MARK:UIScrollViewไปฃ็† extension IngreRedPacketCell: UIScrollViewDelegate { func scrollViewWillBeginDragging(scrollView: UIScrollView) { let firstImageView = containerView!.viewWithTag(300) if firstImageView?.isKindOfClass(UIImageView) == true { firstImageView?.snp_updateConstraints(closure: { (make) in make.left.equalTo(containerView!) }) } } }
mit
5eca5eaa6c03daf1f86aec09bc8607e1
28.006024
169
0.497612
5.738975
false
false
false
false
qingcai518/MyFacePlus
MyFacePlus/FaceManager.swift
1
13389
// // FaceManager.swift // MyFacePlus // // Created by liqc on 2017/07/10. // Copyright ยฉ 2017ๅนด RN-079. All rights reserved. // import UIKit import AVFoundation class FaceManager { static let shared = FaceManager() private init() {} func showAllFilters() { let filterNames = CIFilter.filterNames(inCategory: kCICategoryBuiltIn) let _ = filterNames.map{print($0)} } func makeMosaicFace(with inputImage: CIImage?, _ faceObject: AVMetadataFaceObject?) -> CIImage? { guard let inputImage = inputImage else {return nil} guard let faceObject = faceObject else {return nil} let faceRect = getFaceFrame(in: inputImage, faceObject) // ใƒขใ‚ถใ‚คใ‚ฏใƒ•ใ‚ฃใƒซใ‚ฟ. guard let pixelFilter = CIFilter(name: "CIPixellate") else {return nil} pixelFilter.setValue(inputImage, forKey: kCIInputImageKey) pixelFilter.setValue(60, forKey: kCIInputScaleKey) // ็ฏ„ๅ›ฒใƒ•ใ‚ฃใƒซใ‚ฟ. let radius = faceObject.bounds.size.width * inputImage.extent.size.width let centerX = faceRect.origin.x + faceRect.size.width / 2 let centerY = inputImage.extent.height - faceRect.origin.y - faceRect.size.height / 2 let inputCenter = CIVector(x: centerX, y: centerY) guard let gradientFilter = CIFilter(name: "CIRadialGradient") else {return nil} gradientFilter.setValue(radius, forKey: "inputRadius0") gradientFilter.setValue(radius + 1, forKey: "inputRadius1") gradientFilter.setValue(inputCenter, forKey: kCIInputCenterKey) guard let gradientOutputImage = gradientFilter.outputImage?.cropping(to: inputImage.extent) else {return nil} // ๅˆๆˆใƒ•ใ‚ฃใƒซใ‚ฟ. guard let blendFilter = CIFilter(name: "CIBlendWithMask") else {return nil} blendFilter.setValue(pixelFilter.outputImage, forKey: kCIInputImageKey) blendFilter.setValue(inputImage, forKey: kCIInputBackgroundImageKey) blendFilter.setValue(gradientOutputImage, forKey: kCIInputMaskImageKey) return blendFilter.outputImage } func makeGlassFace(with inputImage : CIImage?, _ context: CIContext) -> CIImage? { guard let inputImage = inputImage else {return nil} guard let maskUIImage = UIImage(named: "icon_face6") else {return inputImage} let maskImage = CIImage(image: maskUIImage) let detector = CIDetector(ofType: CIDetectorTypeFace, context: context, options: [CIDetectorAccuracy: CIDetectorAccuracyLow]) guard let features = detector?.features(in: inputImage) else {return nil} for feature in features { guard let faceFeature = feature as? CIFaceFeature else {continue} let leftEyePosition = faceFeature.leftEyePosition let rightEyePosition = faceFeature.rightEyePosition print("left eye position = \(leftEyePosition)") print("right eye position = \(rightEyePosition)") // ๅˆๆˆ. guard let composeFilter = CIFilter(name: "CIMinimumCompositing") else {return inputImage} composeFilter.setValue(inputImage, forKeyPath: kCIInputImageKey) composeFilter.setValue(maskImage, forKeyPath: kCIInputBackgroundImageKey) return composeFilter.outputImage } return inputImage } // /* // * TODO : ้ก”ใฎไฝ็ฝฎๆƒ…ๅ ฑใจ็”ปๅƒใฎไฝ็ฝฎๆƒ…ๅ ฑใ‚’ใƒžใƒƒใƒใ•ใ›ใ‚‹ๅฟ…่ฆใŒใ‚ใ‚‹. // */ // func makeShinFace(with inputImage: CIImage?, _ context : CIContext, _ value : Float) -> CIImage? { // guard let inputImage = inputImage else {return nil} // let detector = CIDetector(ofType: CIDetectorTypeFace, context: context, options: [CIDetectorAccuracy: CIDetectorAccuracyLow]) // guard let features = detector?.features(in: inputImage) else {return inputImage} // for feature in features { // guard let faceFeature = feature as? CIFaceFeature else {continue} // // let mouthPosition = faceFeature.mouthPosition // let leftEyePosition = faceFeature.leftEyePosition // let rightEyePositon = faceFeature.rightEyePosition // // print("mouth position = \(mouthPosition)") // print("left eye position = \(leftEyePosition)") // print("right eye positoin = \(rightEyePositon)") // // // set filter. // guard let filter = CIFilter(name: "CIBumpDistortion") else {return inputImage} // let inputCenter = CIVector(x: 200, y: 200) // todo ใ“ใ“ใฏใ‚ขใ‚ดใฎไฝ็ฝฎใ‚’่จญๅฎšใ™ใ‚‹. // let inputRadius = 200 // todo. ใ“ใ“ใฏใ‚ใ”ใ‹ใ‚‰ใใกใพใงใฎ่ท้›ขใ‚’่จญๅฎšใ™ใ‚‹. // filter.setDefaults() // filter.setValue(inputImage, forKey: kCIInputImageKey) // filter.setValue(inputCenter, forKey: kCIInputCenterKey) // filter.setValue(inputRadius, forKey: kCIInputRadiusKey) // filter.setValue(value - 1, forKey: kCIInputScaleKey) // // return filter.outputImage // } // // return inputImage // } /* * ้ก”ใ‚’ๅค‰ๅฝขใ•ใ›ใ‚‹. (main ไฟ็•™) */ func makeShinFace(with inputImage : CIImage?, _ faceObject : AVMetadataFaceObject?, _ value: Float) -> CIImage? { guard let inputImage = inputImage else {return nil} guard let faceObject = faceObject else {return nil} // thinๅฏพ่ฑก้ƒจๅˆ†ใ‚’ๅ–ๅพ—ใ™ใ‚‹. let faceRect = getFaceFrame(in: inputImage, faceObject) let partRect = CGRect(x: faceRect.origin.x, y: faceRect.origin.y - faceRect.size.height * 2 / 3, width: faceRect.size.width, height: faceRect.size.height / 3) print("part rect = \(partRect)") guard let filter = CIFilter(name: "CIBumpDistortion") else {return inputImage} let inputCenter = CIVector(x: inputImage.extent.width / 2, y: faceRect.origin.y) let inputRadius = partRect.height filter.setDefaults() filter.setValue(inputImage, forKey: kCIInputImageKey) filter.setValue(inputCenter, forKey: kCIInputCenterKey) filter.setValue(inputRadius, forKeyPath: kCIInputRadiusKey) filter.setValue(-1 + value, forKeyPath: kCIInputScaleKey) return filter.outputImage } /* * ไธ‰ใคใฎ้ƒจๅˆ†ใซๅˆ†ใ‘ใฆใ‚„ใ‚‹. ไธ€ๆ—ฆไฟ็•™. */ // func makeShinFace(with inputImage : CIImage?, _ faceObject : AVMetadataFaceObject?, _ value: Float) -> CIImage? { // guard let inputImage = inputImage else {return nil} // guard let faceObject = faceObject else {return nil} // // // thinๅฏพ่ฑก้ƒจๅˆ†ใ‚’ๅ–ๅพ—ใ™ใ‚‹. // let faceRect = getFaceFrame(in: inputImage, faceObject) // let partRect = CGRect(x: faceRect.origin.x, y: faceRect.origin.y + faceRect.size.height * 2 / 3, width: faceRect.size.width, height: faceRect.size.height / 3) // print("part rect = \(partRect)") // // // ๅค‰ๅฝขๅฏพ่ฑกใฎไธŠใฎ้ƒจๅˆ†ใ‚’ๅˆ‡ใ‚‹. //// let frameTop = CIVector(cgRect: CGRect(x: 0, y: partRect.origin.y + partRect.height, width: inputImage.extent.size.height, height: inputImage.extent.size.height - partRect.origin.y - partRect.height)) // let frameTop = CIVector(cgRect: CGRect(x: 0, y: 700, width: inputImage.extent.size.width, height: inputImage.extent.size.height - 700)) // // guard let topFilter = CIFilter(name: "CICrop") else {return inputImage} // topFilter.setDefaults() // topFilter.setValue(inputImage, forKeyPath: kCIInputImageKey) // topFilter.setValue(frameTop, forKeyPath: "inputRectangle") // guard let topCIImage = topFilter.outputImage else { return inputImage } // let topUIImage = UIImage(ciImage: topCIImage) // // // ๅค‰ๅฝขๅฏพ่ฑก้ƒจๅˆ†ใ‚’ๅˆ‡ใ‚‹. // let frameVector = CIVector(cgRect:CGRect(x: 0, y: 500, width: inputImage.extent.size.width, height: 200)) //// let frameVector = CIVector(cgRect: CGRect(x: 0, y: partRect.origin.y, width: inputImage.extent.size.width, height: partRect.height)) // guard let cropFilter = CIFilter(name: "CICrop") else { return inputImage } // cropFilter.setDefaults() // cropFilter.setValue(inputImage, forKeyPath: kCIInputImageKey) // cropFilter.setValue(frameVector, forKeyPath: "inputRectangle") // guard let cropOutputImage = cropFilter.outputImage else {return inputImage} //// guard let cropOutputImage = cropFilter.outputImage?.cropping(to: UIScreen.main.bounds) else {return inputImage} // // // ๅˆ‡ใ‚Šๅ–ใฃใŸ็”ปๅƒใ‚’ๅŠ ๅทฅใ™ใ‚‹. // guard let filter = CIFilter(name: "CIStretchCrop") else {return inputImage} // filter.setDefaults() // filter.setValue(cropOutputImage, forKeyPath: kCIInputImageKey) // filter.setValue(value, forKey: "inputCenterStretchAmount") // filter.setValue(0, forKey: "inputCropAmount") // // guard let outputImage = filter.outputImage else {return inputImage} // let outputUIImage = UIImage(ciImage: outputImage) // // // ๅค‰ๅฝขๅฏพ่ฑกใฎไธ‹ใฎ้ƒจๅˆ†ใ‚’ๅˆ‡ใ‚‹. // let frameBottom = CIVector(cgRect: CGRect(x: 0, y: 0, width: inputImage.extent.size.width, height: 500)) //// let frameBottom = CIVector(cgRect: CGRect(x: 0, y: 0, width: inputImage.extent.size.width, height: partRect.origin.y)) // guard let bottomFilter = CIFilter(name: "CICrop") else {return inputImage} // bottomFilter.setDefaults() // bottomFilter.setValue(inputImage, forKeyPath: kCIInputImageKey) // bottomFilter.setValue(frameBottom, forKeyPath: "inputRectangle") // guard let bottomCIImage = bottomFilter.outputImage else {return inputImage} // let bottomUIImage = UIImage(ciImage: bottomCIImage) // // // ไธ‰ใคใฎ้ƒจๅˆ†ใ‚’ไฝตๅˆใ™ใ‚‹. // UIGraphicsBeginImageContext(UIScreen.main.bounds.size) // // topUIImage.draw(in: CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight - 700 * screenHeight / inputImage.extent.height)) // outputUIImage.draw(in: CGRect(x: 0, y: screenHeight - 700 * screenHeight / inputImage.extent.height, width: screenWidth, height: 200 * screenHeight / inputImage.extent.height)) // bottomUIImage.draw(in: CGRect(x: 0, y: screenHeight - 500 * screenHeight / inputImage.extent.height, width: screenWidth, height: 500 * screenHeight / inputImage.extent.height)) // // guard let resultUIImage = UIGraphicsGetImageFromCurrentImageContext() else {return inputImage} // UIGraphicsEndImageContext() // // let resultCIImage = CIImage(image: resultUIImage) // return resultCIImage // } /** * ๅ›พ็‰‡ๅˆๆˆ */ func mergeImage(_ baseImage: UIImage?, _ maskImage: UIImage?, _ maskFrame: CGRect) -> UIImage? { guard let base = baseImage else {return nil} guard let mask = maskImage else {return baseImage} UIGraphicsBeginImageContext(CGSize(width: screenWidth, height: screenHeight)) base.draw(in: CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight)) mask.draw(in: maskFrame) let result = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return result } func getFaceFrame(with faceObject : AVMetadataFaceObject) -> CGRect { let centerX = screenWidth * (1 - faceObject.bounds.origin.y - faceObject.bounds.size.height / 2) let centerY = screenHeight * (faceObject.bounds.origin.x + faceObject.bounds.size.width / 2) let width = screenWidth * faceObject.bounds.size.height let height = screenHeight * faceObject.bounds.size.width let originX = centerX - width / 2 let originY = centerY - height / 2 return CGRect(x: originX, y: originY, width: width, height: height) } func getFaceFrame(in inputImage: CIImage, _ faceObject : AVMetadataFaceObject) -> CGRect { let centerX = inputImage.extent.width * (1 - faceObject.bounds.origin.y - faceObject.bounds.size.height / 2) let centerY = inputImage.extent.height * (faceObject.bounds.origin.x + faceObject.bounds.size.width / 2) let width = inputImage.extent.width * faceObject.bounds.size.height let height = inputImage.extent.height * faceObject.bounds.size.width let originX = centerX - width / 2 let originY = centerY - height / 2 return CGRect(x: originX, y: originY, width: width, height: height) } func getFaceFrame(with faceFeature: CIFaceFeature, _ imageSize: CGSize) -> CGRect { var originX = faceFeature.bounds.origin.x var originY = faceFeature.bounds.origin.y var width = faceFeature.bounds.width var height = faceFeature.bounds.height originX = originX * (screenWidth / imageSize.width) originY = originY * (screenHeight / imageSize.height) width = width * (screenWidth / imageSize.width) height = height * (screenHeight / imageSize.height) originY = screenHeight - height - originY // ไฝ็ฝฎ่ฃœๆญฃใ‚’ใ™ใ‚‹. return CGRect(x: originX, y: originY, width: width, height: height) } }
apache-2.0
0fbdcac2a889418956e1a35d7dc98d76
49.622568
212
0.654573
4.24747
false
false
false
false
simonbs/Emcee
LastFMKit/Models/Artist.swift
1
892
// // Artist.swift // Emcee // // Created by Simon Stรธvring on 31/03/15. // Copyright (c) 2015 SimonBS. All rights reserved. // import Foundation import SwiftyJSON public class Artist { public let name: String public let playcount: Int public let url: NSURL public let images: [Asset] init(json: JSON) { name = json["name"].stringValue playcount = json["playcount"].intValue url = json["url"].URL! var mutableAssets = [Asset]() for imageJson in json["image"].arrayValue { mutableAssets.append(Asset(json: imageJson)) } images = mutableAssets } public func smallestImage() -> Asset? { return images.sort { $0.rank < $1.rank }.first } public func largestImage() -> Asset? { return images.sort { $0.rank > $1.rank }.first } }
mit
39fd9d6bb66871a94f6f429734d91b59
21.275
56
0.578002
3.96
false
false
false
false
infobip/mobile-messaging-sdk-ios
Classes/Core/Utils/ApnsRegistrationManager.swift
1
8029
// // ApnsRegistrationManager.swift // MobileMessaging // // Created by Andrey Kadochnikov on 12/02/2018. // import Foundation import UserNotifications class ApnsRegistrationManager: NamedLogger { let mmContext: MobileMessaging init(mmContext: MobileMessaging) { self.mmContext = mmContext } func unregister(userInitiated: Bool) { guard userInitiated == true || mmContext.unregisteringForRemoteNotificationsDisabled == false else { logDebug("Canceling unregistering with args userInitiated \(userInitiated), unregisteringForRemoteNotificationsDisabled \(mmContext.unregisteringForRemoteNotificationsDisabled)") return } if MobileMessaging.application.isRegisteredForRemoteNotifications { MobileMessaging.application.unregisterForRemoteNotifications() } } func stop() { readyToRegisterForNotifications = false unregister(userInitiated: false) UNUserNotificationCenter.current().delegate = nil } func registerForRemoteNotifications(userInitiated: Bool) { guard userInitiated == true || mmContext.registeringForRemoteNotificationsDisabled == false else { logDebug("Canceling registration with args userInitiated \(userInitiated), registeringForRemoteNotificationsDisabled \(mmContext.registeringForRemoteNotificationsDisabled)") return } switch mmContext.internalData().currentDepersonalizationStatus { case .success, .undefined: break case .pending: logDebug("Canceling registration due to pending depersonalize state. Retry will be done on depersonalize state change automatically...") return } logDebug("Registering...") registerNotificationSettings(application: MobileMessaging.application, userNotificationType: mmContext.userNotificationType) if mmContext.currentInstallation().pushServiceToken == nil { if MobileMessaging.application.isRegisteredForRemoteNotifications { logDebug("The application is registered for remote notifications but MobileMessaging lacks of device token. Unregistering...") unregister(userInitiated: userInitiated) } setRegistrationIsHealthy() } // we always registering to avoid cases when the device token stored in SDK database becomes outdated (i.e. due to iOS reserve copy restoration). `didRegisterForRemoteNotificationsWithDeviceToken` will return us the most relevant token. MobileMessaging.application.registerForRemoteNotifications() readyToRegisterForNotifications = true } func didRegisterForRemoteNotificationsWithDeviceToken(userInitiated: Bool, token: Data, completion: @escaping (NSError?) -> Void) { guard readyToRegisterForNotifications else { logDebug("MobileMessaging is not ready to register for notifications") completion(nil) return } let tokenStr = token.mm_toHexString logInfo("Application did register with device token \(tokenStr)") UserEventsManager.postDeviceTokenReceivedEvent(tokenStr) // in most cases we either get the same token we registered earlier or we are just starting let installation = mmContext.resolveInstallation() if installation.pushServiceToken == nil || installation.pushServiceToken == tokenStr { setRegistrationIsHealthy() updateDeviceToken(userInitiated: userInitiated, token: token, completion: completion) } else { // let's check if a special healthy flag is true. It may be false only due to iOS reserve copy restoration if isRegistrationHealthy == false { // if we face the reserve copy restoration we force a new registration resetRegistration(userInitiated: userInitiated) { self.updateDeviceToken(userInitiated: userInitiated, token: token, completion: completion) } } else { // in other cases it is the APNS changing the device token updateDeviceToken(userInitiated: userInitiated, token: token, completion: completion) } } } func resetRegistration(userInitiated: Bool, completion: @escaping () -> Void) { mmContext.installationService.resetRegistration(userInitiated: userInitiated, completion: { _ in completion() }) } func updateDeviceToken(userInitiated: Bool, token: Data, completion: @escaping (NSError?) -> Void) { mmContext.installationService.save(userInitiated: userInitiated, deviceToken: token, completion: completion) } private var isRegistrationHealthy_cached: Bool? /// The attribute shows whether we are sure that the current apns registration is healthy (may receive push, is linked with appropriate people record). May become unhealthy due to iOS reserve copy restoration - so the device token stored (recovered) in local database would not be a working one. var isRegistrationHealthy: Bool { guard isRegistrationHealthy_cached == nil else { return isRegistrationHealthy_cached! } guard let flagUrl = ApnsRegistrationManager.registrationHealthCheckFlagUrl else { logError("registration health flag url is invalid") return false } let apnsRegistrationHealthyFlagValue: String? do { apnsRegistrationHealthyFlagValue = try String.init(contentsOf: flagUrl, encoding: ApnsRegistrationManager.encoding) } catch { apnsRegistrationHealthyFlagValue = nil if !error.mm_isNoSuchFile { logError("failed to read flag: \(error)") } } isRegistrationHealthy_cached = apnsRegistrationHealthyFlagValue != nil return isRegistrationHealthy_cached! } func setRegistrationIsHealthy() { logDebug("setting healthy flag") guard isRegistrationHealthy == false, var flagUrl = ApnsRegistrationManager.registrationHealthCheckFlagUrl else { return } do { let dateString = DateStaticFormatters.ISO8601SecondsFormatter.string(from: MobileMessaging.date.now) try dateString.write(to: flagUrl, atomically: true, encoding: ApnsRegistrationManager.encoding) var resourceValues = URLResourceValues() resourceValues.isExcludedFromBackup = true try flagUrl.setResourceValues(resourceValues) isRegistrationHealthy_cached = true } catch { logError("failed to write healthy flag: \(error)") } } func cleanup() { logDebug("cleaning up...") guard let flagUrl = ApnsRegistrationManager.registrationHealthCheckFlagUrl else { logError("failed to define urls for cleaning") return } do { try FileManager.default.removeItem(at: flagUrl) } catch { if !error.mm_isNoSuchFile { logError("failed to remove flag: \(error)") } } } private static let registrationHealthCheckFlagUrl: URL? = URL(string: "com.mobile-messaging.database/apnsRegistrationHealthyFlag", relativeTo: FileManager.default.urls(for: FileManager.SearchPathDirectory.applicationSupportDirectory, in: FileManager.SearchPathDomainMask.userDomainMask).first) private static let encoding: String.Encoding = .utf8 private func registerNotificationSettings(application: MMApplication, userNotificationType: MMUserNotificationType) { if mmContext.overridingNotificationCenterDeleageDisabled == false { UNUserNotificationCenter.current().delegate = UserNotificationCenterDelegate.sharedInstance } UNUserNotificationCenter.current().requestAuthorization(options: userNotificationType.unAuthorizationOptions) { (granted, error) in UserEventsManager.postNotificationCenterAuthRequestFinished(granted: granted, error: error) guard granted else { self.logDebug("Authorization for notification options wasn't granted with error: \(error.debugDescription)") return } if let categories = self.mmContext.notificationsInteractionService?.allNotificationCategories?.unNotificationCategories { UNUserNotificationCenter.current().setNotificationCategories(categories) } } } var readyToRegisterForNotifications: Bool = false }
apache-2.0
86e9fdfbdd1536b51a0aa575dd29b1db
42.4
296
0.744426
5.059231
false
false
false
false
dreamsxin/swift
validation-test/compiler_crashers_fixed/02173-swift-parser-skipsingle.swift
11
995
// 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 http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse func f<T : String { class A { } protocol P { let h == e<S : C { """a(x, U) -> T : Collection where l.B : A<h == e!) func b typealias B : b> T) { static let x in a { } } class A { protocol b { protocol a { func g> Int { } } } } } let a { } func g<c: a : A> { b() -> T! { let n1: A, self.a<T> (array: d) { protocol e = 0) -> <c(Any) -> Any) { b.a(bytes: () { } } } let i: B<b<d<T) -> [Any, g<(false)() -> String { return NSData(n: (T) { enum S(c { class b: T>(((T>(start, self[0) private let foo as [self.B<d(T) -> Self { for ([c, e = a<h == [](g<U.<1 { return self.Element>((m: T : k) { case b { let d<T
apache-2.0
3b4178b437b33d5e96e987be5c28ed5f
20.170213
78
0.601005
2.57772
false
false
false
false
XLsn0w/XLsn0wKit_swift
XLsn0wKit/Extensions/UIWindow+Extension.swift
1
2426
/********************************************************************************************* * __ __ _ _________ _ _ _ _________ __ _ __ * * \ \ / / | | | _______| | | \ | | | ______ | \ \ / \ / / * * \ \ / / | | | | | |\ \ | | | | | | \ \ / \ \ / / * * \ \/ / | | | |______ | | \ \ | | | | | | \ \ / / \ \ / / * * /\/\/\ | | |_______ | | | \ \| | | | | | \ \ / / \ \ / / * * / / \ \ | |______ ______| | | | \ \ | | |_____| | \ \ / \ \ / * * /_/ \_\ |________| |________| |_| \__| |_________| \_/ \_/ * * * *********************************************************************************************/ import UIKit extension UIWindow { public class func currentViewController() -> UIViewController { return self.findBestViewController(UIApplication.shared.keyWindow?.rootViewController) } private class func findBestViewController(_ vc: UIViewController?) -> UIViewController { if ((vc?.presentedViewController) != nil) { return self.findBestViewController(vc?.presentedViewController) } else if (vc?.isKind(of: UISplitViewController.classForCoder()) == true) { let masterVC = vc as! UISplitViewController if masterVC.viewControllers.count > 0 { return self.findBestViewController(masterVC.viewControllers.last) } else { return vc! } }else if (vc?.isKind(of: UINavigationController.classForCoder()) == true) { let nav = vc as! UINavigationController if nav.viewControllers.count > 0 { return self.findBestViewController(nav.topViewController) }else { return vc! } } else if (vc?.isKind(of: UITabBarController.classForCoder()) == true) { let tabBar = vc as! UITabBarController if (tabBar.viewControllers?.count)! > 0 { return self.findBestViewController(tabBar.selectedViewController) }else { return vc! } } else { return vc! } } }
mit
1ebceb31acd93ad10163b1fd00c2e87b
49.541667
95
0.363149
4.526119
false
false
false
false
LedgerHQ/ledger-wallet-ios
ledger-wallet-ios/Views/Custom/RoundedButton.swift
1
3525
// // RoundedButton.swift // ledger-wallet-ios // // Created by Nicolas Bigot on 14/01/2015. // Copyright (c) 2015 Ledger. All rights reserved. // import UIKit class RoundedButton: Button { private var fillColors: [UInt: UIColor] = [:] // MARK: - Border radius var borderRadius: CGFloat = VisualFactory.Metrics.BordersRadius.Default { didSet { setNeedsDisplay() } } // MARK: - Fill color func setFillColor(color: UIColor, forState state: UIControlState) { fillColors.updateValue(color, forKey: state.rawValue) setNeedsDisplay() } func fillColorForState(state: UIControlState) -> UIColor { if let color = self.fillColors[state.rawValue] { return color } if let color = self.fillColors[UIControlState.Normal.rawValue] { return color } return UIColor.clearColor() } // MARK: - Drawing invalidation override var selected: Bool { didSet { setNeedsDisplay() } } override var highlighted: Bool { didSet { setNeedsDisplay() } } // MARK: - Drawing override func drawRect(rect: CGRect) { let fillPath = UIBezierPath(roundedRect: self.bounds, cornerRadius: self.borderRadius) fillColorForState(self.state).setFill() fillPath.fill() super.drawRect(rect) } // MARK: - Layout override func layoutSubviews() { super.layoutSubviews() imageView?.frame = CGRectMake( contentEdgeInsets.left + imageEdgeInsets.left, (self.bounds.size.height - (self.imageView?.bounds.size.height ?? 0)) / 2, (imageView?.bounds.size.width ?? 0), (imageView?.bounds.size.height ?? 0)) titleLabel?.frame = CGRectMake( self.bounds.size.width - (titleLabel?.bounds.size.width ?? 0) - contentEdgeInsets.right - titleEdgeInsets.right, (self.bounds.size.height - (self.titleLabel?.bounds.size.height ?? 0)) / 2, (titleLabel?.bounds.size.width ?? 0), (titleLabel?.bounds.size.height ?? 0)) } // MARK: - Content size override func intrinsicContentSize() -> CGSize { let width: CGFloat = contentEdgeInsets.left + contentEdgeInsets.right let height: CGFloat = contentEdgeInsets.top + contentEdgeInsets.bottom var contentHeight: CGFloat = 0 var contentWidth: CGFloat = 0 if let imageSize = currentImage?.size { contentWidth += imageSize.width contentWidth += imageEdgeInsets.left + imageEdgeInsets.right contentHeight = max(contentHeight, imageSize.height + imageEdgeInsets.top + imageEdgeInsets.bottom) } if let labelAttributes = currentAttributedTitle?.attributesAtIndex(0, effectiveRange: nil) { if let labelText = currentAttributedTitle?.string { let labelTextAsNSString = labelText as NSString let labelSize = labelTextAsNSString.sizeWithAttributes(labelAttributes) contentWidth += ceil(labelSize.width) contentWidth += titleEdgeInsets.left + titleEdgeInsets.right contentHeight = max(contentHeight, ceil(labelSize.height) + titleEdgeInsets.top + titleEdgeInsets.bottom) } } return CGSize(width: width + contentWidth, height: height + contentHeight) } }
mit
c84b39cd88cf38878779a929ff1b529c
32.894231
124
0.612766
5.042918
false
false
false
false
etamity/AlienBlast
Source/LevelGenerator.swift
1
12778
// // LevelGenerator.swift // AlientBlast // // Created by Joey etamity on 29/03/2016. // Copyright ยฉ 2016 Innovation Apps. All rights reserved. // import Foundation class LevelGenerator: CCNode { var speed:Float = 0.0; var level:Int = 1; var timeSpeed :Double = 1; var countOfTime:Int = 0; var hud:UserInterFace! = nil; var finger:Finger! = nil var touched :Bool = false; weak var backgroundNode : CCNode! = nil; var previousTouchPos: CGPoint = CGPointMake(0, 0); class var sharedInstance : LevelGenerator { struct Static { static let instance : LevelGenerator = LevelGenerator() } return Static.instance } func didLoadFromCCB(){ self.userInteractionEnabled = true; self.name = "LevelGenerator"; self.initData(); finger = CCBReader.load(StaticData.getFingerFile(FingerType.Default.rawValue)) as! Finger self.addChild(finger) let staticData = StaticData.sharedInstance staticData.events.listenTo(GameEvent.UPDATE_LEVEL.rawValue) { (info:Any?) in if let data = info as? Int { if (self.paused == false){ self.upgrageLevel(data) self.goNextLevel() } if (staticData.achievements.contains(data)){ staticData.saveData() self.changeBackground(data) } } } staticData.events.listenTo(GameEvent.UPDATE_FINGER.rawValue) { (info:Any?) in if let data = info as? String { let type : FingerType = FingerType(rawValue: data)! self.showMessage("\(type) Power") self.transformFinger(type) self.schedule(#selector(self.onFinishedFinger), interval: self.finger.duringTime) } } staticData.events.listenTo(GameEvent.GAME_OVER.rawValue) { self.stop() staticData.saveData() let gameover : INGameMenu = CCBReader.load("InGameMenu") as! INGameMenu gameover.updateLevelLCD(self.level) gameover.updateScoreLCD(staticData.points) gameover.position.x = (CCDirector.sharedDirector().viewSize().width - 320) / 2 gameover.position.y = (CCDirector.sharedDirector().viewSize().height - 480) / 2 gameover.gameOverView() self.addChild(gameover) } staticData.events.listenTo(GameEvent.GAME_PAUSE.rawValue) { self.stop() let gamepause : INGameMenu = CCBReader.load("InGameMenu") as! INGameMenu gamepause.updateLevelLCD(self.level) gamepause.updateScoreLCD(staticData.points) gamepause.position.x = (CCDirector.sharedDirector().viewSize().width - 320) / 2 gamepause.position.y = (CCDirector.sharedDirector().viewSize().height - 480) / 2 gamepause.gamePauseView() self.addChild(gamepause) } staticData.events.listenTo(GameEvent.GAME_RESUME.rawValue) { self.resume(); let rd = self.randomNumberBetween(0, max: StaticData.sharedInstance.achievements.count) self.changeBgMusic(StaticData.sharedInstance.achievements[rd]) } OALSimpleAudio.sharedInstance().playBg(StaticData.getSoundFile(GameSoundType.GAME_PLAYING.rawValue), loop:true) self.schedule(#selector(increaseTouches), interval: 0.01) self.upgrageLevel(staticData.level) self.start() } func initData(){ self.level = 1; self.speed = 3000; self.countOfTime = 1; } func start(){ self.paused = false self.schedule(#selector(shootElements), interval: self.timeSpeed) } func showMessage(text:String){ let _animation:Animations = CCBReader.load("Animations") as! Animations; _animation.setMessage(text); self.addChild(_animation); _animation.runAnimation(); OALSimpleAudio.sharedInstance().playEffect(StaticData.getSoundFile(GameSoundType.POWER.rawValue)) _animation.position.x = (CCDirector.sharedDirector().viewSize().width - 320) / 2 _animation.position.y += CCDirector.sharedDirector().viewSize().height - 580 _animation.animationManager.setCompletedAnimationCallbackBlock { (sender:AnyObject!) in _animation.removeFromParentAndCleanup(true) } } func changeBgMusic(index:Int){ switch index { case 20: OALSimpleAudio.sharedInstance().playBg(StaticData.getSoundFile(GameSoundType.GAME_PLAYING1.rawValue), loop:true) break case 40: OALSimpleAudio.sharedInstance().playBg(StaticData.getSoundFile(GameSoundType.GAME_PLAYING2.rawValue), loop:true) break; case 50: OALSimpleAudio.sharedInstance().playBg(StaticData.getSoundFile(GameSoundType.GAME_PLAYING3.rawValue), loop:true) break case 80: OALSimpleAudio.sharedInstance().playBg(StaticData.getSoundFile(GameSoundType.GAME_PLAYING4.rawValue), loop:true) break case 100: OALSimpleAudio.sharedInstance().playBg(StaticData.getSoundFile(GameSoundType.GAME_PLAYING.rawValue), loop:true) break default: OALSimpleAudio.sharedInstance().playBg(StaticData.getSoundFile(GameSoundType.GAME_PLAYING.rawValue), loop:true) break } } func changeBackground(index:Int){ let bg = CCBReader.load("Backgrounds/Background\(index)") let oldbg = self.backgroundNode.children[0] as! CCNode if let abg = bg { self.backgroundNode.addChild(abg,z: -1) } let action = CCActionFadeTo.actionWithDuration(5, opacity: 0.0) let callback = CCActionCallBlock { oldbg.removeFromParentAndCleanup(true) bg.zOrder = 0 } oldbg.cascadeOpacityEnabled = true; let array = [action,callback] let sq = CCActionSequence.init(array: array) oldbg.runAction(sq as CCActionSequence) changeBgMusic(index); } func stop(){ self.paused = true CCDirector.sharedDirector().pause() } func resume(){ self.paused = false CCDirector.sharedDirector().resume() } func increaseTouches(){ if (StaticData.sharedInstance.touches < 1000 && self.touched == false){ StaticData.sharedInstance.touches += 2 ; } } func upgrageLevel(newlevel:Int){ let nextSpeed = Float(newlevel) * 200 + self.speed; if (nextSpeed < 9000){ self.speed = nextSpeed }else{ self.speed = 9000; } self.level = newlevel; let newCountOfTime = 3 + Int(newlevel * (newlevel % 5)) if (newCountOfTime < 8){ self.countOfTime = newCountOfTime; }else{ self.countOfTime = 8 ; } self.timeSpeed = self.timeSpeed - 0.1; if (self.timeSpeed <= 0.1 ) { self.timeSpeed = 0.9; } } func transformFinger(type:FingerType){ let fingerFile : String = StaticData.getFingerFile(type.rawValue) let effectFile : String = StaticData.getEffectFile(EffectType.TRANSFORM.rawValue) let fingerNode : Finger = CCBReader.load(fingerFile) as! Finger let effectNode : CCParticleSystem = CCBReader.load(effectFile) as! CCParticleSystem effectNode.autoRemoveOnFinish = true let pt = finger.position; finger.removeFromParentAndCleanup(true); finger = fingerNode finger.position = pt finger.type = type; effectNode.position = pt self.addChild(finger) self.addChild(effectNode) } func onFinishedFinger(){ self.transformFinger(FingerType.Default) self.unschedule(#selector(self.onFinishedFinger)) StaticData.sharedInstance.events.trigger(GameEvent.RESET_DEFULAT_FINGER.rawValue) } override func touchBegan(touch: CCTouch!, withEvent event: CCTouchEvent!) { if (self.paused == true) { return } let touchPos = touch.locationInNode(self) self.previousTouchPos = touchPos finger.position = touchPos self.touched = true; } override func touchMoved(touch: CCTouch!, withEvent event: CCTouchEvent!) { if (self.paused == true) { return } let touchPos = touch.locationInNode(self) if ( StaticData.sharedInstance.touches > 100 ) { finger.position = touchPos }else{ let moveTo = CCActionMoveToNode.actionWithSpeed(100, positionUpdateBlock: { () -> CGPoint in return touchPos; }) self.finger.runAction(moveTo as! CCActionMoveToNode); } self.touched = true; StaticData.sharedInstance.touches -= 1 ; } override func touchEnded(touch: CCTouch!, withEvent event: CCTouchEvent!) { if (self.paused == true) { return } finger.physicsBody.sensor = true self.touched = false; self.finger.stopAllActions() } func goNextLevel(){ self.unschedule(#selector(shootElements)) StaticData.sharedInstance.points += 1 ; let _animation:Animations = CCBReader.load("Animations") as! Animations; _animation.setMessage("Wave \(level)"); self.addChild(_animation); _animation.runAnimation(); OALSimpleAudio.sharedInstance().playEffect(StaticData.getSoundFile(GameSoundType.WAVEUP.rawValue)) _animation.position.x = (CCDirector.sharedDirector().viewSize().width - 320) / 2 _animation.position.y += CCDirector.sharedDirector().viewSize().height - 530 _animation.animationManager.setCompletedAnimationCallbackBlock { (sender:AnyObject!) in _animation.removeFromParentAndCleanup(true) self.start() } } func shootElements(){ let ElementsTypes = StaticData.sharedInstance.ObjectTypes; var rotationRadians:Float = 0; for _ in 0 ..< self.countOfTime { var index:Int = self.randomNumberBetween(0,max:ElementsTypes.count); let rate: Int = self.randomNumberBetween(0,max:100); let bornRate:Int = StaticData.sharedInstance.bornRate[index]; if (rate<bornRate) { }else{ index = 0; } let type:String = ElementsTypes[index]; let blaster : Blaster = CCBReader.load(StaticData.getObjectFile(type)) as! Blaster; blaster.name = type; rotationRadians = CC_DEGREES_TO_RADIANS(180); blaster.position = CGPointMake(CGFloat(self.randomNumberBetween(60, max:Int(CCDirector.sharedDirector().viewSize().width - 60))), CCDirector.sharedDirector().viewSize().height ); let directionVector : CGPoint = ccp(CGFloat(sinf(rotationRadians)),CGFloat(cosf(rotationRadians))); let force:CGPoint = ccpMult(directionVector, CGFloat(self.speed + Float(self.randomNumberBetween(0, max: 500)))); blaster.physicsBody.applyForce(force); self.addChild(blaster); } } // override func update(delta: CCTime) { // super.update(delta) // let rotationRadians = CC_DEGREES_TO_RADIANS(180); // for node in self.children{ // if let blaster = node as? Blaster{ // let directionVector : CGPoint = ccp(CGFloat(sinf(rotationRadians)),CGFloat(cosf(rotationRadians))); // let force:CGPoint = ccpMult(directionVector, CGFloat(self.speed)); // blaster.physicsBody.applyForce(force); // } // } // // } func randomNumberBetween(min:Int,max:Int) ->Int{ return Int(arc4random_uniform(UInt32(max - min))) + min } }
mit
94f4ec1c8bc04b5d427afa93120bb141
31.93299
190
0.580496
4.459686
false
false
false
false
swordray/ruby-china-ios
RubyChina/Classes/Controllers/AccountController.swift
1
7591
// // AccountController.swift // RubyChina // // Created by Jianqiu Xiao on 2018/3/23. // Copyright ยฉ 2018 Jianqiu Xiao. All rights reserved. // import Alamofire class AccountController: ViewController { private var activityIndicatorView: ActivityIndicatorView! private var isRefreshing = false { didSet { didSetRefreshing() } } private var networkErrorView: NetworkErrorView! private var tableView: UITableView! private var user: User? override init() { super.init() navigationItem.largeTitleDisplayMode = .never title = "ๅธๅท" } override func loadView() { tableView = UITableView(frame: .zero, style: .grouped) tableView.cellLayoutMarginsFollowReadableWidth = true tableView.dataSource = self tableView.delegate = self tableView.register(AccountNameCell.self, forCellReuseIdentifier: AccountNameCell.description()) tableView.register(UITableViewCell.self, forCellReuseIdentifier: UITableViewCell.description()) view = tableView activityIndicatorView = ActivityIndicatorView() view.addSubview(activityIndicatorView) networkErrorView = NetworkErrorView() networkErrorView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(fetchData))) view.addSubview(networkErrorView) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) user = User.current tableView.indexPathsForSelectedRows?.forEach { tableView.deselectRow(at: $0, animated: animated) } fetchData() } @objc private func fetchData() { if isRefreshing { return } isRefreshing = true AF.request( baseURL .appendingPathComponent("users") .appendingPathComponent("current") .appendingPathExtension("json") ) .responseJSON { response in if 200..<300 ~= response.response?.statusCode ?? 0 { if let user = try? User(json: response.value ?? [:]), user.id != nil { User.current = user self.user = user self.tableView.reloadData() } else { self.signedOut() let topicsController = self.navigationController?.viewControllers.first as? TopicsController topicsController?.signIn() } } else { self.networkErrorView.isHidden = false } self.isRefreshing = false } } private func didSetRefreshing() { if isRefreshing { networkErrorView.isHidden = true activityIndicatorView.startAnimating() } else { activityIndicatorView.stopAnimating() } } private func signOut() { showHUD() AF.request( baseURL .appendingPathComponent("sessions") .appendingPathComponent("0") .appendingPathExtension("json"), method: .delete ) .responseJSON { response in if 200..<300 ~= response.response?.statusCode ?? 0 { self.signedOut() } else { self.networkError() } self.hideHUD() } } private func signedOut() { User.current = nil let navigationController = self.navigationController navigationController?.popViewController(animated: true) let topicsController = navigationController?.viewControllers.first as? TopicsController topicsController?.updateRightBarButtonItem() topicsController?.refetchData() } } extension AccountController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 3 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return [1, 3, 1][section] } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch (indexPath.section, indexPath.row) { case (0, 0): let cell = tableView.dequeueReusableCell(withIdentifier: AccountNameCell.description(), for: indexPath) as? AccountNameCell ?? .init() cell.user = user return cell case (1, 0): let cell = UITableViewCell(style: .value1, reuseIdentifier: nil) cell.accessoryType = .disclosureIndicator cell.detailTextLabel?.text = "GitHub" cell.textLabel?.text = "ๅ้ฆˆ" return cell case (1, 1): let cell = UITableViewCell(style: .value1, reuseIdentifier: nil) cell.accessoryType = .disclosureIndicator let diskUsage = URLCache.shared.currentDiskUsage / 1_024 / 1_024 cell.detailTextLabel?.text = diskUsage > 0 ? "\(diskUsage) MB" : "0" cell.textLabel?.text = "็ผ“ๅญ˜" return cell case (1, 2): let cell = UITableViewCell(style: .value1, reuseIdentifier: nil) let shortVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "" let version = Bundle.main.infoDictionary?[kCFBundleVersionKey as String] as? String ?? "" cell.detailTextLabel?.text = "\(shortVersion) (\(version))" cell.selectionStyle = .none cell.textLabel?.text = "็‰ˆๆœฌ" return cell case (2, 0): let cell = tableView.dequeueReusableCell(withIdentifier: UITableViewCell.description(), for: indexPath) cell.textLabel?.text = "้€€ๅ‡บ็™ปๅฝ•" cell.textLabel?.textAlignment = .center cell.textLabel?.textColor = .systemRed return cell default: return .init() } } } extension AccountController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch (indexPath.section, indexPath.row) { case (0, 0): let userController = UserController() userController.user = user navigationController?.pushViewController(userController, animated: true) case (1, 0): let webViewController = WebViewController() webViewController.title = "ๅ้ฆˆ" webViewController.url = baseURL.appendingPathComponent("feedback") navigationController?.pushViewController(webViewController, animated: true) case (1, 1): URLCache.shared.removeAllCachedResponses() tableView.reloadRows(at: [indexPath], with: .automatic) case (2, 0): tableView.deselectRow(at: indexPath, animated: true) let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) alertController.addAction(UIAlertAction(title: "้€€ๅ‡บ็™ปๅฝ•", style: .destructive) { _ in self.signOut() }) alertController.addAction(UIAlertAction(title: "ๅ–ๆถˆ", style: .cancel)) let cell = tableView.cellForRow(at: indexPath) alertController.popoverPresentationController?.permittedArrowDirections = [.up, .down] alertController.popoverPresentationController?.sourceRect = cell?.bounds ?? .zero alertController.popoverPresentationController?.sourceView = cell present(alertController, animated: true) default: break } } }
mit
d2c806ba5cf934338bfcb5a7547daa91
35.298077
146
0.616954
5.539252
false
false
false
false
mrdepth/Neocom
Legacy/Neocom/Neocom/TreeItem+CoreData.swift
2
10574
// // TreeItem+CoreData.swift // Neocom // // Created by Artem Shimanski on 29.08.2018. // Copyright ยฉ 2018 Artem Shimanski. All rights reserved. // import Foundation import CoreData import TreeController import Expressible protocol FetchedResultsControllerProtocol: class { var treeController: TreeController? {get} var diffIdentifier: AnyHashable {get} } protocol FetchedResultsSectionProtocol: class { /*weak*/ var controller: FetchedResultsControllerProtocol? {get} } protocol FetchedResultsSectionTreeItem: TreeItem, FetchedResultsSectionProtocol where Child: FetchedResultsTreeItem { var sectionInfo: NSFetchedResultsSectionInfo {get} var children: [Child]? {get set} init(_ sectionInfo: NSFetchedResultsSectionInfo, controller: FetchedResultsControllerProtocol) } protocol FetchedResultsTreeItem: TreeItem { associatedtype Result: NSFetchRequestResult & Equatable var result: Result {get} /*weak*/ var section: FetchedResultsSectionProtocol? {get set} init(_ result: Result, section: FetchedResultsSectionProtocol) } extension Tree.Item { class FetchedResultsController<T: FetchedResultsSectionTreeItem>: NSObject, TreeItem, NSFetchedResultsControllerDelegate, FetchedResultsControllerProtocol { typealias Section = T var fetchedResultsController: NSFetchedResultsController<Section.Child.Result> weak var treeController: TreeController? override var hash: Int { return fetchedResultsController.fetchRequest.hash } typealias DiffIdentifier = AnyHashable var diffIdentifier: AnyHashable lazy var children: [Section]? = { if fetchedResultsController.fetchedObjects == nil { try? fetchedResultsController.performFetch() } return fetchedResultsController.sections?.map {Child($0, controller: self)} }() init<T: Hashable>(_ fetchedResultsController: NSFetchedResultsController<Section.Child.Result>, diffIdentifier: T, treeController: TreeController?) { self.fetchedResultsController = fetchedResultsController self.diffIdentifier = AnyHashable(diffIdentifier) self.treeController = treeController super.init() if fetchedResultsController.fetchRequest.resultType == .managedObjectResultType { fetchedResultsController.delegate = self } } convenience init(_ fetchedResultsController: NSFetchedResultsController<Section.Child.Result>, treeController: TreeController?) { self.init(fetchedResultsController, diffIdentifier: fetchedResultsController.fetchRequest, treeController: treeController) } static func == (lhs: Tree.Item.FetchedResultsController<Section>, rhs: Tree.Item.FetchedResultsController<Section>) -> Bool { return lhs.fetchedResultsController.fetchRequest == rhs.fetchedResultsController.fetchRequest } override func isEqual(_ object: Any?) -> Bool { guard let rhs = object as? FetchedResultsController<Section> else {return false} return fetchedResultsController.fetchRequest == rhs.fetchedResultsController.fetchRequest } private struct Updates { var sectionInsertions = [(Int, NSFetchedResultsSectionInfo)]() var sectionDeletions = IndexSet() var itemInsertions = [(IndexPath, Any)]() var itemDeletions = [IndexPath]() var isEmpty: Bool { return sectionInsertions.isEmpty && sectionDeletions.isEmpty && itemInsertions.isEmpty && itemDeletions.isEmpty && itemUpdates.isEmpty } var itemUpdates = [(IndexPath, Any)]() } private var updates: Updates? func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { updates = Updates() } func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { switch type { case .insert: updates?.itemInsertions.append((newIndexPath!, anObject)) case .delete: updates?.itemDeletions.append(indexPath!) case .move: updates?.itemDeletions.append(indexPath!) updates?.itemInsertions.append((newIndexPath!, anObject)) case .update: updates?.itemUpdates.append((newIndexPath!, anObject)) @unknown default: break } } func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) { switch type { case .insert: updates?.sectionInsertions.append((sectionIndex, sectionInfo)) case .delete: updates?.sectionDeletions.insert(sectionIndex) default: break } } func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { updates?.itemDeletions.sorted().reversed().forEach { children![$0.section].children?.remove(at: $0.item) } updates?.sectionDeletions.rangeView.reversed().forEach { children!.removeSubrange($0) } updates?.sectionInsertions.sorted {$0.0 < $1.0}.forEach { children!.insert(Section($0.1, controller: self), at: $0.0) } updates?.itemInsertions.sorted {$0.0 < $1.0}.forEach { i in let section = children![i.0.section] if var item = i.1 as? Section.Child { item.section = section section.children!.insert(item, at: i.0.item) } else if let result = i.1 as? Section.Child.Result { let item = Section.Child(result, section: section) section.children!.insert(item, at: i.0.item) } } updates?.itemUpdates.forEach { i in let section = children![i.0.section] section.children!.remove(at: i.0.item) let item = Section.Child(i.1 as! Section.Child.Result, section: section) children![i.0.section].children!.insert(item, at: i.0.item) } if updates?.isEmpty == false { treeController?.update(contentsOf: self, with: .fade) } updates?.itemUpdates.forEach { i in let item = children![i.0.section].children![i.0.item] treeController?.reloadRow(for: item, with: .fade) } updates = nil } } class FetchedResultsSection<Item: FetchedResultsTreeItem>: TreeItem, FetchedResultsSectionTreeItem { func isEqual(_ other: FetchedResultsSection<Item>) -> Bool { return type(of: self) == type(of: other) && sectionInfo.name == other.sectionInfo.name && diffIdentifier == other.diffIdentifier } static func == (lhs: Tree.Item.FetchedResultsSection<Item>, rhs: Tree.Item.FetchedResultsSection<Item>) -> Bool { return lhs.isEqual(rhs) } weak var controller: FetchedResultsControllerProtocol? var diffIdentifier: AnyHashable var sectionInfo: NSFetchedResultsSectionInfo var hashValue: Int { return diffIdentifier.hashValue } lazy var children: [Item]? = sectionInfo.objects?.map{Item($0 as! Item.Result, section: self)} required init(_ sectionInfo: NSFetchedResultsSectionInfo, controller: FetchedResultsControllerProtocol) { self.sectionInfo = sectionInfo self.controller = controller self.diffIdentifier = [controller.diffIdentifier, sectionInfo.name] } } class FetchedResultsRow<Result: NSFetchRequestResult & Equatable & Hashable>: FetchedResultsTreeItem, CellConfigurable { var prototype: Prototype? { return (result as? CellConfigurable)?.prototype } func configure(cell: UITableViewCell, treeController: TreeController?) { (result as? CellConfigurable)?.configure(cell: cell, treeController: treeController) } var result: Result weak var section: FetchedResultsSectionProtocol? required init(_ result: Result, section: FetchedResultsSectionProtocol) { self.result = result self.section = section } var hashValue: Int { return result.hash } typealias DiffIdentifier = Result var diffIdentifier: Result { return result } func isEqual(_ other: FetchedResultsRow<Result>) -> Bool { return type(of: self) == type(of: other) && result == other.result } static func == (lhs: FetchedResultsRow<Result>, rhs: FetchedResultsRow<Result>) -> Bool { return lhs.isEqual(rhs) } } class NamedFetchedResultsController<Section: FetchedResultsSectionTreeItem>: FetchedResultsController<Section>, CellConfigurable, ItemExpandable { var isExpanded: Bool var prototype: Prototype? { return content.prototype } var expandIdentifier: CustomStringConvertible? var content: Tree.Content.Section init<T: Hashable>(_ content: Tree.Content.Section, fetchedResultsController: NSFetchedResultsController<Section.Child.Result>, isExpanded: Bool = true, diffIdentifier: T, expandIdentifier: CustomStringConvertible? = nil, treeController: TreeController?) { self.expandIdentifier = expandIdentifier self.content = content self.isExpanded = isExpanded super.init(fetchedResultsController, diffIdentifier: diffIdentifier, treeController: treeController) } convenience init(_ content: Tree.Content.Section, fetchedResultsController: NSFetchedResultsController<Section.Child.Result>, isExpanded: Bool = true, expandIdentifier: CustomStringConvertible? = nil, treeController: TreeController?) { self.init(content, fetchedResultsController: fetchedResultsController, isExpanded: isExpanded, diffIdentifier: fetchedResultsController.fetchRequest, expandIdentifier: expandIdentifier, treeController: treeController) } func configure(cell: UITableViewCell, treeController: TreeController?) { content.configure(cell: cell, treeController: treeController) guard let cell = cell as? TreeSectionCell else {return} // cell.expandIconView?.image = treeController?.isItemExpanded(self) == true ? #imageLiteral(resourceName: "collapse") : #imageLiteral(resourceName: "expand") cell.expandIconView?.image = isExpanded ? #imageLiteral(resourceName: "collapse") : #imageLiteral(resourceName: "expand") } } class NamedFetchedResultsSection<Item: FetchedResultsTreeItem>: FetchedResultsSection<Item>, CellConfigurable, ItemExpandable { var isExpanded: Bool = true var prototype: Prototype? { return Prototype.TreeSectionCell.default } var expandIdentifier: CustomStringConvertible? var name: String { return sectionInfo.name.uppercased() } func configure(cell: UITableViewCell, treeController: TreeController?) { guard let cell = cell as? TreeSectionCell else {return} cell.titleLabel?.text = name // cell.expandIconView?.image = treeController?.isItemExpanded(self) == true ? #imageLiteral(resourceName: "collapse") : #imageLiteral(resourceName: "expand") cell.expandIconView?.image = isExpanded ? #imageLiteral(resourceName: "collapse") : #imageLiteral(resourceName: "expand") } } }
lgpl-2.1
27e61fefd79ef1fd2540b6c39a137e1e
36.626335
257
0.752483
4.470613
false
false
false
false
proxpero/Endgame
Sources/Game+Transaction.swift
1
3691
// // Game+Transaction.swift // Endgame // // Created by Todd Olsen on 3/28/17. // // /* struct TransactionSet { typealias Space = Board.Space typealias Event = Game.Event typealias Direction = Game.Event.Direction /// The underlying storage. fileprivate(set) var transactions: Set<Transaction> = [] } extension TransactionSet { /// Initialize with an arraySlice of `Event`s and a `Direction`. init(events: ArraySlice<Event>, in direction: Direction) { self = TransactionSet() for event in events { insert(event, for: direction) } } /// public var synthesis: Array<Transaction> { return Array(transactions) } func map<A>(f: @escaping (Transaction) -> A) -> [A] { return transactions.map(f) } } extension TransactionSet: CustomStringConvertible { /// CustomStringConvertible conformance var description: String { var result = "" for transaction in transactions { result += "\(transaction)\n" } return result } } extension TransactionSet { mutating func merge(_ element: Transaction) { let candidates = transactions.filter { $0.target == element.origin } guard candidates.count < 2 else { fatalError("Unexpected extra candidate \(candidates)") } guard candidates.count != 0 else { transactions.insert(element) return } let previous = candidates[0] transactions.remove(previous) let new = Transaction( origin: previous.origin, target: element.target ) transactions.insert(new) } mutating func insert(_ event: Event, for direction: Direction) { guard let history = event.history else { fatalError("no history for \(event)") } let move = direction.isUndo ? history.move.reversed() : history.move let (old, new): (Piece, Piece) = { guard let promotion = history.promotion else { return (history.piece, history.piece) } if direction.isRedo { return (history.piece, promotion) } else { return (promotion, history.piece) } }() merge(Transaction( origin: Space(piece: old, square: move.origin), target: Space(piece: new, square: move.target)) ) if let capture = history.capture { let origin: Space let target: Space switch direction { case .redo: origin = capture target = Space( piece: nil, square: capture.square ) case .undo: origin = Space(piece: nil, square: capture.square) target = capture } merge(Transaction( origin: origin, target: target) ) } if history.move.isCastle() && history.piece.kind == .king { let (old, new) = history.move.castleSquares() let rook = Piece(rook: history.piece.color) switch direction { case .redo: merge(Transaction( origin: Space(piece: rook, square: old), target: Space(piece: rook, square: new)) ) case .undo: merge(Transaction( origin: Space(piece: rook, square: new), target: Space(piece: rook, square: old)) ) } } } } */
mit
cb1361452cc85b496e5caa5118643649
23.939189
98
0.526687
4.79974
false
false
false
false
thislooksfun/Tavi
Tavi/Helper/OverloadsAndConvenience.swift
1
17479
// // OverloadsAndConvenience.swift // Tavi // // Copyright (C) 2016 thislooksfun // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // import UIKit //MARK: Extensions /// Adds easier ways to get the length of and split the string extension String { /// The length of the string - wrapper for `.characters.count` var length: Int { get { return self.characters.count } } var range: NSRange { get { return NSMakeRange(0, self.length) } } /// Splits this string on the given seperator /// /// - Parameters: /// - str: The string to split on /// - ignoreEmpty: Whether or not to ignore empty sections /// /// - Returns: A `String` array of the split string public func split(str: String, ignoreEmpty: Bool = false) -> [String] { if ignoreEmpty { var parts = [String]() for part in self.componentsSeparatedByString(str) { if !part.isEmpty { parts.append(part) } } return parts } else { return self.componentsSeparatedByString(str) } } /// Ensures this string is at least `minLength` characters long /// /// - Note: If `fill` is an empty string `""`, this function will abort /// /// - Parameters: /// - minLength: The minimum length of the string /// - fill: The string with which to pad out the missing length /// - prepend: Whether or not to prepend the `fill` string - used to right-justify text public mutating func ensureAtLeast(minLength: Int, fillWith fill: String = " ", prepend: Bool = false){ guard !fill.isEmpty else { return } //Don't try to append nothing to the end, won't go well if self.length >= minLength { return // Length is already at least `length`, no point } while self.length < minLength { if prepend { self = fill + self } else { self += fill } } } } /// Adds date -> time calculations extension NSDate { /// Calculates how long ago this date was /// /// - Returns: the `NSDateComponents` of how long ago it was. (Uses `.Second`, `.Minute`, `.Hour`, `.Day`, `.WeekOfYear`, `.Month`, and `.Year`) func timeAgo() -> NSDateComponents { return self.timeTo(NSDate()) } /// Calculates how long until the given date /// /// - Parameter date: The date to calculate the time to /// /// - Returns: the `NSDateComponents` of how long ago it was. (Uses `.Second`, `.Minute`, `.Hour`, `.Day`, `.WeekOfYear`, `.Month`, and `.Year`) func timeTo(date: NSDate) -> NSDateComponents { let calendar = NSCalendar.currentCalendar() calendar.timeZone = NSTimeZone(name: "GMT")! let units: NSCalendarUnit = [.Second, .Minute, .Hour, .Day, .WeekOfYear, .Month, .Year] return calendar.components(units, fromDate: self, toDate: date, options: []) } } /// Adds the ability to create gradient layers from general information extension CAGradientLayer { /// Creates a gradient layer /// /// - Parameters: /// - bounds: The bounds of the layer /// - colors: The colors to use /// - start: The start point /// - end: The end point /// /// - SeeAlso: `CAGradientLayer` class func gradientLayerForBounds(bounds: CGRect, andColors colors: [CGColor], andStartPoint start: CGPoint, andEndPoint end: CGPoint) -> CAGradientLayer { let layer = CAGradientLayer() layer.frame = bounds layer.colors = colors layer.startPoint = start layer.endPoint = end return layer } } /// Adds methods for finding the top-most view controller extension UIViewController { /// Finds the 'highest' view controller /// /// - Returns: The 'highest' view controller func findBestViewController() -> UIViewController { if let presented = self.presentedViewController { // Return presented view controller return presented.findBestViewController() } else if self is UISplitViewController { // Return right hand side let svc = self as! UISplitViewController if (svc.viewControllers.count > 0) { return svc.viewControllers.last!.findBestViewController() } else { return self; } } else if self is UINavigationController { // Return top view let svc = self as! UINavigationController if svc.viewControllers.count > 0 { return svc.topViewController!.findBestViewController() } else { return self } } else if self is UITabBarController { // Return visible view let svc = self as! UITabBarController if svc.viewControllers != nil && svc.viewControllers!.count > 0 { return svc.selectedViewController!.findBestViewController() } else { return self; } } else { // Unknown view controller type, return last child view controller return self; } } /// Finds the 'highest' view controller for the current `rootViewController` /// This is identical to calling `UIViewController.rootViewController().findBestViewController()` /// /// - Returns: The 'highest' view controller static func currentViewController() -> UIViewController { // Find best view controller return rootViewController().findBestViewController() } /// Gets the current root view controller for the app /// /// - Returns: The current root view controller static func rootViewController() -> UIViewController { return UIApplication.sharedApplication().keyWindow!.rootViewController! } } /// A simple protocol of a hidable object protocol Hidable { /// Shows the object /// /// - Parameters: /// - maxAlpha: The maximum alpha value /// - duration: The animation duration /// - delay: The animation delay /// - options: The animation options /// - completion: What to do when the animation finishes func show(maxAlpha maxAlpha: CGFloat, duration: Double, delay: Double, options: UIViewAnimationOptions, completion: ((finished: Bool) -> Void)?) /// Hides the object /// /// - Parameters: /// - minAlpha: The minimum alpha value /// - duration: The animation duration /// - delay: The animation delay /// - options: The animation options /// - completion: What to do when the animation finishes func hide(minAlpha minAlpha: CGFloat, duration: Double, delay: Double, options: UIViewAnimationOptions, completion: ((finished: Bool) -> Void)?) } /// Adds simple hide/show functions extension UIView { /// Shows the view /// /// - Parameters: /// - maxAlpha: The maximum alpha value (Default: `1`) /// - duration: The animation duration (Default: `0.3`) /// - delay: The animation delay (Default: `0`) /// - options: The animation options (Default: `[]`) /// - completion: What to do when the animation finishes (Default: `nil`) func show(maxAlpha maxAlpha: CGFloat = 1, duration: Double = 0.3, delay: Double = 0, options: UIViewAnimationOptions = [], completion: ((finished: Bool) -> Void)? = nil) { self.hidden = false guard duration > 0 else { self.alpha = maxAlpha return } UIView.animateWithDuration(duration, delay: delay, options: UIViewAnimationOptions.BeginFromCurrentState, animations: { self.alpha = maxAlpha }, completion: nil) } /// Hides the view /// /// - Parameters: /// - minAlpha: The minimum alpha value (Default: `0`) /// - duration: The animation duration (Default: `0.3`) /// - delay: The animation delay (Default: `0`) /// - options: The animation options (Default: `[]`) /// - completion: What to do when the animation finishes (Default: `nil`) func hide(minAlpha minAlpha: CGFloat = 0, duration: Double = 0.3, delay: Double = 0, options: UIViewAnimationOptions = [], completion: ((finished: Bool) -> Void)? = nil) { guard duration > 0 else { self.alpha = minAlpha self.hidden = true return } UIView.animateWithDuration(duration, animations: { self.alpha = minAlpha }) { (finished) in self.hidden = minAlpha <= 0 completion?(finished: finished) } } } /// Adds a method to force the device orientation extension UIDevice { /// Forces the device orientation /// /// - Warning: This often causes problems with animations and various other visual glitches. /// Use carefully. /// /// - Parameter orientation: The orientation to force func forceOrientation(orientation: UIInterfaceOrientation) { self.setValue(orientation.rawValue, forKey: "orientation") } } /// Adds a way to invert the boolean value extension Bool { /// Inverts this Bool\ /// `true` becomes `false` and `false` becomes `true` mutating func invert() { self = !self } } /// Adds find methods extension SequenceType { /// Finds an element in the sequence /// /// - Parameter search: The closure to use to check if the current element is the currect one /// /// - Returns: The found element, or `nil` if none was found func find(search: (Self.Generator.Element) -> Bool) -> Self.Generator.Element? { for el in self { if search(el) { return el } } return nil } /// Finds an element in the sequence /// /// - Parameter search: The closure to use to check if the current element is the currect one /// /// - Returns: `(index: Int, element: Self.Generator.Element?)`\ /// where `index` is the index of the element in the sequence, or `-1` if no matching element was found /// and `element` is the found element, or `nil` if none was found func findWithPos(search: (Self.Generator.Element) -> Bool) -> (index: Int, element: Self.Generator.Element?) { for (index, el) in self.enumerate() { if search(el) { return (index, el) } } return (-1, nil) } } /// Adds find methods for `Equatable` objects extension SequenceType where Generator.Element: Equatable { /// Finds an element in the sequence /// /// - Parameter element: The element to find /// /// - Returns: The found element, or `nil` if none was found func find(element: Self.Generator.Element) -> Self.Generator.Element? { for el in self { if el == element { return el } } return nil } /// Finds an element in the sequence /// /// - Parameter element: The element to find /// /// - Returns: `(index: Int, element: Self.Generator.Element?)`\ /// where `index` is the index of the element in the sequence, or -1 if no matching element was found /// and `element` is the found element, or `nil` if none was found func findWithPos(element: Self.Generator.Element) -> (index: Int, element: Self.Generator.Element?) { for (index, el) in self.enumerate() { if el == element { return (index, el) } } return (-1, nil) } } /// Adds a move method extension Array { /// Moves an element in the `Array` /// /// - Parameters: /// - from: The index to move from /// - end: The index to move to mutating func moveElementFromPos(from: Int, toPos end: Int) { let tmp = self.removeAtIndex(from) self.insert(tmp, atIndex: end) } } /// Adds a way to remove duplicate entries from a sorted list extension Array where Element: Comparable { /// Removes any duplicate elements from a sorted array /// /// - Warning: This array **must** be pre-sorted for this to work mutating func removeDuplicates() { var out = [Element]() for repo in self { Logger.info("removedupes") if repo == out.last { out.append(repo) } } self = out } } /// A basic view orientation enum public enum ViewOrientation { /// Is Portrait (Either Portrait or PortraitUpsideDown) case Portrait /// Is Landscape. (Either LandscapeLeft or LandscapeRight case Landscape } /// Adds methods to get the orientation from the views size extension UIView { /// Gets the `ViewOrientation` for a given size /// /// - Parameter size: The size to check /// /// - Returns: The `ViewOrientation` for the given size public class func viewOrientationForSize(size:CGSize) -> ViewOrientation { return (size.width > size.height) ? .Landscape : .Portrait } /// The current view orientation for this view public var viewOrientation:ViewOrientation { return UIView.viewOrientationForSize(self.bounds.size) } /// Whether or not the `viewOrientation` is Portrait public func isViewOrientationPortrait() -> Bool { return self.viewOrientation == .Portrait } /// Whether or not the `viewOrientation` is Landscape public func isViewOrientationLandscape() -> Bool { return self.viewOrientation == .Landscape } } //MARK: - Functions /// Pases a string into a date /// /// - Note: The string must be in the format `"yyyy-MM-dd'T'HH:mm:ssZ"` /// /// - Parameter date: The string to parse /// /// - Returns: An `NSDate`, or `nil` if the conversion was unsuccessful func parseDate(date: String) -> NSDate? { let formatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" return formatter.dateFromString(date) } /// Runs the given callback asyncronously, after the specified delay. /// /// - Parameters: /// - delay: If `delay <= 0`, it behaves exactly the same as `async` /// - onNewThread: If `onNewThread` is false, it runs on the main thread, otherwise it runs on a new thread with the given priority. (Default: `false`) /// - withPriority: The priority with which to start the new thread. Only used if `onNewThread` is true. (Default: `DISPATCH_QUEUE_PRIORITY_DEFAULT`) /// - cb: The callback to run on the given thread func delay(delay: Double, onNewThread: Bool = false, withPriority priority: dispatch_queue_priority_t = DISPATCH_QUEUE_PRIORITY_DEFAULT, cb: () -> Void) { guard delay > 0 else { async(onNewThread: onNewThread, withPriority: priority, cb: cb) return } let thread = onNewThread ? dispatch_get_global_queue(priority, 0) : dispatch_get_main_queue() dispatch_after( dispatch_time( DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)) ), thread, cb) } /// Runs the given callback asyncronously, immediatly. /// /// - Parameters: /// - onNewThread: If onNewThread is false, it runs on the main thread, otherwise it runs on a new thread with the given priority. (Default: `false`) /// - withPriority: The priority with which to start the new thread. Only used if onNewThread is true. (Default: `DISPATCH_QUEUE_PRIORITY_DEFAULT`) /// - cb: The callback to run on the given thread func async(onNewThread onNewThread: Bool = false, withPriority priority: dispatch_queue_priority_t = DISPATCH_QUEUE_PRIORITY_DEFAULT, cb: () -> Void) { let thread = onNewThread ? dispatch_get_global_queue(priority, 0) : dispatch_get_main_queue() dispatch_async(thread, cb) } //MARK: - Overloads /// Easy regex matching infix operator =~ {} /// Easy regex matching func =~(input: String, pattern: String) -> Bool { guard let regex = try? NSRegularExpression(pattern: pattern, options: []) else { return false } let matches = regex.matchesInString(input, options: [], range: input.range) return matches.count > 0 } /// Inserts `left` into `right` at index `0` /// /// - Returns: The expanded array func + <ValueType> (left: ValueType, right: [ValueType]) -> [ValueType] { var out = right out.insert(left, atIndex: 0) return out } /// Appends `right` onto `left` /// /// - Returns: The expanded array func + <ValueType> (left: [ValueType], right: ValueType) -> [ValueType] { var out = left out.append(right) return out } /// Appends `right` onto `left` func += <ValueType> (inout left: [ValueType], right: ValueType) { left = left + right } /// Appends `right` onto `left` func += (left: NSMutableAttributedString, right: NSAttributedString) { left.appendAttributedString(right) } /// Converts `right` into a `NSAttributedString`, then appends it to `left` func += (left: NSMutableAttributedString, right: String) { left += NSAttributedString(string: right) } // MARK: Boolean operators /// Logically identical to `left = left && right` infix operator &&= {} /// Logically identical to `left = left && right` func &&=(inout left: Bool, right: Bool) { left = left && right } // MARK: Int & CGFloat arithmetic /// Adds a `CGFloat` to an `Int` func +(left: CGFloat, right: Int) -> CGFloat { return left + CGFloat(right) } /// Adds an `Int` to an `CGFloat` func +(left: Int, right: CGFloat) -> CGFloat { return right + left } /// Subtracts an `Int` from a `CGFloat` func -(left: CGFloat, right: Int) -> CGFloat { return left - CGFloat(right) } /// Subtracts a `CGFloat` from an `Int` func -(left: Int, right: CGFloat) -> CGFloat { return CGFloat(left) - right } // MARK: Re-add ++ /// Prefix declaration of ++ prefix operator ++ {} /// Prefix definition of ++ prefix func ++(inout oper: Int) -> Int { oper += 1 return oper } /// Postfix declaration of ++ postfix operator ++ {} /// Postfix definition of ++ postfix func ++(inout oper: Int) -> Int { let old = oper oper += 1 return old } // MARK: Re-add -- /// Prefix declaration of -- prefix operator -- {} /// Prefix definition of -- prefix func --(inout oper: Int) -> Int { oper -= 1 return oper } /// Postfix declaration of -- postfix operator -- {} /// Postfix definition of -- postfix func --(inout oper: Int) -> Int { let old = oper oper -= 1 return old }
gpl-3.0
9229951f0172b0ad1227c419e88a2f33
28.829352
170
0.678128
3.649061
false
false
false
false
vadymmarkov/Tuner
Source/SignalTracking/Units/OutputSignalTracker.swift
3
1706
import AVFoundation final class OutputSignalTracker: SignalTracker { weak var delegate: SignalTrackerDelegate? var levelThreshold: Float? private let bufferSize: AVAudioFrameCount private let audioUrl: URL private var audioEngine: AVAudioEngine! private var audioPlayer: AVAudioPlayerNode! private let bus = 0 var peakLevel: Float? { return 0.0 } var averageLevel: Float? { return 0.0 } var mode: SignalTrackerMode { return .playback } // MARK: - Initialization required init(audioUrl: URL, bufferSize: AVAudioFrameCount = 2048, delegate: SignalTrackerDelegate? = nil) { self.audioUrl = audioUrl self.bufferSize = bufferSize self.delegate = delegate } // MARK: - Tracking func start() throws { let session = AVAudioSession.sharedInstance() try session.setCategory(AVAudioSession.Category.playback) audioEngine = AVAudioEngine() audioPlayer = AVAudioPlayerNode() let audioFile = try AVAudioFile(forReading: audioUrl) audioEngine.attach(audioPlayer) audioEngine.connect(audioPlayer, to: audioEngine.outputNode, format: audioFile.processingFormat) audioPlayer.scheduleFile(audioFile, at: nil, completionHandler: nil) audioEngine.outputNode.installTap(onBus: bus, bufferSize: bufferSize, format: nil) { buffer, time in DispatchQueue.main.async { self.delegate?.signalTracker(self, didReceiveBuffer: buffer, atTime: time) } } audioEngine.prepare() try audioEngine.start() audioPlayer.play() } func stop() { audioPlayer.stop() audioEngine.stop() audioEngine.reset() audioEngine = nil audioPlayer = nil } }
mit
c6d28f9e35be6c198948f2b773dcba94
23.724638
104
0.702227
4.738889
false
false
false
false
karthik-ios-dev/MySwiftExtension
Pod/Classes/Date-Extension.swift
1
5119
// // Date-Extension.swift // DateHelper // // Created by Karthik on 18/11/15. // Copyright ยฉ 2015 Karthik. All rights reserved. // import UIKit //MARK: DATE EXTENSIONS public extension NSDate{ // Addings func daysBetweenDate(date:NSDate) -> Int { return NSCalendar.gregorianCalendar().components(.Day, fromDate: self, toDate: date, options: []).day } func dateByAddingDays(days: Int) -> NSDate { return NSCalendar.gregorianCalendar().dateByAddingUnit(.Day, value: days, toDate: self, options: [])! } func dateByAddingWeeks(weeks: Int) -> NSDate { return NSCalendar.gregorianCalendar().dateByAddingUnit(.WeekOfYear, value: weeks, toDate: self, options: [])! } func dateByAddingMonths(months: Int) -> NSDate { return NSCalendar.gregorianCalendar().dateByAddingUnit(.Month, value: months, toDate: self, options: [])! } func dateBySubtractingDays(days: Int) -> NSDate { return NSCalendar.gregorianCalendar().dateByAddingUnit(.Day, value: -days, toDate: self, options: [])! } func dateBySubtractingWeeks(weeks: Int) -> NSDate { return NSCalendar.gregorianCalendar().dateByAddingUnit(.WeekOfYear, value: -weeks, toDate: self, options: [])! } func dateBySubtractingMonths(months: Int) -> NSDate { return NSCalendar.gregorianCalendar().dateByAddingUnit(.Month, value: -months, toDate: self, options: [])! } // counts Bw dats (days,weeks,monts,years) func hoursFrom(date:NSDate) -> Int{ return NSCalendar.currentCalendar().components(.Hour, fromDate: date, toDate: self, options: []).hour } func minutesFrom(date:NSDate) -> Int{ return NSCalendar.currentCalendar().components(.Minute, fromDate: date, toDate: self, options: []).minute } func secondsFrom(date:NSDate) -> Int{ return NSCalendar.currentCalendar().components(.Second, fromDate: date, toDate: self, options: []).second } func yearsFrom(date:NSDate) -> Int{ return NSCalendar.currentCalendar().components(.Year, fromDate: date, toDate: self, options: []).year } func monthsFrom(date:NSDate) -> Int{ return NSCalendar.currentCalendar().components(.Month, fromDate: date, toDate: self, options: []).month } func weeksFrom(date:NSDate) -> Int{ return NSCalendar.currentCalendar().components(.WeekOfYear, fromDate: date, toDate: self, options: []).weekOfYear } func daysFrom(date:NSDate) -> Int{ return NSCalendar.currentCalendar().components(.Day, fromDate: date, toDate: self, options: []).day } func offsetFrom(date:NSDate) -> String { if yearsFrom(date) > 0 { return "\(yearsFrom(date))y" } if monthsFrom(date) > 0 { return "\(monthsFrom(date))M" } if weeksFrom(date) > 0 { return "\(weeksFrom(date))w" } if daysFrom(date) > 0 { return "\(daysFrom(date))d" } if hoursFrom(date) > 0 { return "\(hoursFrom(date))h" } if minutesFrom(date) > 0 { return "\(minutesFrom(date))m" } if secondsFrom(date) > 0 { return "\(secondsFrom(date))s" } return "" } //comparisions func isEqualsTo(date: NSDate) -> Bool { return self.compare(date) == NSComparisonResult.OrderedSame } func isGreaterThan(date: NSDate) -> Bool { // today.isGreaterThan(yesterday) return self.compare(date) == NSComparisonResult.OrderedDescending } func isLessThan(date: NSDate) -> Bool { // today.isLessThan(Tomorrow) return self.compare(date) == NSComparisonResult.OrderedAscending } // date => String func toString(format: String = "yyyy-MM-dd HH:mm:ss") -> String{ let formatter = NSDateFormatter() formatter.dateFormat = format return formatter.stringFromDate(self) } // String => date class func dateFromString(dateString: String, format: String = "yyyy-MM-dd HH:mm:ss") -> NSDate{ let formatter = NSDateFormatter() formatter.dateFormat = format return formatter.dateFromString(dateString)! } class func daysBetweenDate(startDate: NSDate, endDate: NSDate) -> Int { return NSCalendar.gregorianCalendar().components(.Day, fromDate: startDate, toDate: endDate, options: []).day } class func getMilliSecondsLongFromSecondsLong(secondsLong : Int64) -> Int64{ return (secondsLong * 1000) } } extension NSDate : Comparable{ } func + (date: NSDate, timeInterval: NSTimeInterval) -> NSDate { return date.dateByAddingTimeInterval(timeInterval) } public func ==(lhs: NSDate, rhs: NSDate) -> Bool { if lhs.compare(rhs) == .OrderedSame { return true } return false } // dateOne is older than dateTwo public func <(lhs: NSDate, rhs: NSDate) -> Bool { if lhs.compare(rhs) == .OrderedAscending { return true } return false } // dateOne is more recent(new) than dateTwo(old or past) public func >(lhs: NSDate, rhs: NSDate) -> Bool { if lhs.compare(rhs) == .OrderedDescending { return true } return false }
mit
4faf3dec33ad471a2417c9a2b7ba278a
37.481203
121
0.65084
4.195082
false
false
false
false
rokuz/omim
iphone/Maps/UI/PlacePage/PlacePageLayout/Content/CatalogPromo/CatalogSingleItemCell.swift
1
1314
@objc class CatalogSingleItemCell: UITableViewCell { @IBOutlet var placeTitleLabel: UILabel! @IBOutlet var placeDescriptionLabel: UILabel! @IBOutlet var guideNameLabel: UILabel! @IBOutlet var guideAuthorLabel: UILabel! @IBOutlet var moreButton: UIButton! @IBOutlet var placeImageView: UIImageView! @IBOutlet var openCatalogButton: UIButton! @IBOutlet var moreButtonHeightConstraint: NSLayoutConstraint! @IBOutlet var guideContainerView: UIView! @IBOutlet var headerLabel: UILabel! @objc var onMore: MWMVoidBlock? @objc var onView: MWMVoidBlock? override func awakeFromNib() { super.awakeFromNib() guideContainerView.layer.borderColor = UIColor.blackDividers().cgColor headerLabel.text = L("pp_discovery_place_related_header").uppercased() } @objc func config(_ promoItem: CatalogPromoItem) { placeTitleLabel.text = promoItem.placeTitle placeDescriptionLabel.text = promoItem.placeDescription guideNameLabel.text = promoItem.guideName guideAuthorLabel.text = promoItem.guideAuthor guard let url = URL(string: promoItem.imageUrl) else { return } placeImageView.wi_setImage(with: url) } @IBAction func onMoreButton(_ sender: UIButton) { onMore?() } @IBAction func onCatalogButton(_ sender: UIButton) { onView?() } }
apache-2.0
be5c74d0c9906d7e706c377893d090d3
31.85
74
0.747336
4.409396
false
false
false
false
mvader/advent-of-code
2021/03/02.swift
1
1092
import Foundation let lines = try String(contentsOfFile: "./input.txt", encoding: .utf8).split(separator: "\n") let diagnostic = lines.map { line in Int(line, radix: 2)! } let rowSize = lines.first!.count let oxygenRating = rating(diagnostic, rowSize, mostCommon) let co2Rating = rating(diagnostic, rowSize, leastCommon) print(oxygenRating * co2Rating) func rating(_ numbers: [Int], _ bits: Int, _ criteria: ([Int], Int) -> Int) -> Int { let selector = criteria(numbers, bits - 1) let selected = numbers.filter { n in bitAt(n, bits - 1) == selector } if selected.count == 1 { return selected.first! } return rating(selected, bits - 1, criteria) } func bitAt(_ n: Int, _ bit: Int) -> Int { return n & (1 << bit) > 0 ? 1 : 0 } func leastCommon(_ numbers: [Int], _ bit: Int) -> Int { let ones = numbers.map { ($0 & (1 << bit) > 0) ? 1 : 0 }.reduce(0, +) return (numbers.count - ones) <= ones ? 0 : 1 } func mostCommon(_ numbers: [Int], _ bit: Int) -> Int { let ones = numbers.map { ($0 & (1 << bit) > 0) ? 1 : 0 }.reduce(0, +) return (numbers.count - ones) > ones ? 0 : 1 }
mit
c78e675758cc80b268add714c8039646
30.2
93
0.624542
2.943396
false
false
false
false
ihomway/RayWenderlichCourses
Advanced Swift 3/Advanced Swift 3.playground/Pages/Hashable Types.xcplaygroundpage/Contents.swift
1
1060
//: [Previous](@previous) import Foundation protocol HashAlgorithm { mutating func consume<S: Sequence>(byte: S) where S.Iterator.Element == UInt8 var finalValue: Int { get } } extension HashAlgorithm { mutating func consume(_ string: String) { consume(byte: string.utf8) } mutating func consume(_ bool: Bool) { let value: UInt8 = bool ? 1 : 0 consume(byte: CollectionOfOne(value)) } } extension FVN1AHash: HashAlgorithm {} struct NamedPosition: Hashable { var name: String var x: Int var y: Int static func ==(lhs: NamedPosition, rhs: NamedPosition) -> Bool { return lhs.x == rhs.x && lhs.y == rhs.y && lhs.name == rhs.name } var hashValue: Int { var hash = FVN1AHash() hash.consume(name) var tx = x withUnsafeBytes(of: &tx) { rawBufferPointer in hash.consume(bytes: rawBufferPointer) } var ty = y withUnsafeBytes(of: &ty) { rawBufferPointer in hash.consume(bytes: rawBufferPointer) } return hash.finalValue } } let p1 = NamedPosition(name: "d", x: 1000, y: 1000) p1.hashValue //: [Next](@next)
mit
cc212a599072b4ccc82840d9c74e658e
19
78
0.676415
3.108504
false
false
false
false
hstdt/GodEye
GodEye/Classes/View/RecordTableView/RecordTableView.swift
1
5198
// // RecordTableView.swift // Pods // // Created by zixun on 16/12/28. // // import Foundation class RecordTableView: UITableView { override init(frame: CGRect, style: UITableViewStyle) { super.init(frame: frame, style: style) self.separatorStyle = .none self.backgroundColor = UIColor.niceBlack() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func smoothReloadData(need scrollToBottom: Bool) { self.timer?.invalidate() self.timer = nil self.needScrollToBottom = false self.timer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(RecordTableView.reloadData), userInfo: nil, repeats: false) } override func reloadData() { super.reloadData() if self.needScrollToBottom == true { DispatchQueue.main.async { self.scrollToBottom(animated: true) } } } func scrollToBottom(animated: Bool) { let point = CGPoint(x: 0, y: max(self.contentSize.height + self.contentInset.bottom - self.bounds.size.height, 0)) self.setContentOffset(point, animated: animated) } private var timer: Timer? private var needScrollToBottom = false } class RecordTableViewDataSource: NSObject { private let maxLogItems: Int = 1000 fileprivate(set) var recordData: [RecordORMProtocol]! private var logIndex: Int = 0 fileprivate var type: RecordType! init(type:RecordType) { super.init() self.type = type self.type.model()?.addCount = 0 self.recordData = self.currentPageModel() } private func currentPageModel() -> [RecordORMProtocol]? { if self.type == RecordType.log { return LogRecordModel.select(at: self.logIndex) }else if self.type == RecordType.crash { return CrashRecordModel.select(at: self.logIndex) }else if self.type == .network { return NetworkRecordModel.select(at: self.logIndex) }else if self.type == .anr { return ANRRecordModel.select(at: self.logIndex) }else if self.type == .command { return CommandRecordModel.select(at: self.logIndex) }else if self.type == .leak { return LeakRecordModel.select(at: self.logIndex) } fatalError("type:\(self.type) not define the database") } private func addCount() { self.type.model()?.addCount += 1 } func loadPrePage() -> Bool { self.logIndex += 1 guard let models = self.currentPageModel() else { return false } guard models.count != 0 else { return false } for model in models.reversed() { self.recordData.insert(model, at: 0) } return true } func addRecord(model:RecordORMProtocol) { if self.recordData.count != 0 && type(of: model).type != self.type { return } self.recordData.append(model) if self.recordData.count > self.maxLogItems { self.recordData.remove(at: 0) } self.addCount() } func cleanRecord() { self.recordData.removeAll() } } extension RecordTableViewDataSource: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.recordData.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return tableView.dequeueReusableCell({ (cell:RecordTableViewCell) in }) } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { let cell = cell as? RecordTableViewCell let attributeString = self.recordData[indexPath.row].attributeString() cell?.configure(attributeString) } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let tableView = tableView as! RecordTableView let width = tableView.bounds.size.width - 10 let attributeString = self.recordData[indexPath.row].attributeString() return RecordTableViewCell.boundingHeight(with: width, attributedText: attributeString) } func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { if self.type == .network || self.type == .anr { return indexPath }else { return nil } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let model = self.recordData[indexPath.row] model.showAll = !model.showAll tableView.reloadData() } }
mit
814a826c448ef0166754a940ecd9675f
29.576471
122
0.588303
4.922348
false
false
false
false
zhxnlai/Algorithms
swift/Palindrome Partitioning II.playground/Contents.swift
2
2108
// Playground - noun: a place where people can play import UIKit extension String { subscript (i: Int) -> String { return String(Array(self)[i]) } subscript (r: Range<Int>) -> String { return String(Array(self)[r]) } } func isPalindrome(s: String) -> Bool { return s == String(Array(s).reverse()) } isPalindrome("aa") isPalindrome("aab") func palindromePartition(s: String) -> [[String]] { let strlen = count(s) var opt = [[Bool]](count: strlen, repeatedValue: [Bool](count: strlen, repeatedValue: false)) for var from=0; from<strlen; from++ { for var to=from; to<strlen; to++ { if isPalindrome(s[from..<to]) { opt[from][to] = true } opt[from][to] = reduce(0..<to, false, { (acc, f) -> Bool in return acc || (opt[0][f] && isPalindrome(s[f..<to])) }) } } var path = [String]() var result = [[String]]() findSolution(s, opt, strlen, &path, &result) return result } func findSolution(s: String, opt: [[Bool]], to: Int, inout path: [String], inout result: [[String]]) { if to==0 { result.append(Array(path)) } for var from=0; from<to; from++ { if isPalindrome(s[from..<to]) { path.append(s[from..<to]) findSolution(s, opt, from, &path, &result) path.removeLast() } } } palindromePartition("a") palindromePartition("aa") palindromePartition("aab") palindromePartition("aabc") func minCut(s: String) -> Int { let strlen = count(s) var opt = [Int](count: strlen+1, repeatedValue: Int.max) opt [0] = 0 for var to = 1; to<=strlen; to++ { opt[to] = reduce(0..<to, Int.max, { (acc, from) -> Int in var subStr = s[from..<to] if isPalindrome(subStr) { var cut = (from == 0 ? 0: 1) return min(acc, opt[from]+cut) } else { return acc } }) } opt return opt.last! } minCut("aab") minCut("aabc") minCut("aabbc") minCut("aacbbc")
mit
282327de7a46518068bd30827ce0bbb4
24.095238
102
0.532258
3.455738
false
false
false
false
SlaunchaMan/Advent-of-Code-2016
Advent of Code 2016 Day 4.playground/Contents.swift
1
4134
import Foundation let separatorSet = CharacterSet(charactersIn: "[]") let dashSet = CharacterSet(charactersIn: "-") extension String { private var mainComponents: [String] { return components(separatedBy: separatorSet) .filter { !$0.isEmpty } } var checksum: String { var characterCounts: [Character: Int] = [:] for scalar in unicodeScalars { if CharacterSet.letters.contains(scalar) { let char = Character(scalar) if let count = characterCounts[char] { characterCounts[char] = count + 1 } else { characterCounts[char] = 1 } } } characterCounts.map { "\($0.key) : \($0.value)" } var checksum = characterCounts.sorted { (l, r) in if l.value > r.value { return true } if l.value == r.value && l.key < r.key { return true } return false } .map { $0.key } .map { String($0) } .joined() if checksum.characters.count > 5 { checksum = checksum.substring(to: checksum.index(checksum.startIndex, offsetBy: 5)) } return checksum } var sectorID: Int? { guard mainComponents.count == 2 else { return nil } guard let sector = mainComponents[0] .components(separatedBy: dashSet) .last .flatMap({ (a) -> Int? in Int(a) }) else { return nil } return sector } var isRealRoom: Bool { guard mainComponents.count == 2 else { return false } let letters = mainComponents[0] .components(separatedBy: dashSet) .joined() let givenChecksum = mainComponents[1] let computedChecksum = letters.checksum return givenChecksum == computedChecksum } var decrypted: String? { guard isRealRoom, let sectorID = sectorID else { return nil } let shift = sectorID % 26 return mainComponents[0] .components(separatedBy: dashSet) .map { let newScalars = $0.unicodeScalars .map { (scalar) -> UnicodeScalar in guard CharacterSet.letters.contains(scalar) else { return scalar } let shifted = UnicodeScalar(scalar.value + UInt32(shift)) if shifted! > UnicodeScalar("z")! { return UnicodeScalar(shifted!.value - UInt32(26))! } return shifted! } var view = UnicodeScalarView(newScalars) return view.description } .joined(separator: " ") } } // Test Input let testInput = "aaaaa-bbb-z-y-x-123[abxyz]\na-b-c-d-e-f-g-h-987[abcde]\nnot-a-real-room-404[oarel]\ntotally-real-room-200[decoy]" testInput.enumerateLines { (line, _) in if (line.isRealRoom) { print("real") } else { print("decoy") } } // Real Input guard let input = try? String(contentsOf: #fileLiteral(resourceName: "Advent of Code 2016 Day 4 Input.txt")) else { fatalError("Couldn't load input") } // Part 1 var realRooms: [String] = [] input.enumerateLines(invoking: { (line, _) in if line.isRealRoom { realRooms.append(line) } }) let sum = realRooms.reduce(0) { (sum, roomString) in if let sectorID = roomString.sectorID { return sum + sectorID } return sum } sum // Part 2 let decrypted = realRooms.flatMap { $0.decrypted } let north = decrypted.filter { $0.contains("north") }.filter { $0.contains("pole") } north
mit
c1d82e6787bc0a41e026fdc201b4e14d
25.33121
130
0.493711
4.573009
false
false
false
false
tutao/tutanota
app-ios/tutanota/Sources/Files/BlobUtil.swift
1
2002
// // Created by Tutao GmbH on 9/16/21. // import Foundation /** Functions for working with larger files from Blob Store */ class BlobUtil { func hashFile(fileUri: String) async throws -> String { let url = URL(fileURLWithPath: fileUri) let data = try Data(contentsOf: url) let hash = TUTCrypto.sha256(data).subdata(in: 0..<6) return hash.base64EncodedString() } func joinFiles(fileName: String, filePathsToJoin: [String]) async throws -> String { let decryptedDir = try! FileUtils.getDecryptedFolder() as NSString let outputFilePath = decryptedDir.appendingPathComponent(fileName) let outputFileUri = URL(fileURLWithPath: outputFilePath) let createdFile = FileManager.default.createFile(atPath: outputFilePath, contents: nil, attributes: nil) guard createdFile else { throw TUTErrorFactory.createError("Could not create file \(outputFileUri)") } let outputFileHandle = try! FileHandle(forWritingTo: outputFileUri) for inputFile in filePathsToJoin { let fileUri = URL(fileURLWithPath: inputFile) let fileContent = try Data(contentsOf: fileUri) outputFileHandle.write(fileContent) } return outputFilePath } func splitFile(fileUri: String, maxBlobSize: Int) async throws -> [String] { let fileHandle = FileHandle(forReadingAtPath: fileUri)! var result = [String]() while true { let chunk = fileHandle.readData(ofLength: maxBlobSize) if chunk.isEmpty { // End of file break } let hash = TUTCrypto.sha256(chunk) let outputFileName = "\(TUTEncodingConverter.bytes(toHex: hash.subdata(in: 0..<6))).blob" let decryptedDir = try! FileUtils.getDecryptedFolder() as NSString let outputPath = decryptedDir.appendingPathComponent(outputFileName) let outputUrl = URL(fileURLWithPath: outputPath) try chunk.write(to: outputUrl) result.append(outputPath) } return result } }
gpl-3.0
20fc8eafd39b29477a99a55e16419eda
30.777778
108
0.69031
4.4
false
false
false
false
eshurakov/SwiftHTTPClient
HTTPClient/DefaultHTTPSession.swift
1
4106
// // DefaultHTTPSession.swift // HTTPClient // // Created by Evgeny Shurakov on 30.07.16. // Copyright ยฉ 2016 Evgeny Shurakov. All rights reserved. // import Foundation public class DefaultHTTPSession: NSObject, HTTPSession { fileprivate var taskContexts: [Int: TaskContext] = [:] fileprivate var session: Foundation.URLSession? private let sessionFactory: HTTPSessionFactory public var logger: HTTPLogger? fileprivate class TaskContext { lazy var data = Data() let completion: (HTTPRequestResult) -> Void init(completion: @escaping (HTTPRequestResult) -> Void) { self.completion = completion } } private override init() { fatalError("Not implemented") } public init(sessionFactory: HTTPSessionFactory) { self.sessionFactory = sessionFactory super.init() } public func execute(_ request: URLRequest, completion: @escaping (HTTPRequestResult) -> Void) { if self.session == nil { self.session = self.sessionFactory.session(withDelegate: self) } guard let session = self.session else { fatalError("Session is nil right after it was created") } let task = session.dataTask(with: request) self.logger?.logStart(of: task) // TODO: call completion with a failure? assert(self.taskContexts[task.taskIdentifier] == nil) self.taskContexts[task.taskIdentifier] = TaskContext(completion: completion) task.resume() } } extension DefaultHTTPSession: URLSessionDelegate { public func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { self.session = nil self.logger?.logSessionFailure(error) let taskContexts = self.taskContexts self.taskContexts = [:] for (_, context) in taskContexts { context.completion(.failure(HTTPSessionError.becameInvalid(error))) } } } extension DefaultHTTPSession: URLSessionTaskDelegate { public func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) { self.logger?.logRedirect(of: task) completionHandler(request) } public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { guard let context = self.taskContexts[task.taskIdentifier] else { return } self.taskContexts[task.taskIdentifier] = nil if let error = error { self.logger?.logFailure(of: task, with: error) context.completion(.failure(error)) } else { if let response = task.response { if let httpResponse = response as? HTTPURLResponse { let response = HTTPResponse(with: httpResponse, data: context.data) self.logger?.logSuccess(of: task, with: response) context.completion(.success(response)) } else { let error = HTTPSessionError.unsupportedURLResponseSubclass(String(describing: type(of: response))) self.logger?.logFailure(of: task, with: error) context.completion(.failure(error)) } } else { let error = HTTPSessionError.missingURLResponse self.logger?.logFailure(of: task, with: error) context.completion(.failure(error)) } } } } extension DefaultHTTPSession: URLSessionDataDelegate { public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { guard let context = self.taskContexts[dataTask.taskIdentifier] else { return } context.data.append(data) } }
mit
bb3224c175c5abcdbbd7a14f479d0dad
33.788136
211
0.609501
5.170025
false
false
false
false
Sadmansamee/quran-ios
Pods/GenericDataSources/Sources/CompositeDataSource.swift
1
15628
// // CompositeDataSource.swift // GenericDataSource // // Created by Mohamed Afifi on 9/16/15. // Copyright ยฉ 2016 mohamede1945. All rights reserved. // import UIKit /** The composite data source class that is responsible for managing a set of children data sources. Delegating requests to the approperiate child data source to respond. Mutli section data source represents multiple sections, each child data source represents a section. (e.g. if we have 2 basic data sources first one has 3 items and second one has 4 items, then we have 2 sections first one will have 3 cells and second one will have 4 cells.) Single section data source represents one section, children data sources are all on the same section. (e.g. if we have 2 basic data sources first one has 3 items and second one has 4 items, then we have 1 section with 7 cells, the first 3 cells will be dequeued and configured by the first basic data source followed by 4 cells dequeued and configured by the second data source.) It's recommended to subclass it if you want to have a common behavior. (e.g. If all the cells will have a common cell size. Then, implement `ds_shouldConsumeItemSizeDelegateCalls` and return `true`, then implement `ds_collectionView(_:sizeForItemAt:)` and return the desired size for all the cells regardless of the children data sources.) */ open class CompositeDataSource: AbstractDataSource { /** The type of the composite data source. - SingleSection: Single section data source represents one section, children data sources are all on the same section. - MultiSection: Mutli section data source represents multiple sections, each child data source represents a section. */ public enum SectionType { case single case multi } /// The collection class that manages the data sources. fileprivate var collection: DataSourcesCollection! /// Represents the section type of the composite data source. open let sectionType: SectionType /** Creates new instance with the desired type. - parameter sectionType: The desired composite data source type. */ public init(sectionType: SectionType) { self.sectionType = sectionType super.init() switch sectionType { case .single: collection = SingleSectionDataSourcesCollection(parentDataSource: self) case .multi: collection = MultiSectionDataSourcesCollection(parentDataSource: self) } } /// Returns the list of children data sources. open var dataSources: [DataSource] { return collection.dataSources } /** Returns a Boolean value that indicates whether the receiver implements or inherits a method that can respond to a specified message. true if the receiver implements or inherits a method that can respond to aSelector, otherwise false. - parameter selector: A selector that identifies a message. - returns: `true` if the receiver implements or inherits a method that can respond to aSelector, otherwise `false`. */ open override func responds(to selector: Selector) -> Bool { if sizeSelectors.contains(selector) { return ds_shouldConsumeItemSizeDelegateCalls() } return super.responds(to: selector) } // MARK: Children DataSources /** Adds a new data source to the list of children data sources. - parameter dataSource: The new data source to add. */ open func addDataSource(_ dataSource: DataSource) { collection.addDataSource(dataSource) } /** Inserts the data source to the list of children data sources at specific index. - parameter dataSource: The new data source to add. - parameter index: The index to insert the new data source at. */ open func insertDataSource(_ dataSource: DataSource, atIndex index: Int) { collection.insertDataSource(dataSource, atIndex: index) } /** Removes a data source from the children data sources list. - parameter dataSource: The data source to remove. */ open func removeDataSource(_ dataSource: DataSource) { collection.removeDataSource(dataSource) } /// Clear the collection of data sources. open func removeAllDataSources() { collection.removeAllDataSources() } /** Returns the data source at certain index. - parameter index: The index of the data source to return. - returns: The data source at specified index. */ open func dataSourceAtIndex(_ index: Int) -> DataSource { return collection.dataSourceAtIndex(index) } /** Check if a data source exists or not. - parameter dataSource: The data source to check. - returns: `true``, if the data source exists. Otherwise `false`. */ open func containsDataSource(_ dataSource: DataSource) -> Bool { return collection.containsDataSource(dataSource) } /** Gets the index of a data source or `nil` if not exist. - parameter dataSource: The data source to get the index for. - returns: The index of the data source. */ open func indexOfDataSource(_ dataSource: DataSource) -> Int? { return collection.indexOfDataSource(dataSource) } // MARK:- IndexPath and Section translations /** Converts a section value relative to a specific data source to a section value relative to the composite data source. - parameter section: The local section relative to the passed data source. - parameter dataSource: The data source that is the local section is relative to it. Should be a child data source. - returns: The global section relative to the composite data source. */ open func globalSectionForLocalSection(_ section: Int, dataSource: DataSource) -> Int { return collection.globalSectionForLocalSection(section, dataSource: dataSource) } /** Converts a section value relative to the composite data source to a section value relative to a specific data source. - parameter section: The section relative to the compsite data source. - parameter dataSource: The data source that is the returned local section is relative to it. Should be a child data source. - returns: The global section relative to the composite data source. */ open func localSectionForGlobalSection(_ section: Int, dataSource: DataSource) -> Int { return collection.localSectionForGlobalSection(section, dataSource: dataSource) } /** Converts an index path value relative to a specific data source to an index path value relative to the composite data source. - parameter indexPath: The local index path relative to the passed data source. - parameter dataSource: The data source that is the local index path is relative to it. Should be a child data source. - returns: The global index path relative to the composite data source. */ open func globalIndexPathForLocalIndexPath(_ indexPath: IndexPath, dataSource: DataSource) -> IndexPath { return collection.globalIndexPathForLocalIndexPath(indexPath, dataSource: dataSource) } /** Converts an index path value relative to the composite data source to an index path value relative to a specific data source. - parameter indexPath: The index path relative to the compsite data source. - parameter dataSource: The data source that is the returned local index path is relative to it. Should be a child data source. - returns: The global index path relative to the composite data source. */ open func localIndexPathForGlobalIndexPath(_ indexPath: IndexPath, dataSource: DataSource) -> IndexPath { return collection.localIndexPathForGlobalIndexPath(indexPath, dataSource: dataSource) } // MARK:- Data Source /** Gets whether the data source will handle size delegate calls. It only handle delegate calls if there is at least 1 data source and all the data sources can handle the size delegate calls. - returns: `false` if there is no data sources or any of the data sources cannot handle size delegate calls. */ open override func ds_shouldConsumeItemSizeDelegateCalls() -> Bool { if dataSources.isEmpty { return false } // if all data sources should consume item size delegates return dataSources.filter { $0.ds_shouldConsumeItemSizeDelegateCalls() }.count == dataSources.count } // MARK: Cell /** Asks the data source to return the number of sections. `1` for Single Section. `dataSources.count` for Multi section. - returns: The number of sections. */ open override func ds_numberOfSections() -> Int { return collection.numberOfSections() } /** Asks the data source to return the number of items in a given section. - parameter section: An index number identifying a section. - returns: The number of items in a given section */ open override func ds_numberOfItems(inSection section: Int) -> Int { return collection.numberOfItems(inSection: section) } /** Asks the data source for a cell to insert in a particular location of the general collection view. - parameter collectionView: A general collection view object requesting the cell. - parameter indexPath: An index path locating an item in the view. - returns: An object conforming to ReusableCell that the view can use for the specified item. */ open override func ds_collectionView(_ collectionView: GeneralCollectionView, cellForItemAt indexPath: IndexPath) -> ReusableCell { let mapping = collection.collectionViewWrapperFromIndexPath(indexPath, collectionView: collectionView) return mapping.dataSource.ds_collectionView(mapping.wrapperView, cellForItemAt: mapping.localIndexPath) } // MARK: Size /** Asks the data source for the size of a cell in a particular location of the general collection view. - parameter collectionView: A general collection view object initiating the operation. - parameter indexPath: An index path locating an item in the view. - returns: The size of the cell in a given location. For `UITableView`, the width is ignored. */ open override func ds_collectionView(_ collectionView: GeneralCollectionView, sizeForItemAt indexPath: IndexPath) -> CGSize { let mapping = collection.collectionViewWrapperFromIndexPath(indexPath, collectionView: collectionView) return mapping.dataSource.ds_collectionView?(mapping.wrapperView, sizeForItemAt: mapping.localIndexPath) ?? CGSize.zero } // MARK: Selection /** Asks the delegate if the specified item should be highlighted. `true` if the item should be highlighted or `false` if it should not. - parameter collectionView: A general collection view object initiating the operation. - parameter indexPath: An index path locating an item in the view. - returns: `true` if the item should be highlighted or `false` if it should not. */ open override func ds_collectionView(_ collectionView: GeneralCollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool { let mapping = collection.collectionViewWrapperFromIndexPath(indexPath, collectionView: collectionView) return mapping.dataSource.ds_collectionView(mapping.wrapperView, shouldHighlightItemAt: mapping.localIndexPath) } /** Tells the delegate that the specified item was highlighted. - parameter collectionView: A general collection view object initiating the operation. - parameter indexPath: An index path locating an item in the view. */ open override func ds_collectionView(_ collectionView: GeneralCollectionView, didHighlightItemAt indexPath: IndexPath) { let mapping = collection.collectionViewWrapperFromIndexPath(indexPath, collectionView: collectionView) return mapping.dataSource.ds_collectionView(mapping.wrapperView, didHighlightItemAt: mapping.localIndexPath) } /** Tells the delegate that the highlight was removed from the item at the specified index path. - parameter collectionView: A general collection view object initiating the operation. - parameter indexPath: An index path locating an item in the view. */ open override func ds_collectionView(_ collectionView: GeneralCollectionView, didUnhighlightItemAt indexPath: IndexPath) { let mapping = collection.collectionViewWrapperFromIndexPath(indexPath, collectionView: collectionView) return mapping.dataSource.ds_collectionView(collectionView, didUnhighlightItemAt: mapping.localIndexPath) } /** Asks the delegate if the specified item should be selected. `true` if the item should be selected or `false` if it should not. - parameter collectionView: A general collection view object initiating the operation. - parameter indexPath: An index path locating an item in the view. - returns: `true` if the item should be selected or `false` if it should not. */ open override func ds_collectionView(_ collectionView: GeneralCollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { let mapping = collection.collectionViewWrapperFromIndexPath(indexPath, collectionView: collectionView) return mapping.dataSource.ds_collectionView(collectionView, shouldSelectItemAt: mapping.localIndexPath) } /** Tells the delegate that the specified item was selected. - parameter collectionView: A general collection view object initiating the operation. - parameter indexPath: An index path locating an item in the view. */ open override func ds_collectionView(_ collectionView: GeneralCollectionView, didSelectItemAt indexPath: IndexPath) { let mapping = collection.collectionViewWrapperFromIndexPath(indexPath, collectionView: collectionView) return mapping.dataSource.ds_collectionView(mapping.wrapperView, didSelectItemAt: mapping.localIndexPath) } /** Asks the delegate if the specified item should be deselected. `true` if the item should be deselected or `false` if it should not. - parameter collectionView: A general collection view object initiating the operation. - parameter indexPath: An index path locating an item in the view. - returns: `true` if the item should be deselected or `false` if it should not. */ open override func ds_collectionView(_ collectionView: GeneralCollectionView, shouldDeselectItemAt indexPath: IndexPath) -> Bool { let mapping = collection.collectionViewWrapperFromIndexPath(indexPath, collectionView: collectionView) return mapping.dataSource.ds_collectionView(collectionView, shouldDeselectItemAt: mapping.localIndexPath) } /** Tells the delegate that the specified item was deselected. - parameter collectionView: A general collection view object initiating the operation. - parameter indexPath: An index path locating an item in the view. */ open override func ds_collectionView(_ collectionView: GeneralCollectionView, didDeselectItemAt indexPath: IndexPath) { let mapping = collection.collectionViewWrapperFromIndexPath(indexPath, collectionView: collectionView) return mapping.dataSource.ds_collectionView(mapping.wrapperView, didDeselectItemAt: mapping.localIndexPath) } }
mit
fb5b7bc7468ff26831ac099a83a310f0
41.813699
143
0.722468
5.238686
false
false
false
false
k-o-d-e-n/CGLayout
Example/CGLayout/ViewController.swift
1
3075
// // ViewController.swift // CGLayout // // Created by k-o-d-e-n on 08/31/2017. // Copyright (c) 2017 k-o-d-e-n. All rights reserved. // import UIKit import CGLayout extension UIView { convenience init(backgroundColor: UIColor) { self.init() self.backgroundColor = backgroundColor } } extension UILabel { convenience init(text: String) { self.init() self.text = text self.numberOfLines = 0 } } class LabelPlaceholder: ViewPlaceholder<UILabel> { var font: UIFont? var textColor: UIColor? override var frame: CGRect { didSet { elementIfLoaded?.frame = frame } } open override func elementDidLoad() { super.elementDidLoad() element.font = font element.textColor = textColor } convenience init() { self.init(frame: .zero) } convenience init(font: UIFont, textColor: UIColor) { self.init() self.font = font self.textColor = textColor } } class ViewController: UIViewController { var scrollView: UIScrollView { return view as! UIScrollView } var elements: [UIView] = [] lazy var scheme: LayoutScheme = self.buildScheme() override func viewDidLoad() { super.viewDidLoad() scrollView.contentSize.height = view.frame.height scrollView.contentSize.width = view.frame.width self.elements = (0..<10).map { (i) -> UIView in let view = buildView(UIView.self, bg: UIColor(white: CGFloat(i) / 10, alpha: 1)) view.translatesAutoresizingMaskIntoConstraints = false scrollView.addSubview(view) return view } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() scheme.layout(in: view.layoutBounds) } private func buildScheme() -> LayoutScheme { let borderLayer = CALayer() borderLayer.borderWidth = 1 view.layer.addSublayer(borderLayer) let initial: (blocks: [LayoutBlockProtocol], last: UIView?) = ([], nil) return LayoutScheme( blocks: elements.reduce(into: initial) { (blocks, view) -> Void in var constraints: [LayoutConstraintProtocol] = [] if let last = blocks.last { constraints.append(last.layoutConstraint(for: [.top(.limit(on: .outer))])) } else { constraints.append(scrollView.layoutConstraint(for: [.bottom(.limit(on: .inner))])) } blocks.blocks += [ view.layoutBlock( with: Layout(x: .equal, y: blocks.last == nil ? .bottom() : .bottom(between: 0...10), width: .equal, height: .fixed(50)) + .top(0...), constraints: constraints ) ] blocks.last = view }.blocks + [ borderLayer.layoutBlock(constraints: [ scrollView.contentLayoutConstraint(for: [.equally]) ]) ] ) } }
mit
8272d6d75aa07e26102b1007d3622357
28.567308
158
0.572683
4.562315
false
false
false
false
bigxodus/candlelight
candlelight/screen/main/controller/community/CommunityViewDelegate.swift
1
2386
import UIKit import Foundation class CommunityViewDelegate: NSObject, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { let scManager: SiteConfigManager = SiteConfigManager() var siteInfos: Array<SiteInfo> = [] weak var communityController: CommunityController? weak var collectionView: UICollectionView? = nil public init(_ communityController: CommunityController) { self.communityController = communityController // load settings let scs = scManager.select() for sc in scs { if let community = Community(rawValue: sc.id) { siteInfos.append(SiteInfo(community: community, title: sc.name, isOn: sc.isOn)) } } } public func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let count = siteInfos.filter{ $0.isOn }.count return count } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ConfigController.collectionReuseIdentifier, for: indexPath) as! SiteCollectionViewCell cell.backgroundColor = UIColor(red: 0.1, green: 0.1, blue: 0.1, alpha: 1.0) cell.setText(siteInfos[indexPath.row].title) return cell } public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { guard let parent = communityController else { return } let addController = BoardViewController(community: siteInfos[indexPath.row].community, bottomMenuController: parent.bottomMenuController) parent.navigationController?.pushViewController(addController, animated: true) } public func reloadCollectionView(){ siteInfos.removeAll() // load settings let scs = scManager.select() for sc in scs { if sc.isOn, let community = Community(rawValue: sc.id) { siteInfos.append(SiteInfo(community: community, title: sc.name, isOn: sc.isOn)) } } collectionView?.reloadData() } }
apache-2.0
5fde9b1e0e2bb17d910f03c391abdfb9
35.707692
161
0.663873
5.302222
false
false
false
false
SPECURE/rmbt-ios-client
Sources/QOS/Helpers/UDPStreamReceiver.swift
1
4912
/***************************************************************************************************** * Copyright 2014-2016 SPECURE GmbH * * 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 CocoaAsyncSocket /// struct UDPStreamReceiverSettings { var port: UInt16 = 0 var delegateQueue: DispatchQueue var sendResponse: Bool = false var maxPackets: UInt16 = 5 var timeout: UInt64 = 10_000_000_000 } /// class UDPStreamReceiver: NSObject { /// fileprivate let socketQueue = DispatchQueue(label: "com.specure.rmbt.udp.socketQueue") /// fileprivate var udpSocket: GCDAsyncUdpSocket! /// fileprivate let countDownLatch = CountDownLatch() /// // private var running: AtomicBoolean = AtomicBoolean() fileprivate var running: Bool = false // /// var delegate: UDPStreamReceiverDelegate? /// fileprivate let settings: UDPStreamReceiverSettings /// fileprivate var packetsReceived: UInt16 = 0 // /// required init(settings: UDPStreamReceiverSettings) { self.settings = settings } /// func stop() { countDownLatch.countDown() } /// fileprivate func connect() { Log.logger.debug("connecting udp socket") udpSocket = GCDAsyncUdpSocket(delegate: self, delegateQueue: settings.delegateQueue, socketQueue: socketQueue) udpSocket.setupSocket() do { try udpSocket.bind(toPort: settings.port) try udpSocket.beginReceiving() } catch { // TODO: check error (i.e. fail if error) } } /// fileprivate func close() { Log.logger.debug("closing udp socket") udpSocket?.close() } /// fileprivate func receivePacket(_ dataReceived: Data, fromAddress address: Data) { // TODO: use dataReceived packetsReceived += 1 // didReceive callback var shouldStop: Bool = false settings.delegateQueue.sync { shouldStop = self.delegate?.udpStreamReceiver(self, didReceivePacket: dataReceived) ?? false } if shouldStop || packetsReceived >= settings.maxPackets { stop() } // send response if settings.sendResponse { var data = NSMutableData() var shouldSendResponse: Bool = false settings.delegateQueue.sync { shouldSendResponse = self.delegate?.udpStreamReceiver(self, willSendPacketWithNumber: self.packetsReceived, data: &data) ?? false } if shouldSendResponse && data.length > 0 { udpSocket.send(data as Data, toAddress: address, withTimeout: nsToSec(settings.timeout), tag: -1) // TODO: TAG } } } /// func receive() { connect() running = true // TODO: move timeout handling to other class! this class should be more generic! _ = countDownLatch.await(settings.timeout) // TODO: timeout running = false close() } } // MARK: GCDAsyncUdpSocketDelegate methods /// extension UDPStreamReceiver: GCDAsyncUdpSocketDelegate { /// func udpSocket(_ sock: GCDAsyncUdpSocket, didConnectToAddress address: Data) { Log.logger.debug("didConnectToAddress: \(address)") } /// func udpSocket(_ sock: GCDAsyncUdpSocket, didNotConnect error: Error?) { Log.logger.debug("didNotConnect: \(String(describing: error))") } /// func udpSocket(_ sock: GCDAsyncUdpSocket, didSendDataWithTag tag: Int) { Log.logger.debug("didSendDataWithTag: \(tag)") } /// func udpSocket(_ sock: GCDAsyncUdpSocket, didNotSendDataWithTag tag: Int, dueToError error: Error?) { Log.logger.debug("didNotSendDataWithTag: \(String(describing: error))") } /// func udpSocket(_ sock: GCDAsyncUdpSocket, didReceive data: Data, fromAddress address: Data, withFilterContext filterContext: Any?) { Log.logger.debug("didReceiveData: \(data)") if running { receivePacket(data, fromAddress: address) } } /// func udpSocketDidClose(_ sock: GCDAsyncUdpSocket, withError error: Error?) { Log.logger.debug("udpSocketDidClose: \(String(describing: error))") } }
apache-2.0
8013c0dca4e7f6e82d6a730ca67b2f22
27.229885
145
0.615228
4.92678
false
false
false
false
AlanEnjoy/Live
Live/Live/Classes/Home/Model/RecommendGameView.swift
1
2237
// // RecommendGameView.swift // Live // // Created by Alan's Macbook on 2017/7/13. // Copyright ยฉ 2017ๅนด zhushuai. All rights reserved. // import UIKit fileprivate let kGameCellID = "kGameCellID" fileprivate let kEdgeInsetMargin : CGFloat = 8 class RecommendGameView: UIView { //MARK:- ๅฎšไน‰ๆ•ฐๆฎ็š„ๅฑžๆ€ง var groups :[BaseGameModel]? { didSet { //MARK:- ๅˆทๆ–ฐๆ•ฐๆฎ collectionView.reloadData() } } //MARK:- ๆŽงไปถๅฑžๆ€ง @IBOutlet weak var collectionView: UICollectionView! //MARK:- ็ณป็ปŸๅ›ž่ฐƒ override func awakeFromNib() { super.awakeFromNib() //่ฎฉๆŽงไปถไธ้š็ˆถๆŽงไปถ็š„ๆ‹‰ไผธ่€Œๆ‹‰ไผธ autoresizingMask = UIViewAutoresizing(rawValue: 0) //ๆณจๅ†Œcell collectionView.register(UINib(nibName: "CollectionGameCell", bundle: nil), forCellWithReuseIdentifier: kGameCellID) //็ป™collectionGameViewๆทปๅŠ ๅ†…่พน่ท collectionView.contentInset = UIEdgeInsetsMake(0, kEdgeInsetMargin , 0, kEdgeInsetMargin ) } } //MARK:- ๆไพ›ๅฟซ้€Ÿๅˆ›ๅปบ็š„็ฑปๆ–นๆณ• extension RecommendGameView { class func recommendGameView() -> RecommendGameView { return Bundle.main.loadNibNamed("RecommendGameView", owner: nil, options: nil)?.first as! RecommendGameView } } //MARK:- ้ตๅฎˆUICollectionView็š„ๆ•ฐๆฎๆบๅ่ฎฎ extension RecommendGameView : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return groups?.count ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kGameCellID, for: indexPath) as! CollectionGameCell cell.baseGame = groups![indexPath.item] return cell } } //MARK:- ไปŽxibไธญ็›ดๆŽฅๅˆ›ๅปบ็š„็ฑปๆ–นๆณ• extension RecommendGameView { class func recommandGameView() -> RecommendGameView { return Bundle.main.loadNibNamed("RecommendGameView", owner: nil, options: nil)?.first as! RecommendGameView } }
mit
50930d777051d62a4ff2a43642c7021d
27.324324
126
0.671756
5.253133
false
false
false
false
ScoutHarris/WordPress-iOS
WordPress/Classes/ViewRelated/NUX/LoginProloguePromoViewController.swift
2
6027
import UIKit import Lottie class LoginProloguePromoViewController: UIViewController { fileprivate let type: PromoType fileprivate let stackView: UIStackView fileprivate let headingLabel: UILabel fileprivate let animationHolder: UIView fileprivate var animationView: LOTAnimationView fileprivate struct Constants { static let stackSpacing: CGFloat = 36.0 static let stackHeightMultiplier: CGFloat = 0.87 static let stackWidthMultiplier: CGFloat = 0.8 static let labelMinHeight: CGFloat = 21.0 static let labelMaxWidth: CGFloat = 600.0 static let animationWidthHeightRatio: CGFloat = 0.6667 } enum PromoType: String { case post case stats case reader case notifications case jetpack var animationKey: String { return rawValue } var headlineText: String { switch self { case .post: return NSLocalizedString("Publish from the park. Blog from the bus. Comment from the cafรฉ. WordPress goes where you do.", comment: "shown in promotional screens during first launch") case .stats: return NSLocalizedString("Watch readers from around the world read and interact with your site โ€” in real time.", comment: "shown in promotional screens during first launch") case .reader: return NSLocalizedString("Catch up with your favorite sites and join the conversation anywhere, any time.", comment: "shown in promotional screens during first launch") case .notifications: return NSLocalizedString("Your notifications travel with you โ€” see comments and likes as they happen.", comment: "shown in promotional screens during first launch") case .jetpack: return NSLocalizedString("Manage your Jetpack-powered site on the go โ€” youโ€˜ve got WordPress in your pocket.", comment: "shown in promotional screens during first launch") } } var headlineColor: UIColor { switch self { case .post, .reader, .jetpack: return UIColor(hexString: "204E80") default: return UIColor.white } } } init(as promoType: PromoType) { type = promoType stackView = UIStackView() headingLabel = UILabel() animationHolder = UIView() guard let animation = Lottie.LOTAnimationView(name: type.animationKey) else { fatalError("animation could not be created for promo screen \(promoType)") } animationView = animation super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: lifecycle override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.clear headingLabel.font = WPStyleGuide.mediumWeightFont(forStyle: .title3) headingLabel.textColor = type.headlineColor headingLabel.text = type.headlineText headingLabel.textAlignment = .center headingLabel.numberOfLines = 0 headingLabel.sizeToFit() setupLayout() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) animationView.animationProgress = 0.0 } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) animationView.play() } // MARK: layout private func setupLayout() { view.addSubview(stackView) stackView.addArrangedSubview(headingLabel) stackView.addArrangedSubview(animationHolder) animationHolder.addSubview(animationView) stackView.axis = .vertical stackView.spacing = Constants.stackSpacing stackView.alignment = .center stackView.distribution = .fill stackView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor), stackView.bottomAnchor.constraint(equalTo: view.bottomAnchor), stackView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: Constants.stackWidthMultiplier), stackView.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: Constants.stackHeightMultiplier) ]) headingLabel.setContentHuggingPriority(UILayoutPriorityDefaultLow, for: .vertical) headingLabel.setContentCompressionResistancePriority(UILayoutPriorityRequired, for: .vertical) headingLabel.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ headingLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: Constants.labelMinHeight), headingLabel.widthAnchor.constraint(lessThanOrEqualToConstant: Constants.labelMaxWidth) ]) animationHolder.setContentHuggingPriority(UILayoutPriorityDefaultLow, for: .vertical) animationHolder.setContentCompressionResistancePriority(UILayoutPriorityDefaultHigh, for: .vertical) animationHolder.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ animationHolder.widthAnchor.constraint(greaterThanOrEqualTo: animationHolder.heightAnchor, multiplier: Constants.animationWidthHeightRatio) ]) animationView.contentMode = .scaleAspectFit animationView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ animationView.leadingAnchor.constraint(equalTo: animationHolder.leadingAnchor), animationView.trailingAnchor.constraint(equalTo: animationHolder.trailingAnchor), animationView.topAnchor.constraint(equalTo: animationHolder.topAnchor), animationView.bottomAnchor.constraint(equalTo: animationHolder.bottomAnchor) ]) } }
gpl-2.0
0ec0ad9984f237e9dd50cd8725fbe935
40.219178
198
0.690096
5.911591
false
false
false
false
giangbvnbgit128/AnViet
Pods/ZKProgressHUD/ZKProgressHUD/ZKProgressView.swift
1
1957
// // ZKProgressView.swift // ZKProgressHUD // // Created by ็Ž‹ๆ–‡ๅฃฎ on 2017/3/15. // Copyright ยฉ 2017ๅนด WangWenzhuang. All rights reserved. // import UIKit // MARK: - ่ฟ›ๅบฆ class ZKProgressView: UIView { var progressColor: UIColor? var progressFont: UIFont? private var _progress: Double = 0 private var textLabel: UILabel! var progress: Double { get { return _progress } set { self._progress = newValue self.setNeedsDisplay() self.setNeedsLayout() } } override init(frame: CGRect) { super.init(frame: frame) self.textLabel = UILabel() self.addSubview(self.textLabel) self.textLabel.textAlignment = .center self.textLabel.font = self.progressFont ?? ZKProgressHUDConfig.font self.textLabel.textColor = self.progressColor ?? ZKProgressHUDConfig.foregroundColor } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() self.textLabel.text = "\(Int(self.progress * 100))%" self.textLabel.sizeToFit() self.textLabel.frame.origin = CGPoint(x: (self.width - self.textLabel.width) / 2, y: (self.height - self.textLabel.height) / 2) } override func draw(_ rect: CGRect) { let ctx = UIGraphicsGetCurrentContext() let arcCenter = CGPoint(x: self.width / 2, y: self.width / 2) let radius = arcCenter.x - 2 let startAngle = -(Double.pi / 2) let endAngle = startAngle + Double.pi * 2 * self.progress let path = UIBezierPath(arcCenter: arcCenter, radius: radius, startAngle: CGFloat(startAngle), endAngle: CGFloat(endAngle), clockwise: true) ctx!.setLineWidth(4) self.progressColor?.setStroke() ctx!.addPath(path.cgPath) ctx!.strokePath() } }
apache-2.0
16ca272585c2b288abea3a095a1bf9f4
31.949153
148
0.624486
4.329621
false
false
false
false
piscoTech/GymTracker
Gym Tracker iOS/PartCollectionTVC.swift
1
24772
// // PartCollectionTableViewController.swift // Gym Tracker iOS // // Created by Marco Boschi on 20/08/2018. // Copyright ยฉ 2018 Marco Boschi. All rights reserved. // import UIKit import GymTrackerCore @objc protocol PartCollectionController: AnyObject { func addDeletedEntities(_ del: [GTDataObject]) func exerciseUpdated(_ e: GTPart) func updateView(global: Bool) func updateSecondaryInfoChange() func dismissPresentedController() var partCollection: GTDataObject { get } var tableView: UITableView! { get } var editMode: Bool { get } /// Enable or disable circuit rest for the collection if it's in a circuit and it allow so. After changing it reload section `1` of the table view. @objc func enableCircuitRest(_ s: UISwitch) } extension PartCollectionController { typealias CellInfo = (nib: String, identifier: String) var collectionDataId: CellInfo { return ("CollectionData", "collectionData") } func numberOfRowInHeaderSection() -> Int { var count = 0 if let se = partCollection as? GTSetsExercise, se.isInCircuit { count += 1 + (se.allowCircuitRest ? 1 : 0) } return count + ((partCollection as? GTSimpleSetsExercise)?.isInChoice ?? false ? 1 : 0) } func headerCell(forRowAt indexPath: IndexPath, reallyAt realIndex: IndexPath? = nil) -> UITableViewCell { let real = realIndex ?? indexPath switch indexPath.row { case 0: // Circuit information guard let se = partCollection as? GTSetsExercise, let (n, t) = se.circuitStatus else { fallthrough } let cell = tableView.dequeueReusableCell(withIdentifier: collectionDataId.identifier, for: real) cell.accessoryView = nil cell.textLabel?.text = GTLocalizedString("IS_CIRCUIT", comment: "Circuit info") cell.detailTextLabel?.text = String( format: GTLocalizedString("COMPOSITE_INFO_%lld_OF_%lld", comment: "Exercise n/m"), n, t) return cell case 1: guard let se = partCollection as? GTSetsExercise, se.isInCircuit, se.allowCircuitRest else { fallthrough } let s = UISwitch() s.addTarget(self, action: #selector(enableCircuitRest(_:)), for: .valueChanged) s.isOn = se.hasCircuitRest s.isEnabled = editMode let cell = tableView.dequeueReusableCell(withIdentifier: collectionDataId.identifier, for: real) cell.accessoryView = s cell.textLabel?.text = GTLocalizedString("CIRCUITE_USE_REST", comment: "Use rest") cell.detailTextLabel?.text = nil return cell case 2: guard let e = partCollection as? GTSimpleSetsExercise, let (n, t) = e.choiceStatus else { fallthrough } let cell = tableView.dequeueReusableCell(withIdentifier: collectionDataId.identifier, for: real) cell.accessoryView = nil cell.textLabel?.text = GTLocalizedString("IS_CHOICE", comment: "Choice info") cell.detailTextLabel?.text = String( format: GTLocalizedString("COMPOSITE_INFO_%lld_OF_%lld", comment: "Exercise n/m"), n, t) return cell default: fatalError("Unknown row") } } private func updateCollectionCells() { let total = tableView.numberOfRows(inSection: 0) let collection = numberOfRowInHeaderSection() // The types of parent collections cannot change until you pop to their respective controller, so just reloading is fine tableView.reloadRows(at: ((total - collection) ..< total).map { IndexPath(row: $0, section: 0) }, with: .automatic) } } class PartCollectionTableViewController<T: GTDataObject>: UITableViewController, UIPickerViewDelegate, UIPickerViewDataSource, PartCollectionController where T: ExerciseCollection { weak var delegate: WorkoutListTableViewController! weak var parentCollection: PartCollectionController? private weak var mover: UIViewController? private(set) weak var subCollection: PartCollectionController? private(set) weak var exerciseController: ExerciseTableViewController? var editMode = false var isNew: Bool { return false } final var canControlEdit: Bool { return parentCollection == nil } private var invalidityCache: Set<Int>! var cancelBtn: UIBarButtonItem? var doneBtn: UIBarButtonItem? private var editBtn: UIBarButtonItem? private var reorderBtn: UIBarButtonItem! var additionalRightButton: UIBarButtonItem? { return nil } private let reorderLbl = GTLocalizedString("REORDER_EXERCISE", comment: "Reorder") private let doneReorderLbl = GTLocalizedString("DONE_REORDER_EXERCISE", comment: "Done Reorder") private let additionalTip: String? var collection: T! var partCollection: GTDataObject { return collection } private var deletedEntities = [GTDataObject]() func addDeletedEntities(_ del: [GTDataObject]) { if let parent = parentCollection { parent.addDeletedEntities(del) } else { deletedEntities += del } } typealias CellInfo = PartCollectionController.CellInfo private let collectionDataId: CellInfo = ("CollectionData", "collectionData") private let noExercisesId: CellInfo = ("NoExercises", "noExercise") private let exerciseId: CellInfo = ("ExerciseTableViewCell", "exercise") private let restId: CellInfo = ("RestCell", "rest") private let restPickerId: CellInfo = ("RestPickerCell", "restPicker") private let addExerciseId: CellInfo = ("AddExerciseCell", "add") init(additionalTip: String? = nil) { self.additionalTip = additionalTip super.init(style: .grouped) } required init?(coder aDecoder: NSCoder) { additionalTip = nil super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() for (n, i) in [collectionDataId, noExercisesId, exerciseId, restId, restPickerId, addExerciseId] { tableView.register(UINib(nibName: n, bundle: Bundle.main), forCellReuseIdentifier: i) } tableView.rowHeight = UITableView.automaticDimension tableView.estimatedRowHeight = 44 title = T.collectionType if #available(iOS 11.0, *) { navigationItem.largeTitleDisplayMode = .never } if canControlEdit { cancelBtn = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(doCancel)) doneBtn = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(saveEdit)) editBtn = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: #selector(edit)) } reorderBtn = UIBarButtonItem(title: "", style: .plain, target: self, action: #selector(updateReorderMode)) updateButtons() if editMode { updateValidityAndButtons() } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) if self.isMovingFromParent { DispatchQueue.main.async { self.parentCollection?.exerciseUpdated(self.collection as! GTPart) } } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if editMode && canControlEdit { navigationController?.interactivePopGestureRecognizer?.isEnabled = false } } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) if editMode && canControlEdit { navigationController?.interactivePopGestureRecognizer?.isEnabled = true if navigationController?.isBeingDismissed ?? false { // Make sure the actual cancel action is triggered when swiping down to dismiss if self.presentationController != nil { self.cancel(animated: false, animationCompletion: nil) } } } } func updateButtons() { navigationItem.leftBarButtonItem = editMode ? cancelBtn : nil let right = (editMode ? [doneBtn, reorderBtn] : [additionalRightButton, canControlEdit ? editBtn : nil] ).compactMap { $0 } navigationItem.rightBarButtonItems = right editBtn?.isEnabled = delegate.canEdit reorderBtn.title = isEditing ? doneReorderLbl : reorderLbl } func updateValidityAndButtons(doUpdateTable: Bool = true) { guard !(self.navigationController?.isBeingDismissed ?? false) else { // Cancelling creation, nothing to do return } addDeletedEntities(collection.purge(onlySettings: true)) invalidityCache = Set(collection.exercises.lazy.filter { !$0.isValid }.map { Int($0.order) }) invalidityCache.formUnion((collection as? GTCircuit)?.exercisesError ?? []) invalidityCache.formUnion((collection as? GTChoice)?.inCircuitExercisesError ?? []) doneBtn?.isEnabled = collection.isPurgeableToValid if doUpdateTable { tableView.reloadRows(at: collection.exerciseList.lazy.filter { $0 is GTExercise }.map { self.exerciseCellIndexPath(for: $0) }, with: .automatic) } } func updateView(global: Bool = false) { if global { if let p = parentCollection { p.updateView(global: global) return } else { addDeletedEntities(collection.removePurgeable()) } } updateValidityAndButtons(doUpdateTable: false) tableView.reloadData() subCollection?.updateView(global: false) exerciseController?.updateView() } func updateSecondaryInfoChange() { subCollection?.updateSecondaryInfoChange() exerciseController?.updateSecondaryInfoChange() tableView.reloadSections([mainSectionIndex], with: .automatic) } // MARK: - Table view data source private enum ExerciseCellType { case exercise, rest, picker } var mainSectionIndex: Int { return numberOfRowInHeaderSection() > 0 ? 1 : 0 } override func numberOfSections(in tableView: UITableView) -> Int { return mainSectionIndex + (editMode ? 2 : 1) } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == mainSectionIndex { return GTLocalizedString("EXERCISES", comment: "Exercises") } return nil } override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { if editMode && section == mainSectionIndex { var tip = GTLocalizedString("EXERCISE_MANAGEMENT_TIP", comment: "Remove exercise") if let addTip = additionalTip { tip += "\n\(addTip)" } return tip } return nil } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.section == mainSectionIndex && collection.exercises.count > 0 && exerciseCellType(for: indexPath) == .picker { return 150 } return tableView.estimatedRowHeight } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case mainSectionIndex: return max(collection.exercises.count, 1) + (editRest != nil ? 1 : 0) case mainSectionIndex + 1: return 1 case 0: return numberOfRowInHeaderSection() default: return 0 } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch indexPath.section { case mainSectionIndex: if collection.exercises.isEmpty { return tableView.dequeueReusableCell(withIdentifier: noExercisesId.identifier, for: indexPath) } let p = collection[Int32(exerciseNumber(for: indexPath))]! switch exerciseCellType(for: indexPath) { case .rest: let cell = tableView.dequeueReusableCell(withIdentifier: restId.identifier, for: indexPath) as! RestCell let r = p as! GTRest cell.set(rest: r.rest) cell.isUserInteractionEnabled = editMode return cell case .exercise: if invalidityCache == nil { updateValidityAndButtons(doUpdateTable: false) } let cell = tableView.dequeueReusableCell(withIdentifier: exerciseId.identifier, for: indexPath) as! ExerciseTableViewCell let e = p as! GTExercise cell.setInfo(for: e) cell.setValidity(!invalidityCache.contains(Int(e.order))) return cell case .picker: let cell = tableView.dequeueReusableCell(withIdentifier: restPickerId.identifier, for: indexPath) as! RestPickerCell let r = p as! GTRest cell.picker.delegate = self cell.picker.dataSource = self cell.picker.selectRow(Int(ceil(r.rest / GTRest.restStep) - 1), inComponent: 0, animated: false) return cell } case mainSectionIndex + 1: let cell = tableView.dequeueReusableCell(withIdentifier: addExerciseId.identifier, for: indexPath) as! AddExerciseCell cell.addExercise.addTarget(self, action: #selector(newExercise), for: .primaryActionTriggered) if handleableTypes().count == 1 { cell.addOther.isHidden = true } else { cell.addOther.isHidden = false cell.addOther.addTarget(self, action: #selector(newChoose), for: .primaryActionTriggered) } cell.addExistent.addTarget(self, action: #selector(moveExercises), for: .primaryActionTriggered) return cell case 0: return headerCell(forRowAt: indexPath) default: fatalError("Unknown section") } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) guard !collection.exercises.isEmpty, !self.isEditing, indexPath.section == mainSectionIndex else { return } switch exerciseCellType(for: indexPath) { case .rest: guard editMode else { break } self.editRest(at: indexPath) case .exercise: self.openExercise(collection[Int32(exerciseNumber(for: indexPath))]!) default: break } } private func reloadAllSections() { let old = tableView.numberOfSections let new = self.numberOfSections(in: tableView) tableView.beginUpdates() tableView.reloadSections(IndexSet(integersIn: 0 ..< min(old, new)), with: .automatic) if old < new { tableView.insertSections(IndexSet(integersIn: old ..< new), with: .automatic) } else if old > new { tableView.deleteSections(IndexSet(integersIn: new ..< old), with: .automatic) } tableView.endUpdates() } // MARK: - Editing @objc private func edit() { guard delegate.canEdit, canControlEdit else { return } editMode = true navigationController?.interactivePopGestureRecognizer?.isEnabled = false appDelegate.tabController.isPopToWorkoutListRootEnabled = false reorderBtn.title = reorderLbl updateButtons() reloadAllSections() } private func exitEdit() { if isNew { self.dismiss(animated: true) } else { tableView.beginUpdates() editMode = false deletedEntities.removeAll() navigationController?.interactivePopGestureRecognizer?.isEnabled = true appDelegate.tabController.isPopToWorkoutListRootEnabled = true _ = navigationController?.popToViewController(self, animated: true) updateButtons() editRest = nil self.setEditing(false, animated: false) reloadAllSections() tableView.endUpdates() } } @objc func saveEdit() -> Bool { guard editMode, canControlEdit else { return false } endEditRest() guard doneBtn?.isEnabled ?? false else { return false } addDeletedEntities(collection.purge()) if appDelegate.dataManager.persistChangesForObjects(collection.subtreeNodes, andDeleteObjects: deletedEntities) { exitEdit() return true } else { self.present(UIAlertController(simpleAlert: GTLocalizedString("WORKOUT_SAVE_ERR", comment: "Cannot save"), message: nil), animated: true) tableView.reloadSections([mainSectionIndex], with: .automatic) return false } } private func canHandle(_ p: GTPart.Type) -> Bool { return p is T.Exercise.Type } private func handleableTypes() -> [(String, GTPart.Type)] { return [("CIRCUIT", GTCircuit.self), ("CHOICE", GTChoice.self), ("EXERCISE", GTSimpleSetsExercise.self), ("REST", GTRest.self)].filter { canHandle($0.1) } } @objc private func newChoose() { let choose = UIAlertController(title: GTLocalizedString("ADD_CHOOSE", comment: "Choose"), message: nil, preferredStyle: .actionSheet) for (n, t) in handleableTypes() { guard canHandle(t) else { continue } choose.addAction(UIAlertAction(title: GTLocalizedString(n, comment: "Type"), style: .default) { _ in self.newPart(of: t) }) } choose.addAction(UIAlertAction(title: GTLocalizedString("CANCEL", comment: "Cancel"), style: .cancel)) self.present(choose, animated: true) } @objc private func newExercise() { newPart(of: GTSimpleSetsExercise.self) } private func newPart(of type: GTPart.Type) { guard editMode, canHandle(type) else { return } endEditRest() tableView.beginUpdates() if collection.exercises.isEmpty { tableView.deleteRows(at: [IndexPath(row: 0, section: mainSectionIndex)], with: .automatic) } let p = appDelegate.dataManager.newPart(type) as! T.Exercise collection.add(parts: p) if let e = p as? GTSimpleSetsExercise { e.set(name: "") } else if let r = p as? GTRest { r.set(rest: 4 * 60) } tableView.insertRows(at: [IndexPath(row: Int(p.order), section: mainSectionIndex)], with: .automatic) tableView.endUpdates() openExercise(p) updateValidityAndButtons(doUpdateTable: false) } func exerciseUpdated(_ e: GTPart) { guard let p = e as? T.Exercise, collection.exercises.contains(p) else { return } addDeletedEntities(p.purge()) if p.shouldBePurged { removeExercise(p) } DispatchQueue.main.async { self.updateValidityAndButtons() } } private func removeExercise(_ e: T.Exercise) { let index = IndexPath(row: Int(e.order), section: mainSectionIndex) addDeletedEntities([e]) collection.remove(part: e) tableView.beginUpdates() tableView.deleteRows(at: [index], with: .automatic) if collection.exercises.isEmpty { tableView.insertRows(at: [IndexPath(row: 0, section: mainSectionIndex)], with: .automatic) } if let rest = editRest, rest == Int(e.order) { editRest = nil tableView.deleteRows(at: [IndexPath(row: index.row + 1, section: mainSectionIndex)], with: .fade) } tableView.endUpdates() DispatchQueue.main.async { self.updateValidityAndButtons() } } // MARK: - Edit circuit func enableCircuitRest(_ s: UISwitch) { guard editMode, let se = partCollection as? GTSetsExercise, se.isInCircuit, se.allowCircuitRest else { return } se.enableCircuitRest(s.isOn) s.isOn = se.hasCircuitRest tableView.reloadSections([mainSectionIndex], with: .automatic) } // MARK: - Edit rest private var editRest: Int? private func exerciseNumber(for i: IndexPath) -> Int { var row = i.row if let r = editRest { if r + 1 == i.row { return r } else if r + 1 < row { row -= 1 } } return row } private func exerciseCellType(for i: IndexPath) -> ExerciseCellType { var row = i.row if let r = editRest { if r + 1 == row { return .picker } else if r + 1 < row { row -= 1 } } return collection.exerciseList[row] is GTRest ? .rest : .exercise } private func exerciseCellIndexPath(for e: T.Exercise) -> IndexPath { var i = IndexPath(row: Int(e.order), section: mainSectionIndex) if let r = editRest, r < i.row { i.row += 1 } return i } func endEditRest() { if let rest = editRest { //Simulate tap on rest row to hide picker self.tableView(tableView, didSelectRowAt: IndexPath(row: rest, section: mainSectionIndex)) } } private func editRest(at indexPath: IndexPath) { let exNum = exerciseNumber(for: indexPath) tableView.beginUpdates() var onlyClose = false if let r = editRest { onlyClose = r == exNum tableView.deleteRows(at: [IndexPath(row: r + 1, section: mainSectionIndex)], with: .fade) } if onlyClose { editRest = nil } else { tableView.insertRows(at: [IndexPath(row: exNum + 1, section: mainSectionIndex)], with: .automatic) editRest = exNum } tableView.endUpdates() } func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return Int(ceil(GTRest.maxRest / GTRest.restStep)) } func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? { if #available(iOS 13, *) { // Fallback to un-styled picker return nil } else { guard let title = self.pickerView(pickerView, titleForRow: row, forComponent: component) else { return nil } return NSAttributedString(string: title, attributes: [.foregroundColor : UIColor(named: "Text Color")!]) } } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return (TimeInterval(row + 1) * GTRest.restStep).formattedDuration } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { guard let exN = editRest, let rest = collection.exerciseList[exN] as? GTRest else { return } rest.set(rest: TimeInterval(row + 1) * GTRest.restStep) tableView.reloadRows(at: [IndexPath(row: exN, section: mainSectionIndex)], with: .none) } // MARK: - Delete exercises override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return editMode && indexPath.section == mainSectionIndex && !collection.exercises.isEmpty && exerciseCellType(for: indexPath) != .picker } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { guard editingStyle == .delete else { return } let exN = exerciseNumber(for: indexPath) guard let p = collection[Int32(exN)] else { return } removeExercise(p) } // MARK: - Reorder exercises @objc private func updateReorderMode() { guard editMode, !collection.exercises.isEmpty || self.isEditing else { return } endEditRest() self.setEditing(!self.isEditing, animated: true) reorderBtn.title = self.isEditing ? doneReorderLbl : reorderLbl } override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { return editMode && indexPath.section == mainSectionIndex && !collection.exercises.isEmpty && exerciseCellType(for: indexPath) != .picker } override func tableView(_ tableView: UITableView, targetIndexPathForMoveFromRowAt sourceIndexPath: IndexPath, toProposedIndexPath proposedDestinationIndexPath: IndexPath) -> IndexPath { if proposedDestinationIndexPath.section < mainSectionIndex { return IndexPath(row: 0, section: mainSectionIndex) } else if proposedDestinationIndexPath.section > mainSectionIndex { return IndexPath(row: collection.exercises.count - 1, section: mainSectionIndex) } return proposedDestinationIndexPath } override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { guard editMode && fromIndexPath.section == mainSectionIndex && to.section == mainSectionIndex && !collection.exercises.isEmpty else { return } collection.movePart(at: Int32(fromIndexPath.row), to: Int32(to.row)) DispatchQueue.main.async { self.updateValidityAndButtons() } } // MARK: - Navigation @objc func doCancel() { cancel(animated: true, animationCompletion: nil) } func cancel(animated: Bool, animationCompletion: (() -> Void)?) { appDelegate.dataManager.discardAllChanges() dismissPresentedController() if isNew { self.dismiss(animated: animated, completion: animationCompletion) } else { exitEdit() } } func dismissPresentedController() { self.mover?.dismiss(animated: false) self.subCollection?.dismissPresentedController() self.exerciseController?.dismissPresentedController() } func openExercise(_ p: T.Exercise) { let circuitChoiceAdditionalTip = GTLocalizedString("EXERCISE_MANAGEMENT_CIRC_CHOICE_TIP", comment: "2 exercises") if let e = p as? GTSimpleSetsExercise { let dest = ExerciseTableViewController.instanciate() dest.exercise = e dest.editMode = self.editMode dest.delegate = self self.exerciseController = dest navigationController?.pushViewController(dest, animated: true) } else if p is GTRest { // No need to push anything else, edit is in place } else if let c = p as? GTCircuit { let dest = PartCollectionTableViewController<GTCircuit>(additionalTip: circuitChoiceAdditionalTip) self.subCollection = dest dest.parentCollection = self dest.editMode = editMode dest.collection = c navigationController?.pushViewController(dest, animated: true) } else if let ch = p as? GTChoice { let dest = PartCollectionTableViewController<GTChoice>(additionalTip: circuitChoiceAdditionalTip) self.subCollection = dest dest.parentCollection = self dest.editMode = editMode dest.collection = ch navigationController?.pushViewController(dest, animated: true) } else { fatalError("Unknown part type") } } @objc private func moveExercises() { let mover = MovePartTableViewController.initialize(currentPart: collection) { self.updateView(global: true) } self.mover = mover self.present(mover, animated: true) } }
mit
bf3ef9f9ddabdba61a583c5255248eef
28.844578
186
0.719026
3.83037
false
false
false
false
Tyrant2013/LeetCodePractice
LeetCodePractice/Easy/67_Add_Binary.swift
1
1400
// // Add_Binary.swift // LeetCodePractice // // Created by ๅบ„ๆ™“ไผŸ on 2018/2/11. // Copyright ยฉ 2018ๅนด Zhuang Xiaowei. All rights reserved. // //Given two binary strings, return their sum (also a binary string). // //For example, //a = "11" //b = "1" //Return "100". // import UIKit class Add_Binary: Solution { override func ExampleTest() { [ "11": "1", //110 "10": "1", "110": "0", "111": "0", "1111": "1", "100": "11", "11111" : "11", ].forEach { (key, value) in print("\(key), \(value), ret: \(self.addBinary(key, value))") } } func addBinary(_ a: String, _ b: String) -> String { let (al, bl) = (a.count, b.count) let tmpLa = Array(a.map({ Int(String($0)) }).reversed()) let tmpLb = Array(b.map({ Int(String($0)) }).reversed()) var la = al > bl ? tmpLa : tmpLb let ra = al > bl ? tmpLb : tmpLa var next = 0 for index in 0..<la.count { let raN = index >= ra.count ? 0 : ra[index]! let num = la[index]! + raN + next la[index] = num >= 2 ? num % 2 : num next = num >= 2 ? num / 2 : 0 } if (next > 0) { la.append(1) } return Array(la.map({ String($0!) }).reversed()).joined() } }
mit
4f61c42bfe3f3b7bfd1f7aa599f502d3
24.759259
77
0.45363
3.335731
false
false
false
false
practicalswift/swift
test/Sema/diag_use_before_declaration.swift
34
4032
// RUN: %target-typecheck-verify-swift // SR-5163 func sr5163() { func foo(_ x: Int) -> Int? { return 1 } func fn() { let a = foo(c) // expected-error {{use of local variable 'c' before its declaration}} guard let b = a else { return } let c = b // expected-note {{'c' declared here}} } } // SR-6726 var foo: Int? func test() { guard let bar = foo else { return } let foo = String(bar) // expected-warning {{initialization of immutable value 'foo' was never used; consider replacing with assignment to '_' or removing it}} } // SR-7660 class C { var variable: Int? func f() { guard let _ = variable else { return } let variable = 1 // expected-warning {{initialization of immutable value 'variable' was never used; consider replacing with assignment to '_' or removing it}} } } // SR-7517 func testExample() { let app = app2 // expected-error {{use of local variable 'app2' before its declaration}} let app2 = app // expected-note {{'app2' declared here}} } // SR-8447 func test_circular() { let obj = sr8447 // expected-error {{use of local variable 'sr8447' before its declaration}} let _ = obj.prop, sr8447 // expected-note {{'sr8447' declared here}} expected-error {{type annotation missing in pattern}} } //===----------------------------------------------------------------------===// // Nested scope //===----------------------------------------------------------------------===// func nested_scope_1() { do { do { let _ = x // expected-error {{use of local variable 'x' before its declaration}} let x = 111 // expected-note {{'x' declared here}} } let x = 11 } let x = 1 } func nested_scope_2() { do { let x = 11 do { let _ = x let x = 111 // expected-warning {{initialization of immutable value 'x' was never used; consider replacing with assignment to '_' or removing it}} } } let x = 1 // expected-warning {{initialization of immutable value 'x' was never used; consider replacing with assignment to '_' or removing it}} } func nested_scope_3() { let x = 1 do { do { let _ = x let x = 111 // expected-warning {{initialization of immutable value 'x' was never used; consider replacing with assignment to '_' or removing it}} } let x = 11 // expected-warning {{initialization of immutable value 'x' was never used; consider replacing with assignment to '_' or removing it}} } } //===----------------------------------------------------------------------===// // Type scope //===----------------------------------------------------------------------===// class Ty { var v : Int? func fn() { let _ = v let v = 1 // expected-warning {{initialization of immutable value 'v' was never used; consider replacing with assignment to '_' or removing it}} } } //===----------------------------------------------------------------------===// // File scope //===----------------------------------------------------------------------===// let g = 0 func file_scope_1() { let _ = g let g = 1 // expected-warning {{initialization of immutable value 'g' was never used; consider replacing with assignment to '_' or removing it}} } func file_scope_2() { let _ = gg // expected-error {{use of local variable 'gg' before its declaration}} let gg = 1 // expected-note {{'gg' declared here}} } //===----------------------------------------------------------------------===// // Module scope //===----------------------------------------------------------------------===// func module_scope_1() { let _ = print // Legal use of func print declared in Swift Standard Library let print = "something" // expected-warning {{initialization of immutable value 'print' was never used; consider replacing with assignment to '_' or removing it}} } func module_scope_2() { let _ = another_print // expected-error {{use of local variable 'another_print' before its declaration}} let another_print = "something" // expected-note {{'another_print' declared here}} }
apache-2.0
45d87daaf2586a62f9ba45fa756d6297
31.780488
164
0.546875
4.330827
false
false
false
false
crossroadlabs/ExpressCommandLine
swift-express/Core/FoundationExtensions.swift
1
4770
//===--- FoundationExtensions.swift -------------------------------------===// //Copyright (c) 2015-2016 Daniel Leping (dileping) // //This file is part of Swift Express Command Line // //Swift Express Command Line is free software: you can redistribute it and/or modify //it under the terms of the GNU General Public License as published by //the Free Software Foundation, either version 3 of the License, or //(at your option) any later version. // //Swift Express Command Line is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU General Public License for more details. // //You should have received a copy of the GNU General Public License //along with Swift Express Command Line. If not, see <http://www.gnu.org/licenses/>. // //===-------------------------------------------------------------------===// import Foundation import Regex extension NSData { func toArray() -> [UInt8] { return Array<UInt8>(UnsafeBufferPointer(start: UnsafePointer<UInt8>(self.bytes), count: self.length)) } static func fromArray(array: [UInt8]) -> NSData { return array.toData() } static func fromArray(array: [Int8]) -> NSData { return array.toData() } } protocol SEByte {} extension UInt8 : SEByte {} extension Int8 : SEByte {} extension Array where Element:SEByte { func toString() throws -> String { if count == 0 { return "" } var arr:Array<Element> = self switch self[count-1] { case let char as Int8: if char != 0 { arr = self + [Int8(0) as! Element] } case let char as UInt8: if char != 0 { arr = self + [UInt8(0) as! Element] } default: arr = self } return String.fromCString(UnsafePointer<Int8>(arr))! } func toData() -> NSData { return NSData(bytes: self, length: self.count) } static func fromData(data: NSData) -> Array<UInt8> { return data.toArray() } } extension String { static func fromArray(array: [UInt8]) throws -> String { return try array.toString() } static func fromArray(array: [Int8]) throws -> String { return try array.toString() } func ltrim(char: Character = " ") -> String { var index = 0 for c in characters { if c != char { break } index += 1 } return substringFromIndex(characters.startIndex.advancedBy(index)) } func rtrim(char: Character = " ") -> String { var index = 0 for c in characters.reverse() { if c != char { break } index += 1 } return substringToIndex(characters.endIndex.advancedBy(-index)) } func trim(char: Character = " ") -> String { return ltrim(char).rtrim(char) } func addPathComponent(component: String) -> String { let trimmed = component.trim("/") let selftrimed = rtrim("/") return selftrimed + "/" + trimmed } func removeLastPathComponent() -> String { let trimmed = rtrim("/") var index = 0 for c in trimmed.characters.reverse() { if c == "/" { break; } index += 1 } return trimmed.substringToIndex(characters.endIndex.advancedBy(-index)) } func lastPathComponent() -> String { let trimmed = rtrim("/") var index = 0 for c in trimmed.characters.reverse() { if c == "/" { break; } index += 1 } return trimmed.substringFromIndex(characters.endIndex.advancedBy(-index)) } func toArray() -> [UInt8] { return Array<UInt8>(utf8) } private static let _curDirR = "\\/\\.\\/|\\/\\.$|^\\.\\/".r! private static let _topDirR = "[^\\/\\?\\%\\*\\:\\|\"<>\\.]+/\\.\\.".r! func standardizedPath() -> String { if characters.count == 0 { return self } var output = trim().rtrim("/") if output.characters[output.characters.startIndex] == "~" { output = FileManager.homeDirectory().addPathComponent(output.ltrim("~")) } if output.characters[output.characters.startIndex] != "/" { output = FileManager.currentWorkingDirectory().addPathComponent(output) } return String._curDirR.replaceAll(String._topDirR.replaceAll(output, replacement: ""), replacement: "/").rtrim("/") } }
gpl-3.0
3c6d2dde75040d61425796ba818ef966
29.382166
123
0.547799
4.582133
false
false
false
false
mrlegowatch/RolePlayingCore
CharacterGenerator/CharacterGenerator/Player/PlayerDetailViewController.swift
1
1814
// // PlayerDetailViewController.swift // CharacterGenerator // // Created by Brian Arnold on 7/4/17. // Copyright ยฉ 2017 Brian Arnold. All rights reserved. // import UIKit import RolePlayingCore class PlayerDetailViewController: UICollectionViewController { var characterSheet: CharacterSheet! func configureView() { guard characterSheet != nil else { return } collectionView?.reloadData() } override func viewDidLoad() { super.viewDidLoad() // Configure the layout to be dynamic based on content if let layout = self.collectionViewLayout as? UICollectionViewFlowLayout { layout.estimatedItemSize = CGSize(width: 100, height: 50) } configureView() } var player: Player? { didSet { characterSheet = CharacterSheet(player!) configureView() } } override func numberOfSections(in collectionView: UICollectionView) -> Int { return characterSheet.numberOfSections } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return characterSheet.numberOfItems(in: section) } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // TODO: implement a TraitCellFactory. let cellIdentifier = characterSheet.cellIdentifiers[indexPath.section][indexPath.row] let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) if let configurable = cell as? TraitConfigurable { configurable.configure(characterSheet, at: indexPath) } return cell } }
mit
24b0a9b4ca3a111844b65241e88cf55c
28.721311
130
0.664093
5.683386
false
true
false
false
LogTape/LogTape-iOS
LogTape/Classes/LogTape.swift
1
9881
import UIKit extension UIApplication { public class func lt_inject() { // make sure this isn't a subclass if self !== UIApplication.self { return } if !LogTape.swizzled { LogTape.swizzled = true let originalSelector = #selector(UIApplication.sendEvent(_:)) let swizzledSelector = #selector(UIApplication.lt_sendEvent(_:)) guard let originalMethod = class_getInstanceMethod(self, originalSelector) else { return } guard let swizzledMethod = class_getInstanceMethod(self, swizzledSelector) else { return } let didAddMethod = class_addMethod(self, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod)) if didAddMethod { class_replaceMethod(self, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod)) } else { method_exchangeImplementations(originalMethod, swizzledMethod) } } } // MARK: - Method Swizzling @objc func lt_sendEvent(_ event : UIEvent) { if event.subtype == UIEvent.EventSubtype.motionShake { LogTape.showReportVC() } if let window = UIApplication.shared.keyWindow { for touch in event.touches(for: window) ?? Set<UITouch>() { if let videoRecorder = LogTape.VideoRecorder { videoRecorder.handleTouch(touch) } } } self.lt_sendEvent(event) } } open class LogEvent { static let dateFormatter = LogEvent.InitDateFormatter() let timestamp = Date() static var idCounter = Int(0) let id : Int let tags : [String : String] init(tags : [String : String]) { self.id = LogEvent.idCounter LogEvent.idCounter += 1 self.tags = tags } static func InitDateFormatter() -> DateFormatter { let formatter = DateFormatter() formatter.timeZone = TimeZone(abbreviation: "UTC") formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" return formatter } func toDictionary() -> NSDictionary { return NSDictionary() } func timestampAsUTCString() -> String { return LogEvent.dateFormatter.string(from: self.timestamp) } } class ObjectLogEvent : LogEvent { var object = NSDictionary() var message = NSString() init(object : NSDictionary, message : String, tags : [String : String]) { super.init(tags: tags) self.object = object self.message = message as NSString } override func toDictionary() -> NSDictionary { return [ "type" : "JSON", "id" : self.id, "message" : message, "timestamp" : timestampAsUTCString(), "data" : object, "tags" : self.tags ] } } open class RequestLogStartedEvent : LogEvent { var request : URLRequest? = nil init(request : URLRequest?, tags : [String : String]) { super.init(tags: tags) self.request = request } override func toDictionary() -> NSDictionary { let requestDict = NSMutableDictionary() if let request = request { requestDict["method"] = request.httpMethod if let requestData = request.httpBody { let dataString = String(data: requestData, encoding: String.Encoding.utf8) ?? "" requestDict["data"] = dataString } if let url = request.url { requestDict["url"] = url.absoluteString } if let headers = request.allHTTPHeaderFields { requestDict["headers"] = headers } } let data = NSMutableDictionary() data["request"] = requestDict let ret = NSMutableDictionary() ret["type"] = "REQUEST_START" ret["timestamp"] = timestampAsUTCString() ret["data"] = data ret["id"] = self.id ret["tags"] = self.tags return ret } } class RequestLogEvent : LogEvent { var response : URLResponse? = nil var error : Error? = nil var responseData : Data? = nil var requestStartedEvent : RequestLogStartedEvent init(startEvent : RequestLogStartedEvent, response : URLResponse?, responseData : Data?, error : Error?, tags : [String : String]) { self.requestStartedEvent = startEvent super.init(tags: tags) self.response = response self.error = error self.responseData = responseData } override func toDictionary() -> NSDictionary { let ret = NSMutableDictionary(dictionary : requestStartedEvent.toDictionary()) var dataString = "" if let responseData = responseData { dataString = String(data: responseData, encoding: String.Encoding.utf8) ?? "" } var responseDict = NSMutableDictionary() if let response = response as? HTTPURLResponse { let elapsedTime = self.timestamp.timeIntervalSince(self.requestStartedEvent.timestamp) * 1000 responseDict = ["headers" : response.allHeaderFields as NSDictionary, "statusCode" : response.statusCode as NSNumber, "data" : dataString, "time" : elapsedTime as NSNumber] if let error = self.error { responseDict["error"] = error.localizedDescription } } let dataDict = ret["data"] as! NSMutableDictionary dataDict["response"] = responseDict ret["type"] = "REQUEST" ret["timestamp"] = timestampAsUTCString() ret["id"] = self.id ret["startId"] = self.requestStartedEvent.id ret["tags"] = self.tags return ret } } class MessageLogEvent : LogEvent { var message : String = "" init(message : String, tags : [String : String]) { super.init(tags: tags) self.message = message } override func toDictionary() -> NSDictionary { return [ "type" : "LOG", "id" : self.id, "timestamp" : timestampAsUTCString(), "data" : message, "tags" : self.tags ] } } open class LogTape { static var instance : LogTape? = nil static var swizzled = false; fileprivate var events = [LogEvent]() fileprivate var apiKey = "" var videoRecorder = LogTapeVideoRecorder() var attachedScreenshots = [UIImage]() init(apiKey : String) { self.apiKey = apiKey } static var VideoRecorder : LogTapeVideoRecorder? { return instance?.videoRecorder } static func showReportVC() { LogTape.VideoRecorder?.stop() LogTapeVC.show(LogTape.instance?.apiKey ?? "") } public static func start(_ apiKey : String) { self.instance = LogTape(apiKey : apiKey) UIApplication.lt_inject() } init() { } fileprivate func Log(_ message : String, tags : [String : String] = [:]) { self.events.append(MessageLogEvent(message: message, tags : tags)) } fileprivate func LogObject(_ object : NSDictionary, message : String = "", tags : [String : String] = [:]) { self.events.append(ObjectLogEvent(object: object, message: message, tags : tags)) } // MARK: URLRequest convenience methods var pendingReqEvents = [URLRequest : RequestLogStartedEvent]() fileprivate func LogRequestStart(_ request : URLRequest, tags : [String : String] = [:]) { let event = RequestLogStartedEvent(request: request, tags : tags) self.events.append(event) pendingReqEvents[request] = event } fileprivate func LogRequestFinished(_ request : URLRequest, response : URLResponse?, data : Data?, error : Error?, tags : [String : String]) { if let startEvent = pendingReqEvents[request] { let event = RequestLogEvent(startEvent: startEvent, response: response, responseData: data, error: error, tags : tags) self.events.append(event) pendingReqEvents.removeValue(forKey: request) } } // Convenience static methods public static func Log(_ message : String, tags : [String : String] = [:]) { self.instance?.Log(message, tags : tags) } public static func Log(_ message : String, infoTag : String) { self.instance?.Log(message, tags : [infoTag : "info"]) } public static func LogRequestStart(_ request : URLRequest, tags : [String : String] = [:]) { self.instance?.LogRequestStart(request, tags: tags) } public static func LogRequestFinished(_ request : URLRequest, response : URLResponse?, data : Data?, error : Error?, tags : [String : String]) { self.instance?.LogRequestFinished(request, response: response, data: data, error: error, tags: tags) } public static func LogObject(_ object : NSDictionary, message : String = "", tags : [String : String] = [:]) { self.instance?.LogObject(object, message : message, tags : tags) } static var Events : [LogEvent] { return self.instance?.events ?? [] } }
mit
06c60abb9463d38779e6061c4810d16b
31.29085
152
0.565024
4.938031
false
false
false
false
cuappdev/eatery
Eatery/Views/BRB/DescriptionTableViewCell.swift
1
865
// // DescriptionTableViewCell.swift // Eatery // // Created by William Ma on 3/2/19. // Copyright ยฉ 2019 CUAppDev. All rights reserved. // import UIKit class DescriptionTableViewCell: UITableViewCell { let textView = UITextView() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) selectionStyle = .none textView.isEditable = false textView.isScrollEnabled = false textView.isSelectable = false textView.font = .preferredFont(forTextStyle: .body) contentView.addSubview(textView) textView.snp.makeConstraints { make in make.edges.equalToSuperview().inset(10) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) will not be implemented") } }
mit
2cc8bbde0de364552903455f11a79961
24.411765
74
0.670139
4.747253
false
false
false
false
kitasuke/TwitterClientDemo
TwitterClientDemo/Classes/ViewControllers/LoginViewController.swift
1
2153
// // LoginViewController.swift // TwitterClientDemo // // Created by Yusuke Kita on 5/20/15. // Copyright (c) 2015 kitasuke. All rights reserved. // import UIKit import Accounts class LoginViewController: UIViewController { @IBOutlet weak var loginButton: UIButton? // MARK: - IBActions @IBAction func loginWithTwitter(sender: AnyObject) { // prevent from double tap loginButton?.enabled = false TwitterStore.sharedStore.login { [unowned self] (result: Result<[ACAccount]>) -> Void in let alertController: UIAlertController if let error = result.error { alertController = LoginAlert.Failure.alertController self.presentViewController(alertController, animated: true, completion: nil) // make it enabled to try again self.loginButton?.enabled = true return } if let accounts = result.value { alertController = LoginAlert.Account(accounts: accounts, completionHandler: { (account) -> Void in self.setupAccount(account) }).alertController self.presentViewController(alertController, animated: true, completion: nil) return } } } // MARK: - Account manager private func setupAccount(account: ACAccount) { UserStore.sharedStore.account = account TwitterStore.sharedStore.fetchMe { (result: Result<User>) -> Void in } let alertController = LoginAlert.Success(name: account.username, completionHandler: openHome).alertController self.presentViewController(alertController, animated: true, completion: nil) } // MARK: - Completion handler private var openHome = { () -> Void in let rootViewController = UIStoryboard(name: StoryboardName.Home.rawValue, bundle: nil).instantiateInitialViewController() as! UINavigationController UIApplication.sharedApplication().keyWindow?.rootViewController = rootViewController } }
mit
0e4ecfc3a161a35d1eddfa5c9757cf06
34.9
156
0.62889
5.606771
false
false
false
false
danielbyon/Convert
Sources/Convert/Length.swift
1
4389
// // Length.swift // Convert // // Copyright ยฉ 2017 Daniel Byon // // 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 CoreGraphics public struct Length: Convertible { public enum Unit: Double { case millimeter = 0.001 case centimeter = 0.01 case decimeter = 0.1 case meter = 1.0 case dekameter = 10.0 case hectometer = 100.0 case kilometer = 1_000.0 case yard = 0.914_4 case parsec = 30_856_775_813_060_000.0 case mile = 1_609.344 case foot = 0.304_8 case fathom = 1.828_8 case inch = 0.025_4 case league = 4_000.0 } public let value: Double public let unit: Unit public init(value: Double, unit: Unit) { self.value = value self.unit = unit } } public extension Double { var millimeter: Length { return Length(value: self, unit: .millimeter) } var centimeter: Length { return Length(value: self, unit: .centimeter) } var decimeter: Length { return Length(value: self, unit: .decimeter) } var meter: Length { return Length(value: self, unit: .meter) } var dekameter: Length { return Length(value: self, unit: .dekameter) } var hectometer: Length { return Length(value: self, unit: .hectometer) } var kilometer: Length { return Length(value: self, unit: .kilometer) } var yard: Length { return Length(value: self, unit: .yard) } var parsec: Length { return Length(value: self, unit: .parsec) } var mile: Length { return Length(value: self, unit: .mile) } var foot: Length { return Length(value: self, unit: .foot) } var fathom: Length { return Length(value: self, unit: .fathom) } var inch: Length { return Length(value: self, unit: .inch) } var league: Length { return Length(value: self, unit: .league) } } public extension CGFloat { var millimeter: Length { return Length(value: Double(self), unit: .millimeter) } var centimeter: Length { return Length(value: Double(self), unit: .centimeter) } var decimeter: Length { return Length(value: Double(self), unit: .decimeter) } var meter: Length { return Length(value: Double(self), unit: .meter) } var dekameter: Length { return Length(value: Double(self), unit: .dekameter) } var hectometer: Length { return Length(value: Double(self), unit: .hectometer) } var kilometer: Length { return Length(value: Double(self), unit: .kilometer) } var yard: Length { return Length(value: Double(self), unit: .yard) } var parsec: Length { return Length(value: Double(self), unit: .parsec) } var mile: Length { return Length(value: Double(self), unit: .mile) } var foot: Length { return Length(value: Double(self), unit: .foot) } var fathom: Length { return Length(value: Double(self), unit: .fathom) } var inch: Length { return Length(value: Double(self), unit: .inch) } var league: Length { return Length(value: Double(self), unit: .league) } }
mit
63be40dbfedf1f3bbd0a43c0003c9b8e
23.931818
82
0.622151
3.852502
false
false
false
false
wangyaqing/LeetCode-swift
Solutions/27. Remove Element.playground/Contents.swift
1
386
import UIKit class Solution { func removeElement(_ nums: inout [Int], _ val: Int) -> Int { var i = 0 while i < nums.count { if nums[i] == val { nums.remove(at: i) } else { i += 1 } } return nums.count } } var nums = [0,1,2,2,3,0,4,2] print(Solution().removeElement(&nums, 2))
mit
a82ba5e24f5e8380a104b79a84ab6497
20.444444
64
0.445596
3.446429
false
false
false
false