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
radazzouz/firefox-ios
Shared/KeyboardHelper.swift
2
5129
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Foundation /** * The keyboard state at the time of notification. */ public struct KeyboardState { public let animationDuration: Double public let animationCurve: UIViewAnimationCurve private let userInfo: [AnyHashable: Any] fileprivate init(_ userInfo: [AnyHashable: Any]) { self.userInfo = userInfo animationDuration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! Double // HACK: UIViewAnimationCurve doesn't expose the keyboard animation used (curveValue = 7), // so UIViewAnimationCurve(rawValue: curveValue) returns nil. As a workaround, get a // reference to an EaseIn curve, then change the underlying pointer data with that ref. var curve = UIViewAnimationCurve.easeIn if let curveValue = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? Int { NSNumber(value: curveValue as Int).getValue(&curve) } self.animationCurve = curve } /// Return the height of the keyboard that overlaps with the specified view. This is more /// accurate than simply using the height of UIKeyboardFrameBeginUserInfoKey since for example /// on iPad the overlap may be partial or if an external keyboard is attached, the intersection /// height will be zero. (Even if the height of the *invisible* keyboard will look normal!) public func intersectionHeightForView(_ view: UIView) -> CGFloat { if let keyboardFrameValue = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue { let keyboardFrame = keyboardFrameValue.cgRectValue let convertedKeyboardFrame = view.convert(keyboardFrame, from: nil) let intersection = convertedKeyboardFrame.intersection(view.bounds) return intersection.size.height } return 0 } } public protocol KeyboardHelperDelegate: class { func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardWillShowWithState state: KeyboardState) func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardDidShowWithState state: KeyboardState) func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardWillHideWithState state: KeyboardState) } /** * Convenience class for observing keyboard state. */ open class KeyboardHelper: NSObject { open var currentState: KeyboardState? fileprivate var delegates = [WeakKeyboardDelegate]() open class var defaultHelper: KeyboardHelper { struct Singleton { static let instance = KeyboardHelper() } return Singleton.instance } /** * Starts monitoring the keyboard state. */ open func startObserving() { NotificationCenter.default.addObserver(self, selector: #selector(KeyboardHelper.SELkeyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(KeyboardHelper.SELkeyboardDidShow(_:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(KeyboardHelper.SELkeyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } deinit { NotificationCenter.default.removeObserver(self) } /** * Adds a delegate to the helper. * Delegates are weakly held. */ open func addDelegate(_ delegate: KeyboardHelperDelegate) { for weakDelegate in delegates { // Reuse any existing slots that have been deallocated. if weakDelegate.delegate == nil { weakDelegate.delegate = delegate return } } delegates.append(WeakKeyboardDelegate(delegate)) } func SELkeyboardWillShow(_ notification: Notification) { if let userInfo = notification.userInfo { currentState = KeyboardState(userInfo) for weakDelegate in delegates { weakDelegate.delegate?.keyboardHelper(self, keyboardWillShowWithState: currentState!) } } } func SELkeyboardDidShow(_ notification: Notification) { if let userInfo = notification.userInfo { currentState = KeyboardState(userInfo) for weakDelegate in delegates { weakDelegate.delegate?.keyboardHelper(self, keyboardDidShowWithState: currentState!) } } } func SELkeyboardWillHide(_ notification: Notification) { if let userInfo = notification.userInfo { currentState = KeyboardState(userInfo) for weakDelegate in delegates { weakDelegate.delegate?.keyboardHelper(self, keyboardWillHideWithState: currentState!) } } } } private class WeakKeyboardDelegate { weak var delegate: KeyboardHelperDelegate? init(_ delegate: KeyboardHelperDelegate) { self.delegate = delegate } }
mpl-2.0
a923e844062376c3666977d4ef2a783c
39.070313
172
0.692923
5.630077
false
false
false
false
sleepsaint/OL-Language
ol-swift/ol-swift/main.swift
1
3347
// // main.swift // ol-swift // // Created by 伍 威 on 14/12/29. // Copyright (c) 2014年 sleepsaint. All rights reserved. // import Foundation func test_parse() { let test = [ "^.wear.{^.person.{~.person}.wear.hat}.price", "#(abd,bdf)", "(abd, adfsdf, asdfd, ", "!(abd, [email protected].{@.abd}.(~.abc,daf, $12.4) )", "!(abd, [email protected].{@.abd}.(~.abc,daf, $12.4)", "!()", "!(abd, [email protected].{@.abd}.)", "(abd, [email protected].$123.{@.abd})", "(abd, sdfe", "(abd, [email protected].{@.abd.{~.abd})", "(abd, [email protected].{@.abd.{.abd})", "(abd, !)" ] for t in test { if let value = OLSource.parse(t) { println(value) } } } let root = NSJSONSerialization.JSONObjectWithData(NSString(string: "{\"person\":{\"P0001\":{\"name\":\"Tom\",\"age\":30,\"wear\":{\"hat\":\"W0001\",\"upper\":\"W0002\",\"under\":\"W0003\",\"shoes\":null}},\"P0002\":{\"name\":\"May\",\"age\":25,\"wear\":{\"hat\":\"W0004\",\"upper\":\"W0005\",\"under\":\"W0006\",\"shoes\":\"W0007\"}}},\"wear\":{\"W0001\":{\"name\":\"Red Hat\",\"price\":100},\"W0002\":{\"name\":\"White Jacket\",\"price\":200},\"W0003\":{\"name\":\"Black Shorts\",\"price\":50},\"W0004\":{\"name\":\"White Hat\",\"price\":210},\"W0005\":{\"name\":\"Red Jacket\",\"price\":220},\"W0006\":{\"name\":\"White Skirt\",\"price\":60},\"W0007\":{\"name\":\"Red HHS\",\"price\":10}}}").dataUsingEncoding(NSUTF8StringEncoding)!, options: NSJSONReadingOptions(0), error: nil) as NSDictionary let temp = NSJSONSerialization.JSONObjectWithData(NSString(string: "{\"person\":\"P0001\",\"person2\":\"^.person.P0001\",\"wearnow\":\"upper\",\"personwear\":\"^.wear.{~.person2.wear.{~.wearnow}}\",\"wearfilter1\":\"#(>, @.price, $150)\",\"wearsorter1\":\"#(!(=,@.name,Red Hat),[email protected]))\",\"now\":\"^.wear\"}").dataUsingEncoding(NSUTF8StringEncoding)!, options: NSJSONReadingOptions(0), error: nil) as NSDictionary let test = [ "^.wear.{^.person.{~.person}.wear.hat}.price", "^.wear.{~.person2.wear.hat}.price", "~.personwear.price", "(-, (+, ^.wear.W0001.price, ^.wear.W0002.price), ^.wear.W0002.price)", "(filter, ^.wear, #(>, @.price, $150))", "(filter, ^.wear, ~.wearfilter1)", "(or, !(>,^.wear.W0001.price,50), (>, ^.wear.W0002.price, 100) )", "(sort, ^.wear, #(@.price))", "(sort, ^.wear, #(!(=,@.name,Red Hat),@.price))", "(sort, ^.wear, ~.wearsorter1)", "(some, ^.wear, ~.wearfilter1)", "(sort, ~.now, ~.wearsorter1)", "(some, ~.now, #(>,@.price,50))", "(sort, ^.wear, #@.price)", "(sort, ^.wear, #[email protected])", "(random)", "(random, $5)", "(random, $-5, $-3)" ] func test_lookup() { for t in test { if let value = OLSource.parse(t) { let a = value.lookup(root, temp: temp, now: root) println(t) println(a) } } } func test_lookup2() { for t in test { if let value = OLSource.parse(t) { // let a = value.lookup(root, temp: temp, now: root) // println(t) // println(a) } } } func PP(f: ()->()) { let start = clock() for i in 0 ..< 10 { f() } let end = clock() println(end - start) } //test_parse() //test_lookup() PP(test_lookup2)
mit
5261bc57e5a040d715dea1e2946566b2
37.413793
797
0.499252
3.093519
false
true
false
false
karstengresch/rw_studies
Apprentice/Checklists09/Checklists/ItemDetailViewController.swift
1
5882
// // ItemDetailViewController.swift // Checklists // // Created by Karsten Gresch on 02.12.15. // Copyright © 2015 Closure One. All rights reserved. // import Foundation import UIKit protocol ItemDetailViewControllerDelegate: class { func itemDetailViewControllerDidCancel(_ controller: ItemDetailViewController) func itemDetailViewController(_ controller: ItemDetailViewController, didFinishAddingItem checklistItem: ChecklistItem) func itemDetailViewController(_ controller: ItemDetailViewController, didFinishEditingItem checklistItem: ChecklistItem) } class ItemDetailViewController: UITableViewController, UITextFieldDelegate { var checklistItemToEdit: ChecklistItem? var dueDate = Date() var datePickerVisible = false @IBOutlet weak var addItemTextField: UITextField? @IBOutlet weak var doneBarButton: UIBarButtonItem? @IBOutlet weak var shouldRemindSwitch: UISwitch? @IBOutlet weak var dueDateLabel: UILabel? @IBOutlet weak var datePickerCell: UITableViewCell? @IBOutlet weak var datePicker: UIDatePicker? weak var delegate: ItemDetailViewControllerDelegate? // MARK: View related override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) addItemTextField?.becomeFirstResponder() } override func viewDidLoad() { super.viewDidLoad() if let itemToEdit = checklistItemToEdit { title = "Edit item" addItemTextField?.text = itemToEdit.text doneBarButton?.isEnabled = true shouldRemindSwitch?.isOn = itemToEdit.shouldRemind dueDate = itemToEdit.dueDate as Date } updateDueDateLabel() } func updateDueDateLabel() { print("updateDueDateLabel") let formatter = DateFormatter() formatter.dateStyle = .medium formatter.timeStyle = .short dueDateLabel?.text = formatter.string(from: dueDate) } // MARK: Table specific // MARK: Action handlers @IBAction func cancel() { // dismissViewControllerAnimated(true, completion: nil) delegate?.itemDetailViewControllerDidCancel(self); } @IBAction func done() { print("done()") if let checklistItem = checklistItemToEdit { print("done() - checklistItem exists") checklistItem.text = (addItemTextField?.text)! checklistItem.shouldRemind = (shouldRemindSwitch?.isOn)! checklistItem.dueDate = dueDate delegate?.itemDetailViewController(self, didFinishEditingItem: checklistItem) } else { print("done() - checklistItem does not exist") let checklistItem = ChecklistItem() checklistItem.text = (addItemTextField?.text)! checklistItem.checked = false checklistItem.shouldRemind = (shouldRemindSwitch?.isOn)! checklistItem.dueDate = dueDate delegate?.itemDetailViewController(self, didFinishAddingItem: checklistItem) } } // MARK: Text field specific func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if let oldText: NSString = textField.text as NSString? { let newText: NSString = oldText.replacingCharacters(in: range, with: string) as NSString doneBarButton?.isEnabled = (newText.length > 0) } return true } func showDatePicker() { print("showDatePicker()") datePickerVisible = true let indexPathDatePicker = IndexPath(row: 2, section: 1) tableView.insertRows(at: [indexPathDatePicker], with: .fade) } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { print("cellForRowAtIndexPath() indexPath.section: \((indexPath as NSIndexPath).section) - indexPath.row: \((indexPath as NSIndexPath).row)") if (indexPath as NSIndexPath).section == 1 && (indexPath as NSIndexPath).row == 2 { // dangerous return datePickerCell! } else { return super.tableView(tableView, cellForRowAt: indexPath) } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 1 && datePickerVisible { print("numberOfRowsInSection(): section 1 AND datePickerVisible") return 3 } else { print("numberOfRowsInSection(): section 1 ?XOR datePickerVisible") return super.tableView(tableView, numberOfRowsInSection: section) } } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if (indexPath as NSIndexPath).section == 1 && (indexPath as NSIndexPath).row == 2 { return 217 } else { return super.tableView(tableView, heightForRowAt: indexPath) } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print("didSelectRowAtIndexPath: \((indexPath as NSIndexPath).row) - didSelectRowAtIndexPath: \((indexPath as NSIndexPath).section)") tableView.deselectRow(at: indexPath, animated: true) addItemTextField?.resignFirstResponder() if (indexPath as NSIndexPath).section == 1 && (indexPath as NSIndexPath).row == 1 { print("Trying to show date picker") showDatePicker() } } override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { if (indexPath as NSIndexPath).section == 1 && (indexPath as NSIndexPath).row == 1 { return indexPath } else { return nil } } override func tableView(_ tableView: UITableView, indentationLevelForRowAt indexPath: IndexPath) -> Int { var indexPath = indexPath if (indexPath as NSIndexPath).section == 1 && (indexPath as NSIndexPath).row == 2 { indexPath = IndexPath(row: 0, section: (indexPath as NSIndexPath).section) } return super.tableView(tableView, indentationLevelForRowAt: indexPath) } }
unlicense
faee776e6f436649487b824c43e26416
31.672222
144
0.706342
5.154251
false
false
false
false
HWdan/DYTV
DYTV/DYTV/Classes/Home/View/AmuseMenuView.swift
1
2662
// // AmuseMenuView.swift // DYTV // // Created by hegaokun on 2017/4/11. // Copyright © 2017年 AAS. All rights reserved. // import UIKit private let kMenuCellID = "kMenuCellID" class AmuseMenuView: UIView { //MARK:- 定义属性 var groups: [AnchorGroup]? { didSet { collectionView.reloadData() } } //MARK:- 控件属性 @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var pageControl: UIPageControl! //MARK:- 从 xib 中加载出来执行 override func awakeFromNib() { super.awakeFromNib() collectionView.register(UINib(nibName: "AmuseMenuViewCell", bundle: nil), forCellWithReuseIdentifier: kMenuCellID) } //MARK:- UI布局要在 layoutSubviews override func layoutSubviews() { super.layoutSubviews() let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout layout.itemSize = collectionView.bounds.size } } //MARK:- 快速创建 AmuseMenuView extension AmuseMenuView { class func amuseMenuView() -> AmuseMenuView { return Bundle.main.loadNibNamed("AmuseMenuView", owner: nil, options: nil)?.first as! AmuseMenuView } } //MARK:- UICollectionViewDataSource extension AmuseMenuView: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if groups == nil { return 0 } let pageNumber = (groups!.count - 1) / 8 + 1 pageControl.numberOfPages = pageNumber return pageNumber } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kMenuCellID, for: indexPath) as! AmuseMenuViewCell setupCellDataWithCell(cell: cell, indexPath: indexPath) return cell } private func setupCellDataWithCell(cell: AmuseMenuViewCell, indexPath:IndexPath){ //根据 0页:0 ~ 7 1页:8 ~ 15 2页:16 ~ 23 可以获取起点和终点位置 let startIndex = indexPath.item * 8 var endIndex = (indexPath.item + 1) * 8 - 1 //越界处理 if endIndex > groups!.count - 1 { endIndex = groups!.count - 1 } cell.groups = Array(groups![startIndex...endIndex]) } } //MARK:- UICollectionViewDelegate extension AmuseMenuView: UICollectionViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { pageControl.currentPage = Int(scrollView.contentOffset.x / scrollView.bounds.width) } }
mit
21aaf0e058544e21fc0571ffb7355448
31.0625
125
0.673294
4.821429
false
false
false
false
xwu/swift
test/SILGen/foreach.swift
4
23536
// RUN: %target-swift-emit-silgen -module-name foreach %s | %FileCheck %s ////////////////// // Declarations // ////////////////// class C {} @_silgen_name("loopBodyEnd") func loopBodyEnd() -> () @_silgen_name("condition") func condition() -> Bool @_silgen_name("loopContinueEnd") func loopContinueEnd() -> () @_silgen_name("loopBreakEnd") func loopBreakEnd() -> () @_silgen_name("funcEnd") func funcEnd() -> () struct TrivialStruct { var value: Int32 } struct NonTrivialStruct { var value: C } struct GenericStruct<T> { var value: T var value2: C } protocol P {} protocol ClassP : class {} protocol GenericCollection : Collection { } /////////// // Tests // /////////// //===----------------------------------------------------------------------===// // Trivial Struct //===----------------------------------------------------------------------===// // CHECK-LABEL: sil hidden [ossa] @$s7foreach13trivialStructyySaySiGF : $@convention(thin) (@guaranteed Array<Int>) -> () { // CHECK: bb0([[ARRAY:%.*]] : @guaranteed $Array<Int>): // CHECK: [[ITERATOR_BOX:%.*]] = alloc_box ${ var IndexingIterator<Array<Int>> }, var, name "$x$generator" // CHECK: [[PROJECT_ITERATOR_BOX:%.*]] = project_box [[ITERATOR_BOX]] // CHECK: br [[LOOP_DEST:bb[0-9]+]] // // CHECK: [[LOOP_DEST]]: // CHECK: switch_enum [[IND_VAR:%.*]] : $Optional<Int>, case #Optional.some!enumelt: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[SOME_BB]]([[VAR:%.*]] : $Int): // CHECK: [[LOOP_END_FUNC:%.*]] = function_ref @loopBodyEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_END_FUNC]]() // CHECK: br [[LOOP_DEST]] // // CHECK: [[NONE_BB]]: // CHECK: destroy_value [[ITERATOR_BOX]] // CHECK: [[FUNC_END_FUNC:%.*]] = function_ref @funcEnd : $@convention(thin) () -> () // CHECK: apply [[FUNC_END_FUNC]]() // CHECK: } // end sil function '$s7foreach13trivialStructyySaySiGF' func trivialStruct(_ xx: [Int]) { for x in xx { loopBodyEnd() } funcEnd() } // TODO: Write this test func trivialStructContinue(_ xx: [Int]) { for x in xx { if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } // TODO: Write this test func trivialStructBreak(_ xx: [Int]) { for x in xx { if (condition()) { loopBreakEnd() break } loopBodyEnd() } funcEnd() } // CHECK-LABEL: sil hidden [ossa] @$s7foreach26trivialStructContinueBreakyySaySiGF : $@convention(thin) (@guaranteed Array<Int>) -> () { // CHECK: bb0([[ARRAY:%.*]] : @guaranteed $Array<Int>): // CHECK: [[ITERATOR_BOX:%.*]] = alloc_box ${ var IndexingIterator<Array<Int>> }, var, name "$x$generator" // CHECK: [[PROJECT_ITERATOR_BOX:%.*]] = project_box [[ITERATOR_BOX]] // CHECK: [[BORROWED_ARRAY_STACK:%.*]] = alloc_stack $Array<Int> // CHECK: store [[ARRAY_COPY:%.*]] to [init] [[BORROWED_ARRAY_STACK]] // CHECK: [[MAKE_ITERATOR_FUNC:%.*]] = witness_method $Array<Int>, #Sequence.makeIterator : <Self where Self : Sequence> (__owned Self) -> () -> Self.Iterator : $@convention(witness_method: Sequence) <τ_0_0 where τ_0_0 : Sequence> (@in τ_0_0) -> @out τ_0_0.Iterator // CHECK: apply [[MAKE_ITERATOR_FUNC]]<[Int]>([[PROJECT_ITERATOR_BOX]], [[BORROWED_ARRAY_STACK]]) // CHECK: br [[LOOP_DEST:bb[0-9]+]] // // CHECK: [[LOOP_DEST]]: // CHECK: [[GET_ELT_STACK:%.*]] = alloc_stack $Optional<Int> // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PROJECT_ITERATOR_BOX]] : $*IndexingIterator<Array<Int>> // CHECK: [[FUNC_REF:%.*]] = witness_method $IndexingIterator<Array<Int>>, #IteratorProtocol.next : <Self where Self : IteratorProtocol> (inout Self) -> () -> Self.Element? : $@convention(witness_method: IteratorProtocol) <τ_0_0 where τ_0_0 : IteratorProtocol> (@inout τ_0_0) -> @out Optional<τ_0_0.Element> // CHECK: apply [[FUNC_REF]]<IndexingIterator<Array<Int>>>([[GET_ELT_STACK]], [[WRITE]]) // CHECK: [[IND_VAR:%.*]] = load [trivial] [[GET_ELT_STACK]] // CHECK: switch_enum [[IND_VAR]] : $Optional<Int>, case #Optional.some!enumelt: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[SOME_BB]]([[VAR:%.*]] : $Int): // CHECK: cond_br {{%.*}}, [[LOOP_BREAK_END_BLOCK:bb[0-9]+]], [[CONTINUE_CHECK_BLOCK:bb[0-9]+]] // // CHECK: [[LOOP_BREAK_END_BLOCK]]: // CHECK: [[LOOP_BREAK_FUNC:%.*]] = function_ref @loopBreakEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_BREAK_FUNC]]() // CHECK: br [[CONT_BLOCK:bb[0-9]+]] // // CHECK: [[CONTINUE_CHECK_BLOCK]]: // CHECK: cond_br {{%.*}}, [[LOOP_CONTINUE_END:bb[0-9]+]], [[LOOP_END_BLOCK:bb[0-9]+]] // // CHECK: [[LOOP_CONTINUE_END]]: // CHECK: [[LOOP_CONTINUE_FUNC:%.*]] = function_ref @loopContinueEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_CONTINUE_FUNC]]() : $@convention(thin) () -> () // CHECK: br [[LOOP_DEST]] // // CHECK: [[LOOP_END_BLOCK]]: // CHECK: [[LOOP_BODY_FUNC:%.*]] = function_ref @loopBodyEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_BODY_FUNC]]() // CHECK: br [[LOOP_DEST]] // // CHECK: [[NONE_BB]]: // CHECK: br [[CONT_BLOCK]] // // CHECK: [[CONT_BLOCK]] // CHECK: destroy_value [[ITERATOR_BOX]] : ${ var IndexingIterator<Array<Int>> } // CHECK: [[FUNC_END_FUNC:%.*]] = function_ref @funcEnd : $@convention(thin) () -> () // CHECK: apply [[FUNC_END_FUNC]]() // CHECK: } // end sil function '$s7foreach26trivialStructContinueBreakyySaySiGF' func trivialStructContinueBreak(_ xx: [Int]) { for x in xx { if (condition()) { loopBreakEnd() break } if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } //===----------------------------------------------------------------------===// // Existential //===----------------------------------------------------------------------===// func existential(_ xx: [P]) { for x in xx { loopBodyEnd() } funcEnd() } func existentialContinue(_ xx: [P]) { for x in xx { if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } func existentialBreak(_ xx: [P]) { for x in xx { if (condition()) { loopBreakEnd() break } loopBodyEnd() } funcEnd() } // CHECK-LABEL: sil hidden [ossa] @$s7foreach24existentialContinueBreakyySayAA1P_pGF : $@convention(thin) (@guaranteed Array<P>) -> () { // CHECK: bb0([[ARRAY:%.*]] : @guaranteed $Array<P>): // CHECK: [[ITERATOR_BOX:%.*]] = alloc_box ${ var IndexingIterator<Array<P>> }, var, name "$x$generator" // CHECK: [[PROJECT_ITERATOR_BOX:%.*]] = project_box [[ITERATOR_BOX]] // CHECK: [[BORROWED_ARRAY_STACK:%.*]] = alloc_stack $Array<P> // CHECK: store [[ARRAY_COPY:%.*]] to [init] [[BORROWED_ARRAY_STACK]] // CHECK: [[MAKE_ITERATOR_FUNC:%.*]] = witness_method $Array<P>, #Sequence.makeIterator : <Self where Self : Sequence> (__owned Self) -> () -> Self.Iterator : $@convention(witness_method: Sequence) <τ_0_0 where τ_0_0 : Sequence> (@in τ_0_0) -> @out τ_0_0.Iterator // CHECK: apply [[MAKE_ITERATOR_FUNC]]<[P]>([[PROJECT_ITERATOR_BOX]], [[BORROWED_ARRAY_STACK]]) // CHECK: [[ELT_STACK:%.*]] = alloc_stack $Optional<P> // CHECK: br [[LOOP_DEST:bb[0-9]+]] // // CHECK: [[LOOP_DEST]]: // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PROJECT_ITERATOR_BOX]] : $*IndexingIterator<Array<P>> // CHECK: [[FUNC_REF:%.*]] = witness_method $IndexingIterator<Array<P>>, #IteratorProtocol.next : <Self where Self : IteratorProtocol> (inout Self) -> () -> Self.Element? : $@convention(witness_method: IteratorProtocol) <τ_0_0 where τ_0_0 : IteratorProtocol> (@inout τ_0_0) -> @out Optional<τ_0_0.Element> // CHECK: apply [[FUNC_REF]]<IndexingIterator<Array<P>>>([[ELT_STACK]], [[WRITE]]) // CHECK: switch_enum_addr [[ELT_STACK]] : $*Optional<P>, case #Optional.some!enumelt: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[SOME_BB]]: // CHECK: [[T0:%.*]] = alloc_stack $P, let, name "x" // CHECK: [[ELT_STACK_TAKE:%.*]] = unchecked_take_enum_data_addr [[ELT_STACK]] : $*Optional<P>, #Optional.some!enumelt // CHECK: copy_addr [take] [[ELT_STACK_TAKE]] to [initialization] [[T0]] // CHECK: cond_br {{%.*}}, [[LOOP_BREAK_END_BLOCK:bb[0-9]+]], [[CONTINUE_CHECK_BLOCK:bb[0-9]+]] // // CHECK: [[LOOP_BREAK_END_BLOCK]]: // CHECK: [[LOOP_BREAK_FUNC:%.*]] = function_ref @loopBreakEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_BREAK_FUNC]]() // CHECK: destroy_addr [[T0]] // CHECK: dealloc_stack [[T0]] // CHECK: br [[CONT_BLOCK:bb[0-9]+]] // // CHECK: [[CONTINUE_CHECK_BLOCK]]: // CHECK: cond_br {{%.*}}, [[LOOP_CONTINUE_END:bb[0-9]+]], [[LOOP_END_BLOCK:bb[0-9]+]] // // CHECK: [[LOOP_CONTINUE_END]]: // CHECK: [[LOOP_CONTINUE_FUNC:%.*]] = function_ref @loopContinueEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_CONTINUE_FUNC]]() : $@convention(thin) () -> () // CHECK: destroy_addr [[T0]] // CHECK: dealloc_stack [[T0]] // CHECK: br [[LOOP_DEST]] // // CHECK: [[LOOP_END_BLOCK]]: // CHECK: [[LOOP_BODY_FUNC:%.*]] = function_ref @loopBodyEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_BODY_FUNC]]() // CHECK: destroy_addr [[T0]] // CHECK: dealloc_stack [[T0]] // CHECK: br [[LOOP_DEST]] // // CHECK: [[NONE_BB]]: // CHECK: br [[CONT_BLOCK]] // // CHECK: [[CONT_BLOCK]] // CHECK: dealloc_stack [[ELT_STACK]] // CHECK: destroy_value [[ITERATOR_BOX]] : ${ var IndexingIterator<Array<P>> } // CHECK: [[FUNC_END_FUNC:%.*]] = function_ref @funcEnd : $@convention(thin) () -> () // CHECK: apply [[FUNC_END_FUNC]]() // CHECK: } // end sil function '$s7foreach24existentialContinueBreakyySayAA1P_pGF' func existentialContinueBreak(_ xx: [P]) { for x in xx { if (condition()) { loopBreakEnd() break } if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } //===----------------------------------------------------------------------===// // Class Constrainted Existential //===----------------------------------------------------------------------===// func existentialClass(_ xx: [ClassP]) { for x in xx { loopBodyEnd() } funcEnd() } func existentialClassContinue(_ xx: [ClassP]) { for x in xx { if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } func existentialClassBreak(_ xx: [ClassP]) { for x in xx { if (condition()) { loopBreakEnd() break } loopBodyEnd() } funcEnd() } func existentialClassContinueBreak(_ xx: [ClassP]) { for x in xx { if (condition()) { loopBreakEnd() break } if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } //===----------------------------------------------------------------------===// // Generic Struct //===----------------------------------------------------------------------===// func genericStruct<T>(_ xx: [GenericStruct<T>]) { for x in xx { loopBodyEnd() } funcEnd() } func genericStructContinue<T>(_ xx: [GenericStruct<T>]) { for x in xx { if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } func genericStructBreak<T>(_ xx: [GenericStruct<T>]) { for x in xx { if (condition()) { loopBreakEnd() break } loopBodyEnd() } funcEnd() } // CHECK-LABEL: sil hidden [ossa] @$s7foreach26genericStructContinueBreakyySayAA07GenericC0VyxGGlF : $@convention(thin) <T> (@guaranteed Array<GenericStruct<T>>) -> () { // CHECK: bb0([[ARRAY:%.*]] : @guaranteed $Array<GenericStruct<T>>): // CHECK: [[ITERATOR_BOX:%.*]] = alloc_box $<τ_0_0> { var IndexingIterator<Array<GenericStruct<τ_0_0>>> } <T>, var, name "$x$generator" // CHECK: [[PROJECT_ITERATOR_BOX:%.*]] = project_box [[ITERATOR_BOX]] // CHECK: [[BORROWED_ARRAY_STACK:%.*]] = alloc_stack $Array<GenericStruct<T>> // CHECK: store [[ARRAY_COPY:%.*]] to [init] [[BORROWED_ARRAY_STACK]] // CHECK: [[MAKE_ITERATOR_FUNC:%.*]] = witness_method $Array<GenericStruct<T>>, #Sequence.makeIterator : <Self where Self : Sequence> (__owned Self) -> () -> Self.Iterator : $@convention(witness_method: Sequence) <τ_0_0 where τ_0_0 : Sequence> (@in τ_0_0) -> @out τ_0_0.Iterator // CHECK: apply [[MAKE_ITERATOR_FUNC]]<[GenericStruct<T>]>([[PROJECT_ITERATOR_BOX]], [[BORROWED_ARRAY_STACK]]) // CHECK: [[ELT_STACK:%.*]] = alloc_stack $Optional<GenericStruct<T>> // CHECK: br [[LOOP_DEST:bb[0-9]+]] // // CHECK: [[LOOP_DEST]]: // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PROJECT_ITERATOR_BOX]] : $*IndexingIterator<Array<GenericStruct<T>>> // CHECK: [[FUNC_REF:%.*]] = witness_method $IndexingIterator<Array<GenericStruct<T>>>, #IteratorProtocol.next : <Self where Self : IteratorProtocol> (inout Self) -> () -> Self.Element? : $@convention(witness_method: IteratorProtocol) <τ_0_0 where τ_0_0 : IteratorProtocol> (@inout τ_0_0) -> @out Optional<τ_0_0.Element> // CHECK: apply [[FUNC_REF]]<IndexingIterator<Array<GenericStruct<T>>>>([[ELT_STACK]], [[WRITE]]) // CHECK: switch_enum_addr [[ELT_STACK]] : $*Optional<GenericStruct<T>>, case #Optional.some!enumelt: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[SOME_BB]]: // CHECK: [[T0:%.*]] = alloc_stack $GenericStruct<T>, let, name "x" // CHECK: [[ELT_STACK_TAKE:%.*]] = unchecked_take_enum_data_addr [[ELT_STACK]] : $*Optional<GenericStruct<T>>, #Optional.some!enumelt // CHECK: copy_addr [take] [[ELT_STACK_TAKE]] to [initialization] [[T0]] // CHECK: cond_br {{%.*}}, [[LOOP_BREAK_END_BLOCK:bb[0-9]+]], [[CONTINUE_CHECK_BLOCK:bb[0-9]+]] // // CHECK: [[LOOP_BREAK_END_BLOCK]]: // CHECK: [[LOOP_BREAK_FUNC:%.*]] = function_ref @loopBreakEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_BREAK_FUNC]]() // CHECK: destroy_addr [[T0]] // CHECK: dealloc_stack [[T0]] // CHECK: br [[CONT_BLOCK:bb[0-9]+]] // // CHECK: [[CONTINUE_CHECK_BLOCK]]: // CHECK: cond_br {{%.*}}, [[LOOP_CONTINUE_END:bb[0-9]+]], [[LOOP_END_BLOCK:bb[0-9]+]] // // CHECK: [[LOOP_CONTINUE_END]]: // CHECK: [[LOOP_CONTINUE_FUNC:%.*]] = function_ref @loopContinueEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_CONTINUE_FUNC]]() : $@convention(thin) () -> () // CHECK: destroy_addr [[T0]] // CHECK: dealloc_stack [[T0]] // CHECK: br [[LOOP_DEST]] // // CHECK: [[LOOP_END_BLOCK]]: // CHECK: [[LOOP_BODY_FUNC:%.*]] = function_ref @loopBodyEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_BODY_FUNC]]() // CHECK: destroy_addr [[T0]] // CHECK: dealloc_stack [[T0]] // CHECK: br [[LOOP_DEST]] // // CHECK: [[NONE_BB]]: // CHECK: br [[CONT_BLOCK]] // // CHECK: [[CONT_BLOCK]] // CHECK: dealloc_stack [[ELT_STACK]] // CHECK: destroy_value [[ITERATOR_BOX]] // CHECK: [[FUNC_END_FUNC:%.*]] = function_ref @funcEnd : $@convention(thin) () -> () // CHECK: apply [[FUNC_END_FUNC]]() // CHECK: } // end sil function '$s7foreach26genericStructContinueBreakyySayAA07GenericC0VyxGGlF' func genericStructContinueBreak<T>(_ xx: [GenericStruct<T>]) { for x in xx { if (condition()) { loopBreakEnd() break } if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } //===----------------------------------------------------------------------===// // Fully Generic Collection //===----------------------------------------------------------------------===// func genericCollection<T : Collection>(_ xx: T) { for x in xx { loopBodyEnd() } funcEnd() } func genericCollectionContinue<T : Collection>(_ xx: T) { for x in xx { if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } func genericCollectionBreak<T : Collection>(_ xx: T) { for x in xx { if (condition()) { loopBreakEnd() break } loopBodyEnd() } funcEnd() } // CHECK-LABEL: sil hidden [ossa] @$s7foreach30genericCollectionContinueBreakyyxSlRzlF : $@convention(thin) <T where T : Collection> (@in_guaranteed T) -> () { // CHECK: bb0([[COLLECTION:%.*]] : $*T): // CHECK: [[ITERATOR_BOX:%.*]] = alloc_box $<τ_0_0 where τ_0_0 : Collection> { var τ_0_0.Iterator } <T>, var, name "$x$generator" // CHECK: [[PROJECT_ITERATOR_BOX:%.*]] = project_box [[ITERATOR_BOX]] // CHECK: [[MAKE_ITERATOR_FUNC:%.*]] = witness_method $T, #Sequence.makeIterator : // CHECK: apply [[MAKE_ITERATOR_FUNC]]<T>([[PROJECT_ITERATOR_BOX]], [[COLLECTION_COPY:%.*]]) // CHECK: [[ELT_STACK:%.*]] = alloc_stack $Optional<T.Element> // CHECK: br [[LOOP_DEST:bb[0-9]+]] // // CHECK: [[LOOP_DEST]]: // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PROJECT_ITERATOR_BOX]] : $*T.Iterator // CHECK: [[GET_NEXT_FUNC:%.*]] = witness_method $T.Iterator, #IteratorProtocol.next : <Self where Self : IteratorProtocol> (inout Self) -> () -> Self.Element? : $@convention(witness_method: IteratorProtocol) <τ_0_0 where τ_0_0 : IteratorProtocol> (@inout τ_0_0) -> @out Optional<τ_0_0.Element> // CHECK: apply [[GET_NEXT_FUNC]]<T.Iterator>([[ELT_STACK]], [[WRITE]]) // CHECK: switch_enum_addr [[ELT_STACK]] : $*Optional<T.Element>, case #Optional.some!enumelt: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[SOME_BB]]: // CHECK: [[T0:%.*]] = alloc_stack $T.Element, let, name "x" // CHECK: [[ELT_STACK_TAKE:%.*]] = unchecked_take_enum_data_addr [[ELT_STACK]] : $*Optional<T.Element>, #Optional.some!enumelt // CHECK: copy_addr [take] [[ELT_STACK_TAKE]] to [initialization] [[T0]] // CHECK: cond_br {{%.*}}, [[LOOP_BREAK_END_BLOCK:bb[0-9]+]], [[CONTINUE_CHECK_BLOCK:bb[0-9]+]] // // CHECK: [[LOOP_BREAK_END_BLOCK]]: // CHECK: [[LOOP_BREAK_FUNC:%.*]] = function_ref @loopBreakEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_BREAK_FUNC]]() // CHECK: destroy_addr [[T0]] // CHECK: dealloc_stack [[T0]] // CHECK: br [[CONT_BLOCK:bb[0-9]+]] // // CHECK: [[CONTINUE_CHECK_BLOCK]]: // CHECK: cond_br {{%.*}}, [[LOOP_CONTINUE_END:bb[0-9]+]], [[LOOP_END_BLOCK:bb[0-9]+]] // // CHECK: [[LOOP_CONTINUE_END]]: // CHECK: [[LOOP_CONTINUE_FUNC:%.*]] = function_ref @loopContinueEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_CONTINUE_FUNC]]() : $@convention(thin) () -> () // CHECK: destroy_addr [[T0]] // CHECK: dealloc_stack [[T0]] // CHECK: br [[LOOP_DEST]] // // CHECK: [[LOOP_END_BLOCK]]: // CHECK: [[LOOP_BODY_FUNC:%.*]] = function_ref @loopBodyEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_BODY_FUNC]]() // CHECK: destroy_addr [[T0]] // CHECK: dealloc_stack [[T0]] // CHECK: br [[LOOP_DEST]] // // CHECK: [[NONE_BB]]: // CHECK: br [[CONT_BLOCK]] // // CHECK: [[CONT_BLOCK]] // CHECK: dealloc_stack [[ELT_STACK]] // CHECK: destroy_value [[ITERATOR_BOX]] // CHECK: [[FUNC_END_FUNC:%.*]] = function_ref @funcEnd : $@convention(thin) () -> () // CHECK: apply [[FUNC_END_FUNC]]() // CHECK: } // end sil function '$s7foreach30genericCollectionContinueBreakyyxSlRzlF' func genericCollectionContinueBreak<T : Collection>(_ xx: T) { for x in xx { if (condition()) { loopBreakEnd() break } if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } //===----------------------------------------------------------------------===// // Pattern Match Tests //===----------------------------------------------------------------------===// // CHECK-LABEL: sil hidden [ossa] @$s7foreach13tupleElementsyySayAA1CC_ADtGF func tupleElements(_ xx: [(C, C)]) { // CHECK: bb{{.*}}([[PAYLOAD:%.*]] : @owned $(C, C)): // CHECK: ([[A:%.*]], [[B:%.*]]) = destructure_tuple [[PAYLOAD]] // CHECK: destroy_value [[B]] // CHECK: destroy_value [[A]] for (a, b) in xx {} // CHECK: bb{{.*}}([[PAYLOAD:%.*]] : @owned $(C, C)): // CHECK: ([[A:%.*]], [[B:%.*]]) = destructure_tuple [[PAYLOAD]] // CHECK: destroy_value [[B]] // CHECK: destroy_value [[A]] for (a, _) in xx {} // CHECK: bb{{.*}}([[PAYLOAD:%.*]] : @owned $(C, C)): // CHECK: ([[A:%.*]], [[B:%.*]]) = destructure_tuple [[PAYLOAD]] // CHECK: destroy_value [[A]] // CHECK: destroy_value [[B]] for (_, b) in xx {} // CHECK: bb{{.*}}([[PAYLOAD:%.*]] : @owned $(C, C)): // CHECK: ([[A:%.*]], [[B:%.*]]) = destructure_tuple [[PAYLOAD]] // CHECK: destroy_value [[B]] // CHECK: destroy_value [[A]] for (_, _) in xx {} // CHECK: bb{{.*}}([[PAYLOAD:%.*]] : @owned $(C, C)): // CHECK: ([[A:%.*]], [[B:%.*]]) = destructure_tuple [[PAYLOAD]] // CHECK: destroy_value [[B]] // CHECK: destroy_value [[A]] for _ in xx {} } // Make sure that when we have an unused value, we properly iterate over the // loop rather than run through the loop once. // // CHECK-LABEL: sil hidden [ossa] @$s7foreach16unusedArgPatternyySaySiGF : $@convention(thin) (@guaranteed Array<Int>) -> () { // CHECK: bb0([[ARG:%.*]] : @guaranteed $Array<Int>): // CHECK: br [[LOOP_DEST:bb[0-9]+]] // // CHECK: [[LOOP_DEST]]: // CHECK: switch_enum [[OPT_VAL:%.*]] : $Optional<Int>, case #Optional.some!enumelt: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[SOME_BB]]([[VAL:%.*]] : $Int): // CHECK: [[LOOP_END_FUNC:%.*]] = function_ref @loopBodyEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_END_FUNC]] func unusedArgPattern(_ xx: [Int]) { for _ in xx { loopBodyEnd() } } // Test for SR-11269. Make sure that the sil contains the needed upcast. // // CHECK-LABEL: sil hidden [ossa] @$s7foreach25genericFuncWithConversion4listySayxG_tAA1CCRbzlF // CHECK: bb2([[ITER_VAL:%.*]] : @owned $T): // CHECK: [[ITER_VAL_UPCAST:%.*]] = upcast [[ITER_VAL]] : $T to $C func genericFuncWithConversion<T: C>(list : [T]) { for item: C in list { print(item) } } // SR-8688: Check that branch on result of next() precedes optional injection. // If we branch on the converted result of next(), the loop won't terminate. // // CHECK-LABEL: sil hidden [ossa] @$s7foreach32injectForEachElementIntoOptionalyySaySiGF // CHECK: [[NEXT_RESULT:%.*]] = load [trivial] {{.*}} : $*Optional<Int> // CHECK: switch_enum [[NEXT_RESULT]] : $Optional<Int>, case #Optional.some!enumelt: [[BB_SOME:bb.*]], case // CHECK: [[BB_SOME]]([[X_PRE_BINDING:%.*]] : $Int): // CHECK: [[X_BINDING:%.*]] = enum $Optional<Int>, #Optional.some!enumelt, [[X_PRE_BINDING]] : $Int // CHECK: debug_value [[X_BINDING]] : $Optional<Int>, let, name "x" func injectForEachElementIntoOptional(_ xs: [Int]) { for x : Int? in xs {} } // SR-8688: Check that branch on result of next() precedes optional injection. // If we branch on the converted result of next(), the loop won't terminate. // // CHECK-LABEL: sil hidden [ossa] @$s7foreach32injectForEachElementIntoOptionalyySayxGlF // CHECK: copy_addr [take] [[NEXT_RESULT:%.*]] to [initialization] [[NEXT_RESULT_COPY:%.*]] : $*Optional<T> // CHECK: switch_enum_addr [[NEXT_RESULT_COPY]] : $*Optional<T>, case #Optional.some!enumelt: [[BB_SOME:bb.*]], case // CHECK: [[BB_SOME]]: // CHECK: [[X_BINDING:%.*]] = alloc_stack $Optional<T>, let, name "x" // CHECK: [[ADDR:%.*]] = unchecked_take_enum_data_addr [[NEXT_RESULT_COPY]] : $*Optional<T>, #Optional.some!enumelt // CHECK: [[X_ADDR:%.*]] = init_enum_data_addr [[X_BINDING]] : $*Optional<T>, #Optional.some!enumelt // CHECK: copy_addr [take] [[ADDR]] to [initialization] [[X_ADDR]] : $*T // CHECK: inject_enum_addr [[X_BINDING]] : $*Optional<T>, #Optional.some!enumelt func injectForEachElementIntoOptional<T>(_ xs: [T]) { for x : T? in xs {} }
apache-2.0
7d82cf31399612b4fcbe4a864755ecbe
36.070978
322
0.573033
3.339443
false
false
false
false
easyui/EZPlayer
EZPlayerExample/EZPlayerExample/ParamsEmbedTableViewController.swift
1
9539
// // ParamsEmbedTableViewController.swift // EZPlayerExample // // Created by yangjun zhu on 2016/12/28. // Copyright © 2016年 yangjun zhu. All rights reserved. // import UIKit import EZPlayer import AVFoundation class ParamsEmbedTableViewController: UITableViewController { weak var paramsViewController: ParamsViewController! override func viewDidLoad() { super.viewDidLoad() let volume = AVAudioSession.sharedInstance().outputVolume//其他会获取不到,比如:EZPlayerUtils.systemVolumeSlider.value volumeLabel.text = String(format:"%.2f", volume) volumeSilder.value = volume NotificationCenter.default.addObserver(self, selector: #selector(ParamsEmbedTableViewController.volumeChange(_:)) , name:Notification.Name(rawValue: "AVSystemController_SystemVolumeDidChangeNotification") , object: nil) // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } deinit { NotificationCenter.default.removeObserver(self) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - url @IBOutlet weak var urlTextField: UITextField! @IBAction func playButtonTap(_ sender: UIButton) { self.view.endEditing(true) if let text = self.urlTextField.text,let url = URL(string: text){ MediaManager.sharedInstance.playEmbeddedVideo(url: url, embeddedContentView: self.paramsViewController.dlView) } } // MARK: - local @IBAction func localMP4ButtonTap(_ sender: UIButton) { MediaManager.sharedInstance.playEmbeddedVideo(url:URL.Test.localMP4_0, embeddedContentView: self.paramsViewController.dlView) } // MARK: - remote @IBAction func remoteT1Tap(_ sender: UIButton) { MediaManager.sharedInstance.playEmbeddedVideo(url: URL.Test.apple_0, embeddedContentView: self.paramsViewController.dlView) } @IBAction func remoteT2Tap(_ sender: UIButton) { MediaManager.sharedInstance.playEmbeddedVideo(url: URL.Test.apple_1, embeddedContentView: self.paramsViewController.dlView) } @IBAction func remoteT3Tap(_ sender: UIButton) { MediaManager.sharedInstance.playEmbeddedVideo(url: URL.Test.remoteMP4_0, embeddedContentView: self.paramsViewController.dlView) } @IBAction func liveTap(_ sender: UIButton) { MediaManager.sharedInstance.playEmbeddedVideo(url: URL.Test.live_0, embeddedContentView: self.paramsViewController.dlView) } // MARK: - rate @IBAction func rateSlowTap(_ sender: UIButton) { MediaManager.sharedInstance.player?.rate = 0.5 } @IBAction func rateNormalTap(_ sender: UIButton) { MediaManager.sharedInstance.player?.rate = 1 } @IBAction func rateFastTap(_ sender: UIButton) { MediaManager.sharedInstance.player?.rate = 1.5 } // MARK: - videoGravity @IBAction func aspectTap(_ sender: UIButton) { MediaManager.sharedInstance.player?.videoGravity = .aspect } @IBAction func aspectFillTap(_ sender: UIButton) { MediaManager.sharedInstance.player?.videoGravity = .aspectFill } @IBAction func scaleFillTap(_ sender: UIButton) { MediaManager.sharedInstance.player?.videoGravity = .scaleFill } // MARK: - displayMode @IBAction func embeddedTap(_ sender: UIButton) { // MediaManager.sharedInstance.hiddenFloatVideo() if MediaManager.sharedInstance.player != nil { MediaManager.sharedInstance.player?.toEmbedded() }else{ MediaManager.sharedInstance.playEmbeddedVideo(url:URL.Test.localMP4_0, embeddedContentView: self.paramsViewController.dlView) } } @IBAction func fullscreenPortraitTap(_ sender: UIButton) { if MediaManager.sharedInstance.player != nil { MediaManager.sharedInstance.player?.fullScreenMode = .portrait MediaManager.sharedInstance.player?.toFull() }else{ MediaManager.sharedInstance.playEmbeddedVideo(url:URL.Test.localMP4_0, embeddedContentView: nil, userinfo: ["fullScreenMode" :EZPlayerFullScreenMode.portrait]) } } @IBAction func fullscreenLandscapeTap(_ sender: UIButton) { if MediaManager.sharedInstance.player != nil { MediaManager.sharedInstance.player?.fullScreenMode = .landscape MediaManager.sharedInstance.player?.toFull() }else{ MediaManager.sharedInstance.playEmbeddedVideo(url:URL.Test.localMP4_0) } } @IBAction func floatTap(_ sender: UIButton) { if MediaManager.sharedInstance.player != nil { MediaManager.sharedInstance.player?.toFloat() }else{ } } // MARK: - skin @IBAction func noneSkinTap(_ sender: UIButton) { if MediaManager.sharedInstance.player != nil { MediaManager.sharedInstance.player?.controlViewForIntercept = UIView() }else{ MediaManager.sharedInstance.playEmbeddedVideo(url:URL.Test.localMP4_0, embeddedContentView: self.paramsViewController.dlView, userinfo: ["skin" : UIView()]) } } @IBAction func yellowSkinTap(_ sender: UIButton) { let yellow = UIView() yellow.backgroundColor = UIColor.yellow.withAlphaComponent(0.3) if MediaManager.sharedInstance.player != nil { MediaManager.sharedInstance.player?.controlViewForIntercept = yellow }else{ let yellow = UIView() yellow.backgroundColor = UIColor.yellow.withAlphaComponent(0.3) MediaManager.sharedInstance.playEmbeddedVideo(url:URL.Test.localMP4_0, embeddedContentView: self.paramsViewController.dlView, userinfo: ["skin" :yellow]) } } @IBAction func defaultSkinTap(_ sender: UIButton) { if MediaManager.sharedInstance.player != nil { MediaManager.sharedInstance.player?.controlViewForIntercept = nil }else{ MediaManager.sharedInstance.playEmbeddedVideo(url:URL.Test.localMP4_0, embeddedContentView: self.paramsViewController.dlView) } } // MARK: - Continued: @IBAction func firstVideoTap(_ sender: UIButton) { if MediaManager.sharedInstance.player != nil { MediaManager.sharedInstance.player?.replaceToPlayWithURL(URL.Test.apple_0) }else{ MediaManager.sharedInstance.playEmbeddedVideo(url:URL.Test.apple_0, embeddedContentView: self.paramsViewController.dlView) } } @IBAction func secondTap(_ sender: UIButton) { if MediaManager.sharedInstance.player != nil { MediaManager.sharedInstance.player?.replaceToPlayWithURL(URL.Test.localMP4_0) }else{ MediaManager.sharedInstance.playEmbeddedVideo(url:URL.Test.localMP4_0, embeddedContentView: self.paramsViewController.dlView) } } // MARK: - autoPlay: @IBAction func autoPlayTap(_ sender: UIButton) { MediaManager.sharedInstance.playEmbeddedVideo(url:URL.Test.localMP4_1, embeddedContentView: self.paramsViewController.dlView) } @IBAction func nonautoPlayTap(_ sender: UIButton) { MediaManager.sharedInstance.playEmbeddedVideo(url:URL.Test.localMP4_2, embeddedContentView: self.paramsViewController.dlView , userinfo: ["autoPlay" :false]) } // MARK: - fairPlay: @IBAction func onlineTap(_ sender: UIButton) { } @IBAction func offlineTap(_ sender: UIButton) { } // MARK: - Volume: @IBOutlet weak var volumeSilder: UISlider! @IBOutlet weak var volumeLabel: UILabel! @IBAction func volumeChanged(_ sender: UISlider) { if let player = MediaManager.sharedInstance.player { player.systemVolume = sender.value volumeLabel.text = String(format:"%.2f", sender.value) } } @objc func volumeChange(_ notification:NSNotification) { if let userInfo = notification.userInfo{ let volume = userInfo["AVSystemController_AudioVolumeNotificationParameter"] as! Float volumeLabel.text = String(format:"%.2f", volume) volumeSilder.value = volume } } // MARK: - snapshot: @IBOutlet weak var snapshotImageView: UIImageView! @IBAction func snapshotWithoutM3u8(_ sender: Any) { if let player = MediaManager.sharedInstance.player { let width = UIScreen.main.scale * 100; player.generateThumbnails(times: [player.currentTime ?? 0], maximumSize: CGSize(width:width,height:width)) { [weak self] items in self?.snapshotImageView.image = items[0].image } } } @IBAction func snapshotWithM3u8(_ sender: Any) { if let player = MediaManager.sharedInstance.player ,let image = player.snapshotImage() { self.snapshotImageView.image = image } } // MARK: - pip: @IBAction func startPIP(_ sender: Any) { if let player = MediaManager.sharedInstance.player { player.startPIP() } } @IBAction func stopPIP(_ sender: Any) { if let player = MediaManager.sharedInstance.player { player.stopPIP() } } }
mit
a407025f94e55960b2c1e1db9506eb5c
33.303249
227
0.678804
4.524762
false
true
false
false
PokemonGoSucks/pgoapi-swift
PGoApi/Classes/Unknown6/subFuncM.swift
1
11014
// // subFuncA.swift // Pods // // Created by PokemonGoSucks on 2016-08-10 // // import Foundation internal class subFuncM { internal func subFuncM(_ input:inout Array<UInt32>, output:inout Array<UInt32>) { var v = Array<UInt32>(repeating: 0, count: 156) v[0] = input[18] v[1] = input[119] v[2] = input[94] v[3] = input[97] let part0 = (((v[2] & v[0]) ^ input[6])) v[4] = ((part0 & input[22]) ^ input[40]) v[5] = (v[3] | input[39]) v[6] = input[14] v[7] = (input[135] ^ input[79]) let part1 = (((input[142] ^ input[64]) | v[0])) v[8] = (part1 ^ input[142]) let part2 = ((input[31] ^ v[8])) let part3 = (((input[140] ^ input[161]) ^ (part2 & v[1]))) input[140] = ~part3 v[9] = input[30] input[64] = v[8] v[10] = input[70] input[135] = (v[7] ^ (v[1] & ~v[4])) v[11] = ((v[5] & v[1]) ^ v[3]) v[12] = ((v[2] & v[6]) ^ v[9]) v[13] = (v[3] & ~input[39]) input[94] = v[12] v[14] = v[10] v[15] = ((v[3] & v[1]) ^ v[13]) v[16] = v[13] v[17] = ((v[3] & v[6]) & ~input[6]) v[18] = input[108] input[31] = (v[2] ^ v[6]) v[19] = (v[18] ^ input[93]) v[20] = input[22] input[70] = v[11] let part4 = (((v[6] & ~v[2]) ^ v[19])) v[21] = (v[20] & ~part4) v[22] = (v[17] ^ v[3]) let part5 = ((v[17] ^ v[3])) v[23] = (((part5 & ~v[0]) ^ v[2]) ^ v[6]) v[24] = (input[32] ^ input[113]) v[25] = (v[5] & ~v[3]) v[26] = (~v[3] & v[1]) v[27] = input[46] v[28] = (v[26] ^ input[101]) let part6 = ((v[5] | ~v[1])) v[29] = (part6 & v[27]) let part7 = ((v[26] ^ input[113])) v[30] = (((v[27] & ~part7) ^ input[170]) | input[104]) v[31] = input[86] v[32] = input[55] v[33] = input[44] input[18] = v[23] v[34] = ((v[32] ^ v[33]) ^ v[23]) v[35] = (v[3] ^ v[1]) let part8 = ((((v[15] & v[27]) ^ input[117]) | input[104])) v[36] = (((part8 ^ (v[27] & ~v[28])) ^ v[31]) ^ v[25]) v[37] = (((v[27] & ~v[28]) ^ v[31]) ^ v[25]) input[86] = (v[31] ^ v[25]) let part9 = ((v[17] ^ input[50])) v[38] = (part9 & ~v[0]) v[39] = (v[1] & ~v[25]) v[40] = (v[24] ^ v[39]) v[41] = (((input[39] & v[1]) & ~v[3]) ^ input[113]) v[42] = (v[41] ^ input[148]) v[43] = ((v[41] ^ input[162]) | input[104]) let part10 = ((v[39] ^ v[3])) v[44] = (part10 & v[27]) v[45] = ((v[39] & v[27]) ^ input[170]) v[46] = input[105] let part11 = (((v[16] & v[1]) ^ input[113])) v[47] = ((part11 & ~v[27]) | input[104]) v[48] = (v[36] & input[62]) input[161] = (v[38] ^ v[12]) let part12 = ((v[3] ^ v[1])) v[49] = (part12 & v[27]) input[44] = (v[11] ^ v[49]) let part13 = ((v[3] ^ v[1])) v[50] = (v[27] & ~part13) v[51] = (v[49] ^ input[39]) v[52] = input[104] input[40] = ((v[46] ^ v[50]) ^ v[47]) v[53] = ~v[52] v[54] = (v[51] ^ (v[45] & ~v[52])) v[55] = (v[48] ^ v[54]) v[56] = (v[50] ^ v[25]) let part14 = (((v[40] & ~v[52]) ^ input[44])) v[57] = ((input[62] & ~part14) ^ input[40]) v[58] = (v[44] ^ input[99]) v[59] = (input[145] ^ input[36]) v[60] = (v[35] ^ input[171]) v[61] = ((v[42] & v[53]) ^ v[60]) let part15 = ((input[161] ^ v[21])) v[62] = (v[1] & ~part15) v[63] = input[104] let part16 = ((v[43] ^ v[14])) v[64] = ((input[62] & ~part16) ^ v[61]) input[145] = v[54] v[65] = (v[58] | v[63]) input[30] = v[55] v[66] = input[9] input[162] = v[64] input[148] = v[61] input[171] = v[60] v[67] = (v[57] ^ v[66]) v[68] = (v[55] ^ input[11]) v[69] = input[195] let part17 = ((v[56] ^ v[30])) v[70] = (((v[59] ^ v[29]) ^ v[65]) ^ (part17 & input[62])) input[55] = (v[34] ^ v[62]) input[36] = v[70] input[99] = v[22] v[71] = input[80] input[9] = ~v[67] v[72] = input[1] v[73] = input[172] input[93] = v[16] input[80] = (v[71] ^ v[64]) input[117] = v[37] input[32] = v[57] v[74] = input[188] input[11] = ~v[68] v[75] = ((v[69] ^ v[74]) ^ (v[73] & v[72])) v[76] = (v[75] & ~input[34]) v[77] = input[96] v[78] = ((input[128] ^ input[25]) ^ (v[75] & ~input[98])) v[79] = input[84] v[80] = (input[149] ^ input[194]) v[81] = v[77] v[82] = (v[75] & ~v[77]) v[83] = input[58] v[84] = (v[82] ^ v[79]) v[85] = (((v[79] ^ v[83]) ^ v[75]) ^ v[81]) let part18 = ((v[75] ^ input[77])) v[86] = (part18 & v[83]) v[87] = ~v[83] v[88] = (v[75] ^ v[81]) v[89] = input[110] input[42] ^= (input[56] ^ (v[75] & input[123])) input[25] = ~v[78] let part19 = ((v[80] ^ v[76])) input[149] = ~part19 v[90] = (v[86] ^ v[89]) let part20 = ((v[82] ^ v[79])) v[91] = (part20 & ~v[83]) input[77] = (v[86] ^ v[89]) v[92] = v[75] let part21 = ((v[79] | v[75])) v[93] = ((part21 ^ v[75]) ^ v[91]) input[108] = v[93] v[94] = (v[75] & ~v[82]) v[95] = (v[85] ^ input[49]) input[172] = (v[82] ^ v[79]) input[1] = v[94] v[96] = (~v[75] & v[81]) v[97] = (v[75] | v[81]) v[98] = input[76] input[104] = ~v[75] input[76] = v[85] v[99] = (v[91] ^ v[98]) v[100] = (v[75] & ~v[79]) let part22 = ((v[79] | v[75])) let part23 = ((v[82] ^ part22)) v[101] = (part23 & ~v[83]) let part24 = ((v[82] ^ v[79])) v[102] = (part24 & ~v[83]) v[103] = input[106] v[104] = v[81] input[49] = v[95] v[105] = v[99] v[106] = (v[101] ^ input[110]) input[106] = (v[103] ^ v[88]) v[107] = input[106] input[194] = (v[92] | v[81]) input[34] = (v[96] ^ v[100]) let part25 = (((v[100] ^ v[81]) | v[83])) v[108] = (part25 ^ v[107]) let part26 = ((v[96] | v[79])) let part27 = ((part26 ^ v[96])) v[109] = ((part27 & ~v[83]) ^ v[97]) v[110] = ((v[104] & v[92]) & ~v[79]) v[111] = (v[101] ^ v[110]) v[112] = v[79] v[113] = v[92] v[114] = ((v[104] & v[92]) ^ v[79]) v[115] = (v[97] & ~v[79]) v[116] = (v[112] | v[94]) v[117] = (v[114] | v[83]) v[118] = ((v[110] ^ v[92]) ^ v[102]) v[119] = (v[116] ^ v[82]) let part28 = ((v[97] | v[83])) v[120] = (v[115] ^ part28) v[121] = (v[117] ^ v[116]) let part29 = ((v[88] | v[83])) v[122] = (((part29 ^ v[88]) ^ v[116]) | input[175]) v[123] = input[34] input[98] = v[120] let part30 = (((v[94] ^ v[115]) | v[83])) input[195] = (part30 ^ v[123]) let part31 = (((v[116] ^ v[96]) | v[83])) v[124] = (part31 ^ v[84]) v[125] = input[175] v[126] = (v[119] & v[87]) v[127] = input[175] input[119] = v[124] v[128] = ~v[125] v[129] = (v[122] ^ v[120]) v[130] = (v[108] & ~v[125]) v[131] = (v[118] ^ (v[111] & ~v[125])) v[132] = (v[96] ^ input[199]) v[133] = (v[109] & v[128]) v[134] = input[103] let part32 = ((v[106] ^ (v[105] & v[128]))) v[135] = (v[134] & ~part32) let part33 = ((v[121] | v[127])) v[136] = (part33 ^ input[195]) v[137] = ((v[134] & ~v[129]) ^ v[95]) let part34 = ((v[130] ^ v[93])) v[138] = ((input[103] & ~part34) ^ v[136]) v[139] = ((v[126] ^ v[132]) | input[175]) v[140] = (input[119] ^ v[133]) v[141] = (v[138] ^ input[7]) v[142] = input[57] v[143] = ((input[103] & ~v[131]) ^ v[140]) input[96] = v[96] v[144] = (v[143] ^ v[142]) v[145] = (v[137] ^ input[21]) input[128] = v[138] v[146] = (v[90] ^ v[139]) v[147] = input[2] v[148] = v[146] input[188] = v[136] v[149] = (v[113] & v[147]) v[150] = input[173] input[79] = v[143] v[151] = v[150] v[152] = input[61] input[84] = v[109] input[173] = ((v[151] ^ v[152]) ^ v[149]) v[153] = (v[148] ^ v[135]) input[123] = v[137] input[57] = ~v[144] v[154] = input[78] input[2] = v[115] v[155] = input[115] input[7] = ~v[141] input[175] = v[140] input[21] = ~v[145] input[110] = v[153] input[62] = v[148] input[199] = v[132] input[115] = (v[155] ^ v[153]) output[0] = v[154] output[1] = input[183] output[2] = input[3] output[3] = input[176] output[4] = input[197] output[5] = input[184] output[6] = input[7] output[7] = input[6] output[8] = input[9] output[9] = input[8] output[10] = input[11] output[11] = input[66] output[12] = input[13] output[13] = input[12] output[14] = input[178] output[15] = input[14] output[16] = input[17] output[17] = input[134] output[18] = input[87] output[19] = input[5] output[20] = input[21] output[21] = input[20] output[22] = input[23] output[23] = input[22] output[24] = input[25] output[25] = input[19] output[26] = input[112] output[27] = input[104] output[28] = input[135] output[29] = input[28] output[30] = input[154] output[31] = input[97] output[32] = input[33] output[33] = input[120] output[34] = input[54] output[35] = input[139] output[36] = input[37] output[37] = input[192] output[38] = input[42] output[39] = input[130] output[40] = input[41] output[41] = input[136] output[42] = input[149] output[43] = input[103] output[44] = input[173] output[45] = input[191] output[46] = input[115] output[47] = input[46] output[48] = input[196] output[49] = input[71] output[50] = input[140] output[51] = input[68] output[52] = input[53] output[53] = input[122] output[54] = input[55] output[55] = input[109] output[56] = input[57] output[57] = input[111] output[58] = input[36] output[59] = input[144] output[60] = input[80] output[61] = input[121] output[62] = input[63] output[63] = input[47] } }
mit
837fabde44c71bd46943e55d656f7916
32.477204
85
0.396859
2.490165
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/MarketplaceCatalog/MarketplaceCatalog_Paginator.swift
1
6344
//===----------------------------------------------------------------------===// // // 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 SotoCore // MARK: Paginators extension MarketplaceCatalog { /// Returns the list of change sets owned by the account being used to make the call. You can filter this list by providing any combination of entityId, ChangeSetName, and status. If you provide more than one filter, the API operation applies a logical AND between the filters. You can describe a change during the 60-day request history retention period for API calls. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listChangeSetsPaginator<Result>( _ input: ListChangeSetsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListChangeSetsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listChangeSets, tokenKey: \ListChangeSetsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listChangeSetsPaginator( _ input: ListChangeSetsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListChangeSetsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listChangeSets, tokenKey: \ListChangeSetsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provides the list of entities of a given type. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listEntitiesPaginator<Result>( _ input: ListEntitiesRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListEntitiesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listEntities, tokenKey: \ListEntitiesResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listEntitiesPaginator( _ input: ListEntitiesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListEntitiesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listEntities, tokenKey: \ListEntitiesResponse.nextToken, on: eventLoop, onPage: onPage ) } } extension MarketplaceCatalog.ListChangeSetsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> MarketplaceCatalog.ListChangeSetsRequest { return .init( catalog: self.catalog, filterList: self.filterList, maxResults: self.maxResults, nextToken: token, sort: self.sort ) } } extension MarketplaceCatalog.ListEntitiesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> MarketplaceCatalog.ListEntitiesRequest { return .init( catalog: self.catalog, entityType: self.entityType, filterList: self.filterList, maxResults: self.maxResults, nextToken: token, sort: self.sort ) } }
apache-2.0
5903bb47bb3897ce388275aed3ef5879
41.864865
374
0.637137
5.01502
false
false
false
false
Ryan-Vanderhoef/Antlers
AppIdea/Frameworks/Bond/Bond/Bond+UITableView.swift
1
9326
// // Bond+UITableView.swift // Bond // // The MIT License (MIT) // // Copyright (c) 2015 Srdan Rasic (@srdanrasic) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit extension NSIndexSet { convenience init(array: [Int]) { let set = NSMutableIndexSet() for index in array { set.addIndex(index) } self.init(indexSet: set) } } @objc class TableViewDynamicArrayDataSource: NSObject, UITableViewDataSource { weak var dynamic: DynamicArray<DynamicArray<UITableViewCell>>? @objc weak var nextDataSource: UITableViewDataSource? init(dynamic: DynamicArray<DynamicArray<UITableViewCell>>) { self.dynamic = dynamic super.init() } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return self.dynamic?.count ?? 0 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.dynamic?[section].count ?? 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { return self.dynamic?[indexPath.section][indexPath.item] ?? UITableViewCell() } // Forwards func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if let ds = self.nextDataSource { return ds.tableView?(tableView, titleForHeaderInSection: section) } else { return nil } } func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? { if let ds = self.nextDataSource { return ds.tableView?(tableView, titleForFooterInSection: section) } else { return nil } } func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { if let ds = self.nextDataSource { return ds.tableView?(tableView, canEditRowAtIndexPath: indexPath) ?? false } else { return false } } func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { if let ds = self.nextDataSource { return ds.tableView?(tableView, canMoveRowAtIndexPath: indexPath) ?? false } else { return false } } func sectionIndexTitlesForTableView(tableView: UITableView) -> [AnyObject]! { if let ds = self.nextDataSource { return ds.sectionIndexTitlesForTableView?(tableView) ?? [] } else { return [] } } func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int { if let ds = self.nextDataSource { return ds.tableView?(tableView, sectionForSectionIndexTitle: title, atIndex: index) ?? index } else { return index } } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if let ds = self.nextDataSource { ds.tableView?(tableView, commitEditingStyle: editingStyle, forRowAtIndexPath: indexPath) } } func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) { if let ds = self.nextDataSource { ds.tableView?(tableView, moveRowAtIndexPath: sourceIndexPath, toIndexPath: destinationIndexPath) } } } private class UITableViewDataSourceSectionBond<T>: ArrayBond<UITableViewCell> { weak var tableView: UITableView? var section: Int init(tableView: UITableView?, section: Int) { self.tableView = tableView self.section = section super.init() self.didInsertListener = { [unowned self] a, i in if let tableView: UITableView = self.tableView { tableView.beginUpdates() tableView.insertRowsAtIndexPaths(i.map { NSIndexPath(forItem: $0, inSection: self.section) }, withRowAnimation: UITableViewRowAnimation.Automatic) tableView.endUpdates() } } self.didRemoveListener = { [unowned self] a, i in if let tableView = self.tableView { tableView.beginUpdates() tableView.deleteRowsAtIndexPaths(i.map { NSIndexPath(forItem: $0, inSection: self.section) }, withRowAnimation: UITableViewRowAnimation.Automatic) tableView.endUpdates() } } self.didUpdateListener = { [unowned self] a, i in if let tableView = self.tableView { tableView.beginUpdates() tableView.reloadRowsAtIndexPaths(i.map { NSIndexPath(forItem: $0, inSection: self.section) }, withRowAnimation: UITableViewRowAnimation.Automatic) tableView.endUpdates() } } } deinit { self.unbindAll() } } public class UITableViewDataSourceBond<T>: ArrayBond<DynamicArray<UITableViewCell>> { weak var tableView: UITableView? private var dataSource: TableViewDynamicArrayDataSource? private var sectionBonds: [UITableViewDataSourceSectionBond<Void>] = [] public weak var nextDataSource: UITableViewDataSource? { didSet(newValue) { dataSource?.nextDataSource = newValue } } public init(tableView: UITableView) { self.tableView = tableView super.init() self.didInsertListener = { [weak self] array, i in if let s = self { if let tableView: UITableView = self?.tableView { tableView.beginUpdates() tableView.insertSections(NSIndexSet(array: i), withRowAnimation: UITableViewRowAnimation.Automatic) for section in sorted(i, <) { let sectionBond = UITableViewDataSourceSectionBond<Void>(tableView: tableView, section: section) let sectionDynamic = array[section] sectionDynamic.bindTo(sectionBond) s.sectionBonds.insert(sectionBond, atIndex: section) for var idx = section + 1; idx < s.sectionBonds.count; idx++ { s.sectionBonds[idx].section += 1 } } tableView.endUpdates() } } } self.didRemoveListener = { [weak self] array, i in if let s = self { if let tableView = s.tableView { tableView.beginUpdates() tableView.deleteSections(NSIndexSet(array: i), withRowAnimation: UITableViewRowAnimation.Automatic) for section in sorted(i, >) { s.sectionBonds[section].unbindAll() s.sectionBonds.removeAtIndex(section) for var idx = section; idx < s.sectionBonds.count; idx++ { s.sectionBonds[idx].section -= 1 } } tableView.endUpdates() } } } self.didUpdateListener = { [weak self] array, i in if let tableView = self?.tableView { tableView.beginUpdates() tableView.reloadSections(NSIndexSet(array: i), withRowAnimation: UITableViewRowAnimation.Automatic) for section in i { let sectionBond = UITableViewDataSourceSectionBond<Void>(tableView: tableView, section: section) let sectionDynamic = array[section] sectionDynamic.bindTo(sectionBond) self?.sectionBonds[section].unbindAll() self?.sectionBonds[section] = sectionBond } tableView.endUpdates() } } } public func bind(dynamic: DynamicArray<UITableViewCell>) { bind(DynamicArray([dynamic])) } public override func bind(dynamic: Dynamic<Array<DynamicArray<UITableViewCell>>>, fire: Bool, strongly: Bool) { super.bind(dynamic, fire: false, strongly: strongly) if let dynamic = dynamic as? DynamicArray<DynamicArray<UITableViewCell>> { for section in 0..<dynamic.count { let sectionBond = UITableViewDataSourceSectionBond<Void>(tableView: self.tableView, section: section) let sectionDynamic = dynamic[section] sectionDynamic.bindTo(sectionBond) sectionBonds.append(sectionBond) } dataSource = TableViewDynamicArrayDataSource(dynamic: dynamic) dataSource?.nextDataSource = self.nextDataSource tableView?.dataSource = dataSource tableView?.reloadData() } } deinit { self.unbindAll() tableView?.dataSource = nil self.dataSource = nil } } public func ->> <T>(left: DynamicArray<UITableViewCell>, right: UITableViewDataSourceBond<T>) { right.bind(left) }
mit
048faa1b2ce53e64df1910cfd2306697
33.540741
154
0.68057
4.832124
false
false
false
false
apple/swift-syntax
Sources/lit-test-helper/main.swift
1
20941
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftSyntax import SwiftSyntaxParser import Foundation /// Print the given message to stderr func printerr(_ message: String, terminator: String = "\n") { FileHandle.standardError.write((message + terminator).data(using: .utf8)!) } /// Print the help message func printHelp() { print(""" Utility to test SwiftSyntax syntax tree creation. Actions (must specify one): -classify-syntax Parse the given source file (-source-file) and output it with tokens classified for syntax colouring. -parse-incremental Parse a pre-edit source file (-old-source-file) and incrementally parse the post-edit source file (-source-file) that was the result of applying the given edits (-incremental-edit). -roundtrip Parse the given source file (-source-file) and print it out using its syntax tree. -verify-roundtrip Parse the given source file (-source-file) and exit with a non-zero exit code if printing the tree does not result in the original source file. -print-tree Parse the given source file (-source-file) and output its syntax tree. -help Print this help message Arguments: -source-file FILENAME The path to a Swift source file to parse -old-source-file FILENAME Path to the pre-edit source file to translate line:column edits into the file's byte offsets. -incremental-edit EDIT An edit that was applied to reach the input file from the source file that generated the old syntax tree in the format <start-line>: <start-column>-<end-line>:<end-column>=<replacement> where start and end are dfined in terms of the pre-edit file and <replacement> is the string that shall replace the selected range. Can be passed multiple times. -reparse-region REGION If specified, an error will be emitted if any part of the file ouside of the reparse region gets parsed again. Can be passed multiple times to specify multiple reparse regions. Reparse regions are specified in the form <start-column>-<end-line>:<end-column> in terms of the post-edit file. -incremental-reuse-log FILENAME Path to which a log should be written that describes all the nodes reused during incremental parsing. -out FILENAME The file to which the source representation of the post-edit syntax tree shall be written. -swift-version Interpret input according to a specific Swift language version number -enable-bare-slash-regex [0|1] Enable or disable the use of forward slash regular-expression literal syntax """) } extension CommandLineArguments { func getIncrementalEdits() throws -> [IncrementalEdit] { let regex = try NSRegularExpression( pattern: "([0-9]+):([0-9]+)-([0-9]+):([0-9]+)=(.*)") var parsedEdits = [IncrementalEdit]() let editArgs = try self.getValues("-incremental-edit") for edit in editArgs { guard let match = regex.firstMatch(in: edit, range: NSRange(edit.startIndex..., in: edit)) else { throw CommandLineArguments.InvalidArgumentValueError( argName: "-incremental-edit", value: edit ) } let region = getSourceRegion(match, text: edit) let replacement = match.match(at: 5, text: edit) parsedEdits.append(IncrementalEdit( region: region, replacement: replacement )) } return parsedEdits } func getReparseRegions() throws -> [SourceRegion] { let regex = try NSRegularExpression( pattern: "([0-9]+):([0-9]+)-([0-9]+):([0-9]+)") var reparseRegions = [SourceRegion]() let regionArgs = try self.getValues("-reparse-region") for regionStr in regionArgs { guard let match = regex.firstMatch(in: regionStr, range: NSRange(regionStr.startIndex..., in: regionStr)) else { throw CommandLineArguments.InvalidArgumentValueError( argName: "-reparse-region", value: regionStr ) } let region = getSourceRegion(match, text: regionStr) reparseRegions.append(region) } return reparseRegions } private func getSourceRegion(_ match: NSTextCheckingResult, text: String) -> SourceRegion { let matchAsInt = { (i: Int) -> Int in return Int(match.match(at: i, text: text))! } let startLine = matchAsInt(1) let startColumn = matchAsInt(2) let endLine = matchAsInt(3) let endColumn = matchAsInt(4) return SourceRegion( startLine: startLine, startColumn: startColumn, endLine: endLine, endColumn: endColumn ) } } extension NSTextCheckingResult { func match(at: Int, text: String) -> String { let range = self.range(at: at) let text = String(text[Range(range, in: text)!]) return text } } struct ByteSourceRangeSet { var ranges = [ByteSourceRange]() mutating func addRange(_ range: ByteSourceRange) { ranges.append(range) } func inverted(totalLength: Int) -> ByteSourceRangeSet { var result = ByteSourceRangeSet() var currentOffset = 0 for range in ranges { assert(currentOffset <= range.offset, "Ranges must be sorted in ascending order and not be overlapping") if currentOffset < range.offset { result.addRange(ByteSourceRange(offset: currentOffset, length: range.offset-currentOffset)) } currentOffset = range.endOffset } if currentOffset < totalLength { result.addRange(ByteSourceRange(offset: currentOffset, length: totalLength-currentOffset)) } return result } func intersected(_ other: ByteSourceRangeSet) -> ByteSourceRangeSet { var intersection = ByteSourceRangeSet() for A in self.ranges { for B in other.ranges { let partialIntersection = A.intersected(B) if !partialIntersection.isEmpty { intersection.addRange(partialIntersection) } } } return intersection } } struct SourceRegion { let startLine: Int let startColumn: Int let endLine: Int let endColumn: Int } struct IncrementalEdit { let region: SourceRegion let replacement: String } func getSwiftLanguageVersionInfo(args: CommandLineArguments) -> (languageVersion: String?, enableBareSlashRegexLiteral: Bool?) { return ( args["-swift-version"], args["-enable-bare-slash-regex"].map({ $0 == "1" }) ) } /// Rewrites a parsed tree with all constructed nodes. class TreeReconstructor : SyntaxRewriter { override func visit(_ token: TokenSyntax) -> TokenSyntax { let token = TokenSyntax( token.tokenKind, leadingTrivia: token.leadingTrivia, trailingTrivia: token.trailingTrivia, presence: token.presence) return token } } func performClassifySyntax(args: CommandLineArguments) throws { let treeURL = URL(fileURLWithPath: try args.getRequired("-source-file")) let versionInfo = getSwiftLanguageVersionInfo(args: args) let tree = try SyntaxParser.parse(treeURL, languageVersion: versionInfo.languageVersion, enableBareSlashRegexLiteral: versionInfo.enableBareSlashRegexLiteral) let result = ClassifiedSyntaxTreePrinter.print(Syntax(tree)) do { // Sanity check that we get the same result if the tree has constructed nodes. let ctorTree = TreeReconstructor().visit(tree) let ctorResult = ClassifiedSyntaxTreePrinter.print(Syntax(ctorTree)) if ctorResult != result { throw TestingError.classificationVerificationFailed(result, ctorResult) } } if let outURL = args["-out"].map(URL.init(fileURLWithPath:)) { try result.write(to: outURL, atomically: false, encoding: .utf8) } else { print(result) } } /// Returns an array of UTF8 bytes offsets for each line. func getLineTable(_ text: String) -> [Int] { return text.withCString { (p: UnsafePointer<Int8>) -> [Int] in var lineOffsets = [Int]() lineOffsets.append(0) var idx = 0 while p[idx] != 0 { if p[idx] == Int8(UnicodeScalar("\n").value) { lineOffsets.append(idx+1) } idx += 1 } return lineOffsets } } func getByteRange(_ region: SourceRegion, lineTable: [Int], argName: String) throws -> ByteSourceRange { if region.startLine-1 >= lineTable.count { throw CommandLineArguments.InvalidArgumentValueError( argName: argName, value: "startLine: \(region.startLine)" ) } if region.endLine-1 >= lineTable.count { throw CommandLineArguments.InvalidArgumentValueError( argName: argName, value: "endLine: \(region.endLine)" ) } let startOffset = lineTable[region.startLine-1] + region.startColumn-1 let endOffset = lineTable[region.endLine-1] + region.endColumn-1 let length = endOffset-startOffset return ByteSourceRange(offset: startOffset, length: length) } func parseIncrementalEditArguments( args: CommandLineArguments ) throws -> [SourceEdit] { var edits = [SourceEdit]() let argEdits = try args.getIncrementalEdits() let preEditURL = URL(fileURLWithPath: try args.getRequired("-old-source-file")) let text = try String(contentsOf: preEditURL) let lineTable = getLineTable(text) for argEdit in argEdits { let range = try getByteRange(argEdit.region, lineTable: lineTable, argName: "-incremental-edit") let replacementLength = argEdit.replacement.utf8.count edits.append(SourceEdit(range: range, replacementLength: replacementLength)) } return edits } func performParseIncremental(args: CommandLineArguments) throws { let preEditURL = URL(fileURLWithPath: try args.getRequired("-old-source-file")) let postEditURL = URL(fileURLWithPath: try args.getRequired("-source-file")) let expectedReparseRegions = try args.getReparseRegions() let versionInfo = getSwiftLanguageVersionInfo(args: args) let preEditTree = try SyntaxParser.parse(preEditURL, languageVersion: versionInfo.languageVersion, enableBareSlashRegexLiteral: versionInfo.enableBareSlashRegexLiteral) let edits = try parseIncrementalEditArguments(args: args) let regionCollector = IncrementalParseReusedNodeCollector() let editTransition = IncrementalParseTransition( previousTree: preEditTree, edits: try ConcurrentEdits(concurrent: edits), reusedNodeDelegate: regionCollector ) let postEditText = try String(contentsOf: postEditURL) let postEditTree = try SyntaxParser.parse(source: postEditText, parseTransition: editTransition) let postTreeDump = postEditTree.description if let outURL = args["-out"].map(URL.init(fileURLWithPath:)) { try postTreeDump.write(to: outURL, atomically: false, encoding: .utf8) } else { print(postTreeDump) } let regions = regionCollector.rangeAndNodes.map { $0.0 } if let reuseLogURL = args["-incremental-reuse-log"].map(URL.init(fileURLWithPath:)) { var log = "" for region in regions { log += "Reused \(region.offset) to \(region.endOffset)\n" } try log.write(to: reuseLogURL, atomically: false, encoding: .utf8) } if !expectedReparseRegions.isEmpty { try verifyReusedRegions(expectedReparseRegions: expectedReparseRegions, reusedRegions: regions, source: postEditText) } } enum TestingError: Error, CustomStringConvertible { case reparsedRegionsVerificationFailed(ByteSourceRange) case classificationVerificationFailed(String, String) case readingSourceFileFailed(URL) case roundTripFailed public var description: String { switch self { case .reparsedRegionsVerificationFailed(let range): return "unexpectedly reparsed following region: (offset: \(range.offset)," + " length:\(range.length))" case .classificationVerificationFailed(let parsed, let constructed): return """ parsed vs constructed tree resulted in different classification output --- PARSED: \(parsed) --- CONSTRUCTED: \(constructed) """ case .readingSourceFileFailed(let url): return "Reading the source file at \(url) failed" case .roundTripFailed: return "Round-tripping the source file failed" } } } func verifyReusedRegions(expectedReparseRegions: [SourceRegion], reusedRegions: [ByteSourceRange], source text: String) throws { let fileLength = text.utf8.count // Compute the repared regions by inverting the reused regions let reusedRanges = ByteSourceRangeSet(ranges: reusedRegions) let reparsedRegions = reusedRanges.inverted(totalLength: fileLength) // Same for expected reuse regions let lineTable = getLineTable(text) var expectedReparseRanges = ByteSourceRangeSet() for region in expectedReparseRegions { let range = try getByteRange(region, lineTable: lineTable, argName: "-reparse-region") expectedReparseRanges.addRange(range) } let expectedReuseRegions = expectedReparseRanges.inverted(totalLength: fileLength) // Intersect the reparsed regions with the expected reuse regions to get // regions that should not have been reparsed let unexpectedReparseRegions = reparsedRegions.intersected(expectedReuseRegions) for reparseRange in unexpectedReparseRegions.ranges { // To improve the ergonomics when writing tests we do not want to complain // about reparsed whitespaces. let utf8 = text.utf8 let begin = utf8.index(utf8.startIndex, offsetBy: reparseRange.offset) let end = utf8.index(begin, offsetBy: reparseRange.length) let rangeStr = String(utf8[begin..<end])! let whitespaceOnlyRegex = try NSRegularExpression(pattern: "^[ \t\r\n]*$") let match = whitespaceOnlyRegex.firstMatch(in: rangeStr, range: NSRange(rangeStr.startIndex..., in: rangeStr)) if match != nil { continue } throw TestingError.reparsedRegionsVerificationFailed(reparseRange) } } func performRoundtrip(args: CommandLineArguments) throws { let sourceURL = URL(fileURLWithPath: try args.getRequired("-source-file")) let versionInfo = getSwiftLanguageVersionInfo(args: args) let tree = try SyntaxParser.parse(sourceURL, languageVersion: versionInfo.languageVersion, enableBareSlashRegexLiteral: versionInfo.enableBareSlashRegexLiteral) let treeText = tree.description if let outURL = args["-out"].map(URL.init(fileURLWithPath:)) { try treeText.write(to: outURL, atomically: false, encoding: .utf8) } else { print(treeText) } } func performVerifyRoundtrip(args: CommandLineArguments) throws { let sourceURL = URL(fileURLWithPath: try args.getRequired("-source-file")) guard let source = try String(data: Data(contentsOf: sourceURL), encoding: .utf8) else { throw TestingError.readingSourceFileFailed(sourceURL) } let versionInfo = getSwiftLanguageVersionInfo(args: args) let tree = try SyntaxParser.parse(source: source, languageVersion: versionInfo.languageVersion, enableBareSlashRegexLiteral: versionInfo.enableBareSlashRegexLiteral) if tree.description != source { throw TestingError.roundTripFailed } } class NodePrinter: SyntaxAnyVisitor { init() { super.init(viewMode: .sourceAccurate) } override func visitAny(_ node: Syntax) -> SyntaxVisitorContinueKind { assert(!node.isUnknown) print("<\(type(of: node.asProtocol(SyntaxProtocol.self)))>", terminator: "") return .visitChildren } override func visitAnyPost(_ node: Syntax) { print("</\(type(of: node.asProtocol(SyntaxProtocol.self)))>", terminator: "") } override func visit(_ token: TokenSyntax) -> SyntaxVisitorContinueKind { print("<\(type(of: token))>", terminator: "") print(token, terminator:"") return .visitChildren } } func printSyntaxTree(args: CommandLineArguments) throws { let treeURL = URL(fileURLWithPath: try args.getRequired("-source-file")) let versionInfo = getSwiftLanguageVersionInfo(args: args) let tree = try SyntaxParser.parse(treeURL, languageVersion: versionInfo.languageVersion, enableBareSlashRegexLiteral: versionInfo.enableBareSlashRegexLiteral) let printer = NodePrinter() printer.walk(tree) } func printParserDiags(args: CommandLineArguments) throws { let treeURL = URL(fileURLWithPath: try args.getRequired("-source-file")) let versionInfo = getSwiftLanguageVersionInfo(args: args) var diagCounter : (error: Int, warning: Int, note: Int) = (0, 0, 0) func handleDiagnostic(diagnostic: Diagnostic) { switch diagnostic.message.severity { case .error: diagCounter.error += 1 diagCounter.note += diagnostic.notes.count case .warning: diagCounter.warning += 1 diagCounter.note += diagnostic.notes.count case .note: diagCounter.note += 1 } print(diagnostic.debugDescription) } _ = try SyntaxParser.parse(treeURL, languageVersion: versionInfo.languageVersion, enableBareSlashRegexLiteral: versionInfo.enableBareSlashRegexLiteral, diagnosticHandler: handleDiagnostic) print("\(diagCounter.error) error(s) \(diagCounter.warning) warnings(s) \(diagCounter.note) note(s)") } /// Write the given string to stderr **without** appending a newline character. func writeToStderr(_ msg: String) { FileHandle.standardError.write(msg.data(using: .utf8)!) } func diagnose(args: CommandLineArguments) throws { func printDiagnostic(diagnostic: Diagnostic) { if let loc = diagnostic.location { writeToStderr("\(loc.file!):\(loc.line!):\(loc.column!): ") } else { writeToStderr("<unknown>:0:0: ") } switch diagnostic.message.severity { case .note: writeToStderr("note: ") case .warning: writeToStderr("warning: ") case .error: writeToStderr("error: ") } writeToStderr(diagnostic.message.text) writeToStderr("\n") for note in diagnostic.notes { printDiagnostic(diagnostic: note.asDiagnostic()) } } let treeURL = URL(fileURLWithPath: try args.getRequired("-source-file")) let versionInfo = getSwiftLanguageVersionInfo(args: args) let tree = try SyntaxParser.parse(treeURL, languageVersion: versionInfo.languageVersion, enableBareSlashRegexLiteral: versionInfo.enableBareSlashRegexLiteral, diagnosticHandler: printDiagnostic) class DiagnoseUnknown: SyntaxAnyVisitor { let diagnosticHandler: ((Diagnostic) -> Void) let converter: SourceLocationConverter init(diagnosticHandler: @escaping ((Diagnostic) -> Void), _ converter: SourceLocationConverter) { self.diagnosticHandler = diagnosticHandler self.converter = converter super.init(viewMode: .all) } override func visitAny(_ node: Syntax) -> SyntaxVisitorContinueKind { if node.isUnknown { diagnosticHandler(Diagnostic( message: Diagnostic.Message(.warning, "unknown syntax exists"), location: node.startLocation(converter: converter, afterLeadingTrivia: true), actions: nil )) } return .visitChildren } } let visitor = DiagnoseUnknown( diagnosticHandler: printDiagnostic, SourceLocationConverter(file: treeURL.path, tree: tree) ) visitor.walk(tree) } do { let args = try CommandLineArguments.parse(CommandLine.arguments.dropFirst()) if args.has("-classify-syntax") { try performClassifySyntax(args: args) } else if args.has("-parse-incremental") { try performParseIncremental(args: args) } else if args.has("-roundtrip") { try performRoundtrip(args: args) } else if args.has("-verify-roundtrip") { try performVerifyRoundtrip(args: args) } else if args.has("-print-tree") { try printSyntaxTree(args: args) } else if args.has("-dump-diags") { try printParserDiags(args: args) } else if args.has("-diagnose") { try diagnose(args: args) } else if args.has("-help") { printHelp() } else { printerr(""" No action specified. See -help for information about available actions """) exit(1) } exit(0) } catch let error as TestingError { printerr("\(error)") exit(1) } catch { printerr("\(error)") printerr("Run lit-test-helper -help for more help.") exit(1) }
apache-2.0
106f4a1eb72309beade8de0fa198f06a
34.735495
196
0.68779
4.351829
false
false
false
false
iAugux/iBBS-Swift
iBBS/Additions/TopMostViewController+Additions.swift
1
2187
// // TopMostViewController+Additions.swift // iBBS // // Created by Augus on 9/26/15. // Copyright © 2015 iAugus. All rights reserved. // import UIKit /** Description: the toppest view controller of presenting view controller How to use: UIApplication.topMostViewController Where to use: controllers are not complex */ extension UIApplication { class var topMostViewController: UIViewController? { var topController = UIApplication.sharedApplication().keyWindow?.rootViewController while topController?.presentedViewController != nil { topController = topController?.presentedViewController } return topController } } /** Description: the toppest view controller of presenting view controller How to use: UIApplication.sharedApplication().keyWindow?.rootViewController?.topMostViewController Where to use: There are lots of kinds of controllers (UINavigationControllers, UITabbarControllers, UIViewController) */ extension UIViewController { var topMostViewController: UIViewController? { // Handling Modal views if let presentedViewController = self.presentedViewController { return presentedViewController.topMostViewController } // Handling UIViewController's added as subviews to some other views. else { for view in self.view.subviews { // Key property which most of us are unaware of / rarely use. if let subViewController = view.nextResponder() { if subViewController is UIViewController { let viewController = subViewController as! UIViewController return viewController.topMostViewController } } } return self } } } extension UITabBarController { override var topMostViewController: UIViewController? { return self.selectedViewController?.topMostViewController } } extension UINavigationController { override var topMostViewController: UIViewController? { return self.visibleViewController?.topMostViewController } }
mit
0751c415e5d217d426a59db4aad9451f
31.161765
118
0.685727
6.210227
false
false
false
false
exyte/Macaw
Source/model/draw/RadialGradient.swift
1
971
open class RadialGradient: Gradient { public let cx: Double public let cy: Double public let fx: Double public let fy: Double public let r: Double public init(cx: Double = 0.5, cy: Double = 0.5, fx: Double = 0.5, fy: Double = 0.5, r: Double = 0.5, userSpace: Bool = false, stops: [Stop] = []) { self.cx = cx self.cy = cy self.fx = fx self.fy = fy self.r = r super.init( userSpace: userSpace, stops: stops ) } override func equals<T>(other: T) -> Bool where T: Fill { guard let other = other as? RadialGradient else { return false } let cxEquals = cx == other.cx let cyEquals = cy == other.cy let fxEquals = fx == other.fx let fyEquals = fy == other.fy let rEquals = r == other.r return super.equals(other: other) && cxEquals && cyEquals && fxEquals && fyEquals && rEquals } }
mit
223f589a8e7c90a527aba7c832211180
29.34375
151
0.542739
3.720307
false
false
false
false
billdonner/sheetcheats9
sc9/ModelData.swift
1
14280
// // ModelData.swift // Created by william donner on 9/29/15. import UIKit typealias BoardData = [Tyle] typealias BoardModel = [[Tyle]] // MARK: - global storage final class Globals { static let UserActivityType = "com.billdonner.useractivity.song" class var shared: Globals { struct Singleton { static let sharedAppConfiguration = Globals() } return Singleton.sharedAppConfiguration } var colorTheme = "Black" var matcoll: Sideinfo? // used by allDocsVC, cached here var incoming: [SortEntry]? // used by allDocsVC, cached here // // // var sequentialStoryID = 1000 // global var sequentialTyleID = 1 // global // var theModel:SurfaceDataModel! //var processPool: WKProcessPool = WKProcessPool() // enables sharing of cookies across wkwebviews // connect the activity bool to the info plist var openByActivity: Bool = false var showSettingsUI: Bool { get { if let iDict = Bundle.main.infoDictionary { if let w = iDict["SHOW-SETTINGS"] as? Bool { return !w } } return true } } var openURLOptions:[UIApplicationOpenURLOptionsKey : Any] = [:] var launchOptions : [NSObject: AnyObject]? = nil var segueargs : [String:AnyObject] = [:] var userAuthenticated = false var restored = false class func cacheLoad() { // these are cached - invalidated when content is added or deleted if Globals.shared.incoming == nil { Globals.shared.incoming = Corpus.uniques(Corpus.sortedByTitle()) } if Globals.shared.matcoll == nil { Globals.shared.matcoll = CollationSupport.matrixOfIndexes(&Globals.shared.incoming!) }// } class func reloadModel(/*vc:StoriesViewController*/) -> Bool { var sections: [SectionHeaderProperties] = [] // check version // stories if let stories = NSDictionary(contentsOfFile: FS.shared.StoriesPlist){ for (key,value) in stories { // this is an NSDictionary if key as! String == "version" { let v = value as? String ?? "" guard v == currentversion else { fatalError("Version Mismatch for Stories Data should be \(currentversion) not \(v)") } } } } else { return false} // stories and sections if let dict = NSDictionary(contentsOfFile: FS.shared.SurfacePlist) { let v = dict["version"] as? String ?? "" guard v == currentversion else { fatalError("Version Mismatch for Surface Data should be \(currentversion) not \(v)") } // headers if let headers = dict ["sections"] as? NSArray { for he in headers { let h = he as! SectionHeaderProperties sections.append( h) } } else { return false} var ldata :BoardModel = [] // build new map if let list = dict ["items"] as? NSArray { for each in list { var theRow:BoardData = [] let oo = each as! [ExternalTile] for o in oo { if o[K_ExTile_Label] != "+" { let t = Tyle.makeTyleFromExternalTile(o) theRow.append(t) } }// in oo ldata.append(theRow) } Model.data.sectionHeaders = sections Model.data.tiles = ldata return true } // end of items }// end if let dict return false } class func restoreDataModel() { // no ui run in background // // // Recents.shared.restore() Addeds.shared.restore() let _ = Corpus.shared.reload() let _ = reloadModel () // local class func saveDataModel() // why???????? } class func saveDataModel() { //var enabledRowIndex = -1 var tilerowcount = 0 var headercount = 0 // var enabledRowName: String? // let elapsedTime = timedClosure("saving"){ var list :[[ExternalTile]] = [] var theaders: [SectionHeaderProperties] = [] let tales = NSMutableDictionary() tales.setObject(currentversion as NSString, forKey: "version" as NSCopying) if let td = tales as NSDictionary? { td.write(toFile: FS.shared.StoriesPlist, atomically: true) } // rows for row in Model.data.tiles { var thisrowlist:[ExternalTile] = [] for each in row { thisrowlist.append (Tyle.makeExternalTileFromTyle(each)) } list.append(thisrowlist) tilerowcount += 1 } //headers var idx = 0 for header in Model.data.sectionHeaders { // if (header["enabled"] != nil) { enabledRowIndex = idx } // get las enabled for now let x = (header["enabled"] != nil) ? "1":"0" let h = [SectionProperties.NameKey:header[SectionProperties.NameKey]!,"enabled":x] theaders.append(h) headercount += 1 idx += 1 } var d : Dictionary<String,NSObject> = [:] d ["version"] = currentversion as NSString d ["sections"] = theaders as NSObject? d ["items"] = list as NSObject? let dd = d as NSDictionary dd.write(toFile: FS.shared.SurfacePlist, atomically: true) // write a slice of it all to user defaults // if enabledRowIndex >= 0 { // let h = Model.data.sectionHeaders[enabledRowIndex] // if let name = h[SectionProperties.NameKey] { // let rodata = Model.data.tiles[enabledRowIndex] // var thisrowlist:[ExternalTile] = [] // for each in rodata { // thisrowlist.append (Tyle.makeExternalTileFromTyle(each)) // } // InterAppCommunications.save(name,items:thisrowlist) // } // } //}// end of timed closure print ("saved Surface rows \(tilerowcount) headers \(headercount)") // announce what we have done NotificationCenter.default.post(name: Notification.Name(rawValue: kSurfaceUpdatedSignal),object:nil) } } // each header is just a simple dictionary of properties typealias SectionHeaderProperties = [String:String] struct SectionProperties { static let NameKey = "STR" } protocol SectionHeaderOps { func isEqualHeaderString(_ s:SectionHeaderProperties,string:String)->Bool func makeHeaderFrom(_ from:String)->SectionHeaderProperties } extension SectionHeaderOps { func isEqualHeaderString(_ s:SectionHeaderProperties,string:String)->Bool { return s[SectionProperties.NameKey] == string } func makeHeaderFrom(_ from:String)->SectionHeaderProperties{ var s = SectionHeaderProperties() s[SectionProperties.NameKey] = from return s } } final class Model { class var data: Model { struct Singleton { static let sharedAppConfiguration = Model() } return Singleton.sharedAppConfiguration } var tiles = BoardModel() var sectionHeaders = [SectionHeaderProperties]() func describe() { if tiles.count > 0 { print ("Model is ", tiles.count, " rows with ",tiles[0].count," elements in 1st row") for j in 0..<Model.data.tiles.count { print("\n\(j):") for k in 0..<Model.data.tiles[j].count { print (" \(Model.data.tiles[j][k]) ") } } } else { print("Model has no tiles") } if Corpus.shared.hascontent() == false { print ("Corpus has no files") } } } protocol ModelData :SectionHeaderOps{ func mswap(_ sourceIndexPath:IndexPath, _ destinationIndexPath:IndexPath) func mswap2(_ sourceIndexPath:IndexPath, _ destinationIndexPath:IndexPath) func sectionNumFromName(_ section:String) throws -> Int func elementFor(_ path:IndexPath) -> Tyle func setElementFor(_ path:IndexPath,el:Tyle) func noTiles() -> Bool // func sectCount() -> Int func sectHeader(_ i:Int)->SectionHeaderProperties func moveSects(_ from:Int, _ to:Int) func deleteSect(_ i: Int) // func makeNewSect(i:Int,hdr:SectionHeaderProperties ) // func tileInsert(indexPath:NSIndexPath,newElement:Tyle) func tileData(_ indexPath:IndexPath)->Tyle func tileSection(_ indexPath:IndexPath)->[Tyle] func tileRemove(_ indexPath:IndexPath) func tileSectionCount() -> Int func addedsCount()->Int func addedsData(_ i:Int)->AddedListEntry func recentsCount()->Int func recentsData(_ i:Int)->RecentListEntry func makeTileAt(_ indexPath:IndexPath,labelled:String) -> Tyle func makeHeaderAt(_ indexPath:IndexPath,labelled:String) } extension ModelData { //// func addedsCount()->Int { return Addeds.shared.gAddeds.count } func addedsData(_ i:Int)-> AddedListEntry { return Addeds.shared.gAddeds[i] } func recentsCount()->Int { return Recents.shared.gRecents.count } func recentsData(_ i:Int)->RecentListEntry { return Recents.shared.gRecents[i] } func sectCount() -> Int { return Model.data.sectionHeaders.count } func tileSectionCount() -> Int { // should be the same as above return Model.data.tiles.count } func tileCountInSection(_ i:Int) -> Int { return Model.data.tiles[i].count } func noTiles() -> Bool { return Model.data.tiles.count == 0 } func elementFor(_ path:IndexPath) -> Tyle { return Model.data.tiles[(path as NSIndexPath).section][(path as NSIndexPath).item] } func setElementFor(_ path:IndexPath,el:Tyle) { Model.data.tiles[(path as NSIndexPath).section][(path as NSIndexPath).item] = el } func tileSection(_ indexPath:IndexPath)->[Tyle] { return Model.data.tiles[(indexPath as NSIndexPath).section] } func tileRemove(_ indexPath:IndexPath) { Model.data.tiles[(indexPath as NSIndexPath).section].remove(at: (indexPath as NSIndexPath).item) } private func tileInsert(_ indexPath:IndexPath,newElement:Tyle) { // print("tileInsert at \(indexPath)") Model.data.tiles[(indexPath as NSIndexPath).section].insert(newElement, at: (indexPath as NSIndexPath).item) } func tileData(_ indexPath:IndexPath)->Tyle { return Model.data.tiles[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).item] } func sectHeader(_ i:Int)->SectionHeaderProperties { return Model.data.sectionHeaders[i] } func renameSectHeader(_ i:Int,headerTitle:String) { Model.data.sectionHeaders[i][SectionProperties.NameKey] = headerTitle } func moveSects(_ from:Int, _ to:Int){ let t = Model.data.tiles [from] Model.data.tiles.insert(t,at:to) let h = Model.data.sectionHeaders [from] Model.data.sectionHeaders.insert(h,at:to) } func deleteSect(_ i: Int){ Model.data.sectionHeaders.remove(at: i) Model.data.tiles.remove(at: i) } private func makeNewSect(_ i:Int,hdr:SectionHeaderProperties ){ // print("making section index:\(i)") let title = hdr[SectionProperties.NameKey]! Model.data.sectionHeaders.insert(self.makeHeaderFrom("\(title)"), at:i ) Model.data.tiles.insert ([], at:i) //append a new, empty section } func mswap2(_ sourceIndexPath:IndexPath, _ destinationIndexPath:IndexPath) { let section = Model.data.tiles[(sourceIndexPath as NSIndexPath).section] let temp = section[(sourceIndexPath as NSIndexPath).item] // the character //shrink source array Model.data.tiles[(sourceIndexPath as NSIndexPath).section].remove(at: (sourceIndexPath as NSIndexPath).item) //insert in dest array Model.data.tiles[(destinationIndexPath as NSIndexPath).section].insert(temp, at: (destinationIndexPath as NSIndexPath).item) } func mswap(_ sourceIndexPath:IndexPath, _ destinationIndexPath:IndexPath) { // swap values if source and destination sections are the same let temp = Model.data.tiles[(sourceIndexPath as NSIndexPath).section][(sourceIndexPath as NSIndexPath).item] Model.data.tiles[(sourceIndexPath as NSIndexPath).section][(sourceIndexPath as NSIndexPath).item] = Model.data.tiles[(destinationIndexPath as NSIndexPath).section][(destinationIndexPath as NSIndexPath).item] Model.data.tiles[(destinationIndexPath as NSIndexPath).section][(destinationIndexPath as NSIndexPath).item] = temp } func sectionNumFromName(_ section:String) throws -> Int { var i = 0 for hd in Model.data.sectionHeaders { if hd["title"] == section { return i } i += 1 } throw TyleError.generalFailure } func makeTileAt(_ indexPath:IndexPath,labelled:String = "newtile") -> Tyle { let tyle = Tyle(label: labelled, bpm: "", key: "", docPath: "", url: "", note: "", textColor:.white, backColor:.black ) tileInsert(indexPath,newElement:tyle) return tyle } func makeHeaderAt(_ indexPath:IndexPath,labelled:String = "newheader") { let hdr = makeHeaderFrom(labelled) makeNewSect((indexPath as NSIndexPath).row,hdr:hdr) } }
apache-2.0
bd8165828132f7effd372dacce440af4
36.382199
215
0.582143
4.576923
false
false
false
false
AlexeyGolovenkov/DevHelper
DevHelper/DevHelperTests/ArrayOfStringTests.swift
1
4684
// // ArrayOfStringTests.swift // DevHelperTests // // Created by Alex Golovenkov on 20/03/2018. // Copyright © 2018 Alexey Golovenkov. All rights reserved. // import XCTest class ArrayOfStringTests: XCTestCase { 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 testSubstringForward() { guard let source = String(testFileName:"UncommentSource.test") else { XCTFail("Source test file not found") return } let lines = source.lines() let startPosition = DHTextPosition(line: 29, column: 3) let endCommentPostion = lines.position(of: "*/", between: startPosition, and: nil, direction: []) let correctPosition = DHTextPosition(line: 31, column: 0) XCTAssertEqual(endCommentPostion, correctPosition, "Wrong position of */ symbol") } func testSubstringBackward() { guard let source = String(testFileName:"UncommentSource.test") else { XCTFail("Source test file not found") return } let lines = source.lines() let endPosition = DHTextPosition(line: 29, column: 3) let endCommentPostion = lines.position(of: "/*", between: nil, and: endPosition, direction: [.backwards]) let correctPosition = DHTextPosition(line: 25, column: 0) XCTAssertEqual(endCommentPostion, correctPosition, "Wrong position of */ symbol") } func testPositionOfCommentEnd() { guard let source = String(testFileName:"UncommentSource.test") else { XCTFail("Source test file not found") return } let lines = source.lines() let startPosition = DHTextPosition(line: 24, column: 3) let positionOfCommentEnd = lines.positionOfBlockEnd(from: startPosition) let correctPosition = DHTextPosition(line: 33, column: 0) XCTAssertEqual(positionOfCommentEnd, correctPosition, "Wrong position: \(String(describing: positionOfCommentEnd))") } func testClassBracketsStart() { guard let source = String(testFileName:"SwiftClass.test") else { XCTFail("Source test file not found") return } let lines = source.lines() let startPosition = DHTextPosition(line: 11, column: 22) let classStartPosition = lines.positionOfBlockStart(from: startPosition, startBlockMarker: "{", endBlockMarker: "}") let correctPosition = DHTextPosition(line: 10, column: 19) XCTAssertEqual(classStartPosition, correctPosition, "Wrong position: \(String(describing: classStartPosition))") } func testClassBracketsEnd() { guard let source = String(testFileName:"SwiftClass.test") else { XCTFail("Source test file not found") return } let lines = source.lines() let startPosition = DHTextPosition(line: 11, column: 22) let classEndPosition = lines.positionOfBlockEnd(from: startPosition, startBlockMarker: "{", endBlockMarker: "}") let correctPosition = DHTextPosition(line: 46, column: 0) XCTAssertEqual(classEndPosition, correctPosition, "Wrong position: \(String(describing: classEndPosition))") } func testClassName() { guard let source = String(testFileName:"SwiftClass.test") else { XCTFail("Source test file not found") return } let lines = source.lines() let noClassLocation = lines.positionOfClass(over: 9) XCTAssertNil(noClassLocation, "No class over line 9") let classNameLocation = lines.positionOfClass(over: 12) XCTAssertNotNil(classNameLocation, "Class name not found") XCTAssertTrue(classNameLocation?.lineIndex == 10, "Wrong line of class declare: \(String(describing: classNameLocation?.lineIndex))") XCTAssertTrue(classNameLocation?.className == "StringHelper", "Wrong class name: \(String(describing: classNameLocation?.className))") let classNameLocationAboveClassFunc = lines.positionOfClass(over: 45) XCTAssertTrue(classNameLocationAboveClassFunc?.lineIndex == 10, "Wrong line of class declare: \(String(describing: classNameLocationAboveClassFunc?.lineIndex))") XCTAssertTrue(classNameLocationAboveClassFunc?.className == "StringHelper", "Wrong class name: \(String(describing: classNameLocationAboveClassFunc?.className))") } }
mit
95b6955f1c6775a276cc7ea467f1b536
45.366337
170
0.669656
4.744681
false
true
false
false
blockchain/My-Wallet-V3-iOS
Modules/CryptoAssets/Sources/BitcoinChainKit/Transactions/NativeBitcoin/CoinSelection/TransactionSizeCalculator/TransactionSizeCalculatorQuantities.swift
1
1821
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import BigInt import Foundation /// An struct that express the quantity of different types of unspent /// outputs being used. struct TransactionSizeCalculatorQuantities { static let zero = TransactionSizeCalculatorQuantities(bitcoinScriptTypes: []) private let p2pkh: UInt private let p2wpkh: UInt private let p2sh: UInt private let p2wsh: UInt var count: UInt { p2pkh + p2wpkh + p2sh + p2wsh } var hasWitness: Bool { p2wpkh > 0 || p2wsh > 0 } init(bitcoinScriptTypes: [BitcoinScriptType]) { p2pkh = UInt(bitcoinScriptTypes.filter { $0 == .P2PKH }.count) p2wpkh = UInt(bitcoinScriptTypes.filter { $0 == .P2WPKH }.count) p2sh = UInt(bitcoinScriptTypes.filter { $0 == .P2SH }.count) p2wsh = UInt(bitcoinScriptTypes.filter { $0 == .P2WSH }.count) } init(unspentOutputs: [UnspentOutput]) { self.init(bitcoinScriptTypes: unspentOutputs.map(\.scriptType)) } var vBytesTotalInput: Decimal { var vBytesTotal = Decimal(0) vBytesTotal += TransactionCost.PerInput.p2pkh * Decimal(p2pkh) vBytesTotal += TransactionCost.PerInput.p2wpkh * Decimal(p2wpkh) vBytesTotal += TransactionCost.PerInput.p2sh * Decimal(p2sh) vBytesTotal += TransactionCost.PerInput.p2wsh * Decimal(p2wsh) return vBytesTotal } var vBytesTotalOutput: Decimal { var vBytesTotal = Decimal(0) vBytesTotal += TransactionCost.PerOutput.p2pkh * Decimal(p2pkh) vBytesTotal += TransactionCost.PerOutput.p2wpkh * Decimal(p2wpkh) vBytesTotal += TransactionCost.PerOutput.p2sh * Decimal(p2sh) vBytesTotal += TransactionCost.PerOutput.p2wsh * Decimal(p2wsh) return vBytesTotal } }
lgpl-3.0
d3e4b3a57c954510d81f6537caf266d4
33.339623
81
0.678022
3.395522
false
true
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureActivity/Sources/FeatureActivityUI/Details/ERC20/ERC20ActivityDetailsViewModel+Ethereum.swift
1
2117
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import BigInt import ERC20Kit import EthereumKit import Localization import MoneyKit import PlatformKit import PlatformUIKit extension ERC20ActivityDetailsViewModel { init(details: EthereumActivityItemEventDetails, price: FiatValue?, feePrice: FiatValue?) { confirmation = Confirmation( needConfirmation: details.confirmation.needConfirmation, // swiftlint:disable line_length title: "\(details.confirmation.confirmations) \(LocalizedString.of) \(details.confirmation.requiredConfirmations) \(LocalizedString.confirmations)", factor: details.confirmation.factor, statusBadge: details.confirmation.status.statusBadge ) dateCreated = DateFormatter.elegantDateFormatter.string(from: details.createdAt) let gas = ERC20ContractGasActivityModel(details: details) amounts = ERC20ActivityDetailsViewModel.amounts(details: details, gas: gas, price: price, feePrice: feePrice) to = gas?.to?.publicKey from = details.from.publicKey fee = "\(amounts.fee.cryptoAmount) / \(amounts.fee.value)" } private static func amounts( details: EthereumActivityItemEventDetails, gas: ERC20ContractGasActivityModel?, price: FiatValue?, feePrice: FiatValue? ) -> Amounts { func value(cryptoValue: CryptoValue, price: FiatValue?) -> Amounts.Value { let cryptoAmount = cryptoValue.displayString let value: String if let price = price { value = cryptoValue.convert(using: price).displayString } else { value = "" } return Amounts.Value(cryptoAmount: cryptoAmount, value: value) } var gasFor: Amounts.Value? if let gasCryptoValue = gas?.cryptoValue { gasFor = value(cryptoValue: gasCryptoValue, price: price) } return Amounts( fee: value(cryptoValue: details.fee, price: feePrice), gasFor: gasFor ) } }
lgpl-3.0
7f4d8c151adb9b939d3329df5328c403
34.864407
160
0.657845
4.83105
false
false
false
false
sgr-ksmt/PDFGenerator
Demo/Controllers/SampleTableViewController.swift
1
1834
// // SampleTableViewController.swift // PDFGenerator // // Created by Suguru Kishimoto on 2016/02/27. // // import UIKit import PDFGenerator class SampleTableViewController: UITableViewController { @objc fileprivate func generatePDF() { do { let dst = NSHomeDirectory() + "/sample_tblview.pdf" try PDFGenerator.generate(self.tableView, to: dst) openPDFViewer(dst) } catch let error { print(error) } } fileprivate func openPDFViewer(_ pdfPath: String) { self.performSegue(withIdentifier: "PreviewVC", sender: pdfPath) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let pdfPreviewVC = segue.destination as? PDFPreviewVC, let pdfPath = sender as? String { let url = URL(fileURLWithPath: pdfPath) pdfPreviewVC.setupWithURL(url) } } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 3 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 10 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! SampleTableViewCell cell.leftLabel.text = "\((indexPath as NSIndexPath).section)-\((indexPath as NSIndexPath).row)cell" cell.rightLabel.text = "sample" return cell } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "section\(section)" } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { generatePDF() } }
mit
23c20464b2c5b22fd507c3a3d71a33b9
30.084746
112
0.660305
4.763636
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/ViewRelated/Reader/ReaderHelpers.swift
1
20844
import Foundation import WordPressShared import WordPressFlux // MARK: - Reader Notifications extension NSNotification.Name { // Sent when a site or a tag is unfollowed via Reader Manage screen. static let ReaderTopicUnfollowed = NSNotification.Name(rawValue: "ReaderTopicUnfollowed") // Sent when a site is followed via Reader Manage screen. static let ReaderSiteFollowed = NSNotification.Name(rawValue: "ReaderSiteFollowed") // Sent when a post's seen state has been toggled. static let ReaderPostSeenToggled = NSNotification.Name(rawValue: "ReaderPostSeenToggled") // Sent when a site is blocked. static let ReaderSiteBlocked = NSNotification.Name(rawValue: "ReaderSiteBlocked") } struct ReaderNotificationKeys { static let post = "post" static let topic = "topic" } // Used for event tracking properties enum ReaderPostMenuSource { case card case details var description: String { switch self { case .card: return "post_card" case .details: return "post_details" } } } // Titles for post menu options struct ReaderPostMenuButtonTitles { static let cancel = NSLocalizedString("Cancel", comment: "The title of a cancel button.") static let blockSite = NSLocalizedString("Block this site", comment: "The title of a button that triggers blocking a site from the user's reader.") static let reportPost = NSLocalizedString("Report this post", comment: "The title of a button that triggers reporting of a post from the user's reader.") static let share = NSLocalizedString("Share", comment: "Verb. Title of a button. Pressing lets the user share a post to others.") static let visit = NSLocalizedString("Visit", comment: "An option to visit the site to which a specific post belongs") static let unfollow = NSLocalizedString("Unfollow site", comment: "Verb. An option to unfollow a site.") static let follow = NSLocalizedString("Follow site", comment: "Verb. An option to follow a site.") static let subscribe = NSLocalizedString("Turn on site notifications", comment: "Verb. An option to switch on site notifications.") static let unsubscribe = NSLocalizedString("Turn off site notifications", comment: "Verb. An option to switch off site notifications.") static let markSeen = NSLocalizedString("Mark as seen", comment: "An option to mark a post as seen.") static let markUnseen = NSLocalizedString("Mark as unseen", comment: "An option to mark a post as unseen.") static let followConversation = NSLocalizedString("Follow conversation by email", comment: "Verb. Button title. Follow the comments on a post.") static let unFollowConversation = NSLocalizedString("Unfollow conversation by email", comment: "Verb. Button title. The user is following the comments on a post.") } /// A collection of helper methods used by the Reader. /// @objc open class ReaderHelpers: NSObject { // MARK: - Topic Helpers public static let discoverSiteID = NSNumber(value: 53424024) /// Check if the specified topic is a default topic /// /// - Parameters: /// - topic: A ReaderAbstractTopic /// /// - Returns: True if the topic is a default topic /// @objc open class func isTopicDefault(_ topic: ReaderAbstractTopic) -> Bool { return topic.isKind(of: ReaderDefaultTopic.self) } /// Check if the specified topic is a list /// /// - Parameters: /// - topic: A ReaderAbstractTopic /// /// - Returns: True if the topic is a list topic /// @objc open class func isTopicList(_ topic: ReaderAbstractTopic) -> Bool { return topic.isKind(of: ReaderListTopic.self) } /// Check if the specified topic is a site topic /// /// - Parameters: /// - topic: A ReaderAbstractTopic /// /// - Returns: True if the topic is a site topic /// @objc open class func isTopicSite(_ topic: ReaderAbstractTopic) -> Bool { return topic.isKind(of: ReaderSiteTopic.self) } /// Check if the specified topic is a tag topic /// /// - Parameters: /// - topic: A ReaderAbstractTopic /// /// - Returns: True if the topic is a tag topic /// @objc open class func isTopicTag(_ topic: ReaderAbstractTopic) -> Bool { return topic.isKind(of: ReaderTagTopic.self) } /// Check if the specified topic is a search topic /// /// - Parameters: /// - topic: A ReaderAbstractTopic /// /// - Returns: True if the topic is a search topic /// @objc open class func isTopicSearchTopic(_ topic: ReaderAbstractTopic) -> Bool { return topic.isKind(of: ReaderSearchTopic.self) } /// Check if the specified topic is for Freshly Pressed /// /// - Parameters: /// - topic: A ReaderAbstractTopic /// /// - Returns: True if the topic is for Freshly Pressed /// @objc open class func topicIsFreshlyPressed(_ topic: ReaderAbstractTopic) -> Bool { return topic.path.hasSuffix("/freshly-pressed") } /// Check if the specified topic is for Discover /// /// - Parameters: /// - topic: A ReaderAbstractTopic /// /// - Returns: True if the topic is for Discover /// @objc open class func topicIsDiscover(_ topic: ReaderAbstractTopic) -> Bool { return topic.path.contains("/read/sites/53424024/posts") } /// Check if the specified topic is for Following /// /// - Parameters: /// - topic: A ReaderAbstractTopic /// /// - Returns: True if the topic is for Following /// @objc open class func topicIsFollowing(_ topic: ReaderAbstractTopic) -> Bool { return topic.path.hasSuffix("/read/following") } /// Check if the specified topic is for Posts I Like /// /// - Parameters: /// - topic: A ReaderAbstractTopic /// /// - Returns: True if the topic is for Posts I Like /// @objc open class func topicIsLiked(_ topic: ReaderAbstractTopic) -> Bool { return topic.path.hasSuffix("/read/liked") } /// Check if the specified topic is for Posts Saved for Later /// /// - Parameters: /// - topic: A ReaderAbstractTopic /// /// - Returns: True if the topic is for Saved For Later /// @objc open class func topicIsSavedForLater(_ topic: ReaderAbstractTopic) -> Bool { //TODO. Update this logic with the right one. I am not sure how this is going to be modeeled now. return topic.path.hasSuffix("/mock") } // MARK: Analytics Helpers class func trackLoadedTopic(_ topic: ReaderAbstractTopic, withProperties properties: [AnyHashable: Any]) { var stat: WPAnalyticsStat? if topicIsFreshlyPressed(topic) { stat = .readerFreshlyPressedLoaded } else if topicIsFollowing(topic) { WPAnalytics.trackReader(.readerFollowingShown, properties: properties) } else if topicIsLiked(topic) { WPAnalytics.trackReader(.readerLikedShown, properties: properties) } else if isTopicSite(topic) { WPAnalytics.trackReader(.readerBlogPreviewed, properties: properties) } else if isTopicDefault(topic) && topicIsDiscover(topic) { // Tracks Discover only if it was one of the default menu items. WPAnalytics.trackReaderEvent(.readerDiscoverShown, properties: properties) } else if isTopicList(topic) { stat = .readerListLoaded } else if isTopicTag(topic) { stat = .readerTagLoaded } else if let teamTopic = topic as? ReaderTeamTopic { WPAnalytics.trackReader(teamTopic.shownTrackEvent, properties: properties) } if stat != nil { WPAnalytics.track(stat!, withProperties: properties) } } @objc open class func statsPropertiesForPost(_ post: ReaderPost, andValue value: AnyObject?, forKey key: String?) -> [AnyHashable: Any] { var properties = [AnyHashable: Any]() properties[WPAppAnalyticsKeyBlogID] = post.siteID properties[WPAppAnalyticsKeyPostID] = post.postID properties[WPAppAnalyticsKeyIsJetpack] = post.isJetpack if let feedID = post.feedID, let feedItemID = post.feedItemID { properties[WPAppAnalyticsKeyFeedID] = feedID properties[WPAppAnalyticsKeyFeedItemID] = feedItemID } if let value = value, let key = key { properties[key] = value } return properties } @objc open class func bumpPageViewForPost(_ post: ReaderPost) { // Don't bump page views for feeds else the wrong blog/post get's bumped if post.isExternal && !post.isJetpack { return } guard let siteID = post.siteID, let postID = post.postID, let host = NSURL(string: post.blogURL)?.host else { return } // If the user is an admin on the post's site do not bump the page view unless // the the post is private. if !post.isPrivate() && isUserAdminOnSiteWithID(siteID) { return } let pixelStatReferrer = "https://wordpress.com/" let pixel = "https://pixel.wp.com/g.gif" let params: NSArray = [ "v=wpcom", "reader=1", "ref=\(pixelStatReferrer)", "host=\(host)", "blog=\(siteID)", "post=\(postID)", NSString(format: "t=%d", arc4random()) ] let userAgent = WPUserAgent.wordPress() let path = NSString(format: "%@?%@", pixel, params.componentsJoined(by: "&")) as String guard let url = URL(string: path) else { return } let request = NSMutableURLRequest(url: url) request.setValue(userAgent, forHTTPHeaderField: "User-Agent") request.addValue(pixelStatReferrer, forHTTPHeaderField: "Referer") let session = URLSession.shared let task = session.dataTask(with: request as URLRequest) task.resume() } @objc open class func isUserAdminOnSiteWithID(_ siteID: NSNumber) -> Bool { Blog.lookup(withID: siteID, in: ContextManager.sharedInstance().mainContext)?.isAdmin ?? false } // convenience method that returns the topic type class func topicType(_ topic: ReaderAbstractTopic?) -> ReaderTopicType { guard let topic = topic else { return .noTopic } if topicIsDiscover(topic) { return .discover } if topicIsFollowing(topic) { return .following } if topicIsLiked(topic) { return .likes } if isTopicList(topic) { return .list } if isTopicSearchTopic(topic) { return .search } if isTopicSite(topic) { return .site } if isTopicTag(topic) { return .tag } if topic is ReaderTeamTopic { return .organization } return .noTopic } // MARK: Logged in helper @objc open class func isLoggedIn() -> Bool { return AccountHelper.isDotcomAvailable() } // MARK: ActionDispatcher Notification helper class func dispatchToggleSeenMessage(post: ReaderPost, success: Bool) { var notice: Notice { if success { return Notice(title: post.isSeen ? NoticeMessages.seenSuccess : NoticeMessages.unseenSuccess) } return Notice(title: post.isSeen ? NoticeMessages.unseenFail : NoticeMessages.seenFail) } dispatchNotice(notice) } class func dispatchToggleFollowSiteMessage(post: ReaderPost, follow: Bool, success: Bool) { dispatchToggleFollowSiteMessage(siteTitle: post.blogNameForDisplay(), siteID: post.siteID, follow: follow, success: success) } class func dispatchToggleFollowSiteMessage(site: ReaderSiteTopic, follow: Bool, success: Bool) { dispatchToggleFollowSiteMessage(siteTitle: site.title, siteID: site.siteID, follow: follow, success: success) } class func dispatchToggleSubscribeCommentMessage(subscribing: Bool, success: Bool) { let title: String if success { title = subscribing ? NoticeMessages.commentFollowSuccess : NoticeMessages.commentUnfollowSuccess } else { title = subscribing ? NoticeMessages.commentFollowFail : NoticeMessages.commentUnfollowFail } dispatchNotice(Notice(title: title)) } class func dispatchToggleSubscribeCommentErrorMessage(subscribing: Bool) { let title = subscribing ? NoticeMessages.commentFollowError : NoticeMessages.commentUnfollowError dispatchNotice(Notice(title: title)) } class func dispatchToggleFollowSiteMessage(siteTitle: String, siteID: NSNumber, follow: Bool, success: Bool) { var notice: Notice if success { notice = follow ? followedSiteNotice(siteTitle: siteTitle, siteID: siteID) : Notice(title: NoticeMessages.unfollowSuccess, message: siteTitle) } else { notice = Notice(title: follow ? NoticeMessages.followFail : NoticeMessages.unfollowFail) } dispatchNotice(notice) } class func dispatchToggleNotificationMessage(topic: ReaderSiteTopic, success: Bool) { var notice: Notice { if success { return Notice(title: topic.isSubscribedForPostNotifications ? NoticeMessages.notificationOnSuccess : NoticeMessages.notificationOffSuccess) } return Notice(title: topic.isSubscribedForPostNotifications ? NoticeMessages.notificationOffFail : NoticeMessages.notificationOnFail) } dispatchNotice(notice) } class func dispatchSiteBlockedMessage(post: ReaderPost, success: Bool) { var notice: Notice { if success { return Notice(title: NoticeMessages.blockSiteSuccess, message: post.blogNameForDisplay()) } return Notice(title: NoticeMessages.blockSiteFail, message: post.blogNameForDisplay()) } dispatchNotice(notice) } private class func dispatchNotice(_ notice: Notice) { ActionDispatcher.dispatch(NoticeAction.post(notice)) } private class func followedSiteNotice(siteTitle: String, siteID: NSNumber) -> Notice { let notice = Notice(title: String(format: NoticeMessages.followSuccess, siteTitle), message: NoticeMessages.enableNotifications, actionTitle: NoticeMessages.enableButtonLabel) { _ in let service = ReaderTopicService(managedObjectContext: ContextManager.sharedInstance().mainContext) service.toggleSubscribingNotifications(for: siteID.intValue, subscribe: true, { WPAnalytics.track(.readerListNotificationEnabled) }) } return notice } private struct NoticeMessages { static let seenFail = NSLocalizedString("Unable to mark post seen", comment: "Notice title when updating a post's seen status failed.") static let unseenFail = NSLocalizedString("Unable to mark post unseen", comment: "Notice title when updating a post's unseen status failed.") static let seenSuccess = NSLocalizedString("Marked post as seen", comment: "Notice title when updating a post's seen status succeeds.") static let unseenSuccess = NSLocalizedString("Marked post as unseen", comment: "Notice title when updating a post's unseen status succeeds.") static let followSuccess = NSLocalizedString("Following %1$@", comment: "Notice title when following a site succeeds. %1$@ is a placeholder for the site name.") static let unfollowSuccess = NSLocalizedString("Unfollowed site", comment: "Notice title when unfollowing a site succeeds.") static let followFail = NSLocalizedString("Unable to follow site", comment: "Notice title when following a site fails.") static let unfollowFail = NSLocalizedString("Unable to unfollow site", comment: "Notice title when unfollowing a site fails.") static let notificationOnFail = NSLocalizedString("Unable to turn on site notifications", comment: "Notice title when turning site notifications on fails.") static let notificationOffFail = NSLocalizedString("Unable to turn off site notifications", comment: "Notice title when turning site notifications off fails.") static let notificationOnSuccess = NSLocalizedString("Turned on site notifications", comment: "Notice title when turning site notifications on succeeds.") static let notificationOffSuccess = NSLocalizedString("Turned off site notifications", comment: "Notice title when turning site notifications off succeeds.") static let enableNotifications = NSLocalizedString("Enable site notifications?", comment: "Message prompting user to enable site notifications.") static let enableButtonLabel = NSLocalizedString("Enable", comment: "Button title for the enable site notifications action.") static let blockSiteSuccess = NSLocalizedString("Blocked site", comment: "Notice title when blocking a site succeeds.") static let blockSiteFail = NSLocalizedString("Unable to block site", comment: "Notice title when blocking a site fails.") static let commentFollowSuccess = NSLocalizedString("Successfully followed conversation", comment: "The app successfully subscribed to the comments for the post") static let commentUnfollowSuccess = NSLocalizedString("Successfully unfollowed conversation", comment: "The app successfully unsubscribed from the comments for the post") static let commentFollowFail = NSLocalizedString("Unable to follow conversation", comment: "The app failed to subscribe to the comments for the post") static let commentUnfollowFail = NSLocalizedString("Failed to unfollow conversation", comment: "The app failed to unsubscribe from the comments for the post") static let commentFollowError = NSLocalizedString("Could not subscribe to comments", comment: "The app failed to subscribe to the comments for the post") static let commentUnfollowError = NSLocalizedString("Could not unsubscribe from comments", comment: "The app failed to unsubscribe from the comments for the post") } } /// Reader tab items extension ReaderHelpers { static let defaultSavedItemPosition = 3 /// Sorts the default tabs according to the order [Following, Discover, Likes], and adds the Saved tab class func rearrange(items: [ReaderTabItem]) -> [ReaderTabItem] { guard !items.isEmpty else { return items } var mutableItems = items mutableItems.sort { guard let leftTopic = $0.content.topic, let rightTopic = $1.content.topic else { return true } // first item: Following if topicIsFollowing(leftTopic) { return true } if topicIsFollowing(rightTopic) { return false } // second item: Discover if topicIsDiscover(leftTopic) { return true } if topicIsDiscover(rightTopic) { return false } // third item: Likes if topicIsLiked(leftTopic) { return true } if topicIsLiked(rightTopic) { return false } // any other items: sort them alphabetically, grouped by topic type if leftTopic.type == rightTopic.type { return leftTopic.title < rightTopic.title } return true } // fourth item: Saved. It's manually inserted after the sorting let savedPosition = min(mutableItems.count, defaultSavedItemPosition) mutableItems.insert(ReaderTabItem(ReaderContent(topic: nil, contentType: .saved)), at: savedPosition) // in case of log in with a self hosted site, prepend a 'dummy' Following tab if !isLoggedIn() { mutableItems.insert(ReaderTabItem(ReaderContent(topic: nil, contentType: .selfHostedFollowing)), at: 0) } return mutableItems } } /// Typed topic type enum ReaderTopicType { case discover case following case likes case list case search case site case tag case organization case noTopic } @objc enum SiteOrganizationType: Int { // site does not belong to an organization case none // site is an A8C P2 case automattic // site is a non-A8C P2 case p2 }
gpl-2.0
e1a811d3c5d0b36238979954bf674507
38.477273
178
0.656592
4.921842
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/WordPressUITests/Screens/Login/LoginCheckMagicLinkScreen.swift
1
973
import UITestsFoundation import XCTest private struct ElementStringIDs { static let passwordOption = "Use Password" static let mailButton = "Open Mail Button" } class LoginCheckMagicLinkScreen: BaseScreen { let passwordOption: XCUIElement let mailButton: XCUIElement let mailAlert: XCUIElement init() { let app = XCUIApplication() passwordOption = app.buttons[ElementStringIDs.passwordOption] mailButton = app.buttons[ElementStringIDs.mailButton] mailAlert = app.alerts.element(boundBy: 0) super.init(element: mailButton) } func proceedWithPassword() -> LoginPasswordScreen { passwordOption.tap() return LoginPasswordScreen() } func openMagicLoginLink() -> LoginEpilogueScreen { openMagicLink() return LoginEpilogueScreen() } static func isLoaded() -> Bool { return XCUIApplication().buttons[ElementStringIDs.mailButton].exists } }
gpl-2.0
28979ae714ee8459bc57fcc3cf4310ca
24.605263
76
0.693731
4.633333
false
true
false
false
apple/swift-nio-http2
Sources/NIOHTTP2PerformanceTester/ServerOnly10KRequestsBenchmark.swift
1
7223
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2020-2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import NIOCore import NIOEmbedded import NIOHPACK import NIOHTTP2 final class ServerOnly10KRequestsBenchmark: Benchmark { private let concurrentStreams: Int var channel: EmbeddedChannel? // This offset is preserved across runs. var streamID = HTTP2StreamID(1) // A manually constructed data frame. private var dataFrame: ByteBuffer = { var buffer = ByteBuffer(repeating: 0xff, count: 1024 + 9) // UInt24 length, is 1024 bytes. buffer.setInteger(UInt8(0), at: buffer.readerIndex) buffer.setInteger(UInt16(1024), at: buffer.readerIndex + 1) // Type buffer.setInteger(UInt8(0x00), at: buffer.readerIndex + 3) // Flags, turn on end-stream. buffer.setInteger(UInt8(0x01), at: buffer.readerIndex + 4) // 4 byte stream identifier, set to zero for now as we update it later. buffer.setInteger(UInt32(0), at: buffer.readerIndex + 5) return buffer }() // A manually constructed headers frame. private var headersFrame: ByteBuffer = { var headers = HPACKHeaders() headers.add(name: ":method", value: "GET", indexing: .indexable) headers.add(name: ":authority", value: "localhost", indexing: .nonIndexable) headers.add(name: ":path", value: "/", indexing: .indexable) headers.add(name: ":scheme", value: "https", indexing: .indexable) headers.add(name: "user-agent", value: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36", indexing: .nonIndexable) headers.add(name: "accept-encoding", value: "gzip, deflate", indexing: .indexable) var hpackEncoder = HPACKEncoder(allocator: .init()) var buffer = ByteBuffer() buffer.writeRepeatingByte(0, count: 9) buffer.moveReaderIndex(forwardBy: 9) try! hpackEncoder.encode(headers: headers, to: &buffer) let encodedLength = buffer.readableBytes buffer.moveReaderIndex(to: buffer.readerIndex - 9) // UInt24 length buffer.setInteger(UInt8(0), at: buffer.readerIndex) buffer.setInteger(UInt16(encodedLength), at: buffer.readerIndex + 1) // Type buffer.setInteger(UInt8(0x01), at: buffer.readerIndex + 3) // Flags, turn on END_HEADERs. buffer.setInteger(UInt8(0x04), at: buffer.readerIndex + 4) // 4 byte stream identifier, set to zero for now as we update it later. buffer.setInteger(UInt32(0), at: buffer.readerIndex + 5) return buffer }() private let emptySettings: ByteBuffer = { var buffer = ByteBuffer() buffer.reserveCapacity(9) // UInt24 length, is 0 bytes. buffer.writeInteger(UInt8(0)) buffer.writeInteger(UInt16(0)) // Type buffer.writeInteger(UInt8(0x04)) // Flags, none. buffer.writeInteger(UInt8(0x00)) // 4 byte stream identifier, set to zero. buffer.writeInteger(UInt32(0)) return buffer }() private var settingsACK: ByteBuffer { // Copy the empty SETTINGS and add the ACK flag var settingsCopy = self.emptySettings settingsCopy.setInteger(UInt8(0x01), at: settingsCopy.readerIndex + 4) return settingsCopy } init(concurrentStreams: Int) { self.concurrentStreams = concurrentStreams } func setUp() throws { let channel = EmbeddedChannel() _ = try channel.configureHTTP2Pipeline(mode: .server) { streamChannel -> EventLoopFuture<Void> in return streamChannel.pipeline.addHandler(TestServer()) }.wait() try channel.connect(to: .init(unixDomainSocketPath: "/fake"), promise: nil) // Gotta do the handshake here. var initialBytes = ByteBuffer(string: "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n") initialBytes.writeImmutableBuffer(self.emptySettings) initialBytes.writeImmutableBuffer(self.settingsACK) try channel.writeInbound(initialBytes) while try channel.readOutbound(as: ByteBuffer.self) != nil { } self.channel = channel } func tearDown() { _ = try! self.channel!.finish() self.channel = nil } func run() throws -> Int { var bodyByteCount = 0 var completedIterations = 0 while completedIterations < 10_000 { bodyByteCount &+= try self.sendInterleavedRequests(self.concurrentStreams) completedIterations += self.concurrentStreams } return bodyByteCount } private func sendInterleavedRequests(_ interleavedRequests: Int) throws -> Int { var streamID = self.streamID for _ in 0 ..< interleavedRequests { self.headersFrame.setInteger(UInt32(Int32(streamID)), at: self.headersFrame.readerIndex + 5) try self.channel!.writeInbound(self.headersFrame) streamID = streamID.advanced(by: 2) } streamID = self.streamID for _ in 0 ..< interleavedRequests { self.dataFrame.setInteger(UInt32(Int32(streamID)), at: self.dataFrame.readerIndex + 5) try self.channel!.writeInbound(self.dataFrame) streamID = streamID.advanced(by: 2) } self.channel!.embeddedEventLoop.run() self.streamID = streamID var count = 0 while let data = try self.channel!.readOutbound(as: ByteBuffer.self) { count &+= data.readableBytes self.channel!.embeddedEventLoop.run() } return count } } fileprivate class TestServer: ChannelInboundHandler { public typealias InboundIn = HTTP2Frame.FramePayload public typealias OutboundOut = HTTP2Frame.FramePayload public func channelRead(context: ChannelHandlerContext, data: NIOAny) { let payload = self.unwrapInboundIn(data) switch payload { case .headers(let headers) where headers.endStream: self.sendResponse(context: context) case .data(let data) where data.endStream: self.sendResponse(context: context) default: () } } private func sendResponse(context: ChannelHandlerContext) { let responseHeaders = HPACKHeaders([(":status", "200"), ("server", "test-benchmark")]) let response = HTTP2Frame.FramePayload.headers(.init(headers: responseHeaders, endStream: false)) let responseData = HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(ByteBuffer()), endStream: true)) context.write(self.wrapOutboundOut(response), promise: nil) context.writeAndFlush(self.wrapOutboundOut(responseData), promise: nil) } }
apache-2.0
bdbeab0e7165c5c239f0f6de5a3b6068
34.581281
145
0.634224
4.466914
false
false
false
false
uasys/swift
test/IRGen/closure.swift
3
3394
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -primary-file %s -emit-ir | %FileCheck %s // REQUIRES: CPU=x86_64 // -- partial_apply context metadata // CHECK: [[METADATA:@.*]] = private constant %swift.full_boxmetadata { void (%swift.refcounted*)* @objectdestroy, i8** null, %swift.type { i64 64 }, i32 16, i8* bitcast ({ i32, i32, i32, i32 }* @"\01l__swift3_reflection_descriptor" to i8*) } func a(i i: Int) -> (Int) -> Int { return { x in i } } // -- Closure entry point // CHECK: define internal swiftcc i64 @_T07closure1aS2icSi1i_tFS2icfU_(i64, i64) protocol Ordinable { func ord() -> Int } func b<T : Ordinable>(seq seq: T) -> (Int) -> Int { return { i in i + seq.ord() } } // -- partial_apply stub // CHECK: define internal swiftcc i64 @_T07closure1aS2icSi1i_tFS2icfU_TA(i64, %swift.refcounted* swiftself) // CHECK: } // -- Closure entry point // CHECK: define internal swiftcc i64 @_T07closure1bS2icx3seq_tAA9OrdinableRzlFS2icfU_(i64, %swift.refcounted*, %swift.type* %T, i8** %T.Ordinable) {{.*}} { // -- partial_apply stub // CHECK: define internal swiftcc i64 @_T07closure1bS2icx3seq_tAA9OrdinableRzlFS2icfU_TA(i64, %swift.refcounted* swiftself) {{.*}} { // CHECK: entry: // CHECK: [[CONTEXT:%.*]] = bitcast %swift.refcounted* %1 to <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>* // CHECK: [[BINDINGSADDR:%.*]] = getelementptr inbounds <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>, <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>* [[CONTEXT]], i32 0, i32 1 // CHECK: [[TYPEADDR:%.*]] = bitcast [16 x i8]* [[BINDINGSADDR]] // CHECK: [[TYPE:%.*]] = load %swift.type*, %swift.type** [[TYPEADDR]], align 8 // CHECK: [[WITNESSADDR_0:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[TYPEADDR]], i32 1 // CHECK: [[WITNESSADDR:%.*]] = bitcast %swift.type** [[WITNESSADDR_0]] // CHECK: [[WITNESS:%.*]] = load i8**, i8*** [[WITNESSADDR]], align 8 // CHECK: [[BOXADDR:%.*]] = getelementptr inbounds <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>, <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>* [[CONTEXT]], i32 0, i32 2 // CHECK: [[BOX:%.*]] = load %swift.refcounted*, %swift.refcounted** [[BOXADDR]], align 8 // CHECK: call %swift.refcounted* @swift_rt_swift_retain(%swift.refcounted* returned [[BOX]]) // CHECK: call void @swift_rt_swift_release(%swift.refcounted* %1) // CHECK: [[RES:%.*]] = tail call swiftcc i64 @_T07closure1bS2icx3seq_tAA9OrdinableRzlFS2icfU_(i64 %0, %swift.refcounted* [[BOX]], %swift.type* [[TYPE]], i8** [[WITNESS]]) // CHECK: ret i64 [[RES]] // CHECK: } // -- <rdar://problem/14443343> Boxing of tuples with generic elements // CHECK: define hidden swiftcc { i8*, %swift.refcounted* } @_T07closure14captures_tuplex_q_tycx_q_t1x_tr0_lF(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T, %swift.type* %U) func captures_tuple<T, U>(x x: (T, U)) -> () -> (T, U) { // CHECK: [[METADATA:%.*]] = call %swift.type* @swift_getTupleTypeMetadata2(%swift.type* %T, %swift.type* %U, i8* null, i8** null) // CHECK-NOT: @swift_getTupleTypeMetadata2 // CHECK: [[BOX:%.*]] = call { %swift.refcounted*, %swift.opaque* } @swift_allocBox(%swift.type* [[METADATA]]) // CHECK: [[ADDR:%.*]] = extractvalue { %swift.refcounted*, %swift.opaque* } [[BOX]], 1 // CHECK: bitcast %swift.opaque* [[ADDR]] to <{}>* return {x} }
apache-2.0
ac0cf243b5581dbcbaec3532f10bf389
57.517241
242
0.643194
3.122355
false
false
false
false
breadwallet/breadwallet-ios
breadwallet/src/ViewControllers/AssetListTableView.swift
1
8098
// // AssetListTableView.swift // breadwallet // // Created by Adrian Corscadden on 2017-12-04. // Copyright © 2017-2019 Breadwinner AG. All rights reserved. // import UIKit class AssetListTableView: UITableViewController, Subscriber { var didSelectCurrency: ((Currency) -> Void)? var didTapAddWallet: (() -> Void)? let loadingSpinner = UIActivityIndicatorView(style: .white) private let assetHeight: CGFloat = 80.0 // rowHeight of 72 plus 8 padding private let addWalletButtonHeight: CGFloat = 56.0 private let addWalletButton = UIButton() // MARK: - Init init() { super.init(style: .plain) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if Store.state.wallets.isEmpty { showLoadingState(true) } } override func viewDidLayoutSubviews() { setupAddWalletButton() } override func viewDidLoad() { super.viewDidLoad() tableView.backgroundColor = .darkBackground tableView.register(HomeScreenCell.self, forCellReuseIdentifier: HomeScreenCellIds.regularCell.rawValue) tableView.register(HomeScreenHiglightableCell.self, forCellReuseIdentifier: HomeScreenCellIds.highlightableCell.rawValue) tableView.separatorStyle = .none tableView.rowHeight = assetHeight tableView.contentInset = UIEdgeInsets(top: C.padding[1], left: 0, bottom: C.padding[2], right: 0) setupSubscriptions() reload() } private func setupAddWalletButton() { guard tableView.tableFooterView == nil else { return } let topInset: CGFloat = 0 let leftRightInset: CGFloat = C.padding[1] let width = tableView.frame.width - tableView.contentInset.left - tableView.contentInset.right let footerView = UIView(frame: CGRect(x: 0, y: 0, width: width, height: addWalletButtonHeight)) addWalletButton.titleLabel?.font = Theme.body1 addWalletButton.tintColor = Theme.tertiaryBackground addWalletButton.setTitleColor(Theme.tertiaryText, for: .normal) addWalletButton.setTitleColor(.transparentWhite, for: .highlighted) addWalletButton.titleLabel?.font = Theme.body1 addWalletButton.imageView?.contentMode = .scaleAspectFit addWalletButton.setBackgroundImage(UIImage(named: "add"), for: .normal) addWalletButton.contentHorizontalAlignment = .center addWalletButton.contentVerticalAlignment = .center let buttonTitle = S.MenuButton.manageWallets addWalletButton.setTitle(buttonTitle, for: .normal) addWalletButton.accessibilityLabel = E.isScreenshots ? "Manage Wallets" : buttonTitle addWalletButton.addTarget(self, action: #selector(addWallet), for: .touchUpInside) addWalletButton.frame = CGRect(x: leftRightInset, y: topInset, width: footerView.frame.width - (2 * leftRightInset), height: addWalletButtonHeight) footerView.addSubview(addWalletButton) footerView.backgroundColor = .darkBackground tableView.tableFooterView = footerView } private func setupSubscriptions() { Store.lazySubscribe(self, selector: { var result = false let oldState = $0 let newState = $1 $0.wallets.values.map { $0.currency }.forEach { currency in if oldState[currency]?.balance != newState[currency]?.balance || oldState[currency]?.currentRate?.rate != newState[currency]?.currentRate?.rate { result = true } } return result }, callback: { _ in self.reload() }) Store.lazySubscribe(self, selector: { $0.currencies.map { $0.code } != $1.currencies.map { $0.code } }, callback: { _ in self.reload() }) } @objc func addWallet() { didTapAddWallet?() } func reload() { tableView.reloadData() showLoadingState(false) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Data Source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return Store.state.currencies.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let currency = Store.state.currencies[indexPath.row] let viewModel = HomeScreenAssetViewModel(currency: currency) let cellIdentifier = (shouldHighlightCell(for: currency) ? HomeScreenCellIds.highlightableCell : HomeScreenCellIds.regularCell).rawValue let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) if let highlightable: HighlightableCell = cell as? HighlightableCell { handleCellHighlightingOnDisplay(cell: highlightable, currency: currency) } if let cell = cell as? HomeScreenCell { cell.set(viewModel: viewModel) } return cell } // MARK: - Delegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let currency = Store.state.currencies[indexPath.row] // If a currency has a wallet, home screen cells are always tap-able // Also, if HBAR account creation is required, it is also tap-able guard (currency.wallet != nil) || //Only an HBAR wallet requiring creation can go to the account screen without a wallet (currency.isHBAR && Store.state.requiresCreation(currency)) else { return } didSelectCurrency?(currency) handleCellHighlightingOnSelect(indexPath: indexPath, currency: currency) } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return assetHeight } } // loading state management extension AssetListTableView { func showLoadingState(_ show: Bool) { showLoadingIndicator(show) showAddWalletsButton(!show) } func showLoadingIndicator(_ show: Bool) { guard show else { loadingSpinner.removeFromSuperview() return } view.addSubview(loadingSpinner) loadingSpinner.constrain([ loadingSpinner.centerXAnchor.constraint(equalTo: view.centerXAnchor), loadingSpinner.centerYAnchor.constraint(equalTo: view.centerYAnchor)]) loadingSpinner.startAnimating() } func showAddWalletsButton(_ show: Bool) { addWalletButton.isHidden = !show } } // cell highlighting extension AssetListTableView { func shouldHighlightCell(for currency: Currency) -> Bool { // Currently the only currency/wallet we highlight is BRD. guard currency.isBRDToken else { return false } return UserDefaults.shouldShowBRDCellHighlight } func clearShouldHighlightForCurrency(currency: Currency) { guard currency.isBRDToken else { return } UserDefaults.shouldShowBRDCellHighlight = false } func handleCellHighlightingOnDisplay(cell: HighlightableCell, currency: Currency) { guard shouldHighlightCell(for: currency) else { return } cell.highlight() } func handleCellHighlightingOnSelect(indexPath: IndexPath, currency: Currency) { guard shouldHighlightCell(for: currency) else { return } guard let highlightable: HighlightableCell = tableView.cellForRow(at: indexPath) as? HighlightableCell else { return } highlightable.unhighlight() clearShouldHighlightForCurrency(currency: currency) } }
mit
11e529b6032135c2486feb182f95bf4b
35.147321
144
0.649376
5.111742
false
false
false
false
think-dev/MadridBUS
MadridBUS/Source/UI/Commons/Infrastructure/Wireframe.swift
1
2337
import Foundation import UIKit protocol Wireframe { func setFrom(view: Any) func pushTo(view: UIViewController) func pushTo(view: UIViewController, completion: (() -> ())?) func pushTo(view: UIViewController, params: [String: Any]) func pushTo(view: UIViewController, params: [String: Any], completion: (() -> ())?) func present(controller: UIViewController, completion: @escaping (() -> ())) func present(controller: UIViewController) func pop(animated: Bool) } class WireframeBase: Wireframe { private var from: UIViewController! func setFrom(view: Any) { guard let viewController = view as? UIViewController else { fatalError("\(view) is not an UIViewController") } self.from = viewController } func pushTo(view: UIViewController) { DispatchQueue.main.async { self.from.show(view, sender: self.from) } } func pushTo(view: UIViewController, completion: (() -> ())?) { DispatchQueue.main.async { self.from.show(view, sender: self.from, completion: completion) } } func pushTo(view: UIViewController, params: [String: Any]) { guard let viewController = view as? ParameterizedView else { fatalError("\(view) doesn't conform ParameterizedView protocol") } viewController.params = params pushTo(view: view) } func pushTo(view: UIViewController, params: [String: Any], completion: (() -> ())?) { guard let viewController = view as? ParameterizedView else { fatalError("\(view) doesn't conform ParameterizedView protocol") } viewController.params = params pushTo(view: view, completion: completion) } func present(controller: UIViewController, completion: @escaping (() -> ())) { DispatchQueue.main.async { self.from.present(controller, animated: true, completion: completion) } } func present(controller: UIViewController) { DispatchQueue.main.async { self.from.present(controller, animated: true, completion: nil) } } func pop(animated: Bool) { _ = from.navigationController?.popViewController(animated: animated) } }
mit
b2d623ca1636b635a32fef1622a09115
30.581081
89
0.616175
4.940803
false
false
false
false
iot-spotted/spotted
Source/EVCloudKitEnums.swift
2
4062
// // EVCloudKitEnums.swift // // Created by Edwin Vermeer on 12/5/15. // Copyright © 2015 mirabeau. All rights reserved. // // ------------------------------------------------------------------------ // MARK: - EVCloudKitDao enums // ------------------------------------------------------------------------ /** Wrapper class for being able to use a class instance Dictionary */ internal class DaoContainerWrapper { /** Wrapping the public containers */ var publicContainers : Dictionary<String,EVCloudKitDao> = Dictionary<String,EVCloudKitDao>() /** Wrapping the private containers */ var privateContainers : Dictionary<String,EVCloudKitDao> = Dictionary<String,EVCloudKitDao>() } /** The functional statuses for a CloudKit error */ public enum HandleCloudKitErrorAs { case success, retry(afterSeconds:Double), recoverableError, fail } /** Indicates if a dao is setup as private or public */ public enum InstanceType { case isPrivate, isPublic } // ------------------------------------------------------------------------ // MARK: - EVCloudKitData enums // ------------------------------------------------------------------------ /** The enum for specifying the caching strategy for the data */ public enum CachingStrategy { /** Do not cache this */ case none, /** Always write changes to the cache immediately */ direct, /** Only write to the cache once every .. minutes when there are changes (initial query result will always be written directly) */ every(minute:Int) } /** The enum for getting the notification key to subscribe to when observing changes */ public enum DataChangeNotificationType { /** Data retrieval is progressing/finished */ case completed, /** New item has been inserted */ inserted, /** Existing item has been updated */ updated, /** Notification of any data modification (completion, inserted, updated or deleted) */ dataChanged, /** Existing item has been deleted */ deleted, /** An error occurred while attempting a data operation */ error } /** The enum for determining the current state of data retrieval in the Completion handler and/or NSNotificationManager push notification */ public enum CompletionStatus: Int { /** The results were returned from the local cache */ case fromCache, /** The requested data wasn't found in the local cache. It will be requested from iCloud */ retrieving, /** Some data was received from iCloud, but more results are available if wanted (return true to request more results) */ partialResult, /** All available data has been successfully retrieved from iCloud */ finalResult } /** Strange enough by default Swift does not implement the Equality operator for enums. So we just made one ourselves. - parameter leftPart: The CachingStrategy value at the left of the equality operator. - parameter rightPart: The CachingStrategy value at the right of the equality operator. */ func ==(leftPart: CachingStrategy, rightPart: CachingStrategy) -> Bool { switch(leftPart) { case .none: switch(rightPart) { case .none: return true default: return false } case .direct: switch(rightPart) { case .direct: return true default: return false } case .every(let minutea): switch(rightPart) { case .every(let minuteb): return minutea == minuteb default: return false } } } /** Strange enough by default Swift does not implement the not Equality operator for enums. So we just made one ourselves. - parameter leftPart: The CachingStrategy value at the left of the equality operator. - parameter rightPart: The CachingStrategy value at the right of the equality operator. */ func !=(leftPart: CachingStrategy, rightPart: CachingStrategy) -> Bool { return !(leftPart == rightPart) }
bsd-3-clause
8a690adab9475bd7e55220fbb8f758a8
24.702532
134
0.624969
4.744159
false
false
false
false
AboutObjectsTraining/Swift4Examples
Model.playground/Contents.swift
1
843
import Foundation import Model let item1 = Garment.tie // Overloaded implementation of Equatable item1 == Garment.tie let pants1 = Garment.pants(waist: 32, inseam: 34) let pants2 = Garment.pants(waist: 32, inseam: 34) let pants3 = Garment.pants(waist: 33, inseam: 35) pants1 == pants2 pants1 == pants3 let foo = Apparel.tie let jacket1 = Apparel.jacket(size: .small) let jacket2 = Apparel.jacket(size: .small) // Compile error: no overload of == for type Apparel // // jacket1 == jacket2 if case let Apparel.jacket(size1) = jacket1, case let Apparel.jacket(size2) = jacket2, size1 == size2 { print("Same size jacket") } let size = "Large" var larges = 0 var extraLarges = 0 switch size { case "Large": larges += 1 case "Extra Large": extraLarges += 1 default: print("No match") } if case "Large" = size { larges += 1 }
mit
720284961d973b5d083cfd0d1f6a3576
19.071429
52
0.692764
2.67619
false
false
false
false
padawan/smartphone-app
MT_iOS/MT_iOS/Classes/ViewController/PageDraftTableViewController.swift
1
4279
// // PageDraftTableViewController.swift // MT_iOS // // Created by CHEEBOW on 2015/06/11. // Copyright (c) 2015年 Six Apart, Ltd. All rights reserved. // import UIKit class PageDraftTableViewController: BaseDraftTableViewController { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() self.title = NSLocalizedString("Pages of unsent", comment: "Pages of unsent") let user = (UIApplication.sharedApplication().delegate as! AppDelegate).currentUser! if self.blog.canCreatePage(user: user) { self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "btn_newentry"), left: false, target: self, action: "composeButtonPushed:") } else { self.navigationItem.rightBarButtonItem = nil } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as! UITableViewCell // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ // MARK: - Table view delegte override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let filename = self.files[indexPath.row] let dir = self.dataDir() let path = dir.stringByAppendingPathComponent(filename) let item = EntryItemList.loadFromFile(path, filename: filename) item.blog = blog let app = UIApplication.sharedApplication().delegate as! AppDelegate let vc = PageDetailTableViewController() vc.list = item vc.object = item.object vc.blog = blog self.navigationController?.pushViewController(vc, animated: true) } //MARK: - func composeButtonPushed(sender: UIBarButtonItem) { let app = UIApplication.sharedApplication().delegate as! AppDelegate app.createPage(self.blog, controller: self) } }
mit
b817ea6d3f4d8130e27bed928a4a6ebc
36.191304
166
0.680617
5.339576
false
false
false
false
xcodeswift/xcproj
Sources/XcodeProj/Utils/CommentedString.swift
1
2238
import Foundation import XcodeProjCExt /// String that includes a comment struct CommentedString { /// Entity string value. let string: String /// String comment. let comment: String? /// Initializes the commented string with the value and the comment. /// /// - Parameters: /// - string: string value. /// - comment: comment. init(_ string: String, comment: String? = nil) { self.string = string self.comment = comment } /// Set of characters that are invalid. private static var invalidCharacters: CharacterSet = { var invalidSet = CharacterSet(charactersIn: "_$") invalidSet.insert(charactersIn: UnicodeScalar(".") ... UnicodeScalar("9")) invalidSet.insert(charactersIn: UnicodeScalar("A") ... UnicodeScalar("Z")) invalidSet.insert(charactersIn: UnicodeScalar("a") ... UnicodeScalar("z")) invalidSet.invert() return invalidSet }() /// Substrings that cause Xcode to quote the string content. private let invalidStrings = [ "___", "//", ] /// Returns a valid string for Xcode projects. var validString: String { switch string { case "": return "".quoted case "false": return "NO" case "true": return "YES" default: break } return string.withCString { buffer in let esc = XCPEscapedString(buffer)! let newString = String(cString: esc) free(UnsafeMutableRawPointer(mutating: esc)) return newString } } } // MARK: - Hashable extension CommentedString: Hashable { public func hash(into hasher: inout Hasher) { hasher.combine(string) } static func == (lhs: CommentedString, rhs: CommentedString) -> Bool { lhs.string == rhs.string && lhs.comment == rhs.comment } } // MARK: - ExpressibleByStringLiteral extension CommentedString: ExpressibleByStringLiteral { public init(stringLiteral value: String) { self.init(value) } public init(extendedGraphemeClusterLiteral value: String) { self.init(value) } public init(unicodeScalarLiteral value: String) { self.init(value) } }
mit
6d3e9baf7023c841d01ae082139cac82
26.292683
82
0.618856
4.792291
false
false
false
false
jexwang/DateSelector
DateSelector/DateSelector.swift
1
27403
// // DateSelector.swift // DateSelector // // Created by Jay on 2017/9/30. // // import UIKit open class DateSelectorViewController: UIViewController { open let date: Date required public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?, date: Date) { self.date = date super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } @objc public protocol DateSelectorDelegate { @objc optional func dateSelectorSetViewController() -> DateSelectorViewController.Type @objc optional func dateSelector(willChange oldDate: Date, to newDate: Date) @objc optional func dateSelector(didChange oldDate: Date, to newDate: Date) } @IBDesignable open class DateSelector: UIView, DateSelectorViewDelegate { @IBInspectable open var themeColor: UIColor! { didSet { backgroundColor = themeColor } } @IBInspectable open var textColor: UIColor = .black @IBInspectable open var dateFormat: String = "yyyy-M-d (eeeee)" fileprivate var date: Date = Date() { willSet { delegate?.dateSelector?(willChange: date, to: newValue) } didSet { dateButton.setTitle(dateConvertToString(), for: .normal) delegate?.dateSelector?(didChange: oldValue, to: date) } } @IBOutlet weak open var delegate: DateSelectorDelegate? @IBOutlet weak var containerCollectionView: DateSelectorCollectionView? private var prevDateButton: UIButton! private var prevDateButtonSetting: (title: String?, image: UIImage?) = ("<", nil) private var nextDateButton: UIButton! private var nextDateButtonSetting: (title: String?, image: UIImage?) = (">", nil) private var dateButton: UIButton! private var dateSelectorView: DateSelectorView! fileprivate var dateSelectorMaskView: UIView! fileprivate var cancelButtonSetting: (title: String?, image: UIImage?) = ("Cancel", nil) fileprivate var doneButtonSetting: (title: String?, image: UIImage?) = ("Done", nil) fileprivate var titleLabelSetting: String? = "Select Date" fileprivate var todayButtonSetting: (title: String?, textColor: UIColor?, image: UIImage?) = ("Today", nil, nil) fileprivate var locale: String? public override init(frame: CGRect) { super.init(frame: frame) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) NotificationCenter.default.addObserver(self, selector: #selector(adjustContainerCollectionViewFlowLayout), name: Notification.Name.UIDeviceOrientationDidChange, object: nil) } deinit { NotificationCenter.default.removeObserver(self, name: Notification.Name.UIDeviceOrientationDidChange, object: nil) } override open func draw(_ rect: CGRect) { super.draw(rect) prevDateButtonInit() nextDateButtonInit() dateButtonInit() dateSelectorViewInit() dateSelectorMaskViewInit() } @objc private func adjustContainerCollectionViewFlowLayout() { if let containerCollectionView = containerCollectionView { let flowLayout = containerCollectionView.collectionViewLayout as! UICollectionViewFlowLayout flowLayout.itemSize = containerCollectionView.frame.size containerCollectionView.scrollToItem(at: IndexPath(item: 1, section: 0), at: .centeredHorizontally, animated: false) } } open func setLocale(identifier: String) { locale = identifier } private func prevDateButtonInit() { prevDateButton = UIButton() prevDateButton.setTitle(prevDateButtonSetting.title, for: .normal) prevDateButton.setTitleColor(textColor, for: .normal) prevDateButton.setImage(prevDateButtonSetting.image, for: .normal) prevDateButton.addTarget(self, action: #selector(prevDateButtonClick), for: .touchUpInside) addSubview(prevDateButton) prevDateButton.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint(item: prevDateButton, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: prevDateButton, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: prevDateButton, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0).isActive = true if frame.height < frame.width / 4 { NSLayoutConstraint(item: prevDateButton, attribute: .width, relatedBy: .equal, toItem: self, attribute: .height, multiplier: 1, constant: 0).isActive = true } else { NSLayoutConstraint(item: prevDateButton, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 0.25, constant: 0).isActive = true } } @objc private func prevDateButtonClick() { if let newDate = Calendar(identifier: .gregorian).date(byAdding: .day, value: -1, to: date) { date = newDate } if let containerCollectionView = containerCollectionView { containerCollectionView.prevDate() } } open func setPrevDateButton(title: String?, image: UIImage?) { prevDateButtonSetting = (title, image) } private func nextDateButtonInit() { nextDateButton = UIButton() nextDateButton.setTitle(nextDateButtonSetting.title, for: .normal) nextDateButton.setTitleColor(textColor, for: .normal) nextDateButton.setImage(nextDateButtonSetting.image, for: .normal) nextDateButton.addTarget(self, action: #selector(nextDateButtonClick), for: .touchUpInside) addSubview(nextDateButton) nextDateButton.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint(item: nextDateButton, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: nextDateButton, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: nextDateButton, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0).isActive = true if frame.height < frame.width / 4 { NSLayoutConstraint(item: nextDateButton, attribute: .width, relatedBy: .equal, toItem: self, attribute: .height, multiplier: 1, constant: 0).isActive = true } else { NSLayoutConstraint(item: nextDateButton, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 0.25, constant: 0).isActive = true } } @objc private func nextDateButtonClick() { if let newDate = Calendar(identifier: .gregorian).date(byAdding: .day, value: 1, to: date) { date = newDate } if let containerCollectionView = containerCollectionView { containerCollectionView.nextDate() } } open func setNextDateButton(title: String?, image: UIImage?) { nextDateButtonSetting = (title, image) } private func dateButtonInit() { dateButton = UIButton() dateButton.setTitle(dateConvertToString(), for: .normal) dateButton.setTitleColor(textColor, for: .normal) dateButton.addTarget(self, action: #selector(dateButtonClick), for: .touchUpInside) addSubview(dateButton) dateButton.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint(item: dateButton, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: dateButton, attribute: .left, relatedBy: .equal, toItem: prevDateButton, attribute: .right, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: dateButton, attribute: .right, relatedBy: .equal, toItem: nextDateButton, attribute: .left, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: dateButton, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0).isActive = true } @objc private func dateButtonClick() { guard let window = UIApplication.shared.delegate?.window as? UIWindow else { return } guard let view = window.rootViewController?.view else { return } view.addSubview(dateSelectorMaskView) dateSelectorMaskView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint(item: dateSelectorMaskView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: dateSelectorMaskView, attribute: .left, relatedBy: .equal, toItem: view, attribute: .left, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: dateSelectorMaskView, attribute: .right, relatedBy: .equal, toItem: view, attribute: .right, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: dateSelectorMaskView, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0).isActive = true view.bringSubview(toFront: dateSelectorView) dateSelectorView.isHidden = false UIView.animate(withDuration: 0.2) { self.dateSelectorView.transform = CGAffineTransform(translationX: 0, y: -self.dateSelectorView.frame.height) } } private func dateSelectorViewInit() { guard let window = UIApplication.shared.delegate?.window as? UIWindow else { return } guard let view = window.rootViewController?.view else { return } dateSelectorView = DateSelectorView(frame: CGRect(x:0, y: UIScreen.main.bounds.maxY, width: UIScreen.main.bounds.width, height: 306)) dateSelectorView.delegate = self dateSelectorView.backgroundColor = .white dateSelectorView.isHidden = true view.addSubview(dateSelectorView) dateSelectorView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint(item: dateSelectorView, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: dateSelectorView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 306).isActive = true NSLayoutConstraint(item: dateSelectorView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: dateSelectorView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0).isActive = true } open func setCancelButton(title: String?, image: UIImage?) { cancelButtonSetting = (title, image) } open func setDoneButton(title: String?, image: UIImage?) { doneButtonSetting = (title, image) } open func setTitleLabel(title: String) { titleLabelSetting = title } open func setTodayButton(title: String?, titleColor: UIColor?, image: UIImage?) { todayButtonSetting = (title, titleColor, image) } private func dateSelectorMaskViewInit() { dateSelectorMaskView = UIView() dateSelectorMaskView?.backgroundColor = UIColor(white: 0, alpha: 0.6) dateSelectorMaskView?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(dateSelectorMaskViewTap))) } @objc private func dateSelectorMaskViewTap() { UIView.animate(withDuration: 0.2, animations: { self.dateSelectorView.transform = .identity }) { _ in self.dateSelectorView.isHidden = true self.dateSelectorMaskView?.removeFromSuperview() } } private func dateConvertToString() -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = dateFormat if let locale = locale { dateFormatter.locale = Locale(identifier: locale) } return dateFormatter.string(from: date) } open func getDate() -> Date { return date } } extension DateSelector: UICollectionViewDataSource, UICollectionViewDelegate { public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 3 } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! DateSelectorCollectionViewCell return cell } public func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { if let cell = cell as? DateSelectorCollectionViewCell, let viewController = delegate?.dateSelectorSetViewController?() { switch indexPath.item { case 0: if let newDate = Calendar(identifier: .gregorian).date(byAdding: .day, value: -1, to: date) { cell.viewController = viewController.init(nibName: String(describing: viewController), bundle: nil, date: newDate) } case 1: cell.viewController = viewController.init(nibName: String(describing: viewController), bundle: nil, date: date) case 2: if let newDate = Calendar(identifier: .gregorian).date(byAdding: .day, value: 1, to: date) { cell.viewController = viewController.init(nibName: String(describing: viewController), bundle: nil, date: newDate) } default: break } } } public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { guard let dateSelectorCollectionView = scrollView as? DateSelectorCollectionView else { return } let visibleItems = dateSelectorCollectionView.indexPathsForVisibleItems var visibleItem: IndexPath if visibleItems.count > 1 { visibleItem = visibleItems.first(where: { (indexPath) -> Bool in return indexPath.row != 1 })! } else { visibleItem = visibleItems.first! } switch visibleItem.row { case 0: if let newDate = Calendar(identifier: .gregorian).date(byAdding: .day, value: -1, to: date) { date = newDate } UIView.setAnimationsEnabled(false) dateSelectorCollectionView.performBatchUpdates({ dateSelectorCollectionView.deleteItems(at: [IndexPath(item: 2, section: 0)]) dateSelectorCollectionView.insertItems(at: [IndexPath(item: 0, section: 0)]) dateSelectorCollectionView.scrollToItem(at: IndexPath(item: 1, section: 0), at: .centeredHorizontally, animated: false) }, completion: { _ in UIView.setAnimationsEnabled(true) }) case 2: if let newDate = Calendar(identifier: .gregorian).date(byAdding: .day, value: 1, to: date) { date = newDate } UIView.setAnimationsEnabled(false) dateSelectorCollectionView.performBatchUpdates({ dateSelectorCollectionView.deleteItems(at: [IndexPath(item: 0, section: 0)]) dateSelectorCollectionView.insertItems(at: [IndexPath(item: 2, section: 0)]) dateSelectorCollectionView.scrollToItem(at: IndexPath(item: 1, section: 0), at: .centeredHorizontally, animated: false) }, completion: { _ in UIView.setAnimationsEnabled(true) }) default: break } } } fileprivate protocol DateSelectorViewDelegate { var themeColor: UIColor! { get } var textColor: UIColor { get } var date: Date { get set } var containerCollectionView: DateSelectorCollectionView? { get } var dateSelectorMaskView: UIView! { get set } var cancelButtonSetting: (title: String?, image: UIImage?) { get } var doneButtonSetting: (title: String?, image: UIImage?) { get } var titleLabelSetting: String? { get } var todayButtonSetting: (title: String?, textColor: UIColor?, image: UIImage?) { get } var locale: String? { get } } fileprivate class DateSelectorView: UIView { fileprivate var delegate: DateSelectorViewDelegate? private var toolbarView: UIView! private var cancelButton: UIButton! private var doneButton: UIButton! private var todayButton: UIButton! private var datePicker: UIDatePicker! override func draw(_ rect: CGRect) { super.draw(rect) toolbarViewInit() cancelButtonInit() doneButtonInit() titleLabelInit() todayButtonInit() datePickerInit() } private func toolbarViewInit() { toolbarView = UIView() toolbarView.backgroundColor = delegate?.themeColor addSubview(toolbarView) toolbarView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint(item: toolbarView, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: toolbarView, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: toolbarView, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: toolbarView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 50).isActive = true } private func cancelButtonInit() { cancelButton = UIButton() cancelButton.setTitle(delegate?.cancelButtonSetting.title, for: .normal) cancelButton.setTitleColor(delegate?.textColor, for: .normal) cancelButton.setImage(delegate?.cancelButtonSetting.image, for: .normal) cancelButton.addTarget(self, action: #selector(cancelButtonClick), for: .touchUpInside) toolbarView.addSubview(cancelButton) cancelButton.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint(item: cancelButton, attribute: .top, relatedBy: .equal, toItem: toolbarView, attribute: .top, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: cancelButton, attribute: .left, relatedBy: .equal, toItem: toolbarView, attribute: .left, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: cancelButton, attribute: .bottom, relatedBy: .equal, toItem: toolbarView, attribute: .bottom, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: cancelButton, attribute: .width, relatedBy: .equal, toItem: toolbarView, attribute: .height, multiplier: 1.5, constant: 0).isActive = true } @objc private func cancelButtonClick() { putDownDateSelectorView() } private func doneButtonInit() { doneButton = UIButton() doneButton.setTitle(delegate?.doneButtonSetting.title, for: .normal) doneButton.setTitleColor(delegate?.textColor, for: .normal) doneButton.setImage(delegate?.doneButtonSetting.image, for: .normal) doneButton.addTarget(self, action: #selector(doneButtonClick), for: .touchUpInside) toolbarView.addSubview(doneButton) doneButton.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint(item: doneButton, attribute: .top, relatedBy: .equal, toItem: toolbarView, attribute: .top, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: doneButton, attribute: .right, relatedBy: .equal, toItem: toolbarView, attribute: .right, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: doneButton, attribute: .bottom, relatedBy: .equal, toItem: toolbarView, attribute: .bottom, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: doneButton, attribute: .width, relatedBy: .equal, toItem: toolbarView, attribute: .height, multiplier: 1.5, constant: 0).isActive = true } @objc private func doneButtonClick() { delegate?.date = datePicker.date if let containerCollectionView = delegate?.containerCollectionView { containerCollectionView.selectedDate() } putDownDateSelectorView() } private func titleLabelInit() { let titleLabel = UILabel() titleLabel.text = delegate?.titleLabelSetting titleLabel.textColor = delegate?.textColor titleLabel.textAlignment = .center toolbarView.addSubview(titleLabel) titleLabel.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint(item: titleLabel, attribute: .top, relatedBy: .equal, toItem: toolbarView, attribute: .top, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: titleLabel, attribute: .left, relatedBy: .equal, toItem: cancelButton, attribute: .right, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: titleLabel, attribute: .right, relatedBy: .equal, toItem: doneButton, attribute: .left, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: titleLabel, attribute: .bottom, relatedBy: .equal, toItem: toolbarView, attribute: .bottom, multiplier: 1, constant: 0).isActive = true } private func todayButtonInit() { todayButton = UIButton(type: .system) todayButton.setTitle(delegate?.todayButtonSetting.title, for: .normal) todayButton.setTitleColor(delegate?.todayButtonSetting.textColor, for: .normal) todayButton.setImage(delegate?.todayButtonSetting.image, for: .normal) todayButton.addTarget(self, action: #selector(todayButtonClick), for: .touchUpInside) addSubview(todayButton) todayButton.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint(item: todayButton, attribute: .top, relatedBy: .equal, toItem: toolbarView, attribute: .bottom, multiplier: 1, constant: 10).isActive = true NSLayoutConstraint(item: todayButton, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: todayButton, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: todayButton, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 30).isActive = true } @objc private func todayButtonClick() { if let datePicker = datePicker { datePicker.setDate(Date(), animated: true) } } private func datePickerInit() { datePicker = UIDatePicker() datePicker.datePickerMode = .date if let locale = delegate?.locale { datePicker.locale = Locale(identifier: locale) } addSubview(datePicker) datePicker.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint(item: datePicker, attribute: .top, relatedBy: .equal, toItem: todayButton, attribute: .bottom, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: datePicker, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: datePicker, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: datePicker, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0).isActive = true } private func putDownDateSelectorView() { UIView.animate(withDuration: 0.2, animations: { self.transform = .identity }) { _ in self.isHidden = true self.delegate?.dateSelectorMaskView?.removeFromSuperview() } } } open class DateSelectorCollectionView: UICollectionView { @IBOutlet weak open var dateSelector: DateSelector? { didSet { dataSource = dateSelector delegate = dateSelector reloadData() } } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) register(DateSelectorCollectionViewCell.self, forCellWithReuseIdentifier: "Cell") isPagingEnabled = true showsHorizontalScrollIndicator = false bounces = false scrollsToTop = false } open override func draw(_ rect: CGRect) { super.draw(rect) let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout flowLayout.itemSize = rect.size flowLayout.minimumLineSpacing = 0 flowLayout.scrollDirection = .horizontal scrollToItem(at: IndexPath(item: 1, section: 0), at: .centeredHorizontally, animated: false) } @objc internal func prevDate() { performBatchUpdates({ self.deleteItems(at: [IndexPath(item: 2, section: 0)]) self.insertItems(at: [IndexPath(item: 0, section: 0)]) }, completion: nil) } @objc internal func nextDate() { performBatchUpdates({ self.deleteItems(at: [IndexPath(item: 0, section: 0)]) self.insertItems(at: [IndexPath(item: 2, section: 0)]) }, completion: nil) } @objc internal func selectedDate() { reloadData() } } private class DateSelectorCollectionViewCell: UICollectionViewCell { var viewController: DateSelectorViewController? { didSet { view = viewController!.view! } } private var view: UIView? { willSet { if let view = view { view.removeFromSuperview() } } didSet { view!.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(view!) NSLayoutConstraint(item: view!, attribute: .top, relatedBy: .equal, toItem: contentView, attribute: .top, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: view!, attribute: .left, relatedBy: .equal, toItem: contentView, attribute: .left, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: view!, attribute: .right, relatedBy: .equal, toItem: contentView, attribute: .right, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: view!, attribute: .bottom, relatedBy: .equal, toItem: contentView, attribute: .bottom, multiplier: 1, constant: 0).isActive = true } } }
mit
e16010753fab6da7d49a87c9d35eac61
48.285971
181
0.67416
4.962514
false
false
false
false
thehorbach/instagram-clone
instagram-clone/FancyButton.swift
1
579
// // FancyButton.swift // instagram-clone // // Created by Vyacheslav Horbach on 21/09/16. // Copyright © 2016 Vjaceslav Horbac. All rights reserved. // import UIKit class FancyButton: RoundButton { override func awakeFromNib() { super.awakeFromNib() layer.shadowColor = UIColor(red: SHADOW_GRAY, green: SHADOW_GRAY, blue: SHADOW_GRAY, alpha: 0.6).cgColor layer.shadowOpacity = 0.8 layer.shadowRadius = 5 layer.shadowOffset = CGSize(width: 1.0, height: 0.0) self.layer.cornerRadius = 2.0 } }
mit
5a7daa525037ff066dfbbb62ffeed29d
24.130435
112
0.633218
3.658228
false
false
false
false
vinsan/presteasymo
presteasymo/presteasymo/RegistrationIIViewController.swift
1
1269
// // RegistrationIIViewController.swift // presteasymo // // Created by Pietro Russo on 06/04/17. // Copyright © 2017 Team 2.4. All rights reserved. // import UIKit class RegistrationIIViewController: UIViewController { @IBOutlet weak var batteria: UISlider! @IBOutlet weak var chitarra: UISlider! @IBOutlet weak var basso: UISlider! @IBOutlet weak var canto: UISlider! @IBOutlet weak var tastiera: UISlider! var reg=Registrazione() var user=User() 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. } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "registered" { reg.newUserAbility(ability: "Batteria", voto: 5, user: user) reg.newUserAbility(ability: "Canto", voto: 2, user: user) let nextWindow = segue.destination as! ProfileViewController nextWindow.user = user nextWindow.isLogged = true } } }
apache-2.0
986279067460e8ead0800d933dc21e92
25.416667
72
0.619874
4.496454
false
false
false
false
jerrypupu111/LearnDrawingToolSet
SwiftGL-Demo/Source/iOS/SubViewPanelAnimateState.swift
1
2575
// // SubViewPanelState.swift // SwiftGL // // Created by jerry on 2015/9/12. // Copyright © 2015年 Jerry Chan. All rights reserved. // import UIKit class SubViewPanelAnimateState { var hideValue:CGFloat! var showValue:CGFloat! weak var constraint:NSLayoutConstraint! weak var view:UIView? var isLocked:Bool = false init(view:UIView,constraint:NSLayoutConstraint,hideValue:CGFloat,showValue:CGFloat) { self.hideValue = hideValue self.showValue = showValue self.constraint = constraint self.view = view self.view!.isHidden = true } enum AnimateDir{ case x case y } var animateDir:AnimateDir! func registerPanMove(_ dir:AnimateDir) { animateDir = dir let viewPanGestureRecognizer = UIPanGestureRecognizer(target: self, action: "handlePan:") view!.addGestureRecognizer(viewPanGestureRecognizer) } func handlePan(_ sender:UIPanGestureRecognizer) { let delta = sender.translation(in: view) let vel = sender.velocity(in: view) switch sender.state { case UIGestureRecognizerState.changed: constraint.constant = delta.x if constraint.constant > 0 { constraint.constant = 0 } case .ended: if vel.x < -100 { print("hide", terminator: "") animateHide(0.2) } else { print("show", terminator: "") animateShow(0.2) } default: break } view!.layoutIfNeeded() } func xPan() { } func animateShow(_ dur:TimeInterval) { self.view!.isHidden = false animate(constraint,value: showValue,duration: dur,hidden: false) } func animateHide(_ dur:TimeInterval) { animate(constraint,value: hideValue,duration: dur,hidden: true) } func animate(_ constraint:NSLayoutConstraint,value:CGFloat,duration:TimeInterval,hidden:Bool = false) { UIView.setAnimationsEnabled(true) UIView.animate(withDuration: duration, delay: 0.0, options: UIViewAnimationOptions.curveLinear, animations: { constraint.constant = value }, completion: { (value: Bool) in self.view!.isHidden = hidden } ) } }
mit
e76dfc0057d5895bc235b83875811110
23.970874
117
0.554432
4.908397
false
false
false
false
bomjkolyadun/goeuro-test
GoEuro/GoEuro/ViewControllers/GESortViewController.swift
1
1905
// // GESortViewController.swift // GoEuro // // Created by Dmitry Osipa on 7/31/17. // Copyright © 2017 Dmitry Osipa. All rights reserved. // import UIKit enum SortType: String { case arrivalTime = "Arrival Time" case duration = "Trip Duration" case departure = "Departure Time" } protocol GESortViewControllerDelegate: NSObjectProtocol { func controller(controller: GESortViewController, didPick sort: SortType) } class GESortViewController: UITableViewController { static let sortCell = "kSortCell" let items: [SortType] = [.arrivalTime, .duration, .departure] private var selectedIndex = 0 weak open var delegate: GESortViewControllerDelegate? override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: GESortViewController.sortCell, for: indexPath) cell.textLabel?.text = items[indexPath.row].rawValue if indexPath.row == self.selectedIndex { cell.accessoryType = .checkmark } else { cell.accessoryType = .none } cell.selectionStyle = .none return cell; } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let prevIndex = selectedIndex let prevIndexPath = IndexPath(row: prevIndex, section: 0) selectedIndex = indexPath.row; self.tableView.beginUpdates() self.tableView.reloadRows(at: [indexPath, prevIndexPath], with: .none) self.tableView.endUpdates() self.delegate?.controller(controller: self, didPick: items[selectedIndex]) } func select(type: SortType) { self.selectedIndex = items.index(of: type)! } }
apache-2.0
6059a95bf4fdf937c0dcc567a961e4d3
31.271186
111
0.690651
4.565947
false
false
false
false
fgengine/quickly
Quickly/StringFormatter/QCardExpirationDateStringFormatter.swift
1
1451
// // Quickly // open class QCardExpirationDateStringFormatter : IQStringFormatter { public init() { } public func format(_ unformat: String) -> String { var format = String() var unformatOffset = 0 while unformatOffset < unformat.count { let unformatIndex = unformat.index(unformat.startIndex, offsetBy: unformatOffset) let unformatCharacter = unformat[unformatIndex] format.append(unformatCharacter) if unformatOffset == 1 { format.append("/") } unformatOffset += 1 } return format } public func format(_ unformat: String, caret: inout Int) -> String { let format = self.format(unformat) caret = self.formatDifferenceCaret( unformat: unformat, format: format, formatPrefix: 0, formatSuffix: 0, caret: caret ) return format } public func unformat(_ format: String) -> String { return format.replacingOccurrences(of: "/", with: "") } public func unformat(_ format: String, caret: inout Int) -> String { let unformat = self.unformat(format) caret = self.unformatDifferenceCaret( unformat: unformat, format: format, formatPrefix: 0, formatSuffix: 0, caret: caret ) return unformat } }
mit
9aba164203a66e9b5c7eccfc03895cdf
26.377358
93
0.56306
4.591772
false
false
false
false
uber/RIBs
ios/tutorials/tutorial4-completed/TicTacToe/LoggedIn/LoggedInBuilder.swift
1
2758
// // Copyright (c) 2017. Uber Technologies // // 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 RIBs protocol LoggedInDependency: Dependency { var loggedInViewController: LoggedInViewControllable { get } } final class LoggedInComponent: Component<LoggedInDependency> { fileprivate var loggedInViewController: LoggedInViewControllable { return dependency.loggedInViewController } fileprivate var games: [Game] { return shared { return [RandomWinAdapter(dependency: self), TicTacToeAdapter(dependency: self)] } } var mutableScoreStream: MutableScoreStream { return shared { ScoreStreamImpl() } } var scoreStream: ScoreStream { return mutableScoreStream } let player1Name: String let player2Name: String init(dependency: LoggedInDependency, player1Name: String, player2Name: String) { self.player1Name = player1Name self.player2Name = player2Name super.init(dependency: dependency) } } // MARK: - Builder protocol LoggedInBuildable: Buildable { func build(withListener listener: LoggedInListener, player1Name: String, player2Name: String) -> (router: LoggedInRouting, actionableItem: LoggedInActionableItem) } final class LoggedInBuilder: Builder<LoggedInDependency>, LoggedInBuildable { override init(dependency: LoggedInDependency) { super.init(dependency: dependency) } func build(withListener listener: LoggedInListener, player1Name: String, player2Name: String) -> (router: LoggedInRouting, actionableItem: LoggedInActionableItem) { let component = LoggedInComponent(dependency: dependency, player1Name: player1Name, player2Name: player2Name) let interactor = LoggedInInteractor(games: component.games) interactor.listener = listener let offGameBuilder = OffGameBuilder(dependency: component) let router = LoggedInRouter(interactor: interactor, viewController: component.loggedInViewController, offGameBuilder: offGameBuilder) return (router, interactor) } }
apache-2.0
b3f94dda0e0a0480dae926312742845d
34.358974
168
0.692168
4.788194
false
false
false
false
coodly/TalkToCloud
Sources/TalkToCloud/RecordsCursor.swift
1
1666
/* * Copyright 2016 Coodly LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation public struct RecordsCursor { internal let records: [Raw.Record] internal let deleted: [Raw.RecordID] internal let errors: [Raw.RecordError] public let moreComing: Bool public let syncToken: String public let continuation: (() -> Void)? public func records<T: CloudRecord>(of type: T.Type) -> [T] { Logging.verbose("Decode records named \(T.recordType)") let named = records.filter({ $0.recordType == T.recordType }) Logging.verbose("Have \(named.count) records") let decoder = RecordDecoder() var loaded = [T]() for record in named { do { decoder.record = record let decoded = try T(from: decoder) loaded.append(decoded) } catch { Logging.error(error) fatalError() } } return loaded } internal var hasRecordsWithAssets: Bool { records.map(\.containsAsset).filter({ $0 }).count > 0 } }
apache-2.0
348e70b1b990a7c4da96325efe926038
30.433962
75
0.617647
4.527174
false
false
false
false
MrSongzj/MSDouYuZB
MSDouYuZB/MSDouYuZB/Classes/Main/Model/TVCate.swift
1
741
// // TVCate.swift // MSDouYuZB // // Created by jiayuan on 2017/8/3. // Copyright © 2017年 mrsong. All rights reserved. // import UIKit class TVCate: BaseModel, TVCateProtocol { // 房间模型数组 var roomArr = [TVRoom]() // 该组中对应的房间信息 var room_list: [[String: Any]]? { didSet { guard let room_list = room_list else { return } for dict in room_list { roomArr.append(TVRoom(dict: dict)) } } } // 组标题 var tag_name = "" // 分类默认小图标 var icon_name = "home_header_normal" // 分类网络小图标 var small_icon_url = "" // 分类网络图标 var icon_url = "" }
mit
d4b35b36a046c4a6b67c495f40f44833
18.411765
59
0.525758
3.235294
false
false
false
false
100mango/SwiftNotificationCenter
SwiftNotificationCenterTests/SwiftNotificationCenterTests.swift
1
1423
// // SwiftNotificationCenterTests.swift // SwiftNotificationCenterTests // // Created by Mango on 16/5/5. // Copyright © 2016年 Mango. All rights reserved. // import XCTest @testable import SwiftNotificationCenter class SwiftNotificationCenterTests: XCTestCase { 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 testNotify() { let object = MockClass() Broadcaster.register(MockProtocol.self, observer: object) Broadcaster.notify(MockProtocol.self) { observer in let string = observer.hello() XCTAssertTrue(string == "hello") } } func testRemove() { let object = MockClass() Broadcaster.register(MockProtocol.self, observer: object) Broadcaster.unregister(MockProtocol.self, observer: object) Broadcaster.notify(MockProtocol.self) { observer in XCTFail() } XCTAssertTrue(true) } } protocol MockProtocol { func hello() -> String } extension MockProtocol { func hello() -> String { return "hello" } } class MockClass: MockProtocol { }
mit
ad05eea19ede3ff755d0a08f2accd037
23.482759
111
0.638028
4.493671
false
true
false
false
BigZhanghan/DouYuLive
DouYuLive/DouYuLive/Classes/Main/View/PageTitleView.swift
1
5001
// // PageTitleView.swift // DouYuLive // // Created by zhanghan on 2017/9/28. // Copyright © 2017年 zhanghan. All rights reserved. // import UIKit protocol PageTitleViewDelegate : class { func pageTitleView(titleView : PageTitleView, selectIndex index : Int) } private let ScrollLineH : CGFloat = 2 private let NormalColor : (CGFloat, CGFloat, CGFloat) = (85,85,85) private let SelectColor : (CGFloat, CGFloat, CGFloat) = (253,119,34) class PageTitleView: UIView { var titles : [String]; var currentIndex : Int = 0 weak var delegate : PageTitleViewDelegate? lazy var titleLabels : [UILabel] = [UILabel]() lazy var scrollView : UIScrollView = { let scrollView = UIScrollView(); scrollView.showsHorizontalScrollIndicator = false scrollView.bounces = false scrollView.scrollsToTop = false return scrollView }() lazy var scrollLine : UIView = { let scrollLine = UIView() scrollLine.backgroundColor = UIColor.mainColor() return scrollLine }() init(frame : CGRect, titles : [String]) { self.titles = titles; super.init(frame: frame); setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension PageTitleView { func setupUI() { addSubview(scrollView) scrollView.frame = bounds; setTitleLabels(); setupBottomLine() } private func setTitleLabels() { let labelW : CGFloat = frame.width / CGFloat(titles.count) let labelH : CGFloat = frame.height - ScrollLineH; let labelY : CGFloat = 0 for (index, title) in titles.enumerated() { let label = UILabel(); label.text = title label.tag = index label.font = UIFont.systemFont(ofSize: 16) label.textColor = UIColor(r: NormalColor.0, g: NormalColor.1, b: NormalColor.2) label.textAlignment = .center let labelX : CGFloat = CGFloat(index) * labelW label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH) scrollView.addSubview(label) titleLabels.append(label) label.isUserInteractionEnabled = true let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.titleLabelTap(tap:))) label.addGestureRecognizer(tapGesture) } } private func setupBottomLine() { let bottomLine = UIView() bottomLine.backgroundColor = UIColor.lightGray let lineH : CGFloat = 0.5 bottomLine.frame = CGRect(x: 0, y: frame.height - lineH, width: frame.width, height: lineH) addSubview(bottomLine) guard let firstLabel = titleLabels.first else { return } firstLabel.textColor = UIColor.mainColor() scrollView.addSubview(scrollLine) scrollLine.frame = CGRect(x: firstLabel.frame.origin.x, y:frame.height - ScrollLineH, width: firstLabel.frame.width, height: ScrollLineH) } } extension PageTitleView { func titleLabelTap(tap:UITapGestureRecognizer) { guard let currentLabel = tap.view as? UILabel else { return } //修复重复点击选中失效 if currentLabel.tag == currentIndex { return } let oldLabel = titleLabels[currentIndex] currentLabel.textColor = UIColor.mainColor() oldLabel.textColor = UIColor(r: NormalColor.0, g: NormalColor.1, b: NormalColor.2) currentIndex = currentLabel.tag let scrollLineX = CGFloat(currentLabel.tag) * scrollLine.frame.width UIView.animate(withDuration: 0.2) { self.scrollLine.frame.origin.x = scrollLineX } delegate?.pageTitleView(titleView: self, selectIndex: currentIndex) } } //Public-Method extension PageTitleView { func setTitleWithProgress(progress : CGFloat, sourceIndex : Int, targetIndex : Int) { let sourceLabel = titleLabels[sourceIndex] let targetLabel = titleLabels[targetIndex] let moveTotal = targetLabel.frame.origin.x - sourceLabel.frame.origin.x let moveX = progress * moveTotal scrollLine.frame.origin.x = sourceLabel.frame.origin.x + moveX let colorDelte = (SelectColor.0 - NormalColor.0, SelectColor.1 - NormalColor.1, SelectColor.2 - NormalColor.2) sourceLabel.textColor = UIColor(r: SelectColor.0 - colorDelte.0 * progress, g: SelectColor.1 - colorDelte.1 * progress, b: SelectColor.2 - colorDelte.2 * progress) targetLabel.textColor = UIColor(r: NormalColor.0 + colorDelte.0 * progress, g: NormalColor.1 + colorDelte.1 * progress, b: NormalColor.2 + colorDelte.2 * progress) currentIndex = targetIndex } }
mit
fe7a05c9415c7c411cd3c10cfed8b4c6
31.966887
171
0.624749
4.674178
false
false
false
false
firebase/quickstart-ios
authentication/AuthenticationExample/ViewControllers/UserViewController.swift
1
7423
// Copyright 2020 Google 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 import FirebaseAuth class UserViewController: UIViewController, DataSourceProviderDelegate { var dataSourceProvider: DataSourceProvider<User>! var userImage = UIImageView(systemImageName: "person.circle.fill", tintColor: .secondaryLabel) var tableView: UITableView { view as! UITableView } private var _user: User? var user: User? { get { _user ?? Auth.auth().currentUser } set { _user = newValue } } /// Init allows for injecting a `User` instance during UI Testing /// - Parameter user: A Firebase User instance init(_ user: User? = nil) { super.init(nibName: nil, bundle: nil) self.user = user } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - UIViewController Life Cycle override func loadView() { view = UITableView(frame: .zero, style: .insetGrouped) } override func viewDidLoad() { super.viewDidLoad() configureNavigationBar() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) configureDataSourceProvider() updateUserImage() } // MARK: - DataSourceProviderDelegate func tableViewDidScroll(_ tableView: UITableView) { adjustUserImageAlpha(tableView.contentOffset.y) } func didSelectRowAt(_ indexPath: IndexPath, on tableView: UITableView) { let item = dataSourceProvider.item(at: indexPath) let actionName = item.isEditable ? item.detailTitle! : item.title! guard let action = UserAction(rawValue: actionName) else { // The row tapped has no affiliated action. return } switch action { case .signOut: signCurrentUserOut() case .link: linkUserToOtherAuthProviders() case .requestVerifyEmail: requestVerifyEmail() case .tokenRefresh: refreshCurrentUserIDToken() case .delete: deleteCurrentUser() case .updateEmail: presentEditUserInfoController(for: item, to: updateUserEmail) case .updateDisplayName: presentEditUserInfoController(for: item, to: updateUserDisplayName) case .updatePhotoURL: presentEditUserInfoController(for: item, to: updatePhotoURL) case .refreshUserInfo: refreshUserInfo() } } // MARK: - Firebase 🔥 public func signCurrentUserOut() { try? Auth.auth().signOut() updateUI() } public func linkUserToOtherAuthProviders() { guard let user = user else { return } let accountLinkingController = AccountLinkingViewController(for: user) let navController = UINavigationController(rootViewController: accountLinkingController) navigationController?.present(navController, animated: true, completion: nil) } public func requestVerifyEmail() { user?.sendEmailVerification { error in guard error == nil else { return self.displayError(error) } print("Verification email sent!") } } public func refreshCurrentUserIDToken() { let forceRefresh = true user?.getIDTokenForcingRefresh(forceRefresh) { token, error in guard error == nil else { return self.displayError(error) } if let token = token { print("New token: \(token)") } } } public func refreshUserInfo() { user?.reload { error in if let error = error { print(error) } self.updateUI() } } public func updateUserDisplayName(to newDisplayName: String) { let changeRequest = user?.createProfileChangeRequest() changeRequest?.displayName = newDisplayName changeRequest?.commitChanges { error in guard error == nil else { return self.displayError(error) } self.updateUI() } } public func updateUserEmail(to newEmail: String) { user?.updateEmail(to: newEmail, completion: { error in guard error == nil else { return self.displayError(error) } self.updateUI() }) } public func updatePhotoURL(to newPhotoURL: String) { guard let newPhotoURL = URL(string: newPhotoURL) else { print("Could not create new photo URL!") return } let changeRequest = user?.createProfileChangeRequest() changeRequest?.photoURL = newPhotoURL changeRequest?.commitChanges { error in guard error == nil else { return self.displayError(error) } self.updateUI() } } public func deleteCurrentUser() { user?.delete { error in guard error == nil else { return self.displayError(error) } self.updateUI() } } // MARK: - Private Helpers private func configureNavigationBar() { navigationItem.title = "User" guard let navigationBar = navigationController?.navigationBar else { return } navigationBar.prefersLargeTitles = true navigationBar.titleTextAttributes = [.foregroundColor: UIColor.systemOrange] navigationBar.largeTitleTextAttributes = [.foregroundColor: UIColor.systemOrange] navigationBar.addProfilePic(userImage) } private func updateUserImage() { guard let photoURL = user?.photoURL else { let defaultImage = UIImage(systemName: "person.circle.fill") userImage.image = defaultImage?.withTintColor(.secondaryLabel, renderingMode: .alwaysOriginal) return } userImage.setImage(from: photoURL) } private func configureDataSourceProvider() { dataSourceProvider = DataSourceProvider( dataSource: user?.sections, emptyStateView: SignedOutView(), tableView: tableView ) dataSourceProvider.delegate = self } private func updateUI() { configureDataSourceProvider() animateUpdates(for: tableView) updateUserImage() } private func animateUpdates(for tableView: UITableView) { UIView.transition(with: tableView, duration: 0.2, options: .transitionCrossDissolve, animations: { tableView.reloadData() }) } private func presentEditUserInfoController(for item: Itemable, to saveHandler: @escaping (String) -> Void) { let editController = UIAlertController( title: "Update \(item.detailTitle!)", message: nil, preferredStyle: .alert ) editController.addTextField { $0.placeholder = "New \(item.detailTitle!)" } let saveHandler: (UIAlertAction) -> Void = { _ in let text = editController.textFields!.first!.text! saveHandler(text) } editController.addAction(UIAlertAction(title: "Save", style: .default, handler: saveHandler)) editController.addAction(UIAlertAction(title: "Cancel", style: .cancel)) present(editController, animated: true, completion: nil) } private var originalOffset: CGFloat? private func adjustUserImageAlpha(_ offset: CGFloat) { originalOffset = originalOffset ?? offset let verticalOffset = offset - originalOffset! userImage.alpha = 1 - (verticalOffset * 0.05) } }
apache-2.0
749a1b117188cdc67c5282a91bd182e4
29.040486
100
0.692453
4.732143
false
false
false
false
apple/swift-lldb
packages/Python/lldbsuite/test/lang/swift/printdecl/main.swift
2
955
// main.swift // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // // ----------------------------------------------------------------------------- struct Str1 { func foo() {} func bar() {} var a = 3 var b = "hi" } class Cla1 { func baz() {} func bat(_ x: Int, y : Str1) -> Int { return 1 } var x = Str1() var y = Dictionary<Int,String>() } func main() { var s = Str1() var c = Cla1() print("break here") } class Toplevel { struct Nested { class Deeper { func foo() {} } } } class Generic<T> { func foo(_ x: T) {} } func foo(_ x: Int, y: Int) -> Int { return x + 1 } func foo() -> Double { return 3.1415 } main()
apache-2.0
fb030ebb491e8437e5365cc28e9234c6
19.319149
80
0.565445
3.293103
false
false
false
false
EasySwift/EasySwift
EasySwift_iOS/Core/EZSystemInfo.swift
2
5756
// // EZSystemInfo.swift // YXJ // // Created by YXJ on 16/6/2. // Copyright (c) 2016年 YXJ. All rights reserved. // import UIKit #if os(iOS) public let IOS10_OR_LATER = (UIDevice.current.systemVersion.caseInsensitiveCompare("10.0") != ComparisonResult.orderedAscending) public let IOS9_OR_LATER = (UIDevice.current.systemVersion.caseInsensitiveCompare("9.0") != ComparisonResult.orderedAscending) public let IOS8_OR_LATER = (UIDevice.current.systemVersion.caseInsensitiveCompare("8.0") != ComparisonResult.orderedAscending) public let IOS7_OR_LATER = (UIDevice.current.systemVersion.caseInsensitiveCompare("7.0") != ComparisonResult.orderedAscending) public let IOS6_OR_LATER = (UIDevice.current.systemVersion.caseInsensitiveCompare("6.0") != ComparisonResult.orderedAscending) public let IOS5_OR_LATER = (UIDevice.current.systemVersion.caseInsensitiveCompare("5.0") != ComparisonResult.orderedAscending) public let IOS4_OR_LATER = (UIDevice.current.systemVersion.caseInsensitiveCompare("4.0") != ComparisonResult.orderedAscending) public let IOS3_OR_LATER = (UIDevice.current.systemVersion.caseInsensitiveCompare("3.0") != ComparisonResult.orderedAscending) public let IOS9_OR_EARLIER = !IOS10_OR_LATER public let IOS8_OR_EARLIER = !IOS9_OR_LATER public let IOS7_OR_EARLIER = !IOS8_OR_LATER public let IOS6_OR_EARLIER = !IOS7_OR_LATER public let IOS5_OR_EARLIER = !IOS6_OR_LATER public let IOS4_OR_EARLIER = !IOS5_OR_LATER public let IOS3_OR_EARLIER = !IOS4_OR_LATER public let IS_SCREEN_35_INCH = CGSize(width: 640, height: 960).equalTo(UIScreen.main.currentMode!.size) public let IS_SCREEN_4_INCH = CGSize(width: 640, height: 1136).equalTo(UIScreen.main.currentMode!.size) public let IS_SCREEN_47_INCH = CGSize(width: 750, height: 1334).equalTo(UIScreen.main.currentMode!.size) public let IS_SCREEN_47_INCH_BIG = (ScreenWidth == 568) public let IS_SCREEN_55_INCH = CGSize(width: 1242, height: 2208).equalTo(UIScreen.main.currentMode!.size) public let IS_SCREEN_55_INCH_BIG = (ScreenWidth == 667) #else public let IOS9_OR_LATER = false public let IOS8_OR_LATER = false public let IOS7_OR_LATER = false public let IOS6_OR_LATER = false public let IOS5_OR_LATER = false public let IOS4_OR_LATER = false public let IOS3_OR_LATER = false public let IOS9_OR_EARLIER = false public let IOS8_OR_EARLIER = false public let IOS7_OR_EARLIER = false public let IOS6_OR_EARLIER = false public let IOS5_OR_EARLIER = false public let IOS4_OR_EARLIER = false public let IOS3_OR_EARLIER = false public let IS_SCREEN_4_INCH = false public let IS_SCREEN_35_INCH = false public let IS_SCREEN_47_INCH = false public let IS_SCREEN_47_INCH_BIG = false public let IS_SCREEN_55_INCH = false public let IS_SCREEN_55_INCH_BIG = false #endif /// 是否是模拟器 public var IsSimulator: Bool { #if (arch(i386) || arch(x86_64)) && os(iOS) return true; #else return false; #endif } /// 获取设备名称 public let name = UIDevice.current.name /// 获取设备系统名称 public let systemName = UIDevice.current.systemName /// 获取系统版本 public let systemVersion = UIDevice.current.systemVersion /// 获取设备模型 public let model = UIDevice.current.model /// 获取设备本地模型 public let localizedModel = UIDevice.current.localizedModel /// Swift获取Bundle的相关信息 public let infoDict = Bundle.main.infoDictionary /// app名称 public let appName = infoDict!["CFBundleName"] as! String! /// app版本 public let appVersion = infoDict!["CFBundleShortVersionString"] as! String! /// app build版本 public let appBuild = infoDict!["CFBundleVersion"] as! String! /** 设备类型 - returns: 设备类型 */ public func deviceType () -> String? { let name = UnsafeMutablePointer<utsname>.allocate(capacity: 1) uname(name) let machine = withUnsafePointer(to: &name.pointee.machine, { (ptr) -> String? in let int8Ptr = unsafeBitCast(ptr, to: UnsafePointer<CChar>.self) return String(cString: int8Ptr) }) name.deallocate(capacity: 1) if let deviceString = machine { switch deviceString { // iPhone case "iPhone1,1": return "iPhone 1G" case "iPhone1,2": return "iPhone 3G" case "iPhone2,1": return "iPhone 3GS" case "iPhone3,1", "iPhone3,2": return "iPhone 4" case "iPhone4,1": return "iPhone 4S" case "iPhone5,1", "iPhone5,2": return "iPhone 5" case "iPhone5,3", "iPhone5,4": return "iPhone 5C" case "iPhone6,1", "iPhone6,2": return "iPhone 5S" case "iPhone7,1": return "iPhone 6 Plus" case "iPhone7,2": return "iPhone 6" case "iPhone8,1": return "iPhone 6s" case "iPhone8,2": return "iPhone 6s Plus" default: return deviceString } } else { return nil } } public var Orientation: UIInterfaceOrientation { get { return UIApplication.shared.statusBarOrientation } } /// 屏幕宽度 public var ScreenWidth: CGFloat { get { if UIInterfaceOrientationIsPortrait(Orientation) { return UIScreen.main.bounds.size.width } else { return UIScreen.main.bounds.size.height } } } /// 屏幕高度 public var ScreenHeight: CGFloat { get { if UIInterfaceOrientationIsPortrait(Orientation) { return UIScreen.main.bounds.size.height } else { return UIScreen.main.bounds.size.width } } } /// 状态栏高度 public var StatusBarHeight: CGFloat { get { return UIApplication.shared.statusBarFrame.height } }
apache-2.0
9b6d6402127c9bfae3ab3148a9f095e6
32.771084
132
0.684267
3.612113
false
false
false
false
apurushottam/IPhone-Learning-Codes
Project 8-Petitions/Project 8-Petitions/MasterViewController.swift
1
4141
// // MasterViewController.swift // Project 8-Petitions // // Created by Ashutosh Purushottam on 9/29/15. // Copyright © 2015 Vivid Designs. All rights reserved. // import UIKit class MasterViewController: UITableViewController { var detailViewController: DetailViewController? = nil // Array of String:String Dictionary var objects = [[String: String]]() override func viewDidLoad() { super.viewDidLoad() // Url of the api request let urlString: String if navigationController?.tabBarItem.tag == 0 { urlString = "https://api.whitehouse.gov/v1/petitions.json?limit=100" } else { urlString = "https://api.whitehouse.gov/v1/petitions.json?signatureCountFloor=10000&limit=100" } if let url = NSURL(string: urlString){ // get data as NSData from api hit if let data = try? NSData(contentsOfURL: url, options: []) { let json = JSON(data: data) if json["metadata"]["responseInfo"]["status"] == 200 { // We can parse json now parseJSON(json) } else { showError() } } else { showError() } } else { showError() } } /* */ func parseJSON(json: JSON) { // Get info from each petition from array for result in json["results"].arrayValue { let title = result["title"].stringValue let body = result["body"].stringValue let sigs = result["signatureCount"].stringValue let obj = ["title": title, "body": body, "sigs": sigs] objects.append(obj) } tableView.reloadData() } /* Method to parse json and populate objects array of dictionary initialized above */ override func viewWillAppear(animated: Bool) { self.clearsSelectionOnViewWillAppear = self.splitViewController!.collapsed super.viewWillAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showDetail" { if let indexPath = self.tableView.indexPathForSelectedRow { let object = objects[indexPath.row] let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController controller.detailItem = object controller.navigationController?.navigationBar.hidden = false controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem() controller.navigationItem.leftItemsSupplementBackButton = true } } } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return objects.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) let object = objects[indexPath.row] // Set title cell.textLabel?.text = object["title"] // Set subtitle cell.detailTextLabel?.text = object["body"] return cell } func showError() { let ac = UIAlertController(title: "Loading error", message: "There was a problem loading the feed; please check your connection and try again.", preferredStyle: .Alert) ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) presentViewController(ac, animated: true, completion: nil) } }
apache-2.0
47433c44fbf57c7d05d42ce67fdf0933
31.093023
176
0.604106
5.447368
false
false
false
false
breadwallet/breadwallet
BreadWallet/BRCameraPlugin.swift
4
14064
// // BRCameraPlugin.swift // BreadWallet // // Created by Samuel Sutch on 10/9/16. // Copyright © 2016 Aaron Voisine. All rights reserved. // import Foundation @available(iOS 8.0, *) @objc open class BRCameraPlugin: NSObject, BRHTTPRouterPlugin, UIImagePickerControllerDelegate, UINavigationControllerDelegate, CameraOverlayDelegate { let controller: UIViewController var response: BRHTTPResponse? var picker: UIImagePickerController? init(fromViewController: UIViewController) { self.controller = fromViewController super.init() } open func hook(_ router: BRHTTPRouter) { // GET /_camera/take_picture // // Optionally pass ?overlay=<id> (see overlay ids below) to show an overlay // in picture taking mode // // Status codes: // - 200: Successful image capture // - 204: User canceled image picker // - 404: Camera is not available on this device // - 423: Multiple concurrent take_picture requests. Only one take_picture request may be in flight at once. // router.get("/_camera/take_picture") { (request, match) -> BRHTTPResponse in if self.response != nil { print("[BRCameraPlugin] already taking a picture") return BRHTTPResponse(request: request, code: 423) } if !UIImagePickerController.isSourceTypeAvailable(.camera) || UIImagePickerController.availableCaptureModes(for: .rear) == nil { print("[BRCameraPlugin] no camera available") guard let resp = try? BRHTTPResponse(request: request, code: 200, json: ["id": "test"]) else { return BRHTTPResponse(request: request, code: 404) } return resp } let response = BRHTTPResponse(async: request) self.response = response DispatchQueue.main.async { let picker = UIImagePickerController() picker.delegate = self picker.sourceType = .camera picker.cameraCaptureMode = .photo // set overlay if let overlay = request.query["overlay"] , overlay.count == 1 { print(["BRCameraPlugin] overlay = \(overlay)"]) let screenBounds = UIScreen.main.bounds if overlay[0] == "id" { picker.showsCameraControls = false picker.allowsEditing = false picker.hidesBarsOnTap = true picker.isNavigationBarHidden = true let overlay = IDCameraOverlay(frame: screenBounds) overlay.delegate = self overlay.backgroundColor = UIColor.clear picker.cameraOverlayView = overlay } } self.picker = picker self.controller.present(picker, animated: true, completion: nil) } return response } // GET /_camera/picture/(id) // // Return a picture as taken by take_picture // // Status codes: // - 200: Successfully returned iamge // - 404: Couldn't find image with that ID // router.get("/_camera/picture/(id)") { (request, match) -> BRHTTPResponse in var id: String! if let ids = match["id"] , ids.count == 1 { id = ids[0] } else { return BRHTTPResponse(request: request, code: 500) } let resp = BRHTTPResponse(async: request) do { // read img var imgDat: [UInt8] if id == "test" { imgDat = [UInt8](try! Data(contentsOf: URL(string: "http://i.imgur.com/VG2UvcY.jpg")!)) } else { imgDat = try self.readImage(id) } // scale img guard let img = UIImage(data: Data(imgDat)) else { return BRHTTPResponse(request: request, code: 500) } let scaledImg = img.scaled(to: CGSize(width: 1000, height: 1000), scalingMode: .aspectFit) guard let scaledImageDat = UIImageJPEGRepresentation(scaledImg, 0.7) else { return BRHTTPResponse(request: request, code: 500) } imgDat = [UInt8](scaledImageDat) // return img to client var contentType = "image/jpeg" if let b64opt = request.query["base64"], b64opt.count > 0 { contentType = "text/plain" let b64 = "data:image/jpeg;base64," + Data(imgDat).base64EncodedString() guard let b64encoded = b64.data(using: .utf8) else { resp.provide(500) return resp } imgDat = [UInt8](b64encoded) } resp.provide(200, data: imgDat, contentType: contentType) } catch let e { print("[BRCameraPlugin] error reading image: \(e)") resp.provide(500) } return resp } } open func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { guard let resp = self.response else { return } defer { self.response = nil DispatchQueue.main.async { picker.dismiss(animated: true, completion: nil) } } resp.provide(204, json: nil) } open func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { defer { DispatchQueue.main.async { picker.dismiss(animated: true, completion: nil) } } guard let resp = self.response else { return } guard var img = info[UIImagePickerControllerOriginalImage] as? UIImage else { print("[BRCameraPlugin] error picking image... original image doesnt exist. data: \(info)") resp.provide(500) response = nil return } resp.request.queue.async { defer { self.response = nil } do { if let overlay = self.picker?.cameraOverlayView as? CameraOverlay { if let croppedImg = overlay.cropImage(img) { img = croppedImg } } let id = try self.writeImage(img) print(["[BRCameraPlugin] wrote image to \(id)"]) resp.provide(200, json: ["id": id]) } catch let e { print("[BRCameraPlugin] error writing image: \(e)") resp.provide(500) } } } func takePhoto() { self.picker?.takePicture() } func cancelPhoto() { if let picker = self.picker { self.imagePickerControllerDidCancel(picker) } } func readImage(_ name: String) throws -> [UInt8] { let fm = FileManager.default let docsUrl = fm.urls(for: .documentDirectory, in: .userDomainMask).first! let picDirUrl = docsUrl.appendingPathComponent("pictures", isDirectory: true) let picUrl = picDirUrl.appendingPathComponent("\(name).jpeg") guard let dat = try? Data(contentsOf: picUrl) else { throw ImageError.couldntRead } let bp = (dat as NSData).bytes.bindMemory(to: UInt8.self, capacity: dat.count) return Array(UnsafeBufferPointer(start: bp, count: dat.count)) } func writeImage(_ image: UIImage) throws -> String { guard let dat = UIImageJPEGRepresentation(image, 0.5) else { throw ImageError.errorConvertingImage } let name = (NSData(uInt256: (dat as NSData).sha256()) as NSData).base58String() let fm = FileManager.default let docsUrl = fm.urls(for: .documentDirectory, in: .userDomainMask).first! let picDirUrl = docsUrl.appendingPathComponent("pictures", isDirectory: true) let picDirPath = picDirUrl.path var attrs = try? fm.attributesOfItem(atPath: picDirPath) if attrs == nil { try fm.createDirectory(atPath: picDirPath, withIntermediateDirectories: true, attributes: nil) attrs = try fm.attributesOfItem(atPath: picDirPath) } let picUrl = picDirUrl.appendingPathComponent("\(name).jpeg") try dat.write(to: picUrl, options: []) return name } } enum ImageError: Error { case errorConvertingImage case couldntRead } protocol CameraOverlayDelegate { func takePhoto() func cancelPhoto() } protocol CameraOverlay { func cropImage(_ image: UIImage) -> UIImage? } class IDCameraOverlay: UIView, CameraOverlay { var delegate: CameraOverlayDelegate? let takePhotoButton: UIButton let cancelButton: UIButton let overlayRect: CGRect override init(frame: CGRect) { overlayRect = CGRect(x: 0, y: 0, width: frame.width, height: frame.width * CGFloat(4.0/3.0)) takePhotoButton = UIButton(type: .custom) takePhotoButton.setImage(UIImage(named: "camera-btn"), for: UIControlState()) takePhotoButton.setImage(UIImage(named: "camera-btn-pressed"), for: .highlighted) takePhotoButton.frame = CGRect(x: 0, y: 0, width: 79, height: 79) takePhotoButton.center = CGPoint( x: overlayRect.midX, y: overlayRect.maxX + (frame.height - overlayRect.maxX) * 0.75 ) cancelButton = UIButton(type: .custom) cancelButton.setTitle(NSLocalizedString("Cancel", comment: ""), for: UIControlState()) cancelButton.frame = CGRect(x: 0, y: 0, width: 88, height: 44) cancelButton.center = CGPoint(x: takePhotoButton.center.x * 0.3, y: takePhotoButton.center.y) cancelButton.setTitleColor(UIColor.white, for: UIControlState()) super.init(frame: frame) takePhotoButton.addTarget(self, action: #selector(IDCameraOverlay.doTakePhoto(_:)), for: .touchUpInside) cancelButton.addTarget(self, action: #selector(IDCameraOverlay.doCancelPhoto(_:)), for: .touchUpInside) self.addSubview(cancelButton) self.addSubview(takePhotoButton) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) is not implemented") } func doTakePhoto(_ target: UIControl) { delegate?.takePhoto() } func doCancelPhoto(_ target: UIControl) { delegate?.cancelPhoto() } override func draw(_ rect: CGRect) { super.draw(rect) UIColor.black.withAlphaComponent(0.92).setFill() UIRectFill(overlayRect) guard let ctx = UIGraphicsGetCurrentContext() else { return } ctx.setBlendMode(.destinationOut) let width = rect.size.width * 0.9 var cutout = CGRect(origin: overlayRect.origin, size: CGSize(width: width, height: width * 0.65)) cutout.origin.x = (overlayRect.size.width - cutout.size.width) * 0.5 cutout.origin.y = (overlayRect.size.height - cutout.size.height) * 0.5 let path = UIBezierPath(rect: cutout.integral) path.fill() ctx.setBlendMode(.normal) let str = NSLocalizedString("Center your ID in the box", comment: "") as NSString let style = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle style.alignment = .center let attr = [ NSParagraphStyleAttributeName: style, NSFontAttributeName: UIFont.boldSystemFont(ofSize: 17), NSForegroundColorAttributeName: UIColor.white ] str.draw(in: CGRect(x: 0, y: cutout.maxY + 14.0, width: rect.width, height: 22), withAttributes: attr) } func cropImage(_ image: UIImage) -> UIImage? { guard let cgimg = image.cgImage else { return nil } let rect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height) let width = rect.size.width * 0.9 var cutout = CGRect(origin: rect.origin, size: CGSize(width: width, height: width * 0.65)) cutout.origin.x = (rect.size.width - cutout.size.width) * 0.5 cutout.origin.y = (rect.size.height - cutout.size.height) * 0.5 cutout = cutout.integral func rad(_ f: CGFloat) -> CGFloat { return f / 180.0 * CGFloat(Double.pi) } var transform: CGAffineTransform! switch image.imageOrientation { case .left: transform = CGAffineTransform(rotationAngle: rad(90)).translatedBy(x: 0, y: -image.size.height) case .right: transform = CGAffineTransform(rotationAngle: rad(-90)).translatedBy(x: -image.size.width, y: 0) case .down: transform = CGAffineTransform(rotationAngle: rad(-180)).translatedBy(x: -image.size.width, y: -image.size.height) default: transform = CGAffineTransform.identity } transform = transform.scaledBy(x: image.scale, y: image.scale) cutout = cutout.applying(transform) guard let retRef = cgimg.cropping(to: cutout) else { return nil } return UIImage(cgImage: retRef, scale: image.scale, orientation: image.imageOrientation) } }
mit
6bbb7020a65ff6123bf3c518dcf68e67
39.065527
118
0.558416
4.864407
false
false
false
false
RayTao/CoreAnimation_Collection
CoreAnimation_Collection/EfficientImageViewController.swift
1
3891
// // EfficientImageViewController.swift // CoreAnimation_Collection // // Created by ray on 16/2/17. // Copyright © 2016年 ray. All rights reserved. // import UIKit class EfficientImageViewController: UIViewController, UICollectionViewDataSource { let imagePaths = Bundle.main.paths(forResourcesOfType: "png", inDirectory: "Vacation Photos") let cellID = "cellID" let cache = NSCache<AnyObject, AnyObject>.init() lazy var collectionView: UICollectionView = { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .vertical layout.minimumInteritemSpacing = 10.0 layout.minimumLineSpacing = 10.0 layout.itemSize = CGSize(width: 200, height: 150) let collectionView = UICollectionView.init(frame: self.view.bounds, collectionViewLayout: layout) collectionView.dataSource = self return collectionView }() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.view.addSubview(collectionView) collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellID) } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.imagePaths.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath) //add image view let imageTag = 99 var imageView = cell.viewWithTag(imageTag) as! UIImageView? if imageView == nil { imageView = UIImageView.init(frame: cell.contentView.bounds) imageView?.tag = 99 cell.contentView.addSubview(imageView!) } //set or load image for this index imageView?.image = self.loadImageAtIndex((indexPath as NSIndexPath).item); //preload image for previous and next index if ((indexPath as NSIndexPath).item < self.imagePaths.count - 1) { _ = self.loadImageAtIndex((indexPath as NSIndexPath).item + 1); } if ((indexPath as NSIndexPath).item > 0) { _ = self.loadImageAtIndex((indexPath as NSIndexPath).item - 1); } return cell } func loadImageAtIndex(_ index: Int) -> UIImage? { var image = cache.object(forKey: index as AnyObject) as! UIImage? if image != nil { return image } //switch to background thread DispatchQueue.global(qos: .default).async(execute: { () -> Void in //load image let imagePath = self.imagePaths[index]; // UIImage *image = [UIImage imageWithContentsOfFile:imagePath]; image = UIImage.init(contentsOfFile: imagePath) //redraw image using device context UIGraphicsBeginImageContextWithOptions(image!.size, true, 0); image!.draw(at: CGPoint.zero); image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); //set image for correct image view DispatchQueue.main.async(execute: { () -> Void in //cache the image self.cache.setObject(image!, forKey:index as AnyObject); //display the image let indexPath = IndexPath.init(row: index, section: 0) let cell = self.collectionView.cellForItem(at: indexPath); let imageView = cell?.contentView.subviews.last as! UIImageView? imageView?.image = image; }) }) return nil } }
mit
50640d2068d23be6e2ace8cb0af93224
35
121
0.614969
5.445378
false
false
false
false
EdgarM-/MobileComputing
ChatIOS/ChatIOS[ea-cj]/TCiceChat/PruebaInicial/PruebaInicial/sContactView.swift
1
3065
// // sContactView.swift // PruebaInicial // // Created by Estudiantes on 5/31/16. // Copyright © 2016 TCIceChat. All rights reserved. ///Users/estudiantes/Documents/Native Instruments/FM8/Moviles[ea-cj]_3/TCiceChat/PruebaInicial/PruebaInicial.xcodeproj import UIKit class sContactViewController: UIViewController, UITableViewDataSource { //@IBOutlet weak var lblID: UILabel! @IBOutlet var tableView: UITableView! var idEntrar:Int = 1 var cManager = ContactManager () var nombreUserDestino:Contact = Contact(id: 1,name: "a",userName: "b") var nombreUserRemitente:Contact = Contact(id: 1,name: "a",userName: "b") var userRemitente : Int = 1 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell:CustomTableViewCell = tableView.dequeueReusableCellWithIdentifier("Custom01") as! CustomTableViewCell let contact = cManager.getContactAt(indexPath.row) cell.nameLbl.text = contact?.name cell.userNameLbl.text = contact?.userName return cell } func tableView(tableView: UITableView,numberOfRowsInSection section: Int) -> Int{ return cManager.contactCount(); } override func viewDidLoad() { //super.viewDidLoad() cManager.getContacts(idEntrar) let nameRemitente:String = "Carlos" let userNameRemitente:String = "Jaramillo" //cManager.getContactAt(idEntrar)?.userName nombreUserRemitente = Contact(id: idEntrar, name: nameRemitente, userName: userNameRemitente) //lblID.text? = "usuario: \(idEntrar)" let seconds = 1.0 let delay = seconds*Double(NSEC_PER_SEC) let dispatchtime = dispatch_time(DISPATCH_TIME_NOW,Int64(delay)) dispatch_after(dispatchtime, dispatch_get_main_queue(), { self.viewWillAppear(true) }) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if(segue.identifier == "Tab1Conversar"){ let tabBarController = segue.destinationViewController as! TabBarController1; let destinationViewController = tabBarController.viewControllers![0] as! ChatView2 let destinationViewController2 = tabBarController.viewControllers![1] as! FileView nombreUserDestino = cManager.getContactAt((tableView.indexPathForSelectedRow?.row)!)! userRemitente = idEntrar destinationViewController.userDestino = nombreUserDestino destinationViewController.userRemitente = nombreUserRemitente.id destinationViewController2.userDestino = nombreUserDestino destinationViewController2.userRemitente = nombreUserRemitente.id print("Id from",nombreUserDestino.id,"Id to",nombreUserRemitente.id) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewWillAppear(animated: Bool) { tableView.reloadData() } }
mit
f0a6f96f5f15b4d394705794bc0d41ab
40.405405
118
0.689295
4.370899
false
false
false
false
PriyamDutta/PDFloraButton
FloraButton/Classes/PDFloraButton.swift
1
16651
// // PDFloraButton.swift // PDFloraButton // // Created by Priyam Dutta on 27/08/16. // Copyright © 2016 Priyam Dutta. All rights reserved. // import UIKit public enum ButtonPosition { case center case topLeft case topRight case bottomLeft case bottomRight case midTop case midBottom case midLeft case midRight } private func getRadian(degree: CGFloat) -> CGFloat { return CGFloat(degree * .pi/180) } final public class PDFloraButton: UIButton { private let radius: CGFloat = 100.0 private let childButtonSize: CGFloat = 30.0 private let circumference: CGFloat = 360.0 private let delayInterval = 0.0 private let duration = 0.25 private let damping: CGFloat = 0.9 private let initialVelocity: CGFloat = 0.9 private var anchorPoint: CGPoint! private var xPadding: CGFloat = 10.0 private var yPadding: CGFloat = 10.0 private var buttonSize: CGFloat = 0.0 private var childButtons = 0 private var buttonPosition: ButtonPosition = .center private var childButtonsArray = [UIButton]() private var degree: CGFloat = 0.0 private var imageArray = [String]() public var isOpen = false public var buttonActionDidSelected: ((_ indexSelected: Int)->())! public convenience init(withPosition position: ButtonPosition, size: CGFloat, numberOfPetals: Int, images: [String]) { self.init(frame: CGRect(x: 0, y: 0, width: size, height: size)) self.layer.cornerRadius = size/2.0 childButtons = numberOfPetals buttonPosition = position imageArray = images DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(0.01 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { switch position { case .topLeft: self.center = CGPoint(x: (self.superview?.frame)!.minX+(size/2.0)+self.xPadding, y: (self.superview?.frame)!.minY+(size/2.0)+self.yPadding) case .topRight: self.center = CGPoint(x: (self.superview?.frame)!.maxX-(size/2.0)-self.xPadding, y: (self.superview?.frame)!.minY+(size/2.0)+self.yPadding) case .bottomLeft: self.center = CGPoint(x: (self.superview?.frame)!.minX+(size/2.0)+self.xPadding, y: (self.superview?.frame)!.maxY-(size/2.0)-self.yPadding) case .bottomRight: self.center = CGPoint(x: (self.superview?.frame)!.maxX-(size/2.0)-self.xPadding, y: (self.superview?.frame)!.maxY-(size/2.0)-self.yPadding) case .midTop: self.center = CGPoint(x: (self.superview?.frame)!.midX, y: (self.superview?.frame)!.minY+(size/2.0)+self.yPadding) case .midBottom: self.center = CGPoint(x: (self.superview?.frame)!.midX, y: (self.superview?.frame)!.maxY-(size/2.0)-self.yPadding) case .midLeft: self.center = CGPoint(x: (self.superview?.frame)!.minX+(size/2.0)+self.xPadding, y: (self.superview?.frame)!.midY) case .midRight: self.center = CGPoint(x: (self.superview?.frame)!.maxX-(size/2.0)-(self.xPadding), y: (self.superview?.frame)!.midY) default: self.center = CGPoint(x: (self.superview?.frame)!.midX, y: (self.superview?.frame)!.midY) } self.anchorPoint = self.center self.createButtons(numbers: numberOfPetals) } } override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .brown self.addTarget(self, action: #selector(self.animateChildButtons(_:)), for: .touchUpInside) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // Create Buttons private func createButtons(numbers: Int) { for index in 0..<numbers { let petal = UIButton(frame: CGRect(x: 0, y: 0, width: childButtonSize, height: childButtonSize)) petal.center = self.center petal.layer.cornerRadius = childButtonSize/2.0 petal.backgroundColor = .cyan petal.setTitleColor(.black, for: UIControl.State()) petal.tag = index if index < imageArray.count { petal.setImage(UIImage(named: imageArray[index]), for: UIControl.State()) } petal.setTitle(String(index), for: UIControl.State()) petal.addTarget(self, action: #selector(self.buttonAction(_:)), for: .touchUpInside) self.superview?.addSubview(petal) self.superview?.bringSubview(toFront: self) childButtonsArray.append(petal) } } // Present Buttons @IBAction func animateChildButtons(_ sender: UIButton) { scaleAnimate(sender) self.isUserInteractionEnabled = false if !isOpen { switch buttonPosition { case .topLeft: self.presentationForTopLeft() case .topRight: self.presentationForTopRight() case .bottomLeft: self.presentationForBottomLeft() case .bottomRight: self.presentationForBottomRight() case .midTop: self.presentationForMidTop() case .midBottom: self.presentationForMidBottom() case .midLeft: self.presentationForMidLeft() case .midRight: self.presentationForMidRight() default: self.presentationForCenter() } } else { closeButtons() } } //Simple Scale private func scaleAnimate(_ sender: UIView) { UIView.animate(withDuration: self.duration, animations: { sender.transform = CGAffineTransform(scaleX: 1.3, y: 1.3) }, completion: { (completion) in UIView.animate(withDuration: self.duration, animations: { sender.transform = CGAffineTransform.identity }) }) } // Center private func presentationForCenter() { for (index, item) in self.childButtonsArray.enumerated() { self.degree = getRadian(degree: (circumference/CGFloat(childButtons))*CGFloat(index)) UIView.animate(withDuration: self.duration, delay: self.delayInterval+(Double(index)/10), usingSpringWithDamping: damping, initialSpringVelocity: initialVelocity, options: UIView.AnimationOptions(), animations: { item.center = CGPoint(x: self.anchorPoint.x+(self.radius*cos(self.degree)), y: self.anchorPoint.y+(self.radius*sin(self.degree))) }, completion: { (completion) in self.isOpen = true if index == self.childButtonsArray.count-1 { self.isUserInteractionEnabled = true } }) } } // Top Left private func presentationForTopLeft() { for (index, item) in self.childButtonsArray.enumerated() { self.degree = getRadian(degree: (90.0/CGFloat(childButtons-1))*CGFloat(index)) if item == self.childButtonsArray.first { self.degree = getRadian(degree: 0.0) } if item == self.childButtonsArray.last { self.degree = getRadian(degree: 90.0) } UIView.animate(withDuration: self.duration, delay: self.delayInterval+(Double(index)/10), usingSpringWithDamping: damping, initialSpringVelocity: initialVelocity, options: UIView.AnimationOptions(), animations: { item.center = CGPoint(x: self.anchorPoint.x+(self.radius*cos(self.degree)), y: self.anchorPoint.y+(self.radius*sin(self.degree))) }, completion: { (completion) in self.isOpen = true if index == self.childButtonsArray.count-1 { self.isUserInteractionEnabled = true } }) } } // Top Right private func presentationForTopRight() { for (index, item) in self.childButtonsArray.enumerated() { self.degree = getRadian(degree: 90+((90.0)/CGFloat(childButtons-1))*CGFloat(index)) if item == self.childButtonsArray.first { self.degree = getRadian(degree: 90.0) } if item == self.childButtonsArray.last { self.degree = getRadian(degree: 180.0) } UIView.animate(withDuration: self.duration, delay: self.delayInterval+(Double(index)/10), usingSpringWithDamping: damping, initialSpringVelocity: initialVelocity, options: UIView.AnimationOptions(), animations: { item.center = CGPoint(x: self.anchorPoint.x+(self.radius*cos(self.degree)), y: self.anchorPoint.y+(self.radius*sin(self.degree))) }, completion: { (completion) in self.isOpen = true if index == self.childButtonsArray.count-1 { self.isUserInteractionEnabled = true } }) } } // Bottom Left private func presentationForBottomLeft() { for (index, item) in self.childButtonsArray.enumerated() { self.degree = getRadian(degree: 270+((90.0)/CGFloat(childButtons-1))*CGFloat(index)) if item == self.childButtonsArray.first { self.degree = getRadian(degree: 270.0) } if item == self.childButtonsArray.last { self.degree = getRadian(degree: 360.0) } UIView.animate(withDuration: self.duration, delay: self.delayInterval+(Double(index)/10), usingSpringWithDamping: damping, initialSpringVelocity: initialVelocity, options: UIView.AnimationOptions(), animations: { item.center = CGPoint(x: self.anchorPoint.x+(self.radius*cos(self.degree)), y: self.anchorPoint.y+(self.radius*sin(self.degree))) }, completion: { (completion) in self.isOpen = true if index == self.childButtonsArray.count-1 { self.isUserInteractionEnabled = true } }) } } // Bottom Right private func presentationForBottomRight() { for (index, item) in self.childButtonsArray.enumerated() { self.degree = getRadian(degree: 180+((90.0)/CGFloat(childButtons-1))*CGFloat(index)) if item == self.childButtonsArray.first { self.degree = getRadian(degree: 180.0) } if item == self.childButtonsArray.last { self.degree = getRadian(degree: 270.0) } UIView.animate(withDuration: self.duration, delay: self.delayInterval+(Double(index)/10), usingSpringWithDamping: damping, initialSpringVelocity: initialVelocity, options: UIView.AnimationOptions(), animations: { item.center = CGPoint(x: self.anchorPoint.x+(self.radius*cos(self.degree)), y: self.anchorPoint.y+(self.radius*sin(self.degree))) }, completion: { (completion) in self.isOpen = true if index == self.childButtonsArray.count-1 { self.isUserInteractionEnabled = true } }) } } //Mid Top private func presentationForMidTop() { for (index, item) in self.childButtonsArray.enumerated() { self.degree = getRadian(degree: ((180.0)/CGFloat(childButtons-1))*CGFloat(index)) if item == self.childButtonsArray.first { self.degree = getRadian(degree: 0.0) } if item == self.childButtonsArray.last { self.degree = getRadian(degree: 180.0) } UIView.animate(withDuration: self.duration, delay: self.delayInterval+(Double(index)/10), usingSpringWithDamping: damping, initialSpringVelocity: initialVelocity, options: UIView.AnimationOptions(), animations: { item.center = CGPoint(x: self.anchorPoint.x+(self.radius*cos(self.degree)), y: self.anchorPoint.y+(self.radius*sin(self.degree))) }, completion: { (completion) in self.isOpen = true if index == self.childButtonsArray.count-1 { self.isUserInteractionEnabled = true } }) } } //Mid Bottom private func presentationForMidBottom() { for (index, item) in self.childButtonsArray.enumerated() { self.degree = getRadian(degree: 180+((180.0)/CGFloat(childButtons-1))*CGFloat(index)) if item == self.childButtonsArray.first { self.degree = getRadian(degree: 180.0) } if item == self.childButtonsArray.last { self.degree = getRadian(degree: 360.0) } UIView.animate(withDuration: self.duration, delay: self.delayInterval+(Double(index)/10), usingSpringWithDamping: damping, initialSpringVelocity: initialVelocity, options: UIView.AnimationOptions(), animations: { item.center = CGPoint(x: self.anchorPoint.x+(self.radius*cos(self.degree)), y: self.anchorPoint.y+(self.radius*sin(self.degree))) }, completion: { (completion) in self.isOpen = true if index == self.childButtonsArray.count-1 { self.isUserInteractionEnabled = true } }) } } //Mid Left private func presentationForMidLeft() { for (index, item) in self.childButtonsArray.enumerated() { self.degree = getRadian(degree: 270+((180.0)/CGFloat(childButtons-1))*CGFloat(index)) if item == self.childButtonsArray.first { self.degree = getRadian(degree: 270.0) } if item == self.childButtonsArray.last { self.degree = getRadian(degree: 90.0) } UIView.animate(withDuration: self.duration, delay: self.delayInterval+(Double(index)/10), usingSpringWithDamping: damping, initialSpringVelocity: initialVelocity, options: UIView.AnimationOptions(), animations: { item.center = CGPoint(x: self.anchorPoint.x+(self.radius*cos(self.degree)), y: self.anchorPoint.y+(self.radius*sin(self.degree))) }, completion: { (completion) in self.isOpen = true if index == self.childButtonsArray.count-1 { self.isUserInteractionEnabled = true } }) } } //Mid Right private func presentationForMidRight() { for (index, item) in self.childButtonsArray.enumerated() { self.degree = getRadian(degree: 90+((180.0)/CGFloat(childButtons-1))*CGFloat(index)) if item == self.childButtonsArray.first { self.degree = getRadian(degree: 90.0) } if item == self.childButtonsArray.last { self.degree = getRadian(degree: 270.0) } UIView.animate(withDuration: self.duration, delay: self.delayInterval+(Double(index)/10), usingSpringWithDamping: damping, initialSpringVelocity: initialVelocity, options: UIView.AnimationOptions(), animations: { item.center = CGPoint(x: self.anchorPoint.x+(self.radius*cos(self.degree)), y: self.anchorPoint.y+(self.radius*sin(self.degree))) }, completion: { (completion) in self.isOpen = true if index == self.childButtonsArray.count-1 { self.isUserInteractionEnabled = true } }) } } // Close Button private func closeButtons() { UIView.animate(withDuration: self.duration, animations: { for (_,item) in self.childButtonsArray.enumerated() { item.center = self.center } }, completion: { (completion) in self.isOpen = false self.isUserInteractionEnabled = true }) } // Remove Buttons func removeButtons() { for item in childButtonsArray { item.removeFromSuperview() } self.removeFromSuperview() } @IBAction func buttonAction(_ sender: UIButton) { scaleAnimate(sender) if buttonActionDidSelected != nil { buttonActionDidSelected(sender.tag) } } }
mit
9b1863f8bd171e099c8ddc41077d085c
44.491803
224
0.587688
4.577949
false
false
false
false
johnlui/Swift-MMP
Frameworks/Pitaya/Example/PitayaExample/ExamplesViewController.swift
1
7387
// // ExamplesViewController.swift // PitayaExample // // Created by 吕文翰 on 16/12/16. // Copyright © 2016年 http://lvwenhan.com. All rights reserved. // import UIKit import Pitaya enum RequestType: String { case SimpleGET, SimplePOST, GETWithStringOrNumberParams, POSTWithStringOrNumberParams, UploadFilesByURL, UploadFilesByData, SetHTTPHeaders, SetHTTPRawBody, HTTPBasicAuth, AddSSLPinning, AddManySSLPinning, SyncRequest } class ExamplesViewController: UIViewController { var requestType: RequestType! @IBOutlet weak var fireUpButton: UIButton! @IBOutlet weak var resultLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() self.fireUpButton.setTitle(self.requestType.rawValue, for: .normal) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.clearAllNotice() } @IBAction func FireUpButtonBeTapped(_ sender: Any) { self.perform(Selector(self.requestType.rawValue)) } func SimpleGET() { self.pleaseWait() Pita.build(HTTPMethod: .GET, url: "http://httpbin.org/get") .responseString { (string, nil) in self.resultLabel.text = string self.clearAllNotice() } } func SimplePOST() { self.pleaseWait() Pita.build(HTTPMethod: .POST, url: "http://httpbin.org/post") .addParams(["key": "pitaaaaaaaaaaaaaaaya"]) .responseString { (string, nil) in self.resultLabel.text = string self.clearAllNotice() } } func GETWithStringOrNumberParams() { self.pleaseWait() Pita.build(HTTPMethod: .GET, url: "http://httpbin.org/get") .addParams(["key": "pitaaaaaaaaaaaaaaaya"]) .responseString { (string, nil) in self.resultLabel.text = string self.clearAllNotice() } } func POSTWithStringOrNumberParams() { self.pleaseWait() Pita.build(HTTPMethod: .POST, url: "http://httpbin.org/post") .addParams(["key": "pitaaaaaaaaaaaaaaaya"]) .responseString { (string, nil) in self.resultLabel.text = string self.clearAllNotice() } } func UploadFilesByURL() { let fileURL = Bundle(for: ExamplesViewController.self).url(forResource: "logo@2x", withExtension: "jpg")! let file = File(name: "file", url: fileURL) self.pleaseWait() Pita.build(HTTPMethod: .POST, url: "http://staticonsae.sinaapp.com/pitaya.php") .addFiles([file]) .responseString({ (string, response) -> Void in self.resultLabel.text = string == "1" ? "success" : "failure" self.clearAllNotice() }) } func UploadFilesByData() { let fileURL = Bundle(for: ExamplesViewController.self).url(forResource: "logo@2x", withExtension: "jpg")! let data = try! Data(contentsOf: fileURL) let file = File(name: "file", data: data, type: "jpg") self.pleaseWait() Pita.build(HTTPMethod: .POST, url: "http://staticonsae.sinaapp.com/pitaya.php") .addFiles([file]) .responseString({ (string, response) -> Void in self.resultLabel.text = string == "1" ? "success" : "failure" self.clearAllNotice() }) } func SetHTTPHeaders() { self.pleaseWait() Pita.build(HTTPMethod: .GET, url: "http://httpbin.org/headers") .setHTTPHeader(Name: "Accept-Language", Value: "Pitaya Language") .setHTTPHeader(Name: "pitaaaaaaaaaaaaaaa", Value: "ya") .responseString { (string, nil) in self.resultLabel.text = string self.clearAllNotice() } } func SetHTTPRawBody() { let jsonString = JSONND(dictionary: ["key": "pitaaaaaaaaaaaaaaaya"]).RAWValue self.pleaseWait() Pita.build(HTTPMethod: .POST, url: "http://httpbin.org/post") .setHTTPBodyRaw(jsonString, isJSON: true) .responseString { (string, nil) in self.resultLabel.text = string self.clearAllNotice() } } func HTTPBasicAuth() { self.pleaseWait() Pita.build(HTTPMethod: .GET, url: "http://httpbin.org/basic-auth/user/passwd") .setBasicAuth("user", password: "passwd") .responseString { (string, nil) in self.resultLabel.text = string self.clearAllNotice() } } func AddSSLPinning() { let certURL = Bundle(for: ExamplesViewController.self).url(forResource: "lvwenhancom", withExtension: "cer")! let certData = try! Data(contentsOf: certURL) self.pleaseWait() Pita.build(HTTPMethod: .GET, url: "https://lvwenhan.com/") .addSSLPinning(LocalCertData: certData, SSLValidateErrorCallBack: { () -> Void in self.noticeOnlyText("Under the Man-in-the-middle attack!") }) .responseString { (string, nil) in self.resultLabel.text = "lvwenhan.com success" self.clearAllNotice() } self.pleaseWait() Pita.build(HTTPMethod: .GET, url: "https://httpbin.org/get") .addSSLPinning(LocalCertData: certData, SSLValidateErrorCallBack: { () -> Void in self.clearAllNotice() self.noticeOnlyText("httpbin.org is Under the \nMan-in-the-middle attack!") }) .responseString { (string, nil) in self.resultLabel.text = "success" } } func AddManySSLPinning() { let certURL0 = Bundle(for: ExamplesViewController.self).url(forResource: "lvwenhancom", withExtension: "cer")! let certData0 = try! Data(contentsOf: certURL0) let certURL1 = Bundle(for: ExamplesViewController.self).url(forResource: "logo@2x", withExtension: "jpg")! let certData1 = try! Data(contentsOf: certURL1) self.pleaseWait() Pita.build(HTTPMethod: .GET, url: "https://lvwenhan.com/") .addSSLPinning(LocalCertDataArray: [certData0, certData1], SSLValidateErrorCallBack: { () -> Void in self.noticeOnlyText("Under the Man-in-the-middle attack!") }) .responseString { (string, nil) in self.resultLabel.text = "lvwenhan.com success" self.clearAllNotice() } self.pleaseWait() Pita.build(HTTPMethod: .GET, url: "https://httpbin.org/get") .addSSLPinning(LocalCertDataArray: [certData0, certData1], SSLValidateErrorCallBack: { () -> Void in self.clearAllNotice() self.noticeOnlyText("httpbin.org is Under the \nMan-in-the-middle attack!") }) .responseString { (string, nil) in self.resultLabel.text = "success" } } func SyncRequest(){ Pita.build(HTTPMethod: .GET, url: "http://httpbin.org/delay/3", timeout: 10, execution: .sync).responseString { (string, response) in self.resultLabel.text = string } } }
mit
fcc1f40efe52fbac12c520d7eaf84052
38.454545
220
0.59203
4.175439
false
false
false
false
ddimitrov90/EverliveSDK
Tests/Pods/EVReflection/EVReflection/pod/EVExtensions.swift
3
4010
// // EVExtensions.swift // EVReflection // // Created by Edwin Vermeer on 9/2/15. // Copyright © 2015 evict. All rights reserved. // import Foundation /** Implementation for Equatable == - parameter lhs: The object at the left side of the == - parameter rhs: The object at the right side of the == - returns: True if the objects are the same, otherwise false. */ public func == (lhs: EVObject, rhs: EVObject) -> Bool { return EVReflection.areEqual(lhs, rhs: rhs) } /** Implementation for Equatable != - parameter lhs: The object at the left side of the == - parameter rhs: The object at the right side of the == - returns: False if the objects are the the same, otherwise true. */ public func != (lhs: EVObject, rhs: EVObject) -> Bool { return !EVReflection.areEqual(lhs, rhs: rhs) } /** Extending Array with an initializer with a json string */ public extension Array where Element: NSObject { /** Initialize an array based on a json string - parameter json: The json string - parameter conversionOptions: Option set for the various conversion options. */ public init(json: String?, conversionOptions: ConversionOptions = .DefaultDeserialize) { self.init() let arrayTypeInstance = getArrayTypeInstance(self) let newArray = EVReflection.arrayFromJson(nil, type:arrayTypeInstance, json: json, conversionOptions: conversionOptions) for item in newArray { self.append(item) } } /** Initialize an array based on a dictionary - parameter json: The json string - parameter conversionOptions: Option set for the various conversion options. */ public init(dictionaryArray: [NSDictionary], conversionOptions: ConversionOptions = .DefaultDeserialize) { self.init() for item in dictionaryArray { let arrayTypeInstance = getArrayTypeInstance(self) if arrayTypeInstance is EVObject { EVReflection.setPropertiesfromDictionary(item, anyObject: arrayTypeInstance as! EVObject) self.append(arrayTypeInstance) } } } /** Get the type of the object where this array is for - parameter arr: this array - returns: The object type */ public func getArrayTypeInstance<T: NSObject>(arr: Array<T>) -> T { return arr.getTypeInstance() } /** Get the type of the object where this array is for - returns: The object type */ public func getTypeInstance<T: NSObject>( ) -> T { if let nsobjectype: NSObject.Type = T.self { let nsobject: NSObject = nsobjectype.init() if let obj = nsobject as? T { return obj } // Could not instantiate array item instance. will crash return (nsobject as? T)! } // Could not instantiate array item instance. will crash assert(false, "You can only instantiate an array of objects that have EVObject (or NSObject) as its base class. Please make this change to your object: \(T.self)") return (NSObject() as? T)! } /** Convert this array to a json string - parameter conversionOptions: Option set for the various conversion options. - returns: The json string */ public func toJsonString(conversionOptions: ConversionOptions = .DefaultSerialize) -> String { return "[\n" + self.map({($0 as? EVObject ?? EVObject()).toJsonString(conversionOptions)}).joinWithSeparator(", \n") + "\n]" } /** Returns the dictionary representation of this array. - parameter conversionOptions: Option set for the various conversion options. - returns: The array of dictionaries */ public func toDictionaryArray(conversionOptions: ConversionOptions = .DefaultSerialize) -> NSArray { return self.map({($0 as? EVObject ?? EVObject()).toDictionary(conversionOptions)}) } }
mit
7f317a88e447ad139953833ba1c1c8ed
30.81746
171
0.64879
4.597477
false
false
false
false
ranacquat/fish
Carthage/Checkouts/Fusuma/Sources/FSVideoCameraView.swift
1
12640
// // FSVideoCameraView.swift // Fusuma // // Created by Brendan Kirchner on 3/18/16. // Copyright © 2016 CocoaPods. All rights reserved. // import UIKit import AVFoundation @objc protocol FSVideoCameraViewDelegate: class { func videoFinished(withFileURL fileURL: URL) } final class FSVideoCameraView: UIView { @IBOutlet weak var previewViewContainer: UIView! @IBOutlet weak var shotButton: UIButton! @IBOutlet weak var flashButton: UIButton! @IBOutlet weak var flipButton: UIButton! weak var delegate: FSVideoCameraViewDelegate? = nil var session: AVCaptureSession? var device: AVCaptureDevice? var videoInput: AVCaptureDeviceInput? var videoOutput: AVCaptureMovieFileOutput? var focusView: UIView? var flashOffImage: UIImage? var flashOnImage: UIImage? var videoStartImage: UIImage? var videoStopImage: UIImage? fileprivate var isRecording = false static func instance() -> FSVideoCameraView { return UINib(nibName: "FSVideoCameraView", bundle: Bundle(for: self.classForCoder())).instantiate(withOwner: self, options: nil)[0] as! FSVideoCameraView } func initialize() { if session != nil { return } self.backgroundColor = fusumaBackgroundColor self.isHidden = false // AVCapture session = AVCaptureSession() for device in AVCaptureDevice.devices() { if let device = device as? AVCaptureDevice , device.position == AVCaptureDevicePosition.back { self.device = device } } do { if let session = session { videoInput = try AVCaptureDeviceInput(device: device) session.addInput(videoInput) videoOutput = AVCaptureMovieFileOutput() let totalSeconds = 60.0 //Total Seconds of capture time let timeScale: Int32 = 30 //FPS let maxDuration = CMTimeMakeWithSeconds(totalSeconds, timeScale) videoOutput?.maxRecordedDuration = maxDuration videoOutput?.minFreeDiskSpaceLimit = 1024 * 1024 //SET MIN FREE SPACE IN BYTES FOR RECORDING TO CONTINUE ON A VOLUME if session.canAddOutput(videoOutput) { session.addOutput(videoOutput) } let videoLayer = AVCaptureVideoPreviewLayer(session: session) videoLayer?.frame = self.previewViewContainer.bounds videoLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill self.previewViewContainer.layer.addSublayer(videoLayer!) session.startRunning() } // Focus View self.focusView = UIView(frame: CGRect(x: 0, y: 0, width: 90, height: 90)) let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(FSVideoCameraView.focus(_:))) self.previewViewContainer.addGestureRecognizer(tapRecognizer) } catch { } let bundle = Bundle(for: self.classForCoder) flashOnImage = fusumaFlashOnImage != nil ? fusumaFlashOnImage : UIImage(named: "ic_flash_on", in: bundle, compatibleWith: nil) flashOffImage = fusumaFlashOffImage != nil ? fusumaFlashOffImage : UIImage(named: "ic_flash_off", in: bundle, compatibleWith: nil) let flipImage = fusumaFlipImage != nil ? fusumaFlipImage : UIImage(named: "ic_loop", in: bundle, compatibleWith: nil) videoStartImage = fusumaVideoStartImage != nil ? fusumaVideoStartImage : UIImage(named: "video_button", in: bundle, compatibleWith: nil) videoStopImage = fusumaVideoStopImage != nil ? fusumaVideoStopImage : UIImage(named: "video_button_rec", in: bundle, compatibleWith: nil) if(fusumaTintIcons) { flashButton.tintColor = fusumaBaseTintColor flipButton.tintColor = fusumaBaseTintColor shotButton.tintColor = fusumaBaseTintColor flashButton.setImage(flashOffImage?.withRenderingMode(.alwaysTemplate), for: UIControlState()) flipButton.setImage(flipImage?.withRenderingMode(.alwaysTemplate), for: UIControlState()) shotButton.setImage(videoStartImage?.withRenderingMode(.alwaysTemplate), for: UIControlState()) } else { flashButton.setImage(flashOffImage, for: UIControlState()) flipButton.setImage(flipImage, for: UIControlState()) shotButton.setImage(videoStartImage, for: UIControlState()) } if (DeviceType.IS_IPAD || DeviceType.IS_IPAD_PRO) { print("VIDEO : IS_IPAD : NO FLASH CONFIGURATION") }else{ flashConfiguration() } self.startCamera() } deinit { NotificationCenter.default.removeObserver(self) } func startCamera() { let status = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo) if status == AVAuthorizationStatus.authorized { session?.startRunning() } else if status == AVAuthorizationStatus.denied || status == AVAuthorizationStatus.restricted { session?.stopRunning() } } func stopCamera() { if self.isRecording { self.toggleRecording() } session?.stopRunning() } @IBAction func shotButtonPressed(_ sender: UIButton) { self.toggleRecording() } fileprivate func toggleRecording() { guard let videoOutput = videoOutput else { return } self.isRecording = !self.isRecording let shotImage: UIImage? if self.isRecording { shotImage = videoStopImage } else { shotImage = videoStartImage } self.shotButton.setImage(shotImage, for: UIControlState()) if self.isRecording { let outputPath = "\(NSTemporaryDirectory())output.mov" let outputURL = URL(fileURLWithPath: outputPath) let fileManager = FileManager.default if fileManager.fileExists(atPath: outputPath) { do { try fileManager.removeItem(atPath: outputPath) } catch { print("error removing item at path: \(outputPath)") self.isRecording = false return } } self.flipButton.isEnabled = false self.flashButton.isEnabled = false videoOutput.startRecording(toOutputFileURL: outputURL, recordingDelegate: self) } else { videoOutput.stopRecording() self.flipButton.isEnabled = true self.flashButton.isEnabled = true } return } @IBAction func flipButtonPressed(_ sender: UIButton) { session?.stopRunning() do { session?.beginConfiguration() if let session = session { for input in session.inputs { session.removeInput(input as! AVCaptureInput) } let position = (videoInput?.device.position == AVCaptureDevicePosition.front) ? AVCaptureDevicePosition.back : AVCaptureDevicePosition.front for device in AVCaptureDevice.devices(withMediaType: AVMediaTypeVideo) { if let device = device as? AVCaptureDevice , device.position == position { videoInput = try AVCaptureDeviceInput(device: device) session.addInput(videoInput) } } } session?.commitConfiguration() } catch { } session?.startRunning() } @IBAction func flashButtonPressed(_ sender: UIButton) { do { if let device = device { try device.lockForConfiguration() let mode = device.flashMode if mode == AVCaptureFlashMode.off { device.flashMode = AVCaptureFlashMode.on flashButton.setImage(flashOnImage, for: UIControlState()) } else if mode == AVCaptureFlashMode.on { device.flashMode = AVCaptureFlashMode.off flashButton.setImage(flashOffImage, for: UIControlState()) } device.unlockForConfiguration() } } catch _ { flashButton.setImage(flashOffImage, for: UIControlState()) return } } } extension FSVideoCameraView: AVCaptureFileOutputRecordingDelegate { func capture(_ captureOutput: AVCaptureFileOutput!, didStartRecordingToOutputFileAt fileURL: URL!, fromConnections connections: [Any]!) { print("started recording to: \(fileURL)") } func capture(_ captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAt outputFileURL: URL!, fromConnections connections: [Any]!, error: Error!) { print("finished recording to: \(outputFileURL)") self.delegate?.videoFinished(withFileURL: outputFileURL) } } extension FSVideoCameraView { func focus(_ recognizer: UITapGestureRecognizer) { let point = recognizer.location(in: self) let viewsize = self.bounds.size let newPoint = CGPoint(x: point.y/viewsize.height, y: 1.0-point.x/viewsize.width) let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) do { try device?.lockForConfiguration() } catch _ { return } if device?.isFocusModeSupported(AVCaptureFocusMode.autoFocus) == true { device?.focusMode = AVCaptureFocusMode.autoFocus device?.focusPointOfInterest = newPoint } if device?.isExposureModeSupported(AVCaptureExposureMode.continuousAutoExposure) == true { device?.exposureMode = AVCaptureExposureMode.continuousAutoExposure device?.exposurePointOfInterest = newPoint } device?.unlockForConfiguration() self.focusView?.alpha = 0.0 self.focusView?.center = point self.focusView?.backgroundColor = UIColor.clear self.focusView?.layer.borderColor = UIColor.white.cgColor self.focusView?.layer.borderWidth = 1.0 self.focusView!.transform = CGAffineTransform(scaleX: 1.0, y: 1.0) self.addSubview(self.focusView!) UIView.animate(withDuration: 0.8, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 3.0, options: UIViewAnimationOptions.curveEaseIn, // UIViewAnimationOptions.BeginFromCurrentState animations: { self.focusView!.alpha = 1.0 self.focusView!.transform = CGAffineTransform(scaleX: 0.7, y: 0.7) }, completion: {(finished) in self.focusView!.transform = CGAffineTransform(scaleX: 1.0, y: 1.0) self.focusView!.removeFromSuperview() }) } func flashConfiguration() { do { if let device = device { try device.lockForConfiguration() device.flashMode = AVCaptureFlashMode.off flashButton.setImage(flashOffImage, for: UIControlState()) device.unlockForConfiguration() } } catch _ { return } } }
mit
75b8a2951b44945d36ecf32162f0ade6
33.252033
163
0.557956
6.3195
false
false
false
false
rhwood/Doing-Time
Classes/AboutView.swift
1
2688
// // AboutView.swift // Doing Time // // Created by Randall Wood on 2020-11-18. // // Copyright 2020 Randall Wood DBA Alexandria Software // // 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 SwiftUI struct AboutView: View { let logoUrl = "http://axsw.co/fufMuq" let webUrl = "http://axsw.co/icgDcu" let twitterUrl = "http://axsw.co/f4dzGc" let facebookUrl = "http://axsw.co/eaDeKF" let supportUrl = "http://axsw.co/fO5256" let product = Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String ?? "UNK" let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "UNK" let build = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "UNK" var body: some View { List { Section { imageLink(destination: URL(string: logoUrl)!, image: "ASlogo1-64x192") } Section(footer: Text("\(product) version \(version) (\(build))")) { textLink(destination: URL(string: webUrl)!, primary: "Web", secondary: "alexandriasoftware.com") textLink(destination: URL(string: twitterUrl)!, primary: "Twitter", secondary: "@alexandriasw") textLink(destination: URL(string: facebookUrl)!, primary: "Facebook", secondary: "Like Us!") textLink(destination: URL(string: supportUrl)!, primary: "Support", secondary: "Contact Us") } }.listStyle(GroupedListStyle()) } private func imageLink(destination: URL, image: String) -> some View { Link(destination: destination) { HStack { Spacer() Image(image) Spacer() } } } private func textLink(destination: URL, primary: String, secondary: String) -> some View { Link(destination: destination) { HStack { Text(primary).foregroundColor(.primary) Spacer() Text(secondary) } } } } struct AboutView_Previews: PreviewProvider { static var previews: some View { AboutView() } }
mit
b1bdfa4b56c76b115f1e174d2ee14af8
35.821918
112
0.625
4.180404
false
false
false
false
ontouchstart/swift3-playground
123/123.playgroundbook/Contents/Chapters/1.playgroundchapter/Pages/2.playgroundpage/Contents.swift
1
335
/*: # 2 */ print("2: Hello world") import UIKit import PlaygroundSupport let frame = CGRect(x: 0, y:0, width: 400, height: 300) let label = UILabel(frame: frame) label.text = "2: Hello world" label.textColor = .blue label.textAlignment = .center label.font = UIFont.boldSystemFont(ofSize: 60) PlaygroundPage.current.liveView = label
mit
198ae3123ce1467ccdaa515239181caf
21.333333
54
0.728358
3.316832
false
false
false
false
informmegp2/inform-me
InformME/CenterCellCollectionViewFlowLayout.swift
1
2297
// // CenterCellCollectionViewFlowLayout.swift // InformME // // Created by Amal Ibrahim on 3/3/16. // Copyright © 2016 King Saud University. All rights reserved. // import Foundation import UIKit class CenterCellCollectionViewFlowLayout: UICollectionViewFlowLayout { override func targetContentOffsetForProposedContentOffset(proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint { if let cv = self.collectionView { let cvBounds = cv.bounds let halfWidth = cvBounds.size.width * 0.5; let proposedContentOffsetCenterX = proposedContentOffset.x + halfWidth; if let attributesForVisibleCells = self.layoutAttributesForElementsInRect(cvBounds)! as[UICollectionViewLayoutAttributes]? { var candidateAttributes : UICollectionViewLayoutAttributes? for attributes in attributesForVisibleCells { // == Skip comparison with non-cell items (headers and footers) == // if attributes.representedElementCategory != UICollectionElementCategory.Cell { continue } if let candAttrs = candidateAttributes { let a = attributes.center.x - proposedContentOffsetCenterX let b = candAttrs.center.x - proposedContentOffsetCenterX if fabsf(Float(a)) < fabsf(Float(b)) { candidateAttributes = attributes; } } else { // == First time in the loop == // candidateAttributes = attributes; continue; } } return CGPoint(x: round(candidateAttributes!.center.x - halfWidth), y: proposedContentOffset.y) } } // Fallback return super.targetContentOffsetForProposedContentOffset(proposedContentOffset) } }
mit
4abba7ceb5a28f5095efcb08bc89c508
37.283333
147
0.524826
7.152648
false
false
false
false
rowungiles/SwiftTech
SwiftTech/SwiftTech/Utilities/Indexing/RestaurantIndexer.swift
1
2148
// // RestaurantIndexer.swift // SwiftTech // // Created by Rowun Giles on 04/01/2016. // Copyright © 2016 Rowun Giles. All rights reserved. // import Foundation import CoreSpotlight import MobileCoreServices struct RestaurantIndexer { // todo: removing items from indexes static func indexRestaurants(restaurants: [RestaurantStruct], outcode: String) { let searchableItems = restaurants.map { restaurant -> CSSearchableItem in let attributeSet = attributeSetFromRestaurant(restaurant, outcode: outcode) return searchableItemFromAttributeSet(attributeSet, outcode: outcode, restaurant: restaurant) } indexSearchableItems(searchableItems, attemptCount: 3) } static private func indexSearchableItems(searchableItems: [CSSearchableItem], attemptCount: Int) { guard attemptCount != 0 else { print("Error: failed to add index items after multiple attempts") return } CSSearchableIndex.defaultSearchableIndex().indexSearchableItems(searchableItems) { (error) -> Void in guard error == nil else { indexSearchableItems(searchableItems, attemptCount: attemptCount - 1) return } } } static private func attributeSetFromRestaurant(restaurant: RestaurantStruct, outcode: String) -> CSSearchableItemAttributeSet { let attributeSet = CSSearchableItemAttributeSet(itemContentType: kUTTypeContent as String) attributeSet.displayName = restaurant.name attributeSet.title = restaurant.name attributeSet.keywords = restaurant.cuisines.map{ $0.name } return attributeSet } static private func searchableItemFromAttributeSet(attributeSet: CSSearchableItemAttributeSet, outcode: String, restaurant: RestaurantStruct) -> CSSearchableItem { return CSSearchableItem(uniqueIdentifier: restaurant.url, domainIdentifier: Constants.reverseHost + ".outcode." + outcode, attributeSet: attributeSet) } }
gpl-3.0
ae6efb41027247daf1c5004e6387980a
35.40678
167
0.675827
5.591146
false
false
false
false
JimmyPeng4iOS/JMWaterFlow
WaterFlowView/WaterFlowViewLayout.swift
1
4876
// // WaterFlowViewLayout.swift // JMWaterFlow // // Created by Jimmy on 15/10/11. // Copyright © 2015年 Jimmy. All rights reserved. // import UIKit //代理 protocol WaterFlowViewLayoutDelegate: NSObjectProtocol { /// Width是瀑布流每列的宽度 func waterFlowViewLayout(waterFlowViewLayout: WaterFlowViewLayout, heightForWidth: CGFloat,atIndexPath: NSIndexPath) -> CGFloat } ///自定义布局 class WaterFlowViewLayout: UICollectionViewLayout { ///间隔,默认8 static var Margin: CGFloat = 8 /// 瀑布流四周的间距 var sectionInsert = UIEdgeInsets(top: Margin, left: Margin, bottom: Margin, right: Margin) /// 瀑布流列数 var column = 4 /// 列间距 var columnMargin: CGFloat = Margin /// 行间距 var rowMargin: CGFloat = Margin /// 布局的代理 weak var delegate: WaterFlowViewLayoutDelegate? /// 所有cell的布局属性 var layoutAttributes = [UICollectionViewLayoutAttributes]() /// 使用一个字典记录每列的最大Y值 var maxYDict = [Int: CGFloat]() var maxY: CGFloat = 0 var columnWidth: CGFloat = 0 // prepareLayout会在调用collectionView.reloadData() override func prepareLayout() { // 设置布局 // 需要清空字典里面的值 for key in 0..<column { maxYDict[key] = 0 } // 清空之前的布局属性 layoutAttributes.removeAll() // 清空最大列的Y值 maxY = 0 // 清空列宽 columnWidth = 0 // 计算每列的宽度,需要在布局之前算好 columnWidth = (UIScreen.mainScreen().bounds.width - sectionInsert.left - sectionInsert.right - (CGFloat(column) - 1) * columnMargin) / CGFloat(column) // 有多少个cell要显示 let number = collectionView?.numberOfItemsInSection(0) ?? 0 for i in 0..<number { // 布局每一个cell的frame let layoutAttr = layoutAttributesForItemAtIndexPath(NSIndexPath(forItem: i, inSection: 0))! layoutAttributes.append(layoutAttr) } // 在布局之后计算最大Y值 calcMaxY() } func calcMaxY() { // 获取最大这一列的Y // 默认第0列最长 var maxYCoulumn = 0 // for循环比较,获取最长的这列 for (key, value) in maxYDict { // value的Y值大于目前Y值最大的这列 if value > maxYDict[maxYCoulumn] { // key这列的Y值是最大的 maxYCoulumn = key } } // 获取到Y值最大的这一列 maxY = maxYDict[maxYCoulumn]! + sectionInsert.bottom } // 返回collectionViewcontentSize大小 override func collectionViewContentSize() -> CGSize { return CGSize(width: UIScreen.mainScreen().bounds.width, height: maxY) } // 返回每一个cell的布局属性(layoutAttributes) override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? { assert(delegate != nil, "瀑布流必须实现代理来返回cell的高度") // 高度通过代理传入 let height = delegate!.waterFlowViewLayout(self, heightForWidth: columnWidth, atIndexPath: indexPath) // 最短的这一列 var minYColumn = 0 // 通过for循环去和其他列比较 for (key, value) in maxYDict { // value 当前遍历出来的这一列的高度 if value < maxYDict[minYColumn] { // maxYDict[minYColumn] 之前最短的哪一列 // 说明 key这一列小于 minYColumn这一列,将key这个设置为最小的那一列 minYColumn = key } } // minYColumn 就是短的那一列 let x = sectionInsert.left + CGFloat(minYColumn) * (columnWidth + columnMargin) // 最短这列的Y值 + 行间距 let y = maxYDict[minYColumn]! + rowMargin // 设置cell的frame let frame = CGRect(x: x, y: y, width: columnWidth, height: height) // 更新最短这列的最大Y值 maxYDict[minYColumn] = CGRectGetMaxY(frame) // 创建每个cell对应的布局属性 let layoutAttr = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath) layoutAttr.frame = frame return layoutAttr } // 预加载下一页数据 override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? { return layoutAttributes } }
apache-2.0
fe4b1e1b066eb7f57588a07645252b4a
25.345912
158
0.581523
4.37722
false
false
false
false
PhillipEnglish/TIY-Assignments
Jackpot/QuickPickTableViewController.swift
1
2313
// // QuickPickTableViewController.swift // Jackpot // // Created by Phillip English on 10/13/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import UIKit class QuickPickTableViewController: UITableViewController { var quickPickTableArray = Array<String>() var ticketNumber = 1 override func viewDidLoad() { super.viewDidLoad() loadNumbers() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return quickPickTableArray.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("quickPickCell", forIndexPath: indexPath) // Configure the cell... let aQuickPick = quickPickTableArray[indexPath.row] cell.textLabel?.text = String(aQuickPick) return cell } //@IBAction func testFunc(Sender: UIBarButtonItem) @IBAction func addButton(sender: UIBarButtonItem) { loadNumbers() // listening to Keron let newPath = NSIndexPath(forRow: quickPickTableArray.count, inSection: 0) //Create Ticket //Add ticket to array //loadNumbers() } // MARK: - Private private func loadNumbers() { let aNumber = LottoNumbers() quickPickTableArray.append("\(ticketNumber): \(aNumber.toString())") ticketNumber++ tableView.reloadData() } }
cc0-1.0
3a7212d3f9bb78664cc2741fd4d449c4
25.272727
118
0.649221
5.376744
false
false
false
false
lanit-tercom-school/grouplock
GroupLockiOS/GroupLock/Core/CryptoFake.swift
1
9905
// // CryptoFake.swift // GroupLock // // Created by Sergej Jaskiewicz on 16.08.16. // Copyright © 2016 Lanit-Tercom School. All rights reserved. // import Foundation import CoreGraphics import ImageIO import MobileCoreServices class CryptoFake: CryptoWrapperProtocol { let maximumNumberOfKeys = 15 /** Creates 120-digit random key and represents it as a String. - parameter min: Concrete value does not play a role for now - parameter max: Number of parts to divide the key into. - precondition: `max` is not greater than `maximumNumberOfKeys` and `min` is not greater than `max` - returns: String representation of the key */ func getKeys(min: Int, max: Int) -> [String] { precondition(max <= maximumNumberOfKeys, "Maximum number of keys provided exceeds the value of maximumNumberOfKeys") precondition(min <= max, "min should be less than or equal to max") let digitalKey = (0 ..< 40).map { _ in UInt8(arc4random_uniform(256)) } let stringKey = digitalKey.map { String(format: "%03d", $0) }.reduce("", +) return splitKey(stringKey, intoParts: max) .enumerated() .map { String(format: "%02d%02d", $0, max) + $1 } } private func splitKey(_ key: String, intoParts parts: Int) -> [String] { let splittedSize = Int(round(Double(key.characters.count) / Double(parts))) return (0 ..< parts - 1).map { (i: Int) -> String in let start = key.characters.index(key.startIndex, offsetBy: i * splittedSize) let end = key.characters.index(key.startIndex, offsetBy: (i + 1) * splittedSize) return key.substring(with: start ..< end) } + [key.substring(from: key.characters.index(key.startIndex, offsetBy: (parts - 1) * splittedSize))] } private func mergeKeys(_ keys: [String]) -> String { return keys.reduce("", +) } func validate(key: [String]) -> Bool { guard let processedKey = processKeys(key) else { return false } let parsedKey = parse(key: processedKey) // swiftlint:disable:next force_unwrapping (since we check for nil) return parsedKey != nil && parsedKey!.count > 3 } func validatePart(_ key: String) -> Bool { let regex = try? NSRegularExpression(pattern: "[0-9]+", options: []) let stringToMatch = key as NSString return !(regex?.matches(in: key, options: [], range: NSRange(location: 0, length: stringToMatch.length)).isEmpty ?? true) } /** Encrypts given image with given key. Expands the key using linear congruential pseudorandom generator and encrypts the image using improved Kasenkov's cipher - parameter data: Image data to encrypt - parameter key: Encryption key - precondition: `key` is at least 12 digits long. - returns: Encrypted data, or `nil` is something went wrong. For example, the key is invalid or the data is not image-representable */ func encrypt(image data: Data, withEncryptionKey key: [String]) -> Data? { guard let mergedKey = processKeys(key), let parsedKey = parse(key: mergedKey), let cgImage = image(from: data) else { return nil } let expandedKey = expand(parsedKey, for: cgImage) let imagePixelsBuffer = cgImage.createPixelsBuffer() encryptPixels(imagePixelsBuffer, withKey: expandedKey) let encryptedImage = CGImage.createFromPixelsBuffer(imagePixelsBuffer, width: cgImage.width, height: cgImage.height) imagePixelsBuffer.baseAddress?.deinitialize() imagePixelsBuffer.baseAddress?.deallocate(capacity: cgImage.width * cgImage.height) return encryptedImage?.createPNGData() } /** Decrypts given image with given decryption key. Expands the key using linear congruential pseudorandom generator and decrypts the image using improved Kasenkov's cipher - parameter data: Encrypted data - parameter key: Decryption key - precondition: `key` is at least 12 digits long. - returns: Decrypted data, or `nil` is something went wrong. For example, the key is invalid or the data is not image-representable */ func decrypt(image data: Data, withDecryptionKey key: [String]) -> Data? { guard let mergedKey = processKeys(key), let parsedKey = parse(key: mergedKey), let cgImage = image(from: data) else { return nil } let expandedKey = expand(parsedKey, for: cgImage) let imagePixelsBuffer = cgImage.createPixelsBuffer() decryptPixels(imagePixelsBuffer, withKey: expandedKey) let decryptedImage = CGImage.createFromPixelsBuffer(imagePixelsBuffer, width: cgImage.width, height: cgImage.height) imagePixelsBuffer.baseAddress?.deinitialize() imagePixelsBuffer.baseAddress?.deallocate(capacity: cgImage.width * cgImage.height) return decryptedImage?.createPNGData() } private func processKeys(_ keys: [String]) -> String? { guard keys.map(validatePart).reduce(true, { $0 && $1 }) else { return nil } return mergeKeys( keys.map { (key: String) -> (Int, String) in let numberIndex = key.index(key.startIndex, offsetBy: 2) let keyIndex = key.index(key.startIndex, offsetBy: 4) // swiftlint:disable:next force_unwrapping (since we validate the key) let number = Int(key.substring(to: numberIndex))! let key = key.substring(from: keyIndex) return (number, key) }.sorted { $0.0 < $0.0 }.map { $0.1 } ) } private func expand(_ key: [UInt8], for image: CGImage) -> [UInt8] { let numberOfPixels = image.height * image.width let expandingFactor = numberOfPixels / key.count + 1 func generateExpansion(for element: UInt8) -> [UInt8] { let lcg = LinearCongruentialGenerator(seed: Double(element)) let expansion: [UInt8] = (0 ..< expandingFactor).map({ _ in return UInt8(lcg.random() * 255) }) return expansion } return key.flatMap(generateExpansion) } private func image(from data: Data) -> CGImage? { // swiftlint:disable:next force_unwrapping (no failure case is documented, what can possibly go wrong) let cgDataProvider = CGDataProvider(data: data as CFData)! switch getImageType(from: data) { case .some("JPG"): return CGImage(jpegDataProviderSource: cgDataProvider, decode: nil, shouldInterpolate: false, intent: .defaultIntent)! // swiftlint:disable:previous force_unwrapping (since we check for type) case .some("PNG"): return CGImage(pngDataProviderSource: cgDataProvider, decode: nil, shouldInterpolate: false, intent: .defaultIntent)! // swiftlint:disable:previous force_unwrapping (since we check for type) default: return nil } } private func getImageType(from data: Data) -> String? { var acc: UInt8 = 0 data.copyBytes(to: &acc, count: 1) switch acc { case 0xFF: return "JPG" case 0x89: return "PNG" case 0x47: return "GIF" case 0x49, 0x4D: return "TIFF" default: return nil } } private func parse(key: String) -> [UInt8]? { guard !key.characters.isEmpty else { return nil } let digits = key.characters.map { String.init($0) } var parsedKey = [UInt8](repeating: 0, count: digits.count / 3) for i in stride(from: 0, to: digits.count, by: 3) where i + 2 < digits.count { if let number = UInt8(digits[i] + digits[i + 1] + digits[i + 2]) { parsedKey[i / 3] = number } else { return nil } } return parsedKey } private struct ColorOffsets { static let red = 234 static let green = -132 static let blue = 17 } func decryptPixels(_ pixels: UnsafeMutableBufferPointer<UInt32>, withKey key: [UInt8]) { precondition(key.count > 3, "key is too short") for i in 0 ..< pixels.count { let value = pixels[i] let _r = (value & 0xFF0000) >> 16 let _g = (value & 0xFF00) >> 8 let _b = value & 0xFF let r = (Int(_r) - Int(key[i % (key.count - 3) ]) + 512 - ColorOffsets.red) % 256 let g = (Int(_g) - Int(key[i % (key.count - 3) + 1]) + 512 - ColorOffsets.green) % 256 let b = (Int(_b) - Int(key[i % (key.count - 3) + 2]) + 512 - ColorOffsets.blue) % 256 pixels[i] = (value & 0xFF000000) | UInt32(r) << 16 | UInt32(g) << 8 | UInt32(b) } } private func encryptPixels(_ pixels: UnsafeMutableBufferPointer<UInt32>, withKey key: [UInt8]) { precondition(key.count > 3, "key is too short") for index in 0 ..< pixels.count { let value = pixels[index] let _r = (value & 0xFF0000) >> 16 let _g = (value & 0xFF00) >> 8 let _b = value & 0xFF let r = (Int(_r) + Int(key[index % (key.count - 3) ]) + 512 + ColorOffsets.red) % 256 let g = (Int(_g) + Int(key[index % (key.count - 3) + 1]) + 512 + ColorOffsets.green) % 256 let b = (Int(_b) + Int(key[index % (key.count - 3) + 2]) + 512 + ColorOffsets.blue) % 256 pixels[index] = (value & 0xFF000000) | UInt32(r) << 16 | UInt32(g) << 8 | UInt32(b) } } }
apache-2.0
48bb0739934469f5f4f2cc8baa06ddd5
36.233083
113
0.591882
4.157851
false
false
false
false
gobetti/Swift
Airdrop/Airdrop/URLViewController.swift
1
1628
// // URLViewController.swift // Airdrop // // Created by Carlos Butron on 07/12/14. // Copyright (c) 2014 Carlos Butron. // import UIKit class URLViewController: UIViewController, UIWebViewDelegate { @IBOutlet weak var myURL: UITextField! @IBOutlet weak var webView: UIWebView! @IBAction func send(sender: UIButton) { let url:NSURL = NSURL(string: myURL.text!)! let controller = UIActivityViewController(activityItems: [url], applicationActivities: nil) self.presentViewController(controller, animated: true, completion: nil) } @IBAction func load(sender: UIButton) { let request = NSURLRequest(URL: NSURL(string: myURL.text!)!) self.webView.loadRequest(request) } override func viewDidLoad() { super.viewDidLoad() myURL.text = "http://carlosbutron.es/" webView.delegate = self let request = NSURLRequest(URL: NSURL(string: myURL.text!)!) self.webView.loadRequest(request) // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
6f0915d00066402b1f733eb62e12d5bf
28.071429
106
0.660934
4.845238
false
false
false
false
KrishMunot/swift
stdlib/public/core/SequenceWrapper.swift
2
2783
//===--- SequenceWrapper.swift - sequence/collection wrapper protocols ----===// // // 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 // //===----------------------------------------------------------------------===// // // To create a Sequence that forwards requirements to an // underlying Sequence, have it conform to this protocol. // //===----------------------------------------------------------------------===// /// A type that is just a wrapper over some base Sequence @_show_in_interface public // @testable protocol _SequenceWrapper { associatedtype Base : Sequence associatedtype Iterator : IteratorProtocol = Base.Iterator var _base: Base { get } } extension _SequenceWrapper where Self : Sequence, Self.Iterator == Self.Base.Iterator { public var underestimatedCount: Int { return _base.underestimatedCount } } extension Sequence where Self : _SequenceWrapper, Self.Iterator == Self.Base.Iterator { /// Return an iterator over the elements of this sequence. /// /// - Complexity: O(1). public func makeIterator() -> Base.Iterator { return self._base.makeIterator() } @warn_unused_result public func map<T>( @noescape _ transform: (Base.Iterator.Element) throws -> T ) rethrows -> [T] { return try _base.map(transform) } @warn_unused_result public func filter( @noescape _ includeElement: (Base.Iterator.Element) throws -> Bool ) rethrows -> [Base.Iterator.Element] { return try _base.filter(includeElement) } public func _customContainsEquatableElement( _ element: Base.Iterator.Element ) -> Bool? { return _base._customContainsEquatableElement(element) } /// If `self` is multi-pass (i.e., a `Collection`), invoke /// `preprocess` on `self` and return its result. Otherwise, return /// `nil`. public func _preprocessingPass<R>(@noescape _ preprocess: () -> R) -> R? { return _base._preprocessingPass(preprocess) } /// Create a native array buffer containing the elements of `self`, /// in the same order. public func _copyToNativeArrayBuffer() -> _ContiguousArrayBuffer<Base.Iterator.Element> { return _base._copyToNativeArrayBuffer() } /// Copy a Sequence into an array, returning one past the last /// element initialized. public func _copyContents( initializing ptr: UnsafeMutablePointer<Base.Iterator.Element> ) -> UnsafeMutablePointer<Base.Iterator.Element> { return _base._copyContents(initializing: ptr) } }
apache-2.0
f55a7e7fc3c5fdeb0590bec145d1cd87
29.922222
80
0.65972
4.495961
false
false
false
false
evgenyneu/moa
Demo/CollectionViewCell.swift
1
564
import UIKit import moa class CollectionViewCell: UICollectionViewCell { @IBOutlet weak var imageView: UIImageView! override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func prepareForDisplay() { backgroundColor = MoaColor.random if let appDelegate = UIApplication.shared.delegate as? AppDelegate { imageView.image = nil // clear previous image let url = appDelegate.randomImageUrl.url imageView.moa.url = url } } }
mit
c523f926eea279a1a52c45e2f0dc9dfd
22.5
72
0.68617
4.440945
false
false
false
false
xwu/swift
libswift/Sources/SIL/Registration.swift
1
4710
//===--- Registration.swift - register SIL classes ------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SILBridging private func register<T: AnyObject>(_ cl: T.Type) { String(describing: cl).withBridgedStringRef { nameStr in let metatype = unsafeBitCast(cl, to: SwiftMetatype.self) registerBridgedClass(nameStr, metatype) } } public func registerSILClasses() { register(Function.self) register(BasicBlock.self) register(GlobalVariable.self) // The "unimplemented" registrations must be done before all other node // registrations. In the order from super -> sub class. register(UnimplementedInstruction.self) register(UnimplementedSingleValueInst.self) register(UnimplementedRefCountingInst.self) register(MultipleValueInstructionResult.self) register(Undef.self) register(PlaceholderValue.self) register(FunctionArgument.self) register(BlockArgument.self) register(StoreInst.self) register(CopyAddrInst.self) register(EndAccessInst.self) register(EndBorrowInst.self) register(DeallocStackInst.self) register(CondFailInst.self) register(FixLifetimeInst.self) register(DebugValueInst.self) register(UnconditionalCheckedCastAddrInst.self) register(SetDeallocatingInst.self) register(DeallocRefInst.self) register(StrongRetainInst.self) register(RetainValueInst.self) register(StrongReleaseInst.self) register(ReleaseValueInst.self) register(DestroyValueInst.self) register(DestroyAddrInst.self) register(LoadInst.self) register(LoadBorrowInst.self) register(BuiltinInst.self) register(UpcastInst.self) register(UncheckedRefCastInst.self) register(RawPointerToRefInst.self) register(AddressToPointerInst.self) register(PointerToAddressInst.self) register(IndexAddrInst.self) register(InitExistentialRefInst.self) register(OpenExistentialRefInst.self) register(InitExistentialValueInst.self) register(OpenExistentialValueInst.self) register(InitExistentialAddrInst.self) register(OpenExistentialAddrInst.self) register(OpenExistentialBoxInst.self) register(OpenExistentialBoxValueInst.self) register(InitExistentialMetatypeInst.self) register(OpenExistentialMetatypeInst.self) register(ValueMetatypeInst.self) register(ExistentialMetatypeInst.self) register(GlobalAddrInst.self) register(GlobalValueInst.self) register(TupleInst.self) register(TupleExtractInst.self) register(TupleElementAddrInst.self) register(StructInst.self) register(StructExtractInst.self) register(StructElementAddrInst.self) register(EnumInst.self) register(UncheckedEnumDataInst.self) register(RefElementAddrInst.self) register(RefTailAddrInst.self) register(UnconditionalCheckedCastInst.self) register(UnconditionalCheckedCastValueInst.self) register(ConvertFunctionInst.self) register(ThinToThickFunctionInst.self) register(ObjCExistentialMetatypeToObjectInst.self) register(ObjCMetatypeToObjectInst.self) register(ValueToBridgeObjectInst.self) register(BridgeObjectToRefInst.self) register(BeginAccessInst.self) register(BeginBorrowInst.self) register(CopyValueInst.self) register(EndCOWMutationInst.self) register(ClassifyBridgeObjectInst.self) register(PartialApplyInst.self) register(ApplyInst.self) register(ClassMethodInst.self) register(SuperMethodInst.self) register(ObjCMethodInst.self) register(ObjCSuperMethodInst.self) register(WitnessMethodInst.self) register(AllocStackInst.self) register(AllocRefInst.self) register(AllocRefDynamicInst.self) register(AllocBoxInst.self) register(AllocExistentialBoxInst.self) register(BeginCOWMutationInst.self) register(DestructureStructInst.self) register(DestructureTupleInst.self) register(BeginApplyInst.self) register(UnreachableInst.self) register(ReturnInst.self) register(ThrowInst.self) register(YieldInst.self) register(UnwindInst.self) register(TryApplyInst.self) register(BranchInst.self) register(CondBranchInst.self) register(SwitchValueInst.self) register(SwitchEnumInst.self) register(SwitchEnumAddrInst.self) register(DynamicMethodBranchInst.self) register(AwaitAsyncContinuationInst.self) register(CheckedCastBranchInst.self) register(CheckedCastAddrBranchInst.self) register(CheckedCastValueBranchInst.self) }
apache-2.0
f5159e13fa613005370912c4edbb3b24
33.379562
80
0.79448
4.153439
false
false
false
false
aschwaighofer/swift
test/attr/attr_originally_definedin_backward_compatibility.swift
1
2989
// REQUIRES: OS=macosx // REQUIRES: executable_test // // RUN: %empty-directory(%t) // // ----------------------------------------------------------------------------- // --- Prepare SDK (.swiftmodule). // RUN: %empty-directory(%t/SDK) // // --- Build original high level framework. // RUN: mkdir -p %t/SDK/Frameworks/HighLevel.framework/Modules/HighLevel.swiftmodule // RUN: %target-build-swift-dylib(%t/SDK/Frameworks/HighLevel.framework/HighLevel) -module-name HighLevel -emit-module \ // RUN: -emit-module-path %t/SDK/Frameworks/HighLevel.framework/Modules/HighLevel.swiftmodule/%module-target-triple.swiftmodule \ // RUN: %S/Inputs/SymbolMove/HighLevelOriginal.swift -Xlinker -install_name -Xlinker @rpath/HighLevel.framework/HighLevel -enable-library-evolution // --- Build an executable using the original high level framework // RUN: %target-build-swift -emit-executable %s -g -o %t/HighlevelRunner -F %t/SDK/Frameworks/ -framework HighLevel \ // RUN: -Xlinker -rpath -Xlinker %t/SDK/Frameworks // --- Run the executable // RUN: %t/HighlevelRunner | %FileCheck %s -check-prefix=BEFORE_MOVE // --- Build low level framework. // RUN: mkdir -p %t/SDK/Frameworks/LowLevel.framework/Modules/LowLevel.swiftmodule // RUN: %target-build-swift-dylib(%t/SDK/Frameworks/LowLevel.framework/LowLevel) -module-name LowLevel -emit-module \ // RUN: -emit-module-path %t/SDK/Frameworks/LowLevel.framework/Modules/LowLevel.swiftmodule/%module-target-triple.swiftmodule \ // RUN: %S/Inputs/SymbolMove/LowLevel.swift -Xlinker -install_name -Xlinker @rpath/LowLevel.framework/LowLevel -enable-library-evolution // --- Build high level framework. // RUN: mkdir -p %t/SDK/Frameworks/HighLevel.framework/Modules/HighLevel.swiftmodule // RUN: %target-build-swift-dylib(%t/SDK/Frameworks/HighLevel.framework/HighLevel) -module-name HighLevel -emit-module \ // RUN: -emit-module-path %t/SDK/Frameworks/HighLevel.framework/Modules/HighLevel.swiftmodule/%module-target-triple.swiftmodule \ // RUN: %S/Inputs/SymbolMove/HighLevel.swift -F %t/SDK/Frameworks -Xlinker -reexport_framework -Xlinker LowLevel -enable-library-evolution // --- Run the executable // RUN: %t/HighlevelRunner | %FileCheck %s -check-prefix=AFTER_MOVE import HighLevel printMessage() printMessageMoved() // BEFORE_MOVE: Hello from HighLevel // BEFORE_MOVE: Hello from HighLevel // AFTER_MOVE: Hello from LowLevel // AFTER_MOVE: Hello from LowLevel let e = Entity() print(e.location()) // BEFORE_MOVE: Entity from HighLevel // AFTER_MOVE: Entity from LowLevel print(CandyBox(Candy()).ItemKind) // BEFORE_MOVE: candy // AFTER_MOVE: candy print(CandyBox(Candy()).shape()) // BEFORE_MOVE: square // AFTER_MOVE: round print(LanguageKind.Cpp.rawValue) // BEFORE_MOVE: -1 // AFTER_MOVE: 1 print("\(Vehicle().currentSpeed)") // BEFORE_MOVE: -40 // AFTER_MOVE: 40 class Bicycle: Vehicle {} let bicycle = Bicycle() bicycle.currentSpeed = 15.0 print("\(bicycle.currentSpeed)") // BEFORE_MOVE: 15.0 // AFTER_MOVE: 15.0
apache-2.0
80b036c77bf4570f07b3f9df3226f0f1
38.328947
151
0.720977
3.583933
false
false
false
false
mattjgalloway/emoncms-ios
EmonCMSiOS/Helpers/ChartDateValueFormatter.swift
1
1801
// // ChartXAxisDateFormatter.swift // EmonCMSiOS // // Created by Matt Galloway on 15/09/2016. // Copyright © 2016 Matt Galloway. All rights reserved. // import Foundation import Charts final class ChartDateValueFormatter: NSObject, IAxisValueFormatter { enum FormatType { case auto case format(String) case formatter(DateFormatter) } private let dateFormatter: DateFormatter private let autoUpdateFormat: Bool static let posixLocale = Locale(identifier: "en_US_POSIX") private var dateRange: TimeInterval? { didSet { if oldValue != dateRange { self.updateAutoFormat() } } } init(_ type: FormatType) { let dateFormatter: DateFormatter switch type { case .auto: dateFormatter = DateFormatter() self.autoUpdateFormat = true case .format(let formatString): dateFormatter = DateFormatter() dateFormatter.locale = ChartDateValueFormatter.posixLocale dateFormatter.dateFormat = formatString self.autoUpdateFormat = false case .formatter(let formatter): dateFormatter = formatter self.autoUpdateFormat = false } self.dateFormatter = dateFormatter super.init() } convenience override init() { self.init(.auto) } private func updateAutoFormat() { guard self.autoUpdateFormat else { return } let range = self.dateRange ?? 0 if range < 86400 { dateFormatter.timeStyle = .short dateFormatter.dateStyle = .none } else { dateFormatter.timeStyle = .none dateFormatter.dateStyle = .short } } func stringForValue(_ value: Double, axis: AxisBase?) -> String { self.dateRange = axis?.axisRange let date = Date(timeIntervalSince1970: value) return self.dateFormatter.string(from: date) } }
mit
c79c328e8130f755b45cdb6f2c988d8c
22.076923
68
0.682222
4.556962
false
false
false
false
jpush/aurora-imui
iOS/IMUIInputView/Views/IMUIGalleryCell.swift
1
3242
// // IMUIGalleryCell.swift // IMUIChat // // Created by wuxingchen on 2017/3/14. // Copyright © 2017年 HXHG. All rights reserved. // import UIKit import Photos class IMUIGalleryCell: UICollectionViewCell, IMUIFeatureCellProtocol { @IBOutlet weak var grayView: UIView! @IBOutlet weak var galleryImageView: UIImageView! @IBOutlet weak var selectImageView: UIImageView! @IBOutlet weak var mediaView: UIView! var playerLayer : AVPlayerLayer! override func awakeFromNib() { super.awakeFromNib() playerLayer = AVPlayerLayer() playerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill self.mediaView.layer.addSublayer(playerLayer) self.galleryImageView.layer.masksToBounds = true self.galleryImageView.layer.mask = nil } override func layoutSubviews() { super.layoutSubviews() playerLayer.frame = self.mediaView.layer.bounds } var asset : PHAsset?{ didSet{ switch asset!.mediaType { case .image: PHImageManager.default().requestImage(for: asset!, targetSize: self.frame.size, contentMode: PHImageContentMode.default, options: nil, resultHandler: { [weak self] (image, _) in self?.galleryImageView.image = image self?.galleryImageView.isHidden = false self?.mediaView.isHidden = true self?.playerLayer.player = nil }) break case .audio, .video: galleryImageView.image = nil galleryImageView.isHidden = true mediaView.isHidden = false PHImageManager.default().requestPlayerItem(forVideo: self.asset!, options: nil, resultHandler: { [weak self] (avPlayerItem, _) in self?.contentView.sendSubviewToBack((self?.mediaView)!) self?.playerLayer.player?.pause() let player = AVPlayer(playerItem: avPlayerItem) self?.playerLayer.player = player player.play() }) break default: break } animate(duration: 0) } } private var didSelect : Bool{ get{ return IMUIGalleryDataManager.selectedAssets.contains(asset!) } } func clicked(){ if asset!.mediaType != .image { print("now only support send image type") return } if didSelect { IMUIGalleryDataManager.selectedAssets = IMUIGalleryDataManager.selectedAssets.filter({$0 != asset!}) } else { _ = IMUIGalleryDataManager.insertSelectedAssets(with: asset!) } animate(duration: 0.2) } private func animate(duration:TimeInterval){ var scale : CGFloat = 1 if didSelect { scale = 0.9 } else { scale = 1/0.9 } UIView.animate(withDuration: duration, animations: { [weak self] in let transform = CGAffineTransform(scaleX: scale, y: scale) self?.galleryImageView.transform = transform self?.grayView.transform = transform self?.mediaView.transform = transform }) { [weak self] ( completion ) in self?.selectImageView.isHidden = !(self?.didSelect)! self?.grayView.isHidden = !(self?.didSelect)! self?.contentView.bringSubviewToFront((self?.grayView)!) self?.contentView.bringSubviewToFront((self?.selectImageView)!) } } }
mit
949596e47e7a34de5d723adfd8c0a7f6
28.715596
185
0.658537
4.68741
false
false
false
false
Shopify/mobile-buy-sdk-ios
PayTests/PayAddressTests.swift
1
7632
// // PayAddressTests.swift // PayTests // // Created by Shopify. // Copyright (c) 2017 Shopify Inc. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import XCTest @testable import Pay #if canImport(PassKit) import PassKit #endif @available(iOS 11.0, *) class PayAddressTests: XCTestCase { // ---------------------------------- // MARK: - Init - // func testInitPostalAddress() { let address = PayPostalAddress( city: "Brooklyn", country: "United States", countryCode: "US", province: "NY", zip: "11217" ) XCTAssertEqual(address.city, "Brooklyn") XCTAssertEqual(address.country, "United States") XCTAssertEqual(address.province, "NY") XCTAssertEqual(address.zip, "11217") XCTAssertEqual(address.originalZip, "11217") XCTAssertEqual(address.isPadded, false) } func testInitPostalAddressInUnitedStates() { let address = PayPostalAddress( city: "Brooklyn", country: "United States", countryCode: "US", province: "NY", zip: "112" ) XCTAssertEqual(address.city, "Brooklyn") XCTAssertEqual(address.country, "United States") XCTAssertEqual(address.province, "NY") XCTAssertEqual(address.zip, "112") XCTAssertEqual(address.originalZip, "112") XCTAssertEqual(address.isPadded, false) } func testInitPartialPostalAddressInCanada() { let address = PayPostalAddress( city: "Toronto", country: "Canada", countryCode: "CA", province: "ON", zip: "L5S " ) XCTAssertEqual(address.city, "Toronto") XCTAssertEqual(address.country, "Canada") XCTAssertEqual(address.province, "ON") XCTAssertEqual(address.zip, "L5S 0Z0") XCTAssertEqual(address.originalZip, "L5S ") XCTAssertEqual(address.isPadded, true) } func testInitPartialPostalAddressInUnitedKingdom() { let address = PayPostalAddress( city: "London", country: "United Kingdom", countryCode: "gb", province: "ON", zip: "W1A" ) XCTAssertEqual(address.city, "London") XCTAssertEqual(address.country, "United Kingdom") XCTAssertEqual(address.province, "ON") XCTAssertEqual(address.zip, "W1A 0ZZ") XCTAssertEqual(address.originalZip, "W1A") XCTAssertEqual(address.isPadded, true) } func testInitEmptyZipAddress() { let address = PayPostalAddress( city: "London", country: "United Kingdom", countryCode: nil, province: "ON", zip: nil ) XCTAssertEqual(address.city, "London") XCTAssertEqual(address.country, "United Kingdom") XCTAssertEqual(address.province, "ON") XCTAssertEqual(address.zip, nil) XCTAssertEqual(address.originalZip, nil) XCTAssertEqual(address.isPadded, false) } func testInitAddress() { let address = PayAddress( addressLine1: "123 Lakeshore Blvd.", addressLine2: "Unit 9876", city: "Toronto", country: "Canada", province: "ON", zip: "A1B 2C3", firstName: "John", lastName: "Smith", phone: "1-123-456-7890", email: "[email protected]" ) XCTAssertEqual(address.addressLine1, "123 Lakeshore Blvd.") XCTAssertEqual(address.addressLine2, "Unit 9876") XCTAssertEqual(address.city, "Toronto") XCTAssertEqual(address.country, "Canada") XCTAssertEqual(address.province, "ON") XCTAssertEqual(address.zip, "A1B 2C3") XCTAssertEqual(address.firstName, "John") XCTAssertEqual(address.lastName, "Smith") XCTAssertEqual(address.phone, "1-123-456-7890") XCTAssertEqual(address.email, "[email protected]") } #if canImport(PassKit) // ---------------------------------- // MARK: - CNPostalAddress - // func testInitFromPassKitAddress() { let passKitAddress = Models.createPostalAddress() let address = PayPostalAddress(with: passKitAddress) XCTAssertEqual(address.city, "Toronto") XCTAssertEqual(address.country, "Canada") XCTAssertEqual(address.province, "ON") XCTAssertEqual(address.zip, "M5V 2J4") XCTAssertEqual(address.originalZip, "M5V 2J4") XCTAssertEqual(address.isPadded, false) } // ---------------------------------- // MARK: - PKContact - // func testInitFromPassKitContact() { let contact = Models.createContact() let postalAddress = contact.postalAddress!.mutableCopy() as! CNMutablePostalAddress let address = PayAddress(with: contact) XCTAssertEqual(address.addressLine1, "80 Spadina") XCTAssertEqual(address.addressLine2, nil) XCTAssertEqual(address.city, "Toronto") XCTAssertEqual(address.country, "Canada") XCTAssertEqual(address.province, "ON") XCTAssertEqual(address.zip, "M5V 2J4") XCTAssertEqual(address.firstName, "John") XCTAssertEqual(address.lastName, "Smith") XCTAssertEqual(address.phone, "1234567890") XCTAssertEqual(address.email, "[email protected]") postalAddress.street = "123 Lakeshore Blvd\nUnit 987" contact.postalAddress = postalAddress let address2 = PayAddress(with: contact) XCTAssertEqual(address2.addressLine1, "123 Lakeshore Blvd") XCTAssertEqual(address2.addressLine2, "Unit 987") postalAddress.street = "" contact.postalAddress = postalAddress let address3 = PayAddress(with: contact) XCTAssertEqual(address3.addressLine1, nil) XCTAssertEqual(address3.addressLine2, nil) } #endif }
mit
b475dd22f7aaa37803bd512fe8a3f59d
36.229268
91
0.58032
4.55914
false
true
false
false
grzegorzleszek/algorithms-swift
Sources/Vertex.swift
1
1333
// // Vertex.swift // // Copyright © 2015 Grzegorz.Leszek. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation func ==(l: Vertex, r: Vertex) -> Bool { return l.id == r.id } struct Vertex { let id: Int init(id _id: Int) { self.id = _id } }
mit
bb4e19c83d2792b2e18c4005684e5434
37.057143
80
0.728228
4.201893
false
false
false
false
yinnieryou/DesignPattern
Command.playground/contents.swift
1
1011
// Playground - noun: a place where people can play import UIKit //命令模式 //调用者,负责调用命令 class Invoker { private var command:Command! func action(){ self.command.execute() } } //声明命令 class Command { func execute(){ assert(false, "must be override") } } //具体的命令实现 class ConcreteCommand:Command { private var receiver:Receiver! init(receiver:Receiver){ self.receiver = receiver } override func execute() { self.receiver.doSomething() } } //接受者,接受命令并执行 class Receiver { func doSomething(){ println("receiver handle") } } class Client { init(){ var receiver:Receiver = Receiver() var command:Command = ConcreteCommand(receiver: receiver) command.execute()//直接执行 var invoker:Invoker = Invoker() invoker.command = command invoker.action() //通过调用者执行 } } var client = Client()
mit
bfede979451525d26aa977356d1240bb
18.595745
65
0.615635
4.039474
false
false
false
false
narner/AudioKit
AudioKit/Common/Nodes/Effects/Phaser/AKPhaser.swift
1
9520
// // AKPhaser.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright © 2017 Aurelius Prochazka. All rights reserved. // /// A stereo phaser This is a stereo phaser, generated from Faust code taken /// from the Guitarix project. /// open class AKPhaser: AKNode, AKToggleable, AKComponent, AKInput { public typealias AKAudioUnitType = AKPhaserAudioUnit /// Four letter unique description of the node public static let ComponentDescription = AudioComponentDescription(effect: "phas") // MARK: - Properties private var internalAU: AKAudioUnitType? private var token: AUParameterObserverToken? fileprivate var notchMinimumFrequencyParameter: AUParameter? fileprivate var notchMaximumFrequencyParameter: AUParameter? fileprivate var notchWidthParameter: AUParameter? fileprivate var notchFrequencyParameter: AUParameter? fileprivate var vibratoModeParameter: AUParameter? fileprivate var depthParameter: AUParameter? fileprivate var feedbackParameter: AUParameter? fileprivate var invertedParameter: AUParameter? fileprivate var lfoBPMParameter: AUParameter? /// Ramp Time represents the speed at which parameters are allowed to change @objc open dynamic var rampTime: Double = AKSettings.rampTime { willSet { internalAU?.rampTime = rampTime } } /// Notch Minimum Frequency @objc open dynamic var notchMinimumFrequency: Double = 100 { willSet { if notchMinimumFrequency != newValue { if internalAU?.isSetUp() ?? false { if let existingToken = token { notchMinimumFrequencyParameter?.setValue(Float(newValue), originator: existingToken) } } else { internalAU?.notchMinimumFrequency = Float(newValue) } } } } /// Notch Maximum Frequency @objc open dynamic var notchMaximumFrequency: Double = 800 { willSet { if notchMaximumFrequency != newValue { if internalAU?.isSetUp() ?? false { if let existingToken = token { notchMaximumFrequencyParameter?.setValue(Float(newValue), originator: existingToken) } } else { internalAU?.notchMaximumFrequency = Float(newValue) } } } } /// Between 10 and 5000 @objc open dynamic var notchWidth: Double = 1_000 { willSet { if notchWidth != newValue { if internalAU?.isSetUp() ?? false { if let existingToken = token { notchWidthParameter?.setValue(Float(newValue), originator: existingToken) } } else { internalAU?.notchWidth = Float(newValue) } } } } /// Between 1.1 and 4 @objc open dynamic var notchFrequency: Double = 1.5 { willSet { if notchFrequency != newValue { if internalAU?.isSetUp() ?? false { if let existingToken = token { notchFrequencyParameter?.setValue(Float(newValue), originator: existingToken) } } else { internalAU?.notchFrequency = Float(newValue) } } } } /// 1 or 0 @objc open dynamic var vibratoMode: Double = 1 { willSet { if vibratoMode != newValue { if internalAU?.isSetUp() ?? false { if let existingToken = token { vibratoModeParameter?.setValue(Float(newValue), originator: existingToken) } } else { internalAU?.vibratoMode = Float(newValue) } } } } /// Between 0 and 1 @objc open dynamic var depth: Double = 1 { willSet { if depth != newValue { if internalAU?.isSetUp() ?? false { if let existingToken = token { depthParameter?.setValue(Float(newValue), originator: existingToken) } } else { internalAU?.depth = Float(newValue) } } } } /// Between 0 and 1 @objc open dynamic var feedback: Double = 0 { willSet { if feedback != newValue { if internalAU?.isSetUp() ?? false { if let existingToken = token { feedbackParameter?.setValue(Float(newValue), originator: existingToken) } } else { internalAU?.feedback = Float(newValue) } } } } /// 1 or 0 @objc open dynamic var inverted: Double = 0 { willSet { if inverted != newValue { if internalAU?.isSetUp() ?? false { if let existingToken = token { invertedParameter?.setValue(Float(newValue), originator: existingToken) } } else { internalAU?.inverted = Float(newValue) } } } } /// Between 24 and 360 @objc open dynamic var lfoBPM: Double = 30 { willSet { if lfoBPM != newValue { if internalAU?.isSetUp() ?? false { if let existingToken = token { lfoBPMParameter?.setValue(Float(newValue), originator: existingToken) } } else { internalAU?.lfoBPM = Float(newValue) } } } } /// Tells whether the node is processing (ie. started, playing, or active) @objc open dynamic var isStarted: Bool { return internalAU?.isPlaying() ?? false } // MARK: - Initialization /// Initialize this phaser node /// /// - Parameters: /// - input: Input node to process /// - notchMinimumFrequency: Notch Minimum Frequency /// - notchMaximumFrequency: Notch Maximum Frequency /// - notchWidth: Between 10 and 5000 /// - notchFrequency: Between 1.1 and 4 /// - vibratoMode: 1 or 0 /// - depth: Between 0 and 1 /// - feedback: Between 0 and 1 /// - inverted: 1 or 0 /// - lfoBPM: Between 24 and 360 /// @objc public init( _ input: AKNode? = nil, notchMinimumFrequency: Double = 100, notchMaximumFrequency: Double = 800, notchWidth: Double = 1_000, notchFrequency: Double = 1.5, vibratoMode: Double = 1, depth: Double = 1, feedback: Double = 0, inverted: Double = 0, lfoBPM: Double = 30) { self.notchMinimumFrequency = notchMinimumFrequency self.notchMaximumFrequency = notchMaximumFrequency self.notchWidth = notchWidth self.notchFrequency = notchFrequency self.vibratoMode = vibratoMode self.depth = depth self.feedback = feedback self.inverted = inverted self.lfoBPM = lfoBPM _Self.register() super.init() AVAudioUnit._instantiate(with: _Self.ComponentDescription) { [weak self] avAudioUnit in self?.avAudioNode = avAudioUnit self?.internalAU = avAudioUnit.auAudioUnit as? AKAudioUnitType input?.connect(to: self!) } guard let tree = internalAU?.parameterTree else { AKLog("Parameter Tree Failed") return } notchMinimumFrequencyParameter = tree["notchMinimumFrequency"] notchMaximumFrequencyParameter = tree["notchMaximumFrequency"] notchWidthParameter = tree["notchWidth"] notchFrequencyParameter = tree["notchFrequency"] vibratoModeParameter = tree["vibratoMode"] depthParameter = tree["depth"] feedbackParameter = tree["feedback"] invertedParameter = tree["inverted"] lfoBPMParameter = tree["lfoBPM"] token = tree.token(byAddingParameterObserver: { [weak self] _, _ in guard let _ = self else { AKLog("Unable to create strong reference to self") return } // Replace _ with strongSelf if needed DispatchQueue.main.async { // This node does not change its own values so we won't add any // value observing, but if you need to, this is where that goes. } }) internalAU?.notchMinimumFrequency = Float(notchMinimumFrequency) internalAU?.notchMaximumFrequency = Float(notchMaximumFrequency) internalAU?.notchWidth = Float(notchWidth) internalAU?.notchFrequency = Float(notchFrequency) internalAU?.vibratoMode = Float(vibratoMode) internalAU?.depth = Float(depth) internalAU?.feedback = Float(feedback) internalAU?.inverted = Float(inverted) internalAU?.lfoBPM = Float(lfoBPM) } // MARK: - Control /// Function to start, play, or activate the node, all do the same thing @objc open func start() { internalAU?.start() } /// Function to stop or bypass the node, both are equivalent @objc open func stop() { internalAU?.stop() } }
mit
ce3ae269bd510922ac693b10b700b000
33.48913
108
0.559408
5.282464
false
false
false
false
pecuniabanking/pecunia-client
Source/AccountMergeWindowController.swift
1
1889
// // AccountMergeWindowController.swift // Pecunia // // Created by Frank Emminghaus on 12.08.20. // Copyright © 2020 Frank Emminghaus. All rights reserved. // import Foundation class AccountMergeWindowController : NSWindowController { @IBOutlet var sourceAccounts: NSArrayController! @IBOutlet var targetAccounts: NSArrayController! @IBOutlet var context: NSManagedObjectContext! convenience init() { self.init(windowNibName: "AccountMergeWindow"); self.context = MOAssistant.shared().context; } @IBAction override func cancelOperation(_ sender: Any?) { self.close(); NSApp.stopModal(withCode: NSApplication.ModalResponse.cancel); } @IBAction func ok( sender: Any?) { guard let sourceAccount = sourceAccounts.selectedObjects.first as? BankAccount else { return; } guard let targetAccount = targetAccounts.selectedObjects.first as? BankAccount else { return; } let alert = NSAlert(); alert.alertStyle = NSAlert.Style.critical; let msg = String(format: NSLocalizedString("AP2200", comment: ""), sourceAccount.localAccountName, targetAccount.localAccountName, MOAssistant.shared()?.pecuniaFileURL.path ?? "<unbekannt>"); alert.messageText = NSLocalizedString("AP38", comment: ""); alert.informativeText = msg; alert.addButton(withTitle: NSLocalizedString("AP2", comment: "Cancel")); alert.addButton(withTitle: NSLocalizedString("AP36", comment: "Continue")); let result = alert.runModal(); if result == NSApplication.ModalResponse.alertFirstButtonReturn { return; } targetAccount.moveStatements(from: sourceAccount); self.close(); NSApp.stopModal(withCode: NSApplication.ModalResponse.OK); } }
gpl-2.0
024a7f9914ee88ff3e5d23e0d0eaa5a0
33.962963
199
0.663136
4.903896
false
false
false
false
GenerallyHelpfulSoftware/Scalar2D
Styling/Sources/CSSParser.swift
1
7708
// // CSSParser.swift // Scalar2D // // The MIT License (MIT) // Copyright (c) 2016-2019 Generally Helpful Software // 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 Scalar2D_Utils /** If the parsing of a string fails, and it turns out to not be a valid SVG path string. These errors will be thrown. **/ public enum CSSParserFailureReason : CustomStringConvertible, ParseBufferError { case noReason case missingSelector(String.UnicodeScalarView.Index) case missingValues(String.UnicodeScalarView.Index) case unexpectedCharacter(Character, String.UnicodeScalarView.Index) case unexpectedTermination(String.UnicodeScalarView.Index) public var description: String { switch self { case .noReason: return "No Failure" case .unexpectedCharacter(let badCharacter, _): return "Unexpected character: \(badCharacter)" case .missingSelector: return "Missing Selectors" case .missingValues: return "Missing Values" case .unexpectedTermination: return "Unexpected Termination" } } public var failurePoint: String.UnicodeScalarView.Index? { switch self { case .noReason: return nil case .missingSelector(let result): return result case .missingValues(let result): return result case .unexpectedCharacter(_, let result): return result case .unexpectedTermination(let result): return result } } } public struct CSSParser { /** This property provides knowledge of the document object model for the flavor of css being parsed to this parser. It is responsible for assigning knowledge of type to properties. For example that a "fill" property will be a colour. default: SVGPropertyInterpreter */ let propertyInterpreter : StylePropertyInterpreter /** init method - parameter propertyInterpreter:StylePropertyInterpreter - an object that can interpret properties and assign them types, such as colours or font styles */ public init(propertyInterpreter : StylePropertyInterpreter = SVGPropertyInterpreter()) { self.propertyInterpreter = propertyInterpreter } /** the primary method of the parser, takes a string thought to be css and converts ito to a list of style blocks. - parameter cssString:String CSS format - throws an error if string cannot be interpretted - returns a list of StyleBlock */ public func parse(cssString: String) throws -> [StyleBlock] { enum ParseState { case lookingForSelectorStart case lookingForProperties case lookingForAProperty } var result = [StyleBlock]() var state = ParseState.lookingForSelectorStart let buffer = cssString.unicodeScalars var currentSelectors: [[SelectorCombinator]]? = nil // StyleBlocks are composed of collections of selectors and styles var currentStyles : [GraphicStyle]? = nil var cursor = try buffer.findUncommentedIndex() // find the first index not in a comment let range = cursor..<buffer.endIndex var blockBegin = cursor // beginning of block of properties parseLoop: while range.contains(cursor) // loop over the characters in the string { let character = buffer[cursor] switch state { case .lookingForSelectorStart: switch character { case " ", "\t", " ", "\n": break default: let (combinators, newCursor) = try GroupSelector.parse(buffer: buffer, range: cursor..<buffer.endIndex) currentSelectors = combinators cursor = newCursor state = .lookingForProperties continue parseLoop // avoid updating the cursor for one loop } case .lookingForProperties: switch character { case "{": state = .lookingForAProperty blockBegin = cursor currentStyles = [GraphicStyle]() case " ", "\t", " ", "\n": break default: throw CSSParserFailureReason.unexpectedCharacter(Character(character), cursor) } case .lookingForAProperty: switch character { case " ", "\t", " ", "\n": break case "{", "\"", ";", ":": throw CSSParserFailureReason.unexpectedCharacter(Character(character), cursor) case "}": state = .lookingForSelectorStart if !(currentStyles?.isEmpty ?? false) { let aBlock = StyleBlock(combinators: currentSelectors!, styles: currentStyles!) result.append(aBlock) } currentSelectors = nil currentStyles = nil default: let (properties, newCursor) = try self.propertyInterpreter.parseProperties(buffer: buffer, range: cursor..<buffer.endIndex) cursor = newCursor if currentStyles == nil { currentStyles = [GraphicStyle]() } currentStyles! += properties continue parseLoop // avoid updating the cursor for one loop } } cursor = try buffer.uncommentedIndex(after: cursor) } switch state { case .lookingForSelectorStart: break default: // finished in the middle of parsing a block throw CSSParserFailureReason.unexpectedTermination(blockBegin) } return result } }
mit
804ed78607adfe0e0d7291b7d14d90b4
38.716495
158
0.562881
5.694752
false
false
false
false
Kalito98/Find-me-a-band
Find me a band/Find me a band/Models/UserModel.swift
1
851
// // UserModel.swift // Find me a band // // Created by Kaloyan Yanev on 3/27/17. // Copyright © 2017 Kaloyan Yanev. All rights reserved. // import Foundation import Gloss struct UserModel: Decodable { let userId: String? let username: String? let email: String? let passHash: String? let role: String? init?(json: JSON) { self.userId = "_id" <~~ json self.username = "username" <~~ json self.email = "email" <~~ json self.passHash = "passHash" <~~ json self.role = "role" <~~ json } func toJSON() -> JSON? { return jsonify([ "_id" ~~> self.userId, "username" ~~> self.username, "email" ~~> self.email, "passHash" ~~> self.passHash, "role" ~~> self.role ]) } }
mit
56473a3c3ad709ffe6030b869333fc24
20.25
56
0.514118
3.72807
false
false
false
false
theProtagony/One800Game
One800Game/ViewController.swift
1
5797
// // ViewController.swift // One800Game // // Created by Mitesh Shah on 9/30/14. // Copyright (c) 2014 PartlyCrazy. All rights reserved. // import UIKit import AudioToolbox class ViewController: UIViewController { @IBOutlet weak var txtCurrentNum : UILabel? @IBOutlet var txtScore : UILabel? @IBOutlet var numberButtons: [UIButton]! @IBOutlet var btnCall : UIButton? @IBOutlet var flash : UIView? @IBOutlet var timer : UIProgressView? var score = 0; var currentNumber = ""; var currentInput = ""; var firstLoad = true; var touchToneIDs: [SystemSoundID]! var functionTimer : NSTimer? var dialTime:Float = 1.0; override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. for button in numberButtons { button.addTarget(self, action: "didPressNumber:", forControlEvents: UIControlEvents.TouchUpInside) } initSounds() } override func viewDidAppear(animated: Bool) { if(firstLoad) { onNewGame() firstLoad = false } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func didPressCall() { if(currentNumber == currentInput) { onScore() newNumber() setCurrentInput("") } else { onGameOver(); } } func onScore() { setScore(score+1) // self.flash?.alpha = 1.0; let time :Double = 1; UIView.animateWithDuration(1.0, animations: { // self.flash!.alpha = 0.0 }) } @IBAction func didPressNumber(info : AnyObject) { var theButton = info as DigitButton; print(theButton.digit) let toneSSID = touchToneIDs[theButton.digit]; AudioServicesPlaySystemSound(toneSSID); currentInput += toString(theButton.digit) var range = (currentNumber as NSString).rangeOfString(currentInput) if(range.location != 0 || range.length == 0) { onGameOver(); } else { updateNumericDisplay() } } func decorateString(str : NSString) -> NSString { if(str.length <= 1) { return NSString(string: str) } else if( str.length <= 4) { return "\(str.substringToIndex(1)) (\(str.substringWithRange(NSRange(location:1, length:str.length-1)))" } else if (str.length <= 7) { return "\(str.substringToIndex(1)) (\(str.substringWithRange(NSRange(location:1, length:3)))) \(str.substringWithRange(NSRange(location:4, length:str.length-4)))" } else { return "\(str.substringToIndex(1)) (\(str.substringWithRange(NSRange(location:1, length:3)))) \(str.substringWithRange(NSRange(location:4, length:3)))-\(str.substringWithRange(NSRange(location:7, length:str.length-7)))" } } func updateNumericDisplay() { var range = (decorateString(currentNumber) as NSString).rangeOfString(decorateString(currentInput)) var attributedString = NSMutableAttributedString(string:decorateString(currentNumber)) attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor(red: 0.0, green: 0.7, blue: 0.0, alpha: 1.0) , range: range) txtCurrentNum?.attributedText = attributedString; } func newNumber() { var result = "1800" let length = 7 for index in 1...length { let digit = arc4random_uniform(10); result += toString(digit); } setCurrentNumber(result); timer?.progress = 1 dialTime = 1 if(functionTimer != nil) { functionTimer?.invalidate() } functionTimer = NSTimer(timeInterval: 1.0/30.0, target: self, selector: Selector("updateProgressBar"), userInfo: nil, repeats: true) NSRunLoop.currentRunLoop().addTimer(functionTimer!, forMode: NSRunLoopCommonModes) } func updateProgressBar() { if(dialTime <= 0.0) { //Invalidate timer when time reaches 0 functionTimer?.invalidate() functionTimer = nil onGameOver(); } else { dialTime -= 1.0/30.0/10.0; timer?.progress = dialTime; } } func setCurrentNumber(newNumber : NSString) { currentNumber = newNumber; updateNumericDisplay() } func setCurrentInput(newString : NSString) { currentInput = newString } func setScore(newScore: Int) { score = newScore txtScore?.text = toString(score); } func onGameOver() { self.performSegueWithIdentifier("GameOverSegue", sender: self) } func onNewGame() { setScore(0) newNumber() setCurrentInput("") } func initSounds() { touchToneIDs = [SystemSoundID](count: 10, repeatedValue: 0) for count in 1...10 { let toneFileName = "DTMF_0\(count-1)" let resourceURL = NSBundle.mainBundle().URLForResource(toneFileName, withExtension: "wav"); AudioServicesCreateSystemSoundID(resourceURL, &touchToneIDs[count-1]) } } }
mit
0c49cd05d23ecb07efa560f5578b753f
24.650442
231
0.55615
4.851046
false
false
false
false
ocrickard/Theodolite
Theodolite/UI/Text/TextCache.swift
1
4056
// // TextCache.swift // Theodolite // // Cloned from https://github.com/apple/swift-corelibs-foundation/blob/master/Foundation/NSCache.swift // to fix a bug in NSCache. // import Foundation private class TextCacheEntry<KeyType, ObjectType> where KeyType : Hashable, ObjectType : AnyObject { var key: KeyType var value: ObjectType var cost: Int var prevByCost: TextCacheEntry? var nextByCost: TextCacheEntry? init(key: KeyType, value: ObjectType, cost: Int) { self.key = key self.value = value self.cost = cost } } open class TextCache<KeyType, ObjectType> where KeyType : Hashable, ObjectType : AnyObject { private var _entries: [KeyType: TextCacheEntry<KeyType, ObjectType>] = [:] private let _lock: os_unfair_lock_t = { let lock = os_unfair_lock_t.allocate(capacity: 1) lock.initialize(repeating: os_unfair_lock_s(), count: 1) return lock }() private var _totalCost = 0 private var _head: TextCacheEntry<KeyType, ObjectType>? open var name: String = "" open var totalCostLimit: Int = 0 // limits are imprecise/not strict open var countLimit: Int = 0 // limits are imprecise/not strict open var evictsObjectsWithDiscardedContent: Bool = false deinit { _lock.deinitialize(count: 1) _lock.deallocate() } open func object(forKey key: KeyType) -> ObjectType? { var object: ObjectType? os_unfair_lock_lock(_lock) if let entry = _entries[key] { object = entry.value } os_unfair_lock_unlock(_lock) return object } open func setObject(_ obj: ObjectType, forKey key: KeyType) { setObject(obj, forKey: key, cost: 0) } private func remove(_ entry: TextCacheEntry<KeyType, ObjectType>) { let oldPrev = entry.prevByCost let oldNext = entry.nextByCost oldPrev?.nextByCost = oldNext oldNext?.prevByCost = oldPrev if entry === _head { _head = oldNext } } private func insert(_ entry: TextCacheEntry<KeyType, ObjectType>) { guard var currentElement = _head else { // The cache is empty entry.prevByCost = nil entry.nextByCost = nil _head = entry return } guard entry.cost > currentElement.cost else { // Insert entry at the head entry.prevByCost = nil entry.nextByCost = currentElement currentElement.prevByCost = entry _head = entry return } while currentElement.nextByCost != nil && currentElement.nextByCost!.cost < entry.cost { currentElement = currentElement.nextByCost! } // Insert entry between currentElement and nextElement let nextElement = currentElement.nextByCost currentElement.nextByCost = entry entry.prevByCost = currentElement entry.nextByCost = nextElement nextElement?.prevByCost = entry } open func setObject(_ obj: ObjectType, forKey key: KeyType, cost g: Int) { let g = max(g, 0) os_unfair_lock_lock(_lock) let costDiff: Int if let entry = _entries[key] { costDiff = g - entry.cost entry.cost = g entry.value = obj if costDiff != 0 { remove(entry) insert(entry) } } else { let entry = TextCacheEntry(key: key, value: obj, cost: g) _entries[key] = entry insert(entry) costDiff = g } _totalCost += costDiff var purgeAmount = (totalCostLimit > 0) ? (_totalCost - totalCostLimit) : 0 while purgeAmount > 0 { if let entry = _head { _totalCost -= entry.cost purgeAmount -= entry.cost remove(entry) // _head will be changed to next entry in remove(_:) _entries[entry.key] = nil } else { break } } var purgeCount = (countLimit > 0) ? (_entries.count - countLimit) : 0 while purgeCount > 0 { if let entry = _head { _totalCost -= entry.cost purgeCount -= 1 remove(entry) // _head will be changed to next entry in remove(_:) _entries[entry.key] = nil } else { break } } os_unfair_lock_unlock(_lock) } }
mit
15a74a5e40f8339c6c6607caf0877631
23.287425
103
0.637574
4.051948
false
false
false
false
anatoliyv/LikeAnimation
Example/LikeAnimation/ViewController.swift
1
3501
// // ViewController.swift // LikeAnimation // // Created by Anatoliy Voropay on 03/15/2017. // Copyright (c) 2017 Anatoliy Voropay. All rights reserved. // import UIKit import LikeAnimation class ViewController: UIViewController { @IBOutlet var durationSlider: UISlider! @IBOutlet var mainParticlesSlider: UISlider! @IBOutlet var smallParticlesSlider: UISlider! @IBOutlet var circlesSlider: UISlider! @IBOutlet var durationLabel: UILabel! @IBOutlet var mainParticlesLabel: UILabel! @IBOutlet var smallParticlesLabel: UILabel! @IBOutlet var circlesLabel: UILabel! @IBOutlet var placeholderView: UIView! override func viewDidLoad() { super.viewDidLoad() durationSlider.minimumValue = Float(LikeAnimation.Constants.DurationMin) durationSlider.maximumValue = Float(LikeAnimation.Constants.DurationMax) mainParticlesSlider.minimumValue = Float(LikeAnimation.Constants.MainParticlesMin) mainParticlesSlider.maximumValue = Float(LikeAnimation.Constants.MainParticlesMax) smallParticlesSlider.minimumValue = Float(LikeAnimation.Constants.SmallParticlesMin) smallParticlesSlider.maximumValue = Float(LikeAnimation.Constants.SmallParticlesMax) circlesSlider.minimumValue = Float(LikeAnimation.Constants.CirclesMin) circlesSlider.maximumValue = Float(LikeAnimation.Constants.CirclesMax) setDefaultValues() sliderValueChanged(slider: durationSlider) } private func setDefaultValues() { let likeAnimation = LikeAnimation() durationSlider.value = Float(likeAnimation.duration) mainParticlesSlider.value = Float(likeAnimation.particlesCounter.main) smallParticlesSlider.value = Float(likeAnimation.particlesCounter.small) circlesSlider.value = Float(likeAnimation.circlesCounter) } @IBAction func sliderValueChanged(slider: UISlider) { durationLabel.text = String(format: "%0.2f", durationSlider.value) mainParticlesLabel.text = String(Int(mainParticlesSlider.value)) smallParticlesLabel.text = String(Int(smallParticlesSlider.value)) circlesLabel.text = String(Int(circlesSlider.value)) } @IBAction func runPressed(button: UIButton) { let likeAnimation = LikeAnimation(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: 100, height: 100))) likeAnimation.center = placeholderView.center likeAnimation.duration = TimeInterval(durationSlider.value) likeAnimation.circlesCounter = Int(circlesSlider.value) likeAnimation.particlesCounter.main = Int(mainParticlesSlider.value) likeAnimation.particlesCounter.small = Int(smallParticlesSlider.value) likeAnimation.delegate = self // Set custom colors here // likeAnimation.heartColors.initial = .white // likeAnimation.heartColors.animated = .orange // likeAnimation.particlesColor = .orange placeholderView.addSubview(likeAnimation) likeAnimation.run() } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } } extension ViewController: LikeAnimationDelegate { func likeAnimationWillBegin(view: LikeAnimation) { print("Like animation will start") } func likeAnimationDidEnd(view: LikeAnimation) { print("Like animation ended") } }
mit
d455b491cd175a4c927f475de87472a3
36.645161
117
0.71094
4.835635
false
false
false
false
ScoutHarris/WordPress-iOS
WordPress/Classes/ViewRelated/Plugins/PluginListViewController.swift
1
2723
import UIKit import WordPressKit class PluginListViewController: UITableViewController, ImmuTablePresenter { let siteID: Int let service: PluginServiceRemote fileprivate lazy var handler: ImmuTableViewHandler = { return ImmuTableViewHandler(takeOver: self) }() fileprivate var viewModel: PluginListViewModel = .loading { didSet { handler.viewModel = viewModel.tableViewModelWithPresenter(self) updateNoResults() } } fileprivate let noResultsView = WPNoResultsView() init(siteID: Int, service: PluginServiceRemote) { self.siteID = siteID self.service = service super.init(style: .grouped) title = NSLocalizedString("Plugins", comment: "Title for the plugin manager") noResultsView.delegate = self } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } convenience init?(blog: Blog) { precondition(blog.dotComID != nil) guard let api = blog.wordPressComRestApi(), let service = PluginServiceRemote(wordPressComRestApi: api) else { return nil } self.init(siteID: Int(blog.dotComID!), service: service) } override func viewDidLoad() { super.viewDidLoad() WPStyleGuide.configureColors(for: view, andTableView: tableView) ImmuTable.registerRows([PluginListRow.self], tableView: tableView) handler.viewModel = viewModel.tableViewModelWithPresenter(self) updateNoResults() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) service.getPlugins(siteID: siteID, success: { result in self.viewModel = .ready(result) }, failure: { error in self.viewModel = .error(String(describing: error)) }) } func updateNoResults() { if let noResultsViewModel = viewModel.noResultsViewModel { showNoResults(noResultsViewModel) } else { hideNoResults() } } func showNoResults(_ viewModel: WPNoResultsView.Model) { noResultsView.bindViewModel(viewModel) if noResultsView.isDescendant(of: tableView) { noResultsView.centerInSuperview() } else { tableView.addSubview(withFadeAnimation: noResultsView) } } func hideNoResults() { noResultsView.removeFromSuperview() } } // MARK: - WPNoResultsViewDelegate extension PluginListViewController: WPNoResultsViewDelegate { func didTap(_ noResultsView: WPNoResultsView!) { let supportVC = SupportViewController() supportVC.showFromTabBar() } }
gpl-2.0
e3ea5b14130335fe6cac62ed6596ffbb
29.255556
85
0.654058
5.216475
false
false
false
false
k8mil/ContactCircularView
Example/Tests/InitialsCreatorSpec.swift
1
1809
// // Created by Kamil Wysocki on 14/10/16. // Copyright (c) 2016 CocoaPods. All rights reserved. // import Quick import Nimble import ContactCircularView class InitialsCreatorSpec: QuickSpec { override func spec() { super.spec() describe("InitialsCreator", { let initialsCreator = InitialsCreator() it("empty initials from empty name", closure: { let name = "" let initials = initialsCreator.formattedTextFromString(name) expect(initials).to(equal("")) }) it("first letter from name without last name", closure: { let name = "John" let initials = initialsCreator.formattedTextFromString(name) expect(initials).to(equal("J")) }) it("only first name with additional spaces", closure: { let name = " John " let initials = initialsCreator.formattedTextFromString(name) expect(initials).to(equal("J")) }) it("simple full name", closure: { let fullName = "John Doe" let initials = initialsCreator.formattedTextFromString(fullName); expect(initials).to(equal("JD")) }) it("complex name", closure: { let fullName = "John Mark Doe" let initials = initialsCreator.formattedTextFromString(fullName); expect(initials).to(equal("JD")) }) it("complex name with additional spaces", closure: { let fullName = "John Mark Doe " let initials = initialsCreator.formattedTextFromString(fullName); expect(initials).to(equal("JD")) }) }) } }
mit
64ccd9dd56dbb055dc4f98089e107203
32.5
81
0.546711
5.110169
false
false
false
false
domenicosolazzo/practice-swift
Multitasking/Downloading urls using NSBlockOperation/Downloading urls using NSBlockOperation/ViewController.swift
1
2136
// // ViewController.swift // Downloading urls using NSBlockOperation // // Created by Domenico Solazzo on 13/05/15. // License MIT // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() /* Define our operation here using a block operation */ let operation = BlockOperation(block: downloadUrls) /* Create an operation queue */ let operationQueue = OperationQueue() /* We assume that the reason we are downloading the content to disk is that the user wanted us to and that it was "user initiated" */ operationQueue.qualityOfService = QualityOfService.userInitiated /* We will avoid overloading the system with too many URL downloads and download only a few simultaneously */ operationQueue.maxConcurrentOperationCount = 3 // Add the operation operationQueue.addOperation(operation) } //- MARK: Helpers func downloadUrls(urls: Array<NSURL>){ // Download the images for url in urls{ let request = NSURLRequest(url: url as URL) NSURLConnection.sendAsynchronousRequest( request as URLRequest, queue: OperationQueue.current!, completionHandler: { (response:URLResponse?, data:Data?, error:Error?) -> Void in if let theError = error{ print("Error: \(theError)") }else{ print("Downloading the picture and saving it in the disk") } }) } } func downloadUrls(){ let urls = [ "http://goo.gl/oMnO9k", "http://goo.gl/3rABU1", "http://goo.gl/DS3kRe" ] // Convert all the string in NSURL var arrayUrls = Array<NSURL>() for str in urls{ arrayUrls.append(NSURL(string: str)!) } // Download all the urls downloadUrls(urls: arrayUrls) } }
mit
7529edd14270feeebc6201ef906b1591
29.514286
82
0.557584
5.326683
false
false
false
false
jcoudsi/PORadarView
PORadarViewExample/PORadarViewExample/MainViewController.swift
1
1619
// // ViewController.swift // connected-cup // // Created by COUDSI Julien on 29/10/2015. // Copyright (c) 2015 Julien Coudsi. All rights reserved. // import UIKit import PORadarView class MainViewController: UIViewController { var isAnimating: Bool = false var displayFromPairing: Bool = false var radarView: PORadarView! @IBOutlet weak var radarContainerView: UIView! override func viewDidLoad() { super.viewDidLoad() self.radarView = PORadarView(frame: self.radarContainerView.bounds) self.radarView.setImage(UIImage(named:"new-item-example")!) self.radarContainerView.addSubview(self.radarView) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.configureForExample1(self) } @IBAction func configureForExample1(sender: AnyObject) { self.radarView.contentCircleColor = ColorHelper.getLightRedColor() self.radarView.detectionItemColor = ColorHelper.getMediumRedColor() self.radarView.objectUndetectedWithAutoRestartDetection() } @IBAction func configureForExample2(sender: AnyObject) { self.radarView.contentCircleColor = ColorHelper.getMediumOrangeColor() self.radarView.detectionItemColor = ColorHelper.getMediumRedColor() self.radarView.objectDetected() self.radarView.startDetectionIfNeeded() } @IBAction func configureForExample3(sender: AnyObject) { self.radarView.contentCircleColor = ColorHelper.getMediumGreenColor() self.radarView.objectDetectedWithAutoStopDetection() } }
mit
0bc7f895326cc0160b93b94d94c792d5
25.112903
78
0.722051
4.328877
false
true
false
false
makma/cloud-sdk-swift
KenticoCloud/Classes/DeliveryService/DeliveryClient.swift
1
21482
// // DeliveryClient.swift // KenticoCloud // // Created by Martin Makarsky on 15/08/2017. // Copyright © 2017 Martin Makarsky. All rights reserved. // import AlamofireObjectMapper import Alamofire import ObjectMapper /// DeliveryClient is the main class repsonsible for getting items from Delivery API. public class DeliveryClient { private var projectId: String private var previewApiKey: String? private var secureApiKey: String? private var headers: HTTPHeaders? private var isDebugLoggingEnabled: Bool private var sessionManager: SessionManager /** Inits delivery client instance. Requests Preview API if previewApiKey is specified, otherwise requests Live API. - Parameter projectId: Identifier of the project. - Parameter previewApiKey: Preview API key for the project. - Parameter secureApiKey: Secure API key for the project. - Parameter enableDebugLogging: Flag for logging debug messages. - Parameter isRetryEnabled: Flag for enabling retry policy. - Parameter maxRetryAttempts: Maximum number of retry attempts. - Returns: Instance of the DeliveryClient. */ public init(projectId: String, previewApiKey: String? = nil, secureApiKey: String? = nil, enableDebugLogging: Bool = false, isRetryEnabled: Bool = true, maxRetryAttempts: Int = 5) { // checks if both secure and Preview API keys are present if secureApiKey != nil && previewApiKey != nil { fatalError("Preview API and Secured Production API can't be used at the same time.") } self.projectId = projectId self.previewApiKey = previewApiKey self.secureApiKey = secureApiKey self.isDebugLoggingEnabled = enableDebugLogging self.sessionManager = SessionManager() self.headers = getHeaders() let retryHandler = RetryHandler(maxRetryAttempts: maxRetryAttempts, isRetryEnabled: isRetryEnabled) sessionManager.retrier = retryHandler } /** Configures retry policy of the delivery client. - Parameter isRetryEnabled: Flag for enabling retry policy. - Parameter maxRetryAttempts: Maximum number of retry attempts. */ public func setRetryAttribute(isRetryEnabled enabled: Bool, maxRetryAttempts attempts: Int) { let retryHandler = RetryHandler(maxRetryAttempts: attempts, isRetryEnabled: enabled) sessionManager.retrier = retryHandler } /** Gets the maximum number of retry attempts. - Returns: maximum number of retry attempts. */ public func getMaximumRetryAttempts() -> Int { guard let retryHandler = self.sessionManager.retrier as? RetryHandler else { fatalError("Session manager retrier must be an instance of RetryHandler") } return retryHandler.getMaximumRetryNumber() } /** Gets whether the retry policy is enabled - Returns: the flag for enabling retry policy. */ public func getIsRetryEnabled() -> Bool { guard let retryHandler = self.sessionManager.retrier as? RetryHandler else { fatalError("Session manager retrier must be an instance of RetryHandler") } return retryHandler.getIsRetryEnabled() } /** Gets multiple items from Delivery service. Suitable for strongly typed query. - Parameter modelType: Type of the requested items. Type must conform to Mappable protocol. - Parameter queryParameters: Array of the QueryParameters which specifies requested items. - Parameter completionHandler: A handler which is called after completetion. - Parameter isSuccess: Result of the action. - Parameter items: Received items. - Parameter error: Potential error. */ public func getItems<T>(modelType: T.Type, queryParameters: [QueryParameter], completionHandler: @escaping (_ isSuccess: Bool, _ items: ItemsResponse<T>?,_ error: Error?) -> ()) where T: Mappable { let requestUrl = getItemsRequestUrl(queryParameters: queryParameters) sendGetItemsRequest(url: requestUrl, completionHandler: completionHandler) } /** Gets multiple items from Delivery service. Suitable for custom string query. - Parameter modelType: Type of the requested items. Type must conform to Mappable protocol. - Parameter customQuery: String query which specifies requested items. - Parameter completionHandler: A handler which is called after completetion. - Parameter isSuccess: Result of the action. - Parameter items: Received items. - Parameter error: Potential error. */ public func getItems<T>(modelType: T.Type, customQuery: String, completionHandler: @escaping (_ isSuccess: Bool, _ items: ItemsResponse<T>?, _ error: Error?) -> ()) where T: Mappable { let requestUrl = getItemsRequestUrl(customQuery: customQuery) sendGetItemsRequest(url: requestUrl, completionHandler: completionHandler) } /** Gets single item from Delivery service. - Parameter modelType: Type of the requested items. Type must conform to Mappable protocol. - Parameter language: Language of the requested variant. - Parameter completionHandler: A handler which is called after completetion. - Parameter isSuccess: Result of the action. - Parameter item: Received item. - Parameter error: Potential error. */ public func getItem<T>(modelType: T.Type, itemName: String, language: String? = nil, completionHandler: @escaping (_ isSuccess: Bool, _ item: ItemResponse<T>?, _ error: Error?) -> ()) where T: Mappable { let requestUrl = getItemRequestUrl(itemName: itemName, language: language) sendGetItemRequest(url: requestUrl, completionHandler: completionHandler) } /** Gets single item from Delivery service. Suitable for custom string query. - Parameter modelType: Type of the requested items. Type must conform to Mappable protocol. - Parameter customQuery: String query which specifies requested item. - Parameter completionHandler: A handler which is called after completetion. - Parameter isSuccess: Result of the action. - Parameter item: Received item. - Parameter error: Potential error. */ public func getItem<T>(modelType: T.Type, customQuery: String, completionHandler: @escaping (_ isSuccess: Bool, _ item: ItemResponse<T>?,_ error: Error?) -> ()) where T: Mappable { let requestUrl = getItemRequestUrl(customQuery: customQuery) sendGetItemRequest(url: requestUrl, completionHandler: completionHandler) } /** Gets content types from Delivery service. - Parameter skip: Number of content types to skip. - Parameter limit: Number of content types to retrieve in a single request. - Parameter completionHandler: A handler which is called after completetion. - Parameter isSuccess: Result of the action. - Parameter contentTypes: Received content types response. - Parameter error: Potential error. */ public func getContentTypes(skip: Int?, limit: Int?, completionHandler: @escaping (_ isSuccess: Bool, _ contentTypes: ContentTypesResponse?,_ error: Error?) -> ()) { let requestUrl = getContentTypesUrl(skip: skip, limit: limit) sendGetContentTypesRequest(url: requestUrl, completionHandler: completionHandler) } /** Gets single content type from Delivery service. - Parameter name: The codename of a specific content type. - Parameter completionHandler: A handler which is called after completetion. - Parameter isSuccess: Result of the action. - Parameter contentTypes: Received content type response. - Parameter error: Potential error. */ public func getContentType(name: String, completionHandler: @escaping (_ isSuccess: Bool, _ contentType: ContentType?,_ error: Error?) -> ()) { let requestUrl = getContentTypeUrl(name: name) sendGetContentTypeRequest(url: requestUrl, completionHandler: completionHandler) } /** Gets taxonomies from Delivery service. - Parameter customQuery: String query which specifies requested taxonomies. If ommited, all taxonomies for the given project are returned. Custom query example: "taxonomies?skip=1&limit=1" - Parameter completionHandler: A handler which is called after completetion. - Parameter isSuccess: Result of the action. - Parameter taxonomyGroups: Received taxonomy groups. - Parameter error: Potential error. */ public func getTaxonomies(customQuery: String? = nil, completionHandler: @escaping (_ isSuccess: Bool, _ taxonomyGroups: [TaxonomyGroup]?, _ error: Error?) -> ()) { let requestUrl = getTaxonomiesRequestUrl(customQuery: customQuery) sendGetTaxonomiesRequest(url: requestUrl, completionHandler: completionHandler) } /** Gets TaxonomyGroup from Delivery service. - Parameter taxonomyGroupName: Name which specifies requested TaxonomyGroup - Parameter completionHandler: A handler which is called after completetion. - Parameter isSuccess: Result of the action. - Parameter taxonomyGroup: Received taxonomy group. - Parameter error: Potential error. */ public func getTaxonomyGroup(taxonomyGroupName: String, completionHandler: @escaping (_ isSuccess: Bool, _ taxonomyGroup: TaxonomyGroup?, _ error: Error?) -> ()) { let requestUrl = getTaxonomyRequestUrl(taxonomyName: taxonomyGroupName) sendGetTaxonomyRequest(url: requestUrl, completionHandler: completionHandler) } private func sendGetItemsRequest<T>(url: String, completionHandler: @escaping (Bool, ItemsResponse<T>?, Error?) -> ()) where T: Mappable { sessionManager.request(url, headers: self.headers).responseObject { (response: DataResponse<ItemsResponse<T>>) in switch response.result { case .success: if let value = response.result.value { let deliveryItems = value if self.isDebugLoggingEnabled { print("[Kentico Cloud] Getting items action has succeeded. Received \(String(describing: deliveryItems.items?.count)) items.") } completionHandler(true, deliveryItems, nil) } case .failure(let error): if self.isDebugLoggingEnabled { print("[Kentico Cloud] Getting items action has failed. Check requested URL: \(url)") } completionHandler(false, nil, error) } } } private func sendGetItemRequest<T>(url: String, completionHandler: @escaping (Bool, ItemResponse<T>?, Error?) -> ()) where T: Mappable { sessionManager.request(url, headers: self.headers).responseObject() { (response: DataResponse<ItemResponse<T>>) in switch response.result { case .success: if let value = response.result.value { if self.isDebugLoggingEnabled { print("[Kentico Cloud] Getting item action has succeeded.") } completionHandler(true, value, nil) } case .failure(let error): if self.isDebugLoggingEnabled { print("[Kentico Cloud] Getting items action has failed. Check requested URL: \(url)") } completionHandler(false, nil, error) } } } private func sendGetContentTypesRequest(url: String, completionHandler: @escaping (Bool, ContentTypesResponse?, Error?) -> ()) { sessionManager.request(url, headers: self.headers).responseObject() { (response: DataResponse<ContentTypesResponse>) in switch response.result { case .success: if let value = response.result.value { if self.isDebugLoggingEnabled { print("[Kentico Cloud] Getting content types action has succeeded.") } completionHandler(true, value, nil) } case .failure(let error): if self.isDebugLoggingEnabled { print("[Kentico Cloud] Getting content types action has failed. Check requested URL: \(url)") } completionHandler(false, nil, error) } } } private func sendGetContentTypeRequest(url: String, completionHandler: @escaping (Bool, ContentType?, Error?) -> ()) { sessionManager.request(url, headers: self.headers).responseObject() { (response: DataResponse<ContentType>) in switch response.result { case .success: if let value = response.result.value { if self.isDebugLoggingEnabled { print("[Kentico Cloud] Getting content type action has succeeded.") } completionHandler(true, value, nil) } case .failure(let error): if self.isDebugLoggingEnabled { print("[Kentico Cloud] Getting content types action has failed. Check requested URL: \(url)") } completionHandler(false, nil, error) } } } private func sendGetTaxonomiesRequest(url: String, completionHandler: @escaping (Bool, [TaxonomyGroup]?, Error?) -> ()) { sessionManager.request(url, headers: self.headers).responseArray(keyPath: "taxonomies") { (response: DataResponse<[TaxonomyGroup]>) in switch response.result { case .success: if let value = response.result.value { if self.isDebugLoggingEnabled { print("[Kentico Cloud] Getting taxonomies action has succeeded.") } completionHandler(true, value, nil) } case .failure(let error): if self.isDebugLoggingEnabled { print("[Kentico Cloud] Getting taxonomies action has failed. Check requested URL: \(url)") } completionHandler(false, [], error) } } } private func sendGetTaxonomyRequest(url: String, completionHandler: @escaping (Bool, TaxonomyGroup?, Error?) -> ()) { sessionManager.request(url, headers: self.headers).responseObject { (response: DataResponse<TaxonomyGroup>) in switch response.result { case .success: if let value = response.result.value { if self.isDebugLoggingEnabled { print("[Kentico Cloud] Getting taxonomies action has succeeded.") } completionHandler(true, value, nil) } case .failure(let error): if self.isDebugLoggingEnabled { print("[Kentico Cloud] Getting taxonomies action has failed. Check requested URL: \(url)") } completionHandler(false, nil, error) } } } private func getItemsRequestUrl(queryParameters: [QueryParameter]) -> String { let endpoint = getEndpoint() let requestBuilder = ItemsRequestBuilder.init(endpointUrl: endpoint, projectId: projectId, queryParameters: queryParameters) return requestBuilder.getRequestUrl() } private func getItemsRequestUrl(customQuery: String) -> String { let endpoint = getEndpoint() return "\(endpoint)/\(projectId)/\(customQuery)" } private func getItemRequestUrl(customQuery: String) -> String { let endpoint = getEndpoint() return "\(endpoint)/\(projectId)/\(customQuery)" } private func getItemRequestUrl(itemName: String, language: String? = nil) -> String { let endpoint = getEndpoint() var languageQueryParameter = "" if let language = language { languageQueryParameter = "?language=\(language)" } return "\(endpoint)/\(projectId)/items/\(itemName)\(languageQueryParameter)" } private func getContentTypesUrl(skip: Int?, limit: Int?) -> String { let endpoint = getEndpoint() var requestUrl = "\(endpoint)/\(projectId)/types?" if let skip = skip { requestUrl.append("skip=\(skip)&") } if let limit = limit { requestUrl.append("limit=\(limit)&") } // Remove last ampersand or question mark. requestUrl = String(requestUrl.dropLast(1)) return requestUrl } private func getContentTypeUrl(name: String) -> String { let endpoint = getEndpoint() return "\(endpoint)/\(projectId)/types/\(name)" } private func getTaxonomiesRequestUrl(customQuery: String?) -> String { let endpoint = getEndpoint() return "\(endpoint)/\(projectId)/\(customQuery ?? "taxonomies")" } private func getTaxonomyRequestUrl(taxonomyName: String) -> String { let endpoint = getEndpoint() return "\(endpoint)/\(projectId)/taxonomies/\(taxonomyName)" } private func getEndpoint() -> String { var endpoint: String? // Check override from property list first if let path = Bundle.main.path(forResource: "Info", ofType: "plist") { if let propertyList = NSDictionary(contentsOfFile: path) { if let customEndpoint = propertyList["KenticoCloudDeliveryEndpoint"] { endpoint = customEndpoint as? String return endpoint! } } } // Request preview api in case there is an previewApiKey if previewApiKey == nil { return CloudConstants.liveDeliverEndpoint } else { return CloudConstants.previewDeliverEndpoint } } private func getHeaders() -> HTTPHeaders { var headers: HTTPHeaders = [ "Accept": "application/json" ] if let apiKey = previewApiKey { headers["authorization"] = "Bearer " + apiKey } if let apiKey = secureApiKey { headers["authorization"] = "Bearer " + apiKey } headers["X-KC-SDKID"] = "cocoapods.org;KenticoCloud;1.2.0" return headers } private class RetryHandler: RequestRetrier { private var attemptedRetryNumber: Int private var maxRetryAttempts: Int private var isRetryEnabled: Bool /** Inits a Retry Handler instance - Parameter isRetryEnabled: Flag for enabling retry policy. - Parameter maxRetryAttempts: Maximum number of retry attempts. - Returns: A Retry Handler instance */ public init(maxRetryAttempts: Int, isRetryEnabled: Bool) { self.attemptedRetryNumber = 1 self.maxRetryAttempts = maxRetryAttempts self.isRetryEnabled = isRetryEnabled if (maxRetryAttempts < 0) { self.maxRetryAttempts = 0 } } // Protocol requirement public func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) { if shouldRetry() { let waitTime = (pow(2, attemptedRetryNumber + 1) as NSDecimalNumber).doubleValue * 0.1 incrementRetryTimes() completion(true, waitTime) } else { resetRetryTimes() completion(false, 0) } } /** Configures retry policy of the delivery client. - Parameter isRetryEnabled: Flag for enabling retry policy. - Parameter maxRetryAttempts: Maximum number of retry attempts. */ public func setRetryAttribute(isRetryEnabled enabled: Bool, maxRetryAttempts attempts: Int) { self.isRetryEnabled = enabled self.maxRetryAttempts = attempts if (attempts < 0) { self.maxRetryAttempts = 0 } } /** Gets the maximum number of retry attempts. - Returns: maximum number of retry attempts. */ public func getMaximumRetryNumber() -> Int { return self.maxRetryAttempts } /** Gets whether the retry policy is enabled - Returns: the flag for enabling retry policy. */ public func getIsRetryEnabled() -> Bool { return self.isRetryEnabled } private func resetRetryTimes() { attemptedRetryNumber = 0 } private func incrementRetryTimes() { attemptedRetryNumber += 1 } private func shouldRetry() -> Bool { return isRetryEnabled && attemptedRetryNumber <= maxRetryAttempts } } }
mit
a0957ab88a7d97ce06a0c25d5fd2a6b1
39.91619
207
0.622923
5.294799
false
false
false
false
xsunsmile/zentivity
zentivity/ZendeskClient.swift
1
1733
// // ZendeskClient.swift // zentivity // // Created by Hao Sun on 5/20/15. // Copyright (c) 2015 Zendesk. All rights reserved. // import Foundation class ZendeskClient: NSObject { var baseUrlString = "http://volunteer.zd-dev.com" var apiString = "api/v1" var manager = AFHTTPRequestOperationManager() class var sharedInstance: ZendeskClient { struct Singleton { static let instance = ZendeskClient() } return Singleton.instance } func getWithCompletion(resource: String, params: AnyObject!, completion: (result: AnyObject?, error: NSError?) -> Void) { var urlString = String(format: "%@/%@/%@", baseUrlString, apiString, resource) println("hitting url \(urlString)") manager.GET(urlString, parameters: params, success: { (operation, response) -> Void in println("Got response \(response)") completion(result: response, error: nil) }) { (operation, error) -> Void in println("Got error: \(error)") completion(result: nil, error: error) } } func postWithCompletion(resource: String, params: AnyObject!, completion: (result: AnyObject?, error: NSError?) -> Void) { var urlString = String(format: "%@/%@/%@", baseUrlString, apiString, resource) println("post to url \(urlString)") manager.POST(urlString, parameters: params, success: { (operation, response) -> Void in println("Got response \(response)") completion(result: response, error: nil) }) { (operation, error) -> Void in println("Got error: \(error)") completion(result: nil, error: error) } } }
apache-2.0
c3158e59538cf44e22dc1e5beda4f74e
36.695652
126
0.60704
4.409669
false
false
false
false
radubozga/Freedom
speech/Swift/Speech-gRPC-Streaming/Pods/NVActivityIndicatorView/NVActivityIndicatorView/NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationBallGridPulse.swift
9
3531
// // NVActivityIndicatorAnimationBallGridPulse.swift // NVActivityIndicatorView // // The MIT License (MIT) // Copyright (c) 2016 Vinh Nguyen // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit class NVActivityIndicatorAnimationBallGridPulse: NVActivityIndicatorAnimationDelegate { func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) { let circleSpacing: CGFloat = 2 let circleSize = (size.width - circleSpacing * 2) / 3 let x = (layer.bounds.size.width - size.width) / 2 let y = (layer.bounds.size.height - size.height) / 2 let durations: [CFTimeInterval] = [0.72, 1.02, 1.28, 1.42, 1.45, 1.18, 0.87, 1.45, 1.06] let beginTime = CACurrentMediaTime() let beginTimes: [CFTimeInterval] = [ -0.06, 0.25, -0.17, 0.48, 0.31, 0.03, 0.46, 0.78, 0.45] let timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault) // Scale animation let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale") scaleAnimation.keyTimes = [0, 0.5, 1] scaleAnimation.timingFunctions = [timingFunction, timingFunction] scaleAnimation.values = [1, 0.5, 1] // Opacity animation let opacityAnimation = CAKeyframeAnimation(keyPath: "opacity") opacityAnimation.keyTimes = [0, 0.5, 1] opacityAnimation.timingFunctions = [timingFunction, timingFunction] opacityAnimation.values = [1, 0.7, 1] // Animation let animation = CAAnimationGroup() animation.animations = [scaleAnimation, opacityAnimation] animation.repeatCount = HUGE animation.isRemovedOnCompletion = false // Draw circles for i in 0 ..< 3 { for j in 0 ..< 3 { let circle = NVActivityIndicatorShape.circle.layerWith(size: CGSize(width: circleSize, height: circleSize), color: color) let frame = CGRect(x: x + circleSize * CGFloat(j) + circleSpacing * CGFloat(j), y: y + circleSize * CGFloat(i) + circleSpacing * CGFloat(i), width: circleSize, height: circleSize) animation.duration = durations[3 * i + j] animation.beginTime = beginTime + beginTimes[3 * i + j] circle.frame = frame circle.add(animation, forKey: "animation") layer.addSublayer(circle) } } } }
apache-2.0
968bb3ef0700db94c878d2f7116e7c72
43.1375
137
0.656471
4.658311
false
false
false
false
sschiau/swift
stdlib/public/Darwin/Foundation/NSOrderedCollectionDifference.swift
15
4233
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module // CollectionDifference<ChangeElement>.Change is conditionally bridged to NSOrderedCollectionChange @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) extension CollectionDifference.Change : _ObjectiveCBridgeable { @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSOrderedCollectionChange { switch self { case .insert(offset: let o, element: let e, associatedWith: let a): return NSOrderedCollectionChange(object: e, type: .insert, index: o, associatedIndex: a ?? NSNotFound) case .remove(offset: let o, element: let e, associatedWith: let a): return NSOrderedCollectionChange(object: e, type: .remove, index: o, associatedIndex: a ?? NSNotFound) } } public static func _forceBridgeFromObjectiveC(_ input: NSOrderedCollectionChange, result: inout CollectionDifference.Change?) { let _ = input.object as! ChangeElement if !_conditionallyBridgeFromObjectiveC(input, result: &result) { fatalError("Unable to bridge \(_ObjectiveCType.self) to \(self)") } } public static func _conditionallyBridgeFromObjectiveC( _ x: NSOrderedCollectionChange, result: inout CollectionDifference.Change? ) -> Bool { guard let element = x.object as? ChangeElement else { return false } let a: Int? if x.associatedIndex == NSNotFound { a = nil } else { a = x.associatedIndex } switch x.changeType { case .insert: result = .insert(offset: x.index, element: element, associatedWith: a) case .remove: result = .remove(offset: x.index, element: element, associatedWith: a) default: return false } return true } @_effects(readonly) public static func _unconditionallyBridgeFromObjectiveC(_ s: NSOrderedCollectionChange?) -> CollectionDifference.Change { var result: CollectionDifference<ChangeElement>.Change? = nil CollectionDifference<ChangeElement>.Change._forceBridgeFromObjectiveC(s!, result: &result) return result! } } // CollectionDifference<ChangeElement> is conditionally bridged to NSOrderedCollectionDifference @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) extension CollectionDifference : _ObjectiveCBridgeable { @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSOrderedCollectionDifference { return NSOrderedCollectionDifference(changes: self.map({ $0 as NSOrderedCollectionChange })) } public static func _forceBridgeFromObjectiveC(_ input: NSOrderedCollectionDifference, result: inout CollectionDifference?) { if !_conditionallyBridgeFromObjectiveC(input, result: &result) { fatalError("Unable to bridge \(_ObjectiveCType.self) to \(self)") } } private static func _formDifference( from input: NSOrderedCollectionDifference, _ changeConverter: (Any) -> CollectionDifference<ChangeElement>.Change? ) -> CollectionDifference<ChangeElement>? { var changes = Array<Change>() let iteratorSeq = IteratorSequence(NSFastEnumerationIterator(input)) for objc_change in iteratorSeq { guard let swift_change = changeConverter(objc_change) else { return nil } changes.append(swift_change) } return CollectionDifference(changes) } public static func _conditionallyBridgeFromObjectiveC( _ input: NSOrderedCollectionDifference, result: inout CollectionDifference? ) -> Bool { result = _formDifference(from: input) { $0 as? Change } return result != nil } @_effects(readonly) public static func _unconditionallyBridgeFromObjectiveC(_ s: NSOrderedCollectionDifference?) -> CollectionDifference { return _formDifference(from: s!) { ($0 as! Change) }! } }
apache-2.0
6e466ee1ba508f8a6c5a6174985f6d53
38.933962
129
0.700449
4.745516
false
false
false
false
shhuangtwn/ProjectLynla
Pods/FacebookCore/Sources/Core/Permissions/Permission.swift
2
2750
// Copyright (c) 2016-present, Facebook, Inc. All rights reserved. // // You are hereby granted a non-exclusive, worldwide, royalty-free license to use, // copy, modify, and distribute this software in source code or binary form for use // in connection with the web services and APIs provided by Facebook. // // As with any software that integrates with the Facebook platform, your use of // this software is subject to the Facebook Developer Principles and Policies // [http://developers.facebook.com/policy/]. This copyright 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 /** Represents a Graph API permission. Each permission has its own set of requirements and suggested use cases. See a full list at https://developers.facebook.com/docs/facebook-login/permissions */ public struct Permission { internal let name: String /** Create a permission with a string value. - parameter name: Name of the permission. */ public init(name: String) { self.name = name } } extension Permission: StringLiteralConvertible { /** Create a permission with a string value. - parameter value: String literal representation of the permission. */ public init(stringLiteral value: StringLiteralType) { self.init(name: value) } /** Create a permission with a string value. - parameter value: String literal representation of the permission. */ public init(unicodeScalarLiteral value: String) { self.init(name: value) } /** Create a permission with a string value. - parameter value: String literal representation of the permission. */ public init(extendedGraphemeClusterLiteral value: String) { self.init(name: value) } } extension Permission: Equatable, Hashable { /// The hash value. public var hashValue: Int { return name.hashValue } } /** Compare two `Permission`s for equality. - parameter lhs: The first permission to compare. - parameter rhs: The second permission to compare. - returns: Whether or not the permissions are equal. */ public func == (lhs: Permission, rhs: Permission) -> Bool { return lhs.name == rhs.name } internal protocol PermissionRepresentable { var permissionValue: Permission { get } }
mit
bca5bc1a08d78239935dbb4c354106af
29.898876
83
0.735636
4.493464
false
false
false
false
pennlabs/penn-mobile-ios
PennMobile/Onboarding/SAConfettiView.swift
1
3092
// // SAConfettiView.swift // Pods // // Created by Sudeep Agarwal on 12/14/15. // // import UIKit import QuartzCore public class SAConfettiView: UIView { public enum ConfettiType { case confetti case triangle case star case diamond case image(UIImage) } var emitter: CAEmitterLayer! public var colors: [UIColor]! public var intensity: Float! public var type: ConfettiType! private var active: Bool! required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } public override init(frame: CGRect) { super.init(frame: frame) setup() } func setup() { colors = [UIColor(red: 0.95, green: 0.40, blue: 0.27, alpha: 1.0), UIColor(red: 1.00, green: 0.78, blue: 0.36, alpha: 1.0), UIColor(red: 0.48, green: 0.78, blue: 0.64, alpha: 1.0), UIColor(red: 0.30, green: 0.76, blue: 0.85, alpha: 1.0), UIColor(red: 0.58, green: 0.39, blue: 0.55, alpha: 1.0)] intensity = 0.5 type = .confetti active = false } public func startConfetti() { emitter = CAEmitterLayer() emitter.birthRate *= 2 emitter.emitterPosition = CGPoint(x: frame.size.width / 2.0, y: 0) emitter.emitterShape = CAEmitterLayerEmitterShape.line emitter.emitterSize = CGSize(width: frame.size.width, height: 1) var cells = [CAEmitterCell]() for color in colors { cells.append(confettiWithColor(color: color)) } emitter.emitterCells = cells layer.addSublayer(emitter) active = true } public func stopConfetti() { emitter?.birthRate = 0 active = false } func imageForType(type: ConfettiType) -> UIImage? { var fileName: String! switch type { case .confetti: fileName = "confetti" case .triangle: fileName = "triangle" case .star: fileName = "star" case .diamond: fileName = "diamond" case let .image(customImage): return customImage } return UIImage(named: fileName) } func confettiWithColor(color: UIColor) -> CAEmitterCell { let confetti = CAEmitterCell() confetti.birthRate = 6.0 * intensity confetti.lifetime = 14.0 * intensity confetti.lifetimeRange = 0 confetti.color = color.cgColor confetti.velocity = CGFloat(350.0 * intensity) confetti.velocityRange = CGFloat(80.0 * intensity) confetti.emissionLongitude = .pi confetti.emissionRange = .pi confetti.spin = CGFloat(3.5 * intensity) confetti.spinRange = CGFloat(4.0 * intensity) confetti.scaleRange = CGFloat(intensity) confetti.scaleSpeed = CGFloat(-0.1 * intensity) confetti.contents = imageForType(type: type)!.cgImage return confetti } public func isActive() -> Bool { return self.active } }
mit
2941b48e54639ee4f632f0b97566d955
26.607143
74
0.582471
4.229822
false
false
false
false
vahidajimine/RESTController
RESTController/RESTController.swift
1
7844
// // RESTController.swift // // Created by Vahid Ajimine on 3/31/16. // Copyright © 2016 Vahid Ajimine. All rights reserved. import Foundation //MARK: - /** The class that makes JSON RESTful calls to a server NOTE: Only POST calls are supported at this time. */ public class RESTController { /// The delegate for this class public weak var delegate: RESTControllerDelegate? /** Initializes this class - parameter delegate: the delegate protocol definitions. Usually set to self - returns: creates a REST call object */ public init(delegate: RESTControllerDelegate) { self.delegate = delegate } /** Make a REST call to a server. method, contentType and isSuccess are optional parameters Note: this function only currently works for the Content-Type `application/json` for `POST` calls in addition to `GET` method calls - parameter url: the string of the url for the server - parameter headers: A dictionary of `key:value` to be added to the http header call - parameter params: A dictionary of `key:value` for additional parameters to be passed in the url rest call. This parameter is the same as `headers` if the method is `GET`. Default is `[:]`. - parameter method: either `POST` or `GET`. Default is POST - parameter contentType: only supports json and urlEncode currently. Default value is .json - parameter isSuccess: a string that is the key of the (key:value) in the JSON data result. It is usually "success" */ public func restCall(url: String, headers: [String:String]? = nil, params: [String: String] = [:], method: HTTPMethod = HTTPMethod.post, contentType: ContentType = ContentType.json, isSuccess: String? = nil) { //Checks to see if the URL string is valid guard let tempURL = URL(string: url) else { self.runDelegateProtocolFunction(printString: "Error: could not create URL from string", error: "", url: url) return } //Creates the session and request //let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration()) let session = URLSession(configuration: URLSessionConfiguration.default) var request: URLRequest = URLRequest(url: tempURL) request.httpMethod = method.rawValue if let hasHeaders = headers { for (key,value) in hasHeaders{ request.addValue(value, forHTTPHeaderField: key) } } do { if (method == .post) { switch contentType { case .json: //Converts the params object to JSON in the HTTP request let jsonPost = try JSONSerialization.data(withJSONObject: params, options: JSONSerialization.WritingOptions.prettyPrinted) request.httpBody = jsonPost request.addValue(ContentType.json.rawValue , forHTTPHeaderField: ContentType.headerFieldValue) case .urlEncode: //Convert the Dictionary to a String var postValues: String = "" for (key, value) in params{ if postValues == ""{ //Initial run postValues += "\(key)=\(value)" } else { // Need to do have & in between each param postValues += "&\(key)=\(value)" } } //Must encode the request to HTTPRequest request.httpBody = postValues.data(using: String.Encoding.utf8, allowLossyConversion: true) //Needed to let the Server know what kind of data that is being sent request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") case .multipartForm: //TODO: Implement multipart/form-data print ("Not Implemented yet") return case .textHTML: //TODO: Implement text/HTML print ("Not Implemented yet") return } } else { //GET for (key,value) in params { request.addValue(value, forHTTPHeaderField: key) } } } catch { self.runDelegateProtocolFunction(printString: "Error: could not convert params to JSON", error: "", url: url) return } //MARK: After call let task = session.dataTask(with: request, completionHandler: { (data, response, error) -> Void in //First checks to see if the data is not nil guard let resultData = data else { self.runDelegateProtocolFunction(printString: "Error: did not recieve data", error: "", url: url) return } //Checks to see if there were any errors in the request guard error == nil else { self.runDelegateProtocolFunction(printString:"Error in calling POST on \(request)", error: "\(request)", url: url) print(error!) return } let json:[String: AnyObject] //Try to convert the data stream to a dictionary do { //print(resultData) //Debug print json = try JSONSerialization.jsonObject(with: resultData, options: .mutableLeaves) as! [String: AnyObject] //print(json) //Debug print } catch { let jsonString = String(data: resultData, encoding: String.Encoding.utf8) self.runDelegateProtocolFunction(printString: "Error could not parse JSON: '\(jsonString!)'", error: jsonString!, url: url) return } if let success = isSuccess { self.runDelegateProtocolFunction(printString: "\"\(success)\": \(json[success]!)", results: json, url: url) } else { self.runDelegateProtocolFunction(printString: "REST call was successful", results: json, url: url) } }) task.resume() } //MARK: - Helper Functions /** This runs the delegate method `self.delegate.didNotReceiveAPIResults` and dispatches it to the main thread - parameter printString: the `String` to be printed to the console - parameter error: the error string parameter for the function `RESTControllerProtocol.didNotRecieveAPIResults` - parameter url: the url string parameter for the function `RESTControllerProtocol.didNotRecieveAPIResults` */ private func runDelegateProtocolFunction(printString: String, error: String, url: String) { print(printString) DispatchQueue.main.async{ self.delegate?.didNotReceiveAPIResults(error: error, url: url) } } /** This runs the delegate method `self.delegate.didReceiveAPIResults` and dispatches it to the main thread - parameter printString: the `String` to be printed to the console - parameter results: the results `[String: AnyObject]` parameter for the function `RESTControllerProtocol.didRecieveAPIResults` - parameter url: the url string parameter for the function `RESTControllerProtocol.didRecieveAPIResults` */ private func runDelegateProtocolFunction(printString: String, results: [String: AnyObject], url: String) { print(printString) DispatchQueue.main.async {self.delegate?.didReceiveAPIResults(results: results, url: url) } } }
apache-2.0
9871fa48c3589668f48c8f2d9cbeeb4f
45.135294
213
0.597093
5.239145
false
false
false
false
lxcid/LXSemVer
Sources/Version.swift
2
6886
// Version.swift // // Copyright (c) 2015 Trifia (http://trifia.com/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. func versionComponentFromCharacters(_ characters: Substring) -> UInt? { var component: UInt? = nil if characters.count > 0 { if let firstCharacter = characters.first, firstCharacter != "0" || characters.count == 1 { component = UInt(String(characters)) } } return component } public struct Version { public let major: UInt public let minor: UInt public let patch: UInt public let prerelease: DotSeparatedValues? public let buildMetadata: DotSeparatedValues? public init(major: UInt, minor: UInt, patch: UInt, prerelease: DotSeparatedValues? = nil, buildMetadata: DotSeparatedValues? = nil) { self.major = major self.minor = minor self.patch = patch self.prerelease = prerelease self.buildMetadata = buildMetadata } // Heavily referenced from Swift Package Manager to build a non regex version public init?(string: String) { let prereleaseStartIndex = string.index(of: "-") let buildMetadataStartIndex = string.index(of: "+") let versionEndIndex = prereleaseStartIndex ?? buildMetadataStartIndex ?? string.endIndex let versionCharacters = string.prefix(upTo: versionEndIndex) var versionComponents = versionCharacters.split(separator: ".", maxSplits: 2, omittingEmptySubsequences: false).compactMap(versionComponentFromCharacters) guard versionComponents.count == 3 else { return nil } var prerelease: DotSeparatedValues? if let prereleaseStartIndex = prereleaseStartIndex { let prereleaseEndIndex = buildMetadataStartIndex ?? string.endIndex let prereleaseCharacters = string[string.index(after: prereleaseStartIndex)..<prereleaseEndIndex] prerelease = DotSeparatedValues(string: String(prereleaseCharacters)) if prerelease == nil { return nil } } var buildMetadata: DotSeparatedValues? if let buildMetadataStartIndex = buildMetadataStartIndex { let buildMetadataCharacters = string.suffix(from: string.index(after: buildMetadataStartIndex)) buildMetadata = DotSeparatedValues(string: String(buildMetadataCharacters)) if buildMetadata == nil { return nil } } self.init(major: versionComponents[0], minor: versionComponents[1], patch: versionComponents[2], prerelease: prerelease, buildMetadata: buildMetadata) } } extension Version : Equatable { } public func ==(lhs: Version, rhs: Version) -> Bool { return lhs.major == rhs.major && lhs.minor == rhs.minor && lhs.patch == rhs.patch && lhs.prerelease == rhs.prerelease } extension Version : Comparable { } public func <(lhs: Version, rhs: Version) -> Bool { if lhs.major != rhs.major { return lhs.major < rhs.major } else if lhs.minor != rhs.minor { return lhs.minor < rhs.minor } else if lhs.patch != rhs.patch { return lhs.patch < rhs.patch } else if let lprv = lhs.prerelease, let rprv = rhs.prerelease, lprv != rprv { return lprv < rprv } else if lhs.prerelease != nil && rhs.prerelease == nil { return true } else { return false } } extension Version : ExpressibleByStringLiteral { public init(unicodeScalarLiteral value: String) { if let created = type(of: self).init(string: value) { self = created } else { self = Version(major: 0, minor: 0, patch: 0) } } public init(extendedGraphemeClusterLiteral value: String) { if let created = type(of: self).init(string: value) { self = created } else { self = Version(major: 0, minor: 0, patch: 0) } } public init(stringLiteral value: String) { if let created = type(of: self).init(string: value) { self = created } else { self = Version(major: 0, minor: 0, patch: 0) } } } extension Version : CustomStringConvertible { public var description: String { var description = "\(self.major).\(self.minor).\(self.patch)" if let prerelease = self.prerelease { description += "-\(prerelease)" } if let buildMetadata = self.buildMetadata { description += "+\(buildMetadata)" } return description } } extension Version { public func next() -> [Version] { if let prerelease = self.prerelease { var versions = prerelease.next().map { Version(major: self.major, minor: self.minor, patch: self.patch, prerelease: $0) } if let firstPrereleaseIdentifier = prerelease.values.first?.lowercased() { switch firstPrereleaseIdentifier { case "alpha": versions.append(Version(major: self.major, minor: self.minor, patch: self.patch, prerelease: "beta.1")) case "beta": versions.append(Version(major: self.major, minor: self.minor, patch: self.patch, prerelease: "rc.1")) case "rc": versions.append(Version(major: self.major, minor: self.minor, patch: self.patch)) break default: break } } return versions } else { return [ Version(major: self.major, minor: self.minor, patch: self.patch + 1, prerelease: "alpha.1"), Version(major: self.major, minor: self.minor + 1, patch: 0, prerelease: "alpha.1"), Version(major: self.major + 1, minor: 0, patch: 0, prerelease: "alpha.1") ] } } }
mit
cbb31400c5640c0a7adac2aee4ec94b9
38.125
162
0.633895
4.468527
false
false
false
false
tgu/HAP
Sources/HAP/HTTP/Message.swift
1
3213
import Foundation class Response { var status = Status.ok var headers = [String: String]() var body: Data? { didSet { headers["Content-Length"] = "\(body?.count ?? 0)" } } var text: String? { guard let body = body else { return nil } return String(data: body, encoding: .utf8) } func serialized() -> Data { var header = "HTTP/1.1 \(status)\r\n" for (key, value) in headers { header.append(key) header.append(": ") header.append(value) header.append("\r\n") } header.append("\r\n") return header.data(using: .utf8)! + (body ?? Data()) } enum Status: Int, CustomStringConvertible { case ok = 200 case created = 201 case accepted = 202 case noContent = 204 case multiStatus = 207 case movedPermanently = 301 case badRequest = 400, unauthorized = 401, forbidden = 403, notFound = 404 case methodNotAllowed = 405 case unprocessableEntity = 422 case internalServerError = 500 public var description: String { switch self { case .ok: return "200 OK" case .created: return "201 Created" case .accepted: return "202 Accepted" case .noContent: return "204 No Content" case .multiStatus: return "207 Multi-Status" case .movedPermanently: return "301 Moved Permanently" case .badRequest: return "400 Bad Request" case .unauthorized: return "401 Unauthorized" case .forbidden: return "403 Forbidden" case .notFound: return "404 Not Found" case .methodNotAllowed: return "405 Method Not Allowed" case .unprocessableEntity: return "422 Unprocessable Entity" case .internalServerError: return "500 Internal Server Error" } } } init(status: Status) { self.status = status headers["Content-Length"] = "0" } convenience init(status: Status = .ok, data: Data, mimeType: String) { self.init(status: status) headers["Content-Type"] = mimeType // Defer setting body, so that body.didSet will be called. defer { self.body = data } } convenience init(status: Status = .ok, text: String, mimeType: String = "text/html") { guard let data = text.data(using: .utf8) else { abort() } self.init(status: status, data: data, mimeType: "\(mimeType); charset=utf8") } static var ok: Response { return Response(status: .ok) } static var badRequest: Response { return Response(status: .badRequest) } static var forbidden: Response { return Response(status: .forbidden) } static var methodNotAllowed: Response { return Response(status: .methodNotAllowed) } static var unprocessableEntity: Response { return Response(status: .unprocessableEntity) } static var notFound: Response { return Response(status: .notFound) } static var internalServerError: Response { return Response(status: .internalServerError) } }
mit
e22b78a6338d7aa09b04465ced17f3e7
33.923913
95
0.592281
4.51264
false
false
false
false
ludoded/ReceiptBot
Pods/Material/Sources/iOS/CollectionViewCard.swift
2
4617
/* * 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 class CardCollectionViewCell: CollectionViewCell { open var card: Card? { didSet { oldValue?.removeFromSuperview() if let v = card { contentView.addSubview(v) } } } } @objc(CollectionViewCard) open class CollectionViewCard: Card { /// A reference to the dataSourceItems. open var dataSourceItems = [DataSourceItem]() /// An index of IndexPath to DataSourceItem. open var dataSourceItemsIndexPaths = [IndexPath: Any]() /// A reference to the collectionView. @IBInspectable open let collectionView = CollectionView() open override func layoutSubviews() { super.layoutSubviews() reload() } open override func prepare() { super.prepare() pulseAnimation = .none prepareCollectionView() prepareContentView() } open override func reload() { if 0 == collectionView.height { var h: CGFloat = 0 var i: Int = 0 for dataSourceItem in dataSourceItems { h += dataSourceItem.height ?? (dataSourceItems[i].data as? Card)?.height ?? 0 i += 1 } collectionView.height = h } collectionView.reloadData() super.reload() } } extension CollectionViewCard { /// Prepares the collectionView. fileprivate func prepareCollectionView() { collectionView.delegate = self collectionView.dataSource = self collectionView.interimSpacePreset = .none collectionView.register(CardCollectionViewCell.self, forCellWithReuseIdentifier: "CardCollectionViewCell") } /// Prepares the contentView. fileprivate func prepareContentView() { contentView = collectionView } } extension CollectionViewCard: CollectionViewDelegate {} extension CollectionViewCard: CollectionViewDataSource { @objc open func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } @objc open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return dataSourceItems.count } @objc open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CardCollectionViewCell", for: indexPath) as! CardCollectionViewCell cell.pulseAnimation = .none guard let card = dataSourceItems[indexPath.item].data as? Card else { return cell } dataSourceItemsIndexPaths[indexPath] = card if .vertical == self.collectionView.scrollDirection { card.width = cell.width } else { card.height = cell.height } cell.card = card return cell } }
lgpl-3.0
71b32e068303e0ad62bbe8e124819c50
33.2
143
0.671865
5.270548
false
false
false
false
NachoSoto/AsyncImageView
AsyncImageView/AsyncSwiftUIImageView.swift
1
4444
// // AsyncSwiftUIImageView.swift // AsyncImageView // // Created by Javier Soto on 5/1/20. // Copyright © 2020 Nacho Soto. All rights reserved. // import SwiftUI import Combine import ReactiveSwift public struct AsyncSwiftUIImageView< Data: RenderDataType, ImageViewData: ImageViewDataType, Renderer: RendererType, PlaceholderRenderer: RendererType>: View where ImageViewData.RenderData == Data, Renderer.Data == Data, Renderer.Error == Never, PlaceholderRenderer.Data == Data, PlaceholderRenderer.Error == Never, Renderer.RenderResult == PlaceholderRenderer.RenderResult { private typealias ImageLoader = AsyncImageLoader<Data, ImageViewData, Renderer, PlaceholderRenderer> private let renderer: Renderer private let placeholderRenderer: PlaceholderRenderer? private let uiScheduler: ReactiveSwift.Scheduler private let requestsSignal: Signal<Data?, Never> private let requestsObserver: Signal<Data?, Never>.Observer private let imageCreationScheduler: ReactiveSwift.Scheduler public init( renderer: Renderer, placeholderRenderer: PlaceholderRenderer? = nil, uiScheduler: ReactiveSwift.Scheduler = UIScheduler(), imageCreationScheduler: ReactiveSwift.Scheduler = QueueScheduler()) { self.renderer = renderer self.placeholderRenderer = placeholderRenderer self.uiScheduler = uiScheduler self.imageCreationScheduler = imageCreationScheduler (self.requestsSignal, self.requestsObserver) = Signal.pipe() } @State private var renderResult: Renderer.RenderResult? @State private var disposable: Disposable? public var data: ImageViewData? { didSet { self.requestImage() } } @State private var size: CGSize = .zero { didSet { if self.size != oldValue { self.requestImage() } } } public var body: some View { ZStack { self.imageView Color.clear .modifier(SizeModifier()) .onPreferenceChange(ImageSizePreferenceKey.self) { imageSize in self.size = imageSize } } .onAppear { self.disposable?.dispose() self.disposable = ImageLoader.createSignal( requestsSignal: self.requestsSignal, renderer: self.renderer, placeholderRenderer: self.placeholderRenderer, uiScheduler: self.uiScheduler, imageCreationScheduler: self.imageCreationScheduler ) .observeValues { self.renderResult = $0 } self.requestImage() } .onDisappear { self.disposable?.dispose() } } @ViewBuilder private var imageView: some View { if let result = self.renderResult { Image(uiImage: result.image) .resizable() .scaledToFit() .transition( AnyTransition.opacity.animation( result.cacheHit ? nil : .easeOut(duration: fadeAnimationDuration) ) ) } else { Color.clear } } private func requestImage() { guard self.size.width > 0 && self.size.height > 0 else { return } self.imageCreationScheduler.schedule { [data, size, weak observer = self.requestsObserver] in observer?.send(value: data?.renderDataWithSize(size)) } } } public extension AsyncSwiftUIImageView { func data(_ data: ImageViewData) -> Self { var view = self view.data = data return view } } private struct ImageSizePreferenceKey: PreferenceKey { typealias Value = CGSize static var defaultValue: CGSize = .zero static func reduce(value: inout CGSize, nextValue: () -> CGSize) { value = nextValue() } } private struct SizeModifier: ViewModifier { func body(content: Content) -> some View { content.background( GeometryReader { geometry in Color.clear .preference(key: ImageSizePreferenceKey.self, value: geometry.size) } ) } }
mit
9e893c7ee399cdb8e8480b92c8b4f23f
27.850649
104
0.594643
5.220917
false
false
false
false
recruit-lifestyle/Smile-Lock
SmileLock-Example/SmileLock-Example/PasswordLoginViewController.swift
2
1890
// // PasswordLoginViewController.swift // SmileLock-Example // // Created by rain on 4/22/16. // Copyright © 2016 RECRUIT LIFESTYLE CO., LTD. All rights reserved. // import UIKit import SmileLock class PasswordLoginViewController: UIViewController { @IBOutlet weak var passwordStackView: UIStackView! //MARK: Property var passwordContainerView: PasswordContainerView! let kPasswordDigit = 6 override func viewDidLoad() { super.viewDidLoad() //create PasswordContainerView passwordContainerView = PasswordContainerView.create(in: passwordStackView, digit: kPasswordDigit) passwordContainerView.delegate = self passwordContainerView.deleteButtonLocalizedTitle = "smilelock_delete" //customize password UI passwordContainerView.tintColor = UIColor.color(.textColor) passwordContainerView.highlightedColor = UIColor.color(.blue) } } extension PasswordLoginViewController: PasswordInputCompleteProtocol { func passwordInputComplete(_ passwordContainerView: PasswordContainerView, input: String) { if validation(input) { validationSuccess() } else { validationFail() } } func touchAuthenticationComplete(_ passwordContainerView: PasswordContainerView, success: Bool, error: Error?) { if success { self.validationSuccess() } else { passwordContainerView.clearInput() } } } private extension PasswordLoginViewController { func validation(_ input: String) -> Bool { return input == "123456" } func validationSuccess() { print("*️⃣ success!") dismiss(animated: true, completion: nil) } func validationFail() { print("*️⃣ failure!") passwordContainerView.wrongPassword() } }
apache-2.0
3826c7f9a38a1de428832c831c73bb14
27.5
116
0.666135
5.313559
false
false
false
false
Yalantis/Persei
Persei/Source/Menu/MenuView.swift
1
3944
// For License please refer to LICENSE file in the root of Persei project import UIKit private let CellIdentifier = "MenuCell" private let DefaultContentHeight: CGFloat = 112.0 open class MenuView: StickyHeaderView { // MARK: - Init override func commonInit() { super.commonInit() if backgroundColor == nil { backgroundColor = UIColor(red: 51 / 255, green: 51 / 255, blue: 76 / 255, alpha: 1) } contentHeight = DefaultContentHeight updateContentLayout() } // MARK: - FlowLayout private lazy var collectionLayout: UICollectionViewFlowLayout = { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal return layout }() // MARK: - CollectionView private lazy var collectionView: UICollectionView = { let view = UICollectionView(frame: .zero, collectionViewLayout: self.collectionLayout) view.clipsToBounds = false view.backgroundColor = .clear view.showsHorizontalScrollIndicator = false view.register(MenuCell.self, forCellWithReuseIdentifier: CellIdentifier) view.delegate = self view.dataSource = self self.contentView = view return view }() // MARK: - Delegate @IBOutlet open weak var delegate: MenuViewDelegate? // TODO: remove explicit type declaration when compiler error will be fixed open var items: [MenuItem] = [] { didSet { collectionView.reloadData() selectedIndex = items.count > 0 ? 0 : nil } } open var selectedIndex: Int? = 0 { didSet { var indexPath: IndexPath? if let index = selectedIndex { indexPath = IndexPath(item: index, section: 0) } self.collectionView.selectItem(at: indexPath, animated: revealed, scrollPosition: .centeredHorizontally ) } } // MARK: - ContentHeight & Layout open override var contentHeight: CGFloat { didSet { updateContentLayout() } } private func updateContentLayout() { let inset = ceil(contentHeight / 6.0) let spacing = floor(inset / 2.0) collectionLayout.minimumLineSpacing = spacing collectionLayout.minimumInteritemSpacing = spacing collectionView.contentInset = UIEdgeInsets(top: 0.0, left: inset, bottom: 0.0, right: inset) collectionLayout.itemSize = CGSize(width: contentHeight - inset * 2, height: contentHeight - inset * 2) } public func frameOfItem(at index: Int) -> CGRect { let indexPath = IndexPath(item: index, section: 0) let layoutAttributes = collectionLayout.layoutAttributesForItem(at: indexPath)! return convert(layoutAttributes.frame, from: collectionLayout.collectionView) } } extension MenuView: UICollectionViewDataSource { public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return items.count } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CellIdentifier,for: indexPath) as! MenuCell cell.apply(items[indexPath.item]) return cell } } extension MenuView: UICollectionViewDelegate { public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { selectedIndex = indexPath.item delegate?.menu(self, didSelectItemAt: selectedIndex!) UIView.animate(withDuration: 0.2, delay: 0.4, options: [], animations: { self.revealed = false }, completion: nil) } }
mit
50bc39ff96f8497d9975cbaa29edd99b
31.327869
128
0.635649
5.547117
false
false
false
false
volodg/iAsync.utils
Sources/CollectionType+Additions.swift
1
847
// // CollectionType+Additions.swift // iAsync_utils // // Created by Gorbenko Vladimir on 12.08.15. // Copyright © 2015 EmbeddedSources. All rights reserved. // import Foundation extension Collection { public func any(_ predicate: (Self.Iterator.Element) -> Bool) -> Bool { let index = self.index(where: predicate) return index != nil } public func all(_ predicate: (Self.Iterator.Element) -> Bool) -> Bool { return !any { object -> Bool in return !predicate(object) } } public func foldr<B>(_ zero: B, f: @escaping (Iterator.Element, () -> B) -> B) -> B { var g = makeIterator() var next: (() -> B)! = {zero} next = { return g.next().map {x in f(x, next)} ?? zero } let result = next() next = nil return result } }
mit
7db298337583a89198b2231f93abd466
22.5
89
0.562648
3.828054
false
false
false
false
swiftde/Udemy-Swift-Kurs
Kapitel 1/Kapitel 1/A_synchronDatenLadenVC.swift
1
1718
// // DetailVC.swift // Kapitel 1 // // Created by Udemy on 27.12.14. // Copyright (c) 2014 Udemy. All rights reserved. // import UIKit class a_synchronDatenLadenVC: UIViewController { var titel: String? var asynchron: Bool = false @IBOutlet private weak var imageView: UIImageView? override func viewDidLoad() { super.viewDidLoad() if let sichererTitel = titel { navigationItem.title = sichererTitel } } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if !asynchron { ladeDasBildSynchron() } else { ladeDasBildAsynchron() } } func ladeDasBildSynchron() { let URL = NSURL(string: "http://upload.wikimedia.org/wikipedia/commons/f/f5/Steve_Jobs_Headshot_2010-CROP2.jpg")! let datenDesBildes = NSData(contentsOfURL: URL)! let bild = UIImage(data: datenDesBildes) imageView?.image = bild } func ladeDasBildAsynchron() { let URL = NSURL(string: "http://upload.wikimedia.org/wikipedia/commons/f/f5/Steve_Jobs_Headshot_2010-CROP2.jpg")! let request = NSURLRequest(URL: URL) NSURLSession.sharedSession().dataTaskWithRequest(request) { [weak self] data, response, error in if let e = error { print("Fehler... (\(e))") return } let bild = UIImage(data: data!) dispatch_async(dispatch_get_main_queue()) { [weak self] in self?.imageView?.image = bild } }.resume() } }
apache-2.0
b4721388202ad2937f8cb5fc3328cc55
25.84375
121
0.557625
4.004662
false
false
false
false
luzefeng/iOS8-day-by-day
25-notification-actions/NotifyTimely/NotifyTimely/TimerNotifications.swift
21
4732
// // Copyright 2014 Scott Logic // // 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 UIKit let restartTimerActionString = "RestartTimer" let editTimerActionString = "EditTimer" let snoozeTimerActionString = "SnoozeTimer" let timerFiredCategoryString = "TimerFiredCategory" protocol TimerNotificationManagerDelegate { func timerStatusChanged() func presentEditOptions() } class TimerNotificationManager: Printable { let snoozeDuration: Float = 5.0 var delegate: TimerNotificationManagerDelegate? var timerRunning: Bool { didSet { delegate?.timerStatusChanged() } } var timerDuration: Float { didSet { delegate?.timerStatusChanged() } } var description: String { if timerRunning { return "\(timerDuration)s timer, running" } else { return "\(timerDuration)s timer, stopped" } } init() { timerRunning = false timerDuration = 30.0 registerForNotifications() checkForPreExistingTimer() } func startTimer() { if !timerRunning { // Create the notification... scheduleTimerWithOffset(timerDuration) } } func stopTimer() { if timerRunning { // Kill all local notifications UIApplication.sharedApplication().cancelAllLocalNotifications() timerRunning = false } } func restartTimer() { stopTimer() startTimer() } func timerFired() { timerRunning = false } func handleActionWithIdentifier(identifier: String?) { timerRunning = false if let identifier = identifier { switch identifier { case restartTimerActionString: restartTimer() case snoozeTimerActionString: scheduleTimerWithOffset(snoozeDuration) case editTimerActionString: delegate?.presentEditOptions() default: println("Unrecognised Identifier") } } } // MARK: - Utility methods private func checkForPreExistingTimer() { if UIApplication.sharedApplication().scheduledLocalNotifications.count > 0 { timerRunning = true } } private func scheduleTimerWithOffset(fireOffset: Float) { let timer = createTimer(fireOffset) UIApplication.sharedApplication().scheduleLocalNotification(timer) timerRunning = true } private func createTimer(fireOffset: Float) -> UILocalNotification { let notification = UILocalNotification() notification.category = timerFiredCategoryString notification.fireDate = NSDate(timeIntervalSinceNow: NSTimeInterval(fireOffset)) notification.alertBody = "Your time is up!" return notification } private func registerForNotifications() { let requestedTypes = UIUserNotificationType.Alert | .Sound let categories = Set(arrayLiteral: timerFiredNotificationCategory()) let settingsRequest = UIUserNotificationSettings(forTypes: requestedTypes, categories: categories) UIApplication.sharedApplication().registerUserNotificationSettings(settingsRequest) } private func timerFiredNotificationCategory() -> UIUserNotificationCategory { let restartAction = UIMutableUserNotificationAction() restartAction.identifier = restartTimerActionString restartAction.destructive = false restartAction.title = "Restart" restartAction.activationMode = .Background restartAction.authenticationRequired = false let editAction = UIMutableUserNotificationAction() editAction.identifier = editTimerActionString editAction.destructive = true editAction.title = "Edit" editAction.activationMode = .Foreground editAction.authenticationRequired = true let snoozeAction = UIMutableUserNotificationAction() snoozeAction.identifier = snoozeTimerActionString snoozeAction.destructive = false snoozeAction.title = "Snooze" snoozeAction.activationMode = .Background snoozeAction.authenticationRequired = false let category = UIMutableUserNotificationCategory() category.identifier = timerFiredCategoryString category.setActions([restartAction, snoozeAction], forContext: .Minimal) category.setActions([restartAction, snoozeAction, editAction], forContext: .Default) return category } }
apache-2.0
9b0649f507a1d3ae9237af0baf8dc9de
28.761006
102
0.730769
5.257778
false
false
false
false
EvsenevDev/SmartReceiptsiOS
SmartReceipts/Modules/Account/AccountViewController.swift
2
4634
// // AccountViewController.swift // SmartReceipts // // Created Bogdan Evsenev on 29/07/2019. // Copyright © 2019 Will Baumann. All rights reserved. // import UIKit import RxSwift import RxCocoa class AccountViewController: UIViewController, Storyboardable { var viewModel: AccountViewModelProtocol! private let bag = DisposeBag() private let dataSource = AccountDataSource() @IBOutlet private weak var tableView: UITableView! @IBOutlet private weak var loginButton: UIButton! @IBOutlet private weak var authPlaceholder: UIView! private let refreshControl = UIRefreshControl() override func viewDidLoad() { super.viewDidLoad() setupViews() localize() bind() viewModel.moduleDidLoad() } private func setupViews() { loginButton.apply(style: .mainBig) tableView.refreshControl = refreshControl tableView.dataSource = dataSource tableView.delegate = self tableView.beginRefreshing(animated: false) } private func bind() { tableView.refreshControl?.rx .controlEvent(.valueChanged) .bind(to: viewModel.onRefresh) .disposed(by: bag) loginButton.rx.tap .bind(to: viewModel.onLoginTap) .disposed(by: bag) viewModel.dataSet .subscribe(onNext: { [weak self] dataSet in self?.refreshControl.endRefreshing() self?.dataSource.update(dataSet: dataSet) self?.tableView.reloadData() }).disposed(by: bag) viewModel.isAuthorized .subscribe(onNext: { [weak self] in self?.authPlaceholder.isHidden = $0 }).disposed(by: bag) } private func localize() { title = LocalizedString("menu_main_my_account") } } extension AccountViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if dataSource.tableView(tableView, titleForHeaderInSection: section) == nil { return 0.1 } return Constants.headerHeight } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard let title = dataSource.tableView(tableView, titleForHeaderInSection: section) else { return nil } let label = UILabel(frame: .init(x: UI_MARGIN_16, y: UI_MARGIN_16)) label.text = title label.font = .semibold17 label.sizeToFit() let container = UIView() container.addSubview(label) return container } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return Constants.footerHeight } func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { guard section < tableView.numberOfSections - 1 else { return nil } let separatorFrame = CGRect(x: UI_MARGIN_16, y: 0, width: tableView.bounds.width, height: Constants.footerHeight) let footer = UIView(frame: separatorFrame) footer.backgroundColor = Constants.footerColor let container = UIView() container.addSubview(footer) return container } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { switch cell { case let cell as UserCell: cell.onLogoutTap = { [weak self] in self?.logoutTap() } case let cell as OrganizationCell: cell.onApplyTap = { [weak self] in self?.applyTap(organiztion: $0) } cell.onUploadTap = { [weak self] in self?.uploadTap(organiztion: $0) } case let cell as OCRCell: cell.onConfigureTap = { [weak self] in self?.onConfigureOcrTap() } default: break } } // MARK: Private actions for cells private func logoutTap() { viewModel.onLogoutTap.onNext() } private func applyTap(organiztion: OrganizationModel) { viewModel.onSyncOrganization.onNext(organiztion) } private func uploadTap(organiztion: OrganizationModel) { viewModel.onUploadSettings.onNext(organiztion) } private func onConfigureOcrTap() { viewModel.onOcrConfigureTap.onNext() } } private enum Constants { static let headerHeight: CGFloat = 52 static let footerHeight: CGFloat = 0.5 static let footerColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0.2) }
agpl-3.0
b3f27d67f0fea853f179212689e27ec1
31.858156
121
0.636952
4.881981
false
false
false
false
mohsinalimat/OYSimpleAlertController
OYSimpleAlertController/OYSimpleAlertController.swift
4
10793
// // OYSimpleAlertController.swift // OYSimpleAlertController // // Created by oyuk on 2015/09/09. // Copyright (c) 2015年 oyuk. All rights reserved. // import UIKit let cornerRadius:CGFloat = 10 class LunchAnimation:NSObject,UIViewControllerAnimatedTransitioning { private var presenting = false func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return 0.5 } func animateTransition(transitionContext: UIViewControllerContextTransitioning) { presenting ? presentTransition(transitionContext) : dismissTransition(transitionContext) } private func presentTransition(transitionContext: UIViewControllerContextTransitioning){ let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)! let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) as! OYSimpleAlertController toVC.contentView.transform = CGAffineTransformMakeScale(0.8, 0.8) let containerView = transitionContext.containerView() containerView!.insertSubview(toVC.view, aboveSubview: fromVC.view) UIView.animateWithDuration( transitionDuration(transitionContext),animations: { () -> Void in }) { (finished) -> Void in UIView.animateWithDuration(0.4, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 1.0, options: UIViewAnimationOptions.AllowAnimatedContent, animations: { () -> Void in toVC.backgroundView.alpha = 1 toVC.contentView.alpha = 1.0 toVC.contentView.transform = CGAffineTransformIdentity }, completion: { (finish) -> Void in transitionContext.completeTransition(true) }) } } private func dismissTransition(transitionContext: UIViewControllerContextTransitioning){ let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as! OYSimpleAlertController UIView.animateWithDuration( transitionDuration(transitionContext),animations: { () -> Void in }) { (finished) -> Void in UIView.animateWithDuration(0.4, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 1.0, options: UIViewAnimationOptions.AllowAnimatedContent, animations: { () -> Void in fromVC.backgroundView.alpha = 0 fromVC.contentView.alpha = 0 fromVC.contentView.transform = CGAffineTransformMakeScale(0.8, 0.8) }, completion: { (finish) -> Void in transitionContext.completeTransition(true) }) } } } extension UIScreen { class func screenWidth()->CGFloat { return self.mainScreen().bounds.width } class func screenHeight()->CGFloat { return self.mainScreen().bounds.size.height } } public enum OYActionStyle:Int { case Default,Cancel } public class OYAlertAction:NSObject { private var title:String! private var actionStyle:OYActionStyle! private var actionHandler:(()->Void)? convenience public init(title:String,actionStyle:OYActionStyle,actionHandler:(()->Void)?){ self.init() self.title = title self.actionStyle = actionStyle self.actionHandler = actionHandler } } public class OYSimpleAlertController: UIViewController,UIViewControllerTransitioningDelegate { private class OYAlertTitleLabel:UILabel { override func layoutSubviews() { super.layoutSubviews() let maskPath = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: [UIRectCorner.TopLeft , UIRectCorner.TopRight], cornerRadii: CGSize(width: cornerRadius, height: cornerRadius)) let maskLayer = CAShapeLayer() maskLayer.frame = self.bounds maskLayer.path = maskPath.CGPath self.layer.mask = maskLayer } } private class OYAlertTextView:UITextView { override func canBecomeFirstResponder() -> Bool { return false } } class OYActionButton:UIButton { var oyAlertAction:OYAlertAction! } private var alertTitle = "" private var message = "" private let backgroundView = UIView() public var backgroundViewColor:UIColor = UIColor.blackColor().colorWithAlphaComponent(0.3) private let contentView = UIView() private let alertTitleLabel = OYAlertTitleLabel() private let alertTitleLabelHeight:CGFloat = 40 public var alertTitleColor:UIColor = UIColor.whiteColor() public var alertTitleFont:UIFont = UIFont.boldSystemFontOfSize(23) public var alertTitleBackgroundColor = UIColor(red: 46/255.0, green: 204/255.0, blue: 113/255.0, alpha: 1.0) private let messageTextView = OYAlertTextView() private let maxMessageTextViewheight:CGFloat = UIScreen.screenHeight() * 0.7 public var messageColor:UIColor = UIColor.blackColor() public var messageFont:UIFont = UIFont.systemFontOfSize(18) private var actionButtons:[OYActionButton] = [] private let buttonHeight:CGFloat = 40 private let buttonMargin:CGFloat = 5 public var buttonFont:UIFont = UIFont.boldSystemFontOfSize(23) public var buttonTextColor:UIColor = UIColor.whiteColor() public var buttonBackgroundColors:[OYActionStyle:UIColor] = [ .Default:UIColor(red: 3/255.0, green: 169/255.0, blue: 244/255.0, alpha: 1.0), .Cancel :UIColor(red: 231/255.0, green: 76/255.0, blue: 60/255.0 , alpha: 1.0) ] private let alertWidth:CGFloat = UIScreen.screenWidth() - 50 private let maxButtonNum = 2 private let animater = LunchAnimation() convenience public init(title:String,message:String) { self.init() self.alertTitle = title self.message = message self.transitioningDelegate = self self.definesPresentationContext = true self.providesPresentationContextTransitionStyle = true self.modalPresentationStyle = .Custom } override public func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) setup() } private func setup(){ setUpBackgroundView() setUpContentView() setUpTitle() setUpMessage() setUpButton() modifyContentViewSize() } private func modifyContentViewSize(){ contentView.frame.size = CGSizeMake(alertWidth, alertTitleLabelHeight + messageTextView.frame.height + buttonHeight + buttonMargin * 2) contentView.center = self.view.center } private func setUpBackgroundView(){ backgroundView.frame = self.view.bounds backgroundView.backgroundColor = backgroundViewColor self.view.addSubview(backgroundView) } private func setUpContentView(){ contentView.backgroundColor = UIColor.whiteColor() contentView.layer.cornerRadius = cornerRadius self.view.addSubview(contentView) } private func setUpTitle(){ alertTitleLabel.frame = CGRectMake(0, 0, alertWidth, alertTitleLabelHeight) alertTitleLabel.text = alertTitle alertTitleLabel.font = alertTitleFont alertTitleLabel.textColor = alertTitleColor alertTitleLabel.textAlignment = .Center alertTitleLabel.backgroundColor = alertTitleBackgroundColor alertTitleLabel.layer.cornerRadius = cornerRadius contentView.addSubview(alertTitleLabel) } private func setUpMessage(){ messageTextView.frame = CGRectMake(0, alertTitleLabelHeight, alertWidth, 0) messageTextView.text = message messageTextView.font = messageFont messageTextView.textColor = messageColor messageTextView.editable = false contentView.addSubview(messageTextView) messageTextView.sizeToFit() if messageTextView.frame.height > maxMessageTextViewheight { messageTextView.frame.size = CGSizeMake(alertWidth,maxMessageTextViewheight) } } private func setUpButton(){ let buttonOriginY = alertTitleLabelHeight + messageTextView.frame.height + buttonMargin let buttonWidth = actionButtons.count == 2 ? (alertWidth - buttonMargin * 3)/2 : alertWidth - buttonMargin * 2 for button in actionButtons { button.frame = CGRectMake( CGFloat(button.tag) * (buttonWidth + buttonMargin) + buttonMargin, buttonOriginY, buttonWidth, buttonHeight) button.setTitle(button.oyAlertAction.title, forState: .Normal) button.backgroundColor = buttonBackgroundColors[button.oyAlertAction.actionStyle] button.addTarget(self, action: "action:", forControlEvents: .TouchUpInside) button.setTitleColor(buttonTextColor, forState: .Normal) button.titleLabel?.font = buttonFont button.layer.cornerRadius = cornerRadius contentView.addSubview(button) } } public func addAction(action:OYAlertAction) { assert(actionButtons.count < maxButtonNum, "OYAlertAction must be \(maxButtonNum) or less") let button = OYActionButton() button.oyAlertAction = action button.tag = actionButtons.count actionButtons.append(button) } func action(sender: OYActionButton){ let button = sender as OYActionButton if let action = button.oyAlertAction.actionHandler { action() } self.dismissViewControllerAnimated(true, completion: nil) } public func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { animater.presenting = true return animater } public func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { animater.presenting = false return animater } }
mit
3a36b14bd8a5efe2cf75ba690bfa075c
35.829352
224
0.648411
5.786059
false
false
false
false
kitasuke/TwitterClientDemo
TwitterClientDemo/Classes/Views/ProfileDetailView.swift
1
2409
// // ProfileDetailView.swift // TwitterClientDemo // // Created by Yusuke Kita on 5/21/15. // Copyright (c) 2015 kitasuke. All rights reserved. // import UIKit class ProfileDetailView: UIView { @IBOutlet weak var imageView: UIImageView? @IBOutlet weak var nameLabel: UILabel? @IBOutlet weak var screenNameLabel: UILabel? @IBOutlet weak var descriptionLabel: UILabel? @IBOutlet weak var timeZoneLabel: UILabel? @IBOutlet weak var URLTextView: UITextView? @IBOutlet weak var followersCountLabel: UILabel? @IBOutlet weak var friendsCountLabel: UILabel? private var imageCache = NSCache() private var queue = NSOperationQueue() internal func setup() { if let user = UserStore.sharedStore.currentUser { let userViewModel = UserViewModel(user: user) nameLabel?.text = user.name screenNameLabel?.text = userViewModel.screenName descriptionLabel?.text = user.descriptionString timeZoneLabel?.text = user.timeZone URLTextView?.text = user.URL followersCountLabel?.text = userViewModel.followersCountString friendsCountLabel?.text = userViewModel.friendsCountString // use image on cache, if no exists, fetch and store it on cache if let image = imageCache.objectForKey(user) as? UIImage { imageView?.image = image } else { let request = NSURLRequest(URL: NSURL(string: user.profileImage)!) NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler: { [unowned self] (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in if let image = UIImage(data: data) { self.imageCache.setObject(image, forKey: user) dispatch_async(dispatch_get_main_queue(), { () -> Void in self.imageView?.image = image self.imageView?.alpha = 0 UIView.animateWithDuration(1.0, animations: { () -> Void in // like SDWebImage self.imageView?.alpha = 1 }) }) } }) } } } }
mit
f5e9ce8bd43207107c5dd00c4510ccae
42.017857
125
0.568286
5.537931
false
false
false
false
richardpiazza/LCARSDisplayKit
Sources/LCARSDisplayKit/RoundedRectangle.swift
1
4783
#if (os(macOS) || os(iOS) || os(tvOS) || os(watchOS)) import CoreGraphics import GraphPoint /// A rectangle with optionally rounded ends public struct RoundedRectangle: Graphable { public var size: CGSize = CGSize.zero public var leftRounded: Bool = false public var rightRounded: Bool = false public var cornersOnly: Bool = false public init() {} public init(size: CGSize, leftRounded: Bool, rightRounded: Bool, cornersOnly: Bool) { self.size = size self.leftRounded = leftRounded self.rightRounded = rightRounded self.cornersOnly = cornersOnly } /// Caluclates the radius of the arcs depending on `cornersOnly` var radius: CGFloat { return (cornersOnly) ? size.height * 0.25 : size.height * 0.5 } var upperLeftCenter: CGPoint { return CGPoint(x: radius, y: radius) } var lowerRightCenter: CGPoint { return CGPoint(x: size.width - radius, y: size.height - radius) } // MARK: - Graphable public var path: CGMutablePath { let path = CGMutablePath() guard leftRounded == true || rightRounded == true else { path.addRect(CGRect(origin: CGPoint.zero, size: size)) return path } if leftRounded && rightRounded { if cornersOnly { path.addArc(center: upperLeftCenter, radius: radius, startAngle: CGFloat(180).radians, endAngle: CGFloat(270).radians, clockwise: false) path.addLine(to: CGPoint(x: lowerRightCenter.x, y: 0)) path.addArc(center: CGPoint(x: lowerRightCenter.x, y: upperLeftCenter.y), radius: radius, startAngle: CGFloat(270).radians, endAngle: CGFloat(0).radians, clockwise: false) path.addLine(to: CGPoint(x: size.width, y: lowerRightCenter.y)) path.addArc(center: lowerRightCenter, radius: radius, startAngle: CGFloat(0).radians, endAngle: CGFloat(90).radians, clockwise: false) path.addLine(to: CGPoint(x: upperLeftCenter.x, y: size.height)) path.addArc(center: CGPoint(x: upperLeftCenter.x, y:lowerRightCenter.y), radius: radius, startAngle: CGFloat(90).radians, endAngle: CGFloat(180).radians, clockwise: false) path.closeSubpath() } else { path.addArc(center: upperLeftCenter, radius: radius, startAngle: CGFloat(90).radians, endAngle: CGFloat(270).radians, clockwise: false) path.addLine(to: CGPoint(x: lowerRightCenter.x, y: 0)) path.addArc(center: lowerRightCenter, radius: radius, startAngle: CGFloat(270).radians, endAngle: CGFloat(90).radians, clockwise: false) path.closeSubpath() } } else if leftRounded { if cornersOnly { path.addArc(center: upperLeftCenter, radius: radius, startAngle: CGFloat(180).radians, endAngle: CGFloat(270).radians, clockwise: false) path.addLine(to: CGPoint(x: size.width, y: 0)) path.addLine(to: CGPoint(x: size.width, y: size.height)) path.addLine(to: CGPoint(x: upperLeftCenter.x, y: size.height)) path.addArc(center: CGPoint(x: upperLeftCenter.x, y: lowerRightCenter.y), radius: radius, startAngle: CGFloat(90).radians, endAngle: CGFloat(180).radians, clockwise: false) path.closeSubpath() } else { path.addArc(center: upperLeftCenter, radius: radius, startAngle: CGFloat(90).radians, endAngle: CGFloat(270).radians, clockwise: false) path.addLine(to: CGPoint(x: size.width, y: 0)) path.addLine(to: CGPoint(x: size.width, y: size.height)) path.closeSubpath() } } else if rightRounded { if cornersOnly { path.addArc(center: CGPoint(x: lowerRightCenter.x, y: upperLeftCenter.y), radius: radius, startAngle: CGFloat(270).radians, endAngle: CGFloat(0).radians, clockwise: false) path.addLine(to: CGPoint(x: size.width, y: lowerRightCenter.y)) path.addArc(center: lowerRightCenter, radius: radius, startAngle: CGFloat(0).radians, endAngle: CGFloat(90).radians, clockwise: false) path.addLine(to: CGPoint(x: 0, y: size.height)) path.addLine(to: CGPoint.zero) path.closeSubpath() } else { path.addArc(center: lowerRightCenter, radius: radius, startAngle: CGFloat(270).radians, endAngle: CGFloat(90).radians, clockwise: false) path.addLine(to: CGPoint(x: 0, y: size.height)) path.addLine(to: CGPoint.zero) path.closeSubpath() } } return path } } #endif
mit
8e9eb92cc1f392449d7f2702a08535ae
50.430108
188
0.619068
4.206684
false
false
false
false
stripe/stripe-ios
StripeCardScan/StripeCardScan/Source/CardScan/CreditCardOcr/CreditCardOcrPrediction.swift
1
6020
// // CreditCardOcrPrediction.swift // ocr-playground-ios // // Created by Sam King on 3/19/20. // Copyright © 2020 Sam King. All rights reserved. // import CoreGraphics import Foundation struct UxFrameConfidenceValues { let hasOcr: Bool let uxPan: Double let uxNoPan: Double let uxNoCard: Double func toArray() -> [Double] { return [hasOcr ? 1.0 : 0.0, uxPan, uxNoPan, uxNoCard] } } enum CenteredCardState { case numberSide case nonNumberSide case noCard func hasCard() -> Bool { return self == .numberSide || self == .nonNumberSide } } struct CreditCardOcrPrediction { let image: CGImage let ocrCroppingRectangle: CGRect let number: String? let expiryMonth: String? let expiryYear: String? let name: String? let computationTime: Double let numberBoxes: [CGRect]? let expiryBoxes: [CGRect]? let nameBoxes: [CGRect]? // this is only used by Card Verify and the Liveness check and filled in by the UxModel var centeredCardState: CenteredCardState? var uxFrameConfidenceValues: UxFrameConfidenceValues? init( image: CGImage, ocrCroppingRectangle: CGRect, number: String?, expiryMonth: String?, expiryYear: String?, name: String?, computationTime: Double, numberBoxes: [CGRect]?, expiryBoxes: [CGRect]?, nameBoxes: [CGRect]?, centeredCardState: CenteredCardState? = nil, uxFrameConfidenceValues: UxFrameConfidenceValues? = nil ) { self.image = image self.ocrCroppingRectangle = ocrCroppingRectangle self.number = number self.expiryMonth = expiryMonth self.expiryYear = expiryYear self.name = name self.computationTime = computationTime self.numberBoxes = numberBoxes self.expiryBoxes = expiryBoxes self.nameBoxes = nameBoxes self.centeredCardState = centeredCardState self.uxFrameConfidenceValues = uxFrameConfidenceValues } func with(uxPrediction: UxModelOutput) -> CreditCardOcrPrediction { let uxFrameConfidenceValues: UxFrameConfidenceValues? = { if let (hasPan, hasNoPan, hasNoCard) = uxPrediction.confidenceValues() { let hasOcr = self.number != nil return UxFrameConfidenceValues( hasOcr: hasOcr, uxPan: hasPan, uxNoPan: hasNoPan, uxNoCard: hasNoCard ) } return nil }() return CreditCardOcrPrediction( image: self.image, ocrCroppingRectangle: self.ocrCroppingRectangle, number: self.number, expiryMonth: self.expiryMonth, expiryYear: self.expiryYear, name: self.name, computationTime: self.computationTime, numberBoxes: self.numberBoxes, expiryBoxes: self.expiryBoxes, nameBoxes: self.nameBoxes, centeredCardState: uxPrediction.cardCenteredState(), uxFrameConfidenceValues: uxFrameConfidenceValues ) } static func emptyPrediction(cgImage: CGImage) -> CreditCardOcrPrediction { CreditCardOcrPrediction( image: cgImage, ocrCroppingRectangle: CGRect(), number: nil, expiryMonth: nil, expiryYear: nil, name: nil, computationTime: 0.0, numberBoxes: nil, expiryBoxes: nil, nameBoxes: nil ) } var expiryForDisplay: String? { guard let month = expiryMonth, let year = expiryYear else { return nil } return "\(month)/\(year)" } var expiryAsUInt: (UInt, UInt)? { guard let month = expiryMonth.flatMap({ UInt($0) }) else { return nil } guard let year = expiryYear.flatMap({ UInt($0) }) else { return nil } return (month, year) } var numberBox: CGRect? { let xmin = numberBoxes?.map { $0.minX }.min() ?? 0.0 let xmax = numberBoxes?.map { $0.maxX }.max() ?? 0.0 let ymin = numberBoxes?.map { $0.minY }.min() ?? 0.0 let ymax = numberBoxes?.map { $0.maxY }.max() ?? 0.0 return CGRect(x: xmin, y: ymin, width: (xmax - xmin), height: (ymax - ymin)) } var expiryBox: CGRect? { return expiryBoxes.flatMap { $0.first } } var numberBoxesInFullImageFrame: [CGRect]? { guard let boxes = numberBoxes else { return nil } let cropOrigin = ocrCroppingRectangle.origin return boxes.map { CGRect( x: $0.origin.x + cropOrigin.x, y: $0.origin.y + cropOrigin.y, width: $0.size.width, height: $0.size.height ) } } static func likelyExpiry(_ string: String) -> (String, String)? { guard let regex = try? NSRegularExpression(pattern: "^.*(0[1-9]|1[0-2])[./]([1-2][0-9])$") else { return nil } let result = regex.matches(in: string, range: NSRange(string.startIndex..., in: string)) if result.count == 0 { return nil } guard let nsrange1 = result.first?.range(at: 1), let range1 = Range(nsrange1, in: string) else { return nil } guard let nsrange2 = result.first?.range(at: 2), let range2 = Range(nsrange2, in: string) else { return nil } return (String(string[range1]), String(string[range2])) } static func pan(_ text: String) -> String? { let digitsAndSpace = text.reduce(true) { $0 && (($1 >= "0" && $1 <= "9") || $1 == " ") } let number = text.compactMap { $0 >= "0" && $0 <= "9" ? $0 : nil }.map { String($0) } .joined() guard digitsAndSpace else { return nil } guard CreditCardUtils.isValidNumber(cardNumber: number) else { return nil } return number } }
mit
c56d6df24584e3f7db2a8196ca7782f3
30.513089
98
0.582489
4.214986
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/Pods/SwiftMoment/SwiftMoment/SwiftMoment/MomentFromNow.swift
2
5422
// // MomentFromNow.swift // SwiftMoment // // Created by Madhava Jay on 07/06/2016. // Copyright © 2016 Adrian Kosmaczewski. All rights reserved. // import Foundation // needed to dynamically select the bundle below class MomentBundle: NSObject { } extension Moment { /// Returns a localized string specifying the time duration between /// the current instance and the present moment. /// /// - returns: A localized string. public func fromNow() -> String { let timeDiffDuration = moment().intervalSince(self) let deltaSeconds = timeDiffDuration.seconds var value: Double! if deltaSeconds < 5 { // Just Now return NSDateTimeAgoLocalizedStrings("Just now") } else if deltaSeconds < minuteInSeconds { // Seconds Ago return stringFromFormat("%%1.0f %@seconds ago", withValue: deltaSeconds) } else if deltaSeconds < (minuteInSeconds * 2) { // A Minute Ago return NSDateTimeAgoLocalizedStrings("A minute ago") } else if deltaSeconds < hourInSeconds { // Minutes Ago return stringFromFormat("%%1.0f %@minutes ago", withValue: deltaSeconds / minuteInSeconds) } else if deltaSeconds < (hourInSeconds * 2) { // An Hour Ago return NSDateTimeAgoLocalizedStrings("An hour ago") } else if deltaSeconds < dayInSeconds { // Hours Ago value = floor(deltaSeconds / hourInSeconds) return stringFromFormat("%%1.0f %@hours ago", withValue: value) } else if deltaSeconds < (dayInSeconds * 2) { // Yesterday return NSDateTimeAgoLocalizedStrings("Yesterday") } else if deltaSeconds < weekInSeconds { // Days Ago value = floor(deltaSeconds / dayInSeconds) return stringFromFormat("%%1.0f %@days ago", withValue: value) } else if deltaSeconds < (weekInSeconds * 2) { // Last Week return NSDateTimeAgoLocalizedStrings("Last week") } else if deltaSeconds < monthInSeconds { // Weeks Ago value = floor(deltaSeconds / weekInSeconds) return stringFromFormat("%%1.0f %@weeks ago", withValue: value) } else if deltaSeconds < (dayInSeconds * 61) { // Last month return NSDateTimeAgoLocalizedStrings("Last month") } else if deltaSeconds < yearInSeconds { // Month Ago value = floor(deltaSeconds / monthInSeconds) return stringFromFormat("%%1.0f %@months ago", withValue: value) } else if deltaSeconds < (yearInSeconds * 2) { // Last Year return NSDateTimeAgoLocalizedStrings("Last year") } // Years Ago value = floor(deltaSeconds / yearInSeconds) return stringFromFormat("%%1.0f %@years ago", withValue: value) } fileprivate func stringFromFormat(_ format: String, withValue value: Double) -> String { let localeFormat = String(format: format, getLocaleFormatUnderscoresWithValue(value)) return String(format: NSDateTimeAgoLocalizedStrings(localeFormat), value) } fileprivate func NSDateTimeAgoLocalizedStrings(_ key: String) -> String { // get framework bundle guard let bundleIdentifier = Bundle(for: MomentBundle.self).bundleIdentifier else { return "" } guard let frameworkBundle = Bundle(identifier: bundleIdentifier) else { return "" } guard let resourcePath = frameworkBundle.resourcePath else { return "" } let bundleName = "MomentFromNow.bundle" let path = URL(fileURLWithPath:resourcePath).appendingPathComponent(bundleName) guard let bundle = Bundle(url: path) else { return "" } if let languageBundle = getLanguageBundle(bundle) { return languageBundle.localizedString(forKey: key, value: "", table: "NSDateTimeAgo") } return "" } fileprivate func getLanguageBundle(_ bundle: Bundle) -> Bundle? { let localeIdentifer = self.locale.identifier if let languagePath = bundle.path(forResource: localeIdentifer, ofType: "lproj") { return Bundle(path: languagePath) } let langDict = Locale.components(fromIdentifier: localeIdentifer) let languageCode = langDict["kCFLocaleLanguageCodeKey"] if let languagePath = bundle.path(forResource: languageCode, ofType: "lproj") { return Bundle(path: languagePath) } return nil } fileprivate func getLocaleFormatUnderscoresWithValue(_ value: Double) -> String { guard let localeCode = Locale.preferredLanguages.first else { return "" } if localeCode == "ru" { let XY = Int(floor(value)) % 100 let Y = Int(floor(value)) % 10 if Y == 0 || Y > 4 || (XY > 10 && XY < 15) { return "" } if Y > 1 && Y < 5 && (XY < 10 || XY > 20) { return "_" } if Y == 1 && XY != 11 { return "__" } } return "" } }
mit
8d76c97301bf46bef9340f126d12de40
30.517442
102
0.579598
4.941659
false
false
false
false
jpsim/CardsAgainst
CardsAgainst/Views/PlayerCell.swift
1
890
// // PlayerCell.swift // CardsAgainst // // Created by JP Simard on 11/4/14. // Copyright (c) 2014 JP Simard. All rights reserved. // import UIKit import Cartography final class PlayerCell: UICollectionViewCell { class var reuseID: String { return "PlayerCell" } let label = UILabel() override init(frame: CGRect) { super.init(frame: frame) setupLabel() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } fileprivate func setupLabel() { // Label contentView.addSubview(label) label.translatesAutoresizingMaskIntoConstraints = false label.textColor = lightColor label.font = .boldSystemFont(ofSize: 22) // Layout constrain(label) { label in label.edges == inset(label.superview!.edges, 15, 10) } } }
mit
de252822b2d2de3a8854307bc98ea182
22.421053
64
0.630337
4.405941
false
false
false
false