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
OpenTimeApp/OpenTimeIOSSDK
OpenTimeSDK/Classes/OTDeserializedLocation.swift
1
1043
// // OTDeserializedLocation.swift // OpenTimeSDK // // Created by Josh Woodcock on 12/26/15. // Copyright © 2015 Connecting Open Time, LLC. All rights reserved. // public class OTDeserializedLocation : OTDeserializer { private struct Keys { static let LATITUDE = "lat"; static let LONGITUDE = "long"; static let ADDRESS = "address"; } private var _latitude: Double; private var _longitude: Double; private var _address: String; public required init(dictionary: NSDictionary){ self._latitude = dictionary.value(forKey: Keys.LATITUDE) as! Double; self._longitude = dictionary.value(forKey: Keys.LONGITUDE) as! Double; self._address = dictionary.value(forKey: Keys.ADDRESS) as! String; } public func getLatitude() -> Double { return self._latitude; } public func getLongitude() -> Double { return self._longitude; } public func getAddress() -> String { return self._address; } }
mit
703cb287a6a8728e7b2f1e4f8e9e6864
26.421053
78
0.626679
4.235772
false
false
false
false
crazypoo/PTools
Pods/CryptoSwift/Sources/CryptoSwift/CS_BigInt/Bitwise Ops.swift
2
4118
// // Bitwise Ops.swift // CS.BigInt // // Created by Károly Lőrentey on 2016-01-03. // Copyright © 2016-2017 Károly Lőrentey. // //MARK: Bitwise Operations extension CS.BigUInt { /// Return the ones' complement of `a`. /// /// - Complexity: O(a.count) public static prefix func ~(a: CS.BigUInt) -> CS.BigUInt { return CS.BigUInt(words: a.words.map { ~$0 }) } /// Calculate the bitwise OR of `a` and `b`, and store the result in `a`. /// /// - Complexity: O(max(a.count, b.count)) public static func |= (a: inout CS.BigUInt, b: CS.BigUInt) { a.reserveCapacity(b.count) for i in 0 ..< b.count { a[i] |= b[i] } } /// Calculate the bitwise AND of `a` and `b` and return the result. /// /// - Complexity: O(max(a.count, b.count)) public static func &= (a: inout CS.BigUInt, b: CS.BigUInt) { for i in 0 ..< Swift.max(a.count, b.count) { a[i] &= b[i] } } /// Calculate the bitwise XOR of `a` and `b` and return the result. /// /// - Complexity: O(max(a.count, b.count)) public static func ^= (a: inout CS.BigUInt, b: CS.BigUInt) { a.reserveCapacity(b.count) for i in 0 ..< b.count { a[i] ^= b[i] } } } extension CS.BigInt { public static prefix func ~(x: CS.BigInt) -> CS.BigInt { switch x.sign { case .plus: return CS.BigInt(sign: .minus, magnitude: x.magnitude + 1) case .minus: return CS.BigInt(sign: .plus, magnitude: x.magnitude - 1) } } public static func &(lhs: inout CS.BigInt, rhs: CS.BigInt) -> CS.BigInt { let left = lhs.words let right = rhs.words // Note we aren't using left.count/right.count here; we account for the sign bit separately later. let count = Swift.max(lhs.magnitude.count, rhs.magnitude.count) var words: [UInt] = [] words.reserveCapacity(count) for i in 0 ..< count { words.append(left[i] & right[i]) } if lhs.sign == .minus && rhs.sign == .minus { words.twosComplement() return CS.BigInt(sign: .minus, magnitude: CS.BigUInt(words: words)) } return CS.BigInt(sign: .plus, magnitude: CS.BigUInt(words: words)) } public static func |(lhs: inout CS.BigInt, rhs: CS.BigInt) -> CS.BigInt { let left = lhs.words let right = rhs.words // Note we aren't using left.count/right.count here; we account for the sign bit separately later. let count = Swift.max(lhs.magnitude.count, rhs.magnitude.count) var words: [UInt] = [] words.reserveCapacity(count) for i in 0 ..< count { words.append(left[i] | right[i]) } if lhs.sign == .minus || rhs.sign == .minus { words.twosComplement() return CS.BigInt(sign: .minus, magnitude: CS.BigUInt(words: words)) } return CS.BigInt(sign: .plus, magnitude: CS.BigUInt(words: words)) } public static func ^(lhs: inout CS.BigInt, rhs: CS.BigInt) -> CS.BigInt { let left = lhs.words let right = rhs.words // Note we aren't using left.count/right.count here; we account for the sign bit separately later. let count = Swift.max(lhs.magnitude.count, rhs.magnitude.count) var words: [UInt] = [] words.reserveCapacity(count) for i in 0 ..< count { words.append(left[i] ^ right[i]) } if (lhs.sign == .minus) != (rhs.sign == .minus) { words.twosComplement() return CS.BigInt(sign: .minus, magnitude: CS.BigUInt(words: words)) } return CS.BigInt(sign: .plus, magnitude: CS.BigUInt(words: words)) } public static func &=(lhs: inout CS.BigInt, rhs: CS.BigInt) { lhs = lhs & rhs } public static func |=(lhs: inout CS.BigInt, rhs: CS.BigInt) { lhs = lhs | rhs } public static func ^=(lhs: inout CS.BigInt, rhs: CS.BigInt) { lhs = lhs ^ rhs } }
mit
bbd7962c4852c6c2fdee071cf6d4a72e
32.991736
106
0.557257
3.617414
false
false
false
false
yaozongchao/ComplicateTableDemo
ComplicateUI/KDCollectionViewTableCell.swift
1
1885
// // KDCollectionViewTableCell.swift // ComplicateUI // // Created by 姚宗超 on 2017/3/7. // Copyright © 2017年 姚宗超. All rights reserved. // import UIKit import SnapKit class KDCollectionViewTableCell: UITableViewCell { lazy var collectionView: UICollectionView = { let layout = UICollectionViewFlowLayout.init() layout.scrollDirection = UICollectionViewScrollDirection.horizontal layout.sectionInset = UIEdgeInsets(top: 4, left: 5, bottom: 4, right: 5) layout.minimumLineSpacing = 5 layout.itemSize = CGSize(width: 91, height: 91) let view = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: layout) view.register(KDCollectionCell.self, forCellWithReuseIdentifier: "KDCollectionCell") return view }() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.contentView.addSubview(self.collectionView) self.collectionView.snp.makeConstraints { (make) in make.edges.equalTo(self.contentView) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func setCollectionViewDataSourceDelegate(dataSourceDelegate delegate: UICollectionViewDelegate & UICollectionViewDataSource, index: NSInteger) { self.collectionView.dataSource = delegate self.collectionView.delegate = delegate self.collectionView.tag = index self.collectionView.reloadData() } }
mit
fbf5fb979f93fe97313f1ce017e18a5f
32.392857
148
0.693048
5.054054
false
false
false
false
luosheng/OpenSim
OpenSim/Device.swift
1
2797
// // Device.swift // SimPholders // // Created by Luo Sheng on 11/9/15. // Copyright © 2015 Luo Sheng. All rights reserved. // import Foundation enum State { case shutdown case booted case unknown } struct Device { private let stateValue: String public let name: String public let UDID: String } extension Device { public var applications: [Application]? { let applicationPath = URLHelper.deviceURLForUDID(self.UDID).appendingPathComponent("data/Containers/Bundle/Application") let contents = try? FileManager.default.contentsOfDirectory(at: applicationPath, includingPropertiesForKeys: [.isDirectoryKey], options: [.skipsSubdirectoryDescendants, .skipsHiddenFiles]) return contents? .filter({ (url) -> Bool in var isDirectoryObj: AnyObject? try? (url as NSURL).getResourceValue(&isDirectoryObj, forKey: URLResourceKey.isDirectoryKey) guard let isDirectory = isDirectoryObj as? Bool else { return false } return isDirectory }) .map { Application(device: self, url: $0) } .filter { $0 != nil } .map { $0! } } public var state: State { switch stateValue { case "Booted": return .booted case "Shutdown": return .shutdown default: return .unknown } } public func containerURLForApplication(_ application: Application) -> URL? { let URL = URLHelper.containersURLForUDID(UDID) let directories = try? FileManager.default.contentsOfDirectory(at: URL, includingPropertiesForKeys: nil, options: .skipsSubdirectoryDescendants) return directories?.filter({ (dir) -> Bool in if let contents = NSDictionary(contentsOf: dir.appendingPathComponent(".com.apple.mobile_container_manager.metadata.plist")), let identifier = contents["MCMMetadataIdentifier"] as? String, identifier == application.bundleID { return true } return false }).first } func launch() { if state != .booted { SimulatorController.boot(self) } SimulatorController.open() } func shutDown() { if state == .booted { SimulatorController.shutdown(self) } } func factoryReset() { if state != .shutdown { SimulatorController.shutdown(self) } SimulatorController.factoryReset(self) } } extension Device: Decodable { enum CodingKeys: String, CodingKey { case UDID = "udid" case name case stateValue = "state" } }
mit
9c4c8d90a922e5242d671724f10d132e
29.725275
196
0.592632
4.992857
false
false
false
false
onekyle/YCHPhotoKit
Source/Classes/UI/YCHNaviBar.swift
1
3901
// // YCHNaviBar.swift // YCHPhotoKit // // Created by Kyle on 2020/5/5. // import UIKit public class YCHNaviBar: UIView { @objc var leftButton: UIButton @objc var rightButton: UIButton { didSet { oldValue.removeFromSuperview() addSubview(rightButton) updateAllConstraints() } } @objc var titleLabel: UILabel @objc var titleView: UIView? { didSet { if let t = titleView { oldValue?.removeFromSuperview() self.addSubview(t) titleLabel.isHidden = true } else { titleLabel.isHidden = false } } } @objc var backgroundView: UIImageView @objc var seperatorView: UIView @objc var title: String? { set { titleLabel.text = newValue } get { return titleLabel.text } } @objc var didUpdateConstraints: ((YCHNaviBar) -> Void)? convenience init() { self.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height >= 812 ? 88 : 64)) } override init(frame: CGRect) { backgroundView = UIImageView.init(frame: .zero) let itemFont = UIFont.systemFont(ofSize: 14) let titleFont = UIFont.systemFont(ofSize: 18) leftButton = UIButton.init(type: .custom) leftButton.titleLabel?.font = itemFont leftButton.setImage(UIImage.init(named: "naviBack"), for: .normal) rightButton = UIButton.init(type: .custom) rightButton.titleLabel?.font = itemFont titleLabel = UILabel.init(frame: .zero) titleLabel.textAlignment = .center titleLabel.font = titleFont seperatorView = UIView.init(frame: .zero) seperatorView.isHidden = true super.init(frame: frame) addSubview(backgroundView) addSubview(leftButton) addSubview(rightButton) addSubview(titleLabel) addSubview(seperatorView) backgroundView.clp.makeConstraints { (make) in make.edges.equalToSuperview() } updateAllConstraints() } override public func didMoveToSuperview() { super.didMoveToSuperview() if #available(iOS 9.0, *) { } else { // 解决iOS8 系统下的bug. 依赖的约束的控件如果不是autolayout布局的, iOS下就不显示.. if superview != nil { self.clp.remakeConstraints { (make) in make.top.right.left.equalToSuperview() make.height.equalTo(self.frame.size.height) } } } } public func placeHolderFunc() { print("this func is just for debuging xcode10.1 crash bug") } public func updateAllConstraints() { leftButton.clp.remakeConstraints { (make) in make.left.equalToSuperview().offset(8) make.width.height.equalTo(44) make.bottom.equalToSuperview() } rightButton.clp.remakeConstraints { (make) in make.right.equalToSuperview().offset(-8) make.height.equalTo(44) make.width.equalTo(44) make.centerY.equalTo(leftButton) } titleLabel.clp.remakeConstraints { (make) in make.centerY.equalTo(leftButton) make.left.equalTo(50) make.right.equalTo(-50) make.height.equalTo(28) } seperatorView.clp.remakeConstraints { (make) in make.left.right.bottom.equalToSuperview() make.height.equalTo(1) } didUpdateConstraints?(self) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
207eac1bbb5fd405975ac98a4adfbfa1
27.723881
138
0.570798
4.671117
false
false
false
false
CoderYLiu/30DaysOfSwift
Project 14 - EmojiSlotMachine/EmojiMachine/ViewController.swift
1
4250
// // ViewController.swift // EmojiMachine <https://github.com/DeveloperLY/30DaysOfSwift> // // Created by Liu Y on 16/4/20. // Copyright © 2016年 DeveloperLY. All rights reserved. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // import UIKit class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource { @IBOutlet weak var emojiPickerView: UIPickerView! @IBOutlet weak var goButton: UIButton! @IBOutlet weak var resultLabel: UILabel! var imageArray = [String]() var dataArray1 = [Int]() var dataArray2 = [Int]() var dataArray3 = [Int]() var bounds: CGRect = CGRect.zero override func viewDidLoad() { super.viewDidLoad() bounds = goButton.bounds imageArray = ["👻","👸","💩","😘","🍔","🤖","🍟","🐼","🚖","🐷"] for _ in 0 ..< 100 { dataArray1.append((Int)(arc4random() % 10 )) dataArray2.append((Int)(arc4random() % 10 )) dataArray3.append((Int)(arc4random() % 10 )) } resultLabel.text = "" goButton.layer.cornerRadius = 6 } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) goButton.alpha = 0 } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) UIView.animate(withDuration: 0.5, delay: 0.3, options: .curveEaseOut, animations: { self.goButton.alpha = 1 }, completion: nil) } override var preferredStatusBarStyle : UIStatusBarStyle { return UIStatusBarStyle.lightContent } var test = 1 @IBAction func goButtoDidClick(_ sender: AnyObject) { emojiPickerView.selectRow(Int(arc4random()) % 90 + 3, inComponent: 0, animated: true) emojiPickerView.selectRow(Int(arc4random()) % 90 + 3, inComponent: 1, animated: true) emojiPickerView.selectRow(Int(arc4random()) % 90 + 3, inComponent: 2, animated: true) if(dataArray1[emojiPickerView.selectedRow(inComponent: 0)] == dataArray2[emojiPickerView.selectedRow(inComponent: 1)] && dataArray2[emojiPickerView.selectedRow(inComponent: 1)] == dataArray3[emojiPickerView.selectedRow(inComponent: 2)]) { resultLabel.text = "Bingo!" } else { resultLabel.text = "💔" } // animate goButton.transform = CGAffineTransform(scaleX: 0.0, y: 0.0) UIView.animate(withDuration: 1.25, delay: 0.0, usingSpringWithDamping: 0.3, initialSpringVelocity: 10, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in self.goButton.transform = CGAffineTransform.identity }, completion: { (_) -> Void in self.goButton.isUserInteractionEnabled = true }) } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return 100 } func numberOfComponents(in pickerView: UIPickerView) -> Int { return 3 } func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat { return 100.0 } func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat { return 100.0 } func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView { let pickerLabel = UILabel() if component == 0 { pickerLabel.text = imageArray[(Int)(dataArray1[row])] } else if component == 1 { pickerLabel.text = imageArray[(Int)(dataArray2[row])] } else { pickerLabel.text = imageArray[(Int)(dataArray3[row])] } pickerLabel.font = UIFont(name: "Apple Color Emoji", size: 80) pickerLabel.textAlignment = NSTextAlignment.center return pickerLabel } }
mit
bbfba9c2a708b49ad01e0f0c40832fef
30.924242
246
0.594684
4.810502
false
false
false
false
natecook1000/swift
test/SILGen/objc_extensions.swift
2
10459
// RUN: %target-swift-emit-silgen -module-name objc_extensions -enable-sil-ownership -sdk %S/Inputs/ -I %S/Inputs -enable-source-import %s | %FileCheck %s // REQUIRES: objc_interop import Foundation import objc_extensions_helper class Sub : Base {} extension Sub { @objc override var prop: String! { didSet { // Ignore it. } // Make sure that we are generating the @objc thunk and are calling the actual method. // // CHECK-LABEL: sil hidden [thunk] @$S15objc_extensions3SubC4propSSSgvgTo : $@convention(objc_method) (Sub) -> @autoreleased Optional<NSString> { // CHECK: bb0([[SELF:%.*]] : @unowned $Sub): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: [[GETTER_FUNC:%.*]] = function_ref @$S15objc_extensions3SubC4propSSSgvg : $@convention(method) (@guaranteed Sub) -> @owned Optional<String> // CHECK: apply [[GETTER_FUNC]]([[BORROWED_SELF_COPY]]) // CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK: destroy_value [[SELF_COPY]] // CHECK: } // end sil function '$S15objc_extensions3SubC4propSSSgvgTo' // Then check the body of the getter calls the super_method. // CHECK-LABEL: sil hidden @$S15objc_extensions3SubC4propSSSgvg : $@convention(method) (@guaranteed Sub) -> @owned Optional<String> { // CHECK: bb0([[SELF:%.*]] : @guaranteed $Sub): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[SELF_COPY_CAST:%.*]] = upcast [[SELF_COPY]] : $Sub to $Base // CHECK: [[BORROWED_SELF_COPY_CAST:%.*]] = begin_borrow [[SELF_COPY_CAST]] // CHECK: [[CAST_BACK:%.*]] = unchecked_ref_cast [[BORROWED_SELF_COPY_CAST]] : $Base to $Sub // CHECK: [[SUPER_METHOD:%.*]] = objc_super_method [[CAST_BACK]] : $Sub, #Base.prop!getter.1.foreign // CHECK: end_borrow [[BORROWED_SELF_COPY_CAST]] // CHECK: [[RESULT:%.*]] = apply [[SUPER_METHOD]]([[SELF_COPY_CAST]]) // CHECK: bb3( // CHECK: destroy_value [[SELF_COPY_CAST]] // CHECK: } // end sil function '$S15objc_extensions3SubC4propSSSgvg' // Then check the setter @objc thunk. // // CHECK-LABEL: sil hidden [thunk] @$S15objc_extensions3SubC4propSSSgvsTo : $@convention(objc_method) (Optional<NSString>, Sub) -> () { // CHECK: bb0([[NEW_VALUE:%.*]] : @unowned $Optional<NSString>, [[SELF:%.*]] : @unowned $Sub): // CHECK: [[NEW_VALUE_COPY:%.*]] = copy_value [[NEW_VALUE]] // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Sub // CHECK: switch_enum [[NEW_VALUE_COPY]] : $Optional<NSString>, case #Optional.some!enumelt.1: [[SUCC_BB:bb[0-9]+]], case #Optional.none!enumelt: [[FAIL_BB:bb[0-9]+]] // CHECK: [[SUCC_BB]]([[STR:%.*]] : @owned $NSString): // CHECK: [[FAIL_BB]]: // CHECK: bb3([[BRIDGED_NEW_VALUE:%.*]] : @owned $Optional<String>): // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: [[NORMAL_FUNC:%.*]] = function_ref @$S15objc_extensions3SubC4propSSSgvs : $@convention(method) (@owned Optional<String>, @guaranteed Sub) -> () // CHECK: apply [[NORMAL_FUNC]]([[BRIDGED_NEW_VALUE]], [[BORROWED_SELF_COPY]]) // CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK: destroy_value [[SELF_COPY]] // CHECK: } // end sil function '$S15objc_extensions3SubC4propSSSgvsTo' // Then check the body of the actually setter value and make sure that we // call the didSet function. // CHECK-LABEL: sil hidden @$S15objc_extensions3SubC4propSSSgvs : $@convention(method) (@owned Optional<String>, @guaranteed Sub) -> () { // First we get the old value. // CHECK: bb0([[NEW_VALUE:%.*]] : @owned $Optional<String>, [[SELF:%.*]] : @guaranteed $Sub): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[UPCAST_SELF_COPY:%.*]] = upcast [[SELF_COPY]] : $Sub to $Base // CHECK: [[BORROWED_UPCAST_SELF_COPY:%.*]] = begin_borrow [[UPCAST_SELF_COPY]] // CHECK: [[CAST_BACK:%.*]] = unchecked_ref_cast [[BORROWED_UPCAST_SELF_COPY]] : $Base to $Sub // CHECK: [[GET_SUPER_METHOD:%.*]] = objc_super_method [[CAST_BACK]] : $Sub, #Base.prop!getter.1.foreign : (Base) -> () -> String?, $@convention(objc_method) (Base) -> @autoreleased Optional<NSString> // CHECK: end_borrow [[BORROWED_UPCAST_SELF_COPY]] from [[UPCAST_SELF_COPY]] // CHECK: [[OLD_NSSTRING:%.*]] = apply [[GET_SUPER_METHOD]]([[UPCAST_SELF_COPY]]) // CHECK: bb3([[OLD_NSSTRING_BRIDGED:%.*]] : @owned $Optional<String>): // This next line is completely not needed. But we are emitting it now. // CHECK: destroy_value [[UPCAST_SELF_COPY]] // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[UPCAST_SELF_COPY:%.*]] = upcast [[SELF_COPY]] : $Sub to $Base // CHECK: [[BORROWED_NEW_VALUE:%.*]] = begin_borrow [[NEW_VALUE]] // CHECK: [[NEW_VALUE_COPY:%.*]] = copy_value [[BORROWED_NEW_VALUE]] // CHECK: switch_enum [[NEW_VALUE_COPY]] : $Optional<String>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: bb4([[OLD_STRING:%.*]] : @owned $String): // CHECK: bb6([[BRIDGED_NEW_STRING:%.*]] : @owned $Optional<NSString>): // CHECK: end_borrow [[BORROWED_NEW_VALUE]] // CHECK: [[BORROWED_UPCAST_SELF:%.*]] = begin_borrow [[UPCAST_SELF_COPY]] : $Base // CHECK: [[SUPERREF_DOWNCAST:%.*]] = unchecked_ref_cast [[BORROWED_UPCAST_SELF]] : $Base to $Sub // CHECK: [[SET_SUPER_METHOD:%.*]] = objc_super_method [[SUPERREF_DOWNCAST]] : $Sub, #Base.prop!setter.1.foreign : (Base) -> (String?) -> (), $@convention(objc_method) (Optional<NSString>, Base) -> () // CHECK: apply [[SET_SUPER_METHOD]]([[BRIDGED_NEW_STRING]], [[UPCAST_SELF_COPY]]) // CHECK: destroy_value [[BRIDGED_NEW_STRING]] // CHECK: destroy_value [[UPCAST_SELF_COPY]] // CHECK: [[BORROWED_OLD_NSSTRING_BRIDGED:%.*]] = begin_borrow [[OLD_NSSTRING_BRIDGED]] // This is an identity cast that should be eliminated by SILGen peepholes. // CHECK: [[DIDSET_NOTIFIER:%.*]] = function_ref @$S15objc_extensions3SubC4propSSSgvW : $@convention(method) (@guaranteed Optional<String>, @guaranteed Sub) -> () // CHECK: apply [[DIDSET_NOTIFIER]]([[BORROWED_OLD_NSSTRING_BRIDGED]], [[SELF]]) // CHECK: end_borrow [[BORROWED_OLD_NSSTRING_BRIDGED]] from [[OLD_NSSTRING_BRIDGED]] // CHECK: destroy_value [[OLD_NSSTRING_BRIDGED]] // CHECK: destroy_value [[NEW_VALUE]] // CHECK: } // end sil function '$S15objc_extensions3SubC4propSSSgvs' } @objc func foo() { } @objc override func objCBaseMethod() {} } // CHECK-LABEL: sil hidden @$S15objc_extensions20testOverridePropertyyyAA3SubCF func testOverrideProperty(_ obj: Sub) { // CHECK: bb0([[ARG:%.*]] : @guaranteed $Sub): // CHECK: = objc_method [[ARG]] : $Sub, #Sub.prop!setter.1.foreign : (Sub) -> (String?) -> () obj.prop = "abc" } // CHECK: } // end sil function '$S15objc_extensions20testOverridePropertyyyAA3SubCF' testOverrideProperty(Sub()) // CHECK-LABEL: sil shared [thunk] @$S15objc_extensions3SubC3fooyyFTc // CHECK: function_ref @$S15objc_extensions3SubC3fooyyFTD // CHECK: } // end sil function '$S15objc_extensions3SubC3fooyyFTc' // CHECK: sil shared [transparent] [serializable] [thunk] @$S15objc_extensions3SubC3fooyyFTD // CHECK: bb0([[SELF:%.*]] : @guaranteed $Sub): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: objc_method [[SELF_COPY]] : $Sub, #Sub.foo!1.foreign // CHECK: } // end sil function '$S15objc_extensions3SubC3fooyyFTD' func testCurry(_ x: Sub) { _ = x.foo } extension Sub { @objc var otherProp: String { get { return "hello" } set { } } } class SubSub : Sub { // CHECK-LABEL: sil hidden @$S15objc_extensions03SubC0C14objCBaseMethodyyF : // CHECK: bb0([[SELF:%.*]] : @guaranteed $SubSub): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[UPCAST_SELF_COPY:%.*]] = upcast [[SELF_COPY]] : $SubSub to $Sub // CHECK: [[BORROWED_UPCAST_SELF_COPY:%.*]] = begin_borrow [[UPCAST_SELF_COPY]] // CHECK: [[DOWNCAST:%.*]] = unchecked_ref_cast [[BORROWED_UPCAST_SELF_COPY]] : $Sub to $SubSub // CHECK: objc_super_method [[DOWNCAST]] : $SubSub, #Sub.objCBaseMethod!1.foreign : (Sub) -> () -> (), $@convention(objc_method) (Sub) -> () // CHECK: end_borrow [[BORROWED_UPCAST_SELF_COPY]] from [[UPCAST_SELF_COPY]] // CHECK: } // end sil function '$S15objc_extensions03SubC0C14objCBaseMethodyyF' override func objCBaseMethod() { super.objCBaseMethod() } } extension SubSub { // CHECK-LABEL: sil hidden @$S15objc_extensions03SubC0C9otherPropSSvs // CHECK: bb0([[NEW_VALUE:%.*]] : @owned $String, [[SELF:%.*]] : @guaranteed $SubSub): // CHECK: [[SELF_COPY_1:%.*]] = copy_value [[SELF]] // CHECK: [[UPCAST_SELF_COPY_1:%.*]] = upcast [[SELF_COPY_1]] : $SubSub to $Sub // CHECK: [[BORROWED_UPCAST_SELF_COPY_1:%.*]] = begin_borrow [[UPCAST_SELF_COPY_1]] // CHECK: [[DOWNCAST_BORROWED_UPCAST_SELF_COPY_1:%.*]] = unchecked_ref_cast [[BORROWED_UPCAST_SELF_COPY_1]] : $Sub to $SubSub // CHECK: = objc_super_method [[DOWNCAST_BORROWED_UPCAST_SELF_COPY_1]] : $SubSub, #Sub.otherProp!getter.1.foreign // CHECK: end_borrow [[BORROWED_UPCAST_SELF_COPY_1]] from [[UPCAST_SELF_COPY_1]] // CHECK: [[SELF_COPY_2:%.*]] = copy_value [[SELF]] // CHECK: [[UPCAST_SELF_COPY_2:%.*]] = upcast [[SELF_COPY_2]] : $SubSub to $Sub // CHECK: [[BORROWED_UPCAST_SELF_COPY_2:%.*]] = begin_borrow [[UPCAST_SELF_COPY_2]] // CHECK: [[DOWNCAST_BORROWED_UPCAST_SELF_COPY_2:%.*]] = unchecked_ref_cast [[BORROWED_UPCAST_SELF_COPY_2]] : $Sub to $SubSub // CHECK: = objc_super_method [[DOWNCAST_BORROWED_UPCAST_SELF_COPY_2]] : $SubSub, #Sub.otherProp!setter.1.foreign // CHECK: end_borrow [[BORROWED_UPCAST_SELF_COPY_2]] from [[UPCAST_SELF_COPY_2]] // CHECK: } // end sil function '$S15objc_extensions03SubC0C9otherPropSSvs' @objc override var otherProp: String { didSet { // Ignore it. } } } // SR-1025 extension Base { fileprivate static var x = 1 } // CHECK-LABEL: sil hidden @$S15objc_extensions19testStaticVarAccessyyF func testStaticVarAccess() { // CHECK: [[F:%.*]] = function_ref @$SSo4BaseC15objc_extensionsE1x33_1F05E59585E0BB585FCA206FBFF1A92DLLSivau // CHECK: [[PTR:%.*]] = apply [[F]]() // CHECK: [[ADDR:%.*]] = pointer_to_address [[PTR]] _ = Base.x }
apache-2.0
7968ef4b85d032b5e9674532f638b562
54.930481
206
0.62463
3.381507
false
false
false
false
imobilize/Molib
Molib/Classes/Categories/UIImage+Helpers.swift
1
4105
import Foundation import UIKit extension UIImage { static public func from(color: UIColor) -> UIImage { let rect = CGRect(x: 0, y: 0, width: 1, height: 1) UIGraphicsBeginImageContext(rect.size) let context = UIGraphicsGetCurrentContext() context!.setFillColor(color.cgColor) context!.fill(rect) let img = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return img! } public func rotateCameraImageToProperOrientation(maxResolution : CGFloat) -> UIImage { let imageSource = self guard let imgRef = imageSource.cgImage else { return UIImage() } let width = CGFloat(imgRef.width) let height = CGFloat(imgRef.height) var bounds = CGRect(x: 0, y: 0, width: width, height: height) var scaleRatio : CGFloat = 1 if (width > maxResolution || height > maxResolution) { scaleRatio = min(maxResolution / bounds.size.width, maxResolution / bounds.size.height) bounds.size.height = bounds.size.height * scaleRatio bounds.size.width = bounds.size.width * scaleRatio } var transform = CGAffineTransform.identity let orient = imageSource.imageOrientation let imageSize = CGSize(width: width, height: height) switch(imageSource.imageOrientation) { case .up : transform = CGAffineTransform.identity case .upMirrored : transform = CGAffineTransform(translationX: imageSize.width, y: 0.0) transform = transform.scaledBy(x: -1.0, y: 1.0) case .down : transform = CGAffineTransform(translationX: imageSize.width, y: imageSize.height) transform = transform.rotated(by: CGFloat(Double.pi)) case .downMirrored : transform = CGAffineTransform(translationX: 0.0, y: imageSize.height) transform = transform.scaledBy(x: 1.0, y: -1.0) case .left : let storedHeight = bounds.size.height bounds.size.height = bounds.size.width; bounds.size.width = storedHeight; transform = CGAffineTransform(translationX:0.0, y: imageSize.width) transform = transform.rotated(by: 3.0 * CGFloat(Double.pi) / 2.0) case .leftMirrored : let storedHeight = bounds.size.height bounds.size.height = bounds.size.width; bounds.size.width = storedHeight; transform = CGAffineTransform(translationX: imageSize.height, y: imageSize.width) transform = transform.translatedBy(x: -1.0, y: 1.0) transform = transform.rotated(by: 3.0 * CGFloat(Double.pi) / 2.0) case .right : let storedHeight = bounds.size.height bounds.size.height = bounds.size.width; bounds.size.width = storedHeight; transform = CGAffineTransform(translationX: imageSize.height, y: 0.0) transform = transform.rotated(by: CGFloat(Double.pi) / 2.0) case .rightMirrored : let storedHeight = bounds.size.height bounds.size.height = bounds.size.width; bounds.size.width = storedHeight; transform = CGAffineTransform(scaleX: -1.0, y: 1.0) transform = transform.rotated(by: CGFloat(Double.pi) / 2.0) } UIGraphicsBeginImageContext(bounds.size) let context = UIGraphicsGetCurrentContext() if orient == .right || orient == .left { context?.scaleBy(x: -scaleRatio, y: scaleRatio) context?.translateBy(x: -height, y: 0) } else { context?.scaleBy(x: scaleRatio, y: -scaleRatio) context?.translateBy(x: 0, y: -height) } context?.concatenate(transform) context?.draw(imgRef, in: CGRect(x: 0, y: 0, width: width, height: height)) let imageCopy = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return imageCopy! } }
apache-2.0
77a13ddcefe2723b550482f2ada37451
26.18543
99
0.609744
4.675399
false
false
false
false
DadosAbertosBrasil/swift-radar-politico
swift-radar-político/View/VotacaoCell.swift
1
2728
// // VotacaoCell.swift // swift-radar-político // // Created by Ulysses on 3/28/16. // Copyright © 2016 Francisco José A. C. Souza. All rights reserved. // import UIKit class VotacaoCell: UITableViewCell, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! private var proposicao:CDProposicao? func loadWithVotacao(proposicao:CDProposicao){ self.tableView.delegate = self self.tableView.dataSource = self self.proposicao = proposicao self.tableView.reloadData() self.tableView.layer.cornerRadius = 5.0 self.tableView.clipsToBounds = true self.tableView.layer.masksToBounds = true } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (section == 0 ? 1 : DeputadosDataController.sharedInstance.getNumberOfFollowedDeputados() ) } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.section == 0{ let cell = tableView.dequeueReusableCellWithIdentifier("ConteudoCell", forIndexPath: indexPath) as! ConteudoCell cell.loadWithProposicao(proposicao!, votacao: proposicao!.votacoes.last as! CDVotacao) return cell } // -- Voto let cell = tableView.dequeueReusableCellWithIdentifier("VotoCell", forIndexPath: indexPath) if let deputado = DeputadosDataController.sharedInstance.getFollowedDeputadoWith(indexPath.row){ cell.textLabel!.text = deputado.nomeParlamentar.capitalizedString cell.detailTextLabel?.text = self.getVoteFromDeputadoWithName(deputado.nomeParlamentar.capitalizedString, inVotacao: proposicao!.votacoes.last as! CDVotacao) cell.roundCorner() } return cell } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { //TODO: Change to dynamic Height return indexPath.section == 0 ? 240.0 : 40 } private func getVoteFromDeputadoWithName(nomeDeputado:String, inVotacao votacao:CDVotacao)->String{ let votos = votacao.votoDeputados //TODO: Improve search for i in votos{ let name = i.objectForKey("Nome") as! String if name.lowercaseString == nomeDeputado.lowercaseString{ return i.objectForKey("Voto") as! String } } return "Sem Voto" } }
gpl-2.0
de04fa59636a54680ff5f2c2331b51cb
32.641975
169
0.651743
4.541667
false
false
false
false
crspybits/SyncServerII
Sources/Server/Database/DeviceUUIDRepository.swift
1
4385
// // DeviceUUIDRepository.swift // Server // // Created by Christopher Prince on 2/14/17. // // // Tracks deviceUUID's and their userId's. This is important for security. Also can enable limitations about number of devices per userId. import Foundation import LoggerAPI import SyncServerShared class DeviceUUID : NSObject, Model { static let userIdKey = "userId" var userId: UserId! static let deviceUUIDKey = "deviceUUID" var deviceUUID: String! subscript(key:String) -> Any? { set { switch key { case DeviceUUID.userIdKey: userId = newValue as! UserId? case DeviceUUID.deviceUUIDKey: deviceUUID = newValue as! String? default: assert(false) } } get { return getValue(forKey: key) } } override init() { super.init() } init(userId: UserId, deviceUUID: String) { self.userId = userId // TODO: *2* Validate that this is a good UUID. self.deviceUUID = deviceUUID } } class DeviceUUIDRepository : Repository, RepositoryLookup { private(set) var db:Database! var maximumNumberOfDeviceUUIDsPerUser:Int? = Configuration.server.maxNumberDeviceUUIDPerUser required init(_ db:Database) { self.db = db } var tableName:String { return DeviceUUIDRepository.tableName } static var tableName:String { return "DeviceUUID" } // TODO: *3* We can possibly have the same device used by two different users. E.g., if a user signs in on the device with one set of credentials, then signs out and signs in with a different set of credentials. func upcreate() -> Database.TableUpcreateResult { let createColumns = // reference into User table "(userId BIGINT NOT NULL, " + // identifies a specific mobile device (assigned by app) "deviceUUID VARCHAR(\(Database.uuidLength)) NOT NULL, " + "UNIQUE (deviceUUID))" return db.createTableIfNeeded(tableName: "\(tableName)", columnCreateQuery: createColumns) } enum LookupKey : CustomStringConvertible { case userId(UserId) case deviceUUID(String) var description : String { switch self { case .userId(let userId): return "userId(\(userId))" case .deviceUUID(let deviceUUID): return "deviceUUID(\(deviceUUID))" } } } func lookupConstraint(key:LookupKey) -> String { switch key { case .userId(let userId): return "userId = '\(userId)'" case .deviceUUID(let deviceUUID): return "deviceUUID = '\(deviceUUID)'" } } enum DeviceUUIDAddResult { case error(String) case success case exceededMaximumUUIDsPerUser } // Adds a record // If maximumNumberOfDeviceUUIDsPerUser != nil, makes sure that the number of deviceUUID's per user doesn't exceed maximumNumberOfDeviceUUIDsPerUser func add(deviceUUID:DeviceUUID) -> DeviceUUIDAddResult { if deviceUUID.userId == nil || deviceUUID.deviceUUID == nil { let message = "One of the model values was nil!" Log.error(message) return .error(message) } var query = "INSERT INTO \(tableName) (userId, deviceUUID) " if maximumNumberOfDeviceUUIDsPerUser == nil { query += "VALUES (\(deviceUUID.userId!), '\(deviceUUID.deviceUUID!)')" } else { query += "select \(deviceUUID.userId!), '\(deviceUUID.deviceUUID!)' from Dual where " + "(select count(*) from \(tableName) where userId = \(deviceUUID.userId!)) < \(maximumNumberOfDeviceUUIDsPerUser!)" } if db.query(statement: query) { if db.numberAffectedRows() == 1 { return .success } else { return .exceededMaximumUUIDsPerUser } } else { let message = "Could not insert into \(tableName): \(db.error)" Log.error(message) return .error(message) } } }
mit
bac4efe8bf3cfec96e12ac98bcb67a06
28.628378
215
0.573774
4.954802
false
false
false
false
jtbandes/swift
test/IDE/complete_decl_attribute.swift
2
9894
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=AVAILABILITY1 | %FileCheck %s -check-prefix=AVAILABILITY1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=AVAILABILITY2 | %FileCheck %s -check-prefix=AVAILABILITY2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=KEYWORD1 | %FileCheck %s -check-prefix=KEYWORD1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=KEYWORD2 | %FileCheck %s -check-prefix=KEYWORD2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=KEYWORD3 | %FileCheck %s -check-prefix=KEYWORD3 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=KEYWORD4 | %FileCheck %s -check-prefix=KEYWORD4 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=KEYWORD5 | %FileCheck %s -check-prefix=KEYWORD5 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=KEYWORD_LAST | %FileCheck %s -check-prefix=KEYWORD_LAST @available(#^AVAILABILITY1^#) // AVAILABILITY1: Begin completions, 9 items // AVAILABILITY1-NEXT: Keyword/None: *[#Platform#]; name=*{{$}} // AVAILABILITY1-NEXT: Keyword/None: iOS[#Platform#]; name=iOS{{$}} // AVAILABILITY1-NEXT: Keyword/None: tvOS[#Platform#]; name=tvOS{{$}} // AVAILABILITY1-NEXT: Keyword/None: watchOS[#Platform#]; name=watchOS{{$}} // AVAILABILITY1-NEXT: Keyword/None: OSX[#Platform#]; name=OSX{{$}} // AVAILABILITY1-NEXT: Keyword/None: iOSApplicationExtension[#Platform#]; name=iOSApplicationExtension{{$}} // AVAILABILITY1-NEXT: Keyword/None: tvOSApplicationExtension[#Platform#]; name=tvOSApplicationExtension{{$}} // AVAILABILITY1-NEXT: Keyword/None: watchOSApplicationExtension[#Platform#]; name=watchOSApplicationExtension{{$}} // AVAILABILITY1-NEXT: Keyword/None: OSXApplicationExtension[#Platform#]; name=OSXApplicationExtension{{$}} // AVAILABILITY1-NEXT: End completions @available(*, #^AVAILABILITY2^#) // AVAILABILITY2: Begin completions, 5 items // AVAILABILITY2-NEXT: Keyword/None: unavailable; name=unavailable{{$}} // AVAILABILITY2-NEXT: Keyword/None: message: [#Specify message#]; name=message{{$}} // AVAILABILITY2-NEXT: Keyword/None: renamed: [#Specify replacing name#]; name=renamed{{$}} // AVAILABILITY2-NEXT: Keyword/None: introduced: [#Specify version number#]; name=introduced{{$}} // AVAILABILITY2-NEXT: Keyword/None: deprecated: [#Specify version number#]; name=deprecated{{$}} // AVAILABILITY2-NEXT: End completions func method(@#^KEYWORD1^#) {} // KEYWORD1: Begin completions, 2 items // KEYWORD1-NEXT: Keyword/None: autoclosure[#Param Attribute#]; name=autoclosure{{$}} // KEYWORD1-NEXT: Keyword/None: noescape[#Param Attribute#]; name=noescape{{$}} // KEYWORD1-NEXT: End completions @#^KEYWORD2^# func method(){} // KEYWORD2: Begin completions, 9 items // KEYWORD2-NEXT: Keyword/None: available[#Func Attribute#]; name=available{{$}} // KEYWORD2-NEXT: Keyword/None: objc[#Func Attribute#]; name=objc{{$}} // KEYWORD2-NEXT: Keyword/None: noreturn[#Func Attribute#]; name=noreturn{{$}} // KEYWORD2-NEXT: Keyword/None: IBAction[#Func Attribute#]; name=IBAction{{$}} // KEYWORD2-NEXT: Keyword/None: NSManaged[#Func Attribute#]; name=NSManaged{{$}} // KEYWORD2-NEXT: Keyword/None: inline[#Func Attribute#]; name=inline{{$}} // KEYWORD2-NEXT: Keyword/None: nonobjc[#Func Attribute#]; name=nonobjc{{$}} // KEYWORD2-NEXT: Keyword/None: warn_unqualified_access[#Func Attribute#]; name=warn_unqualified_access{{$}} // KEYWORD2-NEXT: Keyword/None: discardableResult[#Func Attribute#]; name=discardableResult // KEYWORD2-NEXT: End completions @#^KEYWORD3^# class C {} // KEYWORD3: Begin completions, 10 items // KEYWORD3-NEXT: Keyword/None: available[#Class Attribute#]; name=available{{$}} // KEYWORD3-NEXT: Keyword/None: objc[#Class Attribute#]; name=objc{{$}} // KEYWORD3-NEXT: Keyword/None: IBDesignable[#Class Attribute#]; name=IBDesignable{{$}} // KEYWORD3-NEXT: Keyword/None: UIApplicationMain[#Class Attribute#]; name=UIApplicationMain{{$}} // KEYWORD3-NEXT: Keyword/None: requires_stored_property_inits[#Class Attribute#]; name=requires_stored_property_inits{{$}} // KEYWORD3-NEXT: Keyword/None: objcMembers[#Class Attribute#]; name=objcMembers{{$}} // KEYWORD3-NEXT: Keyword/None: NSApplicationMain[#Class Attribute#]; name=NSApplicationMain{{$}} // KEYWORD3-NEXT: Keyword/None: objc_non_lazy_realization[#Class Attribute#]; name=objc_non_lazy_realization{{$}} // KEYWORD3-NEXT: Keyword/None: NSKeyedArchiverClassName[#Class Attribute#]; name=NSKeyedArchiverClassName{{$}} // KEYWORD3-NEXT: Keyword/None: NSKeyedArchiverEncodeNonGenericSubclassesOnly[#Class Attribute#]; name=NSKeyedArchiverEncodeNonGenericSubclassesOnly{{$}} // KEYWORD3-NEXT: End completions @#^KEYWORD4^# enum E {} // KEYWORD4: Begin completions, 2 items // KEYWORD4-NEXT: Keyword/None: available[#Enum Attribute#]; name=available{{$}} // KEYWORD4-NEXT: Keyword/None: objc[#Enum Attribute#]; name=objc{{$}} // KEYWORD4-NEXT: End completions @#^KEYWORD5^# struct S{} // KEYWORD5: Begin completions, 1 item // KEYWORD5-NEXT: Keyword/None: available[#Struct Attribute#]; name=available{{$}} // KEYWORD5-NEXT: End completions @#^KEYWORD_LAST^# // KEYWORD_LAST: Begin completions, 23 items // KEYWORD_LAST-NEXT: Keyword/None: available[#Declaration Attribute#]; name=available{{$}} // KEYWORD_LAST-NEXT: Keyword/None: objc[#Declaration Attribute#]; name=objc{{$}} // KEYWORD_LAST-NEXT: Keyword/None: noreturn[#Declaration Attribute#]; name=noreturn{{$}} // KEYWORD_LAST-NEXT: Keyword/None: NSCopying[#Declaration Attribute#]; name=NSCopying{{$}} // KEYWORD_LAST-NEXT: Keyword/None: IBAction[#Declaration Attribute#]; name=IBAction{{$}} // KEYWORD_LAST-NEXT: Keyword/None: IBDesignable[#Declaration Attribute#]; name=IBDesignable{{$}} // KEYWORD_LAST-NEXT: Keyword/None: IBInspectable[#Declaration Attribute#]; name=IBInspectable{{$}} // KEYWORD_LAST-NEXT: Keyword/None: IBOutlet[#Declaration Attribute#]; name=IBOutlet{{$}} // KEYWORD_LAST-NEXT: Keyword/None: NSManaged[#Declaration Attribute#]; name=NSManaged{{$}} // KEYWORD_LAST-NEXT: Keyword/None: UIApplicationMain[#Declaration Attribute#]; name=UIApplicationMain{{$}} // KEYWORD_LAST-NEXT: Keyword/None: inline[#Declaration Attribute#]; name=inline{{$}} // KEYWORD_LAST-NEXT: Keyword/None: requires_stored_property_inits[#Declaration Attribute#]; name=requires_stored_property_inits{{$}} // KEYWORD_LAST-NEXT: Keyword/None: autoclosure[#Declaration Attribute#]; name=autoclosure{{$}} // KEYWORD_LAST-NEXT: Keyword/None: noescape[#Declaration Attribute#]; name=noescape{{$}} // KEYWORD_LAST-NEXT: Keyword/None: nonobjc[#Declaration Attribute#]; name=nonobjc{{$}} // KEYWORD_LAST-NEXT: Keyword/None: objcMembers[#Declaration Attribute#]; name=objcMembers{{$}} // KEYWORD_LAST-NEXT: Keyword/None: NSApplicationMain[#Declaration Attribute#]; name=NSApplicationMain{{$}} // KEYWORD_LAST-NEXT: Keyword/None: objc_non_lazy_realization[#Declaration Attribute#]; name=objc_non_lazy_realization{{$}} // KEYWORD_LAST-NEXT: Keyword/None: warn_unqualified_access[#Declaration Attribute#]; name=warn_unqualified_access // KEYWORD_LAST-NEXT: Keyword/None: discardableResult[#Declaration Attribute#]; name=discardableResult // KEYWORD_LAST-NEXT: Keyword/None: GKInspectable[#Declaration Attribute#]; name=GKInspectable{{$}} // KEYWORD_LAST-NEXT: Keyword/None: NSKeyedArchiverClassName[#Declaration Attribute#]; name=NSKeyedArchiverClassName{{$}} // KEYWORD_LAST-NEXT: Keyword/None: NSKeyedArchiverEncodeNonGenericSubclassesOnly[#Declaration Attribute#]; name=NSKeyedArchiverEncodeNonGenericSubclassesOnly{{$}} // KEYWORD_LAST-NEXT: End completions
apache-2.0
d0c1a8195f68a2c9b01799710ca4e40b
85.034783
197
0.58682
4.85
false
true
false
false
clwm01/RTKitDemo
RCToolsDemo/RTAudioItem.swift
2
1629
// // RTAudioItem.swift // RCToolsDemo // // Created by Rex Tsao on 10/5/2016. // Copyright © 2016 rexcao. All rights reserved. // import Foundation import AVFoundation enum AudioItemType { case Remote case Local } class RTAudioItem { private var type: AudioItemType? var url: NSURL? var title: String? var album: String? var artist: String? var artwork: UIImage? var duration: Float64? var timePlayed: Float64? init(type: AudioItemType, url: NSURL) { self.type = type self.url = url self.retrieveMeta() } private func retrieveMeta() { let playerItem = AVPlayerItem(URL: self.url!) let metaData = playerItem.asset.commonMetadata for data in metaData { if data.commonKey! == "title" { self.title = data.value?.copyWithZone(nil) as? String } else if data.commonKey! == "albumName" { self.album = data.value!.copyWithZone(nil) as? String } else if data.commonKey! == "artist" { self.artist = data.value!.copyWithZone(nil) as? String } else if data.commonKey! == "artwork" { if data.keySpace! == AVMetadataKeySpaceID3 || data.keySpace! == AVMetadataKeySpaceiTunes { self.artwork = UIImage(data: (data.value?.copyWithZone(nil))! as! NSData) } } } } func infoFromItem(item: AVPlayerItem) { self.duration = CMTimeGetSeconds(item.duration) self.timePlayed = CMTimeGetSeconds(item.currentTime()) } }
mit
e9aa84e8ad434d472b2a0013c0c3ca87
27.068966
106
0.587838
4.174359
false
false
false
false
exchangegroup/keychain-swift
Tests/KeychainSwiftTests/ConcurrencyTests.swift
2
6894
// // ConcurrencyTests.swift // KeychainSwift // // Created by Eli Kohen on 08/02/2017. // import XCTest @testable import KeychainSwift class ConcurrencyTests: XCTestCase { var obj: KeychainSwift! override func setUp() { super.setUp() obj = KeychainSwift() obj.clear() obj.lastQueryParameters = nil obj.synchronizable = false } // MARK: - addSynchronizableIfRequired func testConcurrencyDoesntCrash() { let expectation = self.expectation(description: "Wait for write loop") let expectation2 = self.expectation(description: "Wait for write loop") let dataToWrite = "{ asdf ñlk BNALSKDJFÑLAKSJDFÑLKJ ZÑCLXKJ ÑALSKDFJÑLKASJDFÑLKJASDÑFLKJAÑSDLKFJÑLKJ}" obj.set(dataToWrite, forKey: "test-key") var writes = 0 let readQueue = DispatchQueue(label: "ReadQueue", attributes: []) readQueue.async { for _ in 0..<400 { let _: String? = synchronize( { completion in let result: String? = self.obj.get("test-key") DispatchQueue.global(qos: .background).async { DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(5)) { completion(result) } } }, timeoutWith: nil) } } let readQueue2 = DispatchQueue(label: "ReadQueue2", attributes: []) readQueue2.async { for _ in 0..<400 { let _: String? = synchronize( { completion in let result: String? = self.obj.get("test-key") DispatchQueue.global(qos: .background).async { DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(5)) { completion(result) } } }, timeoutWith: nil) } } let readQueue3 = DispatchQueue(label: "ReadQueue3", attributes: []) readQueue3.async { for _ in 0..<400 { let _: String? = synchronize( { completion in let result: String? = self.obj.get("test-key") DispatchQueue.global(qos: .background).async { DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(5)) { completion(result) } } }, timeoutWith: nil) } } let deleteQueue = DispatchQueue(label: "deleteQueue", attributes: []) deleteQueue.async { for _ in 0..<400 { let _: Bool = synchronize( { completion in let result = self.obj.delete("test-key") DispatchQueue.global(qos: .background).async { DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(5)) { completion(result) } } }, timeoutWith: false) } } let deleteQueue2 = DispatchQueue(label: "deleteQueue2", attributes: []) deleteQueue2.async { for _ in 0..<400 { let _: Bool = synchronize( { completion in let result = self.obj.delete("test-key") DispatchQueue.global(qos: .background).async { DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(5)) { completion(result) } } }, timeoutWith: false) } } let clearQueue = DispatchQueue(label: "clearQueue", attributes: []) clearQueue.async { for _ in 0..<400 { let _: Bool = synchronize( { completion in let result = self.obj.clear() DispatchQueue.global(qos: .background).async { DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(5)) { completion(result) } } }, timeoutWith: false) } } let clearQueue2 = DispatchQueue(label: "clearQueue2", attributes: []) clearQueue2.async { for _ in 0..<400 { let _: Bool = synchronize( { completion in let result = self.obj.clear() DispatchQueue.global(qos: .background).async { DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(5)) { completion(result) } } }, timeoutWith: false) } } let writeQueue = DispatchQueue(label: "WriteQueue", attributes: []) writeQueue.async { for _ in 0..<500 { let written: Bool = synchronize({ completion in DispatchQueue.global(qos: .background).async { DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(5)) { let result = self.obj.set(dataToWrite, forKey: "test-key") completion(result) } } }, timeoutWith: false) if written { writes = writes + 1 } } expectation.fulfill() } let writeQueue2 = DispatchQueue(label: "WriteQueue2", attributes: []) writeQueue2.async { for _ in 0..<500 { let written: Bool = synchronize({ completion in DispatchQueue.global(qos: .background).async { DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(5)) { let result = self.obj.set(dataToWrite, forKey: "test-key") completion(result) } } }, timeoutWith: false) if written { writes = writes + 1 } } expectation2.fulfill() } for _ in 0..<1000 { self.obj.set(dataToWrite, forKey: "test-key") let _ = self.obj.get("test-key") } self.waitForExpectations(timeout: 30, handler: nil) XCTAssertEqual(1000, writes) } } // Synchronizes a asynch closure // Ref: https://forums.developer.apple.com/thread/11519 func synchronize<ResultType>(_ asynchClosure: (_ completion: @escaping (ResultType) -> ()) -> Void, timeout: DispatchTime = DispatchTime.distantFuture, timeoutWith: @autoclosure @escaping () -> ResultType) -> ResultType { let sem = DispatchSemaphore(value: 0) var result: ResultType? asynchClosure { (r: ResultType) -> () in result = r sem.signal() } _ = sem.wait(timeout: timeout) if result == nil { result = timeoutWith() } return result! }
mit
f440f20c2ea81f5eb8435b6c6955773d
33.944162
145
0.50523
4.790536
false
true
false
false
andreaperizzato/GCDKit
GCDKitTests/GCDKitTests.swift
2
8804
// // GCDKitTests.swift // GCDKitTests // // Copyright (c) 2014 John Rommel Estropia // // 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 GCDKit import XCTest class GCDKitTests: XCTestCase { @available(iOS 8.0, *) func testGCDBlocks() { var didStartWaiting = false var finishedTasks = 0 let expectation1 = self.expectationWithDescription("dispatch block 1") let expectation2 = self.expectationWithDescription("dispatch block 2") let expectation3 = self.expectationWithDescription("dispatch block 3") GCDBlock.async(.Background) { XCTAssertTrue(finishedTasks == 0) XCTAssertTrue(didStartWaiting) XCTAssertFalse(NSThread.isMainThread()) XCTAssertTrue(GCDQueue.Background.isCurrentExecutionContext()) expectation1.fulfill() finishedTasks++ } .notify(.Default) { XCTAssertTrue(finishedTasks == 1) XCTAssertFalse(NSThread.isMainThread()) XCTAssertTrue(GCDQueue.Default.isCurrentExecutionContext()) expectation2.fulfill() finishedTasks++ } .notify(.Main) { XCTAssertTrue(finishedTasks == 2) XCTAssertTrue(NSThread.isMainThread()) XCTAssertTrue(GCDQueue.Main.isCurrentExecutionContext()) expectation3.fulfill() } didStartWaiting = true self.waitForExpectationsWithTimeout(5.0, handler: nil) } func testGCDQueue() { let mainQueue = GCDQueue.Main XCTAssertNotNil(mainQueue.dispatchQueue()); XCTAssertTrue(mainQueue.dispatchQueue().isEqual(dispatch_get_main_queue())) let allQueues: [GCDQueue] = [.Main, .UserInteractive, .UserInitiated, .Default, .Utility, .Background, .createSerial("serial"), .createConcurrent("serial")] var allQueuesExpectations = [XCTestExpectation]() for queue in allQueues { if queue != .Main { queue.sync { XCTAssertTrue(queue.isCurrentExecutionContext()) for otherQueue in allQueues { if queue != otherQueue { XCTAssertFalse(otherQueue.isCurrentExecutionContext()) } } } } let dispatchExpectation = self.expectationWithDescription("main queue block") allQueuesExpectations.append(dispatchExpectation) queue.async { XCTAssertTrue(queue.isCurrentExecutionContext()) for otherQueue in allQueues { if queue != otherQueue { XCTAssertFalse(otherQueue.isCurrentExecutionContext()) } } dispatchExpectation.fulfill() } } var didStartWaiting = false let dispatchExpectation = self.expectationWithDescription("main queue block") GCDQueue.Background.async { XCTAssertTrue(didStartWaiting) XCTAssertFalse(NSThread.isMainThread()) dispatchExpectation.fulfill() } didStartWaiting = true self.waitForExpectationsWithTimeout(5.0, handler: nil) } func testGCDGroup() { let group = GCDGroup() XCTAssertNotNil(group.dispatchGroup()); let expectation1 = self.expectationWithDescription("dispatch group block 1") let expectation2 = self.expectationWithDescription("dispatch group block 2") group.async(.Main) { XCTAssertTrue(NSThread.isMainThread()) expectation1.fulfill() } .async(.Default) { XCTAssertFalse(NSThread.isMainThread()) expectation2.fulfill() } let expectation3 = self.expectationWithDescription("dispatch group block 3") group.enter() GCDQueue.Utility.after(3.0) { XCTAssertFalse(NSThread.isMainThread()) expectation3.fulfill() group.leave() } let expectation4 = self.expectationWithDescription("dispatch group block 4") group.enter() GCDQueue.Default.async { XCTAssertFalse(NSThread.isMainThread()) expectation4.fulfill() group.leave() } let expectation5 = self.expectationWithDescription("dispatch group block 5") group.notify(.Default) { XCTAssertFalse(NSThread.isMainThread()) expectation5.fulfill() } self.waitForExpectationsWithTimeout(5.0, handler: nil) } func testGCDSemaphore() { let numberOfTasks: UInt = 10 let semaphore = GCDSemaphore(numberOfTasks) XCTAssertNotNil(semaphore.dispatchSemaphore()); var expectations = [XCTestExpectation](); for i in 0 ..< numberOfTasks { expectations.append(self.expectationWithDescription("semaphore block \(i)")) } let queue = GCDQueue.createConcurrent("testGCDSemaphore.queue") queue.apply(numberOfTasks) { (iteration: UInt) -> Void in XCTAssertTrue(queue.isCurrentExecutionContext()) expectations[Int(iteration)].fulfill() semaphore.signal() } semaphore.wait() self.waitForExpectationsWithTimeout(0.0, handler: nil) } func testGCDTimer() { var runningExpectations = [XCTestExpectation]() let numberOfTicksToTest = 10 for i in 0..<numberOfTicksToTest { runningExpectations.append(self.expectationWithDescription("timer tick \(i)")) } let suspendExpectation = self.expectationWithDescription("timer suspended") var previousTimestamp = CFAbsoluteTimeGetCurrent() var iteration = 0 let timer = GCDTimer.createAutoStart(.Default, interval: Double(iteration + 1)) { (timer) -> Void in XCTAssertTrue(GCDQueue.Default.isCurrentExecutionContext()) let currentTimestamp = CFAbsoluteTimeGetCurrent() let elapsed = currentTimestamp - previousTimestamp let expected = Double(iteration + 1) XCTAssertGreaterThanOrEqual(elapsed + Double(0.001), expected, "Timer fired before expected time") XCTAssertTrue(timer.isRunning, "Timer's isRunning property is not true") if Int(iteration) < runningExpectations.count { runningExpectations[Int(iteration)].fulfill() } else { timer.suspend() XCTAssertFalse(timer.isRunning, "Timer's isRunning property is not false") suspendExpectation.fulfill() } iteration++ previousTimestamp = CFAbsoluteTimeGetCurrent() timer.setTimer(Double(iteration + 1)) } XCTAssertTrue(timer.isRunning, "Timer's isRunning property is not true") let numberOfTicks = NSTimeInterval(numberOfTicksToTest) + 1 self.waitForExpectationsWithTimeout((numberOfTicks * (numberOfTicks / 2.0 + 1.0)) + 5.0, handler: nil) } }
mit
f452e31e8b9a2d9233e67ccc8eb31ee3
35.83682
164
0.587347
5.865423
false
true
false
false
ealeksandrov/SomaFM-miniplayer
SomaFM-helper/AppDelegate.swift
1
1288
// // AppDelegate.swift // // Copyright © 2017 Evgeny Aleksandrov. All rights reserved. import Cocoa @NSApplicationMain final class AppDelegate: NSObject, NSApplicationDelegate { func applicationWillFinishLaunching(_ notification: Notification) { // Get helper bundle id guard let helperBundleId = Bundle.main.bundleIdentifier, helperBundleId.hasSuffix("-helper") else { NSApp.terminate(nil); return } // Get main bundle id let mainAppBundleId = helperBundleId.replacingOccurrences(of: "-helper", with: "") // Ensure the app is not already running if !NSRunningApplication.runningApplications(withBundleIdentifier: mainAppBundleId).isEmpty { NSApp.terminate(nil); return } // Get path to main app let helperBundleURL = URL(fileURLWithPath: Bundle.main.bundlePath) let mainAppBundleURL = helperBundleURL .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() let mainAppBundle = Bundle(url: mainAppBundleURL) // Launch main app if let binaryPath = mainAppBundle?.executablePath { NSWorkspace.shared.launchApplication(binaryPath) } NSApp.terminate(nil) } }
mit
e690de0f1800a08cefbf55f54315ebfa
34.75
159
0.698524
5.318182
false
false
false
false
ijoshsmith/json2swift
json2swift/name-translation.swift
1
2988
// // name-translation.swift // json2swift // // Created by Joshua Smith on 10/27/16. // Copyright © 2016 iJoshSmith. All rights reserved. // import Foundation internal extension String { func toSwiftStructName() -> String { let name = capitalizedWithoutInvalidChars.prefixedWithUnderscoreIfNecessary return name.isEmpty ? "DefaultStructName" : name } func toSwiftPropertyName() -> String { let name = capitalizedWithoutInvalidChars.lowercasedFirstCharacter.prefixedWithUnderscoreIfNecessary return name.isEmpty ? "defaultPropertyName" : name } private var capitalizedWithoutInvalidChars: String { let trimmed = trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) let parts = trimmed.components(separatedBy: invalidSwiftNameCharacters) let capitalizedParts = parts.map { $0.uppercasedFirstCharacter } return capitalizedParts.joined() } private var prefixedWithUnderscoreIfNecessary: String { return isSwiftKeyword || startsWithNumber ? "_" + self : self } private var uppercasedFirstCharacter: String { return modifyFirstCharacter(byApplying: { String($0).uppercased() }) } private var lowercasedFirstCharacter: String { return modifyFirstCharacter(byApplying: { String($0).lowercased() }) } private func modifyFirstCharacter(byApplying characterTransform: (Character) -> String) -> String { guard isEmpty == false else { return self } let firstChar = self.first! let modifiedFirstChar = characterTransform(firstChar) let rangeOfFirstRange = Range(uncheckedBounds: (lower: startIndex, upper: index(after: startIndex))) return replacingCharacters(in: rangeOfFirstRange, with: modifiedFirstChar) } private var isSwiftKeyword: Bool { return swiftKeywords.contains(self) } private var startsWithNumber: Bool { guard let digitRange = rangeOfCharacter(from: CharacterSet.decimalDigits) else { return false } return digitRange.lowerBound == startIndex } } private let invalidSwiftNameCharacters = CharacterSet.alphanumerics.inverted private let swiftKeywords: Set<String> = [ "Any", "as", "associatedtype", "break", "case", "catch", "class", "continue", "default", "defer", "deinit", "do", "else", "enum", "extension", "fallthrough", "false", "fileprivate", "for", "func", "guard", "if", "import", "in", "init", "inout", "internal", "is", "let", "nil", "open", "operator", "private", "protocol", "public", "repeat", "rethrows", "return", "Self", "self", "static", "struct", "subscript", "super", "switch", "throw", "throws", "true", "try", "typealias", "var", "where", "while" ]
mit
a4043e4d1662066ee0e2a905201e66cd
24.75
108
0.630733
4.505279
false
false
false
false
TMTBO/TTARefresher
TTARefresher/Classes/Base/TTARefresherHeader.swift
1
5018
// // TTARefresherHeader.swift // Pods // // Created by TobyoTenma on 07/05/2017. // // import UIKit open class TTARefresherHeader: TTARefresherComponent { fileprivate var insetTopDelta: CGFloat = 0 var lastUpdatedTime: Date? { return UserDefaults.standard.object(forKey: TTARefresherUserDefaultKey.lastUpdatedTime) as? Date } override open var state: TTARefresherState { didSet { if state == oldValue { return } if state == .idle { if oldValue != .refreshing { return } UserDefaults.standard.set(Date(), forKey: TTARefresherUserDefaultKey.lastUpdatedTime) UserDefaults.standard.synchronize() UIView.animate(withDuration: TTARefresherAnimationDuration.slow, animations: { [weak self] in guard let `self` = self, let scrollView = self.scrollView else { return } scrollView.contentInset.top += self.insetTopDelta if self.isAutoChangeAlpha { self.alpha = 0} }, completion: { [weak self] (isFinished) in guard let `self` = self else { return } self.pullingPercent = 0 self.endRefreshingCompletionHandler?() }) } else if state == .refreshing { DispatchQueue.main.async { UIView.animate(withDuration: TTARefresherAnimationDuration.fast, animations: { [weak self] in guard let `self` = self else { return } let top = self.scrollViewOriginalInset.top + self.bounds.height self.scrollView?.contentInset.top = top self.scrollView?.setContentOffset(CGPoint(x: 0, y: -top), animated: false) }, completion: { [weak self] (isFinished) in guard let `self` = self else { return } self.executeRefreshingHandler() }) } } } } public init(refreshingHandler: @escaping TTARefresherComponentRefreshingHandler) { super.init(frame: .zero) self.refreshingHandler = refreshingHandler } public init(refreshingTarget aTarget: AnyObject, refreshingAction anAction: Selector) { super.init(frame: .zero) setRefreshingTarget(aTarget: aTarget, anAction: anAction) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - Public Methods extension TTARefresherHeader { public override func endRefreshing(_ completionHandler: TTARefresherComponentEndCompletionHandler? = nil) { DispatchQueue.main.async { [weak self] in guard let `self` = self else { return } self.state = .idle } } } // MARK: - Private Methods extension TTARefresherHeader { func recorrectLastUpdatedTime() {} } // MARK: - Override Methods extension TTARefresherHeader { override open func prepare() { super.prepare() recorrectLastUpdatedTime() bounds.size.height = TTARefresherFrameConst.headerHeight } override open func placeSubviews() { super.placeSubviews() frame.origin.y = -bounds.height } override open func scrollViewContentOffsetDidChange(_ change: [NSKeyValueChangeKey : Any]?) { super.scrollViewContentOffsetDidChange(change) guard let scrollView = scrollView else { return } if state == .refreshing { guard window != nil else { return } var insetTop = -scrollView.contentOffset.y > scrollViewOriginalInset.top ? -scrollView.contentOffset.y : scrollViewOriginalInset.top insetTop = insetTop > bounds.height + scrollViewOriginalInset.top ? bounds.height + scrollViewOriginalInset.top : insetTop scrollView.contentInset.top = insetTop insetTopDelta = scrollViewOriginalInset.top - insetTop return } scrollViewOriginalInset = scrollView.contentInset let offsetY = scrollView.contentOffset.y let happenOffsetY = -scrollViewOriginalInset.top if offsetY > happenOffsetY { return } let normal2PullingOffsetY = happenOffsetY - bounds.height let pullingPercent = (happenOffsetY - offsetY) / bounds.height if scrollView.isDragging { // dragging self.pullingPercent = pullingPercent if state == .idle && offsetY < normal2PullingOffsetY { state = .pulling } else if state == .pulling && offsetY >= normal2PullingOffsetY { state = .idle } } else if state == .pulling { beginRefreshing() } else if pullingPercent < 1 { self.pullingPercent = pullingPercent } } }
mit
2b76b72bf6ddb6d88fd4198213b21a09
35.627737
144
0.597648
5.287671
false
false
false
false
yulingtianxia/Spiral
Spiral/Shape.swift
1
4624
// // Shape.swift // Spiral // // Created by 杨萧玉 on 14-7-12. // Copyright (c) 2014年 杨萧玉. All rights reserved. // import UIKit import SpriteKit enum PathOrientation:Int { case right = 0 case down case left case up } func randomPath() -> PathOrientation{ let pathNum = Int(arc4random_uniform(4)) return PathOrientation(rawValue: pathNum)! } class Shape: SKSpriteNode { var radius:CGFloat = 10 var moveSpeed:CGFloat = 60 var pathOrientation:PathOrientation = randomPath() var lineNum = 0 let speedUpBase:CGFloat = 50 var light = SKLightNode() weak var owner: SpriteComponent? required init(coder: NSCoder) { fatalError("NSCoding not supported") } init(name aName:String,imageName:String) { super.init(texture: SKTexture(imageNamed: imageName),color:SKColor.clear, size: CGSize(width: radius * 2.0, height: radius * 2.0)) // physicsBody = SKPhysicsBody(texture: texture, size: size) physicsBody = SKPhysicsBody(circleOfRadius: radius) physicsBody!.usesPreciseCollisionDetection = true physicsBody!.collisionBitMask = mainSceneCategory physicsBody!.contactTestBitMask = playerCategory|killerCategory|scoreCategory|shieldCategory|reaperCategory moveSpeed += Data.sharedData.speedScale * speedUpBase name = aName zPosition = 100 physicsBody?.angularDamping = 0 physicsBody?.linearDamping = 0 physicsBody?.restitution = 1 physicsBody?.friction = 1 normalTexture = texture?.generatingNormalMap() light.isEnabled = false addChild(light) } func runInOrdinaryMap(_ map:OrdinaryMap) { let distance = calDistanceInOrdinaryMap(map) let duration = distance / moveSpeed let rotate = SKAction.rotate(byAngle: distance/10, duration: Double(duration)) let move = SKAction.move(to: map.points[lineNum+1], duration: Double(duration)) let group = SKAction.group([rotate,move]) self.run(group, completion:{ self.lineNum += 1 if self.lineNum==map.points.count-1 { if self is Player{ Data.sharedData.gameOver = true } else{ self.removeFromParent() } } else { self.runInOrdinaryMap(map) } }) } func calDistanceInOrdinaryMap(_ map:OrdinaryMap)->CGFloat{ if self.lineNum==map.points.count { return 0 } switch lineNum%4{ case 0: return position.y-map.points[lineNum+1].y case 1: return position.x-map.points[lineNum+1].x case 2: return map.points[lineNum+1].y-position.y case 3: return map.points[lineNum+1].x-position.x default: return 0 } } func runInZenMap(_ map:ZenMap){ let distance = calDistanceInZenMap(map) let duration = distance/moveSpeed let rotate = SKAction.rotate(byAngle: distance/10, duration: Double(duration)) let move = SKAction.move(to: map.points[pathOrientation]![lineNum+1], duration: Double(duration)) let group = SKAction.group([rotate,move]) self.run(group, completion: { self.lineNum += 1 if self.lineNum==map.points[self.pathOrientation]!.count-1 { if self is Player{ Data.sharedData.gameOver = true } else{ self.removeFromParent() } } else { self.runInZenMap(map) } }) } func calDistanceInZenMap(_ map:ZenMap)->CGFloat{ if self.lineNum==map.points[pathOrientation]!.count { return 0 } let turnNum:Int switch pathOrientation { case .right: turnNum = lineNum case .down: turnNum = lineNum + 1 case .left: turnNum = lineNum + 2 case .up: turnNum = lineNum + 3 } switch turnNum%4{ case 0: return map.points[pathOrientation]![lineNum+1].x-position.x case 1: return position.y-map.points[pathOrientation]![lineNum+1].y case 2: return position.x-map.points[pathOrientation]![lineNum+1].x case 3: return map.points[pathOrientation]![lineNum+1].y-position.y default: return 0 } } }
apache-2.0
25948408a16eca2a70787177c3555985
30.360544
138
0.577657
4.458414
false
false
false
false
TotemTraining/PracticaliOSAppSecurity
V5/Keymaster/Keymaster/DataManager.swift
1
2527
// // DataManager.swift // Keymaster // // Created by Chris Forant on 4/25/15. // Copyright (c) 2015 Totem. All rights reserved. // import Foundation let documentsDirectory = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).last as! NSURL let entriesPath = documentsDirectory.URLByAppendingPathComponent("Entries", isDirectory: true) // Singleton class DataManager: NSObject { static let sharedManager = DataManager() var entries = [[String: AnyObject]]() override init() { super.init() loadAllEntries() } } // MARK: - Subscript extension DataManager { subscript(#category: String, #ascending: Bool) -> [[String: AnyObject]] { // Filter let filteredEntries = entries.filter({ (entry) -> Bool in return (entry["category"] as! String == category) ? true : false }) // Sort let sortedEntries: [[String: AnyObject]] switch ascending { case true: sortedEntries = filteredEntries.sorted({ (entryA, entryB) -> Bool in if (entryA["desc"] as! String).localizedCaseInsensitiveCompare(entryB["desc"] as! String) == NSComparisonResult.OrderedAscending { return true }else{ return false } }) case false: sortedEntries = filteredEntries.sorted({ (entryA, entryB) -> Bool in if (entryA["desc"] as! String).localizedCaseInsensitiveCompare(entryB["desc"] as! String) == NSComparisonResult.OrderedDescending { return true }else{ return false } }) default: return filteredEntries } return sortedEntries } } // MARK: - Helpers extension DataManager { func loadEntryFromFile(url: NSURL) -> [String: AnyObject]? { return NSDictionary(contentsOfURL: url) as? [String: AnyObject] } func loadAllEntries() { // Reset entries entries = [[String: AnyObject]]() // Load entries from keychain file if let urls = NSFileManager.defaultManager().contentsOfDirectoryAtURL(entriesPath, includingPropertiesForKeys: nil, options: nil, error: nil) as? [NSURL] { for url in urls { if let entry = loadEntryFromFile(url) { entries.append(entry) } } } } }
mit
ed45cb0dd2f538cee94a2701fb6e1c4f
29.457831
163
0.58053
5.084507
false
false
false
false
Ahmed-Ali/RealmObjectEditor
Realm Object Editor/ColorableView.swift
2
3572
// // ColorableView.swift // Realm Object Editor // // Created by Ahmed Ali on 12/26/14. // Copyright (c) 2014 Ahmed Ali. All rights reserved. // import Cocoa @IBDesignable class ColorableView: NSView { @IBInspectable var backgroundColor: NSColor = NSColor.whiteColor(){ didSet{ needsDisplay = true } } @IBInspectable var topSeperatorWidth: CGFloat = 0{ didSet{ needsDisplay = true } } @IBInspectable var topSeperatorColor: NSColor = NSColor.whiteColor(){ didSet{ needsDisplay = true } } @IBInspectable var leftSeperatorWidth: CGFloat = 0{ didSet{ needsDisplay = true } } @IBInspectable var leftSeperatorColor: NSColor = NSColor.whiteColor(){ didSet{ needsDisplay = true } } @IBInspectable var bottomSeperatorWidth: CGFloat = 0{ didSet{ needsDisplay = true } } @IBInspectable var bottomSeperatorColor: NSColor = NSColor.whiteColor(){ didSet{ needsDisplay = true } } @IBInspectable var rightSeperatorWidth: CGFloat = 0{ didSet{ needsDisplay = true } } @IBInspectable var rightSeperatorColor: NSColor = NSColor.whiteColor(){ didSet{ needsDisplay = true } } @IBInspectable var cornerRadius : CGFloat = 0{ didSet{ wantsLayer = true needsDisplay = true } } @IBInspectable var borderWidth : CGFloat = 0{ didSet{ wantsLayer = true needsDisplay = true } } @IBInspectable var borderColor : NSColor = NSColor.clearColor(){ didSet{ wantsLayer = true needsDisplay = true } } override func drawRect(dirtyRect: NSRect) { super.drawRect(dirtyRect) backgroundColor.setFill() NSRectFill(self.bounds) if topSeperatorWidth > 0{ drawTopSep(dirtyRect) } if leftSeperatorWidth > 0{ drawLeftSep(dirtyRect) } if bottomSeperatorWidth > 0{ drawBottomSep(dirtyRect) } if rightSeperatorWidth > 0{ drawRightSep(dirtyRect) } layer?.edgeAntialiasingMask = [.LayerBottomEdge, .LayerTopEdge, .LayerLeftEdge, .LayerRightEdge] layer?.borderColor = borderColor.CGColor layer?.cornerRadius = cornerRadius layer?.borderWidth = borderWidth } func drawTopSep(rect: NSRect) { topSeperatorColor.setFill() let y = rect.origin.y + rect.size.height - topSeperatorWidth NSRectFill(NSMakeRect(rect.origin.x, y, rect.size.width, topSeperatorWidth)) } func drawLeftSep(rect: NSRect) { leftSeperatorColor.setFill() NSRectFill(NSMakeRect(rect.origin.x, rect.origin.y, leftSeperatorWidth, rect.size.height)) } func drawBottomSep(rect: NSRect) { bottomSeperatorColor.setFill() NSRectFill(NSMakeRect(rect.origin.x, rect.origin.y, rect.size.width, bottomSeperatorWidth)) } func drawRightSep(rect: NSRect) { rightSeperatorColor.setFill() let x = rect.origin.x + rect.size.width - rightSeperatorWidth NSRectFill(NSMakeRect(x, rect.origin.y, rightSeperatorWidth, rect.size.height)) } }
mit
4b29252a2e051029197e354d343ae592
22.194805
104
0.571669
4.866485
false
false
false
false
DikeyKing/WeCenterMobile-iOS
WeCenterMobile/Controller/QuestionViewController.swift
1
14550
// // QuestionViewController.swift // WeCenterMobile // // Created by Darren Liu on 15/3/25. // Copyright (c) 2015年 Beijing Information Science and Technology University. All rights reserved. // import DTCoreText import MJRefresh import SVProgressHUD import UIKit class QuestionViewController: UITableViewController, DTLazyImageViewDelegate, QuestionBodyCellLinkButtonDelegate, PublishmentViewControllerDelegate { var question: Question { didSet { let defaultDate = NSDate(timeIntervalSince1970: 0) answers = sorted(question.answers) { ($0.date ?? defaultDate).timeIntervalSince1970 >= ($1.date ?? defaultDate).timeIntervalSince1970 } } } var answers = [Answer]() let answerCellIdentifier = "AnswerCell" let answerCellNibName = "AnswerCell" lazy var questionHeaderCell: QuestionHeaderCell = { [weak self] in let c = NSBundle.mainBundle().loadNibNamed("QuestionHeaderCell", owner: nil, options: nil).first as! QuestionHeaderCell c.userButton.addTarget(self, action: "didPressUserButton:", forControlEvents: .TouchUpInside) return c }() lazy var questionTitleCell: QuestionTitleCell = { [weak self] in return NSBundle.mainBundle().loadNibNamed("QuestionTitleCell", owner: nil, options: nil).first as! QuestionTitleCell }() lazy var questionTagListCell: QuestionTagListCell = { [weak self] in let c = NSBundle.mainBundle().loadNibNamed("QuestionTagListCell", owner: nil, options: nil).first as! QuestionTagListCell c.tagsButton.addTarget(self, action: "didPressTagsButton:", forControlEvents: .TouchUpInside) return c }() lazy var questionBodyCell: QuestionBodyCell = { [weak self] in let c = NSBundle.mainBundle().loadNibNamed("QuestionBodyCell", owner: nil, options: nil).first as! QuestionBodyCell if let self_ = self { c.lazyImageViewDelegate = self_ c.linkButtonDelegate = self_ NSNotificationCenter.defaultCenter().addObserver(self_, selector: "attributedTextContentViewDidFinishLayout:", name: DTAttributedTextContentViewDidFinishLayoutNotification, object: c.attributedTextContextView) } return c }() lazy var questionFooterCell: QuestionFooterCell = { [weak self] in let c = NSBundle.mainBundle().loadNibNamed("QuestionFooterCell", owner: nil, options: nil).first as! QuestionFooterCell c.focusButton.addTarget(self, action: "toggleFocus", forControlEvents: .TouchUpInside) return c }() lazy var answerAdditionCell: AnswerAdditionCell = { [weak self] in let c = NSBundle.mainBundle().loadNibNamed("AnswerAdditionCell", owner: nil, options: nil).first as! AnswerAdditionCell c.answerAdditionButton.addTarget(self, action: "didPressAdditionButton", forControlEvents: .TouchUpInside) return c }() init(question: Question) { self.question = question super.init(nibName: nil, bundle: nil) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func loadView() { super.loadView() let theme = SettingsManager.defaultManager.currentTheme view.backgroundColor = theme.backgroundColorA tableView.indicatorStyle = theme.scrollViewIndicatorStyle tableView.delaysContentTouches = false tableView.msr_wrapperView?.delaysContentTouches = false tableView.msr_setTouchesShouldCancel(true, inContentViewWhichIsKindOfClass: UIButton.self) tableView.separatorStyle = .None tableView.registerNib(UINib(nibName: answerCellNibName, bundle: NSBundle.mainBundle()), forCellReuseIdentifier: answerCellIdentifier) tableView.panGestureRecognizer.requireGestureRecognizerToFail(msr_navigationController!.interactivePopGestureRecognizer) tableView.panGestureRecognizer.requireGestureRecognizerToFail(appDelegate.mainViewController.sidebar.screenEdgePanGestureRecognizer) tableView.wc_addRefreshingHeaderWithTarget(self, action: "refresh") title = "问题详情" // Needs localization navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "Share-Button"), style: .Plain, target: self, action: "didPressShareButton") } override func viewDidLoad() { super.viewDidLoad() tableView.header.beginRefreshing() } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 7 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return [1, 1, 1, 1, 1, 1, answers.count][section] } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { switch indexPath.section { case 0: questionHeaderCell.update(user: question.user, updateImage: true) return questionHeaderCell case 1: questionTitleCell.update(question: question) return questionTitleCell case 2: questionTagListCell.update(question: question) return questionTagListCell case 3: questionBodyCell.update(question: question) return questionBodyCell case 4: questionFooterCell.update(question: question) return questionFooterCell case 5: return answerAdditionCell default: let answerCell = tableView.dequeueReusableCellWithIdentifier(answerCellIdentifier, forIndexPath: indexPath) as! AnswerCell answerCell.userButton.addTarget(self, action: "didPressUserButton:", forControlEvents: .TouchUpInside) answerCell.answerButton.addTarget(self, action: "didPressAnswerButton:", forControlEvents: .TouchUpInside) answerCell.update(answer: answers[indexPath.row], updateImage: true) return answerCell } } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { struct _Static { static var id: dispatch_once_t = 0 static var answerCell: AnswerCell! } dispatch_once(&_Static.id) { [weak self] in if let self_ = self { _Static.answerCell = NSBundle.mainBundle().loadNibNamed(self_.answerCellNibName, owner: nil, options: nil).first as! AnswerCell } } switch indexPath.section { case 0: questionHeaderCell.update(user: question.user, updateImage: false) return questionHeaderCell.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height case 1: questionTitleCell.update(question: question) return questionTitleCell.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height case 2: questionTagListCell.update(question: question) return questionTagListCell.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height case 3: questionBodyCell.update(question: question) let height = questionBodyCell.requiredRowHeightInTableView(tableView) let insets = questionBodyCell.attributedTextContextView.edgeInsets return height > insets.top + insets.bottom ? height : 0 case 4: questionFooterCell.update(question: question) return questionFooterCell.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height case 5: return answerAdditionCell.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height default: _Static.answerCell.update(answer: answers[indexPath.row], updateImage: false) return _Static.answerCell.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height } } func lazyImageView(lazyImageView: DTLazyImageView!, didChangeImageSize size: CGSize) { let predicate = NSPredicate(format: "contentURL == %@", lazyImageView.url) let attachments = questionBodyCell.attributedTextContextView.layoutFrame.textAttachmentsWithPredicate(predicate) as? [DTImageTextAttachment] ?? [] for attachment in attachments { attachment.originalSize = size let v = questionBodyCell.attributedTextContextView let maxWidth = v.bounds.width - v.edgeInsets.left - v.edgeInsets.right if size.width > maxWidth { let scale = maxWidth / size.width attachment.displaySize = CGSize(width: size.width * scale, height: size.height * scale) } } questionBodyCell.attributedTextContextView.layouter = nil questionBodyCell.attributedTextContextView.relayoutText() } func didLongPressLinkButton(linkButton: DTLinkButton) { presentLinkAlertControllerWithURL(linkButton.URL) } func didPressLinkButton(linkButton: DTLinkButton) { presentLinkAlertControllerWithURL(linkButton.URL) } func presentLinkAlertControllerWithURL(URL: NSURL) { let ac = UIAlertController(title: "链接", message: URL.absoluteString, preferredStyle: .ActionSheet) ac.addAction(UIAlertAction(title: "跳转到 Safari", style: .Default) { action in UIApplication.sharedApplication().openURL(URL) }) ac.addAction(UIAlertAction(title: "复制到剪贴板", style: .Default) { [weak self] action in UIPasteboard.generalPasteboard().string = URL.absoluteString SVProgressHUD.showSuccessWithStatus("已复制", maskType: .Gradient) dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(NSEC_PER_SEC / 2)), dispatch_get_main_queue()) { SVProgressHUD.dismiss() } }) ac.addAction(UIAlertAction(title: "取消", style: .Cancel, handler: nil)) presentViewController(ac, animated: true, completion: nil) } func didPressUserButton(sender: UIButton) { if let user = sender.msr_userInfo as? User { msr_navigationController!.pushViewController(UserViewController(user: user), animated: true) } } func didPressAnswerButton(sender: UIButton) { if let answer = sender.msr_userInfo as? Answer { msr_navigationController!.pushViewController(ArticleViewController(dataObject: answer), animated: true) } } func didPressAdditionButton() { let apc = NSBundle.mainBundle().loadNibNamed("PublishmentViewControllerB", owner: nil, options: nil).first as! PublishmentViewController let answer = Answer.temporaryObject() answer.question = Question.temporaryObject() answer.question!.id = question.id apc.delegate = self apc.dataObject = answer apc.headerLabel.text = "发布回答" showDetailViewController(apc, sender: self) } func publishmentViewControllerDidSuccessfullyPublishDataObject(publishmentViewController: PublishmentViewController) { tableView.header.beginRefreshing() } func toggleFocus() { var focusing = question.focusing question.focusing = nil reloadQuestionFooterCell() question.toggleFocus( success: { [weak self] in self?.reloadQuestionFooterCell() return }, failure: { [weak self] error in self?.question.focusing = focusing self?.reloadQuestionFooterCell() }) } func refresh() { Question.fetch( ID: question.id, success: { [weak self] question in if let self_ = self { self_.question = question self_.tableView.reloadData() if let user = question.user { user.fetchProfile( success: { self_.tableView.header.endRefreshing() self_.tableView.reloadData() }, failure: { error in self_.tableView.header.endRefreshing() return }) } else { self_.tableView.header.endRefreshing() } } return }, failure: { [weak self] error in self?.tableView.header.endRefreshing() return }) } func reloadQuestionFooterCell() { tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: 0, inSection: 4)], withRowAnimation: .None) } func didPressShareButton() { let title = question.title! let image = question.user?.avatar ?? defaultUserAvatar let body = question.body!.wc_plainString let url = NetworkManager.defaultManager!.website var items = [title, body, NSURL(string: url)!] if image != nil { items.append(image!) } let vc = UIActivityViewController( activityItems: items, applicationActivities: [SinaWeiboActivity(), WeChatSessionActivity(), WeChatTimelineActivity()]) showDetailViewController(vc, sender: self) } func didPressTagsButton(sender: UIButton) { if let topics = sender.msr_userInfo as? [Topic] { msr_navigationController!.pushViewController(TopicListViewController(topics: topics), animated: true) } } func attributedTextContentViewDidFinishLayout(notification: NSNotification) { tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: 0, inSection: 0)], withRowAnimation: .None) } override func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool { return false } override func preferredStatusBarStyle() -> UIStatusBarStyle { return SettingsManager.defaultManager.currentTheme.statusBarStyle } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } }
gpl-2.0
f787e05a95abfc07a192adaa9e79a981
43.072948
221
0.65269
5.410448
false
false
false
false
Draveness/NightNight
scripts/results/UIView+Mixed.swift
1
1767
// // UIView+Mixed.swift // Pods // // Created by Draveness. // // 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 OWNER 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 Foundation public extension UIView { public var mixedBackgroundColor: MixedColor? { get { return getMixedColor(&Keys.backgroundColor) } set { backgroundColor= newValue?.unfold() setMixedColor(&Keys.backgroundColor, value: newValue) } } public var mixedTintColor: MixedColor? { get { return getMixedColor(&Keys.tintColor) } set { tintColor= newValue?.unfold() setMixedColor(&Keys.tintColor, value: newValue) } } override func updateCurrentColor() { super.updateCurrentColor() if let mixedBackgroundColor = mixedBackgroundColor { backgroundColor = mixedBackgroundColor.unfold() } if let mixedTintColor = mixedTintColor { tintColor = mixedTintColor.unfold() } } }
mit
d4cda2ecde0df6764aca936c9944303f
31.127273
82
0.667233
4.854396
false
false
false
false
JGiola/swift
test/type/explicit_existential_swift6.swift
1
12654
// RUN: %target-typecheck-verify-swift -enable-upcoming-feature ExistentialAny protocol HasSelfRequirements { func foo(_ x: Self) func returnsOwnProtocol() -> any HasSelfRequirements } protocol Bar { init() func bar() -> any Bar } class Bistro{ convenience init(_: Bar){ self.init()} // expected-error{{use of protocol 'Bar' as a type must be written 'any Bar'}}{{25-28=any Bar}} class func returnBar() -> Bar {} // expected-error {{use of protocol 'Bar' as a type must be written 'any Bar'}}{{31-34=any Bar}} } func useBarAsType(_ x: any Bar) {} protocol Pub : Bar { } func refinementErasure(_ p: any Pub) { useBarAsType(p) } typealias Compo = HasSelfRequirements & Bar struct CompoAssocType { typealias Compo = HasSelfRequirements & Bar } func useAsRequirement<T: HasSelfRequirements>(_ x: T) { } func useCompoAsRequirement<T: HasSelfRequirements & Bar>(_ x: T) { } func useCompoAliasAsRequirement<T: Compo>(_ x: T) { } func useNestedCompoAliasAsRequirement<T: CompoAssocType.Compo>(_ x: T) { } func useAsWhereRequirement<T>(_ x: T) where T: HasSelfRequirements {} func useCompoAsWhereRequirement<T>(_ x: T) where T: HasSelfRequirements & Bar {} func useCompoAliasAsWhereRequirement<T>(_ x: T) where T: Compo {} func useNestedCompoAliasAsWhereRequirement<T>(_ x: T) where T: CompoAssocType.Compo {} func useAsType(_: any HasSelfRequirements, _: any HasSelfRequirements & Bar, _: any Compo, _: any CompoAssocType.Compo) { } struct TypeRequirement<T: HasSelfRequirements> {} struct CompoTypeRequirement<T: HasSelfRequirements & Bar> {} struct CompoAliasTypeRequirement<T: Compo> {} struct NestedCompoAliasTypeRequirement<T: CompoAssocType.Compo> {} struct CompoTypeWhereRequirement<T> where T: HasSelfRequirements & Bar {} struct CompoAliasTypeWhereRequirement<T> where T: Compo {} struct NestedCompoAliasTypeWhereRequirement<T> where T: CompoAssocType.Compo {} struct Struct1<T> { } typealias T1 = Pub & Bar typealias T2 = any Pub & Bar protocol HasAssoc { associatedtype Assoc func foo() } do { enum MyError: Error { case bad(Any) } func checkIt(_ js: Any) throws { switch js { case let dbl as any HasAssoc: throw MyError.bad(dbl) default: fatalError("wrong") } } } func testHasAssoc(_ x: Any, _: any HasAssoc) { if let p = x as? any HasAssoc { p.foo() } struct ConformingType : HasAssoc { typealias Assoc = Int func foo() {} func method() -> any HasAssoc {} func existentialArray() -> [any HasAssoc] {} func existentialcSequence() -> any Sequence<HasAssoc> {} } } var b: any HasAssoc protocol P {} typealias MoreHasAssoc = HasAssoc & P func testHasMoreAssoc(_ x: Any) { if let p = x as? any MoreHasAssoc { p.foo() } } typealias X = Struct1<any Pub & Bar> _ = Struct1<any Pub & Bar>.self typealias AliasWhere<T> = T where T: HasAssoc, T.Assoc == any HasAssoc struct StructWhere<T> where T: HasAssoc, T.Assoc == any HasAssoc {} protocol ProtocolWhere where T == any HasAssoc { associatedtype T associatedtype U: HasAssoc where U.Assoc == any HasAssoc } extension HasAssoc where Assoc == any HasAssoc {} func FunctionWhere<T>(_: T) where T : HasAssoc, T.Assoc == any HasAssoc {} struct SubscriptWhere { subscript<T>(_: T) -> Int where T : HasAssoc, T.Assoc == any HasAssoc { get {} set {} } } struct OuterGeneric<T> { func contextuallyGenericMethod() where T == any HasAssoc {} } protocol Collection<T> { associatedtype T } func acceptAny(_: Collection<Int>) {} // expected-error@-1 {{use of protocol 'Collection' as a type must be written 'any Collection'}} func returnsAny() -> Collection<Int> {} // expected-error@-1 {{use of protocol 'Collection' as a type must be written 'any Collection'}} func testInvalidAny() { struct S: HasAssoc { typealias Assoc = Int func foo() {} } let _: any S = S() // expected-error{{'any' has no effect on concrete type 'S'}} func generic<T: HasAssoc>(t: T) { let _: any T = t // expected-error{{'any' has no effect on type parameter 'T'}} let _: any T.Assoc // expected-error {{'any' has no effect on type parameter 'T.Assoc'}} } let _: any ((S) -> Void) = generic // expected-error{{'any' has no effect on concrete type '(S) -> Void'}} } func anyAny() { let _: any Any let _: any AnyObject } protocol P1 {} protocol P2 {} protocol P3 {} do { // Test that we don't accidentally misparse an 'any' type as a 'some' type // and vice versa. let _: P1 & any P2 // expected-error {{'any' should appear at the beginning of a composition}} {{15-19=}} {{10-10=any }} let _: any P1 & any P2 // expected-error {{'any' should appear at the beginning of a composition}} {{19-23=}} let _: any P1 & P2 & any P3 // expected-error {{'any' should appear at the beginning of a composition}} {{24-28=}} let _: any P1 & some P2 // expected-error {{'some' should appear at the beginning of a composition}} {{19-24=}} let _: some P1 & any P2 // expected-error@-1 {{'some' type can only be declared on a single property declaration}} // expected-error@-2 {{'any' should appear at the beginning of a composition}} {{20-24=}} } struct ConcreteComposition: P1, P2 {} func testMetatypes() { let _: any P1.Type = ConcreteComposition.self let _: any (P1 & P2).Type = ConcreteComposition.self } func generic<T: any P1>(_ t: T) {} // expected-error {{type 'T' constrained to non-protocol, non-class type 'any P1'}} protocol RawRepresentable { associatedtype RawValue var rawValue: RawValue { get } } enum E1: RawRepresentable { typealias RawValue = P1 var rawValue: P1 { // expected-error {{use of protocol 'P1' as a type must be written 'any P1'}}{{17-19=any P1}} return ConcreteComposition() } } enum E2: RawRepresentable { typealias RawValue = any P1 var rawValue: any P1 { return ConcreteComposition() } } public protocol MyError {} extension MyError { static func ~=(lhs: any Error, rhs: Self) -> Bool { return true } } struct Wrapper { typealias E = Error } func typealiasMemberReferences(metatype: Wrapper.Type) { let _: Wrapper.E.Protocol = metatype.E.self let _: (any Wrapper.E).Type = metatype.E.self } func testAnyTypeExpr() { let _: (any P).Type = (any P).self func test(_: (any P).Type) {} test((any P).self) // expected-error@+2 {{expected member name or constructor call after type name}} // expected-note@+1 {{use '.self' to reference the type object}} let invalid = any P test(invalid) // Make sure 'any' followed by an identifier // on the next line isn't parsed as a type. func doSomething() {} let any = 10 let _ = any doSomething() } func hasInvalidExistential(_: any DoesNotExistIHope) {} // expected-error@-1 {{cannot find type 'DoesNotExistIHope' in scope}} protocol Input { associatedtype A } protocol InputB { associatedtype B } protocol Output { associatedtype A } // expected-error@+2{{use of protocol 'Input' as a type must be written 'any Input'}}{{30-35=any Input}} // expected-error@+1{{use of protocol 'Output' as a type must be written 'any Output'}}{{40-46=any Output}} typealias InvalidFunction = (Input) -> Output func testInvalidFunctionAlias(fn: InvalidFunction) {} typealias ExistentialFunction = (any Input) -> any Output func testFunctionAlias(fn: ExistentialFunction) {} typealias Constraint = Input typealias ConstraintB = Input & InputB //expected-error@+2{{use of 'Constraint' (aka 'Input') as a type must be written 'any Constraint' (aka 'any Input')}} //expected-error@+1 2{{use of 'ConstraintB' (aka 'Input & InputB') as a type must be written 'any ConstraintB' (aka 'any Input & InputB')}} func testConstraintAlias(x: Constraint, y: ConstraintB) {} typealias Existential = any Input func testExistentialAlias(x: Existential, y: any Constraint) {} // Reject explicit existential types in inheritance clauses protocol Empty {} struct S : any Empty {} // expected-error {{inheritance from non-protocol type 'any Empty'}} class C : any Empty {} // expected-error {{inheritance from non-protocol, non-class type 'any Empty'}} // FIXME: Diagnostics are not great in the enum case because we confuse this with a raw type enum E : any Empty { // expected-error {{raw type 'any Empty' is not expressible by a string, integer, or floating-point literal}} // expected-error@-1 {{'E' declares raw type 'any Empty', but does not conform to RawRepresentable and conformance could not be synthesized}} // expected-error@-2 {{RawRepresentable conformance cannot be synthesized because raw type 'any Empty' is not Equatable}} case hack } enum EE : Equatable, any Empty { // expected-error {{raw type 'any Empty' is not expressible by a string, integer, or floating-point literal}} // expected-error@-1 {{'EE' declares raw type 'any Empty', but does not conform to RawRepresentable and conformance could not be synthesized}} // expected-error@-2 {{RawRepresentable conformance cannot be synthesized because raw type 'any Empty' is not Equatable}} // expected-error@-3 {{raw type 'any Empty' must appear first in the enum inheritance clause}} case hack } func testAnyFixIt() { struct ConformingType : HasAssoc { typealias Assoc = Int func foo() {} func method() -> any HasAssoc {} } // expected-error@+1 {{use of protocol 'HasAssoc' as a type must be written 'any HasAssoc'}}{{10-18=any HasAssoc}} let _: HasAssoc = ConformingType() // expected-error@+1 {{use of protocol 'HasAssoc' as a type must be written 'any HasAssoc'}}{{19-27=any HasAssoc}} let _: Optional<HasAssoc> = nil // expected-error@+1 {{use of protocol 'HasAssoc' as a type must be written 'any HasAssoc'}}{{10-23=any HasAssoc.Type}} let _: HasAssoc.Type = ConformingType.self // expected-error@+1 {{use of protocol 'HasAssoc' as a type must be written 'any HasAssoc'}}{{10-25=any (HasAssoc).Type}} let _: (HasAssoc).Type = ConformingType.self // expected-error@+1 {{use of protocol 'HasAssoc' as a type must be written 'any HasAssoc'}}{{10-27=any ((HasAssoc)).Type}} let _: ((HasAssoc)).Type = ConformingType.self // expected-error@+2 {{use of protocol 'HasAssoc' as a type must be written 'any HasAssoc'}}{{10-18=(any HasAssoc)}} // expected-error@+1 {{use of protocol 'HasAssoc' as a type must be written 'any HasAssoc'}}{{30-38=(any HasAssoc)}} let _: HasAssoc.Protocol = HasAssoc.self // expected-error@+1 {{use of protocol 'HasAssoc' as a type must be written 'any HasAssoc'}}{{11-19=any HasAssoc}} let _: (HasAssoc).Protocol = (any HasAssoc).self // expected-error@+1 {{use of protocol 'HasAssoc' as a type must be written 'any HasAssoc'}}{{10-18=(any HasAssoc)}} let _: HasAssoc? = ConformingType() // expected-error@+1 {{use of protocol 'HasAssoc' as a type must be written 'any HasAssoc'}}{{10-23=(any HasAssoc.Type)}} let _: HasAssoc.Type? = ConformingType.self // expected-error@+1 {{use of protocol 'HasAssoc' as a type must be written 'any HasAssoc'}}{{10-18=(any HasAssoc)}} let _: HasAssoc.Protocol? = (any HasAssoc).self // expected-error@+1 {{optional 'any' type must be written '(any HasAssoc)?'}}{{10-23=(any HasAssoc)?}} let _: any HasAssoc? = nil // expected-error@+1 {{optional 'any' type must be written '(any HasAssoc.Type)?'}}{{10-28=(any HasAssoc.Type)?}} let _: any HasAssoc.Type? = nil } func testNestedMetatype() { let _: (any P.Type).Type = (any P.Type).self let _: (any (P.Type)).Type = (any P.Type).self let _: ((any (P.Type))).Type = (any P.Type).self } func testEnumAssociatedValue() { enum E { case c1((any HasAssoc) -> Void) // expected-error@+1 {{use of protocol 'HasAssoc' as a type must be written 'any HasAssoc'}} case c2((HasAssoc) -> Void) // expected-error@+1 {{use of protocol 'P' as a type must be written 'any P'}} case c3((P) -> Void) } } // https://github.com/apple/swift/issues/58920 typealias Iterator = any IteratorProtocol var example: any Iterator = 5 // expected-error{{redundant 'any' has no effect on existential type 'Iterator' (aka 'any IteratorProtocol')}} {{14-18=}} // expected-error@-1{{value of type 'Int' does not conform to specified type 'IteratorProtocol'}} var example1: any (any IteratorProtocol) = 5 // expected-error{{redundant 'any' has no effect on existential type 'any IteratorProtocol'}} {{15-19=}} // expected-error@-1{{value of type 'Int' does not conform to specified type 'IteratorProtocol'}} protocol PP {} struct A : PP {} let _: any PP = A() // Ok let _: any (any PP) = A() // expected-error{{redundant 'any' has no effect on existential type 'any PP'}} {{8-12=}}
apache-2.0
ba8558eabfcb0fc62394336e146b7ded
33.107817
152
0.683736
3.776186
false
false
false
false
metova/MetovaTestKit
MetovaTestKitTests/TestingUtilities/BasicTestFailureExpectation.swift
1
2783
// // BasicTestFailureExpectation.swift // MetovaTestKit // // Created by Nick Griffith on 2018-12-27. // Copyright © 2018 Metova. All rights reserved. // // MIT License // // 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. // struct BasicTestFailureExpectation: TestFailureExpectation { let description: String? let filePath: String? let lineNumber: UInt? init(description: String? = nil, filePath: String? = nil, lineNumber: UInt? = nil) { self.description = description self.filePath = filePath self.lineNumber = lineNumber } func verifyDescription(_ description: String) -> TestVerificationResult { guard let expectedDescription = self.description else { return .expected } guard description == expectedDescription else { return .mismatch("Description mismatch - Expected: `\(expectedDescription)` Actual: `\(description)`") } return .expected } func verifyFilePath(_ filePath: String) -> TestVerificationResult { guard let expectedFilePath = self.filePath else { return .expected } guard filePath == expectedFilePath else { return .mismatch("File Path mismatch - Expected: `\(expectedFilePath)` Actual: `\(filePath)`") } return .expected } func verifyLineNumber(_ lineNumber: Int) -> TestVerificationResult { guard let expectedLineNumber = self.lineNumber else { return .expected } guard lineNumber == expectedLineNumber else { return .mismatch("Line Number mismatch - Expected: `\(expectedLineNumber)` Actual: `\(lineNumber)`") } return .expected } }
mit
d2f281d60fd774922b3e1a3c2da40d94
38.183099
114
0.681524
4.923894
false
true
false
false
watson-developer-cloud/ios-sdk
Sources/DiscoveryV2/Models/DocumentClassifier.swift
1
3171
/** * (C) Copyright IBM Corp. 2022. * * 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 /** Information about a document classifier. */ public struct DocumentClassifier: Codable, Equatable { /** A unique identifier of the document classifier. */ public var classifierID: String? /** A human-readable name of the document classifier. */ public var name: String /** A description of the document classifier. */ public var description: String? /** The date that the document classifier was created. */ public var created: Date? /** The language of the training data that is associated with the document classifier. Language is specified by using the ISO 639-1 language code, such as `en` for English or `ja` for Japanese. */ public var language: String? /** An array of enrichments to apply to the training data that is used by the document classifier. */ public var enrichments: [DocumentClassifierEnrichment]? /** An array of fields that are used to train the document classifier. The same set of fields must exist in the training data, the test data, and the documents where the resulting document classifier enrichment is applied at run time. */ public var recognizedFields: [String]? /** The name of the field from the training data that contains the classification labels. */ public var answerField: String? /** Name of the CSV file with training data that is used to train the document classifier. */ public var trainingDataFile: String? /** Name of the CSV file with data that is used to test the document classifier. If no test data is provided, a subset of the training data is used for testing purposes. */ public var testDataFile: String? /** An object with details for creating federated document classifier models. */ public var federatedClassification: ClassifierFederatedModel? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case classifierID = "classifier_id" case name = "name" case description = "description" case created = "created" case language = "language" case enrichments = "enrichments" case recognizedFields = "recognized_fields" case answerField = "answer_field" case trainingDataFile = "training_data_file" case testDataFile = "test_data_file" case federatedClassification = "federated_classification" } }
apache-2.0
f394e51196a1121430bcf0334b0692cf
31.357143
119
0.68685
4.697778
false
true
false
false
mukeshthawani/UXMPDFKit
Pod/Classes/Model/PDFAction.swift
1
8200
// // PDFAction.swift // Pods // // Created by Chris Anderson on 9/12/16. // // import Foundation open class PDFAction { open static func fromPDFDictionary(_ sourceDictionary: CGPDFDictionaryRef, documentReference: CGPDFDocument) -> PDFAction? { var action: PDFAction? var destinationName: CGPDFStringRef? = nil var destinationString: UnsafePointer<Int8>? = nil var actionDictionary: CGPDFDictionaryRef? = nil var destinationArray: CGPDFArrayRef? = nil if CGPDFDictionaryGetDictionary(sourceDictionary, "A", &actionDictionary) { var actionType: UnsafePointer<Int8>? = nil if CGPDFDictionaryGetName(actionDictionary!, "S", &actionType) { /// Handle GoTo action types if strcmp(actionType, "GoTo") == 0 { if !CGPDFDictionaryGetArray(actionDictionary!, "D", &destinationArray) { CGPDFDictionaryGetString(actionDictionary!, "D", &destinationName) } } else { /// Handle other link action type possibility /// URI action type if strcmp(actionType, "URI") == 0 { var uriString: CGPDFStringRef? = nil if CGPDFDictionaryGetString(actionDictionary!, "URI", &uriString) { let uri = UnsafeRawPointer(CGPDFStringGetBytePtr(uriString!)!).assumingMemoryBound(to: Int8.self) if let target = String(validatingUTF8: uri) { action = PDFActionURL(stringUrl: target) } } } } } } else { /// Handle other link target possibilities if !CGPDFDictionaryGetArray(sourceDictionary, "Dest", &destinationArray) { if !CGPDFDictionaryGetString(sourceDictionary, "Dest", &destinationName) { CGPDFDictionaryGetName(sourceDictionary, "Dest", &destinationString) } } } /// Handle a destination name if destinationName != nil { let catalogDictionary: CGPDFDictionaryRef = documentReference.catalog! var namesDictionary: CGPDFDictionaryRef? = nil if CGPDFDictionaryGetDictionary(catalogDictionary, "Names", &namesDictionary) { var destsDictionary: CGPDFDictionaryRef? = nil if CGPDFDictionaryGetDictionary(namesDictionary!, "Dests", &destsDictionary) { let localDestinationName = UnsafeRawPointer(CGPDFStringGetBytePtr(destinationName!)!).assumingMemoryBound(to: Int8.self) destinationArray = self.destinationWithName(localDestinationName, node: destsDictionary!) } } } /// Handle a destination string if destinationString != nil { let catalogDictionary: CGPDFDictionaryRef = documentReference.catalog! var destsDictionary: CGPDFDictionaryRef? = nil if CGPDFDictionaryGetDictionary(catalogDictionary, "Dests", &destsDictionary) { var targetDictionary: CGPDFDictionaryRef? = nil if CGPDFDictionaryGetDictionary(destsDictionary!, destinationString!, &targetDictionary) { CGPDFDictionaryGetArray(targetDictionary!, "D", &destinationArray) } } } /// Handle a destination array if (destinationArray != nil) { var targetPageNumber = 0 var pageDictionaryFromDestArray: CGPDFDictionaryRef? = nil if CGPDFArrayGetDictionary(destinationArray!, 0, &pageDictionaryFromDestArray) { let pageCount = documentReference.numberOfPages for pageNumber in 1..<pageCount { let pageRef: CGPDFPage = documentReference.page(at: pageNumber)! let pageDictionaryFromPage: CGPDFDictionaryRef = pageRef.dictionary! if pageDictionaryFromPage == pageDictionaryFromDestArray { targetPageNumber = pageNumber break } } } else { var pageNumber: CGPDFInteger = 0 if CGPDFArrayGetInteger(destinationArray!, 0, &pageNumber) { targetPageNumber = (pageNumber + 1) } } /// We have a target page number, make GoTo link if targetPageNumber > 0 { action = PDFActionGoTo(pageIndex: targetPageNumber) } } return action } fileprivate static func destinationWithName(_ destinationName: UnsafePointer<Int8>, node: CGPDFDictionaryRef) -> CGPDFArrayRef? { var destinationArray: CGPDFArrayRef? = nil var limitsArray: CGPDFArrayRef? = nil if CGPDFDictionaryGetArray(node, "Limits", &limitsArray) { var lowerLimit: CGPDFStringRef? = nil var upperLimit: CGPDFStringRef? = nil if CGPDFArrayGetString(limitsArray!, 0, &lowerLimit) && CGPDFArrayGetString(limitsArray!, 1, &upperLimit) { let llu = CGPDFStringGetBytePtr(lowerLimit!)! let ulu = CGPDFStringGetBytePtr(upperLimit!)! let ll:UnsafePointer<Int8> = UnsafeRawPointer(llu).assumingMemoryBound(to: Int8.self) let ul:UnsafePointer<Int8> = UnsafeRawPointer(ulu).assumingMemoryBound(to: Int8.self) if (strcmp(destinationName, ll) < 0) || (strcmp(destinationName, ul) > 0) { return nil } } } var namesArray: CGPDFArrayRef? = nil if CGPDFDictionaryGetArray(node, "Names", &namesArray) { let namesCount = CGPDFArrayGetCount(namesArray!) for i in stride(from: 0, to: namesCount, by: 2) { var destName: CGPDFStringRef? = nil if CGPDFArrayGetString(namesArray!, i, &destName) { let dnu = CGPDFStringGetBytePtr(destName!)! let dn: UnsafePointer<Int8> = UnsafeRawPointer(dnu).assumingMemoryBound(to: Int8.self) if strcmp(dn, destinationName) == 0 { if !CGPDFArrayGetArray(namesArray!, (i + 1), &destinationArray) { var destinationDictionary: CGPDFDictionaryRef? = nil if CGPDFArrayGetDictionary(namesArray!, (i + 1), &destinationDictionary) { CGPDFDictionaryGetArray(destinationDictionary!, "D", &destinationArray) } } return destinationArray! } } } } var kidsArray: CGPDFArrayRef? = nil if CGPDFDictionaryGetArray(node, "Kids", &kidsArray) { let kidsCount = CGPDFArrayGetCount(kidsArray!) for i in 0..<kidsCount { var kidNode: CGPDFDictionaryRef? = nil if CGPDFArrayGetDictionary(kidsArray!, i, &kidNode) { destinationArray = self.destinationWithName(destinationName, node: kidNode!) if destinationArray != nil { return destinationArray! } } } } return nil } }
mit
d430dd5e0b801e5083c3a2add2f493e3
40.624365
140
0.519146
5.593452
false
false
false
false
XYXiaoYuan/Meilishuo
Meilishuo/Classes/Detail/Controller/DetailVC.swift
1
5406
// // DetailVC.swift // Meilishuo // // Created by 袁小荣 on 2017/5/10. // Copyright © 2017年 袁小荣. All rights reserved. // import UIKit fileprivate let cellID = "detail" class DetailVC: UICollectionViewController { // MARK: - 对外属性 // 1.从首页传递过来的模型数据 var dtDataSource = [ProductModel]() { didSet { collectionView?.reloadData() } } // 2.主界面的collectionView var homeCollectionView: UICollectionView! // 3.主界面传递过来的 thumb_url 下载好的对应的图片 lazy var currentImage = UIImage() // 功能: 用于在DetailVC界面触发更新Home界面刷新操作,然后在Home界面刷新完毕后更新DetailVC界面的数据源,从而触发该界面刷新数据 // 参数: 参数是一个子闭包,该闭包保存"在闭包内部的代码执行完毕(即在Home界面刷新完毕后),更新DetailVC界面的数据源"的操作代码 (DetailClosureType) // 保存刷新Home界面更多数据操作的大闭包 // DetailClosureType类型 是 "([ProductModel]) -> Void" 的别名 fileprivate var loadHomeDataClosure: ((@escaping DetailClosureType) -> Void)? // 自定义构造函数,内部用PhotoBrowserLayout进行布局 init(dtDataSource: [ProductModel], currentIndexPath: IndexPath, homeCollectionView: UICollectionView, currentImage: UIImage, loadHomeDataClosure: @escaping (@escaping DetailClosureType) -> Void) { super.init(collectionViewLayout: DetailFlowLayout()) // 1.更新数据源,内部会同步刷新表格 self.dtDataSource = dtDataSource // 2.跳转到指定的位置 collectionView?.scrollToItem(at: currentIndexPath, at: .left, animated: false) // 3.保存刷新Home界面更多数据操作的大闭包 self.loadHomeDataClosure = loadHomeDataClosure // 4.记录主界面的CollectionView self.homeCollectionView = homeCollectionView // 5.主界面传递过来的 thumb_url 下载好的对应的图片 self.currentImage = currentImage } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() // 1.注册cell collectionView?.register(DetailCell.self, forCellWithReuseIdentifier: cellID) // 2.设置UI setupUI() } } // MARK: - 设置UI extension DetailVC { fileprivate func setupUI() { createButton(title: "退出", isLeft: true, action: #selector(exitHandle)) createButton(title: "保存", isLeft: false, action: #selector(saveHandle)) } private func createButton(title: String, isLeft: Bool, action: Selector) { let width: CGFloat = 80 let height: CGFloat = 40 let margin: CGFloat = 20 let x: CGFloat = isLeft ? margin : UIScreen.main.bounds.width - margin - width let y: CGFloat = UIScreen.main.bounds.height - margin - height let button = UIButton() button.frame = CGRect(x: x, y: y, width: width, height: height) button.setTitle(title, for: .normal) button.backgroundColor = UIColor.blue view.addSubview(button) button.addTarget(self, action: action, for: .touchUpInside) } @objc private func exitHandle() { dismiss(animated: true) } @objc private func saveHandle() { // 1.获取当前的cell guard let cell = collectionView?.visibleCells.first as? DetailCell else { return } // 2.获取当前cell中的图片 let image = cell.currentImage // 3.将图片保存到相册中 UIImageWriteToSavedPhotosAlbum(image, self, #selector(saveSucceed), nil) } @objc private func saveSucceed(image: UIImage, error: Error?, contextInfo: Any?) { print("图片保存成功") } } // MARK: - UICollectionView数据源 extension DetailVC { // 返回每组有多少个item override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return dtDataSource.count } // 负责创建cell override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath) as! DetailCell return cell } } // MARK: - UICollectionView代理 extension DetailVC { // 即将显示某一个cell的时候会调用这个时候 // 负责给cell赋值的 override func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { print("详情\(indexPath.item)🌲") // 设置数据源 let pCell = cell as! DetailCell guard let url = URL(string: dtDataSource[indexPath.item].hd_thumb_url) else { return } pCell.imageView .sd_setImage(with: url, placeholderImage: self.currentImage) // 当滑动到最后一个item的时候刷新调用首页的加载更多数据的接口,并传值过来 if (indexPath.item == dtDataSource.count - 1) { loadHomeDataClosure?({ [weak self] (dataSource: [ProductModel]) in self?.dtDataSource = dataSource }) } } }
mit
b81da5c59d9ff4c5ce31072df3b408c6
28.721519
200
0.658433
4.14841
false
false
false
false
onekiloparsec/KPCTabsControl
KPCTabsControl/SafariStyle.swift
1
1022
// // SafariStyle.swift // KPCTabsControl // // Created by Cédric Foellmi on 27/08/16. // Licensed under the MIT License (see LICENSE file) // import AppKit /** * The Safari style. Use mostly the default implementation of Style. */ public struct SafariStyle: ThemedStyle { public let theme: Theme public let tabButtonWidth: TabWidth public let tabsControlRecommendedHeight: CGFloat = 24.0 public init(theme: Theme = SafariTheme(), tabButtonWidth: TabWidth = .full) { self.theme = theme self.tabButtonWidth = tabButtonWidth } // There is no icons in Safari tabs. Here we force the absence of icon, even if some are provided. public func iconFrames(tabRect rect: NSRect) -> IconFrames { return (NSZeroRect, NSZeroRect) } public func tabButtonBorderMask(_ position: TabPosition) -> BorderMask? { return [.bottom, .top, .right] } public func tabsControlBorderMask() -> BorderMask? { return BorderMask.all() } }
mit
f1b85935fbbb8a22331197f971b9cfd4
26.594595
102
0.670911
4.167347
false
false
false
false
breadwallet/breadwallet-core
Swift/BRCryptoDemo/CoreDemoListener.swift
1
7056
// // CoreXDemoBitcoinClient.swift // CoreXDemo // // Created by Ed Gamble on 11/8/18. // Copyright © 2018-2019 Breadwallet AG. All rights reserved. // // See the LICENSE file at the project root for license information. // See the CONTRIBUTORS file at the project root for a list of contributors. // import UIKit import Foundation import BRCrypto class CoreDemoListener: SystemListener { static let eventQueue: DispatchQueue = DispatchQueue.global() private var managerListeners: [WalletManagerListener] = [] private var walletListeners: [WalletListener] = [] private var transferListeners: [TransferListener] = [] private let networkCurrencyCodesToMode: [String:WalletManagerMode] private let registerCurrencyCodes: [String] internal var isMainnet: Bool public init (networkCurrencyCodesToMode: [String:WalletManagerMode], registerCurrencyCodes: [String], isMainnet: Bool) { self.networkCurrencyCodesToMode = networkCurrencyCodesToMode self.registerCurrencyCodes = registerCurrencyCodes; self.isMainnet = isMainnet } func add(managerListener: WalletManagerListener) { CoreDemoListener.eventQueue.async { if !self.managerListeners.contains (where: { $0 === managerListener }) { self.managerListeners.append (managerListener) } } } func remove(managerListener: WalletManagerListener) { CoreDemoListener.eventQueue.async { if let i = self.managerListeners.firstIndex (where: { $0 === managerListener }) { self.managerListeners.remove (at: i) } } } func add(walletListener: WalletListener) { CoreDemoListener.eventQueue.async { if !self.walletListeners.contains (where: { $0 === walletListener }) { self.walletListeners.append (walletListener) } } } func remove(walletListener: WalletListener) { CoreDemoListener.eventQueue.async { if let i = self.walletListeners.firstIndex (where: { $0 === walletListener }) { self.walletListeners.remove (at: i) } } } func add(transferListener: TransferListener) { CoreDemoListener.eventQueue.async { if !self.transferListeners.contains (where: { $0 === transferListener }) { self.transferListeners.append (transferListener) } } } func remove(transferListener: TransferListener) { CoreDemoListener.eventQueue.async { if let i = self.transferListeners.firstIndex (where: { $0 === transferListener }) { self.transferListeners.remove (at: i) } } } func handleSystemEvent(system: System, event: SystemEvent) { print ("APP: System: \(event)") switch event { case .created: break case .networkAdded(let network): // A network was created; create the corresponding wallet manager. Note: an actual // App might not be interested in having a wallet manager for every network - // specifically, test networks are announced and having a wallet manager for a // testnet won't happen in a deployed App. if isMainnet == network.isMainnet, network.currencies.contains(where: { nil != networkCurrencyCodesToMode[$0.code] }), let currencyMode = self.networkCurrencyCodesToMode [network.currency.code] { // Get a valid mode, ideally from `currencyMode` let mode = network.supportsMode (currencyMode) ? currencyMode : network.defaultMode let scheme = network.defaultAddressScheme let currencies = network.currencies .filter { (c) in registerCurrencyCodes.contains { c.code == $0 } } let success = system.createWalletManager (network: network, mode: mode, addressScheme: scheme, currencies: currencies) if !success { system.wipe (network: network) let successRetry = system.createWalletManager (network: network, mode: mode, addressScheme: scheme, currencies: currencies) if !successRetry { UIApplication.doError(network: network) } } } case .managerAdded (let manager): //TODO: Don't connect here. connect on touch... DispatchQueue.main.async { manager.connect (using: UIApplication.peer (network: manager.network)) } case .discoveredNetworks (let networks): let allCurrencies = networks.flatMap { $0.currencies } print ("APP: System: Currencies (Added): ") allCurrencies.forEach { print ("APP: System: \($0.code)") } } } func handleManagerEvent(system: System, manager: WalletManager, event: WalletManagerEvent) { CoreDemoListener.eventQueue.async { print ("APP: Manager (\(manager.name)): \(event)") self.managerListeners.forEach { $0.handleManagerEvent(system: system, manager: manager, event: event) } } } func handleWalletEvent(system: System, manager: WalletManager, wallet: Wallet, event: WalletEvent) { CoreDemoListener.eventQueue.async { print ("APP: Wallet (\(manager.name):\(wallet.name)): \(event)") self.walletListeners.forEach { $0.handleWalletEvent (system: system, manager: manager, wallet: wallet, event: event) } } } func handleTransferEvent(system: System, manager: WalletManager, wallet: Wallet, transfer: Transfer, event: TransferEvent) { CoreDemoListener.eventQueue.async { print ("APP: Transfer (\(manager.name):\(wallet.name)): \(event)") self.transferListeners.forEach { $0.handleTransferEvent (system: system, manager: manager, wallet: wallet, transfer: transfer, event: event) } } } func handleNetworkEvent(system: System, network: Network, event: NetworkEvent) { print ("APP: Network: \(event)") } }
mit
eb69e0afe029df8f8ab638dbccb61e72
38.634831
128
0.550957
5.336611
false
false
false
false
webim/webim-client-sdk-ios
WebimClientLibrary/Implementation/WebimRemoteNotificationImpl.swift
1
5609
// // WebimRemoteNotificationImpl.swift // WebimClientLibrary // // Created by Nikita Lazarev-Zubov on 09.08.17. // Copyright © 2017 Webim. 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 /** - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ final class WebimRemoteNotificationImpl { // MARK: - Constants enum APNSField: String { case aps = "aps" case webim = "webim" case unreadByVisitorMessagesCount = "unread_by_visitor_msg_cnt" case location = "location" } enum APSField: String { case alert = "alert" } private enum AlertField: String { case event = "event" case parameters = "loc-args" case type = "loc-key" } private enum InternalNotificationEvent: String { case add = "add" case delete = "del" } private enum InternalNotificationType: String { case contactInformationRequest = "P.CR" case operatorAccepted = "P.OA" case operatorFile = "P.OF" case operatorMessage = "P.OM" case widget = "P.WM" case rateOperator = "P.RO" } // MARK: - Properties private var event: InternalNotificationEvent? = nil private lazy var parameters = [String]() private var type: InternalNotificationType? private var location: String? private var unreadByVisitorMessagesCount = 0 // MARK: - Initialization /*init?(jsonDictionary: [String: Any?]) { guard let typeString = jsonDictionary[AlertField.type.rawValue] as? String, let type = InternalNotificationType(rawValue: typeString) else { return nil } self.type = type if let eventString = jsonDictionary[AlertField.event.rawValue] as? String, let event = InternalNotificationEvent(rawValue: eventString) { self.event = event } if let parameters = jsonDictionary[AlertField.parameters.rawValue] as? [String] { self.parameters = parameters } }*/ init?(jsonDictionary: [String: Any?]) { guard let apsFields = jsonDictionary[APNSField.aps.rawValue] as? [String: Any], let alertFields = apsFields[APSField.alert.rawValue] as? [String: Any] else { return nil } if let typeString = alertFields[AlertField.type.rawValue] as? String, let type = InternalNotificationType(rawValue: typeString) { self.type = type } if let eventString = alertFields[AlertField.event.rawValue] as? String, let event = InternalNotificationEvent(rawValue: eventString) { self.event = event } if let parameters = alertFields[AlertField.parameters.rawValue] as? [String] { self.parameters = parameters } if let location = jsonDictionary[APNSField.location.rawValue] as? String { self.location = location } if let unreadByVisitorMessagesCount = jsonDictionary[APNSField.unreadByVisitorMessagesCount.rawValue] as? Int { self.unreadByVisitorMessagesCount = unreadByVisitorMessagesCount } } } // MARK: - WebimRemoteNotification extension WebimRemoteNotificationImpl: WebimRemoteNotification { // MARK: - Methods // MARK: WebimRemoteNotification protocol methods func getType() -> NotificationType? { guard let type = self.type else { return nil } switch type { case .contactInformationRequest: return .contactInformationRequest case .operatorAccepted: return .operatorAccepted case .operatorFile: return .operatorFile case .operatorMessage: return .operatorMessage case .widget: return .widget case .rateOperator: return .rateOperator } } func getEvent() -> NotificationEvent? { if let event = event { switch event { case .add: return .add case .delete: return .delete } } return nil } func getParameters() -> [String] { return parameters } func getLocation() -> String? { return location } func getUnreadByVisitorMessagesCount() -> Int { return unreadByVisitorMessagesCount } }
mit
a8955db991cef1bec0db0b3c0183f177
31.604651
119
0.625357
4.805484
false
false
false
false
doertydoerk/offtube
Offtube/VideoManager.swift
1
6158
// // VideoManager.swift // Offtube // // Created by Dirk Gerretz on 04.06.17. // Copyright © 2017 [code2 app];. All rights reserved. // // GitHub: https://github.com/sonsongithub/YouTubeGetVideoInfoAPIParser import Foundation import YouTubeGetVideoInfoAPIParser import CoreData protocol VideoManagerProtocol: class { func noCompatibleVideoFound(_ reason: String) } class VideoManager: NSObject { // MARK: - Properties weak var delegate: VideoManagerProtocol? let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext let ytClient = YoutubeClient(apiUrl: "https://www.googleapis.com/youtube/v3/videos") func video(url: URL) -> Video? { let video = NSEntityDescription.insertNewObject(forEntityName: "Video", into: context) as! Video // set default values video.timePlayed = 0.0 video.timeRemaining = 0.0 video.downloadComplete = false video.youtubeUrl = url.absoluteString // extract the video ID from the regular Youtube URL guard let id = VideoManager.idFromUrl(url: url) else { delegate?.noCompatibleVideoFound("URL doesn't appear to be a Youtube URL") return nil } video.id = id // get the raw info on the video from Youtube let rawInfo = ytClient.getStreamingDetails(id) // retrieve streaming URL & encoding type let info = convertVideoInfo(info: rawInfo!) if info == nil { delegate?.noCompatibleVideoFound("No iOS compatible video format was found.") return nil } video.streamingUrl = (info?.url)?.absoluteString video.type = (info?.type)! // retrieve additional information (duration, title, ...) if let details = ytClient.getVideoDetails(videoId: id) { video.title = details["title"]! video.details = details["description"]! video.thumbnailUrl = details["thumbnailUrl"] } if let duration = ytClient.getVideoDuration(videoId: id) { video.duration = Int64(duration) } // prep for download guard video.title != nil else { print("*** Can't download video. No title available.") return nil } MainViewController.displayNetworkIndicator(true) let localFilePath = ytClient.prepareForDownload(fileName: (video.id! + ".mp4")) video.fileLocation = localFilePath.absoluteString // download video guard let streamingUrl = URL(string: video.streamingUrl!) else { print("*** Insufficient parameters to execute download") return nil } ytClient.downloadFile(fromUrl: streamingUrl, to: localFilePath, completion: { _ in video.downloadComplete = true }) // download thumbnail guard let thumbnailUrl = URL(string: video.thumbnailUrl!) else { print("*** Can't download thumbnail. No url available.") return nil } let thumbnailFilePath = ytClient.prepareForDownload(fileName: (video.id! + ".jpg")) video.fileLocation = localFilePath.absoluteString ytClient.downloadFile(fromUrl: thumbnailUrl, to: thumbnailFilePath, completion: { _ in video.thumbnailUrl = thumbnailFilePath.absoluteString }) // return NSManagedObject including all infos on the video return video } func convertVideoInfo(info: String) -> (url: URL, type: String)? { do { let maps = try FormatStreamMapFromString(info) for map in maps { if map.quality == .medium && map.type.contains("mp4") { return (map.url, map.type) } } } catch { print("*** Error: couldn't convert to URL/type") } return nil } // MARK: Static Functions static func idFromUrl(url: URL) -> String? { if url.absoluteString.contains("https://youtu.be/") { return idFromShortUrl(url: url) } else if url.absoluteString.contains("https://www.youtube.com/watch") { return idFromRegularUrl(url: url) } return nil } static func idFromRegularUrl(url: URL, param: String = "v") -> String? { guard let url = URLComponents(string: url.absoluteString) else { return nil } return url.queryItems?.first(where: { $0.name == param })?.value } static func idFromShortUrl(url: URL) -> String? { return (url.absoluteString).components(separatedBy: "https://youtu.be/").last } static func delete(file: String) { let fileManager = FileManager.default let url = URL(string: file) do { // Check if file exists if VideoManager.fileExists(url: url!) { // Delete file try fileManager.removeItem(atPath: (url?.path)!) print("*** Deleted file at path: \(file)") } else { print("*** File does not exist: \(file)") } } catch let error as NSError { print("*** An error took place: \(error)") } } static func clearTmpFolder() { let fileManager = FileManager.default let tmpFolder = NSTemporaryDirectory() do { let filePaths = try fileManager.contentsOfDirectory(atPath: tmpFolder) for filePath in filePaths { try fileManager.removeItem(atPath: tmpFolder + filePath) } } catch { print("*** Could not clear temp folder: \(error)") } } static func fileExists(url: URL) -> Bool { let fileManager = FileManager.default if fileManager.fileExists(atPath: url.path) { return true } return false } static func secondsToHoursMinutesSeconds(seconds: Int64) -> (Int, Int, Int) { let secondsInt = Int(truncatingBitPattern: seconds) return (secondsInt / 3600, (secondsInt % 3600) / 60, (secondsInt % 3600) % 60) } }
mit
3f95a6b830611421374f779bbde478a9
32.281081
104
0.600942
4.692835
false
false
false
false
alessioborraccino/reviews
reviews/Main/AppDelegate.swift
1
3046
// // AppDelegate.swift // reviews // // Created by Alessio Borraccino on 13/05/16. // Copyright © 2016 Alessio Borraccino. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { window = UIWindow() window?.rootViewController = rootNavigationController() window?.makeKeyAndVisible() return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. } private func rootNavigationController() -> UINavigationController { let reviewsViewModel = ReviewsViewModel() let reviewsViewController = ReviewsViewController(reviewsViewModel: reviewsViewModel) let navigationController = UINavigationController(rootViewController: reviewsViewController) navigationController.navigationBar.barTintColor = AppColor.main navigationController.navigationBar.tintColor = UIColor.whiteColor() navigationController.navigationBar.titleTextAttributes = [ NSForegroundColorAttributeName: UIColor.whiteColor() ] navigationController.navigationBar.translucent = false return navigationController } }
mit
3d689212caf617b2994b1749882f5aae
48.918033
285
0.75468
5.994094
false
false
false
false
volodg/iAsync.async
Pods/iAsync.utils/Lib/JTimer.swift
2
3713
// // JTimer.swift // JTimer // // Created by Vladimir Gorbenko on 26.06.14. // Copyright (c) 2014 EmbeddedSources. All rights reserved. // import Foundation public typealias JCancelScheduledBlock = () -> Void public typealias JScheduledBlock = (cancel: JCancelScheduledBlock) -> Void //TODO remove NSObject inheritence public class JTimer : NSObject { private var cancelBlocks = [JSimpleBlockHolder]() deinit { cancelAllScheduledOperations() } public func cancelAllScheduledOperations() { let cancelBlocks = self.cancelBlocks self.cancelBlocks.removeAll(keepCapacity: true) for cancelHolder in cancelBlocks { cancelHolder.onceSimpleBlock()() } } public class func sharedByThreadTimer() -> JTimer { let thread = NSThread.currentThread() let key = "JTimer.threadLocalTimer" var result: JTimer? = thread.threadDictionary[key] as? JTimer if result == nil { result = JTimer() thread.threadDictionary[key] = result } return result! } func addBlock(actionBlock: JScheduledBlock, duration : NSTimeInterval, dispatchQueue: dispatch_queue_t) -> JCancelScheduledBlock { return self.addBlock(actionBlock, duration : duration, leeway : duration/10.0, dispatchQueue: dispatchQueue) } public func addBlock(actionBlock: JScheduledBlock, duration : NSTimeInterval, leeway : NSTimeInterval, dispatchQueue: dispatch_queue_t) -> JCancelScheduledBlock { var timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatchQueue) let delta = Int64(duration * Double(NSEC_PER_SEC)) dispatch_source_set_timer(timer, dispatch_time(DISPATCH_TIME_NOW, delta), UInt64(delta), UInt64(leeway * Double(NSEC_PER_SEC))) let cancelTimerBlockHolder = JSimpleBlockHolder() weak var weakCancelTimerBlockHolder = cancelTimerBlockHolder cancelTimerBlockHolder.simpleBlock = { [weak self] () -> () in if timer == nil { return } dispatch_source_cancel(timer) timer = nil if let self_ = self { for (index, cancelHolder) in enumerate(self_.cancelBlocks) { if cancelHolder === weakCancelTimerBlockHolder! { self_.cancelBlocks.removeAtIndex(index) break } } } } cancelBlocks.append(cancelTimerBlockHolder) let eventHandlerBlock = { () -> () in actionBlock(cancel: cancelTimerBlockHolder.onceSimpleBlock()) } dispatch_source_set_event_handler(timer, eventHandlerBlock) dispatch_resume(timer) return cancelTimerBlockHolder.onceSimpleBlock() } public func addBlock(actionBlock: JScheduledBlock, duration: NSTimeInterval) -> JCancelScheduledBlock { return addBlock(actionBlock, duration: duration, leeway : duration/10.0) } public func addBlock(actionBlock: JScheduledBlock, duration: NSTimeInterval, leeway : NSTimeInterval) -> JCancelScheduledBlock { return addBlock(actionBlock, duration : duration, leeway : leeway, dispatchQueue: dispatch_get_main_queue()) } }
mit
189d7488a934fe8201c79d29d8c2b67e
29.68595
91
0.577969
4.983893
false
false
false
false
AvcuFurkan/ColorMatchTabs
ColorMatchTabs/Classes/Transition/CircleTransition.swift
1
3040
// // CircleTransitionAnimator.swift // ColorMatchTabs // // Created by anna on 6/20/16. // Copyright © 2016 Yalantis. All rights reserved. // import UIKit open class CircleTransition: NSObject { public enum Mode { case show, hide } open var startPoint: CGPoint! open var duration: TimeInterval = 0.15 open var mode: Mode! fileprivate weak var transitionContext: UIViewControllerContextTransitioning? } extension CircleTransition: UIViewControllerAnimatedTransitioning { public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return duration } public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { self.transitionContext = transitionContext guard let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to), let fromViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) else { return } transitionContext.containerView.addSubview(toViewController.view) let needShow = mode == .show if !needShow { transitionContext.containerView.addSubview(fromViewController.view) } let animatedViewController = needShow ? toViewController : fromViewController let initialRect = CGRect(origin: startPoint, size: CGSize.zero) let initialCircleMaskPath = UIBezierPath(ovalIn: initialRect) let extremePoint = CGPoint(x: startPoint.x, y: animatedViewController.view.bounds.height) let radius = hypot(extremePoint.x, extremePoint.y) let finalCircleMaskPath = UIBezierPath(ovalIn: initialRect.insetBy(dx: -radius, dy: -radius)) let maskLayer = CAShapeLayer() maskLayer.path = needShow ? finalCircleMaskPath.cgPath : initialCircleMaskPath.cgPath animatedViewController.view.layer.mask = maskLayer let maskLayerAnimation = CABasicAnimation(keyPath: "path") maskLayerAnimation.fromValue = initialCircleMaskPath.cgPath maskLayerAnimation.fromValue = needShow ? initialCircleMaskPath.cgPath : finalCircleMaskPath.cgPath maskLayerAnimation.toValue = needShow ? finalCircleMaskPath.cgPath : initialCircleMaskPath.cgPath maskLayerAnimation.delegate = self maskLayerAnimation.duration = transitionDuration(using: transitionContext) maskLayer.add(maskLayerAnimation, forKey: "path") } } extension CircleTransition: CAAnimationDelegate { public func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { guard let transitionContext = transitionContext else { return } transitionContext.completeTransition(!transitionContext.transitionWasCancelled) transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)?.view.layer.mask = nil } }
mit
927089465acb7796c3e7560c6242aa30
37.468354
123
0.721948
5.617375
false
false
false
false
syoutsey/swift-corelibs-foundation
Foundation/NSSwiftRuntime.swift
1
16079
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 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 // import CoreFoundation #if os(OSX) || os(iOS) import Darwin #elseif os(Linux) import Glibc #endif public typealias ObjCBool = Bool public typealias NSStringEncoding = UInt public var NSASCIIStringEncoding: UInt { return 1 } public var NSNEXTSTEPStringEncoding: UInt { return 2 } public var NSJapaneseEUCStringEncoding: UInt { return 3 } public var NSUTF8StringEncoding: UInt { return 4 } public var NSISOLatin1StringEncoding: UInt { return 5 } public var NSSymbolStringEncoding: UInt { return 6 } public var NSNonLossyASCIIStringEncoding: UInt { return 7 } public var NSShiftJISStringEncoding: UInt { return 8 } public var NSISOLatin2StringEncoding: UInt { return 9 } public var NSUnicodeStringEncoding: UInt { return 10 } public var NSWindowsCP1251StringEncoding: UInt { return 11 } public var NSWindowsCP1252StringEncoding: UInt { return 12 } public var NSWindowsCP1253StringEncoding: UInt { return 13 } public var NSWindowsCP1254StringEncoding: UInt { return 14 } public var NSWindowsCP1250StringEncoding: UInt { return 15 } public var NSISO2022JPStringEncoding: UInt { return 21 } public var NSMacOSRomanStringEncoding: UInt { return 30 } public var NSUTF16StringEncoding: UInt { return NSUnicodeStringEncoding } public var NSUTF16BigEndianStringEncoding: UInt { return 0x90000100 } public var NSUTF16LittleEndianStringEncoding: UInt { return 0x94000100 } public var NSUTF32StringEncoding: UInt { return 0x8c000100 } public var NSUTF32BigEndianStringEncoding: UInt { return 0x98000100 } public var NSUTF32LittleEndianStringEncoding: UInt { return 0x9c000100 } internal class __NSCFType : NSObject { private var _cfinfo : Int32 override init() { // This is not actually called; _CFRuntimeCreateInstance will initialize _cfinfo _cfinfo = 0 } override var hash: Int { get { return Int(CFHash(self)) } } override func isEqual(object: AnyObject?) -> Bool { if let obj = object { return CFEqual(self, obj) } else { return false } } override var description: String { get { return CFCopyDescription(unsafeBitCast(self, CFTypeRef.self))._swiftObject } } deinit { _CFDeinit(self) } } internal func _CFSwiftGetTypeID(cf: AnyObject) -> CFTypeID { return (cf as! NSObject)._cfTypeID } internal func _CFSwiftGetHash(cf: AnyObject) -> CFHashCode { return CFHashCode((cf as! NSObject).hash) } internal func _CFSwiftIsEqual(cf1: AnyObject, cf2: AnyObject) -> Bool { return (cf1 as! NSObject).isEqual(cf2) } // Ivars in _NSCF* types must be zeroed via an unsafe accessor to avoid deinit of potentially unsafe memory to accces as an object/struct etc since it is stored via a foreign object graph internal func _CFZeroUnsafeIvars<T>(inout arg: T) { withUnsafeMutablePointer(&arg) { (ptr: UnsafeMutablePointer<T>) -> Void in bzero(unsafeBitCast(ptr, UnsafeMutablePointer<Void>.self), sizeof(T)) } } internal func __CFSwiftGetBaseClass() -> AnyObject.Type { return __NSCFType.self } internal func __CFInitializeSwift() { _CFRuntimeBridgeTypeToClass(CFStringGetTypeID(), unsafeBitCast(_NSCFString.self, UnsafePointer<Void>.self)) _CFRuntimeBridgeTypeToClass(CFArrayGetTypeID(), unsafeBitCast(_NSCFArray.self, UnsafePointer<Void>.self)) _CFRuntimeBridgeTypeToClass(CFDictionaryGetTypeID(), unsafeBitCast(_NSCFDictionary.self, UnsafePointer<Void>.self)) _CFRuntimeBridgeTypeToClass(CFSetGetTypeID(), unsafeBitCast(_NSCFSet.self, UnsafePointer<Void>.self)) _CFRuntimeBridgeTypeToClass(CFNumberGetTypeID(), unsafeBitCast(NSNumber.self, UnsafePointer<Void>.self)) _CFRuntimeBridgeTypeToClass(CFDataGetTypeID(), unsafeBitCast(NSData.self, UnsafePointer<Void>.self)) _CFRuntimeBridgeTypeToClass(CFDateGetTypeID(), unsafeBitCast(NSDate.self, UnsafePointer<Void>.self)) _CFRuntimeBridgeTypeToClass(CFURLGetTypeID(), unsafeBitCast(NSURL.self, UnsafePointer<Void>.self)) _CFRuntimeBridgeTypeToClass(CFCalendarGetTypeID(), unsafeBitCast(NSCalendar.self, UnsafePointer<Void>.self)) _CFRuntimeBridgeTypeToClass(CFLocaleGetTypeID(), unsafeBitCast(NSLocale.self, UnsafePointer<Void>.self)) _CFRuntimeBridgeTypeToClass(CFTimeZoneGetTypeID(), unsafeBitCast(NSTimeZone.self, UnsafePointer<Void>.self)) _CFRuntimeBridgeTypeToClass(CFCharacterSetGetTypeID(), unsafeBitCast(NSMutableCharacterSet.self, UnsafePointer<Void>.self)) // _CFRuntimeBridgeTypeToClass(CFErrorGetTypeID(), unsafeBitCast(NSError.self, UnsafePointer<Void>.self)) // _CFRuntimeBridgeTypeToClass(CFAttributedStringGetTypeID(), unsafeBitCast(NSMutableAttributedString.self, UnsafePointer<Void>.self)) // _CFRuntimeBridgeTypeToClass(CFReadStreamGetTypeID(), unsafeBitCast(NSInputStream.self, UnsafePointer<Void>.self)) // _CFRuntimeBridgeTypeToClass(CFWriteStreamGetTypeID(), unsafeBitCast(NSOutputStream.self, UnsafePointer<Void>.self)) // _CFRuntimeBridgeTypeToClass(CFRunLoopTimerGetTypeID(), unsafeBitCast(NSTimer.self, UnsafePointer<Void>.self)) __CFSwiftBridge.NSObject.isEqual = _CFSwiftIsEqual __CFSwiftBridge.NSObject.hash = _CFSwiftGetHash __CFSwiftBridge.NSObject._cfTypeID = _CFSwiftGetTypeID __CFSwiftBridge.NSArray.count = _CFSwiftArrayGetCount __CFSwiftBridge.NSArray.objectAtIndex = _CFSwiftArrayGetValueAtIndex __CFSwiftBridge.NSArray.getObjects = _CFSwiftArrayGetValues __CFSwiftBridge.NSMutableArray.addObject = _CFSwiftArrayAppendValue __CFSwiftBridge.NSMutableArray.setObject = _CFSwiftArraySetValueAtIndex __CFSwiftBridge.NSMutableArray.replaceObjectAtIndex = _CFSwiftArrayReplaceValueAtIndex __CFSwiftBridge.NSMutableArray.insertObject = _CFSwiftArrayInsertValueAtIndex __CFSwiftBridge.NSMutableArray.exchangeObjectAtIndex = _CFSwiftArrayExchangeValuesAtIndices __CFSwiftBridge.NSMutableArray.removeObjectAtIndex = _CFSwiftArrayRemoveValueAtIndex __CFSwiftBridge.NSMutableArray.removeAllObjects = _CFSwiftArrayRemoveAllValues __CFSwiftBridge.NSMutableArray.replaceObjectsInRange = _CFSwiftArrayReplaceValues __CFSwiftBridge.NSDictionary.count = _CFSwiftDictionaryGetCount __CFSwiftBridge.NSDictionary.countForKey = _CFSwiftDictionaryGetCountOfKey __CFSwiftBridge.NSDictionary.containsKey = _CFSwiftDictionaryContainsKey __CFSwiftBridge.NSDictionary.objectForKey = _CFSwiftDictionaryGetValue __CFSwiftBridge.NSDictionary._getValueIfPresent = _CFSwiftDictionaryGetValueIfPresent __CFSwiftBridge.NSDictionary.containsObject = _CFSwiftDictionaryContainsValue __CFSwiftBridge.NSDictionary.countForObject = _CFSwiftDictionaryGetCountOfValue __CFSwiftBridge.NSDictionary.getObjects = _CFSwiftDictionaryGetKeysAndValues __CFSwiftBridge.NSDictionary.__apply = _CFSwiftDictionaryApplyFunction __CFSwiftBridge.NSMutableDictionary.__addObject = _CFSwiftDictionaryAddValue __CFSwiftBridge.NSMutableDictionary.replaceObject = _CFSwiftDictionaryReplaceValue __CFSwiftBridge.NSMutableDictionary.__setObject = _CFSwiftDictionarySetValue __CFSwiftBridge.NSMutableDictionary.removeObjectForKey = _CFSwiftDictionaryRemoveValue __CFSwiftBridge.NSMutableDictionary.removeAllObjects = _CFSwiftDictionaryRemoveAllValues __CFSwiftBridge.NSString._createSubstringWithRange = _CFSwiftStringCreateWithSubstring __CFSwiftBridge.NSString.copy = _CFSwiftStringCreateCopy __CFSwiftBridge.NSString.mutableCopy = _CFSwiftStringCreateMutableCopy __CFSwiftBridge.NSString.length = _CFSwiftStringGetLength __CFSwiftBridge.NSString.characterAtIndex = _CFSwiftStringGetCharacterAtIndex __CFSwiftBridge.NSString.getCharacters = _CFSwiftStringGetCharacters __CFSwiftBridge.NSString.__getBytes = _CFSwiftStringGetBytes __CFSwiftBridge.NSString._fastCStringContents = _CFSwiftStringFastCStringContents __CFSwiftBridge.NSString._fastCharacterContents = _CFSwiftStringFastContents __CFSwiftBridge.NSString._getCString = _CFSwiftStringGetCString __CFSwiftBridge.NSMutableString.insertString = _CFSwiftStringInsert __CFSwiftBridge.NSMutableString.deleteCharactersInRange = _CFSwiftStringDelete __CFSwiftBridge.NSMutableString.replaceCharactersInRange = _CFSwiftStringReplace __CFSwiftBridge.NSMutableString.setString = _CFSwiftStringReplaceAll __CFSwiftBridge.NSMutableString.appendString = _CFSwiftStringAppend __CFSwiftBridge.NSMutableString.appendCharacters = _CFSwiftStringAppendCharacters __CFSwiftBridge.NSMutableString._cfAppendCString = _CFSwiftStringAppendCString __CFSwiftBridge.NSXMLParser.currentParser = _NSXMLParserCurrentParser __CFSwiftBridge.NSXMLParser._xmlExternalEntityWithURL = _NSXMLParserExternalEntityWithURL __CFSwiftBridge.NSXMLParser.getContext = _NSXMLParserGetContext __CFSwiftBridge.NSXMLParser.internalSubset = _NSXMLParserInternalSubset __CFSwiftBridge.NSXMLParser.isStandalone = _NSXMLParserIsStandalone __CFSwiftBridge.NSXMLParser.hasInternalSubset = _NSXMLParserHasInternalSubset __CFSwiftBridge.NSXMLParser.hasExternalSubset = _NSXMLParserHasExternalSubset __CFSwiftBridge.NSXMLParser.getEntity = _NSXMLParserGetEntity __CFSwiftBridge.NSXMLParser.notationDecl = _NSXMLParserNotationDecl __CFSwiftBridge.NSXMLParser.attributeDecl = _NSXMLParserAttributeDecl __CFSwiftBridge.NSXMLParser.elementDecl = _NSXMLParserElementDecl __CFSwiftBridge.NSXMLParser.unparsedEntityDecl = _NSXMLParserUnparsedEntityDecl __CFSwiftBridge.NSXMLParser.startDocument = _NSXMLParserStartDocument __CFSwiftBridge.NSXMLParser.endDocument = _NSXMLParserEndDocument __CFSwiftBridge.NSXMLParser.startElementNs = _NSXMLParserStartElementNs __CFSwiftBridge.NSXMLParser.endElementNs = _NSXMLParserEndElementNs __CFSwiftBridge.NSXMLParser.characters = _NSXMLParserCharacters __CFSwiftBridge.NSXMLParser.processingInstruction = _NSXMLParserProcessingInstruction __CFSwiftBridge.NSXMLParser.cdataBlock = _NSXMLParserCdataBlock __CFSwiftBridge.NSXMLParser.comment = _NSXMLParserComment __CFSwiftBridge.NSXMLParser.externalSubset = _NSXMLParserExternalSubset } #if os(Linux) /// This is ripped from the standard library; technically it should be /// split out into two protocols. _ObjectiveCBridgeable causes extra thunks /// to be emitted during subclassing to properly convert to objc bridgable /// types; however this is being overloaded for it's meaning to be used as /// a conversion point between struct types such as String and Dictionary /// to object types such as NSDictionary; which in this case is a Swift class /// type. So ideally the standard library should provide a _ImplicitConvertable /// protocol which _ObjectiveCBridgeable derives from so that the classes that /// adopt _ObjectiveCBridgeable get the subclassing thunk behavior and the /// classes that adopt _ImplicitConvertable just get the implicit conversion /// behavior and avoid the thunk generation. public protocol _ObjectiveCBridgeable { typealias _ObjectiveCType : AnyObject /// Return true iff instances of `Self` can be converted to /// Objective-C. Even if this method returns `true`, A given /// instance of `Self._ObjectiveCType` may, or may not, convert /// successfully to `Self`; for example, an `NSArray` will only /// convert successfully to `[String]` if it contains only /// `NSString`s. @warn_unused_result static func _isBridgedToObjectiveC() -> Bool // _getObjectiveCType is a workaround: right now protocol witness // tables don't include associated types, so we can not find // '_ObjectiveCType.self' from them. /// Must return `_ObjectiveCType.self`. @warn_unused_result static func _getObjectiveCType() -> Any.Type /// Convert `self` to Objective-C. @warn_unused_result func _bridgeToObjectiveC() -> _ObjectiveCType /// Bridge from an Objective-C object of the bridged class type to a /// value of the Self type. /// /// This bridging operation is used for forced downcasting (e.g., /// via as), and may defer complete checking until later. For /// example, when bridging from `NSArray` to `Array<Element>`, we can defer /// the checking for the individual elements of the array. /// /// - parameter result: The location where the result is written. The optional /// will always contain a value. static func _forceBridgeFromObjectiveC( source: _ObjectiveCType, inout result: Self? ) /// Try to bridge from an Objective-C object of the bridged class /// type to a value of the Self type. /// /// This conditional bridging operation is used for conditional /// downcasting (e.g., via as?) and therefore must perform a /// complete conversion to the value type; it cannot defer checking /// to a later time. /// /// - parameter result: The location where the result is written. /// /// - Returns: `true` if bridging succeeded, `false` otherwise. This redundant /// information is provided for the convenience of the runtime's `dynamic_cast` /// implementation, so that it need not look into the optional representation /// to determine success. static func _conditionallyBridgeFromObjectiveC( source: _ObjectiveCType, inout result: Self? ) -> Bool } #endif protocol _NSObjectRepresentable { func _nsObjectRepresentation() -> NSObject } internal func _NSObjectRepresentableBridge(value: Any) -> NSObject { if let obj = value as? _NSObjectRepresentable { return obj._nsObjectRepresentation() } else if let str = value as? String { return str._nsObjectRepresentation() } else if let obj = value as? NSObject { return obj } fatalError("Unable to convert value of type \(value.dynamicType)") } extension Array : _NSObjectRepresentable { func _nsObjectRepresentation() -> NSObject { return _bridgeToObjectiveC() } } extension Dictionary : _NSObjectRepresentable { func _nsObjectRepresentation() -> NSObject { return _bridgeToObjectiveC() } } extension String : _NSObjectRepresentable { func _nsObjectRepresentation() -> NSObject { return _bridgeToObjectiveC() } } extension Set : _NSObjectRepresentable { func _nsObjectRepresentation() -> NSObject { return _bridgeToObjectiveC() } } #if os(Linux) public func === (lhs: AnyClass, rhs: AnyClass) -> Bool { return unsafeBitCast(lhs, UnsafePointer<Void>.self) == unsafeBitCast(rhs, UnsafePointer<Void>.self) } #endif /// Swift extensions for common operations in Foundation that use unsafe things... extension UnsafeMutablePointer { internal init<T: AnyObject>(retained value: T) { self.init(Unmanaged<T>.passRetained(value).toOpaque()) } internal init<T: AnyObject>(unretained value: T) { self.init(Unmanaged<T>.passUnretained(value).toOpaque()) } internal func array(count: Int) -> [Memory] { let buffer = UnsafeBufferPointer<Memory>(start: self, count: count) return Array<Memory>(buffer) } } extension Unmanaged { internal static func fromOpaque(value: UnsafeMutablePointer<Void>) -> Unmanaged<Instance> { return self.fromOpaque(COpaquePointer(value)) } internal static func fromOptionalOpaque(value: UnsafePointer<Void>) -> Unmanaged<Instance>? { if value != nil { return self.fromOpaque(COpaquePointer(value)) } else { return nil } } } public protocol Bridgeable { typealias BridgeType func bridge() -> BridgeType }
apache-2.0
e5c10c05cb3da932478708ef75d984ac
44.292958
187
0.751415
5.234049
false
false
false
false
inkyfox/RxGoogleMaps
Sources/RxGMSMapView+Rx.swift
1
12303
/// Copyright (c) RxSwiftCommunity // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import UIKit import CoreLocation import RxCocoa import RxSwift extension Reactive where Base: RxGMSMapView { fileprivate var delegateProxy: RxGMSMapViewDelegateProxy { return RxGMSMapViewDelegateProxy.proxyForObject(base) } public func handleTapMarkerWrapper(_ closure: RxGMSHandleTapMarker?) { delegateProxy.handleTapMarker = closure } public func handleMarkerInfoWindowWrapper(_ closure: RxGMSHandleMarkerInfoView?) { delegateProxy.handleMarkerInfoWindow = closure } public func handleMarkerInfoContentsWrapper(_ closure: RxGMSHandleMarkerInfoView?) { delegateProxy.handleMarkerInfoContents = closure } public func handleTapMyLocationButton(_ closure: RxGMSHandleTapMyLocationButton?) { delegateProxy.handleTapMyLocationButton = closure } } // GMSMapView delegate public extension Reactive where Base: RxGMSMapView { private func methodInvokedWithParam1<T>(_ selector: Selector) -> Observable<T> { return delegateProxy .methodInvoked(selector) .map { a in return try castOrThrow(T.self, a[1]) } } private func controlEventWithParam1<T>(_ selector: Selector) -> ControlEvent<T> { return ControlEvent(events: methodInvokedWithParam1(selector)) } /** Wrapper of: func mapView(_ mapView: GMSMapView, willMove gesture: Bool) */ public var willMove: ControlEvent<RxGMSGestureProperty> { return ControlEvent(events: methodInvokedWithParam1(#selector(RxGMSMapViewDelegate.mapView(_:willMove:))) .map(RxGMSGestureProperty.init) ) } public var didChangePositionWrapper: Observable<RxGMSCameraPosition> { return methodInvokedWithParam1(#selector(RxGMSMapViewDelegate.mapView(_:didChangeCameraPosition:))) } public var idleAtPositionWrapper: Observable<RxGMSCameraPosition> { return methodInvokedWithParam1(#selector(RxGMSMapViewDelegate.mapView(_:idleAtCameraPosition:))) } /** Wrapper of: mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D) */ public var didTapAt: ControlEvent<CLLocationCoordinate2D> { let source = delegateProxy .methodInvoked(#selector(RxGMSMapViewDelegate.mapView(_:didTapAtCoordinate:))) .map { a in return try castCoordinateOrThrow(a[1]) } return ControlEvent(events: source) } /** Wrapper of: func mapView(_ mapView: GMSMapView, didLongPressAt coordinate: CLLocationCoordinate2D) */ public var didLongPressAt: ControlEvent<CLLocationCoordinate2D> { let source = delegateProxy .methodInvoked(#selector(RxGMSMapViewDelegate.mapView(_:didLongPressAtCoordinate:))) .map { a in return try castCoordinateOrThrow(a[1]) } return ControlEvent(events: source) } public var didTapMarkerWrapper: Observable<RxGMSMarker> { return delegateProxy.didTapMarkerEvent } public var didTapInfoWindowWrapper: Observable<RxGMSMarker> { return methodInvokedWithParam1(#selector(RxGMSMapViewDelegate.mapView(_:didTapInfoWindowOfMarker:))) } public var didLongPressInfoWindowWrapper: Observable<RxGMSMarker> { return methodInvokedWithParam1(#selector(RxGMSMapViewDelegate.mapView(_:didLongPressInfoWindowOfMarker:))) } public var didTapOverlayWrapper: Observable<RxGMSOverlay> { return methodInvokedWithParam1(#selector(RxGMSMapViewDelegate.mapView(_:didTapOverlay:))) } /** Wrapper of: func mapView(_ mapView: GMSMapView, didTap overlay: GMSOverlay) */ public var didTapPOI: ControlEvent<(placeID: String, name: String, location: CLLocationCoordinate2D)> { let source = delegateProxy .methodInvoked(#selector(RxGMSMapViewDelegate.mapView(_:didTapPOIWithPlaceID:name:location:))) .map { a -> (placeID: String, name: String, location: CLLocationCoordinate2D)in let placeID = try castOrThrow(NSString.self, a[1]) as String let name = try castOrThrow(NSString.self, a[2]) as String let value = try castOrThrow(NSValue.self, a[3]) var coordinate = CLLocationCoordinate2D() value.getValue(&coordinate) return (placeID, name, coordinate) } return ControlEvent(events: source) } /** Wrapper of: func mapView(_ mapView: GMSMapView, didTapPOIWithPlaceID placeID: String, name: String, location: CLLocationCoordinate2D) */ public var didTapMyLocationButton: ControlEvent<Void> { return ControlEvent(events: delegateProxy.didTapMyLocationButtonEvent) } public var didCloseInfoWindowWrapper: Observable<RxGMSMarker> { return methodInvokedWithParam1(#selector(RxGMSMapViewDelegate.mapView(_:didCloseInfoWindowOfMarker:))) } public var didBeginDraggingMarkerWrapper: Observable<RxGMSMarker> { return methodInvokedWithParam1(#selector(RxGMSMapViewDelegate.mapView(_:didBeginDraggingMarker:))) } public var didEndDraggingMarkerWrapper: Observable<RxGMSMarker> { return methodInvokedWithParam1(#selector(RxGMSMapViewDelegate.mapView(_:didEndDraggingMarker:))) } public var didDragMarkerWrapper: Observable<RxGMSMarker> { return methodInvokedWithParam1(#selector(RxGMSMapViewDelegate.mapView(_:didDragMarker:))) } /** Wrapper of: func mapViewDidStartTileRendering(_ mapView: GMSMapView) */ public var didStartTileRendering: ControlEvent<Void> { return ControlEvent(events: delegateProxy .methodInvoked(#selector(RxGMSMapViewDelegate.mapViewDidStartTileRendering(_:))) .map{ _ in return } ) } /** Wrapper of: func mapViewDidFinishTileRendering(_ mapView: GMSMapView) */ public var didFinishTileRendering: ControlEvent<Void> { return ControlEvent(events: delegateProxy .methodInvoked(#selector(RxGMSMapViewDelegate.mapViewDidFinishTileRendering(_:))) .map{ _ in return } ) } /** Wrapper of: func mapViewSnapshotReady(_ mapView: GMSMapView) */ public var snapshotReady: ControlEvent<Void> { return ControlEvent(events: delegateProxy .methodInvoked(#selector(RxGMSMapViewDelegate.mapViewSnapshotReady(_:))) .map{ _ in return } ) } } // GMSMapView properties (camera & animate) public extension Reactive where Base: RxGMSMapView, Base: UIView { public var camera: AnyObserver<RxGMSCameraPosition> { return UIBindingObserver(UIElement: base) { control, camera in control.cameraWrapper = camera }.asObserver() } public var cameraToAnimate: AnyObserver<RxGMSCameraPosition> { return UIBindingObserver(UIElement: base) { control, camera in control.animateWrapper(to: camera) }.asObserver() } public var locationToAnimate: AnyObserver<CLLocationCoordinate2D> { return UIBindingObserver(UIElement: base) { control, location in control.animate(toLocation: location) }.asObserver() } public var zoomToAnimate: AnyObserver<Float> { return UIBindingObserver(UIElement: base) { control, zoom in control.animate(toZoom: zoom) }.asObserver() } public var bearingToAnimate: AnyObserver<CLLocationDirection> { return UIBindingObserver(UIElement: base) { control, bearing in control.animate(toBearing: bearing) }.asObserver() } public var viewingAngleToAnimate: AnyObserver<Double> { return UIBindingObserver(UIElement: base) { control, viewingAngle in control.animate(toViewingAngle: viewingAngle) }.asObserver() } } // GMSMapView properties public extension Reactive where Base: RxGMSMapView, Base: UIView { public var myLocationEnabled: AnyObserver<Bool> { return UIBindingObserver(UIElement: base) { control, myLocationEnabled in control.myLocationEnabled = myLocationEnabled }.asObserver() } public var myLocation: Observable<CLLocation?> { return observeWeakly(CLLocation.self, "myLocation") } public var selectedMarker: ControlProperty<RxGMSMarker?> { return ControlProperty(values: observeWeakly(RxGMSMarker.self, "selectedMarker"), valueSink: UIBindingObserver(UIElement: base) { control, selectedMarker in control.selectedMarkerWrapper = selectedMarker }.asObserver() ) } public var trafficEnabled: AnyObserver<Bool> { return UIBindingObserver(UIElement: base) { control, trafficEnabled in control.trafficEnabled = trafficEnabled }.asObserver() } public var padding: AnyObserver<UIEdgeInsets> { return UIBindingObserver(UIElement: base) { control, padding in control.padding = padding }.asObserver() } } // GMSMapView settings (GMSUISettings) properties public extension Reactive where Base: RxGMSMapView, Base: UIView { public var scrollGesturesEnabled: AnyObserver<Bool> { return UIBindingObserver(UIElement: base) { control, scrollGestures in control.settingsWrapper.scrollGestures = scrollGestures }.asObserver() } public var zoomGesturesEnabled: AnyObserver<Bool> { return UIBindingObserver(UIElement: base) { control, zoomGestures in control.settingsWrapper.zoomGestures = zoomGestures }.asObserver() } public var tiltGesturesEnabled: AnyObserver<Bool> { return UIBindingObserver(UIElement: base) { control, tiltGestures in control.settingsWrapper.tiltGestures = tiltGestures }.asObserver() } public var rotateGesturesEnabled: AnyObserver<Bool> { return UIBindingObserver(UIElement: base) { control, rotateGestures in control.settingsWrapper.rotateGestures = rotateGestures }.asObserver() } public var compassButtonVisible: AnyObserver<Bool> { return UIBindingObserver(UIElement: base) { control, compassButton in control.settingsWrapper.compassButton = compassButton }.asObserver() } public var myLocationButtonVisible: AnyObserver<Bool> { return UIBindingObserver(UIElement: base) { control, myLocationButton in control.settingsWrapper.myLocationButton = myLocationButton }.asObserver() } } // public struct RxGMSGestureProperty { public let byGesture: Bool } fileprivate func castCoordinateOrThrow(_ object: Any) throws -> CLLocationCoordinate2D { let value = try castOrThrow(NSValue.self, object) var coordinate = CLLocationCoordinate2D() value.getValue(&coordinate) return coordinate }
mit
cd583cbdb0af0ad6884ec2d456e23b59
36.281818
138
0.685768
5.202114
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Activity/BaseActivityListViewController.swift
1
21801
import Foundation import CocoaLumberjack import SVProgressHUD import WordPressShared import WordPressFlux struct ActivityListConfiguration { /// An identifier of the View Controller let identifier: String /// The title of the View Controller let title: String /// The title for when loading activities let loadingTitle: String /// Title for when there are no activities let noActivitiesTitle: String /// Subtitle for when there are no activities let noActivitiesSubtitle: String /// Title for when there are no activities for the selected filter let noMatchingTitle: String /// Subtitle for when there are no activities for the selected filter let noMatchingSubtitle: String /// Event to be fired when the date range button is tapped let filterbarRangeButtonTapped: WPAnalyticsEvent /// Event to be fired when a date range is selected let filterbarSelectRange: WPAnalyticsEvent /// Event to be fired when the range date reset button is tapped let filterbarResetRange: WPAnalyticsEvent /// The number of items to be requested for each page let numberOfItemsPerPage: Int } /// ActivityListViewController is used as a base ViewController for /// Jetpack's Activity Log and Backup /// class BaseActivityListViewController: UIViewController, TableViewContainer, ImmuTablePresenter { let site: JetpackSiteRef let store: ActivityStore let configuration: ActivityListConfiguration let isFreeWPCom: Bool var changeReceipt: Receipt? var isUserTriggeredRefresh: Bool = false let containerStackView = UIStackView() let filterView = FilterBarView() let dateFilterChip = FilterChipButton() let activityTypeFilterChip = FilterChipButton() var tableView: UITableView = UITableView() let refreshControl = UIRefreshControl() let numberOfItemsPerPage = 100 fileprivate lazy var handler: ImmuTableViewHandler = { return ImmuTableViewHandler(takeOver: self, with: self) }() private lazy var spinner: UIActivityIndicatorView = { let spinner = UIActivityIndicatorView(style: .medium) spinner.startAnimating() spinner.frame = CGRect(x: 0, y: 0, width: tableView.bounds.width, height: 44) return spinner }() var viewModel: ActivityListViewModel private enum Constants { static let estimatedRowHeight: CGFloat = 62 } // MARK: - GUI fileprivate var noResultsViewController: NoResultsViewController? // MARK: - Constructors init(site: JetpackSiteRef, store: ActivityStore, isFreeWPCom: Bool = false) { fatalError("A configuration struct needs to be provided") } init(site: JetpackSiteRef, store: ActivityStore, configuration: ActivityListConfiguration, isFreeWPCom: Bool = false) { self.site = site self.store = store self.isFreeWPCom = isFreeWPCom self.configuration = configuration self.viewModel = ActivityListViewModel(site: site, store: store, configuration: configuration) super.init(nibName: nil, bundle: nil) self.changeReceipt = viewModel.onChange { [weak self] in self?.refreshModel() } view.addSubview(containerStackView) containerStackView.axis = .vertical if site.shouldShowActivityLogFilter() { setupFilterBar() } containerStackView.addArrangedSubview(tableView) containerStackView.translatesAutoresizingMaskIntoConstraints = false view.pinSubviewToSafeArea(containerStackView) tableView.refreshControl = refreshControl refreshControl.addTarget(self, action: #selector(userRefresh), for: .valueChanged) title = configuration.title } @objc private func showCalendar() { let calendarViewController = CalendarViewController(startDate: viewModel.after, endDate: viewModel.before) calendarViewController.delegate = self let navigationController = UINavigationController(rootViewController: calendarViewController) present(navigationController, animated: true, completion: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc convenience init?(blog: Blog) { precondition(blog.dotComID != nil) guard let siteRef = JetpackSiteRef(blog: blog) else { return nil } let isFreeWPCom = blog.isHostedAtWPcom && !blog.hasPaidPlan self.init(site: siteRef, store: StoreContainer.shared.activity, isFreeWPCom: isFreeWPCom) } // MARK: - View lifecycle override func viewDidLoad() { super.viewDidLoad() refreshModel() tableView.estimatedRowHeight = Constants.estimatedRowHeight WPStyleGuide.configureColors(view: view, tableView: tableView) let nib = UINib(nibName: ActivityListSectionHeaderView.identifier, bundle: nil) tableView.register(nib, forHeaderFooterViewReuseIdentifier: ActivityListSectionHeaderView.identifier) ImmuTable.registerRows([ActivityListRow.self, RewindStatusRow.self], tableView: tableView) tableView.tableFooterView = spinner tableView.tableFooterView?.isHidden = true } override func viewWillDisappear(_ animated: Bool) { SVProgressHUD.dismiss() } @objc func userRefresh() { isUserTriggeredRefresh = true viewModel.refresh(after: viewModel.after, before: viewModel.before, group: viewModel.selectedGroups) } func refreshModel() { updateHeader() handler.viewModel = viewModel.tableViewModel(presenter: self) updateRefreshControl() updateNoResults() updateFilters() } private func updateHeader() { tableView.tableHeaderView = viewModel.backupDownloadHeader() guard let tableHeaderView = tableView.tableHeaderView else { return } tableHeaderView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ tableHeaderView.topAnchor.constraint(equalTo: tableView.topAnchor), tableHeaderView.safeLeadingAnchor.constraint(equalTo: tableView.safeLeadingAnchor), tableHeaderView.safeTrailingAnchor.constraint(equalTo: tableView.safeTrailingAnchor) ]) tableView.tableHeaderView?.layoutIfNeeded() } private func updateRefreshControl() { switch (viewModel.refreshing, refreshControl.isRefreshing) { case (true, false): if isUserTriggeredRefresh { refreshControl.beginRefreshing() isUserTriggeredRefresh = false } else if tableView.numberOfSections > 0 { tableView.tableFooterView?.isHidden = false } case (false, true): refreshControl.endRefreshing() default: tableView.tableFooterView?.isHidden = true break } } private func updateFilters() { viewModel.dateFilterIsActive ? dateFilterChip.enableResetButton() : dateFilterChip.disableResetButton() dateFilterChip.title = viewModel.dateRangeDescription() viewModel.groupFilterIsActive ? activityTypeFilterChip.enableResetButton() : activityTypeFilterChip.disableResetButton() activityTypeFilterChip.title = viewModel.activityTypeDescription() } private func setupFilterBar() { containerStackView.addArrangedSubview(filterView) filterView.add(button: dateFilterChip) filterView.add(button: activityTypeFilterChip) setupDateFilter() setupActivityTypeFilter() } private func setupDateFilter() { dateFilterChip.resetButton.accessibilityLabel = NSLocalizedString("Reset Date Range filter", comment: "Accessibility label for the reset date range button") dateFilterChip.tapped = { [unowned self] in WPAnalytics.track(self.configuration.filterbarRangeButtonTapped) self.showCalendar() } dateFilterChip.resetTapped = { [unowned self] in WPAnalytics.track(self.configuration.filterbarResetRange) self.viewModel.removeDateFilter() self.dateFilterChip.disableResetButton() } } private func setupActivityTypeFilter() { activityTypeFilterChip.resetButton.accessibilityLabel = NSLocalizedString("Reset Activity Type filter", comment: "Accessibility label for the reset activity type button") activityTypeFilterChip.tapped = { [weak self] in guard let self = self else { return } WPAnalytics.track(.activitylogFilterbarTypeButtonTapped) let activityTypeSelectorViewController = ActivityTypeSelectorViewController( viewModel: self.viewModel ) activityTypeSelectorViewController.delegate = self let navigationController = UINavigationController(rootViewController: activityTypeSelectorViewController) self.present(navigationController, animated: true, completion: nil) } activityTypeFilterChip.resetTapped = { [weak self] in WPAnalytics.track(.activitylogFilterbarResetType) self?.viewModel.removeGroupFilter() self?.activityTypeFilterChip.disableResetButton() } } } extension BaseActivityListViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { handler.tableView(tableView, numberOfRowsInSection: section) } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { handler.tableView(tableView, cellForRowAt: indexPath) } } // MARK: - UITableViewDelegate extension BaseActivityListViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { let isLastSection = handler.viewModel.sections.count == section + 1 guard isFreeWPCom, isLastSection, let cell = tableView.dequeueReusableHeaderFooterView(withIdentifier: ActivityListSectionHeaderView.identifier) as? ActivityListSectionHeaderView else { return nil } cell.separator.isHidden = true cell.titleLabel.text = NSLocalizedString("Since you're on a free plan, you'll see limited events in your Activity Log.", comment: "Text displayed as a footer of a table view with Activities when user is on a free plan") return cell } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { let isLastSection = handler.viewModel.sections.count == section + 1 guard isFreeWPCom, isLastSection else { return 0.0 } return UITableView.automaticDimension } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard let cell = tableView.dequeueReusableHeaderFooterView(withIdentifier: ActivityListSectionHeaderView.identifier) as? ActivityListSectionHeaderView else { return nil } cell.titleLabel.text = handler.tableView(tableView, titleForHeaderInSection: section)?.localizedUppercase return cell } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return ActivityListSectionHeaderView.height } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { guard let row = handler.viewModel.rowAtIndexPath(indexPath) as? ActivityListRow else { return false } return row.activity.isRewindable } func scrollViewDidScroll(_ scrollView: UIScrollView) { let offsetY = scrollView.contentOffset.y let contentHeight = scrollView.contentSize.height let shouldLoadMore = offsetY > contentHeight - (2 * scrollView.frame.size.height) && viewModel.hasMore if shouldLoadMore { viewModel.loadMore() } } } // MARK: - NoResultsViewControllerDelegate extension BaseActivityListViewController: NoResultsViewControllerDelegate { func actionButtonPressed() { let supportVC = SupportTableViewController() supportVC.showFromTabBar() } } // MARK: - ActivityPresenter extension BaseActivityListViewController: ActivityPresenter { func presentDetailsFor(activity: FormattableActivity) { let detailVC = ActivityDetailViewController.loadFromStoryboard() detailVC.site = site detailVC.rewindStatus = store.state.rewindStatus[site] detailVC.formattableActivity = activity detailVC.presenter = self self.navigationController?.pushViewController(detailVC, animated: true) } func presentBackupOrRestoreFor(activity: Activity, from sender: UIButton) { let rewindStatus = store.state.rewindStatus[site] let title = rewindStatus?.isMultisite() == true ? RewindStatus.Strings.multisiteNotAvailable : nil let alertController = UIAlertController(title: title, message: nil, preferredStyle: .actionSheet) if rewindStatus?.state == .active { let restoreTitle = NSLocalizedString("Restore", comment: "Title displayed for restore action.") let restoreOptionsVC = JetpackRestoreOptionsViewController(site: site, activity: activity, isAwaitingCredentials: store.isAwaitingCredentials(site: site)) restoreOptionsVC.restoreStatusDelegate = self restoreOptionsVC.presentedFrom = configuration.identifier alertController.addDefaultActionWithTitle(restoreTitle, handler: { _ in self.present(UINavigationController(rootViewController: restoreOptionsVC), animated: true) }) } let backupTitle = NSLocalizedString("Download backup", comment: "Title displayed for download backup action.") let backupOptionsVC = JetpackBackupOptionsViewController(site: site, activity: activity) backupOptionsVC.backupStatusDelegate = self backupOptionsVC.presentedFrom = configuration.identifier alertController.addDefaultActionWithTitle(backupTitle, handler: { _ in self.present(UINavigationController(rootViewController: backupOptionsVC), animated: true) }) if let backupAction = alertController.actions.last { backupAction.accessibilityIdentifier = "jetpack-download-backup-button" } let cancelTitle = NSLocalizedString("Cancel", comment: "Title for cancel action. Dismisses the action sheet.") alertController.addCancelActionWithTitle(cancelTitle) if let presentationController = alertController.popoverPresentationController { presentationController.permittedArrowDirections = .any presentationController.sourceView = sender presentationController.sourceRect = sender.bounds } self.present(alertController, animated: true, completion: nil) } func presentRestoreFor(activity: Activity, from: String? = nil) { guard activity.isRewindable, activity.rewindID != nil else { return } let restoreOptionsVC = JetpackRestoreOptionsViewController(site: site, activity: activity, isAwaitingCredentials: store.isAwaitingCredentials(site: site)) restoreOptionsVC.restoreStatusDelegate = self restoreOptionsVC.presentedFrom = from ?? configuration.identifier let navigationVC = UINavigationController(rootViewController: restoreOptionsVC) self.present(navigationVC, animated: true) } func presentBackupFor(activity: Activity, from: String? = nil) { let backupOptionsVC = JetpackBackupOptionsViewController(site: site, activity: activity) backupOptionsVC.backupStatusDelegate = self backupOptionsVC.presentedFrom = from ?? configuration.identifier let navigationVC = UINavigationController(rootViewController: backupOptionsVC) self.present(navigationVC, animated: true) } } // MARK: - Restores handling extension BaseActivityListViewController { fileprivate func restoreSiteToRewindID(_ rewindID: String) { navigationController?.popToViewController(self, animated: true) store.actionDispatcher.dispatch(ActivityAction.rewind(site: site, rewindID: rewindID)) } } // MARK: - NoResults Handling private extension BaseActivityListViewController { func updateNoResults() { if let noResultsViewModel = viewModel.noResultsViewModel() { showNoResults(noResultsViewModel) } else { noResultsViewController?.view.isHidden = true } } func showNoResults(_ viewModel: NoResultsViewController.Model) { if noResultsViewController == nil { noResultsViewController = NoResultsViewController.controller() noResultsViewController?.delegate = self guard let noResultsViewController = noResultsViewController else { return } if noResultsViewController.view.superview != tableView { tableView.addSubview(withFadeAnimation: noResultsViewController.view) } addChild(noResultsViewController) noResultsViewController.view.translatesAutoresizingMaskIntoConstraints = false } noResultsViewController?.bindViewModel(viewModel) noResultsViewController?.didMove(toParent: self) tableView.pinSubviewToSafeArea(noResultsViewController!.view) noResultsViewController?.view.isHidden = false } } // MARK: - Restore Status Handling extension BaseActivityListViewController: JetpackRestoreStatusViewControllerDelegate { func didFinishViewing(_ controller: JetpackRestoreStatusViewController) { controller.dismiss(animated: true, completion: { [weak self] in guard let self = self else { return } self.store.fetchRewindStatus(site: self.site) }) } } // MARK: - Restore Status Handling extension BaseActivityListViewController: JetpackBackupStatusViewControllerDelegate { func didFinishViewing() { viewModel.refresh() } } // MARK: - Calendar Handling extension BaseActivityListViewController: CalendarViewControllerDelegate { func didCancel(calendar: CalendarViewController) { calendar.dismiss(animated: true, completion: nil) } func didSelect(calendar: CalendarViewController, startDate: Date?, endDate: Date?) { guard startDate != viewModel.after || endDate != viewModel.before else { calendar.dismiss(animated: true, completion: nil) return } trackSelectedRange(startDate: startDate, endDate: endDate) viewModel.refresh(after: startDate, before: endDate, group: viewModel.selectedGroups) calendar.dismiss(animated: true, completion: nil) } private func trackSelectedRange(startDate: Date?, endDate: Date?) { guard let startDate = startDate else { if viewModel.after != nil || viewModel.before != nil { WPAnalytics.track(configuration.filterbarResetRange) } return } var duration: Int // Number of selected days var distance: Int // Distance from the startDate to today (in days) if let endDate = endDate { duration = Int((endDate.timeIntervalSinceReferenceDate - startDate.timeIntervalSinceReferenceDate) / Double(24 * 60 * 60)) + 1 } else { duration = 1 } distance = Int((Date().timeIntervalSinceReferenceDate - startDate.timeIntervalSinceReferenceDate) / Double(24 * 60 * 60)) WPAnalytics.track(configuration.filterbarSelectRange, properties: ["duration": duration, "distance": distance]) } } // MARK: - Activity type filter handling extension BaseActivityListViewController: ActivityTypeSelectorDelegate { func didCancel(selectorViewController: ActivityTypeSelectorViewController) { selectorViewController.dismiss(animated: true, completion: nil) } func didSelect(selectorViewController: ActivityTypeSelectorViewController, groups: [ActivityGroup]) { guard groups != viewModel.selectedGroups else { selectorViewController.dismiss(animated: true, completion: nil) return } trackSelectedGroups(groups) viewModel.refresh(after: viewModel.after, before: viewModel.before, group: groups) selectorViewController.dismiss(animated: true, completion: nil) } private func trackSelectedGroups(_ selectedGroups: [ActivityGroup]) { if !viewModel.selectedGroups.isEmpty && selectedGroups.isEmpty { WPAnalytics.track(.activitylogFilterbarResetType) } else { let totalActivitiesSelected = selectedGroups.map { $0.count }.reduce(0, +) var selectTypeProperties: [AnyHashable: Any] = [:] selectedGroups.forEach { selectTypeProperties["group_\($0.key)"] = true } selectTypeProperties["num_groups_selected"] = selectedGroups.count selectTypeProperties["num_total_activities_selected"] = totalActivitiesSelected WPAnalytics.track(.activitylogFilterbarSelectType, properties: selectTypeProperties) } } }
gpl-2.0
75ddce0edd331121708a993789d92621
36.330479
227
0.691757
5.627517
false
false
false
false
IslandJohn/TeamRadar
Swift/TeamRadar/AppDelegate.swift
1
13595
/* Copyright 2016 IslandJohn and the TeamRadar Authors 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 Cocoa import Foundation @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate, NSSeguePerforming, NSUserNotificationCenterDelegate { @IBOutlet weak var statusItemMenu: NSMenu! @IBOutlet weak var statusItemMenuConnectItem: NSMenuItem! @IBOutlet weak var statusItemMenuStateItem: NSMenuItem! @IBOutlet weak var segueConnectMenuItem: NSMenuItem! var statusItem: NSStatusItem? = nil var goTask: NSTask? = nil var teamRadarParser = TeamRadarParser() func applicationDidFinishLaunching(aNotification: NSNotification) { statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(NSVariableStatusItemLength) statusItem?.title = statusItemMenu.title statusItem?.highlightMode = true statusItem?.menu = statusItemMenu } func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool { return true } func prepareForSegue(segue: NSStoryboardSegue, sender: AnyObject?) { let vc = segue.destinationController as! ViewController vc.prefSaveButtonTitle = segue.identifier! if (segue.identifier == "Connect") { vc.prefSaveButtonMenuItem = statusItemMenuConnectItem } else { vc.prefSaveButtonMenuItem = nil } } func eventTaskOutput(note: NSNotification) { let fh = note.object as! NSFileHandle let data = fh.availableData if data.length > 0 { if let str = NSString(data: data, encoding: NSUTF8StringEncoding) { let lines = str.componentsSeparatedByString("\n") if(lines.count > 0) { for (_,line) in lines.enumerate() { let json = self.teamRadarParser.extractJSONFromLine(line) guard json != "" else { continue } let jsonDict = self.teamRadarParser.convertJSONStringToDictionary(json) guard let jDict = jsonDict else { continue } guard jDict is NSDictionary else { continue } if let content = jDict["Content"] where content != nil { showNotification(content as! String) } } } } } fh.waitForDataInBackgroundAndNotify() } func eventTaskError(note: NSNotification) { let fh = note.object as! NSFileHandle fh.waitForDataInBackgroundAndNotify() } func eventTaskTerminate() { connectAction(statusItemMenuConnectItem) } @IBAction func connectAction(sender: AnyObject) { let menuitem = sender as? NSMenuItem if let url = Settings.get(SettingsKey.URL) where url != "", let user = Settings.get(SettingsKey.USER) where user != "", let password = Settings.get(SettingsKey.PASSWORD) where password != "" { if (goTask == nil) { goTask = NSTask() goTask!.launchPath = NSBundle.mainBundle().pathForResource("teamradar", ofType: nil) goTask?.arguments = [url, user, password] goTask!.standardInput = NSPipe() goTask!.standardOutput = NSPipe() goTask!.standardError = NSPipe() goTask?.terminationHandler = {(task: NSTask) -> Void in self.eventTaskTerminate() } NSNotificationCenter.defaultCenter().addObserver(self, selector: "eventTaskOutput:", name: NSFileHandleDataAvailableNotification, object: goTask!.standardOutput?.fileHandleForReading) NSNotificationCenter.defaultCenter().addObserver(self, selector: "eventTaskError:", name: NSFileHandleDataAvailableNotification, object: goTask!.standardError?.fileHandleForReading) goTask!.standardOutput?.fileHandleForReading.waitForDataInBackgroundAndNotify() goTask!.standardError?.fileHandleForReading.waitForDataInBackgroundAndNotify() goTask?.launch() menuitem?.title = "Disconnect" statusItemMenuStateItem.title = "No rooms." } else { if (goTask!.running) { // trigger termination, but don't clean up yet goTask?.terminate() } else { // this is being called from the terminate event, so clean up goTask = nil menuitem?.title = "Connect..." statusItemMenuStateItem.title = "Not connected." } } } else { // some hackery to show the preferences dialog via a segue if things are not set up segueConnectMenuItem.menu?.performActionForItemAtIndex((segueConnectMenuItem.menu?.indexOfItem(segueConnectMenuItem))!) } } func applicationWillTerminate(aNotification: NSNotification) { // Insert code here to tear down your application } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.islandjohn.TeamRadar" in the user's Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.ApplicationSupportDirectory, inDomains: .UserDomainMask) let appSupportURL = urls[urls.count - 1] return appSupportURL.URLByAppendingPathComponent("com.islandjohn.TeamRadar") }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("TeamRadar", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. (The directory for the store is created, if necessary.) This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. let fileManager = NSFileManager.defaultManager() var failError: NSError? = nil var shouldFail = false var failureReason = "There was an error creating or loading the application's saved data." // Make sure the application files directory is there do { let properties = try self.applicationDocumentsDirectory.resourceValuesForKeys([NSURLIsDirectoryKey]) if !properties[NSURLIsDirectoryKey]!.boolValue { failureReason = "Expected a folder to store application data, found a file \(self.applicationDocumentsDirectory.path)." shouldFail = true } } catch { let nserror = error as NSError if nserror.code == NSFileReadNoSuchFileError { do { try fileManager.createDirectoryAtPath(self.applicationDocumentsDirectory.path!, withIntermediateDirectories: true, attributes: nil) } catch { failError = nserror } } else { failError = nserror } } // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = nil if failError == nil { coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("CocoaAppCD.storedata") do { try coordinator!.addPersistentStoreWithType(NSXMLStoreType, configuration: nil, URL: url, options: nil) } catch { failError = error as NSError } } if shouldFail || (failError != nil) { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason if failError != nil { dict[NSUnderlyingErrorKey] = failError } let error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) NSApplication.sharedApplication().presentError(error) abort() } else { return coordinator! } }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving and Undo support @IBAction func saveAction(sender: AnyObject!) { // Performs the save action for the application, which is to send the save: message to the application's managed object context. Any encountered errors are presented to the user. if !managedObjectContext.commitEditing() { NSLog("\(NSStringFromClass(self.dynamicType)) unable to commit editing before saving") } if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { let nserror = error as NSError NSApplication.sharedApplication().presentError(nserror) } } } func windowWillReturnUndoManager(window: NSWindow) -> NSUndoManager? { // Returns the NSUndoManager for the application. In this case, the manager returned is that of the managed object context for the application. return managedObjectContext.undoManager } func applicationShouldTerminate(sender: NSApplication) -> NSApplicationTerminateReply { // Save changes in the application's managed object context before the application terminates. if !managedObjectContext.commitEditing() { NSLog("\(NSStringFromClass(self.dynamicType)) unable to commit editing to terminate") return .TerminateCancel } if !managedObjectContext.hasChanges { return .TerminateNow } do { try managedObjectContext.save() } catch { let nserror = error as NSError // Customize this code block to include application-specific recovery steps. let result = sender.presentError(nserror) if (result) { return .TerminateCancel } let question = NSLocalizedString("Could not save changes while quitting. Quit anyway?", comment: "Quit without saves error question message") let info = NSLocalizedString("Quitting now will lose any changes you have made since the last successful save", comment: "Quit without saves error question info"); let quitButton = NSLocalizedString("Quit anyway", comment: "Quit anyway button title") let cancelButton = NSLocalizedString("Cancel", comment: "Cancel button title") let alert = NSAlert() alert.messageText = question alert.informativeText = info alert.addButtonWithTitle(quitButton) alert.addButtonWithTitle(cancelButton) let answer = alert.runModal() if answer == NSAlertFirstButtonReturn { return .TerminateCancel } } // If we got here, it is time to quit. return .TerminateNow } func showNotification(content:String) -> Void { let unc = NSUserNotificationCenter.defaultUserNotificationCenter() unc.delegate = self let notification = NSUserNotification() notification.title = "TeamRadar" notification.informativeText = content unc.deliverNotification(notification) } func userNotificationCenter(center: NSUserNotificationCenter, shouldPresentNotification notification: NSUserNotification) -> Bool { return true } }
apache-2.0
46f589fda7f70c792c59ed9d1d29f0d0
44.620805
347
0.633468
5.973199
false
false
false
false
jpedrosa/sua
examples/file_browsing/Sources/main.swift
1
1082
import Glibc import Sua import CSua var buf = stat() var hey: UnsafeMutablePointer<stat> p(buf.self) var i = stat("/home/dewd/t_/sample.txt", &buf) p("iiii \(i) \(buf)") var o = Sys.stat(path: "/home/dewd/t_/sample.txt", buffer: &buf) p("oooo \(o)") var h = Sys.lstat(path: "/home/dewd/t_/sample.txt", buffer: &buf) p("hhhh \(h)") p("exists: \(File.exists(path: "/home/dewd/t_/sample.txt"))") p("exists: \(File.exists(path: "/home/dewd/t_/nosample.txt"))") p(buf.st_dev) var sb = Stat() let _ = sb.stat(path: "/home/dewd/t_/sample.txt") p("\(sb.dev) \(sb.ino) \(sb.mode) \(sb.atime)") p(sb) var rd = Sys.opendir(path: "/home/dewd/t_") p(rd) p(rd.self) // OpaquePointer p(rd == nil) var gr = Sys.readdir(dirp: rd) while gr != nil { p(gr!.pointee) var dirName = gr!.pointee.d_name let name = withUnsafePointer(&dirName) { (ptr) -> String in return String(cString: UnsafePointer<CChar>(ptr)) ?? "" } p(name) gr = Sys.readdir(dirp: rd) } p(Sys.closedir(dirp: rd)) FileBrowser.recurseDir(path: "/home/dewd/t_") { (name, type, path) in p("\(path)\(name)") }
apache-2.0
7ba296b71a5a45ccf241ced744de1775
21.081633
69
0.620148
2.426009
false
false
false
false
wireapp/wire-ios-data-model
Tests/Source/Helper/BaseTestSwiftHelpers.swift
1
1706
// // Wire // Copyright (C) 2016 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import WireTesting func AssertKeyPathDictionaryHasOptionalValue<T: NSObject>( _ dictionary: @autoclosure () -> [WireDataModel.StringKeyPath: T?], key: @autoclosure () -> WireDataModel.StringKeyPath, expected: @autoclosure () -> T, _ message: String = "", file: StaticString = #file, line: UInt = #line) { if let v = dictionary()[key()] { AssertOptionalEqual(v, expression2: expected(), message, file: file, line: line) } else { XCTFail("No value for \(key()). \(message)", file: file, line: line) } } func AssertKeyPathDictionaryHasOptionalNilValue<T: NSObject>( _ dictionary: @autoclosure () -> [WireDataModel.StringKeyPath: T?], key: @autoclosure () -> WireDataModel.StringKeyPath, _ message: String = "", file: StaticString = #file, line: UInt = #line) { if let v = dictionary()[key()] { AssertOptionalNil(v, message, file: file, line: line) } else { XCTFail("No value for \(key()). \(message)", file: file, line: line) } }
gpl-3.0
6392482718d86a7cf3a29b084f18c55e
46.388889
285
0.690504
4.042654
false
false
false
false
ocadaruma/museswift
MuseSwift/Source/Render/SingleLineScore/SingleLineScoreUnit.swift
1
3061
import Foundation protocol RenderUnit { var allElements: [ScoreElement] { get } } extension RenderUnit { func renderToView(view: UIView) { for e in self.allElements { view.addSubview(e) } } func toNoteUnits() -> [NoteUnit] { var result = [NoteUnit]() switch self { case let n as NoteUnit: result.append(n) case let b as BeamUnit: result += b.noteUnits case let t as TupletUnit: result += t.units.flatMap({ u -> [NoteUnit] in switch u { case let n as NoteUnit: return [n] case let b as BeamUnit: return b.noteUnits case let t as TupletUnit: return t.toNoteUnits() default: return [] } }) default: break } return result } } class NoteUnit: RenderUnit { let dots: [EllipseElement] let noteHeads: [ScoreElement] let accidentals: [ScoreElement] let fillingStaff: [ScoreElement] let stem: RectElement? let flag: ScoreElement? let sparse: Bool let invert: Bool let xOffset: CGFloat let allElements: [ScoreElement] init( dots: [EllipseElement], noteHeads: [ScoreElement], accidentals: [ScoreElement], fillingStaff: [ScoreElement], stem: RectElement?, flag: ScoreElement?, sparse: Bool, invert: Bool, xOffset: CGFloat) { self.dots = dots self.noteHeads = noteHeads self.accidentals = accidentals self.fillingStaff = fillingStaff self.stem = stem self.flag = flag self.sparse = sparse self.invert = invert self.xOffset = xOffset var elements: [ScoreElement] = noteHeads + accidentals + fillingStaff + dots stem.foreach({elements.append($0)}) flag.foreach({elements.append($0)}) self.allElements = elements } } class RestUnit: RenderUnit { let dots: [EllipseElement] let restView: ScoreElement let xOffset: CGFloat let allElements: [ScoreElement] init( dots: [EllipseElement], restView: ScoreElement, xOffset: CGFloat) { self.dots = dots self.restView = restView self.xOffset = xOffset self.allElements = [restView] + dots } } class BeamUnit: RenderUnit { let noteUnits: [NoteUnit] let beams: [BeamElement] let invert: Bool let allElements: [ScoreElement] init( noteUnits: [NoteUnit], beams: [BeamElement], invert: Bool ) { self.noteUnits = noteUnits self.beams = beams self.invert = invert var elements = [ScoreElement]() elements += self.noteUnits.flatMap({$0.allElements}) self.allElements = elements + beams } } class TupletUnit: RenderUnit { let units: [RenderUnit] let bracket: BracketElement let invert: Bool let allElements: [ScoreElement] init( units: [RenderUnit], bracket: BracketElement, invert: Bool ) { self.units = units self.bracket = bracket self.invert = invert var elements = [ScoreElement]() elements += self.units.flatMap({$0.allElements}) elements.append(bracket) self.allElements = elements } }
mit
5f12d305c455f116e87270aa67c2a43f
21.188406
82
0.643254
3.855164
false
false
false
false
iMetalk/TCZKit
TCZKitDemo/TCZKit/Views/Cells/标题+紧挨标题的图标 TCZTitleNextToImageCell/TCZTitleNextToImageCell.swift
1
1622
// // TCZTitleNextToImageCell.swift // Dormouse // // Created by 武卓 on 2017/8/14. // Copyright © 2017年 WangSuyan. All rights reserved. // import UIKit import SnapKit class TCZTitleNextToImageCell: TCZBaseTableCell { /// Change icon size var iconSize: CGSize = CGSize.zero { didSet { rightImageView.snp.updateConstraints { (make) in make.width.equalTo(iconSize.width) make.height.equalTo(iconSize.height) } } } lazy var titleLabel: UILabel = { let label = UILabel.tczLabel() return label }() lazy var rightImageView :UIImageView = { let view = UIImageView.tczImageView() return view }() override func tczCreateBaseCellUI() { super.tczCreateBaseCellUI() contentView.addSubview(rightImageView) contentView.addSubview(titleLabel) titleLabel.snp.makeConstraints { (make) in make.left.equalToSuperview().offset(kLeftEdge) make.centerY.equalToSuperview() } rightImageView.snp.makeConstraints { (make) in make.left.equalTo(titleLabel.snp.right).offset(kItemSpace) make.width.equalTo(self.contentView.frame.height * 0.8) make.height.equalTo(self.contentView.frame.height * 0.8) make.centerY.equalToSuperview() } } override func tczConfigureData(aItem: TCZTableViewData) { titleLabel.text = aItem.title rightImageView.image = aItem.image } }
mit
11eb04b413b350c81f92b00706a5877b
25.47541
70
0.598762
4.511173
false
false
false
false
Stitch7/mclient
mclient/PrivateMessages/Chat/ChatViewController.swift
1
13808
// // ChatViewController.swift // mclient // // Copyright © 2014 - 2019 Christopher Reitz. Licensed under the MIT license. // See LICENSE file in the project root for full license information. // import Foundation import UIKit //import MessageKit //import MessageInputBar let primaryColor = UIColor(red: 230/255, green: 230/255, blue: 230/255, alpha: 1) // grey let secondaryColor = UIColor(red: 69/255, green: 193/255, blue: 89/255, alpha: 1) // green class ChatViewController: MessagesViewController, MessagesDataSource { var privateMessagesCache: PrivateMessagesCache? var existingprivateMessages = [PrivateMessage]() var observation : NSKeyValueObservation? @objc var bag: MCLDependencyBag? { didSet { self.privateMessagesCache = self.bag?.privateMessagesManager.privateMessagesCache } } @objc var conversation: MCLPrivateMessageConversation? { didSet { title = conversation?.username } } var queue: OperationQueue = { let queue = OperationQueue() queue.maxConcurrentOperationCount = 1 queue.name = "mclient.private-message-loading-queue" return queue }() // semaphore with count equal to zero is useful for synchronizing completion of work, in our case the renewal of auth token let semaphore = DispatchSemaphore(value: 0) lazy var me: Sender = { let name = bag?.loginManager.username ?? "" return Sender(id: name, displayName: name) }() override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } var messageList: [ChatMessage] = [] let refreshControl = UIRefreshControl() let formatter: DateFormatter = { let formatter = DateFormatter() formatter.dateStyle = .medium return formatter }() override func viewDidLoad() { super.viewDidLoad() configureMessageCollectionView() configureMessageInputBar() observation = queue.observe(\.operationCount, options: [.new]) { [unowned self] (queue, change) in guard let newValue = change.newValue, newValue == 0 else { return } self.addToChat(messages: self.existingprivateMessages.reversed()) self.observation = nil } loadExistingMessages() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if #available(iOS 11.0, *) { bag?.router.masterNavigationController.navigationBar.prefersLargeTitles = false navigationItem.largeTitleDisplayMode = .never } } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) // MockSocket.shared.disconnect() } @objc func profileButtonPressed(sender: UIBarButtonItem) { guard let username = conversation?.username else { return } let user = MCLUser() user.username = username let profileVC = self.bag?.router?.modalToProfile(from: user) profileVC?.showPrivateMessagesButton = false } private func addToChat(messages: [PrivateMessage]) { guard let conversation = self.conversation else { return } let chatMessages = messages.map { (message) -> ChatMessage in let type = ChatMessageType(rawValue: message.type) ?? .inbox let sender = message.type == "inbox" ? Sender(id: conversation.username, displayName: conversation.username) : self.me return ChatMessage(type: type, text: message.text, sender: sender, subject: message.subject, messageId: "String(message.messageId ?? 0)", // TODO date: message.date) } DispatchQueue.main.async { self.messageList.insert(contentsOf: chatMessages, at: 0) // self.messagesCollectionView.reloadDataAndKeepOffset() self.messagesCollectionView.reloadData() self.messagesCollectionView.scrollToBottom() if self.refreshControl.isRefreshing { self.refreshControl.endRefreshing() } } } @objc func loadExistingMessages() { guard let conversation = self.conversation, let messages = conversation.messages else { return } existingprivateMessages = [PrivateMessage]() for message in messages { guard let message = message as? PrivateMessage else { continue } guard let client = self.bag?.httpClient else { return } let operation = createOperation(message: message, client: client) if let lastOperation = queue.operations.last { operation.addDependency(lastOperation) // print("\(operation.name!) should finish after \(operation.dependencies.first!.name!)") } queue.addOperation(operation) } } func createOperation(message: PrivateMessage, client: MCLHTTPClient) -> BlockOperation { return BlockOperation { // print("Operation #\(message.messageId ?? 0) started") self.privateMessagesCache?.load(privateMessage: message) { (cachedMessage) in if let message = cachedMessage { self.existingprivateMessages.append(message) // self.addToChat(message: message) // print("Operation #\(message.messageId ?? 0) finished from CACHE") } else { MCLPrivateMessageRequest(client: client, privateMessage: message)?.load(completionHandler: { (err, data) in if let arr = data as? Array<Dictionary<String, String>>, let text = arr.first?["text"] { message.isRead = true message.text = text // self.addToChat(message: message) self.existingprivateMessages.append(message) self.privateMessagesCache?.store(privateMessage: message) // print("Operation #\(message.messageId ?? 0) finished from REQUEST") } self.semaphore.signal() }) _ = self.semaphore.wait(timeout: .distantFuture) } } } } @objc func refresh() { } func configureMessageCollectionView() { messagesCollectionView.backgroundColor = bag?.themeManager.currentTheme.backgroundColor() messagesCollectionView.messagesDataSource = self messagesCollectionView.messageCellDelegate = self scrollsToBottomOnKeyboardBeginsEditing = true // default false maintainPositionOnKeyboardFrameChanged = true // default false messagesCollectionView.addSubview(refreshControl) refreshControl.addTarget(self, action: #selector(refresh), for: .valueChanged) } func configureMessageInputBar() { messageInputBar.delegate = self // messageInputBar.inputTextView.tintColor = primaryColor messageInputBar.sendButton.tintColor = primaryColor messageInputBar.backgroundView.backgroundColor = bag?.themeManager.currentTheme.tableViewCellBackgroundColor() messageInputBar.inputTextView.keyboardAppearance = bag?.themeManager.currentTheme.isDark() ?? true ? .dark : .light } // MARK: - Helpers func insertMessage(_ message: ChatMessage) { messageList.append(message) // Reload last section to update header/footer labels and insert a new one messagesCollectionView.performBatchUpdates({ messagesCollectionView.insertSections([messageList.count - 1]) if messageList.count >= 2 { messagesCollectionView.reloadSections([messageList.count - 2]) } }, completion: { [weak self] _ in if self?.isLastSectionVisible() == true { self?.messagesCollectionView.scrollToBottom(animated: true) } let newPm = MCLPrivateMessage() if case .text(let textVal) = message.kind { print(textVal) newPm.text = textVal } MCLPrivateMessageSendRequest(client: self?.bag?.httpClient, privateMessage: newPm)?.load(completionHandler: { (error, data) in // guard let arr = data as? Array<Dictionary<String, String>>, let text = arr.first?["text"] else { return } }) }) } func isLastSectionVisible() -> Bool { guard !messageList.isEmpty else { return false } let lastIndexPath = IndexPath(item: 0, section: messageList.count - 1) return messagesCollectionView.indexPathsForVisibleItems.contains(lastIndexPath) } // MARK: - MessagesDataSource func currentSender() -> Sender { return me } func isFromCurrentSender(message: MessageType) -> Bool { guard let mockMessage = message as? ChatMessage else { return false } return mockMessage.type == .outbox } func numberOfSections(in messagesCollectionView: MessagesCollectionView) -> Int { return messageList.count } func messageForItem(at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> MessageType { return messageList[indexPath.section] } func cellTopLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? { if indexPath.section % 3 == 0 { let attrs = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 10), NSAttributedString.Key.foregroundColor: UIColor.darkGray] return NSAttributedString(string: MessageKitDateFormatter.shared.string(from: message.sentDate), attributes: attrs) } return nil } func messageTopLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? { guard let chatMessage = message as? ChatMessage else { return nil } let attr = [NSAttributedString.Key.font: UIFont.preferredFont(forTextStyle: .caption1), NSAttributedString.Key.foregroundColor: bag?.themeManager.currentTheme.textColor() ?? UIColor.black] return NSAttributedString(string: chatMessage.subject, attributes: attr) } func messageBottomLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? { let dateString = formatter.string(from: message.sentDate) let attr = [NSAttributedString.Key.font: UIFont.preferredFont(forTextStyle: .caption2), NSAttributedString.Key.foregroundColor: bag?.themeManager.currentTheme.textColor() ?? UIColor.black] return NSAttributedString(string: dateString, attributes: attr) } } // MARK: - MessageCellDelegate extension ChatViewController: MessageCellDelegate { func didTapAvatar(in cell: MessageCollectionViewCell) { guard let indexPath = messagesCollectionView.indexPath(for: cell), let messagesDataSource = messagesCollectionView.messagesDataSource else { return } let user = MCLUser() let message = messagesDataSource.messageForItem(at: indexPath, in: messagesCollectionView) user.username = message.sender.displayName let profileVC = self.bag?.router?.modalToProfile(from: user) profileVC?.showPrivateMessagesButton = false } func didTapMessage(in cell: MessageCollectionViewCell) { print("Message tapped") } func didTapCellTopLabel(in cell: MessageCollectionViewCell) { print("Top cell label tapped") } func didTapMessageTopLabel(in cell: MessageCollectionViewCell) { print("Top message label tapped") } func didTapMessageBottomLabel(in cell: MessageCollectionViewCell) { print("Bottom label tapped") } func didTapAccessoryView(in cell: MessageCollectionViewCell) { print("Accessory view tapped") } } // MARK: - MessageLabelDelegate extension ChatViewController: MessageLabelDelegate { func didSelectAddress(_ addressComponents: [String: String]) { print("Address Selected: \(addressComponents)") } func didSelectDate(_ date: Date) { print("Date Selected: \(date)") } func didSelectPhoneNumber(_ phoneNumber: String) { print("Phone Number Selected: \(phoneNumber)") } func didSelectURL(_ url: URL) { print("URL Selected: \(url)") } func didSelectTransitInformation(_ transitInformation: [String: String]) { print("TransitInformation Selected: \(transitInformation)") } } // MARK: - MessageInputBarDelegate extension ChatViewController: MessageInputBarDelegate { func messageInputBar(_ inputBar: MessageInputBar, didPressSendButtonWith text: String) { for component in inputBar.inputTextView.components { let messageId = UUID().uuidString let currentDate = Date() if let str = component as? String { let message = ChatMessage(type: .outbox, text: str, sender: me, subject: String(str.prefix(10)), messageId: messageId, date: currentDate) insertMessage(message) } else if let img = component as? UIImage { let message = ChatMessage(type: .outbox, image: img, sender: me, subject: "", messageId: messageId, date: currentDate) insertMessage(message) } } inputBar.inputTextView.text = "" messagesCollectionView.scrollToBottom(animated: true) } }
mit
a5d7567f64feb420ebda084293bd4210
36.417344
153
0.641196
5.222012
false
false
false
false
mindz-eye/MYTableViewIndex
Example/MYTableViewIndex/CollectionViewController.swift
1
3545
// // CollectionViewController.swift // MYTableViewIndex // // Created by Makarov Yury on 24/06/2017. // Copyright © 2017 Makarov Yury. All rights reserved. // import UIKit import MYTableViewIndex class CollectionHeader : UICollectionReusableView { @IBOutlet weak var titleLabel: UILabel! } class CollectionViewController : UICollectionViewController, UICollectionViewDelegateFlowLayout, TableViewIndexDelegate, ExampleContainer { var example: Example! fileprivate var dataSource: DataSource! fileprivate var tableViewIndexController: TableViewIndexController! override func viewDidLoad() { super.viewDidLoad() dataSource = example.dataSource tableViewIndexController = TableViewIndexController(scrollView: collectionView!) tableViewIndexController.tableViewIndex.delegate = self example.setupTableIndexController(tableViewIndexController) let layout = collectionView!.collectionViewLayout as! UICollectionViewFlowLayout layout.headerReferenceSize = CGSize(width: view.bounds.size.width, height: 30) layout.itemSize = CGSize(width: view.bounds.size.width, height: 44) } // MARK: - UICollectionView override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return dataSource.numberOfItemsInSection(section) } override func numberOfSections(in collectionView: UICollectionView) -> Int { return dataSource.numberOfSections() } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CollectionCell if let item = dataSource.itemAtIndexPath(indexPath) { cell.setupWithItem(item) } return cell } override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "Header", for: indexPath) as! CollectionHeader header.titleLabel.text = dataSource.titleForHeaderInSection(indexPath.section) return header } // MARK: - TableViewIndex func tableViewIndex(_ tableViewIndex: TableViewIndex, didSelect item: UIView, at index: Int) -> Bool { let sectionIndex = example.mapIndexItemToSection(item, index: index) if sectionIndex == NSNotFound { return false } guard let collectionView = collectionView else { return false; } let indexPath = IndexPath(row: 0, section: sectionIndex) guard let attrs = collectionView.layoutAttributesForSupplementaryElement(ofKind: UICollectionView.elementKindSectionHeader, at: indexPath) else { return false } var contentInset: UIEdgeInsets if #available(iOS 11.0, *) { contentInset = collectionView.adjustedContentInset } else { contentInset = collectionView.contentInset } let yOffset = min(attrs.frame.origin.y, collectionView.contentSize.height - collectionView.frame.height + contentInset.top) collectionView.contentOffset = CGPoint(x: 0, y: yOffset - contentInset.top) return true } }
mit
c74c20ce049ae21e7c07808227ed5091
38.820225
171
0.701749
5.906667
false
false
false
false
Neft-io/neft
packages/neft-input/native/ios/TextInputItem.swift
1
4332
import UIKit extension Extension.Input { class TextInputItem: NativeItem { override class var name: String { return "TextInput" } override class func register() { onCreate() { return TextInputItem() } onSet("text") { (item: TextInputItem, val: String) in item.fieldView.text = val } onSet("textColor") { (item: TextInputItem, val: UIColor?) in item.fieldView.textColor = val } onSet("placeholder") { (item: TextInputItem, val: String) in item.placeholder = val } onSet("placeholderColor") { (item: TextInputItem, val: UIColor?) in item.placeholderColor = val } onSet("keyboardType") { (item: TextInputItem, val: String) in item.fieldView.keyboardType = keyboardTypes[val] ?? UIKeyboardType.default } onSet("multiline") { (item: TextInputItem, val: Bool) in // TODO } onSet("returnKeyType") { (item: TextInputItem, val: String) in item.fieldView.returnKeyType = returnKeyTypes[val] ?? UIReturnKeyType.default } onSet("secureTextEntry") { (item: TextInputItem, val: Bool) in item.fieldView.isSecureTextEntry = val } onCall("focus") { (item: TextInputItem, args: [Any?]) in item.fieldView.becomeFirstResponder() } } static let keyboardTypes: [String: UIKeyboardType] = [ "text": .default, "numeric": .decimalPad, "email": .emailAddress, "tel": .phonePad ] static let returnKeyTypes: [String: UIReturnKeyType] = [ "done": UIReturnKeyType.done, "go": UIReturnKeyType.go, "next": UIReturnKeyType.next, "search": UIReturnKeyType.search, "send": UIReturnKeyType.send ] var fieldView: UITextField { return itemView as! UITextField } var placeholder: String = "" { didSet { updatePlaceholder() } } var placeholderColor: UIColor? { didSet { updatePlaceholder() } } init() { super.init(itemView: UITextField()) fieldView.addTarget(self, action: #selector(onTextChange(textField:)), for: UIControl.Event.editingChanged) fieldView.addTarget(self, action: #selector(onExit(textField:)), for: UIControl.Event.editingDidEndOnExit) fieldView.borderStyle = .none fieldView.frame.size.width = 250 fieldView.frame.size.height = 30 fieldView.frame = fieldView.frame NotificationCenter.default.addObserver(self, selector: #selector(didBeginEditing(_:)), name: UITextField.textDidBeginEditingNotification, object: fieldView) NotificationCenter.default.addObserver(self, selector: #selector(didEndEditing(_:)), name: UITextField.textDidEndEditingNotification, object: fieldView) } private func updatePlaceholder() { if placeholderColor == nil { fieldView.placeholder = placeholder } else { let attrs = NSAttributedString(string: placeholder, attributes: [NSAttributedString.Key.foregroundColor: placeholderColor!]) fieldView.attributedPlaceholder = attrs } } @objc private func onTextChange(textField: UITextField) { pushEvent(event: "textChange", args: [textField.text ?? ""]) } @objc private func onExit(textField: UITextField) { App.app.client.pushAction(OutAction.keyRelease, "Enter") } @objc private func didBeginEditing(_ notification: Notification) { focused = true } @objc private func didEndEditing(_ notification: Notification) { focused = false } } }
apache-2.0
12a276ba5e39a02d9563dec38c73a493
31.571429
168
0.536473
5.490494
false
false
false
false
kevinvanderlugt/Exercism-Solutions
swift/nucleotide-count/DNA.swift
2
1112
import Foundation struct DNA { private let allNucleotides = ["A", "T", "C", "G"] private var strand: String var nucleotideCounts: [String: Int] { var nucleotides = [String: Int]() allNucleotides.map { nucleotides[$0] = 0 } for (index, nucleotide) in enumerate(strand) { let nucleotideString = String(nucleotide) nucleotides[nucleotideString] = (nucleotides[nucleotideString] ?? 0) + 1 } return nucleotides } static func withStrand(strand: String) -> DNA? { return DNA(strand: strand) } init?(strand: String) { self.strand = strand if(!validStrand(strand)) { return nil } } func validStrand(strand: String) -> Bool { let validCharacters = NSCharacterSet(charactersInString: join("", allNucleotides)) return nil == strand.uppercaseString.rangeOfCharacterFromSet(validCharacters.invertedSet) } func count(matchingStrand: String) -> Int? { return nucleotideCounts[matchingStrand] } }
mit
4abadab7df344d8cfaebfa03904de9be
27.538462
97
0.594424
3.756757
false
false
false
false
joemcbride/outlander-osx
src/Outlander/GameServer2.swift
1
2439
// // GameServer2.swift // Outlander // // Created by Joseph McBride on 3/21/15. // Copyright (c) 2015 Joe McBride. All rights reserved. // import Foundation public class Connection : NSObject, NSStreamDelegate { private var inputStream: NSInputStream? private var outputStream: NSOutputStream? func connect(host:String, port:Int) { print("connecting...") NSStream.getStreamsToHostWithName(host, port: port, inputStream: &inputStream, outputStream: &outputStream) self.inputStream?.delegate = self self.outputStream?.delegate = self self.inputStream?.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) self.outputStream?.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) self.inputStream?.open() self.outputStream?.open() } public func writeData(str:String) { let test = str + "\r\n" print("writing: \(test)") let data = test.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! self.outputStream?.write(UnsafePointer<UInt8>(data.bytes), maxLength: data.length) } public func stream(stream: NSStream, handleEvent eventCode: NSStreamEvent) { print("stream event: \(eventCode)") switch(eventCode) { case NSStreamEvent.OpenCompleted: print("Stream opened") case NSStreamEvent.HasBytesAvailable: print("bytes") readBytes(stream) case NSStreamEvent.ErrorOccurred: print("error") case NSStreamEvent.EndEncountered: print("end") stream.close() stream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) default: print("unknown event!") } } private func readBytes(theStream:NSStream){ if (theStream == inputStream) { var buffer = [UInt8](count: 1024, repeatedValue: 0) while inputStream!.hasBytesAvailable { let length = inputStream!.read(&buffer, maxLength: buffer.count) if(length > 0) { let data = NSString(bytes: buffer, length: length, encoding: NSUTF8StringEncoding) print("recieved data: \(data)") } } } } }
mit
12aa776e02106995ff60822318c91d49
32.888889
115
0.608856
5.167373
false
false
false
false
njdehoog/Spelt
SpeltTests/SiteBuilderTests.swift
1
3414
import XCTest @testable import SpeltKit class SiteBuilderTests: XCTestCase { var buildPath: String { return sampleProjectPath.stringByAppendingPathComponent("_build") } lazy var site: Site = { [unowned self] in return try! SiteReader(sitePath: self.sampleProjectPath).read() }() var siteBuilder: SiteBuilder? override func setUp() { super.setUp() // render site before building try! SiteRenderer(site: site).render() siteBuilder = SiteBuilder(site: site, buildPath: buildPath) } func testThatBuildDirectoryIsRemoved() { // create test file in build directory to check if it is removed by build command try! FileManager().createDirectory(atPath: buildPath, withIntermediateDirectories: true, attributes: nil) let testFilePath = buildPath.stringByAppendingPathComponent("test.txt") try! "hello world".write(toFile: testFilePath, atomically: true, encoding: String.Encoding.utf8) try! siteBuilder?.build() XCTAssertFalse(FileManager().fileExists(atPath: testFilePath)) } func testThatBuildDirectoryIsCreated() { try! siteBuilder?.build() XCTAssertTrue(FileManager().fileExists(atPath: buildPath)) } func testThatStaticFileIsCopied() { try! siteBuilder?.build() let staticHTMLFile = site.staticFiles.filter({ $0.fileName == "static.html" }).first! let filePath = buildPath.stringByAppendingPathComponent(staticHTMLFile.destinationPath!) XCTAssertTrue(FileManager().fileExists(atPath: filePath)) } func testThatStaticFileIsCopiedToSubfolder() { try! siteBuilder?.build() let peacockImageFile = site.staticFiles.filter({ $0.fileName == "peacock.jpeg" }).first! let filePath = buildPath.stringByAppendingPathComponent(peacockImageFile.destinationPath!) XCTAssertTrue(FileManager().fileExists(atPath: filePath)) } func testThatDocumentIsWritten() { try! siteBuilder?.build() let aboutPage = site.documents.filter({ $0.fileName == "about.md" }).first! let filePath = buildPath.stringByAppendingPathComponent(aboutPage.destinationPath!) XCTAssertTrue(FileManager().fileExists(atPath: filePath)) } func testThatDocumentIsWrittenToSubfolder() { try! siteBuilder?.build() let aboutPage = site.documents.filter({ $0.fileName == "info.html" }).first! let filePath = buildPath.stringByAppendingPathComponent(aboutPage.destinationPath!) XCTAssertTrue(FileManager().fileExists(atPath: filePath)) } func testThatPostIsWritten() { try! siteBuilder?.build() let markdownPost = site.posts.filter({ $0.fileName == "markdown.md" }).first! let filePath = buildPath.stringByAppendingPathComponent(markdownPost.destinationPath!) XCTAssertTrue(FileManager().fileExists(atPath: filePath)) } func testThatPostContentIsCorrectlyWritten() { try! siteBuilder?.build() let markdownPost = site.posts.filter({ $0.fileName == "markdown.md" }).first! let filePath = buildPath.stringByAppendingPathComponent(markdownPost.destinationPath!) XCTAssertEqual(markdownPost.contents, try? String(contentsOfFile: filePath)) } }
mit
57b5ab812eccc6929cb31e236dd2bc70
38.697674
113
0.673697
5.065282
false
true
false
false
stripysock/SwiftGen
Pods/Stencil/Stencil/Variable.swift
1
2774
import Foundation class FilterExpression : Resolvable { let filters: [Filter] let variable: Variable init(token: String, parser: TokenParser) throws { let bits = token.componentsSeparatedByString("|") if bits.isEmpty { filters = [] variable = Variable("") throw TemplateSyntaxError("Variable tags must include at least 1 argument") } variable = Variable(bits[0]) let filterBits = bits[1 ..< bits.endIndex] do { filters = try filterBits.map { try parser.findFilter($0) } } catch { filters = [] throw error } } func resolve(context: Context) throws -> Any? { let result = try variable.resolve(context) return try filters.reduce(result) { x, y in return try y(x) } } } /// A structure used to represent a template variable, and to resolve it in a given context. public struct Variable : Equatable, Resolvable { public let variable:String /// Create a variable with a string representing the variable public init(_ variable:String) { self.variable = variable } private func lookup() -> [String] { return variable.componentsSeparatedByString(".") } /// Resolve the variable in the given context public func resolve(context:Context) throws -> Any? { var current: Any? = context if (variable.hasPrefix("'") && variable.hasSuffix("'")) || (variable.hasPrefix("\"") && variable.hasSuffix("\"")) { // String literal return variable[variable.startIndex.successor() ..< variable.endIndex.predecessor()] } for bit in lookup() { if let context = current as? Context { current = context[bit] } else if let dictionary = current as? [String: Any] { current = dictionary[bit] } else if let dictionary = current as? [String: AnyObject] { current = dictionary[bit] } else if let array = current as? [Any] { if let index = Int(bit) { current = array[index] } else if bit == "first" { current = array.first } else if bit == "last" { current = array.last } else if bit == "count" { current = array.count } } else if let array = current as? NSArray { if let index = Int(bit) { current = array[index] } else if bit == "first" { current = array.firstObject } else if bit == "last" { current = array.lastObject } else if bit == "count" { current = array.count } } else if let object = current as? NSObject { current = object.valueForKey(bit) } else { return nil } } return current } } public func ==(lhs:Variable, rhs:Variable) -> Bool { return lhs.variable == rhs.variable }
mit
9ee2f9e10cfa663e2b116e94a9ed19e8
27.306122
119
0.600937
4.314152
false
false
false
false
sschiau/swift
test/Constraints/keypath_dynamic_member_lookup.swift
2
14713
// RUN: %target-swift-frontend -emit-sil -verify %s | %FileCheck %s struct Point { let x: Int var y: Int } struct Rectangle { var topLeft, bottomRight: Point } @dynamicMemberLookup struct Lens<T> { var obj: T init(_ obj: T) { self.obj = obj } subscript<U>(dynamicMember member: KeyPath<T, U>) -> Lens<U> { get { return Lens<U>(obj[keyPath: member]) } } subscript<U>(dynamicMember member: WritableKeyPath<T, U>) -> Lens<U> { get { return Lens<U>(obj[keyPath: member]) } set { obj[keyPath: member] = newValue.obj } } // Used to make sure that keypath and string based lookup are // property disambiguated. subscript(dynamicMember member: String) -> Lens<Int> { return Lens<Int>(42) } } var topLeft = Point(x: 0, y: 0) var bottomRight = Point(x: 10, y: 10) var lens = Lens(Rectangle(topLeft: topLeft, bottomRight: bottomRight)) // CHECK: function_ref @$s29keypath_dynamic_member_lookup4LensV0B6MemberACyqd__Gs15WritableKeyPathCyxqd__G_tcluig // CHECK-NEXT: apply %45<Rectangle, Point>({{.*}}) // CHECK: function_ref @$s29keypath_dynamic_member_lookup4LensV0B6MemberACyqd__Gs7KeyPathCyxqd__G_tcluig // CHECK-NEXT: apply %54<Point, Int>({{.*}}) _ = lens.topLeft.x // CHECK: function_ref @$s29keypath_dynamic_member_lookup4LensV0B6MemberACyqd__Gs15WritableKeyPathCyxqd__G_tcluig // CHECK-NEXT: apply %69<Rectangle, Point>({{.*}}) // CHECK: function_ref @$s29keypath_dynamic_member_lookup4LensV0B6MemberACyqd__Gs15WritableKeyPathCyxqd__G_tcluig // CHECK-NEXT: apply %76<Point, Int>({{.*}}) _ = lens.topLeft.y lens.topLeft = Lens(Point(x: 1, y: 2)) // Ok lens.bottomRight.y = Lens(12) // Ok @dynamicMemberLookup class A<T> { var value: T init(_ v: T) { self.value = v } subscript<U>(dynamicMember member: KeyPath<T, U>) -> U { get { return value[keyPath: member] } } } // Let's make sure that keypath dynamic member lookup // works with inheritance class B<T> : A<T> {} func bar(_ b: B<Point>) { let _: Int = b.x let _ = b.y } struct Point3D { var x, y, z: Int } // Make sure that explicitly declared members take precedence class C<T> : A<T> { var x: Float = 42 } func baz(_ c: C<Point3D>) { // CHECK: ref_element_addr {{.*}} : $C<Point3D>, #C.x let _ = c.x // CHECK: [[Y:%.*]] = keypath $KeyPath<Point3D, Int>, (root $Point3D; stored_property #Point3D.z : $Int) // CHECK: [[KEYPATH:%.*]] = function_ref @$s29keypath_dynamic_member_lookup1AC0B6Memberqd__s7KeyPathCyxqd__G_tcluig // CHECK-NEXT: apply [[KEYPATH]]<Point3D, Int>({{.*}}, [[Y]], {{.*}}) let _ = c.z } @dynamicMemberLookup struct SubscriptLens<T> { var value: T subscript(foo: String) -> Int { get { return 42 } } subscript<U>(dynamicMember member: KeyPath<T, U>) -> U { get { return value[keyPath: member] } } subscript<U>(dynamicMember member: WritableKeyPath<T, U>) -> U { get { return value[keyPath: member] } set { value[keyPath: member] = newValue } } } func keypath_with_subscripts(_ arr: SubscriptLens<[Int]>, _ dict: inout SubscriptLens<[String: Int]>) { // CHECK: keypath $WritableKeyPath<Array<Int>, ArraySlice<Int>>, (root $Array<Int>; settable_property $ArraySlice<Int>, id @$sSays10ArraySliceVyxGSnySiGcig : {{.*}}) _ = arr[0..<3] // CHECK: keypath $KeyPath<Array<Int>, Int>, (root $Array<Int>; gettable_property $Int, id @$sSa5countSivg : {{.*}}) for idx in 0..<arr.count { // CHECK: keypath $WritableKeyPath<Array<Int>, Int>, (root $Array<Int>; settable_property $Int, id @$sSayxSicig : {{.*}}) let _ = arr[idx] // CHECK: keypath $WritableKeyPath<Array<Int>, Int>, (root $Array<Int>; settable_property $Int, id @$sSayxSicig : {{.*}}) print(arr[idx]) } // CHECK: function_ref @$s29keypath_dynamic_member_lookup13SubscriptLensVySiSScig _ = arr["hello"] // CHECK: function_ref @$s29keypath_dynamic_member_lookup13SubscriptLensVySiSScig _ = dict["hello"] if let index = dict.value.firstIndex(where: { $0.value == 42 }) { // CHECK: keypath $KeyPath<Dictionary<String, Int>, (key: String, value: Int)>, (root $Dictionary<String, Int>; gettable_property $(key: String, value: Int), id @$sSDyx3key_q_5valuetSD5IndexVyxq__Gcig : {{.*}}) let _ = dict[index] } // CHECK: keypath $WritableKeyPath<Dictionary<String, Int>, Optional<Int>>, (root $Dictionary<String, Int>; settable_property $Optional<Int>, id @$sSDyq_Sgxcig : {{.*}}) dict["ultimate question"] = 42 } struct DotStruct { var x, y: Int } class DotClass { var x, y: Int init(x: Int, y: Int) { self.x = x self.y = y } } @dynamicMemberLookup struct DotLens<T> { var value: T subscript<U>(dynamicMember member: WritableKeyPath<T, U>) -> U { get { return value[keyPath: member] } set { value[keyPath: member] = newValue } } subscript<U>(dynamicMember member: ReferenceWritableKeyPath<T, U>) -> U { get { return value[keyPath: member] } set { value[keyPath: member] = newValue } } } func dot_struct_test(_ lens: inout DotLens<DotStruct>) { // CHECK: keypath $WritableKeyPath<DotStruct, Int>, (root $DotStruct; stored_property #DotStruct.x : $Int) lens.x = 1 // CHECK: keypath $WritableKeyPath<DotStruct, Int>, (root $DotStruct; stored_property #DotStruct.y : $Int) let _ = lens.y } func dot_class_test(_ lens: inout DotLens<DotClass>) { // CHECK: keypath $ReferenceWritableKeyPath<DotClass, Int>, (root $DotClass; settable_property $Int, id #DotClass.x!getter.1 : (DotClass) -> () -> Int, getter @$s29keypath_dynamic_member_lookup8DotClassC1xSivpACTK : {{.*}}) lens.x = 1 // CHECK: keypath $ReferenceWritableKeyPath<DotClass, Int>, (root $DotClass; settable_property $Int, id #DotClass.y!getter.1 : (DotClass) -> () -> Int, getter @$s29keypath_dynamic_member_lookup8DotClassC1ySivpACTK : {{.*}}) let _ = lens.y } @dynamicMemberLookup struct OverloadedLens<T> { var value: T subscript<U>(keyPath: KeyPath<T, U>) -> U { get { return value[keyPath: keyPath] } } subscript<U>(dynamicMember keyPath: KeyPath<T, U>) -> U { get { return value[keyPath: keyPath] } } } // Make sure if there is a subscript which accepts key path, // existing dynamic member overloads wouldn't interfere. func test_direct_subscript_ref(_ lens: OverloadedLens<Point>) { // CHECK: function_ref @$s29keypath_dynamic_member_lookup14OverloadedLensVyqd__s7KeyPathCyxqd__Gcluig _ = lens[\.x] // CHECK: function_ref @$s29keypath_dynamic_member_lookup14OverloadedLensVyqd__s7KeyPathCyxqd__Gcluig _ = lens[\.y] // CHECK: function_ref @$s29keypath_dynamic_member_lookup14OverloadedLensV0B6Memberqd__s7KeyPathCyxqd__G_tcluig _ = lens.x // CHECK: function_ref @$s29keypath_dynamic_member_lookup14OverloadedLensV0B6Memberqd__s7KeyPathCyxqd__G_tcluig _ = lens.y } func test_keypath_dynamic_lookup_inside_keypath() { // CHECK: keypath $KeyPath<Point, Int>, (root $Point; stored_property #Point.x : $Int) // CHECK-NEXT: keypath $KeyPath<Lens<Point>, Lens<Int>>, (root $Lens<Point>; gettable_property $Lens<Int>, id @$s29keypath_dynamic_member_lookup4LensV0B6MemberACyqd__Gs7KeyPathCyxqd__G_tcluig : {{.*}}) _ = \Lens<Point>.x // CHECK: keypath $WritableKeyPath<Rectangle, Point>, (root $Rectangle; stored_property #Rectangle.topLeft : $Point) // CHECK-NEXT: keypath $WritableKeyPath<Point, Int>, (root $Point; stored_property #Point.y : $Int) // CHECK-NEXT: keypath $WritableKeyPath<Lens<Rectangle>, Lens<Int>>, (root $Lens<Rectangle>; settable_property $Lens<Point>, id @$s29keypath_dynamic_member_lookup4LensV0B6MemberACyqd__Gs15WritableKeyPathCyxqd__G_tcluig : {{.*}}) _ = \Lens<Rectangle>.topLeft.y // CHECK: keypath $KeyPath<Array<Int>, Int>, (root $Array<Int>; gettable_property $Int, id @$sSa5countSivg : {{.*}}) // CHECK-NEXT: keypath $KeyPath<Lens<Array<Int>>, Lens<Int>>, (root $Lens<Array<Int>>; gettable_property $Lens<Int>, id @$s29keypath_dynamic_member_lookup4LensV0B6MemberACyqd__Gs7KeyPathCyxqd__G_tcluig : {{.*}}) _ = \Lens<[Int]>.count // CHECK: keypath $WritableKeyPath<Array<Int>, Int>, (root $Array<Int>; settable_property $Int, id @$sSayxSicig : {{.*}}) // CHECK-NEXT: keypath $WritableKeyPath<Lens<Array<Int>>, Lens<Int>>, (root $Lens<Array<Int>>; settable_property $Lens<Int>, id @$s29keypath_dynamic_member_lookup4LensV0B6MemberACyqd__Gs15WritableKeyPathCyxqd__G_tcluig : {{.*}}) _ = \Lens<[Int]>.[0] // CHECK: keypath $WritableKeyPath<Array<Array<Int>>, Array<Int>>, (root $Array<Array<Int>>; settable_property $Array<Int>, id @$sSayxSicig : {{.*}}) // CHECK-NEXT: keypath $KeyPath<Array<Int>, Int>, (root $Array<Int>; gettable_property $Int, id @$sSa5countSivg : {{.*}}) // CHECK-NEXT: keypath $KeyPath<Lens<Array<Array<Int>>>, Lens<Int>>, (root $Lens<Array<Array<Int>>>; settable_property $Lens<Array<Int>>, id @$s29keypath_dynamic_member_lookup4LensV0B6MemberACyqd__Gs15WritableKeyPathCyxqd__G_tcluig : {{.*}}) _ = \Lens<[[Int]]>.[0].count } func test_recursive_dynamic_lookup(_ lens: Lens<Lens<Point>>) { // CHECK: keypath $KeyPath<Point, Int>, (root $Point; stored_property #Point.x : $Int) // CHECK-NEXT: keypath $KeyPath<Lens<Point>, Lens<Int>>, (root $Lens<Point>; gettable_property $Lens<Int>, id @$s29keypath_dynamic_member_lookup4LensV0B6MemberACyqd__Gs7KeyPathCyxqd__G_tcluig : {{.*}}) // CHECK: function_ref @$s29keypath_dynamic_member_lookup4LensV0B6MemberACyqd__Gs7KeyPathCyxqd__G_tcluig _ = lens.x // CHECK: keypath $KeyPath<Point, Int>, (root $Point; stored_property #Point.x : $Int) // CHECK: function_ref @$s29keypath_dynamic_member_lookup4LensV0B6MemberACyqd__Gs7KeyPathCyxqd__G_tcluig _ = lens.obj.x // CHECK: [[FIRST_OBJ:%.*]] = struct_extract {{.*}} : $Lens<Lens<Point>>, #Lens.obj // CHECK-NEXT: [[SECOND_OBJ:%.*]] = struct_extract [[FIRST_OBJ]] : $Lens<Point>, #Lens.obj // CHECK-NEXT: struct_extract [[SECOND_OBJ]] : $Point, #Point.y _ = lens.obj.obj.y // CHECK: keypath $KeyPath<Point, Int>, (root $Point; stored_property #Point.x : $Int) // CHECK-NEXT: keypath $KeyPath<Lens<Point>, Lens<Int>>, (root $Lens<Point>; gettable_property $Lens<Int>, id @$s29keypath_dynamic_member_lookup4LensV0B6MemberACyqd__Gs7KeyPathCyxqd__G_tcluig : {{.*}}) // CHECK-NEXT: keypath $KeyPath<Lens<Lens<Point>>, Lens<Lens<Int>>>, (root $Lens<Lens<Point>>; gettable_property $Lens<Lens<Int>>, id @$s29keypath_dynamic_member_lookup4LensV0B6MemberACyqd__Gs7KeyPathCyxqd__G_tcluig : {{.*}}) _ = \Lens<Lens<Point>>.x // CHECK: keypath $WritableKeyPath<Rectangle, Point>, (root $Rectangle; stored_property #Rectangle.topLeft : $Point) // CHECK-NEXT: keypath $WritableKeyPath<Lens<Rectangle>, Lens<Point>>, (root $Lens<Rectangle>; settable_property $Lens<Point>, id @$s29keypath_dynamic_member_lookup4LensV0B6MemberACyqd__Gs15WritableKeyPathCyxqd__G_tcluig : {{.*}}) // CHECK-NEXT: keypath $KeyPath<Point, Int>, (root $Point; stored_property #Point.x : $Int) // CHECK-NEXT: keypath $KeyPath<Lens<Point>, Lens<Int>>, (root $Lens<Point>; gettable_property $Lens<Int>, id @$s29keypath_dynamic_member_lookup4LensV0B6MemberACyqd__Gs7KeyPathCyxqd__G_tcluig : {{.*}}) // CHECK-NEXT: keypath $KeyPath<Lens<Lens<Rectangle>>, Lens<Lens<Int>>>, (root $Lens<Lens<Rectangle>>; settable_property $Lens<Lens<Point>>, id @$s29keypath_dynamic_member_lookup4LensV0B6MemberACyqd__Gs15WritableKeyPathCyxqd__G_tcluig : {{.*}}) _ = \Lens<Lens<Rectangle>>.topLeft.x } @dynamicMemberLookup struct RefWritableBox<T> { var obj: T init(_ obj: T) { self.obj = obj } subscript<U>(dynamicMember member: KeyPath<T, U>) -> U { get { return obj[keyPath: member] } } subscript<U>(dynamicMember member: ReferenceWritableKeyPath<T, U>) -> U { get { return obj[keyPath: member] } set { obj[keyPath: member] = newValue } } } func prefer_readonly_keypath_over_reference_writable() { class C { let foo: Int init(_ foo: Int) { self.foo = foo } } var box = RefWritableBox(C(42)) // expected-warning@-1 {{variable 'box' was never mutated; consider changing to 'let' constant}} // CHECK: function_ref RefWritableBox.subscript.getter // CHECK-NEXT: function_ref @$s29keypath_dynamic_member_lookup14RefWritableBoxV0B6Memberqd__s7KeyPathCyxqd__G_tcluig _ = box.foo } // rdar://problem/52779809 - condiitional conformance shadows names of members reachable through dynamic lookup protocol P { var foo: Int { get } } @dynamicMemberLookup struct Ref<T> { var value: T subscript<U>(dynamicMember member: KeyPath<T, U>) -> U { get { return value[keyPath: member] } } } extension P { var foo: Int { return 42 } } struct S { var foo: Int { return 0 } var baz: Int { return 1 } } struct Q { var bar: Int { return 1 } } extension Ref : P where T == Q { var baz: String { return "hello" } } func rdar52779809(_ ref1: Ref<S>, _ ref2: Ref<Q>) { // CHECK: function_ref @$s29keypath_dynamic_member_lookup3RefV0B6Memberqd__s7KeyPathCyxqd__G_tcluig _ = ref1.foo // Ok // CHECK: function_ref @$s29keypath_dynamic_member_lookup3RefV0B6Memberqd__s7KeyPathCyxqd__G_tcluig _ = ref1.baz // Ok // CHECK: function_ref @$s29keypath_dynamic_member_lookup1PPAAE3fooSivg _ = ref2.foo // Ok // CHECK: function_ref @$s29keypath_dynamic_member_lookup3RefV0B6Memberqd__s7KeyPathCyxqd__G_tcluig _ = ref2.bar // Ok } func make_sure_delayed_keypath_dynamic_member_works() { @propertyWrapper @dynamicMemberLookup struct Wrapper<T> { var storage: T? = nil var wrappedValue: T { get { storage! } } var projectedValue: Wrapper<T> { self } init() { } init(wrappedValue: T) { storage = wrappedValue } subscript<Property>(dynamicMember keyPath: KeyPath<T, Property>) -> Wrapper<Property> { get { .init() } } } struct Field { @Wrapper var v: Bool = true } struct Arr { var fields: [Field] = [] } struct Test { @Wrapper var data: Arr func test(_ index: Int) { let _ = self.$data.fields[index].v.wrappedValue } } } // SR-11465 - Ambiguity in expression which matches both dynamic member lookup and declaration from constrained extension @dynamicMemberLookup struct SR_11465<RawValue> { var rawValue: RawValue subscript<Subject>(dynamicMember keyPath: KeyPath<RawValue, Subject>) -> Subject { rawValue[keyPath: keyPath] } } extension SR_11465: Hashable, Equatable where RawValue: Hashable { func hash(into hasher: inout Hasher) { hasher.combine(self.rawValue) } } func test_constrained_ext_vs_dynamic_member() { // CHECK: function_ref @$s29keypath_dynamic_member_lookup8SR_11465VAASHRzlE9hashValueSivg _ = SR_11465<Int>(rawValue: 1).hashValue // Ok, keep choice from constrained extension }
apache-2.0
98b5216188804650c3e5c56c5c41d176
36.533163
247
0.675933
3.211744
false
false
false
false
KSU-Mobile-Dev-Club/Branching-Out-iOS
BranchingOut-iOS/MDCMapViewController.swift
1
5483
// // MDCMapViewController.swift // BranchingOut-iOS // // Created by Kevin Manase on 4/7/16. // Copyright © 2016 MDC. All rights reserved. // import UIKit import MapKit import CoreLocation class MDCMapViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate { @IBOutlet var mapView: OCMapView! let locationManager = CLLocationManager() var treeLocations: [PFObject]! = [] var myLocation: CLLocation! var location: CLLocation! override func viewDidLoad() { super.viewDidLoad() self.locationManager.delegate = self self.locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation self.locationManager.requestWhenInUseAuthorization() self.locationManager.startUpdatingLocation() self.mapView.delegate = self self.mapView.showsUserLocation = true self.mapView.clusteringEnabled = false myLocation = location } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MAR: - Location delegate methods func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let location = myLocation != nil ? myLocation : locations.last let center = CLLocationCoordinate2D(latitude: (location?.coordinate.latitude)!, longitude: (location?.coordinate.longitude)!) let region = MKCoordinateRegion(center: center, span: MKCoordinateSpanMake(0.04, 0.04)) // the smaller the bigger zoom self.mapView.setRegion(region, animated: true) self.locationManager.stopUpdatingLocation() self.addTreesNearby(location!) } func locationManager(manager: CLLocationManager, didFailWithError error: NSError) { print("Errors: " + error.localizedDescription) } func findTreesNearLocation(location: CLLocation, completion:(locations: [PFObject]) -> Void) { let geopoint = PFGeoPoint(location: location) var objectLocations: [PFObject]! = [] PFQuery(className: "trees").whereKey("cord", nearGeoPoint: geopoint, withinMiles: 1.0) .findObjectsInBackgroundWithBlock { (results: [PFObject]?, error: NSError?) -> Void in for location: PFObject in results! { objectLocations.append(location) } completion(locations: objectLocations) } } func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? { var annotationView: MKAnnotationView! // If not then get a group of trees if (annotation.isKindOfClass(OCSingleAnnotation)) { let singleAnnotation: OCSingleAnnotation = annotation as! OCSingleAnnotation annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier("singleAnnotationView") if ((annotationView == nil)) { annotationView = MKAnnotationView(annotation: singleAnnotation, reuseIdentifier: "singleAnnotationView") annotationView.canShowCallout = true annotationView.centerOffset = CGPointMake(0, 0) } singleAnnotation.title = singleAnnotation.groupTag annotationView.image = UIImage(named: "tree_pin") } else if (annotation.isKindOfClass(OCAnnotation)){ let clusterAnnotation: OCAnnotation = annotation as! OCAnnotation annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier("ClusterView") if ((annotationView == nil)) { annotationView = MKAnnotationView(annotation: clusterAnnotation, reuseIdentifier: "ClusterView") annotationView.canShowCallout = true annotationView.centerOffset = CGPointMake(0, -20) } clusterAnnotation.title = "Tree Groups" clusterAnnotation.subtitle = "Contains \(clusterAnnotation.annotationsInCluster().count) trees" annotationView.image = UIImage(named: "forest") } return annotationView } func addTreesNearby(treeLocation: CLLocation) { let annotationsToAdd: NSMutableSet = NSMutableSet() findTreesNearLocation(treeLocation) { (locations) -> Void in for treeObject: PFObject in locations { let descLocation = treeObject["cord"] as! PFGeoPoint let latitude: CLLocationDegrees = descLocation.latitude let longitude: CLLocationDegrees = descLocation.longitude let location: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) let treeName = treeObject["common"] as! String let scientific = treeObject["scientific"] as! String let center = CLLocationCoordinate2D(latitude: location.latitude, longitude: location.longitude) let annotation: OCSingleAnnotation = OCSingleAnnotation(coordinate: center) annotationsToAdd.addObject(annotation) annotation.groupTag = treeName annotation.title = treeName annotation.subtitle = scientific } self.mapView.addAnnotations(annotationsToAdd.allObjects as! [OCSingleAnnotation]) } } }
mit
033bf20611ba98d29faee911443391b4
42.165354
133
0.659066
5.716371
false
false
false
false
jopamer/swift
test/attr/attr_nonobjc.swift
1
3823
// RUN: %target-typecheck-verify-swift // REQUIRES: objc_interop import Foundation @objc class LightSaber { init() { caloriesBurned = 5 } @objc func defeatEnemy(_ b: Bool) -> Bool { // expected-note {{'defeatEnemy' previously declared here}} return !b } // Make sure we can overload a method with @nonobjc methods @nonobjc func defeatEnemy(_ i: Int) -> Bool { return (i > 0) } // This is not allowed, though @objc func defeatEnemy(_ s: String) -> Bool { // expected-error {{method 'defeatEnemy' with Objective-C selector 'defeatEnemy:' conflicts with previous declaration with the same Objective-C selector}} return s != "" } @nonobjc subscript(index: Int) -> Int { return index } @nonobjc var caloriesBurned: Float } class BlueLightSaber : LightSaber { @nonobjc override func defeatEnemy(_ b: Bool) -> Bool { } } @objc class InchoateToad { @objc init(x: Int) {} // expected-note {{previously declared}} @nonobjc init(x: Float) {} @objc init(x: String) {} // expected-error {{conflicts with previous declaration with the same Objective-C selector}} } @nonobjc class NonObjCClassNotAllowed { } // expected-error {{'@nonobjc' attribute cannot be applied to this declaration}} {{1-10=}} class NonObjCDeallocNotAllowed { @nonobjc deinit { // expected-error {{'@nonobjc' attribute cannot be applied to this declaration}} {{3-12=}} } } @objc protocol ObjCProtocol { func protocolMethod() // expected-note {{}} @nonobjc func nonObjCProtocolMethodNotAllowed() // expected-error {{declaration is a member of an @objc protocol, and cannot be marked @nonobjc}} @nonobjc subscript(index: Int) -> Int { get } // expected-error {{declaration is a member of an @objc protocol, and cannot be marked @nonobjc}} var surfaceArea: Float { @nonobjc get } // expected-error {{declaration is implicitly @objc, and cannot be marked @nonobjc}} var displacement: Float { get } } class SillyClass { @objc var description: String { @nonobjc get { return "" } } // expected-error {{declaration is implicitly @objc, and cannot be marked @nonobjc}} } class ObjCAndNonObjCNotAllowed { @objc @nonobjc func redundantAttributes() { } // expected-error {{declaration is marked @objc, and cannot be marked @nonobjc}} } class DynamicAndNonObjCNotAllowed { @nonobjc dynamic func redundantAttributes() { } // expected-error {{a declaration cannot be both '@nonobjc' and 'dynamic'}} } class IBOutletAndNonObjCNotAllowed { @nonobjc @IBOutlet var leeloo : String? = "Hello world" // expected-error {{declaration is marked @IBOutlet, and cannot be marked @nonobjc}} } class NSManagedAndNonObjCNotAllowed { @nonobjc @NSManaged var rosie : NSObject // expected-error {{declaration is marked @NSManaged, and cannot be marked @nonobjc}} } @nonobjc func nonObjCTopLevelFuncNotAllowed() { } // expected-error {{only class members and extensions of classes can be declared @nonobjc}} {{1-10=}} @objc class NonObjCPropertyObjCProtocolNotAllowed : ObjCProtocol { // expected-error {{does not conform to protocol}} @nonobjc func protocolMethod() { } // expected-note {{candidate is explicitly '@nonobjc'}} func nonObjCProtocolMethodNotAllowed() { } subscript(index: Int) -> Int { return index } var displacement: Float { @nonobjc get { // expected-error {{declaration is implicitly @objc, and cannot be marked @nonobjc}} return Float(self[10]) } } var surfaceArea: Float { get { return Float(100) } } } struct SomeStruct { } @nonobjc extension SomeStruct { } // expected-error{{only extensions of classes can be declared @nonobjc}} protocol SR4226_Protocol : class {} extension SR4226_Protocol { @nonobjc func function() {} // expected-error {{only class members and extensions of classes can be declared @nonobjc}} }
apache-2.0
306e6abb9cb2261c6265dc9641ada3e8
32.831858
202
0.707036
4.137446
false
false
false
false
Miguel-Herrero/Swift
Repohub/Repohub/ReposStore.swift
1
811
// // ReposStore.swift // Repohub // // Created by Miguel Herrero on 16/06/2019. // Copyright © 2019 Miguel Herrero. All rights reserved. // import SwiftUI import Combine class ReposStore: BindableObject { var repos: [Repo] = [] { didSet { didChange.send(self) } } var didChange = PassthroughSubject<ReposStore, Never>() let service: GithubService init(service: GithubService) { self.service = service } func fetch(matching query: String) { service.search(matching: query) { [weak self] result in DispatchQueue.main.async { switch result { case .success(let repos): self?.repos = repos case .failure: self?.repos = [] } } } } }
gpl-3.0
c6408c52e21f9ae656958ae108a1d9ec
20.891892
63
0.560494
4.285714
false
false
false
false
sarfraz-akhtar01/SPCalendar
SPCalendar/Classes/CVAuxiliaryView.swift
1
4195
// // CVAuxiliaryView.swift // CVCalendar Demo // // Created by Eugene Mozharovsky on 22/03/15. // Copyright (c) 2015 GameApp. All rights reserved. // import UIKit public final class CVAuxiliaryView: UIView { public var shape: CVShape! public var strokeColor: UIColor! { didSet { setNeedsDisplay() } } public var fillColor: UIColor! { didSet { setNeedsDisplay() } } public let defaultFillColor = UIColor.colorFromCode(0xe74c3c) fileprivate var radius: CGFloat { return (min(frame.height, frame.width) - 10) / 2 } public unowned let dayView: DayView public init(dayView: DayView, rect: CGRect, shape: CVShape) { self.dayView = dayView self.shape = shape super.init(frame: rect) strokeColor = UIColor.clear fillColor = UIColor.colorFromCode(0xe74c3c) layer.cornerRadius = 5 backgroundColor = .clear } public override func didMoveToSuperview() { setNeedsDisplay() } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override func draw(_ rect: CGRect) { var path: UIBezierPath! if let shape = shape { switch shape { case .rightFlag: path = rightFlagPath() case .leftFlag: path = leftFlagPath() case .circle: path = circlePath() case .rect: path = rectPath() case .custom(let customPathBlock): path = customPathBlock(rect) } switch shape { case .custom: break default: path.lineWidth = 1 } } strokeColor.setStroke() fillColor.setFill() if let path = path { path.stroke() path.fill() } } deinit { //println("[CVCalendar Recovery]: AuxiliaryView is deinited.") } } extension CVAuxiliaryView { public func updateFrame(_ frame: CGRect) { self.frame = frame setNeedsDisplay() } } extension CVAuxiliaryView { func circlePath() -> UIBezierPath { let arcCenter = CGPoint(x: frame.width / 2, y: frame.height / 2) let startAngle = CGFloat(0) let endAngle = CGFloat(M_PI * 2.0) let clockwise = true let path = UIBezierPath(arcCenter: arcCenter, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: clockwise) return path } func rightFlagPath() -> UIBezierPath { // let appearance = dayView.calendarView.appearance // let offset = appearance.spaceBetweenDayViews! let flag = UIBezierPath() flag.move(to: CGPoint(x: bounds.width / 2, y: bounds.height / 2 - radius)) flag.addLine(to: CGPoint(x: bounds.width, y: bounds.height / 2 - radius)) flag.addLine(to: CGPoint(x: bounds.width, y: bounds.height / 2 + radius )) flag.addLine(to: CGPoint(x: bounds.width / 2, y: bounds.height / 2 + radius)) let path = CGMutablePath() path.addPath(circlePath().cgPath) path.addPath(flag.cgPath) return UIBezierPath(cgPath: path) } func leftFlagPath() -> UIBezierPath { let flag = UIBezierPath() flag.move(to: CGPoint(x: bounds.width / 2, y: bounds.height / 2 + radius)) flag.addLine(to: CGPoint(x: 0, y: bounds.height / 2 + radius)) flag.addLine(to: CGPoint(x: 0, y: bounds.height / 2 - radius)) flag.addLine(to: CGPoint(x: bounds.width / 2, y: bounds.height / 2 - radius)) let path = CGMutablePath() path.addPath(circlePath().cgPath) path.addPath(flag.cgPath) return UIBezierPath(cgPath: path) } func rectPath() -> UIBezierPath { // let midX = bounds.width / 2 let midY = bounds.height / 2 let appearance = dayView.calendarView.appearance let offset = appearance?.spaceBetweenDayViews! let path = UIBezierPath(rect: CGRect(x: 0 - offset!, y: midY - radius, width: bounds.width + offset! / 2, height: radius * 2)) return path } }
mit
dacb81e81c1ff08e53414629534af7b1
27.537415
97
0.592372
4.338159
false
false
false
false
CaueAlvesSilva/FeaturedGames
FeaturedGames/FeaturedGames/Model/GameImages.swift
1
625
// // GameImages.swift // FeaturedGames // // Created by Cauê Silva on 01/08/17. // Copyright © 2017 Caue Alves. All rights reserved. // import Foundation import ObjectMapper struct GameImages: Mappable { var large = "" var medium = "" var small = "" var template = "" init?(map: Map) { mapping(map: map) } init() { } init(imageURL: String) { large = imageURL } mutating func mapping(map: Map) { large <- map["large"] medium <- map["medium"] small <- map["small"] template <- map["template"] } }
mit
07657821cb8f93f1aaec3e5e382ff8a1
16.305556
53
0.529695
3.869565
false
false
false
false
ckjavacoder/JSONExport
JSONExport/FileContentBuilder.swift
2
12352
// // FileGenerator.swift // JSONExport // // Created by Ahmed on 11/14/14. // Copyright (c) 2014 Ahmed Ali. All rights reserved. // import Foundation /** Singleton used to build the file content with the current configurations */ class FilesContentBuilder{ /** The prefix used for first level type names (and file names as well) */ var classPrefix = "" /** The language for which the files' content should be created */ var lang : LangModel! /** Whether to include utility methods in the generated content */ var includeUtilities = true /** Whether to include constructors (aka initializers) */ var includeConstructors = true /** Whatever value will be assinged to the firstLine property, will appear as the first line in every file if the target language supports first line statement */ var firstLine = "" /** If the target language supports inheritance, all the generated classes will be subclasses of this class */ var parentClassName = "" /** Lazely load and return the singleton instance of the FilesContentBuilder */ class var instance : FilesContentBuilder { struct Static { static var onceToken : dispatch_once_t = 0 static var instance : FilesContentBuilder? = nil } dispatch_once(&Static.onceToken) { Static.instance = FilesContentBuilder() } return Static.instance! } /** Generates a file using the passed className and jsonObject example and appends it in the passed files array :param: className for the file to be generated, if the file already exist with different name, this className will be changed :param: jsonObject acts as an example of the json object, which the generated fill be able to handle :param: files the generated file will be appended to this array */ func addFileWithName(inout className: String, jsonObject: NSDictionary, inout files : [FileRepresenter],toOneRelationWithProperty: Property! = nil) { var properties = [Property]() if !className.hasPrefix(classPrefix){ className = "\(classPrefix)\(className)" } if toOneRelationWithProperty != nil{ if lang.supportMutualRelationships != nil && lang.supportMutualRelationships!{ properties.append(toOneRelationWithProperty) } } //sort all the keys in the passed json dictionary var jsonProperties = sorted(jsonObject.allKeys as! [String]) //loop all the json properties and handle each one individually for jsonPropertyName in jsonProperties{ let value : AnyObject = jsonObject[jsonPropertyName]! let property = propertyForValue(value, jsonKeyName: jsonPropertyName) //recursively handle custom types if property.isCustomClass{ let rProperty = relationProperty(className) addFileWithName(&property.type, jsonObject: value as! NSDictionary, files:&files, toOneRelationWithProperty: rProperty) }else if property.isArray{ let array = value as! NSArray if array.firstObject is NSDictionary{ //complicated enough..... var type = typeNameForPropertyName(property.jsonName) let rProperty = relationProperty(className) let allProperties = unionDictionaryFromArrayElements(array); addFileWithName(&type, jsonObject: allProperties, files:&files, toOneRelationWithProperty: rProperty) } } properties.append(property) } //create the file let file = FileRepresenter(className: className, properties: properties, lang:lang) file.includeUtilities = includeUtilities file.includeConstructors = includeConstructors file.firstLine = firstLine file.parentClassName = parentClassName //TODO: - Check if this file already has similar file, if so merge. var exactMatchFound = false if let similarFile = findSimilarFile(file, inFiles: &files, exactMatchFound: &exactMatchFound){ //there is a similar file if !exactMatchFound{ //If the found file is no exact, then any additional properties to the alread exist file instead of creating new one mergeProperties(fromFile: file, toFile: similarFile) } className = similarFile.className }else{ files.append(file) if lang.headerFileData != nil{ //add header file first let headerFile = HeaderFileRepresenter(className: className, properties: properties, lang:lang) headerFile.includeUtilities = includeUtilities headerFile.includeConstructors = includeConstructors headerFile.parentClassName = parentClassName headerFile.firstLine = firstLine files.append(headerFile) } } } /** Merges the properties from the passed fromFile to the pass toFile :param: fromFile in which to find any new properties :param: toFile to which to add any found new properties */ func mergeProperties(#fromFile: FileRepresenter, toFile: FileRepresenter) { for property in fromFile.properties{ if find(toFile.properties, property) == nil{ toFile.properties.append(property) } } } /** Finds the first file in the passed files which has the same class name as the passed file :param: file the file to compare against :param: inFiles the files array to search in :param: exactMathFound inout param, will have the value of 'true' if any file is found that has exactly the same properties as the passed file :returns: similar file if any */ func findSimilarFile(file: FileRepresenter, inout inFiles files: [FileRepresenter], inout exactMatchFound: Bool) -> FileRepresenter?{ var similarFile : FileRepresenter? for targetFile in files{ exactMatchFound = bothFilesHasSamePropreties(file1: targetFile, file2: file) if exactMatchFound || targetFile.className == file.className{ similarFile = targetFile break } } return similarFile } /** Compares the properties of both files to determine if they exactly similar or no. :param: file1 first file to compare against the second file :param: file2 the second file to compare against the first file :returns: whether both files has exactly the same properties */ func bothFilesHasSamePropreties(#file1: FileRepresenter, file2: FileRepresenter) -> Bool { var bothHasSameProperties = true if file1.properties.count == file2.properties.count{ //there is a propability they both has the same properties for property in file1.properties{ if find(file2.properties, property) == nil{ //property not found, no need to keep looking bothHasSameProperties = false break } } }else{ bothHasSameProperties = false } return bothHasSameProperties } /** Creates and returns a Property object whiche represents a to-one relation property :param: relationClassName to which the relation relates :param: headerProperty optional whether this property is for header file :returns: the relation property */ func relationProperty(relationClassName : String) -> Property { let nativeName = relationClassName.lowercaseFirstChar() let property = Property(jsonName: nativeName, nativeName: nativeName, type: relationClassName, lang: lang) property.isCustomClass = true return property } /** Creates and returns a Property object passed on the passed value and json key name :param: value example value for the property :param: jsonKeyName for the property :returns: a Property instance */ func propertyForValue(value: AnyObject, jsonKeyName: String) -> Property { let nativePropertyName = propertyNativeName(jsonKeyName) var type = propertyTypeName(value, lang:lang) var isDictionary = false var isArray = false var property: Property! if value is NSDictionary { type = typeNameForPropertyName(jsonKeyName) property = Property(jsonName: jsonKeyName, nativeName: nativePropertyName, type: type, isArray:false, isCustomClass: true, lang: lang) }else if value is NSArray{ //we need to check its elements... let array = value as! NSArray if let dic = array.firstObject as? NSDictionary{ //wow complicated let leafClassName = typeNameForPropertyName(jsonKeyName) type = lang.arrayType.stringByReplacingOccurrencesOfString(elementType, withString: leafClassName) property = Property(jsonName: jsonKeyName, nativeName: nativePropertyName, type: type, isArray: true, isCustomClass: false, lang:lang) property.elementsType = leafClassName property.elementsAreOfCustomType = true }else{ property = Property(jsonName: jsonKeyName, nativeName: nativePropertyName, type: type, isArray: true, isCustomClass: false, lang:lang) property.elementsType = typeNameForArrayElements(value as! NSArray, lang:lang) } }else{ property = Property(jsonName: jsonKeyName, nativeName: nativePropertyName, type: type, lang:lang) } property.sampleValue = value return property } /** Returns a camel case presentation from the passed json key :param: jsonKeyName the name of the json key to convert to suitable native property name :returns: property name */ func propertyNativeName(jsonKeyName : String) -> String { return underscoresToCamelCaseForString(jsonKeyName, startFromFirstChar: false).lowercaseFirstChar() } /** Returns the input string with white spaces removed, and underscors converted to camel case :param: inputString to convert :param: startFromFirstChar whether to start with upper case letter :returns: the camel case version of the input */ func underscoresToCamelCaseForString(input: String, startFromFirstChar: Bool) -> String { var str = input.stringByReplacingOccurrencesOfString(" ", withString: "") str = str.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) var output = "" var makeNextCharUpperCase = startFromFirstChar for char in input{ if char == "_" { makeNextCharUpperCase = true }else if makeNextCharUpperCase{ let upperChar = String(char).uppercaseString output += upperChar makeNextCharUpperCase = false }else{ makeNextCharUpperCase = false output += String(char) } } return output } /** Creats and returns the class name for the passed proeprty name :param: propertyName to be converted to a type name :returns: the type name */ func typeNameForPropertyName(propertyName : String) -> String{ var swiftClassName = underscoresToCamelCaseForString(propertyName, startFromFirstChar: true).toSingular() if !swiftClassName.hasPrefix(classPrefix){ swiftClassName = "\(classPrefix)\(swiftClassName)" } return swiftClassName } }
mit
1a8adb05809c1fb3bd2eae938648b966
36.776758
159
0.629048
5.301288
false
false
false
false
iosyoujian/iOS8-day-by-day
14-rotation-deprecation/DeprecateToRotate/DeprecateToRotate/ViewController.swift
22
1538
// // 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 UIKit import QuartzCore class ViewController: UIViewController { @IBOutlet var bgImageView: UIImageView! override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { let transitionToWide = size.width > size.height let image = UIImage(named: transitionToWide ? "bg_wide" : "bg_tall") coordinator.animateAlongsideTransition({ context in // Create a transition and match the context's duration let transition = CATransition() transition.duration = context.transitionDuration() // Make it fade transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) transition.type = kCATransitionFade self.bgImageView.layer.addAnimation(transition, forKey: "Fade") // Set the new image self.bgImageView.image = image }, completion: nil) } }
apache-2.0
dc1bd6f2b25cd0d0e45a24e84ecfae7d
33.954545
134
0.73212
4.993506
false
false
false
false
yuwang17/WYExtensionUtil
WYExtensionUtil/WYExtensionUILabel.swift
1
3098
// // WYExtensionUILabel.swift // WYUtil // // Created by Wang Yu on 11/9/15. // Copyright © 2015 Wang Yu. All rights reserved. // import UIKit extension UILabel { //Auto resizing the height func initWithAutoHeight(rect: CGRect, textColor: UIColor, fontSize: CGFloat, text: String, lineSpacing: CGFloat) { self.frame = rect self.textColor = textColor self.font = UIFont.systemFontOfSize(fontSize) self.numberOfLines = 0 let attributedString = NSMutableAttributedString(string: text) let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineSpacing = lineSpacing attributedString.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSMakeRange(0, text.characters.count)) self.attributedText = attributedString self.sizeToFit() self.frame.size.width = rect.width self.frame.size.height = max(self.frame.size.height, rect.height) } func autoHeight(rect: CGRect, lineSpacing: CGFloat) { self.frame = rect if self.text != nil { self.numberOfLines = 0 let attributedString = NSMutableAttributedString(string: self.text!) let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineSpacing = lineSpacing let str: NSString = self.text! attributedString.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSMakeRange(0, str.length)) self.attributedText = attributedString self.sizeToFit() self.frame.size.width = rect.width self.frame.size.height = max(self.frame.size.height, rect.height) } } func autoHeightByLineSpace(lineSpacing: CGFloat) { self.autoHeight(self.frame, lineSpacing: lineSpacing) } func setForTitleByFont(fontSize: CGFloat) { self.textColor = UIColor.whiteColor() self.textAlignment = NSTextAlignment.Center self.font = UIFont.systemFontOfSize(fontSize) } func sizeToFitHeight() { let width = self.frame.width self.sizeToFit() self.frame.size.width = width } func sizeToFitWidth() { let height = self.frame.height self.sizeToFit() self.frame.size.height = height } func addTextByColor(texts: [MutableColoredText]) { var curStr = "" for text in texts { curStr += text.text } let countStr = NSMutableAttributedString(string: curStr) for text in texts { if (curStr as NSString).rangeOfString(text.text).location != NSNotFound{ countStr.addAttribute(NSForegroundColorAttributeName, value: text.color, range: (curStr as NSString).rangeOfString(text.text)) } } self.attributedText = countStr } } //多种颜色的label struct MutableColoredText { var text: String! var color: UIColor! init(text: String, color: UIColor){ self.text = text self.color = color } }
mit
3d7e8f6113f1bfa835a3e35262deb67b
32.554348
142
0.642371
4.749231
false
false
false
false
UW-AppDEV/AUXWave
AUXWave/ScannerTableViewCell.swift
1
1114
// // ScannerTableViewCell.swift // AUXWave // // Created by Nico Cvitak on 2015-03-01. // Copyright (c) 2015 UW-AppDEV. All rights reserved. // import UIKit import QuartzCore import MultipeerConnectivity class ScannerTableViewCell: UITableViewCell { var peerID: MCPeerID? { didSet { djLabel?.text = peerID?.displayName } } var facebookID: String? { didSet { djImageView?.profileID = facebookID } } @IBOutlet private var djImageView: FBProfilePictureView? @IBOutlet private var djLabel: UILabel? override func awakeFromNib() { super.awakeFromNib() // Initialization code // Add circle mask to djImageView if let imageView = djImageView { imageView.layer.cornerRadius = imageView.frame.size.width / 2.0 imageView.layer.masksToBounds = true } } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
gpl-2.0
67c0c5466bc1c47a7416bd452c217f17
22.702128
75
0.623878
4.510121
false
false
false
false
sdkshredder/SocialMe
SocialMe/SocialMe/SettingsVC.swift
1
2325
// // SettingsVC.swift // SocialMe // // Created by Mariam Ghanbari on 5/17/15. // Copyright (c) 2015 new. All rights reserved. // import UIKit import Parse class SettingsVC: UIViewController, UITableViewDelegate, UITableViewDataSource { //@IBOutlet weak var table: UITableView! func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 62 //selected.containsObject(indexPath.row) } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 5 } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func getTitleForPath(indexPath: NSIndexPath) -> String { var res = "" switch indexPath.row { case 0: res = "Name" case 1: res = "Age" case 2: res = "Hometown" case 3: res = "School" case 4: res = "Occupation" default: res = "hello" } return res } func getCurrentUserAttributes() { /* var user = PFUser.currentUser() user!.setObject(geoPoint, forKey: "location") user!.saveInBackgroundWithBlock { (succeeded, error) -> Void in if error == nil { println("success for user \(user!.username)") } } */ } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier("tableCell") as! TableTVCell cell.layoutMargins = UIEdgeInsetsZero cell.separatorInset = UIEdgeInsetsZero cell.title.text = getTitleForPath(indexPath) cell.textField.placeholder = getTitleForPath(indexPath) cell.title.tag = indexPath.row let attr = getTitleForPath(indexPath) let user = PFUser.currentUser() return cell } override func viewDidLoad() { super.viewDidLoad() /* table.delegate = self table.dataSource = self table.separatorInset = UIEdgeInsetsZero table.layoutMargins = UIEdgeInsetsZero */ } }
mit
a71ca89966006b28509ab96e02a82a64
24.833333
109
0.584516
5.201342
false
false
false
false
ECP-CANDLE/Supervisor
workflows/cp1/nested_me_ex/ext/EQ-Py/EQPy.swift
1
1464
/* EMEWS EQPy.swift */ import location; pragma worktypedef resident_work; @dispatch=resident_work (void v) _void_py(string code, string expr="\"\"") "turbine" "0.1.0" [ "turbine::python 1 1 <<code>> <<expr>> "]; @dispatch=resident_work (string output) _string_py(string code, string expr) "turbine" "0.1.0" [ "set <<output>> [ turbine::python 1 1 <<code>> <<expr>> ]" ]; string init_package_string = "import eqpy\neqpy.init('%s')"; (void v) EQPy_init_package(location loc, string packageName){ //printf("EQPy_init_package(%s) ...", packageName); string code = init_package_string % (packageName); //,packageName); //printf("Code is: \n%s", code); @location=loc _void_py(code) => v = propagate(); } (void v) EQPy_run(location loc){ @location=loc _void_py("eqpy.run()") => v = propagate(); } EQPy_stop(location loc){ // do nothing } string get_string = "result = eqpy.output_q_get()"; (string result) EQPy_get(location loc){ //printf("EQPy_get called"); string code = get_string; //printf("Code is: \n%s", code); result = @location=loc _string_py(code, "result"); } string put_string = """ eqpy.input_q_put("%s")\n"" """; (void v) EQPy_put(location loc, string data){ //printf("EQPy_put called with: \n%s", data); string code = put_string % data; //printf("EQPy_put code: \n%s", code); @location=loc _void_py(code) => v = propagate(); } // Local Variables: // c-basic-offset: 4 // End:
mit
aa9c0bff75b6984890c0f770dfd363d2
25.142857
71
0.618169
2.922156
false
false
false
false
argent-os/argent-ios
app-ios/History.swift
1
5832
// // History.swift // argent-ios // // Created by Sinan Ulkuatam on 4/22/16. // Copyright © 2016 Sinan Ulkuatam. All rights reserved. // import Foundation import SwiftyJSON import Alamofire class History { let id: String let amount: String let created: String let currency: String let type: String required init(id: String, amount: String, created: String, currency: String, type: String) { self.id = id self.amount = amount self.created = created self.currency = currency self.type = type } class func getAccountHistory(limit: String, starting_after: String, completionHandler: ([History]?, NSError?) -> Void) { // request to api to get data as json, put in list and table // check for token, get profile id based on token and make the request if(userAccessToken != nil) { User.getProfile({ (user, error) in if error != nil { print(error) } let parameters : [String : AnyObject] = [:] let headers = [ "Authorization": "Bearer " + (userAccessToken as! String), "Content-Type": "application/x-www-form-urlencoded" ] let limit = limit let starting_after = starting_after let user_id = (user?.id) var endpoint = API_URL + "/stripe/" + user_id! + "/transactions" if starting_after != "" { endpoint = API_URL + "/stripe/" + user_id! + "/transactions?limit=" + limit + "&starting_after=" + starting_after } else { endpoint = API_URL + "/stripe/" + user_id! + "/transactions?limit=" + limit } Alamofire.request(.GET, endpoint, parameters: parameters, encoding: .URL, headers: headers) .validate().responseJSON { response in switch response.result { case .Success: if let value = response.result.value { let data = JSON(value) var historyItemsArray = [History]() let accountHistories = data["transactions"]["data"].arrayValue for history in accountHistories { let id = history["id"].stringValue let amount = history["amount"].stringValue let created = history["created"].stringValue let currency = history["currency"].stringValue let type = history["type"].stringValue let item = History(id: id, amount: amount, created: created, currency: currency, type: type) historyItemsArray.append(item) } completionHandler(historyItemsArray, response.result.error) } case .Failure(let error): print(error) } } }) } } class func getHistoryArrays(completionHandler: (Array<AnyObject>?, Array<AnyObject>?, Array<AnyObject>?, Array<AnyObject>?, Array<AnyObject>?, Array<AnyObject>?, Array<AnyObject>?, NSError?) -> Void) { // request to api to get data as json, put in list and table // check for token, get profile id based on token and make the request if(userAccessToken != nil) { User.getProfile({ (user, error) in if error != nil { print(error) } let parameters : [String : AnyObject] = [:] let headers = [ "Authorization": "Bearer " + (userAccessToken as! String), "Content-Type": "application/x-www-form-urlencoded" ] let limit = "1000" let user_id = (user?.id) let endpoint = API_URL + "/stripe/" + user_id! + "/history?limit=" + limit Alamofire.request(.GET, endpoint, parameters: parameters, encoding: .URL, headers: headers) .responseJSON { response in switch response.result { case .Success: if let value = response.result.value { let data = JSON(value) let historyOneDay = data["history"]["1D"].arrayObject let historyTwoWeeks = data["history"]["2W"].arrayObject let historyOneMonth = data["history"]["1M"].arrayObject let historyThreeMonths = data["history"]["3M"].arrayObject let historySixMonths = data["history"]["6M"].arrayObject let historyOneYear = data["history"]["1Y"].arrayObject let historySixYears = data["history"]["5Y"].arrayObject completionHandler(historyOneDay, historyTwoWeeks, historyOneMonth, historyThreeMonths, historySixMonths, historyOneYear, historySixYears, response.result.error) } case .Failure(let error): print(error) } } }) } } }
mit
c6002ce86ea1c5fc2ab9e2e24f2268a4
44.209302
205
0.470074
5.68878
false
false
false
false
LucianoPAlmeida/SwifterSwift
Sources/Extensions/AppKit/NSImageExtensions.swift
1
2269
// // NSImageExtensions.swift // SwifterSwift-macOS // // Created by BUDDAx2 on 20.10.2017. // Copyright © 2017 SwifterSwift // #if os(macOS) import AppKit // MARK: - Methods extension NSImage { /// SwifterSwift: NSImage scaled to maximum size with respect to aspect ratio /// /// - Parameter toMaxSize: maximum size /// - Returns: scaled NSImage public func scaled(toMaxSize: NSSize) -> NSImage { var ratio: Float = 0.0 let imageWidth = Float(self.size.width) let imageHeight = Float(self.size.height) let maxWidth = Float(toMaxSize.width) let maxHeight = Float(toMaxSize.height) // Get ratio (landscape or portrait) if imageWidth > imageHeight { // Landscape ratio = maxWidth / imageWidth } else { // Portrait ratio = maxHeight / imageHeight } // Calculate new size based on the ratio let newWidth = imageWidth * ratio let newHeight = imageHeight * ratio // Create a new NSSize object with the newly calculated size let newSize: NSSize = NSSize(width: Int(newWidth), height: Int(newHeight)) // Cast the NSImage to a CGImage var imageRect: CGRect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height) let imageRef = self.cgImage(forProposedRect: &imageRect, context: nil, hints: nil) // Create NSImage from the CGImage using the new size let imageWithNewSize = NSImage(cgImage: imageRef!, size: newSize) // Return the new image return imageWithNewSize } /// SwifterSwift: Write NSImage to url. /// /// - Parameters: /// - url: Desired file URL. /// - type: Type of image (default is .jpeg). /// - compressionFactor: used only for JPEG files. The value is a float between 0.0 and 1.0, with 1.0 resulting in no compression and 0.0 resulting in the maximum compression possible. public func write(to url: URL, fileType type: NSBitmapImageRep.FileType = .jpeg, compressionFactor: NSNumber = 1.0) { // https://stackoverflow.com/a/45042611/3882644 guard let data = tiffRepresentation else { return } guard let imageRep = NSBitmapImageRep(data: data) else { return } guard let imageData = imageRep.representation(using: type, properties: [.compressionFactor: compressionFactor]) else { return } try? imageData.write(to: url) } } #endif
mit
3e1b7672107484b7c63493de8dc245f6
30.943662
187
0.703263
3.711948
false
false
false
false
byu-oit-appdev/ios-byuSuite
byuSuite/Apps/LabComputers/view/ComputerLabTableViewCell.swift
2
807
// // ComputerLabTableViewCell.swift // byuSuite // // Created by Nathan Johnson on 4/5/17. // Copyright © 2017 Brigham Young University. All rights reserved. // import UIKit class ComputerLabTableViewCell: UITableViewCell { @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var locationLabel: UILabel! @IBOutlet weak var availableLabel: UILabel! var lab: ComputerLab? { didSet { nameLabel.text = lab?.name if let building = lab?.building, let area = lab?.area { locationLabel.text = "\(building), floor \(area)" } if let available = lab?.availableComputers { availableLabel.text = "\(available) available" } } } }
apache-2.0
1f1cd7e4480ac79b04a102adb483de62
24.1875
67
0.57072
4.769231
false
false
false
false
hilenium/HISwiftExtensions
Example/Tests/DictionaryTests.swift
1
2394
// // DictionaryTests.swift // HISwiftExtensions // // Created by Matthew on 26/12/2015. // Copyright © 2015 CocoaPods. All rights reserved. // import Quick import Nimble import HISwiftExtensions class DictionaryExtensionsSpec: QuickSpec { override func spec() { describe("dictionary extensions") { it("merge") { var a = ["a" : "a"] let b = ["b" : "b"] a.merge(b) expect(a["a"]).to(equal("a")) expect(a["b"]).to(equal("b")) } it("keys to camelcase") { let d = [ "a_property" : [ "nested_property" : "foo" ] ] let dict = d.keysToCamelCase() expect(Array(dict.keys).first).to(equal("aProperty")) expect(Array(dict["aProperty"]!.keys).first).to(equal("nestedProperty")) } it("remove nsnulls") { let d: [String: Any] = [ "null_property" : NSNull(), "a_property" : "a" as AnyObject, "nested": [ "null_property" : NSNull(), "a_property" : "a", ] ] let dict = d.removeNulls() expect(Array(dict.keys).first).to(equal("a_property")) let nested = dict["nested"] as! [String: AnyObject] expect(Array(nested.keys).first).to(equal("a_property")) } it("filter keys") { class Test: NSObject { var a: AnyObject? var b: AnyObject? } var dict = [ "a" : "foo", "b" : "bar", "c" : "foobar", ] dict.filterKeys(Test()) let keys = Array(dict.keys) expect(keys.contains("a")).to(equal(true)) expect(keys.contains("b")).to(equal(true)) expect(keys.contains("c")).to(equal(false)) } } } }
mit
7ae4bc42d745afdf02d513ea426d7d37
28.182927
88
0.374425
4.913758
false
false
false
false
petester42/SwiftCharts
SwiftCharts/ChartCoordsSpace.swift
7
10564
// // ChartCoordsSpace.swift // SwiftCharts // // Created by ischuetz on 27/04/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit public class ChartCoordsSpace { public typealias ChartAxisLayerModel = (p1: CGPoint, p2: CGPoint, axisValues: [ChartAxisValue], axisTitleLabels: [ChartAxisLabel], settings: ChartAxisSettings) public typealias ChartAxisLayerGenerator = (ChartAxisLayerModel) -> ChartAxisLayer private let chartSettings: ChartSettings private let chartSize: CGSize public private(set) var chartInnerFrame: CGRect = CGRectZero private let yLowModels: [ChartAxisModel] private let yHighModels: [ChartAxisModel] private let xLowModels: [ChartAxisModel] private let xHighModels: [ChartAxisModel] private let yLowGenerator: ChartAxisLayerGenerator private let yHighGenerator: ChartAxisLayerGenerator private let xLowGenerator: ChartAxisLayerGenerator private let xHighGenerator: ChartAxisLayerGenerator public private(set) var yLowAxes: [ChartAxisLayer] = [] public private(set) var yHighAxes: [ChartAxisLayer] = [] public private(set) var xLowAxes: [ChartAxisLayer] = [] public private(set) var xHighAxes: [ChartAxisLayer] = [] public convenience init(chartSettings: ChartSettings, chartSize: CGSize, yLowModels: [ChartAxisModel] = [], yHighModels: [ChartAxisModel] = [], xLowModels: [ChartAxisModel] = [], xHighModels: [ChartAxisModel] = []) { let yLowGenerator: ChartAxisLayerGenerator = {model in ChartAxisYLowLayerDefault(p1: model.p1, p2: model.p2, axisValues: model.axisValues, axisTitleLabels: model.axisTitleLabels, settings: model.settings) } let yHighGenerator: ChartAxisLayerGenerator = {model in ChartAxisYHighLayerDefault(p1: model.p1, p2: model.p2, axisValues: model.axisValues, axisTitleLabels: model.axisTitleLabels, settings: model.settings) } let xLowGenerator: ChartAxisLayerGenerator = {model in ChartAxisXLowLayerDefault(p1: model.p1, p2: model.p2, axisValues: model.axisValues, axisTitleLabels: model.axisTitleLabels, settings: model.settings) } let xHighGenerator: ChartAxisLayerGenerator = {model in ChartAxisXHighLayerDefault(p1: model.p1, p2: model.p2, axisValues: model.axisValues, axisTitleLabels: model.axisTitleLabels, settings: model.settings) } self.init(chartSettings: chartSettings, chartSize: chartSize, yLowModels: yLowModels, yHighModels: yHighModels, xLowModels: xLowModels, xHighModels: xHighModels, yLowGenerator: yLowGenerator, yHighGenerator: yHighGenerator, xLowGenerator: xLowGenerator, xHighGenerator: xHighGenerator) } public init(chartSettings: ChartSettings, chartSize: CGSize, yLowModels: [ChartAxisModel], yHighModels: [ChartAxisModel], xLowModels: [ChartAxisModel], xHighModels: [ChartAxisModel], yLowGenerator: ChartAxisLayerGenerator, yHighGenerator: ChartAxisLayerGenerator, xLowGenerator: ChartAxisLayerGenerator, xHighGenerator: ChartAxisLayerGenerator) { self.chartSettings = chartSettings self.chartSize = chartSize self.yLowModels = yLowModels self.yHighModels = yHighModels self.xLowModels = xLowModels self.xHighModels = xHighModels self.yLowGenerator = yLowGenerator self.yHighGenerator = yHighGenerator self.xLowGenerator = xLowGenerator self.xHighGenerator = xHighGenerator self.chartInnerFrame = self.calculateChartInnerFrame() self.yLowAxes = self.generateYLowAxes() self.yHighAxes = self.generateYHighAxes() self.xLowAxes = self.generateXLowAxes() self.xHighAxes = self.generateXHighAxes() } private func generateYLowAxes() -> [ChartAxisLayer] { return generateYAxisShared(axisModels: self.yLowModels, offset: chartSettings.leading, generator: self.yLowGenerator) } private func generateYHighAxes() -> [ChartAxisLayer] { let chartFrame = self.chartInnerFrame return generateYAxisShared(axisModels: self.yHighModels, offset: chartFrame.origin.x + chartFrame.width, generator: self.yHighGenerator) } private func generateXLowAxes() -> [ChartAxisLayer] { let chartFrame = self.chartInnerFrame let y = chartFrame.origin.y + chartFrame.height return self.generateXAxesShared(axisModels: self.xLowModels, offset: y, generator: self.xLowGenerator) } private func generateXHighAxes() -> [ChartAxisLayer] { return self.generateXAxesShared(axisModels: self.xHighModels, offset: chartSettings.top, generator: self.xHighGenerator) } private func generateXAxesShared(#axisModels: [ChartAxisModel], offset: CGFloat, generator: ChartAxisLayerGenerator) -> [ChartAxisLayer] { let chartFrame = self.chartInnerFrame let chartSettings = self.chartSettings let x = chartFrame.origin.x let length = chartFrame.width return generateAxisShared(axisModels: axisModels, offset: offset, pointsCreator: { varDim in (p1: CGPointMake(x, varDim), p2: CGPointMake(x + length, varDim)) }, dimIncr: { layer in layer.rect.height + chartSettings.spacingBetweenAxesX }, generator: generator) } private func generateYAxisShared(#axisModels: [ChartAxisModel], offset: CGFloat, generator: ChartAxisLayerGenerator) -> [ChartAxisLayer] { let chartFrame = self.chartInnerFrame let chartSettings = self.chartSettings let y = chartFrame.origin.y let length = chartFrame.height return generateAxisShared(axisModels: axisModels, offset: offset, pointsCreator: { varDim in (p1: CGPointMake(varDim, y + length), p2: CGPointMake(varDim, y)) }, dimIncr: { layer in layer.rect.width + chartSettings.spacingBetweenAxesY }, generator: generator) } private func generateAxisShared(#axisModels: [ChartAxisModel], offset: CGFloat, pointsCreator: (varDim: CGFloat) -> (p1: CGPoint, p2: CGPoint), dimIncr: (ChartAxisLayer) -> CGFloat, generator: ChartAxisLayerGenerator) -> [ChartAxisLayer] { let chartFrame = self.chartInnerFrame let chartSettings = self.chartSettings return axisModels.reduce((axes: Array<ChartAxisLayer>(), x: offset)) {tuple, chartAxisModel in let layers = tuple.axes let x: CGFloat = tuple.x let axisSettings = ChartAxisSettings(chartSettings) axisSettings.lineColor = chartAxisModel.lineColor let points = pointsCreator(varDim: x) let layer = generator(p1: points.p1, p2: points.p2, axisValues: chartAxisModel.axisValues, axisTitleLabels: chartAxisModel.axisTitleLabels, settings: axisSettings) return ( axes: layers + [layer], x: x + dimIncr(layer) ) }.0 } private func calculateChartInnerFrame() -> CGRect { let totalDim = {(axisLayers: [ChartAxisLayer], dimPicker: (ChartAxisLayer) -> CGFloat, spacingBetweenAxes: CGFloat) -> CGFloat in return axisLayers.reduce((CGFloat(0), CGFloat(0))) {tuple, chartAxisLayer in let totalDim = tuple.0 + tuple.1 return (totalDim + dimPicker(chartAxisLayer), spacingBetweenAxes) }.0 } func totalWidth(axisLayers: [ChartAxisLayer]) -> CGFloat { return totalDim(axisLayers, {$0.rect.width}, self.chartSettings.spacingBetweenAxesY) } func totalHeight(axisLayers: [ChartAxisLayer]) -> CGFloat { return totalDim(axisLayers, {$0.rect.height}, self.chartSettings.spacingBetweenAxesX) } let yLowWidth = totalWidth(self.generateYLowAxes()) let yHighWidth = totalWidth(self.generateYHighAxes()) let xLowHeight = totalHeight(self.generateXLowAxes()) let xHighHeight = totalHeight(self.generateXHighAxes()) let leftWidth = yLowWidth + self.chartSettings.leading let topHeigth = xHighHeight + self.chartSettings.top let rightWidth = yHighWidth + self.chartSettings.trailing let bottomHeight = xLowHeight + self.chartSettings.bottom return CGRectMake( leftWidth, topHeigth, self.chartSize.width - leftWidth - rightWidth, self.chartSize.height - topHeigth - bottomHeight ) } } public class ChartCoordsSpaceLeftBottomSingleAxis { public let yAxis: ChartAxisLayer public let xAxis: ChartAxisLayer public let chartInnerFrame: CGRect public init(chartSettings: ChartSettings, chartFrame: CGRect, xModel: ChartAxisModel, yModel: ChartAxisModel) { let coordsSpaceInitializer = ChartCoordsSpace(chartSettings: chartSettings, chartSize: chartFrame.size, yLowModels: [yModel], xLowModels: [xModel]) self.chartInnerFrame = coordsSpaceInitializer.chartInnerFrame self.yAxis = coordsSpaceInitializer.yLowAxes[0] self.xAxis = coordsSpaceInitializer.xLowAxes[0] } } public class ChartCoordsSpaceLeftTopSingleAxis { public let yAxis: ChartAxisLayer public let xAxis: ChartAxisLayer public let chartInnerFrame: CGRect public init(chartSettings: ChartSettings, chartFrame: CGRect, xModel: ChartAxisModel, yModel: ChartAxisModel) { let coordsSpaceInitializer = ChartCoordsSpace(chartSettings: chartSettings, chartSize: chartFrame.size, yLowModels: [yModel], xHighModels: [xModel]) self.chartInnerFrame = coordsSpaceInitializer.chartInnerFrame self.yAxis = coordsSpaceInitializer.yLowAxes[0] self.xAxis = coordsSpaceInitializer.xHighAxes[0] } } public class ChartCoordsSpaceRightBottomSingleAxis { public let yAxis: ChartAxisLayer public let xAxis: ChartAxisLayer public let chartInnerFrame: CGRect public init(chartSettings: ChartSettings, chartFrame: CGRect, xModel: ChartAxisModel, yModel: ChartAxisModel) { let coordsSpaceInitializer = ChartCoordsSpace(chartSettings: chartSettings, chartSize: chartFrame.size, yHighModels: [yModel], xLowModels: [xModel]) self.chartInnerFrame = coordsSpaceInitializer.chartInnerFrame self.yAxis = coordsSpaceInitializer.yHighAxes[0] self.xAxis = coordsSpaceInitializer.xLowAxes[0] } }
apache-2.0
2063a07da5e4eacdde8f0b5dccc6a263
47.022727
350
0.698315
5.442555
false
false
false
false
away4m/Vendors
Vendors/Extensions/UINavigationController.swift
1
5919
// // UINavigationController.swift // Pods // // Created by away4m on 12/30/16. // // #if canImport(UIKit) import UIKit #if !os(watchOS) public extension UINavigationController { /// SwifterSwift: Pop ViewController with completion handler. /// /// - Parameters: /// - animated: Set this value to true to animate the transition (default is true). /// - completion: optional completion handler (default is nil). public func popViewController(animated: Bool = true, _ completion: (() -> Void)? = nil) { // https://github.com/cotkjaer/UserInterface/blob/master/UserInterface/UIViewController.swift CATransaction.begin() CATransaction.setCompletionBlock(completion) popViewController(animated: animated) CATransaction.commit() } /// SwifterSwift: Pop ViewController with completion handler. /// /// - Parameter completion: optional completion handler (default is nil). public func popToRootViewController(animated: Bool = true, _ completion: (() -> Void)? = nil) { // https://github.com/cotkjaer/UserInterface/blob/master/UserInterface/UIViewController.swift CATransaction.begin() CATransaction.setCompletionBlock(completion) popToRootViewController(animated: animated) CATransaction.commit() } /// SwifterSwift: Push ViewController with completion handler. /// /// - Parameters: /// - viewController: viewController to push. /// - completion: optional completion handler (default is nil). public func pushViewController(animated: Bool = true, _ viewController: UIViewController, completion: (() -> Void)? = nil) { // https://github.com/cotkjaer/UserInterface/blob/master/UserInterface/UIViewController.swift CATransaction.begin() CATransaction.setCompletionBlock(completion) pushViewController(viewController, animated: animated) CATransaction.commit() } /// SwifterSwift: Make navigation controller's navigation bar transparent. /// /// - Parameter tint: tint color (default is .white). public func makeTransparent(with tint: UIColor = UIColor.white) { navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default) navigationBar.shadowImage = UIImage() navigationBar.isTranslucent = true navigationBar.tintColor = tint navigationBar.titleTextAttributes = [.foregroundColor: tint] } /// SwifterSwift: Pop ViewController with completion handler. /// /// - Parameter completion: optional completion handler (default is nil). @objc public func popViewController(animated: Bool = true, completion: (() -> Void)? = nil) { // https://github.com/cotkjaer/UserInterface/blob/master/UserInterface/UIViewController.swift CATransaction.begin() CATransaction.setCompletionBlock(completion) popViewController(animated: animated) CATransaction.commit() } // Push ViewController with completion handler. /// /// - Parameters: /// - viewController: viewController to push. /// - Parameter completion: optional completion handler (default is nil). @objc public func pushViewController(animated: Bool = true, viewController: UIViewController, completion: (() -> Void)? = nil) { // https://github.com/cotkjaer/UserInterface/blob/master/UserInterface/UIViewController.swift CATransaction.begin() CATransaction.setCompletionBlock(completion) pushViewController(viewController, animated: animated) CATransaction.commit() } // @objc public func completelyTransparentBar() { // navigationBar.setBackgroundImage(UIImage(), for: .default) // navigationBar.shadowImage = UIImage() // navigationBar.isTranslucent = true // view.backgroundColor = UIColor.clear // navigationBar.backgroundColor = UIColor.clear // } @objc public func previousViewController() -> UIViewController? { return viewController(at: viewControllers.count - 2) } public func viewController(at index: Int) -> UIViewController? { guard index >= 0 else { return nil } return viewControllers[index] } public func removeViewController(at index: Int) { var _viewControllers = viewControllers _viewControllers.remove(at: index) viewControllers = _viewControllers } @objc public func removeViewController(atTail index: Int) { var _viewControllers = viewControllers _viewControllers.remove(at: _viewControllers.count - index - 1) viewControllers = _viewControllers } @objc public func removeViewControllers(previous number: Int) { var _viewControllers = viewControllers if number < _viewControllers.count { _viewControllers.removeSubrange(_viewControllers.count - number - 1 ... _viewControllers.count - 2) viewControllers = _viewControllers } } @objc public func removePreviousViewController() { removeViewController(atTail: 1) } } #endif #endif
mit
41be96cc78bc1c38ffe265d178e9b22e
44.530769
140
0.591654
5.954728
false
false
false
false
Chris-Perkins/Lifting-Buddy
Lifting Buddy/ExerciseChartViewWithToggles.swift
1
11386
// // ExerciseChartViewWithToggles.swift // Lifting Buddy // // Created by Christopher Perkins on 11/22/17. // Copyright © 2017 Christopher Perkins. All rights reserved. // import UIKit import Realm import RealmSwift import SwiftCharts public class ExerciseChartViewWithToggles: UIView, PrettySegmentedControlDelegate { // MARK: View properties private static let heightPerProgressionMethodButton: CGFloat = 40.0 // The exercise we're graphing private let exercise: Exercise // the amount of space the chart can take up width-wise private let chartWidth: CGFloat // A view we use to select a date view private let timeAmountSelectionView: PrettySegmentedControl // The view where we'll put the chart private let chartFrame: UIView // Filter progressionMethods from graph private var filterProgressionMethods: Set<ProgressionMethod> // the time amount we're currently displaying private var selectedTimeAmount: TimeAmount // the chart we're showing private var chart: Chart? // The labels for every exercise private var progressionButtons: [ToggleablePrettyButtonWithProgressionMethod] // MARK: Inits init(exercise: Exercise, chartWidth: CGFloat) { self.exercise = exercise self.chartWidth = chartWidth selectedTimeAmount = TimeAmount.month filterProgressionMethods = Set<ProgressionMethod>() timeAmountSelectionView = PrettySegmentedControl(labelStrings: TimeAmountArray.map {$0.rawValue}, frame: .zero) chartFrame = UIView() progressionButtons = [ToggleablePrettyButtonWithProgressionMethod]() super.init(frame: .zero) timeAmountSelectionView.delegate = self addSubview(timeAmountSelectionView) addSubview(chartFrame) createAndActivateTimeAmountSelectionViewConstraints() createAndActivateChartFrameConstraints() createProgressionMethodFilterButtons() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: View overrides override public func layoutIfNeeded() { super.layoutIfNeeded() backgroundColor = .niceRed chartFrame.clipsToBounds = true filterProgressionMethods.removeAll() chartFrame.backgroundColor = .niceRed } // MARK: Custom view functions /* Every progression method gets a button of some height (lines 1 + 2) Also, every graph needs a time selection view and the chart height (line 3) Totals up to what this return statement says. */ static func getNecessaryHeightForExerciseGraph(exercise: Exercise) -> CGFloat { return CGFloat(exercise.getProgressionMethods().count) * ExerciseChartViewWithToggles.heightPerProgressionMethodButton + PrettySegmentedControl.defaultHeight + Chart.defaultHeight } // Creates a chart with the given selected information public func createChart() { // Remove any view from chart frame so we don't draw over and over chartFrame.removeAllSubviews() let frame = CGRect(x: 0, y: 0, width: chartWidth, height: Chart.defaultHeight) // Create chart returns (chart, bool) representing the chart, and if the graph is viewable to the user. let chartInfo = createChartFromExerciseHistory(exerciseHistory: exercise.getExerciseHistory(), filterProgressionMethods: filterProgressionMethods, timeAmount: selectedTimeAmount, frame: frame) // If the graph is viewable to the user, work it! if chartInfo.1 { chart = chartInfo.0 chart!.view.backgroundColor = .primaryBlackWhiteColor chartFrame.addSubview(chart!.view) } else { let cannotGraphView = UILabel(frame: frame) cannotGraphView.backgroundColor = .lightBlackWhiteColor cannotGraphView.textColor = .niceBlue cannotGraphView.textAlignment = .center // 8 is chosen arbitrarily. cannotGraphView.numberOfLines = 8 cannotGraphView.text = NSLocalizedString("ExerciseView.Graph", comment: "") chartFrame.addSubview(cannotGraphView) } layoutSubviews() } // Destroys the chart being shown in memory. Used for saving memory public func destroyChart() { if chart != nil { chart?.view.removeFromSuperview() chart = nil chartFrame.removeAllSubviews() layoutSubviews() } } // MARK: Event functions // Whenever a toggle button is pressed, activate or deactivate them from the graph @objc private func toggleButtonPress(sender: ToggleablePrettyButtonWithProgressionMethod) { if sender.isToggled { filterProgressionMethods.remove(sender.progressionMethod) } else { filterProgressionMethods.insert(sender.progressionMethod) } createChart() } // MARK: PrettySegmentedControlDelegate functions func segmentSelectionChanged(index: Int) { selectedTimeAmount = TimeAmountArray[index] createChart() } // MARK: Constraint Functions // Center horiz in view ; below cellTitle ; width of this view * 0.85 ; height of default private func createAndActivateTimeAmountSelectionViewConstraints() { timeAmountSelectionView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.createViewAttributeCopyConstraint(view: timeAmountSelectionView, withCopyView: self, attribute: .centerX).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: timeAmountSelectionView, withCopyView: self, attribute: .top).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: timeAmountSelectionView, withCopyView: self, attribute: .width).isActive = true NSLayoutConstraint.createHeightConstraintForView(view: timeAmountSelectionView, height: PrettySegmentedControl.defaultHeight).isActive = true } // Center horiz in view ; Width of this view ; Below cell title ; Height of Chart's default height private func createAndActivateChartFrameConstraints() { chartFrame.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.createViewAttributeCopyConstraint(view: chartFrame, withCopyView: self, attribute: .centerX).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: chartFrame, withCopyView: timeAmountSelectionView, attribute: .width).isActive = true NSLayoutConstraint.createViewBelowViewConstraint(view: chartFrame, belowView: timeAmountSelectionView, withPadding: 0).isActive = true NSLayoutConstraint.createHeightConstraintForView(view: chartFrame, height: Chart.defaultHeight).isActive = true } // Creates the buttons and lines them up in a downwards fashion. private func createProgressionMethodFilterButtons() { // The last view before these (in terms of top to bottom) var prevView: UIView = chartFrame for progressionMethod in exercise.getProgressionMethods() { let progressionMethodButton = ToggleablePrettyButtonWithProgressionMethod( progressionMethod: progressionMethod, frame: .zero) progressionMethodButton.setTitle(progressionMethod.getName(), for: .normal) progressionMethodButton.setIsToggled(toggled: true) progressionMethodButton.setToggleTextColor(color: .white) progressionMethodButton.setDefaultTextColor(color: .white) progressionMethodButton.setToggleViewColor(color: getColorsForIndex(progressionMethod.getIndex()!)[0]) progressionMethodButton.setDefaultViewColor(color: .lightBlackWhiteColor) progressionMethodButton.addTarget(self, action: #selector(toggleButtonPress(sender:)), for: .touchUpInside) addSubview(progressionMethodButton) // Constraints for this exercise label. // Place 10 from left/right of the cell // Place 10 below above view, height of 20 progressionMethodButton.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.createViewAttributeCopyConstraint(view: progressionMethodButton, withCopyView: self, attribute: .centerX).isActive = true NSLayoutConstraint.createViewBelowViewConstraint(view: progressionMethodButton, belowView: prevView, withPadding: 0).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: progressionMethodButton, withCopyView: chartFrame, attribute: .width).isActive = true NSLayoutConstraint.createHeightConstraintForView( view: progressionMethodButton, height: ExerciseChartViewWithToggles.heightPerProgressionMethodButton).isActive = true progressionButtons.append(progressionMethodButton) prevView = progressionMethodButton } } } class ToggleablePrettyButtonWithProgressionMethod: ToggleablePrettyButton { public var progressionMethod: ProgressionMethod init(progressionMethod: ProgressionMethod, frame: CGRect) { self.progressionMethod = progressionMethod super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
8ff0b87cc219e800e07bbf2a4af48e27
44
118
0.59675
6.43948
false
false
false
false
hemantasapkota/SwiftStore
Example/SwiftStoreExample/SwiftStoreExample/ExampleViewController.swift
1
2615
// // ExampleViewController.swift // SwiftStoreExample // // Created by Hemanta Sapkota on 31/05/2015. // Copyright (c) 2015 Hemanta Sapkota. All rights reserved. // import Foundation import UIKit import SnapKit class ExampleViewController : UIViewController { override func viewDidLoad() { title = "Swift Store Demo" let exampleView = ExampleView() exampleView.viewPusher = { viewController in self.navigationController?.pushViewController(viewController, animated: true) } view = exampleView } } class ExampleView : UIView, UITableViewDataSource, UITableViewDelegate { /* Items */ var items = ["Saving Key / Value Pairs" ] /* Table View */ var tableView: UITableView! var viewPusher: ( (UIViewController) -> Void)! init() { super.init(frame: UIScreen.main.bounds) tableView = UITableView() tableView.dataSource = self tableView.delegate = self addSubview(tableView) tableView.snp_makeConstraints { (make) -> Void in make.top.equalTo(0) make.left.equalTo(0) make.width.equalTo(self.snp_width) make.height.equalTo(self.snp_height) } tableView.register(ExampleViewCell.self, forCellReuseIdentifier: "ExampleViewCell") } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ExampleViewCell") as! ExampleViewCell cell.textLabel?.text = items[(indexPath as NSIndexPath).item] return cell } func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) { let item = (indexPath as NSIndexPath).item if item == 0 { viewPusher(SimpleKeyValueViewController()) } else if item == 1 { // viewPusher(SimpleCollectionViewController()) } } } class ExampleViewCell : UITableViewCell { override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
ce19d637d9da74e78e34196e1a4c58c8
27.423913
103
0.632505
5.067829
false
false
false
false
paulomendes/nextel-challange
nextel-challange/Source/ViewControllers/HomeViewController/SearchViewController.swift
1
3222
import UIKit class SearchViewController: UIViewController, DataAccessObjectProtocol, UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating { var moviesDAO: MoviesDAOProtocol? var movies: [MovieViewModel] = [] let searchController = UISearchController(searchResultsController: nil) @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() self.searchController.searchResultsUpdater = self self.searchController.hidesNavigationBarDuringPresentation = false self.searchController.dimsBackgroundDuringPresentation = false self.searchController.searchBar.sizeToFit() self.tableView.tableHeaderView = self.searchController.searchBar self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") } func setMoviesDAO(moviesDAO: MoviesDAOProtocol) { self.moviesDAO = moviesDAO } func loadMoviesData() { self.movies = [] let searchString = searchController.searchBar.text! if searchString.isEmpty { self.transformModelsAndReloadData([]) return } self.moviesDAO?.searchMovieByTitle(query: searchString, success: { (movies) in self.transformModelsAndReloadData(movies) }, failure: { (err) in // handle error here }) } func filter() { self.loadMoviesData() } func transformModelsAndReloadData(_ movies: [Movie]) { for movie in movies { let movieViewModel = MovieViewModel(movieModel: movie) self.movies.append(movieViewModel) } self.tableView.reloadData() } // MARK: Search Delegate public func updateSearchResults(for searchController: UISearchController) { //Throtlling the Web Request SearchViewController.cancelPreviousPerformRequests(withTarget: self, selector: #selector(self.filter), object: nil) self.perform(#selector(self.filter), with: nil, afterDelay: 0.8) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let destination = segue.destination as? MovieDetailsViewController { destination.movieViewModel = self.movies[sender as! Int] } } // MARK: Table View Delegates func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.performSegue(withIdentifier: "seach-to-details", sender: indexPath.row) } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.movies.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "cell")! cell.textLabel?.text = self.movies[indexPath.row].movieTitle return cell } }
mit
2f07403d400ce691853e2b01bdd2cebf
34.021739
141
0.642458
5.584055
false
false
false
false
benlangmuir/swift
test/SourceKit/DocumentStructure/structure.swift
22
842
// RUN: %sourcekitd-test -req=structure %S/Inputs/main.swift -- -module-name StructureTest %S/Inputs/main.swift | %sed_clean > %t.response // RUN: %diff -u %s.response %t.response // RUN: %sourcekitd-test -req=structure %S/Inputs/invalid.swift | %sed_clean > %t.invalid.response // RUN: %diff -u %s.invalid.response %t.invalid.response // RUN: %sourcekitd-test -req=structure %S/../Inputs/placeholders.swift | %sed_clean > %t.placeholders.response // RUN: %diff -u %s.placeholders.response %t.placeholders.response // RUN: %sourcekitd-test -req=structure %S/Inputs/main.swift -name -foobar | %sed_clean > %t.foobar.response // RUN: %diff -u %s.foobar.response %t.foobar.response // RUN: %sourcekitd-test -req=structure -text-input %S/Inputs/main.swift | %sed_clean > %t.empty.response // RUN: %diff -u %s.empty.response %t.empty.response
apache-2.0
14674d5a7aa689e787c046a0acf7af12
59.142857
138
0.711401
2.996441
false
true
true
false
benlangmuir/swift
test/Interpreter/generic_casts.swift
4
16997
// RUN: %empty-directory(%t) // RUN: %target-build-swift -Onone %s -o %t/a.out // RUN: %target-build-swift -O %s -o %t/a.out.optimized // RUN: %target-codesign %t/a.out // RUN: %target-codesign %t/a.out.optimized // // RUN: %target-run %t/a.out | %FileCheck --check-prefix CHECK %s // RUN: %target-run %t/a.out.optimized | %FileCheck --check-prefix CHECK %s // REQUIRES: executable_test // FIXME: rdar://problem/19648117 Needs splitting objc parts out #if canImport(Foundation) import Foundation #endif func allToInt<T>(_ x: T) -> Int { return x as! Int } func allToIntOrZero<T>(_ x: T) -> Int { if x is Int { return x as! Int } return 0 } func anyToInt(_ x: Any) -> Int { return x as! Int } func anyToIntOrZero(_ x: Any) -> Int { if x is Int { return x as! Int } return 0 } protocol Class : class {} class C : Class { func print() { Swift.print("C!") } } class D : C { override func print() { Swift.print("D!") } } class E : C { override func print() { Swift.print("E!") } } class X : Class { } func allToC<T>(_ x: T) -> C { return x as! C } func allToCOrE<T>(_ x: T) -> C { if x is C { return x as! C } return E() } func anyToC(_ x: Any) -> C { return x as! C } func anyToCOrE(_ x: Any) -> C { if x is C { return x as! C } return E() } func allClassesToC<T : Class>(_ x: T) -> C { return x as! C } func allClassesToCOrE<T : Class>(_ x: T) -> C { if x is C { return x as! C } return E() } func anyClassToC(_ x: Class) -> C { return x as! C } func anyClassToCOrE(_ x: Class) -> C { if x is C { return x as! C } return E() } func allToAll<T, U>(_ t: T, _: U.Type) -> Bool { return t is U } func allMetasToAllMetas<T, U>(_: T.Type, _: U.Type) -> Bool { return T.self is U.Type } print(allToInt(22)) // CHECK: 22 print(anyToInt(44)) // CHECK: 44 allToC(C()).print() // CHECK: C! allToC(D()).print() // CHECK: D! anyToC(C()).print() // CHECK: C! anyToC(D()).print() // CHECK: D! allClassesToC(C()).print() // CHECK: C! allClassesToC(D()).print() // CHECK: D! anyClassToC(C()).print() // CHECK: C! anyClassToC(D()).print() // CHECK: D! print(allToIntOrZero(55)) // CHECK: 55 print(allToIntOrZero("fifty-five")) // CHECK: 0 print(anyToIntOrZero(88)) // CHECK: 88 print(anyToIntOrZero("eighty-eight")) // CHECK: 0 allToCOrE(C()).print() // CHECK: C! allToCOrE(D()).print() // CHECK: D! allToCOrE(143).print() // CHECK: E! allToCOrE(X()).print() // CHECK: E! anyToCOrE(C()).print() // CHECK: C! anyToCOrE(D()).print() // CHECK: D! anyToCOrE(143).print() // CHECK: E! anyToCOrE(X()).print() // CHECK: E! allClassesToCOrE(C()).print() // CHECK: C! allClassesToCOrE(D()).print() // CHECK: D! allClassesToCOrE(X()).print() // CHECK: E! anyClassToCOrE(C()).print() // CHECK: C! anyClassToCOrE(D()).print() // CHECK: D! anyClassToCOrE(X()).print() // CHECK: E! protocol P {} struct PS: P {} enum PE: P {} class PC: P {} class PCSub: PC {} // `is` checks func nongenericAnyIsPType(type: Any.Type) -> Bool { // `is P.Type` tests whether the argument conforms to `P` // Note: this can only be true for a concrete type, never a protocol return type is P.Type } func nongenericAnyIsPProtocol(type: Any.Type) -> Bool { // `P.Protocol` is the metatype for `P` (the type of `P.self`) // `is P.Protocol` tests whether the argument is a subtype of `P` // In particular, it is true for `P.self` return type is P.Protocol } func nongenericAnyIsPAndAnyObjectType(type: Any.Type) -> Bool { return type is (P & AnyObject).Type } func nongenericAnyIsPAndAnyObjectProtocol(type: Any.Type) -> Bool { return type is (P & AnyObject).Protocol } func nongenericAnyIsPAndPCSubType(type: Any.Type) -> Bool { return type is (P & PCSub).Type } func genericAnyIs<T>(type: Any.Type, to: T.Type, expected: Bool) -> Bool { // If we're testing against a runtime that doesn't have the fix this tests, // just pretend we got it right. if #available(SwiftStdlib 5.2, *) { // Remember: If `T` is bound to `P`, then `T.Type` is `P.Protocol` return type is T.Type } else { return expected } } // `as?` checks func nongenericAnyAsConditionalPType(type: Any.Type) -> Bool { return (type as? P.Type) != nil } func nongenericAnyAsConditionalPProtocol(type: Any.Type) -> Bool { return (type as? P.Protocol) != nil } func nongenericAnyAsConditionalPAndAnyObjectType(type: Any.Type) -> Bool { return (type as? (P & AnyObject).Type) != nil } func nongenericAnyAsConditionalPAndAnyObjectProtocol(type: Any.Type) -> Bool { return (type as? (P & AnyObject).Protocol) != nil } func nongenericAnyAsConditionalPAndPCSubType(type: Any.Type) -> Bool { return (type as? (P & PCSub).Type) != nil } func genericAnyAsConditional<T>(type: Any.Type, to: T.Type, expected: Bool) -> Bool { // If we're testing against a runtime that doesn't have the fix this tests, // just pretend we got it right. if #available(SwiftStdlib 5.3, *) { return (type as? T.Type) != nil } else { return expected } } // `as!` checks func blackhole<T>(_ : T) { } func nongenericAnyAsUnconditionalPType(type: Any.Type) -> Bool { blackhole(type as! P.Type) return true } func nongenericAnyAsUnconditionalPProtocol(type: Any.Type) -> Bool { blackhole(type as! P.Protocol) return true } func nongenericAnyAsUnconditionalPAndAnyObjectType(type: Any.Type) -> Bool { blackhole(type as! (P & AnyObject).Type) return true } func nongenericAnyAsUnconditionalPAndPCSubType(type: Any.Type) -> Bool { blackhole(type as! (P & PCSub).Type) return true } func genericAnyAsUnconditional<T>(type: Any.Type, to: T.Type, expected: Bool) -> Bool { if #available(SwiftStdlib 5.3, *) { blackhole(type as! T.Type) } return true } // CHECK-LABEL: casting types to protocols with generics: print("casting types to protocols with generics:") print(#line, nongenericAnyIsPType(type: P.self)) // CHECK: [[@LINE]] false print(#line, nongenericAnyIsPProtocol(type: P.self)) // CHECK: [[@LINE]] true print(#line, genericAnyIs(type: P.self, to: P.self, expected: true)) // CHECK: [[@LINE]] true print(#line, nongenericAnyIsPType(type: PS.self)) // CHECK: [[@LINE]] true print(#line, PS() is P) // CHECK: [[@LINE]] true // One candidate for a Swift type theory holds that // `A is a subtype of B iff A.self is metatype<B>` // In that theory, `PS() is P` above would imply that // `PS.self is P.Protocol` below must also be true. // But that theory is not the one that Swift currently // implements. print(#line, nongenericAnyIsPProtocol(type: PS.self)) // CHECK: [[@LINE]] false print(#line, genericAnyIs(type: PS.self, to: P.self, expected: false)) // CHECK: [[@LINE]] false print(#line, nongenericAnyIsPType(type: PE.self)) // CHECK: [[@LINE]] true print(#line, nongenericAnyIsPProtocol(type: PE.self)) // CHECK: [[@LINE]] false print(#line, genericAnyIs(type: PE.self, to: P.self, expected: false)) // CHECK: [[@LINE]] false print(#line, nongenericAnyIsPType(type: PC.self)) // CHECK: [[@LINE]] true print(#line, nongenericAnyIsPProtocol(type: PC.self)) // CHECK: [[@LINE]] false print(#line, genericAnyIs(type: PC.self, to: P.self, expected: false)) // CHECK: [[@LINE]] false print(#line, nongenericAnyIsPType(type: PCSub.self)) // CHECK: [[@LINE]] true print(#line, nongenericAnyIsPProtocol(type: PCSub.self)) // CHECK: [[@LINE]] false print(#line, genericAnyIs(type: PCSub.self, to: P.self, expected: false)) // CHECK: [[@LINE]] false // CHECK-LABEL: conditionally casting types to protocols with generics: print(#line, "conditionally casting types to protocols with generics:") print(#line, nongenericAnyAsConditionalPType(type: P.self)) // CHECK: [[@LINE]] false print(#line, nongenericAnyAsConditionalPProtocol(type: P.self)) // CHECK: [[@LINE]] true print(#line, genericAnyAsConditional(type: P.self, to: P.self, expected: true)) // CHECK: [[@LINE]] true print(#line, nongenericAnyAsConditionalPType(type: PS.self)) // CHECK: [[@LINE]] true print(#line, nongenericAnyAsConditionalPProtocol(type: PS.self)) // CHECK: [[@LINE]] false print(#line, genericAnyAsConditional(type: PS.self, to: P.self, expected: false)) // CHECK: [[@LINE]] false print(#line, nongenericAnyAsConditionalPType(type: PE.self)) // CHECK: [[@LINE]] true print(#line, nongenericAnyAsConditionalPProtocol(type: PE.self)) // CHECK: [[@LINE]] false print(#line, genericAnyAsConditional(type: PE.self, to: P.self, expected: false)) // CHECK: [[@LINE]] false print(#line, nongenericAnyAsConditionalPType(type: PC.self)) // CHECK: [[@LINE]] true print(#line, nongenericAnyAsConditionalPProtocol(type: PC.self)) // CHECK: [[@LINE]] false print(#line, genericAnyAsConditional(type: PC.self, to: P.self, expected: false)) // CHECK: [[@LINE]] false print(#line, nongenericAnyAsConditionalPType(type: PCSub.self)) // CHECK: [[@LINE]] true print(#line, nongenericAnyAsConditionalPProtocol(type: PCSub.self)) // CHECK: [[@LINE]] false print(#line, genericAnyAsConditional(type: PCSub.self, to: P.self, expected: false)) // CHECK: [[@LINE]] false // CHECK-LABEL: unconditionally casting types to protocols with generics: print(#line, "unconditionally casting types to protocols with generics:") //print(#line, nongenericAnyAsUnconditionalPType(type: P.self)) // expected to trap print(#line, nongenericAnyAsUnconditionalPProtocol(type: P.self)) // CHECK: [[@LINE]] true print(#line, genericAnyAsUnconditional(type: P.self, to: P.self, expected: true)) // CHECK: [[@LINE]] true print(#line, nongenericAnyAsUnconditionalPType(type: PS.self)) // CHECK: [[@LINE]] true print(#line, genericAnyAsUnconditional(type: PS.self, to: P.self, expected: true)) // CHECK: [[@LINE]] true print(#line, nongenericAnyAsUnconditionalPType(type: PE.self)) // CHECK: [[@LINE]] true print(#line, genericAnyAsUnconditional(type: PE.self, to: P.self, expected: true)) // CHECK: [[@LINE]] true print(#line, nongenericAnyAsUnconditionalPType(type: PC.self)) // CHECK: [[@LINE]] true print(#line, genericAnyAsUnconditional(type: PC.self, to: P.self, expected: true)) // CHECK: [[@LINE]] true print(#line, nongenericAnyAsUnconditionalPType(type: PCSub.self)) // CHECK: [[@LINE]] true print(#line, genericAnyAsUnconditional(type: PCSub.self, to: P.self, expected: true)) // CHECK: [[@LINE]] true // CHECK-LABEL: casting types to protocol & AnyObject existentials: print(#line, "casting types to protocol & AnyObject existentials:") print(#line, nongenericAnyIsPAndAnyObjectType(type: PS.self)) // CHECK: [[@LINE]] false print(#line, genericAnyIs(type: PS.self, to: (P & AnyObject).self, expected: false)) // CHECK: [[@LINE]] false print(#line, nongenericAnyIsPAndAnyObjectType(type: PE.self)) // CHECK: [[@LINE]] false print(#line, genericAnyIs(type: PE.self, to: (P & AnyObject).self, expected: false)) // CHECK: [[@LINE]] false print(#line, nongenericAnyIsPAndAnyObjectType(type: PC.self)) // CHECK: [[@LINE]] true print(#line, nongenericAnyIsPAndAnyObjectProtocol(type: PC.self)) // CHECK: [[@LINE]] false print(#line, genericAnyIs(type: PC.self, to: (P & AnyObject).self, expected: false)) // CHECK: [[@LINE]] false print(#line, nongenericAnyIsPAndAnyObjectType(type: PCSub.self)) // CHECK: [[@LINE]] true print(#line, nongenericAnyIsPAndAnyObjectProtocol(type: PCSub.self)) // CHECK: [[@LINE]] false print(#line, genericAnyIs(type: PCSub.self, to: (P & AnyObject).self, expected: false)) // CHECK: [[@LINE]] false print(#line, nongenericAnyAsConditionalPAndAnyObjectType(type: PS.self)) // CHECK: [[@LINE]] false print(#line, genericAnyAsConditional(type: PS.self, to: (P & AnyObject).self, expected: false)) // CHECK: [[@LINE]] false print(#line, nongenericAnyAsConditionalPAndAnyObjectType(type: PE.self)) // CHECK: [[@LINE]] false print(#line, genericAnyAsConditional(type: PE.self, to: (P & AnyObject).self, expected: false)) // CHECK: [[@LINE]] false print(#line, nongenericAnyAsConditionalPAndAnyObjectType(type: PC.self)) // CHECK: [[@LINE]] true print(#line, nongenericAnyAsConditionalPAndAnyObjectProtocol(type: PC.self)) // CHECK: [[@LINE]] false print(#line, genericAnyAsConditional(type: PC.self, to: (P & AnyObject).self, expected: false)) // CHECK: [[@LINE]] false print(#line, nongenericAnyAsConditionalPAndAnyObjectType(type: PCSub.self)) // CHECK: [[@LINE]] true print(#line, genericAnyAsConditional(type: PCSub.self, to: (P & AnyObject).self, expected: false)) // CHECK: [[@LINE]] false // CHECK-LABEL: casting types to protocol & class existentials: print(#line, "casting types to protocol & class existentials:") print(#line, nongenericAnyIsPAndPCSubType(type: PS.self)) // CHECK: [[@LINE]] false print(#line, genericAnyIs(type: PS.self, to: (P & PCSub).self, expected: false)) // CHECK: [[@LINE]] false print(#line, nongenericAnyIsPAndPCSubType(type: PE.self)) // CHECK: [[@LINE]] false print(#line, genericAnyIs(type: PE.self, to: (P & PCSub).self, expected: false)) // CHECK: [[@LINE]] false // FIXME: reenable this when https://github.com/apple/swift/issues/53970 is fixed //print(#line, nongenericAnyIsPAndPCSubType(type: PC.self)) // C HECK: [[@LINE]] false print(#line, genericAnyIs(type: PC.self, to: (P & PCSub).self, expected: false)) // CHECK: [[@LINE]] false print(#line, nongenericAnyIsPAndPCSubType(type: PCSub.self)) // CHECK: [[@LINE]] true print(#line, genericAnyIs(type: PCSub.self, to: (P & PCSub).self, expected: false)) // CHECK: [[@LINE]] false print(#line, nongenericAnyAsConditionalPAndPCSubType(type: PS.self)) // CHECK: [[@LINE]] false print(#line, genericAnyAsConditional(type: PS.self, to: (P & PCSub).self, expected: false)) // CHECK: [[@LINE]] false print(#line, nongenericAnyAsConditionalPAndPCSubType(type: PE.self)) // CHECK: [[@LINE]] false print(#line, genericAnyAsConditional(type: PE.self, to: (P & PCSub).self, expected: false)) // CHECK: [[@LINE]] false // FIXME: reenable this when https://github.com/apple/swift/issues/53970 is fixed // print(#line, nongenericAnyAsConditionalPAndPCSubType(type: PC.self)) // C HECK: [[@LINE]] false print(#line, genericAnyAsConditional(type: PC.self, to: (P & PCSub).self, expected: false)) // CHECK: [[@LINE]] false print(#line, nongenericAnyAsConditionalPAndPCSubType(type: PCSub.self)) // CHECK: [[@LINE]] true print(#line, genericAnyAsConditional(type: PCSub.self, to: (P & PCSub).self, expected: false)) // CHECK: [[@LINE]] false // CHECK-LABEL: type comparisons: print(#line, "type comparisons:\n") print(#line, allMetasToAllMetas(Int.self, Int.self)) // CHECK: [[@LINE]] true print(#line, allMetasToAllMetas(Int.self, Float.self)) // CHECK: [[@LINE]] false print(#line, allMetasToAllMetas(C.self, C.self)) // CHECK: [[@LINE]] true print(#line, allMetasToAllMetas(D.self, C.self)) // CHECK: [[@LINE]] true print(#line, allMetasToAllMetas(C.self, D.self)) // CHECK: [[@LINE]] false print(#line, C.self is D.Type) // CHECK: [[@LINE]] false print(#line, (D.self as C.Type) is D.Type) // CHECK: [[@LINE]] true let t: Any.Type = type(of: 1 as Any) print(#line, t is Int.Type) // CHECK: [[@LINE]] true print(#line, t is Float.Type) // CHECK: [[@LINE]] false print(#line, t is C.Type) // CHECK: [[@LINE]] false let u: Any.Type = type(of: (D() as Any)) print(#line, u is C.Type) // CHECK: [[@LINE]] true print(#line, u is D.Type) // CHECK: [[@LINE]] true print(#line, u is E.Type) // CHECK: [[@LINE]] false print(#line, u is Int.Type) // CHECK: [[@LINE]] false // FIXME: Can't spell AnyObject.Protocol // CHECK-LABEL: AnyObject casts: print(#line, "AnyObject casts:") print(#line, allToAll(C(), AnyObject.self)) // CHECK: [[@LINE]] true // On Darwin, the object will be the ObjC-runtime-class object; // out of Darwin, this should not succeed. print(#line, allToAll(type(of: C()), AnyObject.self)) // CHECK-objc: true // CHECK-native: false // Bridging // NSNumber on Darwin, __SwiftValue on Linux. print(#line, allToAll(0, AnyObject.self)) // CHECK: [[@LINE]] true // This will get bridged using __SwiftValue. struct NotBridged { var x: Int } print(#line, allToAll(NotBridged(x: 0), AnyObject.self)) // CHECK: [[@LINE]] true #if canImport(Foundation) // This requires Foundation (for NSCopying): print(#line, allToAll(NotBridged(x: 0), NSCopying.self)) // CHECK-objc: [[@LINE]] true #endif // On Darwin, these casts fail (intentionally) even though __SwiftValue does // technically conform to these protocols through NSObject. // Off Darwin, it should not conform at all. print(#line, allToAll(NotBridged(x: 0), CustomStringConvertible.self)) // CHECK: [[@LINE]] false print(#line, allToAll(NotBridged(x: 0), (AnyObject & CustomStringConvertible).self)) // CHECK: [[@LINE]] false #if canImport(Foundation) // This requires Foundation (for NSArray): // // rdar://problem/19482567 // func swiftOptimizesThisFunctionIncorrectly() -> Bool { let anArray = [] as NSArray if let whyThisIsNeverExecutedIfCalledFromFunctionAndNotFromMethod = anArray as? [NSObject] { return true } return false } let result = swiftOptimizesThisFunctionIncorrectly() print(#line, "Bridge cast result: \(result)") // CHECK-NEXT-objc: Bridge cast result: true #endif
apache-2.0
67d04ac612522390e49e673eecb2cc23
41.921717
124
0.688592
3.315194
false
false
false
false
benlangmuir/swift
test/api-digester/diff-demangled-name.swift
11
1341
// RUN: %empty-directory(%t) // RUN: echo "public func foo() {}" > %t/Foo.swift // RUN: echo "public protocol P { associatedtype A }" > %t/Foo-1.swift // RUN: echo "public extension P { public func f() where A == Int {} }" >> %t/Foo-1.swift // RUN: echo "public protocol P { associatedtype A }" > %t/Foo-2.swift // RUN: echo "public extension P where A == Int { public func f() {} }" >> %t/Foo-2.swift // RUN: %target-swift-frontend -emit-module %t/Foo-1.swift -module-name Foo -emit-module-interface-path %t/Foo1.swiftinterface // RUN: %target-swift-frontend -emit-module %t/Foo-2.swift -module-name Foo -emit-module-interface-path %t/Foo2.swiftinterface // RUN: %target-swift-frontend -compile-module-from-interface %t/Foo1.swiftinterface -o %t/Foo1.swiftmodule -module-name Foo -emit-abi-descriptor-path %t/Foo1.json // RUN: %target-swift-frontend -compile-module-from-interface %t/Foo2.swiftinterface -o %t/Foo2.swiftmodule -module-name Foo -emit-abi-descriptor-path %t/Foo2.json // RUN: %api-digester -diagnose-sdk -print-module --input-paths %t/Foo1.json -input-paths %t/Foo2.json -abi -o %t/result.txt // RUN: %FileCheck %s < %t/result.txt // CHECK: Foo: Func P.f() has mangled name changing from '(extension in Foo):Foo.P.f< where A.A == Swift.Int>() -> ()' to '(extension in Foo):Foo.P< where A.A == Swift.Int>.f() -> ()'
apache-2.0
2ad4a2c334cf717b79301530ededa837
62.857143
183
0.683072
2.934354
false
false
false
false
mozilla-mobile/firefox-ios
Client/Frontend/Browser/TabCell.swift
2
12452
// 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 Foundation import UIKit import Shared // MARK: - Tab Tray Cell Protocol protocol TabTrayCell where Self: UICollectionViewCell { /// True when the tab is the selected tab in the tray var isSelectedTab: Bool { get } /// Configure a tab cell using a Tab object, setting it's selected state at the same time func configureWith(tab: Tab, isSelected selected: Bool, theme: Theme) } // MARK: - Tab Cell class TabCell: UICollectionViewCell, TabTrayCell, ReusableCell, ThemeApplicable { // MARK: - Constants enum Style { case light case dark } static let borderWidth: CGFloat = 3 // MARK: - UI Vars lazy var backgroundHolder: UIView = .build { view in view.layer.cornerRadius = GridTabTrayControllerUX.CornerRadius view.clipsToBounds = true } lazy private var faviconBG: UIView = .build { view in view.layer.cornerRadius = HomepageViewModel.UX.generalCornerRadius view.layer.borderWidth = HomepageViewModel.UX.generalBorderWidth view.layer.shadowOffset = HomepageViewModel.UX.shadowOffset view.layer.shadowRadius = HomepageViewModel.UX.shadowRadius } lazy var screenshotView: UIImageView = .build { view in view.contentMode = .scaleAspectFill view.clipsToBounds = true view.isUserInteractionEnabled = false } lazy var smallFaviconView: UIImageView = .build { view in view.contentMode = .scaleAspectFill view.clipsToBounds = true view.isUserInteractionEnabled = false view.backgroundColor = UIColor.clear view.layer.cornerRadius = HomepageViewModel.UX.generalIconCornerRadius view.layer.masksToBounds = true } lazy var titleText: UILabel = .build { label in label.isUserInteractionEnabled = false label.numberOfLines = 1 label.font = DynamicFontHelper.defaultHelper.DefaultSmallFontBold } lazy var favicon: UIImageView = .build { favicon in favicon.backgroundColor = UIColor.clear favicon.layer.cornerRadius = 2.0 favicon.layer.masksToBounds = true } lazy var closeButton: UIButton = .build { button in button.setImage(UIImage.templateImageNamed("tab_close"), for: []) button.imageView?.contentMode = .scaleAspectFit button.contentMode = .center button.imageEdgeInsets = UIEdgeInsets(equalInset: GridTabTrayControllerUX.CloseButtonEdgeInset) } // TODO: Handle visual effects theming FXIOS-5064 var title = UIVisualEffectView(effect: UIBlurEffect(style: UIColor.theme.tabTray.tabTitleBlur)) var animator: SwipeAnimator? var isSelectedTab = false weak var delegate: TabCellDelegate? // Changes depending on whether we're full-screen or not. var margin = CGFloat(0) // MARK: - Initializer override init(frame: CGRect) { super.init(frame: frame) self.animator = SwipeAnimator(animatingView: self) self.closeButton.addTarget(self, action: #selector(close), for: .touchUpInside) contentView.addSubview(backgroundHolder) faviconBG.addSubview(smallFaviconView) backgroundHolder.addSubviews(screenshotView, faviconBG) self.accessibilityCustomActions = [ UIAccessibilityCustomAction(name: .TabTrayCloseAccessibilityCustomAction, target: self.animator, selector: #selector(SwipeAnimator.closeWithoutGesture)) ] backgroundHolder.addSubview(title) title.translatesAutoresizingMaskIntoConstraints = false title.contentView.addSubview(self.closeButton) title.contentView.addSubview(self.titleText) title.contentView.addSubview(self.favicon) setupConstraint() } func setupConstraint() { NSLayoutConstraint.activate([ backgroundHolder.topAnchor.constraint(equalTo: contentView.topAnchor), backgroundHolder.leadingAnchor.constraint(equalTo: contentView.leadingAnchor), backgroundHolder.bottomAnchor.constraint(equalTo: contentView.bottomAnchor), backgroundHolder.trailingAnchor.constraint(equalTo: contentView.trailingAnchor), title.topAnchor.constraint(equalTo: backgroundHolder.topAnchor), title.leftAnchor.constraint(equalTo: backgroundHolder.leftAnchor), title.rightAnchor.constraint(equalTo: backgroundHolder.rightAnchor), title.heightAnchor.constraint(equalToConstant: GridTabTrayControllerUX.TextBoxHeight), favicon.leadingAnchor.constraint(equalTo: title.leadingAnchor, constant: 6), favicon.topAnchor.constraint(equalTo: title.topAnchor, constant: (GridTabTrayControllerUX.TextBoxHeight - GridTabTrayControllerUX.FaviconSize) / 2), favicon.heightAnchor.constraint(equalToConstant: GridTabTrayControllerUX.FaviconSize), favicon.widthAnchor.constraint(equalToConstant: GridTabTrayControllerUX.FaviconSize), closeButton.heightAnchor.constraint(equalToConstant: GridTabTrayControllerUX.CloseButtonSize), closeButton.widthAnchor.constraint(equalToConstant: GridTabTrayControllerUX.CloseButtonSize), closeButton.centerYAnchor.constraint(equalTo: title.contentView.centerYAnchor), closeButton.trailingAnchor.constraint(equalTo: title.trailingAnchor), titleText.leadingAnchor.constraint(equalTo: favicon.trailingAnchor, constant: 6), titleText.trailingAnchor.constraint(equalTo: closeButton.leadingAnchor, constant: 6), titleText.centerYAnchor.constraint(equalTo: title.contentView.centerYAnchor), screenshotView.topAnchor.constraint(equalTo: topAnchor), screenshotView.leftAnchor.constraint(equalTo: backgroundHolder.leftAnchor), screenshotView.rightAnchor.constraint(equalTo: backgroundHolder.rightAnchor), screenshotView.bottomAnchor.constraint(equalTo: backgroundHolder.bottomAnchor), faviconBG.centerYAnchor.constraint(equalTo: centerYAnchor, constant: 10), faviconBG.centerXAnchor.constraint(equalTo: centerXAnchor), faviconBG.heightAnchor.constraint(equalToConstant: TopSiteItemCell.UX.imageBackgroundSize.height), faviconBG.widthAnchor.constraint(equalToConstant: TopSiteItemCell.UX.imageBackgroundSize.width), smallFaviconView.heightAnchor.constraint(equalToConstant: TopSiteItemCell.UX.iconSize.height), smallFaviconView.widthAnchor.constraint(equalToConstant: TopSiteItemCell.UX.iconSize.width), smallFaviconView.centerYAnchor.constraint(equalTo: faviconBG.centerYAnchor), smallFaviconView.centerXAnchor.constraint(equalTo: faviconBG.centerXAnchor), ]) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() let shadowPath = CGRect(width: layer.frame.width + (TabCell.borderWidth * 2), height: layer.frame.height + (TabCell.borderWidth * 2)) layer.shadowPath = UIBezierPath(roundedRect: shadowPath, cornerRadius: GridTabTrayControllerUX.CornerRadius+TabCell.borderWidth).cgPath } // MARK: - Configure tab cell with a Tab func configureWith(tab: Tab, isSelected selected: Bool, theme: Theme) { isSelectedTab = selected applyTheme(theme: theme) titleText.text = tab.getTabTrayTitle() accessibilityLabel = getA11yTitleLabel(tab: tab) isAccessibilityElement = true accessibilityHint = .TabTraySwipeToCloseAccessibilityHint favicon.image = UIImage(named: ImageIdentifiers.defaultFavicon) if let favIcon = tab.displayFavicon, let url = URL(string: favIcon.url) { ImageLoadingHandler.shared.getImageFromCacheOrDownload(with: url, limit: ImageLoadingConstants.NoLimitImageSize) { image, error in guard error == nil, let image = image else { return } self.favicon.image = image } } if selected { setTabSelected(tab.isPrivate, theme: theme) } else { layer.shadowOffset = .zero layer.shadowPath = nil layer.shadowOpacity = 0 } faviconBG.isHidden = true // Regular screenshot for home or internal url when tab has home screenshot if let url = tab.url, let tabScreenshot = tab.screenshot, (url.absoluteString.starts(with: "internal") && tab.hasHomeScreenshot) { screenshotView.image = tabScreenshot // Favicon or letter image when home screenshot is present for a regular (non-internal) url } else if let url = tab.url, (!url.absoluteString.starts(with: "internal") && tab.hasHomeScreenshot) { setFaviconImage(for: tab, with: smallFaviconView) // Tab screenshot when available } else if let tabScreenshot = tab.screenshot { screenshotView.image = tabScreenshot // Favicon or letter image when tab screenshot isn't available } else { setFaviconImage(for: tab, with: smallFaviconView) } } func applyTheme(theme: Theme) { backgroundHolder.backgroundColor = theme.colors.layer1 closeButton.tintColor = theme.colors.indicatorActive titleText.textColor = theme.colors.textPrimary screenshotView.backgroundColor = theme.colors.layer1 favicon.tintColor = theme.colors.textPrimary } override func prepareForReuse() { // Reset any close animations. super.prepareForReuse() screenshotView.image = nil backgroundHolder.transform = .identity backgroundHolder.alpha = 1 self.titleText.font = DynamicFontHelper.defaultHelper.DefaultSmallFontBold layer.shadowOffset = .zero layer.shadowPath = nil layer.shadowOpacity = 0 isHidden = false } override func accessibilityScroll(_ direction: UIAccessibilityScrollDirection) -> Bool { var right: Bool switch direction { case .left: right = false case .right: right = true default: return false } animator?.close(right: right) return true } @objc func close() { delegate?.tabCellDidClose(self) } private func setTabSelected(_ isPrivate: Bool, theme: Theme) { // This creates a border around a tabcell. Using the shadow creates a border _outside_ of the tab frame. layer.shadowColor = (isPrivate ? theme.colors.borderAccentPrivate : theme.colors.borderAccent).cgColor layer.shadowOpacity = 1 layer.shadowRadius = 0 // A 0 radius creates a solid border instead of a gradient blur layer.masksToBounds = false // create a frame that is "BorderWidth" size bigger than the cell layer.shadowOffset = CGSize(width: -TabCell.borderWidth, height: -TabCell.borderWidth) let shadowPath = CGRect(width: layer.frame.width + (TabCell.borderWidth * 2), height: layer.frame.height + (TabCell.borderWidth * 2)) layer.shadowPath = UIBezierPath(roundedRect: shadowPath, cornerRadius: GridTabTrayControllerUX.CornerRadius+TabCell.borderWidth).cgPath } func setFaviconImage(for tab: Tab, with imageView: UIImageView) { if let url = tab.url?.domainURL ?? tab.sessionData?.urls.last?.domainURL { imageView.setImageAndBackground(forIcon: tab.displayFavicon, website: url) {} faviconBG.isHidden = false screenshotView.image = nil } } } // MARK: - Extension Tab Tray Cell protocol extension TabTrayCell { func getA11yTitleLabel(tab: Tab) -> String? { let baseName = tab.getTabTrayTitle() if isSelectedTab, let baseName = baseName, !baseName.isEmpty { return baseName + ". " + String.TabTrayCurrentlySelectedTabAccessibilityLabel } else if isSelectedTab { return String.TabTrayCurrentlySelectedTabAccessibilityLabel } else { return baseName } } }
mpl-2.0
1bcac695ac722be44cd5602653b9e2e5
41.790378
164
0.689528
5.245156
false
false
false
false
mrdepth/Neocom
Neocom/Neocom/Fitting/TypePicker.swift
2
4376
// // TypePicker.swift // Neocom // // Created by Artem Shimanski on 2/24/20. // Copyright © 2020 Artem Shimanski. All rights reserved. // import SwiftUI import Expressible import CoreData class TypePickerManager { private let typePickerState = Cache<SDEDgmppItemGroup, TypePicker>() func get(_ parentGroup: SDEDgmppItemGroup, environment: EnvironmentValues, sharedState: SharedState, completion: @escaping (SDEInvType?) -> Void) -> some View { let services = ServicesViewModifier(environment: environment, sharedState: sharedState) let picker = typePickerState[parentGroup, default: TypePicker(content: TypePickerViewController(parentGroup: parentGroup, services: services, completion: {_ in}))] picker.content.completion = { completion($0) } return picker.modifier(services) } } class TypePickerViewController: UIViewController { var completion: (SDEInvType?) -> Void private var rootViewController: UINavigationController? init(parentGroup: SDEDgmppItemGroup, services: ServicesViewModifier, completion: @escaping (SDEInvType?) -> Void) { self.completion = completion super.init(nibName: nil, bundle: nil) let view = TypePickerPage(parentGroup: parentGroup) { [weak self] type in self?.completion(type) } .navigationBarItems(leading: BarButtonItems.close { [weak self] in self?.completion(nil) }).modifier(services) rootViewController = UINavigationController(rootViewController: UIHostingController(rootView: view)) addChild(rootViewController!) } override func viewDidLoad() { super.viewDidLoad() view.addSubview(rootViewController!.view) rootViewController?.view.frame = view.bounds } override func viewDidLayoutSubviews() { rootViewController?.view.frame = view.bounds } required init?(coder aDecoder: NSCoder) { fatalError() } } struct TypePicker: UIViewRepresentable { var content: TypePickerViewController func makeUIView(context: Context) -> UIView { return content.view } func updateUIView(_ uiView: UIView, context: Context) { } // // func makeUIViewController(context: Context) -> TypePickerViewController { // return content // } // // func updateUIViewController(_ uiViewController: TypePickerViewController, context: Context) { // } } struct TypePickerWrapper: View { @Environment(\.managedObjectContext) private var managedObjectContext var parentGroup: SDEDgmppItemGroup var completion: (SDEInvType?) -> Void var page: TypePickerPage init(parentGroup: SDEDgmppItemGroup, completion: @escaping (SDEInvType?) -> Void) { self.parentGroup = parentGroup self.completion = completion page = TypePickerPage(parentGroup: parentGroup) { completion($0) } } var body: some View { page.navigationBarItems(leading: BarButtonItems.close { self.completion(nil) }) } } struct TypePickerPage: View, Equatable { static func == (lhs: TypePickerPage, rhs: TypePickerPage) -> Bool { true } var parentGroup: SDEDgmppItemGroup var completion: (SDEInvType) -> Void @Environment(\.managedObjectContext) private var managedObjectContext @State private var selectedGroup: SDEDgmppItemGroup? @ObservedObject var searchHelper = TypePickerSearchHelper() var body: some View { Group { if (parentGroup.subGroups?.count ?? 0) > 0 { TypePickerGroups(parentGroup: parentGroup, searchHelper: searchHelper, completion: completion) } else { TypePickerTypes(parentGroup: parentGroup, searchHelper: searchHelper, completion: completion) } } } } #if DEBUG struct TypePicker_Previews: PreviewProvider { static var previews: some View { let context = Storage.testStorage.persistentContainer.viewContext let group = try! context.fetch(SDEDgmppItemGroup.rootGroup(categoryID: .ship)).first! return TypePicker(content: TypePickerViewController(parentGroup: group, services: ServicesViewModifier.testModifier(), completion: {_ in})).edgesIgnoringSafeArea(.all) } } #endif
lgpl-2.1
3e2e2674319450cbd8d7d2347cd00eab
32.653846
175
0.677943
4.882813
false
false
false
false
Ehrippura/firefox-ios
Client/Frontend/Browser/SimpleToast.swift
1
2745
/* 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 Foundation import Shared struct SimpleToastUX { static let ToastHeight = BottomToolbarHeight static let ToastAnimationDuration = 0.5 static let ToastDefaultColor = UIColor(red: 10 / 255, green: 132 / 255, blue: 255.0 / 255, alpha: 1) static let ToastFont = UIFont.systemFont(ofSize: 15) static let ToastDismissAfter = DispatchTimeInterval.milliseconds(4500) // 4.5 seconds. static let ToastDelayBefore = DispatchTimeInterval.milliseconds(0) // 0 seconds static let BottomToolbarHeight = CGFloat(45) } struct SimpleToast { func showAlertWithText(_ text: String, bottomContainer: UIView) { guard let window = UIApplication.shared.windows.first else { return } let toast = self.createView() toast.text = text window.addSubview(toast) toast.snp.makeConstraints { (make) in make.width.equalTo(bottomContainer) make.left.equalTo(bottomContainer) make.height.equalTo(SimpleToastUX.ToastHeight) make.bottom.equalTo(bottomContainer) } animate(toast) } fileprivate func createView() -> UILabel { let toast = UILabel() toast.textColor = UIColor.white toast.backgroundColor = SimpleToastUX.ToastDefaultColor toast.font = SimpleToastUX.ToastFont toast.textAlignment = .center return toast } fileprivate func dismiss(_ toast: UIView) { UIView.animate(withDuration: SimpleToastUX.ToastAnimationDuration, animations: { var frame = toast.frame frame.origin.y = frame.origin.y + SimpleToastUX.ToastHeight frame.size.height = 0 toast.frame = frame }, completion: { finished in toast.removeFromSuperview() } ) } fileprivate func animate(_ toast: UIView) { UIView.animate(withDuration: SimpleToastUX.ToastAnimationDuration, animations: { var frame = toast.frame frame.origin.y = frame.origin.y - SimpleToastUX.ToastHeight frame.size.height = SimpleToastUX.ToastHeight toast.frame = frame }, completion: { finished in let dispatchTime = DispatchTime.now() + SimpleToastUX.ToastDismissAfter DispatchQueue.main.asyncAfter(deadline: dispatchTime, execute: { self.dismiss(toast) }) } ) } }
mpl-2.0
5c4fae036f25362e538283dfe8619d93
35.6
104
0.622951
4.981851
false
false
false
false
adeca/SwiftySwift
SwiftyGeometry/CGFloatTuple.swift
1
4706
// // CGFloatTuple.swift // SwiftySwift // // Created by Agustin De Cabrera on 5/18/16. // Copyright © 2016 Agustín de Cabrera. All rights reserved. // import CoreGraphics // MARK: - CGFloatTuple /// Type that can be serialized to a pair of CGFloat values public typealias CGFloatTuple = (CGFloat, CGFloat) public protocol CGFloatTupleConvertible { var tuple: CGFloatTuple { get } init(tuple: CGFloatTuple) // methods with default implementations init<T: CGFloatTupleConvertible>(_ other: T) } extension CGFloatTupleConvertible { public init<T: CGFloatTupleConvertible>(_ other: T) { self.init(tuple: other.tuple) } public func makeIterator() -> AnyIterator<CGFloat> { return AnyIterator([tuple.0, tuple.1].makeIterator()) } public func max() -> CGFloat { return Swift.max(tuple.0, tuple.1) } public func min() -> CGFloat { return Swift.min(tuple.0, tuple.1) } } /// Functional methods used to apply transforms to a pair of floats extension CGFloatTupleConvertible { public func map(_ transform: (CGFloat) throws -> CGFloat) rethrows -> Self { let t = self.tuple let result = (try transform(t.0), try transform(t.1)) return Self(tuple: result) } public func merge(_ other: CGFloatTupleConvertible, _ transform: (CGFloat, CGFloat) throws -> CGFloat) rethrows -> Self { let (t0, t1) = (self.tuple, other.tuple) let result = (try transform(t0.0, t1.0), try transform(t0.1, t1.1)) return Self(tuple: result) } public func merge(_ others: [CGFloatTupleConvertible], _ transform: ([CGFloat]) throws -> CGFloat) rethrows -> Self { let tuples = [self.tuple] + others.map { $0.tuple } let result = (try transform(tuples.map { $0.0 }), try transform(tuples.map { $0.1 })) return Self(tuple: result) } } /// Operators that can be applied to a pair of CGFloatTupleConvertible objects /// Each operation will work on an element-by-element basis extension CGFloatTupleConvertible { public static func +<T: CGFloatTupleConvertible>(lhs: Self, rhs: T) -> Self { return lhs.merge(rhs, +) } public static func +=<T: CGFloatTupleConvertible>(lhs: inout Self, rhs: T) { lhs = lhs + rhs } public static func -<T: CGFloatTupleConvertible>(lhs: Self, rhs: T) -> Self { return lhs.merge(rhs, -) } public static func -=<T: CGFloatTupleConvertible>(lhs: inout Self, rhs: T) { lhs = lhs - rhs } public static func - (lhs: Self, rhs: CGFloat) -> Self { return lhs.map({ $0 - rhs }) } public static func -= (lhs: inout Self, rhs: CGFloat) { lhs = lhs - rhs } public static func *(lhs: Self, rhs: CGFloat) -> Self { return lhs.map { $0 * rhs } } public static func *=(lhs: inout Self, rhs: CGFloat) { lhs = lhs * rhs } public static func /(lhs: Self, rhs: CGFloat) -> Self { return lhs.map { $0 / rhs } } public static func /=(lhs: inout Self, rhs: CGFloat) { lhs = lhs / rhs } public static func *<T: CGFloatTupleConvertible>(lhs: Self, rhs: T) -> Self { return lhs.merge(rhs, *) } public static func *=<T: CGFloatTupleConvertible>(lhs: inout Self, rhs: T) { lhs = lhs * rhs } public static func /<T: CGFloatTupleConvertible>(lhs: Self, rhs: T) -> Self { return lhs.merge(rhs, /) } public static func /=<T: CGFloatTupleConvertible>(lhs: inout Self, rhs: T) { lhs = lhs / rhs } public static prefix func -(rhs: Self) -> Self { return rhs.map { -$0 } } } public func abs<T: CGFloatTupleConvertible>(_ x: T) -> T { return x.map { abs($0) } } public func clamp<T: CGFloatTupleConvertible>(_ x: T, min: CGFloatTupleConvertible, max: CGFloatTupleConvertible) -> T { return x.merge([min, max]) { clamp($0[0], min: $0[1], max: $0[2]) } } @available(*, deprecated) public func clamp<T: CGFloatTupleConvertible>(_ x: T, _ min: CGFloatTupleConvertible, _ max: CGFloatTupleConvertible) -> T { return clamp(x, min: min, max: max) } extension CGRect { /// Multiply the rect's origin and size by the given value public static func * <U: CGFloatTupleConvertible>(lhs: CGRect, rhs: U) -> CGRect { return CGRect(origin: lhs.origin * rhs, size: lhs.size * rhs) } /// Multiply the rect's origin and size by the given value public static func *= <U: CGFloatTupleConvertible>(lhs: inout CGRect, rhs: U) { lhs = lhs * rhs } }
mit
7703f795c4e379b0a352e0e921703115
30.783784
125
0.607568
3.811994
false
false
false
false
master-nevi/UPnAtom
Source/UPnP Objects/AbstractUPnPService.swift
1
21458
// // AbstractUPnPService.swift // // Copyright (c) 2015 David Robles // // 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 Ono import AFNetworking public class AbstractUPnPService: AbstractUPnP { // public public var serviceType: String { return urn } public private(set) var serviceID: String! // TODO: Should ideally be a constant, see Github issue #10 public var serviceDescriptionURL: NSURL { return NSURL(string: _relativeServiceDescriptionURL.absoluteString, relativeToURL: baseURL)! } public var controlURL: NSURL { return NSURL(string: _relativeControlURL.absoluteString, relativeToURL: baseURL)! } public var eventURL: NSURL { return NSURL(string: _relativeEventURL.absoluteString, relativeToURL: baseURL)! } override public var baseURL: NSURL! { if let baseURL = _baseURLFromXML { return baseURL } return super.baseURL } public weak var deviceSource: UPnPDeviceSource? public var device: AbstractUPnPDevice? { return deviceSource?.device(forUSN: _deviceUSN) } /// protected public private(set) var soapSessionManager: SOAPSessionManager! // TODO: Should ideally be a constant, see Github issue #10 // private private var _baseURLFromXML: NSURL? // TODO: Should ideally be a constant, see Github issue #10 private var _relativeServiceDescriptionURL: NSURL! // TODO: Should ideally be a constant, see Github issue #10 private var _relativeControlURL: NSURL! // TODO: Should ideally be a constant, see Github issue #10 private var _relativeEventURL: NSURL! // TODO: Should ideally be a constant, see Github issue #10 private var _deviceUSN: UniqueServiceName! // TODO: Should ideally be a constant, see Github issue #10 private var _serviceDescriptionDocument: ONOXMLDocument? private static let _serviceDescriptionDefaultPrefix = "service" /// Must be accessed within dispatch_sync() or dispatch_async() and updated within dispatch_barrier_async() to the concurrent queue private var _soapActionsSupportCache = [String: Bool]() // MARK: UPnP Event handling related /// Must be accessed within dispatch_sync() or dispatch_async() and updated within dispatch_barrier_async() to the concurrent queue lazy private var _eventObservers = [EventObserver]() private var _concurrentEventObserverQueue: dispatch_queue_t! private var _concurrentSOAPActionsSupportCacheQueue = dispatch_queue_create("com.upnatom.abstract-upnp-service.soap-actions-support-cache-queue", DISPATCH_QUEUE_CONCURRENT) private weak var _eventSubscription: AnyObject? required public init?(usn: UniqueServiceName, descriptionURL: NSURL, descriptionXML: NSData) { super.init(usn: usn, descriptionURL: descriptionURL, descriptionXML: descriptionXML) soapSessionManager = SOAPSessionManager(baseURL: baseURL, sessionConfiguration: nil) _concurrentEventObserverQueue = dispatch_queue_create("com.upnatom.abstract-upnp-service.event-observer-queue.\(usn.rawValue)", DISPATCH_QUEUE_CONCURRENT) let serviceParser = UPnPServiceParser(upnpService: self, descriptionXML: descriptionXML) let parsedService = serviceParser.parse().value if let baseURL = parsedService?.baseURL { _baseURLFromXML = baseURL } guard let serviceID = parsedService?.serviceID, let relativeServiceDescriptionURL = parsedService?.relativeServiceDescriptionURL, let relativeControlURL = parsedService?.relativeControlURL, let relativeEventURL = parsedService?.relativeEventURL, let deviceUSN = parsedService?.deviceUSN else { return nil } self.serviceID = serviceID self._relativeServiceDescriptionURL = relativeServiceDescriptionURL self._relativeControlURL = relativeControlURL self._relativeEventURL = relativeEventURL self._deviceUSN = deviceUSN } deinit { // deinit may be called during init if init returns nil, queue var may not be set guard _concurrentEventObserverQueue != nil else { return } var eventObservers: [EventObserver]! dispatch_sync(_concurrentEventObserverQueue, { () -> Void in eventObservers = self._eventObservers }) for eventObserver in eventObservers { NSNotificationCenter.defaultCenter().removeObserver(eventObserver.notificationCenterObserver) } } /// The service description document can be used for querying for service specific support i.e. SOAP action arguments public func serviceDescriptionDocument(completion: (serviceDescriptionDocument: ONOXMLDocument?, defaultPrefix: String) -> Void) { if let serviceDescriptionDocument = _serviceDescriptionDocument { completion(serviceDescriptionDocument: serviceDescriptionDocument, defaultPrefix: AbstractUPnPService._serviceDescriptionDefaultPrefix) } else { let httpSessionManager = AFHTTPSessionManager() httpSessionManager.requestSerializer = AFHTTPRequestSerializer() httpSessionManager.responseSerializer = AFHTTPResponseSerializer() httpSessionManager.GET(serviceDescriptionURL.absoluteString, parameters: nil, success: { (task: NSURLSessionDataTask, responseObject: AnyObject?) in dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in guard let xmlData = responseObject as? NSData else { completion(serviceDescriptionDocument: nil, defaultPrefix: AbstractUPnPService._serviceDescriptionDefaultPrefix) return } do { let serviceDescriptionDocument = try ONOXMLDocument(data: xmlData) LogVerbose("Parsing service description XML:\nSTART\n\(NSString(data: xmlData, encoding: NSUTF8StringEncoding))\nEND") serviceDescriptionDocument.definePrefix(AbstractUPnPService._serviceDescriptionDefaultPrefix, forDefaultNamespace: "urn:schemas-upnp-org:service-1-0") self._serviceDescriptionDocument = serviceDescriptionDocument completion(serviceDescriptionDocument: serviceDescriptionDocument, defaultPrefix: AbstractUPnPService._serviceDescriptionDefaultPrefix) } catch let parseError as NSError { LogError("Failed to parse service description for SOAP action support check: \(parseError)") completion(serviceDescriptionDocument: nil, defaultPrefix: AbstractUPnPService._serviceDescriptionDefaultPrefix) } }) }, failure: { (task: NSURLSessionDataTask?, error: NSError) in LogError("Failed to retrieve service description for SOAP action support check: \(error)") completion(serviceDescriptionDocument: nil, defaultPrefix: AbstractUPnPService._serviceDescriptionDefaultPrefix) }) } } /// Used for determining support of optional SOAP actions for this service. public func supportsSOAPAction(actionParameters actionParameters: SOAPRequestSerializer.Parameters, completion: (isSupported: Bool) -> Void) { let soapActionName = actionParameters.soapAction // only reading SOAP actions support cache, so distpach_async is appropriate to allow for concurrent reads dispatch_async(_concurrentSOAPActionsSupportCacheQueue, { () -> Void in let soapActionsSupportCache = self._soapActionsSupportCache dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in if let isSupported = soapActionsSupportCache[soapActionName] { completion(isSupported: isSupported) } else { self.serviceDescriptionDocument { (serviceDescriptionDocument: ONOXMLDocument?, defaultPrefix: String) -> Void in if let serviceDescriptionDocument = serviceDescriptionDocument { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in // For better performance, check the action name only for now. If this proves inadequite in the future the argument list can also be compared with the SOAP parameters passed in. let prefix = defaultPrefix let xPathQuery = "/\(prefix):scpd/\(prefix):actionList/\(prefix):action[\(prefix):name='\(soapActionName)']" let isSupported = serviceDescriptionDocument.firstChildWithXPath(xPathQuery) != nil ? true : false dispatch_barrier_async(self._concurrentSOAPActionsSupportCacheQueue) { () -> Void in self._soapActionsSupportCache[soapActionName] = isSupported } completion(isSupported: isSupported) } } else { // Failed to retrieve service description. This result does not warrant recording false in the cache as the service description may still show the action as supported when retreived in a subsequent attempt. completion(isSupported: false) } } } } }) } /// overridable by service subclasses public func createEvent(eventXML: NSData) -> UPnPEvent { return UPnPEvent(eventXML: eventXML, service: self) } } // MARK: UPnP Event handling extension AbstractUPnPService: UPnPEventSubscriber { private static let _upnpEventKey = "UPnPEventKey" private class EventObserver { let notificationCenterObserver: AnyObject init(notificationCenterObserver: AnyObject) { self.notificationCenterObserver = notificationCenterObserver } } private func UPnPEventReceivedNotification() -> String { return "UPnPEventReceivedNotification.\(usn.rawValue)" } /// Returns an opaque object to act as the observer. Use it when the event observer needs to be removed. public func addEventObserver(queue: NSOperationQueue?, callBackBlock: (event: UPnPEvent) -> Void) -> AnyObject { /// Use callBackBlock for event notifications. While the notifications are backed by NSNotifications for broadcasting, they should only be used internally in order to keep track of how many subscribers there are. let observer = EventObserver(notificationCenterObserver: NSNotificationCenter.defaultCenter().addObserverForName(UPnPEventReceivedNotification(), object: nil, queue: queue) { (notification: NSNotification!) -> Void in if let event = notification.userInfo?[AbstractUPnPService._upnpEventKey] as? UPnPEvent { callBackBlock(event: event) } }) dispatch_barrier_async(_concurrentEventObserverQueue, { () -> Void in self._eventObservers.append(observer) if self._eventObservers.count >= 1 { // subscribe UPnPEventSubscriptionManager.sharedInstance.subscribe(self, eventURL: self.eventURL, completion: { (subscription: Result<AnyObject>) -> Void in switch subscription { case .Success(let value): self._eventSubscription = value case .Failure(let error): let errorDescription = error.localizedDescription("Unknown subscribe error") LogError("Unable to subscribe to UPnP events from \(self.eventURL): \(errorDescription)") } }) } }) return observer } public func removeEventObserver(observer: AnyObject) { dispatch_barrier_async(_concurrentEventObserverQueue, { () -> Void in if let observer = observer as? EventObserver { self._eventObservers.removeObject(observer) NSNotificationCenter.defaultCenter().removeObserver(observer.notificationCenterObserver) } if self._eventObservers.count == 0 { // unsubscribe if let eventSubscription: AnyObject = self._eventSubscription { self._eventSubscription = nil UPnPEventSubscriptionManager.sharedInstance.unsubscribe(eventSubscription, completion: { (result: EmptyResult) -> Void in if let error = result.error { let errorDescription = error.localizedDescription("Unknown unsubscribe error") LogError("Unable to unsubscribe to UPnP events from \(self.eventURL): \(errorDescription)") } }) } } }) } func handleEvent(eventSubscriptionManager: UPnPEventSubscriptionManager, eventXML: NSData) { NSNotificationCenter.defaultCenter().postNotificationName(UPnPEventReceivedNotification(), object: nil, userInfo: [AbstractUPnPService._upnpEventKey: self.createEvent(eventXML)]) } func subscriptionDidFail(eventSubscriptionManager: UPnPEventSubscriptionManager) { LogWarn("Event subscription did fail for service: \(self)") } } extension AbstractUPnPService.EventObserver: Equatable { } private func ==(lhs: AbstractUPnPService.EventObserver, rhs: AbstractUPnPService.EventObserver) -> Bool { return lhs.notificationCenterObserver === rhs.notificationCenterObserver } /// for objective-c type checking extension AbstractUPnP { public func isAbstractUPnPService() -> Bool { return self is AbstractUPnPService } } /// overrides ExtendedPrintable protocol implementation extension AbstractUPnPService { override public var className: String { return "\(self.dynamicType)" } override public var description: String { var properties = PropertyPrinter() properties.add(super.className, property: super.description) properties.add("deviceUSN", property: _deviceUSN) properties.add("serviceType", property: serviceType) properties.add("serviceID", property: serviceID) properties.add("serviceDescriptionURL", property: serviceDescriptionURL.absoluteString) properties.add("controlURL", property: controlURL.absoluteString) properties.add("eventURL", property: eventURL.absoluteString) return properties.description } } @objc public protocol UPnPDeviceSource: class { func device(forUSN usn: UniqueServiceName) -> AbstractUPnPDevice? } class UPnPServiceParser: AbstractSAXXMLParser { /// Using a class instead of struct since it's much easier and safer to continuously update from references rather than values directly as it's easy to accidentally update a copy and not the original. class ParserUPnPService { var baseURL: NSURL? var serviceType: String? var serviceID: String? var relativeServiceDescriptionURL: NSURL? var relativeControlURL: NSURL? var relativeEventURL: NSURL? var deviceUSN: UniqueServiceName? } private unowned let _upnpService: AbstractUPnPService private let _descriptionXML: NSData private var _baseURL: NSURL? private var _deviceType: String? private var _currentParserService: ParserUPnPService? private var _foundParserService: ParserUPnPService? init(supportNamespaces: Bool, upnpService: AbstractUPnPService, descriptionXML: NSData) { self._upnpService = upnpService self._descriptionXML = descriptionXML super.init(supportNamespaces: supportNamespaces) /// NOTE: URLBase is deprecated in UPnP v2.0, baseURL should be derived from the SSDP discovery description URL self.addElementObservation(SAXXMLParserElementObservation(elementPath: ["root", "URLBase"], didStartParsingElement: nil, didEndParsingElement: nil, foundInnerText: { [unowned self] (elementName, text) -> Void in self._baseURL = NSURL(string: text) })) self.addElementObservation(SAXXMLParserElementObservation(elementPath: ["*", "device", "deviceType"], didStartParsingElement: nil, didEndParsingElement: nil, foundInnerText: { [unowned self] (elementName, text) -> Void in self._deviceType = text })) self.addElementObservation(SAXXMLParserElementObservation(elementPath: ["*", "device", "serviceList", "service"], didStartParsingElement: { (elementName, attributeDict) -> Void in self._currentParserService = ParserUPnPService() }, didEndParsingElement: { (elementName) -> Void in if let serviceType = self._currentParserService?.serviceType where serviceType == self._upnpService.urn { self._foundParserService = self._currentParserService } }, foundInnerText: nil)) self.addElementObservation(SAXXMLParserElementObservation(elementPath: ["*", "device", "serviceList", "service", "serviceType"], didStartParsingElement: nil, didEndParsingElement: nil, foundInnerText: { [unowned self] (elementName, text) -> Void in let currentService = self._currentParserService currentService?.serviceType = text })) self.addElementObservation(SAXXMLParserElementObservation(elementPath: ["*", "device", "serviceList", "service", "serviceId"], didStartParsingElement: nil, didEndParsingElement: nil, foundInnerText: { [unowned self] (elementName, text) -> Void in let currentService = self._currentParserService currentService?.serviceID = text })) self.addElementObservation(SAXXMLParserElementObservation(elementPath: ["*", "device", "serviceList", "service", "SCPDURL"], didStartParsingElement: nil, didEndParsingElement: nil, foundInnerText: { [unowned self] (elementName, text) -> Void in let currentService = self._currentParserService currentService?.relativeServiceDescriptionURL = NSURL(string: text) })) self.addElementObservation(SAXXMLParserElementObservation(elementPath: ["*", "device", "serviceList", "service", "controlURL"], didStartParsingElement: nil, didEndParsingElement: nil, foundInnerText: { [unowned self] (elementName, text) -> Void in let currentService = self._currentParserService currentService?.relativeControlURL = NSURL(string: text) })) self.addElementObservation(SAXXMLParserElementObservation(elementPath: ["*", "device", "serviceList", "service", "eventSubURL"], didStartParsingElement: nil, didEndParsingElement: nil, foundInnerText: { [unowned self] (elementName, text) -> Void in let currentService = self._currentParserService currentService?.relativeEventURL = NSURL(string: text) })) } convenience init(upnpService: AbstractUPnPService, descriptionXML: NSData) { self.init(supportNamespaces: false, upnpService: upnpService, descriptionXML: descriptionXML) } func parse() -> Result<ParserUPnPService> { switch super.parse(data: _descriptionXML) { case .Success: if let foundParserService = _foundParserService { foundParserService.baseURL = _baseURL if let deviceType = _deviceType { foundParserService.deviceUSN = UniqueServiceName(uuid: _upnpService.uuid, urn: deviceType) } return .Success(foundParserService) } else { return .Failure(createError("Parser error")) } case .Failure(let error): return .Failure(error) } } }
mit
6a729f3c0909ac92cf08c0ac21a5bbc4
53.879795
256
0.668189
5.170602
false
false
false
false
J1aDong/GoodBooks
GoodBooks/AppDelegate.swift
1
7209
// // AppDelegate.swift // GoodBooks // // Created by J1aDong on 2017/1/24. // Copyright © 2017年 J1aDong. All rights reserved. // import UIKit import CoreData import AVOSCloud @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. //MARK: 打印所有的字体 // let familyNames = UIFont.familyNames // for fanilyName:String in familyNames // { // print("Family: \(fanilyName.utf8)") // let fontNames = UIFont.fontNames(forFamilyName: fanilyName) // for fontName:String in fontNames // { // //[@心语风尚]这里打印的系统的字体,对汉字不是全适用,对英语都适用 // print("\t",fontName,"\n") // } // } self.window = UIWindow(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT)) // applicationId 即 App Id,applicationKey 是 App Key AVOSCloud.setApplicationId("TA9p1dH9HIS1cDaVB8cu33eO-gzGzoHsz", clientKey: "M0Da93ljH6lN61H3iFGl5Nnr") let tabbarController = UITabBarController() let rankController = UINavigationController(rootViewController: rankViewController()) let searchConroller = UINavigationController(rootViewController: searchViewController()) let circleController = UINavigationController(rootViewController: circleViewController()) let pushController = UINavigationController(rootViewController: pushViewController()) let moreController = UINavigationController(rootViewController: moreViewController()) tabbarController.viewControllers = [rankController,searchConroller,pushController,circleController,moreController] let tabbarItem1 = UITabBarItem(title: "排行榜", image: UIImage(named: "bio"), selectedImage: UIImage(named: "bio_red")) let tabbarItem2 = UITabBarItem(title: "发现", image: UIImage(named: "timer 2"),selectedImage:UIImage(named:"timer 2_red")) let tabbarItem3 = UITabBarItem(title: "", image: UIImage(named: "pencil"),selectedImage: UIImage(named: "pencil_red")) let tabbarItem4 = UITabBarItem(title: "圈子", image: UIImage(named: "users two-2"),selectedImage:UIImage(named:"users two-2__red")) let tabbarItem5 = UITabBarItem(title: "更多", image: UIImage(named: "more"),selectedImage:UIImage(named:"more_red")) rankController.tabBarItem = tabbarItem1 searchConroller.tabBarItem = tabbarItem2 pushController.tabBarItem = tabbarItem3 circleController.tabBarItem = tabbarItem4 moreController.tabBarItem = tabbarItem5 rankController.tabBarController?.tabBar.tintColor = MAIN_RED self.window?.rootViewController = tabbarController self.window?.makeKeyAndVisible() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "GoodBooks") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
mit
6a5c774a0634c842c4c07c1fa5e84d82
49.771429
285
0.681908
5.280832
false
false
false
false
Mattmlm/tipcalculatorswift
Tip Calculator/Tip Calculator/Constants.swift
1
545
// // Constants.swift // Tip Calculator // // Created by admin on 8/31/15. // Copyright (c) 2015 mattmo. All rights reserved. // /* *Colors */ let kMainColorGreen = "#6FECBF"; let kBackgroundColorGreen2 = "#61C882"; let kLastCloseDate = "lastCloseDate"; let kLastBillTotal = "lastBillTotal"; let kLastTipPercentage = "lastTipPercentage"; let kLastBillSplitNumber = "lastBillSplitNumber"; let kCountryCodeDefault = "countryCodeDefault"; let kCountryIndexDefault = "countryIndexDefault"; let kTipPercentageDefault = "tipPercentageDefault";
mit
bfad0b667df19299bd4804910ecfe329
22.73913
51
0.755963
3.364198
false
false
false
false
cocoaheadsru/server
Sources/App/Models/RegForm/RegForm.swift
1
1378
import Vapor import FluentProvider // sourcery: AutoModelGeneratable // sourcery: toJSON, Preparation, ResponseRepresentable final class RegForm: Model { let storage = Storage() var eventId: Identifier var formName: String var description: String init(eventId: Identifier, formName: String, description: String) { self.eventId = eventId self.formName = formName self.description = description } // sourcery:inline:auto:RegForm.AutoModelGeneratable init(row: Row) throws { eventId = try row.get(Keys.eventId) formName = try row.get(Keys.formName) description = try row.get(Keys.description) } func makeRow() throws -> Row { var row = Row() try row.set(Keys.eventId, eventId) try row.set(Keys.formName, formName) try row.set(Keys.description, description) return row } // sourcery:end } extension RegForm { // sourcery: nestedJSONRepresentableField func regFields() throws -> [RegField] { return try children().all() } func eventRegFields() throws -> [RegField] { return try RegField.makeQuery().filter(RegField.Keys.regFormId, id).all() } var event: Event? { return try? parent(id: eventId).get()! } static func getRegForm(by eventId: Int) throws -> RegForm? { return try RegForm.makeQuery().filter(Keys.eventId, eventId).first() } }
mit
e69660a01bb5f62e3b1d7fe3e5b6fb61
23.175439
77
0.679971
3.859944
false
false
false
false
MrLSPBoy/LSPDouYu
LSPDouYuTV/LSPDouYuTV/Classes/Tools/Extension/UIBarButtonItem+Extension.swift
1
1333
// // UIBarButtonItem+Extension.swift // LSPDouYuTV // // Created by lishaopeng on 17/2/28. // Copyright © 2017年 lishaopeng. All rights reserved. // import UIKit extension UIBarButtonItem{ /**类方法 class func createItem(imageName: String, highImageName: String, size: CGSize) -> UIBarButtonItem{ let btn = UIButton() btn.setImage(UIImage(named: imageName), for: .normal) btn.setImage(UIImage(named: highImageName), for: .highlighted) btn.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: size) return UIBarButtonItem(customView: btn) } */ /**构造函数*/ //便利构造函数: 1>convenience开头 2>在构造函数中必须明确调用一个设计的构造函数(使用self调用) convenience init(imageName: String, highImageName: String = "", size: CGSize = CGSize(width: 0, height: 0)) { let btn = UIButton() btn.setImage(UIImage(named: imageName), for: .normal) if highImageName != "" { btn.setImage(UIImage(named: highImageName), for: .highlighted) } if size == CGSize(width: 0, height: 0){ btn.sizeToFit() }else{ btn.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: size) } self.init(customView: btn) } }
mit
0690e721757363eb8b87a763f2853799
29.487805
113
0.6024
3.99361
false
false
false
false
harlanhaskins/SwiftSAT
Sources/SAT/DIMACS.swift
1
2208
// // DIMACSReader.swift // SATPackageDescription // // Created by Harlan Haskins on 9/21/17. // import Foundation /// A namespace for DIMACS-related functions. struct DIMACSReader { /// A set of errors that can happen while parsing a DIMACS file. enum Error: Swift.Error { case unexpectedEntry(String) case invalidSpecificationLine(String) } /// Reads the DIMACS file at the provided filename into a CNF formula. func read(filename: String) throws -> CNF { let string = try String(contentsOf: URL(fileURLWithPath: filename), encoding: .utf8) return try read(string) } func read(_ string: String) throws -> CNF { return try read(lines: string.split(separator: "\n")) } private func read(line: Substring) throws -> Clause { // Parse individual clauses as space-separated variable lists. var vars = Set<Variable>() let scanner = Scanner(string: String(line)) scanner.charactersToBeSkipped = .whitespaces var n = 0 while scanner.scanInt(&n) { if n == 0 { break } vars.insert(Variable(number: abs(n), isNegative: n < 0)) } return Clause(variables: vars) } /// Parses the DIMACS file lines into a CNF formula. private func read(lines: [Substring]) throws -> CNF { var clauses = [Clause]() var numberOfVariables = 0 for line in lines { // Skip comment lines. if line.hasPrefix("c") { continue } // Attempt to parse the `p cnf $numVariables $numClauses` // specification line. if line.hasPrefix("p cnf") { guard let varNumberString = line.split(separator: " ") .dropFirst(2).first, let n = Int(varNumberString) else { throw Error.invalidSpecificationLine(String(line)) } numberOfVariables = n continue } clauses.append(try read(line: line)) } return CNF(numberOfVariables: numberOfVariables, clauses: clauses) } }
mit
4a7931577817d7352373c8e23cca8ed5
32.454545
75
0.572464
4.460606
false
false
false
false
jnewc/Swift-FlexBox
FlexBoxFramework/FlexBoxFramework/FlexBox.swift
1
10324
// // FlexBox.swift // FlexBox // // Created by Jack Newcombe on 06/03/2015. // Copyright (c) 2015 jnewc. All rights reserved. // import Foundation import UIKit var flexMap: [UIView: Int] = [UIView: Int](); public extension UIView { public var flex : Int { get { if let flex = flexMap[self] { return flex; } else { return 1; } } set { flexMap[self] = newValue; } } } public enum FlexOrient { case Horizontal, Vertical ;} public enum FlexAlign { case Start, End, Center, Justify, Stretch, Flex ;} /** * A view that uses a flexible box layout to arrange its subviews. */ public class FlexBox : UIView { /** * The orientation in which child views will be arranged */ private var orient : FlexOrient = FlexOrient.Horizontal; /** * The alignment of child views along the target axis */ public var orientAlign : FlexAlign = FlexAlign.Start; /** * The alignment of child views along the cross axis */ public var crossAlign : FlexAlign = FlexAlign.Start; // -- Init -------------------------------------------------------------------------------------------------------------- override public init() { super.init(); } override public init(frame: CGRect) { super.init(frame: frame); } required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder); } public init(type: FlexOrient) { super.init(); self.orient = type; } public init(frame: CGRect, orient: FlexOrient) { super.init(frame: frame); self.orient = orient; } public init(frame: CGRect, views: [UIView]) { super.init(frame: frame); for view in views { self += view; } } public convenience init(frame: CGRect, orient: FlexOrient, align: FlexAlign, crossAlign: FlexAlign, views: UIView...) { self.init(frame: frame, views: views); self.orient = orient; self.orientAlign = align; self.crossAlign = crossAlign; } public convenience init(orient: FlexOrient, align: FlexAlign, crossAlign: FlexAlign, flex: Int, views: UIView...) { self.init(frame: CGRectZero, views: views); self.orient = orient; self.orientAlign = align; self.crossAlign = crossAlign; self.flex = flex; } // -- Subview Layout ---------------------------------------------------------------------------------------------------- override public func layoutSubviews() { let views : [UIView] = self.subviews as [UIView]; let count = views.count; layoutOrientAxis(views); for (index, view) in enumerate(views) { layoutCrossAxis(view); self.bringSubviewToFront(view); } //NSLog("FlexBox: layoutSubviews: %@", NSStringFromCGRect(views[0].frame)); } private func layoutOrientAxis(views: [UIView]) { switch(orientAlign) { case FlexAlign.Stretch: let size = self.getOrientAxisSize(self) / CGFloat(views.count); var position : CGFloat = 0; for view in views { setOrientAxisSize(view, size: size); setOrientAxisPosition(view, position: position); position += size; } break; case FlexAlign.Center: let viewsSize : CGFloat = views.reduce(0.0) { $0 + self.getOrientAxisSize($1) }; var position : CGFloat = (getOrientAxisSize(self) / 2.0) - (viewsSize / 2.0); for view in views { setOrientAxisPosition(view, position: position); position += getOrientAxisSize(view); } break; case FlexAlign.Justify: let viewsSize : CGFloat = views.reduce(0.0) { $0 + self.getOrientAxisSize($1) }; let margin = (self.getOrientAxisSize(self) - viewsSize) / CGFloat(views.count + 1); var position : CGFloat = margin; for view in views { setOrientAxisPosition(view, position: position); position += self.getOrientAxisSize(view) + margin; } break; case FlexAlign.Flex: let flex = views.reduce(0, combine: { $0 + $1.flex }); var addedSize : CGFloat = 0; for view in views { if(view.flex == 0) { addedSize += self.getOrientAxisSize(view); } } if(addedSize > self.getOrientAxisSize(self)) { NSException(name: "BadValue", reason: "Size of non-flexs child views too large.", userInfo: nil); } let size = self.getOrientAxisSize(self) - addedSize; println("size=\(size), addedSize=\(addedSize), flex=\(flex)"); let segmentSize = size / CGFloat(flex); var position : CGFloat = 0.0; for view in views { setOrientAxisPosition(view, position: position); var w : CGFloat; if(view.flex > 0) { w = segmentSize * CGFloat(view.flex); } else { w = self.getOrientAxisSize(view); } setOrientAxisSize(view, size: w); position += w; } break; case FlexAlign.Start: var position : CGFloat = 0.0; for view in views { setOrientAxisPosition(view, position: position); position += getOrientAxisSize(view); } break; case FlexAlign.End: let allWidth : CGFloat = views.reduce(0.0) { $0 + self.getOrientAxisSize($1) }; var position : CGFloat = getOrientAxisSize(self) - allWidth; for view in views { setOrientAxisPosition(view, position: position); position += getOrientAxisSize(view); } break; default: break; } } private func layoutCrossAxis(view: UIView) { switch(crossAlign) { case FlexAlign.Stretch: self.setCrossAxisSize(view, size: getCrossAxisSize(self)); break; case FlexAlign.Center, FlexAlign.Justify, FlexAlign.Flex: var position = (getCrossAxisSize(self) / 2.0) - (getCrossAxisSize(view) / 2.0); self.setCrossAxisPosition(view, position: position); break; case FlexAlign.Start: self.setCrossAxisPosition(view, position: 0); break; case FlexAlign.End: var position = getCrossAxisSize(self) - getCrossAxisSize(view); self.setCrossAxisPosition(view, position: position); break default: break; } } // -- Layout Utilities -------------------------------------------------------------------------------------------------- // Orient Axis private func getOrientAxisSize(view: UIView) -> CGFloat { if(isHorizontal) { return view.frame.width; } if(isVertical) { return view.frame.height; } return 0; } private func setOrientAxisSize(view: UIView, size: CGFloat) { if(isHorizontal) { view.frame.size.width = size; } if(isVertical) { view.frame.size.height = size; } } private func getOrientAxisPosition(view: UIView) -> CGFloat { if(isHorizontal) { return view.frame.origin.x; } if(isVertical){ return view.frame.origin.y; } return 0; } private func setOrientAxisPosition(view: UIView, position: CGFloat) { if(isHorizontal) { view.frame.origin.x = position; } if(isVertical) { view.frame.origin.y = position; } } // Cross Axis private func getCrossAxisSize(view: UIView) -> CGFloat { if(isHorizontal) { return view.frame.height; } if(isVertical) { return view.frame.width; } return 0; } private func setCrossAxisSize(view: UIView, size: CGFloat) { if(isHorizontal) { view.frame.size.height = size; } if(isVertical) { view.frame.size.width = size; } } private func getCrossAxisPosition(view: UIView) -> CGFloat { if(isHorizontal) { return view.frame.origin.y; } if(isVertical) { return view.frame.origin.x; } return 0; } private func setCrossAxisPosition(view: UIView, position: CGFloat) { if(isHorizontal) { view.frame.origin.y = position; } if(isVertical) { view.frame.origin.x = position; } } // Other var isHorizontal : Bool { get { return self.orient == FlexOrient.Horizontal; } } var isVertical : Bool { get { return self.orient == FlexOrient.Vertical; } } // -- Layout Utilities -------------------------------------------------------------------------------------------------- public class func fromDictionary(dict: Dictionary<String, AnyObject>) { let keys = dict.keys; for key in keys { let data : AnyObject = dict[key]!; if (data is Dictionary<String, AnyObject>) { } else if data is Array<Dictionary<String, AnyObject>> { } } } } public func +=(left: FlexBox, right: UIView) { left.addSubview(right); }
apache-2.0
f9a56b057ffacb963b4385bcee0b1a79
26.902703
125
0.492348
4.707706
false
false
false
false
brentdax/swift
test/IRGen/class_field_other_module.swift
1
1202
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module -emit-module-path=%t/other_class.swiftmodule %S/Inputs/other_class.swift // RUN: %target-swift-frontend -I %t -emit-ir -O %s | %FileCheck %s -DINT=i%target-ptrsize import other_class // CHECK-LABEL: define {{(protected )?}}{{(dllexport )?}}swiftcc i32 @"$s24class_field_other_module12getSubclassXys5Int32V0c1_A00F0CF"(%T11other_class8SubclassC* nocapture readonly) // CHECK-NEXT: entry: // CHECK-NEXT: %._value = getelementptr inbounds %T11other_class8SubclassC, %T11other_class8SubclassC* %0, [[INT]] 0, i32 1, i32 0 // CHECK-NEXT: %1 = load i32, i32* %._value // CHECK-NEXT: ret i32 %1 public func getSubclassX(_ o: Subclass) -> Int32 { return o.x } // CHECK-LABEL: define {{(protected )?}}{{(dllexport )?}}swiftcc i32 @"$s24class_field_other_module12getSubclassYys5Int32V0c1_A00F0CF"(%T11other_class8SubclassC* nocapture readonly) // CHECK-NEXT: entry: // CHECK-NEXT: %._value = getelementptr inbounds %T11other_class8SubclassC, %T11other_class8SubclassC* %0, [[INT]] 0, i32 2, i32 0 // CHECK-NEXT: %1 = load i32, i32* %._value // CHECK-NEXT: ret i32 %1 public func getSubclassY(_ o: Subclass) -> Int32 { return o.y }
apache-2.0
1d261c0c19ddee35f6fe9ef2955cd311
49.083333
181
0.708819
2.938875
false
false
false
false
RevenueCat/purchases-ios
Sources/Networking/Caching/CallbackCache.swift
1
2343
// // Copyright RevenueCat Inc. All Rights Reserved. // // Licensed under the MIT License (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://opensource.org/licenses/MIT // // CallbackCache.swift // // Created by Joshua Liebowitz on 11/18/21. import Foundation /** Generic callback cache whose primary usage is to help ensure API calls in flight are not duplicated. Users of this class will store a completion block for any Cacheable API call that is running. If the same request is made while a request is in-flight, the completion block will be added to the list and the API call will not be performed. Once the first API call has finished, the user is required to call `performOnAllItemsAndRemoveFromCache`. This way the results from the initial API call will be surfaced to the waiting completion blocks from the duplicate API calls that were not sent. After being called these blocks are removed from the cache. */ final class CallbackCache<T> where T: CacheKeyProviding { let cachedCallbacksByKey: Atomic<[String: [T]]> = .init([:]) func add(_ callback: T) -> CallbackCacheStatus { return self.cachedCallbacksByKey.modify { cachedCallbacksByKey in var values = cachedCallbacksByKey[callback.cacheKey] ?? [] let cacheStatus: CallbackCacheStatus = !values.isEmpty ? .addedToExistingInFlightList : .firstCallbackAddedToList values.append(callback) cachedCallbacksByKey[callback.cacheKey] = values return cacheStatus } } func performOnAllItemsAndRemoveFromCache(withCacheable cacheable: CacheKeyProviding, _ block: (T) -> Void) { self.cachedCallbacksByKey.modify { cachedCallbacksByKey in guard let items = cachedCallbacksByKey.removeValue(forKey: cacheable.cacheKey) else { return } items.forEach(block) } } } extension CallbackCache: Sendable where T: Sendable {} /** For use with `CallbackCache`. We store a list of callback objects in the cache and the key used for the list of callbacks is provided by an object that conforms to `CacheKeyProviding`. */ protocol CacheKeyProviding { var cacheKey: String { get } }
mit
1045e489e6262578d9a6fea35272569e
36.190476
117
0.705506
4.479924
false
false
false
false
TCA-Team/iOS
TUM Campus App/DataSources/TuitionDataSource.swift
1
3016
// // TuitionDataSource.swift // Campus // // This file is part of the TUM Campus App distribution https://github.com/TCA-Team/iOS // Copyright (c) 2018 TCA // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, version 3. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // import UIKit class TuitionDataSource: NSObject, TUMDataSource, TUMInteractiveDataSource { let parent: CardViewController var manager: TuitionStatusManager let cellType: AnyClass = TuitionCollectionViewCell.self var data: [Tuition] = [] var isEmpty: Bool { return data.isEmpty } var cardKey: CardKey { return manager.cardKey } let dateFormatter = DateFormatter() let numberFormatter = NumberFormatter() let preferredHeight: CGFloat = 128.0 lazy var flowLayoutDelegate: ColumnsFlowLayoutDelegate = FixedColumnsFlowLayoutDelegate(delegate: self) init(parent: CardViewController, manager: TuitionStatusManager) { self.parent = parent self.manager = manager self.dateFormatter.dateStyle = .short self.dateFormatter.timeStyle = .none self.numberFormatter.numberStyle = .currency self.numberFormatter.currencySymbol = "€" super.init() } func refresh(group: DispatchGroup) { group.enter() manager.fetch().onSuccess(in: .main) { data in self.data = data group.leave() } } func onItemSelected(at indexPath: IndexPath) { let storyboard = UIStoryboard(name: "Tution", bundle: nil) if let destination = storyboard.instantiateInitialViewController() as? TuitionTableViewController { destination.delegate = parent parent.navigationController?.pushViewController(destination, animated: true) } } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return data.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell( withReuseIdentifier: cellReuseID, for: indexPath) as! TuitionCollectionViewCell let tuition = data[indexPath.row] cell.balanceLabel.text = numberFormatter.string(from: NSNumber(value: tuition.soll)) cell.deadlineLabel.text = dateFormatter.string(from: tuition.frist) return cell } }
gpl-3.0
e548b3711b828d0efd4734b3ff360161
36.209877
107
0.680159
4.86129
false
false
false
false
qiuncheng/study-for-swift
Detector/Detector/ViewController.swift
1
5043
// // ViewController.swift // Detector // // Created by yolo on 2017/1/19. // Copyright © 2017年 Qiuncheng. All rights reserved. // import UIKit import CoreImage class ViewController: UIViewController { var imagePickerController: UIImagePickerController? var imageView: UIImageView! var label: UILabel! override func viewDidLoad() { super.viewDidLoad() let openPhotoButton = UIButton() openPhotoButton.setTitle(NSLocalizedString("打开相册", comment: "打开相册"), for: .normal) openPhotoButton.layer.cornerRadius = 5.0 openPhotoButton.layer.masksToBounds = true openPhotoButton.backgroundColor = UIColor.yellow openPhotoButton.setTitleColor(UIColor.black, for: .normal) openPhotoButton.setTitleColor(UIColor.white, for: .highlighted) openPhotoButton.addTarget(self, action: #selector(openPhotoButtonClicked), for: .touchUpInside) openPhotoButton.translatesAutoresizingMaskIntoConstraints = false view.addSubview(openPhotoButton) view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-20-[button]-20-|", options: .alignAllTop, metrics: [:], views: ["view": view, "button": openPhotoButton])) view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-64-[button(==44)]", options: .alignAllTop, metrics: [:], views: ["view":view, "button":openPhotoButton])) let imageView = UIImageView() imageView.contentMode = .scaleAspectFit imageView.backgroundColor = UIColor.lightGray imageView.layer.cornerRadius = 5.0 imageView.layer.masksToBounds = true imageView.layer.shadowColor = UIColor.black.cgColor imageView.layer.shadowOffset = CGSize(width: 10, height: 10) imageView.layer.shadowRadius = 20 imageView.isUserInteractionEnabled = true imageView.translatesAutoresizingMaskIntoConstraints = false imageView.image = #imageLiteral(resourceName: "IMG_0668") let tap = UITapGestureRecognizer(target: self, action: #selector(detectorImage)) imageView.addGestureRecognizer(tap) view.addSubview(imageView) self.imageView = imageView view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-20-[imageView]-20-|", options: [], metrics: [:], views: ["imageView": imageView])) view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[button]-20-[imageView]-150-|", options: [], metrics: [:], views: ["button": openPhotoButton, "imageView": imageView])) let label = UILabel() label.backgroundColor = UIColor.lightGray label.text = "No feature." label.numberOfLines = 0 label.layer.cornerRadius = 5.0 label.layer.masksToBounds = true label.translatesAutoresizingMaskIntoConstraints = false view.addSubview(label) self.label = label view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-20-[label]-20-|", options: [], metrics: [:], views: ["label": label])) view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[imageView]-20-[label]-20-|", options: [], metrics: [:], views: ["label": label, "imageView": imageView])) } func detectorImage(image: UIImage?) { guard let image = imageView.image, let cgImage = image.cgImage else { return } // guard let cgImage = image.cgImage else { return } let ciImage = CIImage(cgImage: cgImage) let detector = CIDetector(ofType: CIDetectorTypeFace, context: nil, options: [CIDetectorAccuracy: CIDetectorAccuracyHigh]) if let features = detector?.features(in: ciImage) as? [CIFaceFeature] { for feature in features { DispatchQueue.main.async { [weak self] in self?.label.text = "type: \(feature.type) + bounds: \(feature.bounds) + " } } } } func openPhotoButtonClicked() { imagePickerController = UIImagePickerController() imagePickerController?.allowsEditing = false imagePickerController?.sourceType = .photoLibrary imagePickerController?.delegate = self present(imagePickerController!, animated: true, completion: nil) } } extension ViewController: UINavigationControllerDelegate, UIImagePickerControllerDelegate { func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { picker.dismiss(animated: true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage else { return } imageView.image = image detectorImage(image: image) picker.dismiss(animated: true, completion: { picker.delegate = nil }) } }
mit
83a6a009cc96fea8b0837a97c98634d1
44.261261
199
0.671975
5.190083
false
false
false
false
qiuncheng/study-for-swift
learn-rx-swift/Chocotastic-starter/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift
6
8328
// // VirtualTimeScheduler.swift // Rx // // Created by Krunoslav Zaher on 2/14/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation /** Base class for virtual time schedulers using a priority queue for scheduled items. */ open class VirtualTimeScheduler<Converter: VirtualTimeConverterType> : SchedulerType , CustomDebugStringConvertible { public typealias VirtualTime = Converter.VirtualTimeUnit public typealias VirtualTimeInterval = Converter.VirtualTimeIntervalUnit private var _running : Bool private var _clock: VirtualTime fileprivate var _schedulerQueue : PriorityQueue<VirtualSchedulerItem<VirtualTime>> private var _converter: Converter private var _nextId = 0 /** - returns: Current time. */ public var now: RxTime { return _converter.convertFromVirtualTime(clock) } /** - returns: Scheduler's absolute time clock value. */ public var clock: VirtualTime { return _clock } /** Creates a new virtual time scheduler. - parameter initialClock: Initial value for the clock. */ public init(initialClock: VirtualTime, converter: Converter) { _clock = initialClock _running = false _converter = converter _schedulerQueue = PriorityQueue(hasHigherPriority: { switch converter.compareVirtualTime($0.time, $1.time) { case .lessThan: return true case .equal: return $0.id < $1.id case .greaterThan: return false } }) #if TRACE_RESOURCES let _ = AtomicIncrement(&resourceCount) #endif } /** Schedules an action to be executed immediatelly. - parameter state: State passed to the action to be executed. - parameter action: Action to be executed. - returns: The disposable object used to cancel the scheduled action (best effort). */ public func schedule<StateType>(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { return self.scheduleRelative(state, dueTime: 0.0) { a in return action(a) } } /** Schedules an action to be executed. - parameter state: State passed to the action to be executed. - parameter dueTime: Relative time after which to execute the action. - parameter action: Action to be executed. - returns: The disposable object used to cancel the scheduled action (best effort). */ public func scheduleRelative<StateType>(_ state: StateType, dueTime: RxTimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable { let time = self.now.addingTimeInterval(dueTime) let absoluteTime = _converter.convertToVirtualTime(time) let adjustedTime = self.adjustScheduledTime(absoluteTime) return scheduleAbsoluteVirtual(state, time: adjustedTime, action: action) } /** Schedules an action to be executed after relative time has passed. - parameter state: State passed to the action to be executed. - parameter time: Absolute time when to execute the action. If this is less or equal then `now`, `now + 1` will be used. - parameter action: Action to be executed. - returns: The disposable object used to cancel the scheduled action (best effort). */ public func scheduleRelativeVirtual<StateType>(_ state: StateType, dueTime: VirtualTimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable { let time = _converter.offsetVirtualTime(self.clock, offset: dueTime) return scheduleAbsoluteVirtual(state, time: time, action: action) } /** Schedules an action to be executed at absolute virtual time. - parameter state: State passed to the action to be executed. - parameter time: Absolute time when to execute the action. - parameter action: Action to be executed. - returns: The disposable object used to cancel the scheduled action (best effort). */ public func scheduleAbsoluteVirtual<StateType>(_ state: StateType, time: Converter.VirtualTimeUnit, action: @escaping (StateType) -> Disposable) -> Disposable { MainScheduler.ensureExecutingOnScheduler() let compositeDisposable = CompositeDisposable() let item = VirtualSchedulerItem(action: { let dispose = action(state) return dispose }, time: time, id: _nextId) _nextId += 1 _schedulerQueue.enqueue(item) _ = compositeDisposable.insert(item) return compositeDisposable } /** Adjusts time of scheduling before adding item to schedule queue. */ open func adjustScheduledTime(_ time: Converter.VirtualTimeUnit) -> Converter.VirtualTimeUnit { return time } /** Starts the virtual time scheduler. */ public func start() { MainScheduler.ensureExecutingOnScheduler() if _running { return } _running = true repeat { guard let next = findNext() else { break } if _converter.compareVirtualTime(next.time, self.clock).greaterThan { _clock = next.time } next.invoke() _schedulerQueue.remove(next) } while _running _running = false } func findNext() -> VirtualSchedulerItem<VirtualTime>? { while let front = _schedulerQueue.peek() { if front.isDisposed { _schedulerQueue.remove(front) continue } return front } return nil } /** Advances the scheduler's clock to the specified time, running all work till that point. - parameter virtualTime: Absolute time to advance the scheduler's clock to. */ public func advanceTo(_ virtualTime: VirtualTime) { MainScheduler.ensureExecutingOnScheduler() if _running { fatalError("Scheduler is already running") } _running = true repeat { guard let next = findNext() else { break } if _converter.compareVirtualTime(next.time, virtualTime).greaterThan { break } if _converter.compareVirtualTime(next.time, self.clock).greaterThan { _clock = next.time } next.invoke() _schedulerQueue.remove(next) } while _running _clock = virtualTime _running = false } /** Advances the scheduler's clock by the specified relative time. */ public func sleep(_ virtualInterval: VirtualTimeInterval) { MainScheduler.ensureExecutingOnScheduler() let sleepTo = _converter.offsetVirtualTime(clock, offset: virtualInterval) if _converter.compareVirtualTime(sleepTo, clock).lessThen { fatalError("Can't sleep to past.") } _clock = sleepTo } /** Stops the virtual time scheduler. */ public func stop() { MainScheduler.ensureExecutingOnScheduler() _running = false } #if TRACE_RESOURCES deinit { _ = AtomicDecrement(&resourceCount) } #endif } // MARK: description extension VirtualTimeScheduler { /** A textual representation of `self`, suitable for debugging. */ public var debugDescription: String { return self._schedulerQueue.debugDescription } } class VirtualSchedulerItem<Time> : Disposable { typealias Action = () -> Disposable let action: Action let time: Time let id: Int var isDisposed: Bool { return disposable.isDisposed } var disposable = SingleAssignmentDisposable() init(action: @escaping Action, time: Time, id: Int) { self.action = action self.time = time self.id = id } func invoke() { self.disposable.disposable = action() } func dispose() { self.disposable.dispose() } } extension VirtualSchedulerItem : CustomDebugStringConvertible { var debugDescription: String { return "\(time)" } }
mit
5056628d36b395865f2fd50bb3b2e616
27.517123
164
0.624835
5.071255
false
false
false
false
NordicSemiconductor/IOS-nRF-Toolbox
nRF Toolbox/Profiles/ContinuousGlucoseMonitor/Sections/TimeIntervalSection.swift
1
2566
/* * Copyright (c) 2020, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. 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. * * 3. Neither the name of the copyright holder 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 TimeIntervalSection: Section { private var timeSliderModel = StepperCellModel(min: 1, max: 10, step: 1, value: 1) let timeIntervalChanged: (Int) -> () func dequeCell(for index: Int, from tableView: UIKit.UITableView) -> UIKit.UITableViewCell { let cell = tableView.dequeueCell(ofType: StepperTableViewCell.self) cell.update(with: timeSliderModel) cell.timeIntervalChanges = { [unowned self] ti in self.timeSliderModel.value = Double(ti) self.timeIntervalChanged(ti) } return cell } func reset() { } let numberOfItems: Int = 1 let sectionTitle: String = "Time Interval" let id: Identifier<Section> let isHidden: Bool = false init(id: Identifier<Section>, timeIntervalChanged: @escaping (Int) -> () ) { self.id = id self.timeIntervalChanged = timeIntervalChanged } //TODO: Check correct size func cellHeight(for index: Int) -> CGFloat { 54.0 } }
bsd-3-clause
cf8b4c93e09b263315a9f7476e2f1d7f
39.09375
96
0.73032
4.549645
false
false
false
false
toineheuvelmans/Metron
source/Metron/Geometry/CoordinateSystem.swift
1
5763
import CoreGraphics /** * A `CoordinateSystem` is a simple description of a two-dimensional space, * defined by its origin (the visual corner in which the origin {0, 0} * is found. On iOS this defaults to top / left, while on macOS this is * bottom / left. * The `CoordinateSystem` is used to translate from visual positions * (top, right, bottom, left) to coordinate positions (minY, maxX, maxY, minX). */ public struct CoordinateSystem { #if os(macOS) public static let `default` = CoordinateSystem(origin: .bottomLeft) #elseif os(iOS) || os(watchOS) || os(tvOS) public static let `default` = CoordinateSystem(origin: .topLeft) #endif public var origin: CornerPosition public init(origin: CornerPosition) { self.origin = origin } } public extension CoordinateSystem { // MARK: Corners /** * Returns the `Corners` matching the `CornerPositions` in this * coordinate system, running clockwise starting at topLeft. */ public var corners: [Corner] { return CornerPosition.all.map { corner(for: $0) } } /** * Returns the `Corners` matching the `CornerPositions` in this * coordinate system, starting and in rotating order as * provided. */ public func corners(startingAt start: Corner, rotating: RotationDirection = .clockwise) -> [Corner] { var arrangedCorners: [Corner] = corners arrangedCorners = rotating == .clockwise ? arrangedCorners : arrangedCorners.reversed() while arrangedCorners[0] != start { arrangedCorners.append(arrangedCorners.remove(at: 0)) } return arrangedCorners } /// - returns: The `CornerPosition` of the `Corner` in this CoordinateSystem. public func position(for corner: Corner) -> CornerPosition { let tlsCorner: CornerPosition // topLeft system corner switch corner { case .minXminY: tlsCorner = .topLeft case .maxXminY: tlsCorner = .topRight case .minXmaxY: tlsCorner = .bottomLeft case .maxXmaxY: tlsCorner = .bottomRight } switch origin { case .topLeft: return tlsCorner case .topRight: return tlsCorner.opposite(on: .xAxis) case .bottomLeft: return tlsCorner.opposite(on: .yAxis) case .bottomRight: return tlsCorner.opposite } } /// - returns: The `Corner` at the `CornerPosition` in this CoordinateSystem. public func corner(for position: CornerPosition) -> Corner { let tlsPosition: Corner // topLeft system position switch position { case .topLeft: tlsPosition = .minXminY case .topRight: tlsPosition = .maxXminY case .bottomLeft: tlsPosition = .minXmaxY case .bottomRight: tlsPosition = .maxXmaxY } switch origin { case .topLeft: return tlsPosition case .topRight: return tlsPosition.opposite(on: .xAxis) case .bottomLeft: return tlsPosition.opposite(on: .yAxis) case .bottomRight: return tlsPosition.opposite } } // MARK: Edges /** * Returns the `CGRectEdges` matching the `Sides` in this * coordinate system, running clockwise starting at top. */ public var edges: [CGRectEdge] { return Side.all.map { edge(for: $0) } } /** * Returns the `CGRectEdges` matching the `Sides` in this * coordinate system, starting and in rotating order as * provided. */ public func edges(startingAt start: CGRectEdge, rotating: RotationDirection = .clockwise) -> [CGRectEdge] { var arrangedEdges: [CGRectEdge] = edges arrangedEdges = rotating == .clockwise ? arrangedEdges : arrangedEdges.reversed() while arrangedEdges[0] != start { arrangedEdges.append(arrangedEdges.remove(at: 0)) } return arrangedEdges } /// - returns: The `Side` of the `CGRectEdge` in this CoordinateSystem public func side(for edge: CGRectEdge) -> Side { let tlsSide: Side // topLeft system side switch edge { case .minXEdge: tlsSide = .left case .maxXEdge: tlsSide = .right case .minYEdge: tlsSide = .top case .maxYEdge: tlsSide = .bottom } switch origin { case .topLeft: return tlsSide case .topRight: return tlsSide.axis == .xAxis ? tlsSide.opposite : tlsSide case .bottomLeft: return tlsSide.axis == .yAxis ? tlsSide.opposite : tlsSide case .bottomRight: return tlsSide.opposite } } /// - returns: The `CGRectEdge` at the `Side` in this CoordinateSystem public func edge(for side: Side) -> CGRectEdge { let tlsEdge: CGRectEdge // topLeft system edge switch side { case .top: tlsEdge = .minYEdge case .right: tlsEdge = .maxXEdge case .bottom: tlsEdge = .maxYEdge case .left: tlsEdge = .minXEdge } switch origin { case .topLeft: return tlsEdge case .topRight: return tlsEdge.axis == .xAxis ? tlsEdge.opposite : tlsEdge case .bottomLeft: return tlsEdge.axis == .yAxis ? tlsEdge.opposite : tlsEdge case .bottomRight: return tlsEdge.opposite } } /// - returns: True if a circle, traced by incrementing an angle, runs clockwise public var circleRunsClockwise: Bool { switch origin { case .topLeft, .bottomRight: return true case .bottomLeft, .topRight: return false } } } // MARK: CustomDebugStringConvertible extension CoordinateSystem: CustomDebugStringConvertible { public var debugDescription: String { return "CoordinateSystem {origin: \(origin)}" } }
mit
e4307f1ead79019e5a9634db73f01397
34.795031
95
0.634912
4.446759
false
false
false
false
wilfreddekok/Antidote
Antidote/ProfileTabCoordinator.swift
1
8303
// 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 AudioToolbox protocol ProfileTabCoordinatorDelegate: class { func profileTabCoordinatorDelegateLogout(coordinator: ProfileTabCoordinator) func profileTabCoordinatorDelegateDeleteProfile(coordinator: ProfileTabCoordinator) func profileTabCoordinatorDelegateDidChangeUserStatus(coordinator: ProfileTabCoordinator) func profileTabCoordinatorDelegateDidChangeAvatar(coordinator: ProfileTabCoordinator) func profileTabCoordinatorDelegateDidChangeUserName(coordinator: ProfileTabCoordinator) } class ProfileTabCoordinator: ActiveSessionNavigationCoordinator { weak var delegate: ProfileTabCoordinatorDelegate? private weak var toxManager: OCTManager! init(theme: Theme, toxManager: OCTManager) { self.toxManager = toxManager super.init(theme: theme) } override func startWithOptions(options: CoordinatorOptions?) { let controller = ProfileMainController(theme: theme, submanagerUser: toxManager.user) controller.delegate = self navigationController.pushViewController(controller, animated: false) } } extension OCTToxErrorSetInfoCode: ErrorType { } extension ProfileTabCoordinator: ProfileMainControllerDelegate { func profileMainControllerLogout(controller: ProfileMainController) { delegate?.profileTabCoordinatorDelegateLogout(self) } func profileMainControllerChangeUserName(controller: ProfileMainController) { showTextEditController(title: String(localized: "name"), defaultValue: toxManager.user.userName() ?? "") { [unowned self] newName -> Void in do { try self.toxManager.user.setUserName(newName) self.delegate?.profileTabCoordinatorDelegateDidChangeUserName(self) } catch let error as NSError { handleErrorWithType(.ToxSetInfoCodeName, error: error) } } } func profileMainControllerChangeUserStatus(controller: ProfileMainController) { let controller = ChangeUserStatusController(theme: theme, selectedStatus: toxManager.user.userStatus) controller.delegate = self navigationController.pushViewController(controller, animated: true) } func profileMainControllerChangeStatusMessage(controller: ProfileMainController) { showTextEditController(title: String(localized: "status_message"), defaultValue: toxManager.user.userStatusMessage() ?? "") { newStatusMessage -> Void in do { try self.toxManager.user.setUserStatusMessage(newStatusMessage) } catch let error as NSError { handleErrorWithType(.ToxSetInfoCodeStatusMessage, error: error) } } } func profileMainController(controller: ProfileMainController, showQRCodeWithText text: String) { let controller = QRViewerController(theme: theme, text: text) controller.delegate = self let toPresent = UINavigationController(rootViewController: controller) navigationController.presentViewController(toPresent, animated: true, completion: nil) } func profileMainControllerShowProfileDetails(controller: ProfileMainController) { let controller = ProfileDetailsController(theme: theme, toxManager: toxManager) controller.delegate = self navigationController.pushViewController(controller, animated: true) } func profileMainControllerDidChangeAvatar(controller: ProfileMainController) { delegate?.profileTabCoordinatorDelegateDidChangeAvatar(self) } } extension ProfileTabCoordinator: ChangeUserStatusControllerDelegate { func changeUserStatusController(controller: ChangeUserStatusController, selectedStatus: OCTToxUserStatus) { toxManager.user.userStatus = selectedStatus navigationController.popViewControllerAnimated(true) delegate?.profileTabCoordinatorDelegateDidChangeUserStatus(self) } } extension ProfileTabCoordinator: QRViewerControllerDelegate { func qrViewerControllerDidFinishPresenting() { navigationController.dismissViewControllerAnimated(true, completion: nil) } } extension ProfileTabCoordinator: ChangePasswordControllerDelegate { func changePasswordControllerDidFinishPresenting(controller: ChangePasswordController) { navigationController.dismissViewControllerAnimated(true, completion: nil) } } extension ProfileTabCoordinator: ProfileDetailsControllerDelegate { func profileDetailsControllerSetPin(controller: ProfileDetailsController) { let controller = EnterPinController(theme: theme, state: .SetPin) controller.topText = String(localized: "pin_set") controller.delegate = self let toPresent = PortraitNavigationController(rootViewController: controller) toPresent.navigationBarHidden = true navigationController.presentViewController(toPresent, animated: true, completion: nil) } func profileDetailsControllerChangeLockTimeout(controller: ProfileDetailsController) { let controller = ChangePinTimeoutController(theme: theme, submanagerObjects: toxManager.objects) controller.delegate = self navigationController.pushViewController(controller, animated: true) } func profileDetailsControllerChangePassword(controller: ProfileDetailsController) { let controller = ChangePasswordController(theme: theme, toxManager: toxManager) controller.delegate = self let toPresent = UINavigationController(rootViewController: controller) navigationController.presentViewController(toPresent, animated: true, completion: nil) } func profileDetailsControllerDeleteProfile(controller: ProfileDetailsController) { delegate?.profileTabCoordinatorDelegateDeleteProfile(self) } } extension ProfileTabCoordinator: EnterPinControllerDelegate { func enterPinController(controller: EnterPinController, successWithPin pin: String) { switch controller.state { case .ValidatePin: let settings = toxManager.objects.getProfileSettings() settings.unlockPinCode = pin toxManager.objects.saveProfileSettings(settings) navigationController.dismissViewControllerAnimated(true, completion: nil) case .SetPin: guard let presentedNavigation = controller.navigationController else { fatalError("wrong state") } let validate = EnterPinController(theme: theme, state: .ValidatePin(validPin: pin)) validate.topText = String(localized: "pin_confirm") validate.delegate = self presentedNavigation.viewControllers = [validate] } } func enterPinControllerFailure(controller: EnterPinController) { guard let presentedNavigation = controller.navigationController else { fatalError("wrong state") } AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate)) let setPin = EnterPinController(theme: theme, state: .SetPin) setPin.topText = String(localized: "pin_do_not_match") setPin.delegate = self presentedNavigation.viewControllers = [setPin] } } extension ProfileTabCoordinator: ChangePinTimeoutControllerDelegate { func changePinTimeoutControllerDone(controller: ChangePinTimeoutController) { navigationController.popViewControllerAnimated(true) } } private extension ProfileTabCoordinator { func showTextEditController(title title: String, defaultValue: String, setValueClosure: String -> Void) { let controller = TextEditController(theme: theme, title: title, defaultValue: defaultValue, changeTextHandler: { newName -> Void in setValueClosure(newName) }, userFinishedEditing: { [unowned self] in self.navigationController.popViewControllerAnimated(true) }) navigationController.pushViewController(controller, animated: true) } }
mpl-2.0
84675c924f3ced545cc57f8dd4061152
40.10396
133
0.734795
5.498675
false
false
false
false
triniwiz/nativescript-image-cache-it
src/platforms/ios/src/ImageCacheItUtils.swift
1
20012
// // ImageCacheItUtils.swift // NativeScript ImageCacheIt // // Created by Osei Fortune on 19/10/2020. // import Foundation import UIKit import SDWebImage @objcMembers @objc(ImageCacheItUtils) public class ImageCacheItUtils: NSObject { private static var queueCount: Int64 = 0 public static func createConcurrentQueue(_ name: String) -> DispatchQueue { return DispatchQueue(label: name, attributes: .concurrent) } public static func resizeImage(_ image: UIImage? , _ width: CGFloat,_ height: CGFloat, _ scale: SDImageScaleMode, _ callback: @escaping (UIImage?)-> Void){ guard image != nil else { DispatchQueue.main.async { callback(nil) } return } let queue = createConcurrentQueue("ImageCacheUtils-Queue-" + String(queueCount)) queue.async { let resizedImage = image?.sd_resizedImage(with: CGSize(width: width, height: height), scaleMode: scale) DispatchQueue.main.async { callback(resizedImage) } } } public static func applyProcessing(_ ctx: CIContext,_ image: UIImage?, _ filters: [String: Any], _ callback: @escaping (UIImage?)-> Void) { guard image != nil else { DispatchQueue.main.async { callback(nil) } return } let queue = createConcurrentQueue("ImageCacheUtils-Queue-" + String(queueCount)) queue.async { let filter = filters["filter"] as? String let filteredImage = applyFilters(image, ctx,filter) if let overLayer = filters["overlayColor"] as? String { let overlayImage = createImageOverlay(filteredImage, overLayer) DispatchQueue.main.async { callback(overlayImage) } }else { DispatchQueue.main.async { callback(filteredImage) } } } } public static func createImageOverlay(_ image: UIImage?, _ color: String) -> UIImage? { let rgba = color.replacingOccurrences(of: "rgba(", with: "").replacingOccurrences(of: ")", with: "").replacingOccurrences(of: " ", with: "").split(separator: ",") let formatter = NumberFormatter() let red = CGFloat(Int32(truncating: formatter.number(from: String(rgba[0])) ?? 255)) / 255.0 let green = CGFloat(Int32(truncating:formatter.number(from: String(rgba[1])) ?? 255)) / 255.0 let blue = CGFloat(Int32(truncating:formatter.number(from: String(rgba[2])) ?? 255)) / 255.0 let alpha = CGFloat(truncating: formatter.number(from: String(rgba[3])) ?? 1) return createImageOverlay(image, image?.size.width ?? 0 , image?.size.height ?? 0, red, green, blue, alpha) } public static func createImageOverlay(_ image: UIImage?,_ width: CGFloat,_ height: CGFloat,_ red: CGFloat,_ green: CGFloat,_ blue: CGFloat,_ alpha: CGFloat) -> UIImage? { if(image == nil){ return image } let zero = CGFloat(0) let rect = CGRect(x: zero, y: zero, width: CGFloat(width), height: CGFloat(height)) let width = image!.cgImage!.width let height = image!.cgImage!.height let colourSpace = CGColorSpaceCreateDeviceRGB() let imageContext = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4, space: colourSpace, bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue) imageContext?.draw(image!.cgImage!, in: rect) let maskImage = image!.cgImage if(maskImage != nil){ imageContext?.clip(to: rect, mask: maskImage!) } imageContext?.setFillColor(red: red, green: green, blue: blue, alpha: alpha) imageContext?.fill(rect) let outputImage = imageContext!.makeImage() return UIImage(cgImage: outputImage!) } private static var filterCache: [String: CIFilter] = [:] private static func getFilterByName(_ name: String,_ image: UIImage?) -> CIFilter?{ let ciFilter: CIFilter? = filterCache[name] var filter = ciFilter?.copy(with : nil) as? CIFilter if (filter == nil){ filter = CIFilter(name:name) filterCache[name] = filter! }else { filter?.setDefaults() } if let ref = image { if (ref.ciImage != nil) { filter?.setValue(ref.ciImage!, forKey: kCIInputImageKey) filter?.setValue(nil, forKey: CIImageOption.colorSpace.rawValue) } else { if (ref.cgImage != nil) { filter?.setValue(CIImage(cgImage: ref.cgImage!), forKey: kCIInputImageKey) } } } return filter } private static func getFilterByName(_ name: String,_ image: CIImage?) -> CIFilter?{ let ciFilter: CIFilter? = filterCache[name] var filter = ciFilter?.copy(with : nil) as? CIFilter if (filter == nil){ filter = CIFilter(name:name) filterCache[name] = filter! }else { filter?.setDefaults() } if let ref = image { filter?.setValue(ref, forKey: kCIInputImageKey) } return filter } private static func createAlphaImage(_ image: UIImage?, _ alpha: CGFloat) -> CIImage? { if(image == nil){ return nil } let zero = CGFloat(0) let width = image!.cgImage!.width let height = image!.cgImage!.height let rect = CGRect(x: zero, y: zero, width: CGFloat(width), height: CGFloat(height)) let colourSpace = CGColorSpaceCreateDeviceRGB() let imageContext = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4, space: colourSpace, bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue) imageContext?.setAlpha(alpha) imageContext?.draw(image!.cgImage!, in: rect) guard let outputImage = imageContext?.makeImage() else {return nil} return CIImage(cgImage: outputImage) } private static func applyFilters(_ image: UIImage?, _ ctx: CIContext,_ filter: String?) -> UIImage? { if(image == nil){ return nil } var realImage = image! if(filter != nil){ func getValue(_ value: String) -> String? { guard let startIndex = value.firstIndex(of: "(") else {return nil} let start = value.index(after: startIndex) guard let endIndex = value.firstIndex(of: ")") else {return nil} let end = value.index(before: endIndex) return String(value[start ... end]) } func getFilterName(_ value: String) -> String? { guard let endIndex = value.firstIndex(of: "(") else {return nil} let end = value.index(before: endIndex) return String(value[...end]) } func createFilterWithName(_ value: String) -> CIFilter?{ return getFilterByName(value, image) } func createFilterWithName(_ value: String, _ filteredImage: CIImage?) -> CIFilter?{ return getFilterByName(value, filteredImage) } let imageFilters = filter?.split(separator: " ").map { String($0) } ?? [] var filteredImage: CIImage? for imageFilter in imageFilters { let value = getValue(imageFilter) switch getFilterName(imageFilter) { case "blur": var width: CGFloat? if let size = value { if(size.contains("%")){ if let percent = Float(size.replacingOccurrences(of: "%", with: "")) { width = CGFloat((CGFloat(percent) / 100.0) * realImage.size.width) } }else if(size.contains("px")){ if let px = Float(size.replacingOccurrences(of: "px", with: "")) { width = CGFloat(px) * UIScreen.main.scale } }else if(size.contains("dip")) { if let dip = Float(size.replacingOccurrences(of: "dip", with: "")) { width = CGFloat(dip) } }else{ if let raw = Float(size){ width = CGFloat(raw) } } if var realWidth = width { if (realWidth > 25) { realWidth = 25 } if (realWidth > -1) { var blurFilter: CIFilter? if(filteredImage == nil){ blurFilter = createFilterWithName("CIGaussianBlur") }else { blurFilter = createFilterWithName("CIGaussianBlur", filteredImage) } blurFilter?.setValue(width, forKey: kCIInputRadiusKey) if let blurredImg = blurFilter?.value(forKey: kCIOutputImageKey) as? CIImage { filteredImage = blurredImg } } } } break case "contrast": if let size = value { if (size.contains("%")) { if let contrast = Float(size.replacingOccurrences(of: "%", with: "")) { _ = contrast / 100.0 var contrastFilter: CIFilter? if(filteredImage == nil){ contrastFilter = createFilterWithName("CIColorControls") }else { contrastFilter = createFilterWithName("CIColorControls", filteredImage) } contrastFilter?.setValue(contrast, forKey: kCIInputContrastKey) if let contrastImg: CIImage = contrastFilter?.value(forKey: kCIOutputImageKey) as? CIImage{ filteredImage = contrastImg } } } } break case "brightness": if let size = value { if (size.contains("%")) { if let brightness = Float(size.replacingOccurrences(of: "%", with: "")) { /* if (brightness >= 0 && brightness < 1) { brightness = -1 + brightness; }*/ var brightnessFilter: CIFilter? if(filteredImage == nil){ brightnessFilter = createFilterWithName("CIColorControls") }else { brightnessFilter = createFilterWithName("CIColorControls", filteredImage) } brightnessFilter?.setValue(brightness, forKey: kCIInputBrightnessKey) if let brightnessImg = brightnessFilter?.value(forKey: kCIOutputImageKey) as? CIImage { filteredImage = brightnessImg } } } } break case "greyscale" , "grayscale": var grayscale: CGFloat = 0 if let size = value { if (size.contains("%")) { if let realSize = Float(size.replacingOccurrences(of: "%", with: "")) { grayscale = CGFloat(realSize / 100.0) } } else if (size.contains(".")) { if let realSize = Float(size) { grayscale = CGFloat(realSize) } } else { if let realSize = Float(size) { grayscale = CGFloat(realSize) } } if (grayscale > 1) { grayscale = 1; } grayscale = 1 - grayscale; var grayscaleFilter: CIFilter? if(filteredImage == nil){ grayscaleFilter = createFilterWithName("CIColorControls") }else { grayscaleFilter = createFilterWithName("CIColorControls", filteredImage) } grayscaleFilter?.setValue(grayscale, forKey: kCIInputSaturationKey) if let grayscaleImg = grayscaleFilter?.value(forKey: kCIOutputImageKey) as? CIImage { filteredImage = grayscaleImg } } break case "invert": // TODO handle value var invertFilter: CIFilter? if(filteredImage == nil){ invertFilter = createFilterWithName("CIColorInvert") }else { invertFilter = createFilterWithName("CIColorInvert", filteredImage) } if let invertImg = invertFilter?.value(forKey: kCIOutputImageKey) as? CIImage{ filteredImage = invertImg } break case "sepia": if let size = value { if let sepia = Float(size.replacingOccurrences(of: "%", with: "")) { let realSize = sepia / 100 var sepiaFilter: CIFilter? if(filteredImage == nil){ sepiaFilter = createFilterWithName("CISepiaTone") }else { sepiaFilter = createFilterWithName("CISepiaTone", filteredImage) } sepiaFilter?.setValue(realSize, forKey: kCIInputIntensityKey) if let sepiaImg = sepiaFilter?.value(forKey: kCIOutputImageKey) as? CIImage { filteredImage = sepiaImg } } } break case "opacity": if let size = value { var alpha: CGFloat = 1 if (size.contains("%")) { if let realSize = Float(size.replacingOccurrences(of: "%", with: "")) { alpha = CGFloat(realSize / 100) } } else if (size.contains(".")) { if let realSize = Float(size) { alpha = CGFloat(realSize) } } else { if let realSize = Float(size) { alpha = CGFloat(realSize) } } if let newImage = createAlphaImage(realImage, alpha) { filteredImage = newImage } } break case "hue": var hueFilter: CIFilter? if(filteredImage == nil){ hueFilter = createFilterWithName("CIHueAdjust") }else { hueFilter = createFilterWithName("CIHueAdjust", filteredImage) } var hue = 0 if let realValue = value { if (realValue.contains("deg")) { if let realHue = Int(realValue.replacingOccurrences(of: "deg", with: "")){ hue = realHue } } else if (realValue.contains("turn")) { if let realHue = Int(realValue.replacingOccurrences(of: "turn", with: "")){ hue = realHue * 360 } } hueFilter?.setValue(hue, forKey: kCIInputAngleKey) if let hueImg = hueFilter?.value(forKey: kCIOutputImageKey) as? CIImage { filteredImage = hueImg } } break case "saturate": var saturateFilter: CIFilter? if(filteredImage == nil){ saturateFilter = createFilterWithName("CIColorControls") }else { saturateFilter = createFilterWithName("CIColorControls", filteredImage) } var saturate: CGFloat? if let size = value { if(size.contains("%")){ if let realSize = Float(size.replacingOccurrences(of: "%", with: "")){ saturate = CGFloat(realSize / 100) } }else if(size.contains(".")){ if let realSize = Float(size){ saturate = CGFloat(realSize) } }else { if let realSize = Float(size){ saturate = CGFloat(realSize) } } } if let sat = saturate { saturateFilter?.setValue(sat, forKey: kCIInputSaturationKey) if let saturateImg = saturateFilter?.value(forKey: kCIOutputImageKey) as? CIImage { filteredImage = saturateImg } } break default: // NOOP break } } if let cIImage = filteredImage { if let cgImage = ctx.createCGImage(cIImage, from: cIImage.extent){ realImage = UIImage(cgImage: cgImage) } } } return realImage } }
apache-2.0
328d96c451854b0c4df37f78b5b94c79
44.072072
174
0.443634
5.95418
false
false
false
false
Kawoou/FlexibleImage
Sources/Filter/ScreenFilter.swift
1
2421
// // ScreenFilter.swift // FlexibleImage // // Created by Kawoou on 2017. 5. 12.. // Copyright © 2017년 test. All rights reserved. // #if !os(OSX) import UIKit #else import AppKit #endif #if !os(watchOS) import Metal #endif internal class ScreenFilter: ImageFilter { // MARK: - Property internal override var metalName: String { get { return "ScreenFilter" } } internal var color: FIColorType = (1.0, 1.0, 1.0, 1.0) // MARK: - Internal #if !os(watchOS) @available(OSX 10.11, iOS 8, tvOS 9, *) internal override func processMetal(_ device: ImageMetalDevice, _ commandBuffer: MTLCommandBuffer, _ commandEncoder: MTLComputeCommandEncoder) -> Bool { let factors: [Float] = [color.r, color.g, color.b, color.a] for i in 0..<factors.count { var factor = factors[i] let size = max(MemoryLayout<Float>.size, 16) let options: MTLResourceOptions if #available(iOS 9.0, *) { options = [.storageModeShared] } else { options = [.cpuCacheModeWriteCombined] } let buffer = device.device.makeBuffer( bytes: &factor, length: size, options: options ) #if swift(>=4.0) commandEncoder.setBuffer(buffer, offset: 0, index: i) #else commandEncoder.setBuffer(buffer, offset: 0, at: i) #endif } return super.processMetal(device, commandBuffer, commandEncoder) } #endif override func processNone(_ device: ImageNoneDevice) -> Bool { guard let context = device.context else { return false } let color = FIColor( red: CGFloat(self.color.r), green: CGFloat(self.color.g), blue: CGFloat(self.color.b), alpha: CGFloat(self.color.a) ) context.saveGState() context.setBlendMode(.screen) context.setFillColor(color.cgColor) context.fill(device.drawRect!) context.restoreGState() return super.processNone(device) } }
mit
0ca748e28d53cf49282ec2dfb9c0b1f9
26.793103
160
0.513234
4.676983
false
false
false
false
lanjing99/RxSwiftDemo
09-combining-operators/final/RxSwiftPlayground/RxSwift.playground/Contents.swift
1
6407
//: Please build the scheme 'RxSwiftPlayground' first import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true import RxSwift example(of: "startWith") { // 1 let numbers = Observable.of(2, 3, 4) // 2 let observable = numbers.startWith(1) observable.subscribe(onNext: { value in print(value) }) } example(of: "Observable.concat") { // 1 let first = Observable.of(1, 2, 3) let second = Observable.of(4, 5, 6) // 2 let observable = Observable.concat([first, second]) observable.subscribe(onNext: { value in print(value) }) } example(of: "concat") { let germanCities = Observable.of("Berlin", "Munich", "Frankfurt") let spanishCities = Observable.of("Madrid", "Barcelona", "Valencia") let observable = germanCities.concat(spanishCities) observable.subscribe(onNext: { value in print(value) }) } example(of: "concat one element") { let numbers = Observable.of(2, 3, 4) let observable = Observable .just(1) .concat(numbers) observable.subscribe(onNext: { value in print(value) }) } example(of: "merge") { // 1 let left = PublishSubject<String>() let right = PublishSubject<String>() // 2 let source = Observable.of(left.asObservable(), right.asObservable()) // 3 let observable = source.merge() let disposable = observable.subscribe(onNext: { value in print(value) }) // 4 var leftValues = ["Berlin", "Munich", "Frankfurt"] var rightValues = ["Madrid", "Barcelona", "Valencia"] repeat { if arc4random_uniform(2) == 0 { if !leftValues.isEmpty { left.onNext("Left: " + leftValues.removeFirst()) } } else if !rightValues.isEmpty { right.onNext("Right: " + rightValues.removeFirst()) } } while !leftValues.isEmpty || !rightValues.isEmpty // 5 disposable.dispose() } example(of: "combineLatest") { let left = PublishSubject<String>() let right = PublishSubject<String>() // 1 let observable = Observable.combineLatest(left, right, resultSelector: { lastLeft, lastRight in "\(lastLeft) \(lastRight)" }) let disposable = observable.subscribe(onNext: { value in print(value) }) // 2 print("> Sending a value to Left") left.onNext("Hello,") print("> Sending a value to Right") right.onNext("world") print("> Sending another value to Right") right.onNext("RxSwift") print("> Sending another value to Left") left.onNext("Have a good day,") disposable.dispose() } example(of: "combine user choice and value") { let choice : Observable<DateFormatter.Style> = Observable.of(.short, .long) let dates = Observable.of(Date()) let observable = Observable.combineLatest(choice, dates) { (format, when) -> String in let formatter = DateFormatter() formatter.dateStyle = format return formatter.string(from: when) } observable.subscribe(onNext: { value in print(value) }) } example(of: "zip") { enum Weather { case cloudy case sunny } let left: Observable<Weather> = Observable.of(.sunny, .cloudy, .cloudy, .sunny) let right = Observable.of("Lisbon", "Copenhagen", "London", "Madrid", "Vienna") let observable = Observable.zip(left, right) { weather, city in return "It's \(weather) in \(city)" } observable.subscribe(onNext: { value in print(value) }) } example(of: "withLatestFrom") { // 1 let button = PublishSubject<Void>() let textField = PublishSubject<String>() // 2 let observable = textField.sample(button) let disposable = observable.subscribe(onNext: { value in print(value) }) // 3 textField.onNext("Par") textField.onNext("Pari") textField.onNext("Paris") button.onNext() button.onNext() } example(of: "amb") { let left = PublishSubject<String>() let right = PublishSubject<String>() // 1 let observable = left.amb(right) let disposable = observable.subscribe(onNext: { value in print(value) }) // 2 left.onNext("Lisbon") right.onNext("Copenhagen") left.onNext("London") left.onNext("Madrid") right.onNext("Vienna") disposable.dispose() } example(of: "switchLatest") { // 1 let one = PublishSubject<String>() let two = PublishSubject<String>() let three = PublishSubject<String>() let source = PublishSubject<Observable<String>>() // 2 let observable = source.switchLatest() let disposable = observable.subscribe(onNext: { value in print(value) }) // 3 source.onNext(one) one.onNext("Some text from sequence one") two.onNext("Some text from sequence two") source.onNext(two) two.onNext("More text from sequence two") one.onNext("and also from sequence one") source.onNext(three) two.onNext("Why don't you seem me?") one.onNext("I'm alone, help me") three.onNext("Hey it's three. I win.") source.onNext(one) one.onNext("Nope. It's me, one!") disposable.dispose() } example(of: "reduce") { let source = Observable.of(1, 3, 5, 7, 9) // 1 // 1 let observable = source.reduce(0, accumulator: { summary, newValue in return summary + newValue }) observable.subscribe(onNext: { value in print(value) }) } example(of: "scan") { let source = Observable.of(1, 3, 5, 7, 9) let observable = source.scan(0, accumulator: +) observable.subscribe(onNext: { value in print(value) }) } /*: Copyright (c) 2014-2016 Razeware LLC 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. */
mit
3439010ddabf2fe10d1d3e3944643311
23.547893
81
0.682379
3.768824
false
false
false
false
TrustWallet/trust-wallet-ios
Trust/Tokens/ViewControllers/TokensViewController.swift
1
7982
// Copyright DApps Platform Inc. All rights reserved. import Foundation import UIKit import Result import TrustCore import RealmSwift protocol TokensViewControllerDelegate: class { func didPressAddToken( in viewController: UIViewController) func didSelect(token: TokenObject, in viewController: UIViewController) func didRequest(token: TokenObject, in viewController: UIViewController) } final class TokensViewController: UIViewController { fileprivate var viewModel: TokensViewModel lazy var header: TokensHeaderView = { let header = TokensHeaderView(frame: .zero) header.amountLabel.text = viewModel.headerBalance header.amountLabel.textColor = viewModel.headerBalanceTextColor header.backgroundColor = viewModel.headerBackgroundColor header.amountLabel.font = viewModel.headerBalanceFont header.frame.size = header.systemLayoutSizeFitting(UILayoutFittingExpandedSize) return header }() lazy var footer: TokensFooterView = { let footer = TokensFooterView(frame: .zero) footer.textLabel.text = viewModel.footerTitle footer.textLabel.font = viewModel.footerTextFont footer.textLabel.textColor = viewModel.footerTextColor footer.frame.size = footer.systemLayoutSizeFitting(UILayoutFittingExpandedSize) footer.addGestureRecognizer( UITapGestureRecognizer(target: self, action: #selector(missingToken)) ) return footer }() lazy var tableView: UITableView = { let tableView = UITableView(frame: .zero, style: .plain) tableView.translatesAutoresizingMaskIntoConstraints = false tableView.separatorStyle = .singleLine tableView.separatorColor = StyleLayout.TableView.separatorColor tableView.backgroundColor = .white tableView.register(TokenViewCell.self, forCellReuseIdentifier: TokenViewCell.identifier) tableView.tableHeaderView = header tableView.tableFooterView = footer tableView.addSubview(refreshControl) return tableView }() let refreshControl = UIRefreshControl() weak var delegate: TokensViewControllerDelegate? var etherFetchTimer: Timer? let intervalToETHRefresh = 10.0 lazy var fetchClosure: () -> Void = { return debounce(delay: .seconds(7), action: { [weak self] () in self?.viewModel.fetch() }) }() init( viewModel: TokensViewModel ) { self.viewModel = viewModel super.init(nibName: nil, bundle: nil) self.viewModel.delegate = self tableView.delegate = self tableView.dataSource = self view.addSubview(tableView) NSLayoutConstraint.activate([ tableView.topAnchor.constraint(equalTo: view.topAnchor), tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor), tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor), tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor), ]) refreshControl.addTarget(self, action: #selector(pullToRefresh), for: .valueChanged) sheduleBalanceUpdate() NotificationCenter.default.addObserver(self, selector: #selector(TokensViewController.resignActive), name: .UIApplicationWillResignActive, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(TokensViewController.didBecomeActive), name: .UIApplicationDidBecomeActive, object: nil) } override func viewDidLoad() { super.viewDidLoad() startTokenObservation() title = viewModel.title view.backgroundColor = viewModel.backgroundColor footer.textLabel.text = viewModel.footerTitle fetch(force: true) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.applyTintAdjustment() } @objc func pullToRefresh() { refreshControl.beginRefreshing() fetch(force: true) } func fetch(force: Bool = false) { if force { viewModel.fetch() } else { fetchClosure() } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func refreshHeaderView() { header.amountLabel.text = viewModel.headerBalance } @objc func missingToken() { delegate?.didPressAddToken(in: self) } private func startTokenObservation() { viewModel.setTokenObservation { [weak self] (changes: RealmCollectionChange) in guard let strongSelf = self else { return } let tableView = strongSelf.tableView switch changes { case .initial: tableView.reloadData() case .update: self?.tableView.reloadData() case .error: break } strongSelf.refreshControl.endRefreshing() self?.refreshHeaderView() } } @objc func resignActive() { etherFetchTimer?.invalidate() etherFetchTimer = nil stopTokenObservation() } @objc func didBecomeActive() { sheduleBalanceUpdate() startTokenObservation() } private func sheduleBalanceUpdate() { guard etherFetchTimer == nil else { return } etherFetchTimer = Timer.scheduledTimer(timeInterval: intervalToETHRefresh, target: BlockOperation { [weak self] in self?.viewModel.updatePendingTransactions() }, selector: #selector(Operation.main), userInfo: nil, repeats: true) } private func stopTokenObservation() { viewModel.invalidateTokensObservation() } deinit { NotificationCenter.default.removeObserver(self) resignActive() stopTokenObservation() } } extension TokensViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let token = viewModel.item(for: indexPath) delegate?.didSelect(token: token, in: self) } @available(iOS 11.0, *) func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { let token = viewModel.item(for: indexPath) let deleteAction = UIContextualAction(style: .normal, title: R.string.localizable.transactionsReceiveButtonTitle()) { _, _, handler in self.delegate?.didRequest(token: token, in: self) handler(true) } deleteAction.backgroundColor = Colors.lightBlue let configuration = UISwipeActionsConfiguration(actions: [deleteAction]) return configuration } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return TokensLayout.tableView.height } } extension TokensViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: TokenViewCell.identifier, for: indexPath) as! TokenViewCell cell.isExclusiveTouch = true return cell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel.tokens.count } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { guard let tokenViewCell = cell as? TokenViewCell else { return } tokenViewCell.configure(viewModel: viewModel.cellViewModel(for: indexPath)) } } extension TokensViewController: TokensViewModelDelegate { func refresh() { self.tableView.reloadData() self.refreshHeaderView() } } extension TokensViewController: Scrollable { func scrollOnTop() { tableView.scrollOnTop() } }
gpl-3.0
efb69ccc5aecf3d824c917fedd37948a
35.614679
161
0.685793
5.357047
false
false
false
false
onevcat/CotEditor
CotEditor/Sources/TextSelection.swift
1
10099
// // TextSelection.swift // // CotEditor // https://coteditor.com // // Created by nakamuxu on 2005-03-01. // // --------------------------------------------------------------------------- // // © 2004-2007 nakamuxu // © 2014-2022 1024jp // // 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 // // https://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 Cocoa private enum OSACaseType: FourCharCode { case lowercase = "cClw" case uppercase = "cCup" case capitalized = "cCcp" } private enum OSAWidthType: FourCharCode { case full = "rWfl" case half = "rWhf" } private enum OSAKanaType: FourCharCode { case hiragana = "cHgn" case katakana = "cKkn" } private enum OSAUnicodeNormalizationType: FourCharCode { case nfc = "cNfc" case nfd = "cNfd" case nfkc = "cNkc" case nfkd = "cNkd" case nfkcCF = "cNcf" case modifiedNFC = "cNmc" case modifiedNFD = "cNfm" } // MARK: - final class TextSelection: NSObject { // MARK: Private Properties private weak var document: Document? // weak to avoid cycle retain // MARK: - // MARK: Lifecycle required init(document: Document) { self.document = document super.init() } private override init() { } /// return object name which is determined in the sdef file override var objectSpecifier: NSScriptObjectSpecifier? { return NSNameSpecifier(containerSpecifier: self.document!.objectSpecifier, key: "text selection") } // MARK: AppleScript Accessors /// string of the selection (Unicode text) @objc var contents: Any? { get { guard let string = self.document?.selectedString else { return nil } let textStorage = NSTextStorage(string: string) textStorage.observeDirectEditing { [weak self] (editedString) in self?.document?.insert(string: editedString, at: .replaceSelection) } return textStorage } set { guard let string: String = { switch newValue { case let storage as NSTextStorage: return storage.string case let string as String: return string default: return nil } }() else { return } self.document?.insert(string: string, at: .replaceSelection) } } /// character range (location and length) of the selection @objc var range: [Int]? { get { guard let range = self.document?.selectedRange else { return nil } return [range.location, range.length] } set { guard newValue?.count == 2, let location = newValue?[0], let length = newValue?[1], let string = self.document?.string, let range = string.range(in: FuzzyRange(location: location, length: length)) else { return } self.document?.selectedRange = range } } /// line range (location and length) of the selection (list type) @objc var lineRange: [Int]? { get { guard let document = self.document else { return nil } let selectedRange = document.selectedRange let string = document.string let start = string.lineNumber(at: selectedRange.lowerBound) let end = string.lineNumber(at: selectedRange.upperBound) return [start, end - start + 1] } set { guard let lineRange = newValue, (1...2).contains(lineRange.count), let textView = self.document?.textView else { return } let fuzzyRange = FuzzyRange(location: lineRange[0], length: lineRange[safe: 1] ?? 1) guard let range = textView.string.rangeForLine(in: fuzzyRange) else { return } textView.selectedRange = range } } // MARK: AppleScript Handlers /// shift the selection to right @objc func handleShiftRight(_ command: NSScriptCommand) { self.textView?.shiftRight(command) } /// shift the selection to left @objc func handleShiftLeft(_ command: NSScriptCommand) { self.textView?.shiftLeft(command) } /// swap selected lines with the line just above @objc func handleMoveLineUp(_ command: NSScriptCommand) { self.textView?.moveLineUp(command) } /// swap selected lines with the line just below @objc func handleMoveLineDown(_ command: NSScriptCommand) { self.textView?.moveLineDown(command) } /// sort selected lines ascending @objc func handleSortLinesAscending(_ command: NSScriptCommand) { self.textView?.sortLinesAscending(command) } /// reverse selected lines @objc func handleReverseLines(_ command: NSScriptCommand) { self.textView?.reverseLines(command) } /// delete duplicate lines in selection @objc func handleDeleteDuplicateLine(_ command: NSScriptCommand) { self.textView?.deleteDuplicateLine(command) } /// uncomment the selection @objc func handleCommentOut(_ command: NSScriptCommand) { self.textView?.commentOut(types: .both, fromLineHead: false) } /// swap selected lines with the line just below @objc func handleUncomment(_ command: NSScriptCommand) { self.textView?.uncomment(fromLineHead: false) } /// convert letters in the selection to lowercase, uppercase or capitalized @objc func handleChangeCase(_ command: NSScriptCommand) { guard let argument = command.evaluatedArguments?["caseType"] as? UInt32, let type = OSACaseType(rawValue: argument), let textView = self.textView else { return } switch type { case .lowercase: textView.lowercaseWord(command) case .uppercase: textView.uppercaseWord(command) case .capitalized: textView.capitalizeWord(command) } } /// convert half-width roman in the selection to full-width roman or vice versa @objc func handleChangeWidthRoman(_ command: NSScriptCommand) { guard let argument = command.evaluatedArguments?["widthType"] as? UInt32, let type = OSAWidthType(rawValue: argument), let textView = self.textView else { return } switch type { case .half: textView.exchangeHalfwidthRoman(command) case .full: textView.exchangeFullwidthRoman(command) } } /// convert Japanese Hiragana in the selection to Katakana or vice versa @objc func handleChangeKana(_ command: NSScriptCommand) { guard let argument = command.evaluatedArguments?["kanaType"] as? UInt32, let type = OSAKanaType(rawValue: argument), let textView = self.textView else { return } switch type { case .hiragana: textView.exchangeHiragana(command) case .katakana: textView.exchangeKatakana(command) } } /// convert straight quotes to typographical pairs @objc func handleSmartenQuotes(_ command: NSScriptCommand) { self.textView?.perform(Selector(("replaceQuotesInSelection:"))) } /// convert typographical (curly) quotes to straight @objc func handleStraightenQuotes(_ command: NSScriptCommand) { self.textView?.straightenQuotesInSelection(command) } /// convert double hyphens to em dashes (—) @objc func handleSmartenDashes(_ command: NSScriptCommand) { self.textView?.perform(Selector(("replaceDashesInSelection:"))) } /// Unicode normalization @objc func handleNormalizeUnicode(_ command: NSScriptCommand) { guard let argument = command.evaluatedArguments?["unfType"] as? UInt32, let type = OSAUnicodeNormalizationType(rawValue: argument), let textView = self.textView else { return } switch type { case .nfc: textView.normalizeUnicodeWithNFC(command) case .nfd: textView.normalizeUnicodeWithNFD(command) case .nfkc: textView.normalizeUnicodeWithNFKC(command) case .nfkd: textView.normalizeUnicodeWithNFKD(command) case .nfkcCF: textView.normalizeUnicodeWithNFKCCF(command) case .modifiedNFC: textView.normalizeUnicodeWithModifiedNFC(command) case .modifiedNFD: textView.normalizeUnicodeWithModifiedNFD(command) } } // MARK: Private Methods private var textView: EditorTextView? { return self.document?.viewController?.focusedTextView } }
apache-2.0
8211397a879af79bdf6da212345d9c51
27.198324
105
0.569292
5.032403
false
false
false
false
xedin/swift
test/decl/var/property_wrappers_synthesis.swift
1
1249
// RUN: %target-swift-frontend -typecheck -dump-ast %s | %FileCheck %s @propertyWrapper struct Wrapper<T> { var value: T init(initialValue: T) { self.value = initialValue } } protocol DefaultInit { init() } // CHECK: struct_decl{{.*}}"UseWrapper" struct UseWrapper<T: DefaultInit> { // CHECK: var_decl{{.*}}"wrapped" // CHECK: accessor_decl{{.*}}get_for=wrapped // CHECK: member_ref_expr{{.*}}UseWrapper.$wrapped // CHECK: accessor_decl{{.*}}set_for=wrapped // CHECK: member_ref_expr{{.*}}UseWrapper.$wrapped // CHECK: accessor_decl{{.*}}_modify_for=wrapped // CHECK: yield_stmt // CHECK: member_ref_expr{{.*}}UseWrapper.wrapped @Wrapper var wrapped = T() // CHECK: pattern_binding_decl implicit // CHECK-NEXT: pattern_typed implicit type='Wrapper<T>' // CHECK-NEXT: pattern_named implicit type='Wrapper<T>' '$wrapped' // CHECK: constructor_ref_call_expr // CHECK-NEXT: declref_expr{{.*}}Wrapper.init(initialValue:) init() { } } struct UseWillSetDidSet { // CHECK: var_decl{{.*}}"z" // CHECK: accessor_decl{{.*}}set_for=z // CHECK: member_ref_expr{{.*}}UseWillSetDidSet.$z @Wrapper var z: Int { willSet { print(newValue) } didSet { print(oldValue) } } }
apache-2.0
c452f4c171369095bb5d2bb35bdeced4
21.709091
70
0.633307
3.528249
false
false
false
false
Under100/ABOnboarding
Pod/Classes/ABOnboardingItem.swift
1
2678
// // OnboardingItem.swift // ABOnboarding // // Created by Adam Boyd on 2016-02-29. // Copyright © 2016 Under100. All rights reserved. // import Foundation import UIKit public enum RelativePlacement { case Above(UIView), Below(UIView), RelativeToTop(CGFloat), RelativeToBottom(CGFloat), PointingUpAt(CGRect), PointingDownAt(CGRect) } public enum StringType { case Regular(String), Attributed(NSAttributedString) init(string: String) { self = .Regular(string) } init(attributedString: NSAttributedString) { self = .Attributed(attributedString) } } @objc public class ABOnboardingItem: NSObject { var message: StringType var placement: RelativePlacement var onboardingView: ABOnboardingView! { didSet { if let leftTitle = self.leftButtonTitle { self.onboardingView.laterButton.setTitle(leftTitle, forState: .Normal) } if let rightTitle = self.rightButtonTitle { self.onboardingView.nextButton.setTitle(rightTitle, forState: .Normal) } } } var blurredBackground: Bool var nextItemAutomaticallyShows: Bool var leftButtonTitle: String? var rightButtonTitle: String? var image: UIImage? var textAlign: NSTextAlignment //Regular strings public init(message: String, placement: RelativePlacement, blurredBackground: Bool, nextItemAutomaticallyShows: Bool = true, leftButtonTitle: String? = nil, rightButtonTitle: String? = nil, image: UIImage? = nil, textAlign: NSTextAlignment = .Left) { self.message = StringType(string: message) self.placement = placement self.blurredBackground = blurredBackground self.nextItemAutomaticallyShows = nextItemAutomaticallyShows self.leftButtonTitle = leftButtonTitle self.rightButtonTitle = rightButtonTitle self.image = image self.textAlign = textAlign } //Attributed strings public init(attributedString: NSAttributedString, placement: RelativePlacement, blurredBackground: Bool, nextItemAutomaticallyShows: Bool = true, leftButtonTitle: String? = nil, rightButtonTitle: String? = nil, image: UIImage? = nil, textAlign: NSTextAlignment = .Left) { self.message = StringType(attributedString: attributedString) self.placement = placement self.blurredBackground = blurredBackground self.nextItemAutomaticallyShows = nextItemAutomaticallyShows self.leftButtonTitle = leftButtonTitle self.rightButtonTitle = rightButtonTitle self.image = image self.textAlign = textAlign } }
mit
8cec4c70c5238784d2e082572880de77
35.684932
275
0.695181
4.930018
false
false
false
false
AngryLi/ResourceSummary
iOS/Demos/Assignments_swift/assignment-1-calculator/Calculator_assignment/Calculator/ViewController.swift
3
5414
// // ViewController.swift // Calculator // // Created by 李亚洲 on 15/4/15. // Copyright (c) 2015年 liyazhou. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } var brain = CalculatorBrain() var userIsinterface : Bool = false @IBOutlet weak var display: UILabel! @IBOutlet weak var historyLabel: UILabel! @IBAction func digitBtn(sender: UIButton) { let digit = sender.currentTitle! if userIsinterface { var dotNum = 0 for item in display.text! { if item == "." { dotNum++ } } if digit == "." { if dotNum == 0 { display.text = display.text! + digit } } else { display.text = display.text! + digit } } else { if digit == "." { display.text = "0." } else { display.text = digit } userIsinterface = true } } @IBAction func operate(sender: UIButton) { let operation = sender.currentTitle! if userIsinterface { enter() } if let operation = sender.currentTitle { if let result = brain.performOperation(operation) { displayValue = result } else { displayValue = nil } //显示历史算式 historyLabel.text = brain.description println(brain.description) } } @IBAction func enter() { userIsinterface = false if let value = displayValue { if let result = brain.pushOperand(value) { displayValue = result } else { displayValue = 0 } } else { displayValue = nil } } @IBAction func variableBtn(sender: UIButton) { let temp = sender.currentTitle! if temp == "M" { displayValue = 0 brain.pushOperandVariable() } else if temp == "→M" { var result : Double? if userIsinterface { result = brain.pushOperandVariable(displayValue!) } else { result = brain.pushOperandVariable(0) } userIsinterface = false if result != nil { displayValue = result! }else { displayValue = nil } historyLabel.text = brain.description } println(brain.variableValues) } @IBAction func deleteDigit(sender: UIButton) { var strDisplay = display.text! var countDisplay = count(strDisplay) if countDisplay >= 2 { let indexEnd = advance(strDisplay.endIndex, -1) display.text = strDisplay.substringToIndex(indexEnd) } else { display.text = "0" userIsinterface = false } } @IBAction func clear(sender: UIButton) { brain.clear() displayValue = nil historyLabel.text = "" userIsinterface = false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } var displayValue : Double? { get { var displayText : String = display.text! if displayText.hasSuffix("π") { if count(displayText) > 1 { return NSNumberFormatter().numberFromString(displayText.substringToIndex(advance(displayText.endIndex, -1)))!.doubleValue * M_PI } else { return M_PI } } return NSNumberFormatter().numberFromString(display.text!)?.doubleValue } set { if let value = newValue { if value % M_PI == 0 && value != 0 { if value / M_PI == 1 { display.text = "π" return } display.text = "\(Int(value / M_PI))π" } else { display.text = "\(value)" } } else { display.text = "" } userIsinterface = false } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let destination = segue.destinationViewController as? GraphViewController { println(self.brain) destination.brain = self.brain } } }
mit
a0ed0f664e7a219af2566a7aaa54133d
23.834101
148
0.438486
5.549949
false
false
false
false