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
bphun/Calculator
Calculator/ImageBasedInputViewController.swift
1
957
// // ImageBasedInputViewController.swift // Calculator // // Created by Brandon Phan on 8/30/17. // Copyright © 2017 Brandon Phan. All rights reserved. // import UIKit import AVFoundation class ImageBasedInputViewController: UIViewController { var captureSession: AVCaptureSession? var videoPreviewLayer: AVCaptureVideoPreviewLayer? override func viewDidLoad() { super.viewDidLoad() let captureDevice = AVCaptureDevice.default(for: .video) var input: AVCaptureDeviceInput! do { input = try AVCaptureDeviceInput(device: captureDevice!) } catch { print(error) } captureSession = AVCaptureSession() captureSession?.addInput(input) videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession!) videoPreviewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill videoPreviewLayer?.frame = view.layer.bounds view.layer.addSublayer(videoPreviewLayer!) captureSession?.startRunning() } }
mit
22f9d723062c1e4692d7cd82b5597e92
22.9
74
0.76569
4.686275
false
false
false
false
ktilakraj/MuvizzCode
ThirdParty/DropDown/helpers/DPDConstants.swift
8
1241
// // Constants.swift // DropDown // // Created by Kevin Hirsch on 28/07/15. // Copyright (c) 2015 Kevin Hirsch. All rights reserved. // import UIKit internal struct DPDConstant { internal struct KeyPath { static let Frame = "frame" } internal struct ReusableIdentifier { static let DropDownCell = "DropDownCell" } internal struct UI { static let TextColor = UIColor.black static let TextFont = UIFont.systemFont(ofSize: 15) static let BackgroundColor = UIColor(white: 0.94, alpha: 1) static let SelectionBackgroundColor = UIColor(white: 0.89, alpha: 1) static let SeparatorColor = UIColor.clear static let CornerRadius: CGFloat = 2 static let RowHeight: CGFloat = 44 static let HeightPadding: CGFloat = 20 struct Shadow { static let Color = UIColor.darkGray static let Offset = CGSize.zero static let Opacity: Float = 0.4 static let Radius: CGFloat = 8 } } internal struct Animation { static let Duration = 0.15 static let EntranceOptions: UIViewAnimationOptions = [.allowUserInteraction, .curveEaseOut] static let ExitOptions: UIViewAnimationOptions = [.allowUserInteraction, .curveEaseIn] static let DownScaleTransform = CGAffineTransform(scaleX: 0.9, y: 0.9) } }
mit
c5aa3cc0b1df7bbd895760e9d890dc32
21.160714
93
0.726833
3.866044
false
false
false
false
diiingdong/InnerShadowTest
InnerShadowTest/ViewController.swift
1
973
import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.blue.withAlphaComponent(0.5) let innerFrame = CGRect(x: 50, y: 100, width: 100, height: 100) let innerView = UIView(frame: innerFrame) innerView.backgroundColor = UIColor.cyan innerView.addInnerShadow(onSide: UIView.innerShadowSide.bottomAndLeft, shadowColor: UIColor.red, shadowSize: 10.0, shadowOpacity: 10.0) var transform = CGAffineTransform.identity // define a transform transform = transform.rotated(by: CGFloat(Double.pi / 4)) // set transform's rotation transform = transform.scaledBy(x: 1.5, y: 2.0) // set transform's scale innerView.transform = transform // set transform to innerView view.addSubview(innerView) } }
mit
badc8c7dae9c8b70a97ffc329f1ae0d1
33.75
143
0.615622
4.700483
false
false
false
false
bugitapp/bugit
bugit/Tools/TextView.swift
1
4948
// // TextView.swift // bugit // // Created by Ernest on 11/21/16. // Copyright © 2016 BugIt App. All rights reserved. // import UIKit class TextView: UIView { var cgSize: CGSize = CGSize(width: 100, height: 100) var fillColor: UIColor! var outlineColor: UIColor! var originClick: CGPoint = CGPoint(x: 0, y: 0) init(origin: CGPoint, paletteColor: UIColor) { super.init(frame: CGRect(origin.x, origin.y, cgSize.width, cgSize.height)) self.outlineColor = paletteColor self.fillColor = UIColor.clear originClick = origin //self.center = origin self.backgroundColor = UIColor.clear initGestureRecognizers() } init(origin: CGPoint, size: CGSize, paletteColor: UIColor) { super.init(frame: CGRect(origin.x, origin.y, size.width, size.height)) self.cgSize = size self.outlineColor = paletteColor self.fillColor = UIColor.clear originClick = origin //self.center = origin self.backgroundColor = UIColor.clear initGestureRecognizers() } func initGestureRecognizers() { let panGR = UIPanGestureRecognizer(target: self, action: #selector(didPan)) addGestureRecognizer(panGR) let pinchGR = UIPinchGestureRecognizer(target: self, action: #selector(didPinch)) addGestureRecognizer(pinchGR) let rotationGR = UIRotationGestureRecognizer(target: self, action: #selector(didRotate)) addGestureRecognizer(rotationGR) } func pointFrom(angle: CGFloat, radius: CGFloat, offset: CGPoint) -> CGPoint { return CGPoint(radius * cos(angle) + offset.x, radius * sin(angle) + offset.y) } func trianglePathInRect(rect:CGRect) -> UIBezierPath { let path = UIBezierPath() path.move(to: CGPoint(rect.width / 2.0, rect.origin.y)) path.addLine(to: CGPoint(rect.width,rect.height)) path.addLine(to: CGPoint(rect.origin.x,rect.height)) path.close() return path } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func textToImage(drawText text: String, inImage image: UIImage) -> UIImage { let textColor = UIColor.white let textFont = UIFont(name: "HelveticaNeue-Bold", size: 14)! // TODO: Allow configuration of this in Alert box? let scale = UIScreen.main.scale UIGraphicsBeginImageContextWithOptions(image.size, false, scale) let textFontAttributes = [ NSFontAttributeName: textFont, NSForegroundColorAttributeName: textColor, ] as [String : Any] image.draw(in: CGRect(origin: CGPoint.zero, size: image.size)) let rect = CGRect(origin: self.center, size: image.size) text.draw(in: rect, withAttributes: textFontAttributes) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() dlog("newImage: \(newImage), for string: \(text)") return newImage! } func generateText(drawText text: String) -> CATextLayer { let textLayer = CATextLayer() textLayer.frame = CGRect(origin: CGPoint(0, 0), size: cgSize) //UIFont(name: "SFUIText-Light", size: 17)! textLayer.font = CTFontCreateWithName("SFUIText-Light" as CFString?, 17, nil) // TODO: Allow user to change dlog("font: \(textLayer.font)") textLayer.fontSize = 17.0 textLayer.string = text textLayer.foregroundColor = self.outlineColor.cgColor textLayer.isWrapped = true textLayer.alignmentMode = kCAAlignmentLeft textLayer.contentsScale = UIScreen.main.scale dlog("newTextLayer: \(textLayer), for string: \(text)") return textLayer } // MARK: Gestures func didPan(_ sender: UIPanGestureRecognizer) { self.superview!.bringSubview(toFront: self) var translation = sender.translation(in: self) translation = translation.applying(self.transform) self.center.x += translation.x self.center.y += translation.y sender.setTranslation(CGPoint.zero, in: self) } func didPinch(_ sender: UIPinchGestureRecognizer) { self.superview!.bringSubview(toFront: self) let scale = sender.scale self.transform = self.transform.scaledBy(x: scale, y: scale) sender.scale = 1.0 } func didRotate(_ sender: UIRotationGestureRecognizer) { self.superview!.bringSubview(toFront: self) let rotation = sender.rotation self.transform = self.transform.rotated(by: rotation) sender.rotation = 0.0 } }
apache-2.0
82de36024ed09f4a081f88f88d8f957f
31.761589
119
0.617546
4.724928
false
false
false
false
antonio081014/LeetCode-CodeBase
Swift/minimum-domino-rotations-for-equal-row.swift
2
1646
/** * https://leetcode.com/problems/minimum-domino-rotations-for-equal-row/ * * */ // Date: Thu Oct 22 11:48:16 PDT 2020 class Solution { func minDominoRotations(_ A: [Int], _ B: [Int]) -> Int { var count: [Int : Int] = [:] for index in 0 ..< A.count { count[A[index]] = 1 + count[A[index], default: 0] if A[index] != B[index] { count[B[index]] = 1 + count[B[index], default: 0] } } if let filteredOne = count.filter {$0.value == A.count }.first { var times1 = 0 var times2 = 0 // print(filteredOne) for index in 0 ..< A.count { if A[index] != filteredOne.key { times1 += 1 } if B[index] != filteredOne.key { times2 += 1 } } return min(times1, times2) } return -1 } } /** * https://leetcode.com/problems/minimum-domino-rotations-for-equal-row/ * * */ // Date: Thu Oct 22 11:53:07 PDT 2020 class Solution { func minDominoRotations(_ A: [Int], _ B: [Int]) -> Int { var count1 = Array(repeating: 0, count: 7) var count2 = Array(repeating: 0, count: 7) var same = Array(repeating: 0, count: 7) for index in 0 ..< A.count { count1[A[index]] += 1 count2[B[index]] += 1 if A[index] == B[index] { same[A[index]] += 1 } } for n in 1 ... 6 { if count1[n] + count2[n] - same[n] == A.count { return A.count - max(count1[n], count2[n]) } } return -1 } }
mit
1c08f7738d5962c0aeec98afc7f4c463
28.392857
72
0.469623
3.366053
false
false
false
false
HWdan/DYTV
DYTV/DYTV/Classes/Main/View/PageContentView.swift
1
5357
// // PageContentView.swift // DYTV // // Created by hegaokun on 2017/3/15. // Copyright © 2017年 AAS. All rights reserved. // import UIKit //MARK:- 设置代理 protocol PageContentViewDelegate: class { func pageContentView(contentView: PageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) } private let ContentCellID = "ContentCellID" class PageContentView: UIView { //MARK:- 定义属性 var childVcs: [UIViewController] weak var parentViewController: UIViewController? weak var delegate: PageContentViewDelegate? var startOffsetX: CGFloat = 0 var isForbiScrollDelegate: Bool = false //MARK:- 懒加载属性 lazy var collectionView: UICollectionView = {[weak self] in //创建 layout let layout = UICollectionViewFlowLayout() layout.itemSize = (self?.bounds.size)! layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.scrollDirection = .horizontal //创建 UICollectionView let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout) collectionView.showsHorizontalScrollIndicator = false collectionView.isPagingEnabled = true collectionView.bounces = false collectionView.dataSource = self collectionView.delegate = self collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: ContentCellID) return collectionView }() //MARK:- 自定义构造函数 init(frame: CGRect, childVcs: [UIViewController], parentViewController: UIViewController?) { self.childVcs = childVcs self.parentViewController = parentViewController super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } //MARK:- 设置 UI extension PageContentView { func setupUI() { //将所有的子控制器添加到父控制器中 for childVc in childVcs { parentViewController?.addChildViewController(childVc) } //添加 UICollectionView ,用于在 cell 中存放控制器的 View addSubview(collectionView) collectionView.frame = bounds } } //MARK:- UICollectionViewDataSource extension PageContentView: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return childVcs.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ContentCellID, for: indexPath) for view in cell.contentView.subviews { view.removeFromSuperview() } let childVc = childVcs[indexPath.item] cell.contentView.addSubview(childVc.view) return cell } } //MARK:- UICollectionViewDelegate extension PageContentView: UICollectionViewDelegate { func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { isForbiScrollDelegate = false startOffsetX = scrollView.contentOffset.x } func scrollViewDidScroll(_ scrollView: UIScrollView) { //判断是否是点击事件 if isForbiScrollDelegate { return } //获取需要的数据 var progress: CGFloat = 0 var sourceIndex: Int = 0 var targetIndex: Int = 0 //判断是左滑还是右滑 let currentOffsetX = scrollView.contentOffset.x let scrollViewW = scrollView.bounds.width if currentOffsetX > startOffsetX {//左滑 //计算滑动进度 progress let ratio = currentOffsetX / scrollViewW progress = ratio - floor(ratio) //计算 sourceIndex sourceIndex = Int(currentOffsetX / scrollViewW) //计算 targetIndex targetIndex = sourceIndex + 1 if targetIndex >= childVcs.count { targetIndex = childVcs.count - 1 } //如果完全滑动过去一个页面 if currentOffsetX - startOffsetX == scrollViewW { progress = 1 targetIndex = sourceIndex } } else {//右滑 //计算滑动进度 progress let ratio = currentOffsetX / scrollViewW progress = 1 - (ratio - floor(ratio)) //计算目标 targetIndex targetIndex = Int(currentOffsetX / scrollViewW) //计算源 sourceIndex sourceIndex = targetIndex + 1 if sourceIndex >= childVcs.count { sourceIndex = childVcs.count - 1 } } //将数据传递给 titleView delegate?.pageContentView(contentView: self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex) } } //MARK:- 对外暴露的方法 extension PageContentView { func setCurrentIndex(currentIndex: Int) { //记录需要禁止执行代理方法 isForbiScrollDelegate = true //滚动到正确的位置 let offsetX = CGFloat(currentIndex) * collectionView.frame.width collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: false) } }
mit
b510982760b8d6b549db20728312cd3f
32.223684
124
0.651881
5.617353
false
false
false
false
antonio081014/LeetCode-CodeBase
Swift/map-sum-pairs.swift
2
1517
/** * https://leetcode.com/problems/map-sum-pairs/ * * */ // Date: Fri Jul 30 16:44:14 PDT 2021 struct Trie { class TrieNode { var sum: Int = 0 var children: [Character : TrieNode] = [:] } let root: TrieNode = TrieNode() var dict: [String : Int] = [:] mutating func insert(_ key: String, _ val: Int) { let diff = val - dict[key, default: 0] self.dict[key] = val var node = root for c in key { if let child = node.children[c] { child.sum += diff node = child } else { let child = TrieNode() node.children[c] = child child.sum += diff node = child } } } func fetch(_ prefix: String) -> Int? { var node = root for c in prefix { if let child = node.children[c] { node = child } else { return nil } } return node.sum } } class MapSum { /** Initialize your data structure here. */ private var trie: Trie init() { self.trie = Trie() } func insert(_ key: String, _ val: Int) { self.trie.insert(key, val) } func sum(_ prefix: String) -> Int { return self.trie.fetch(prefix) ?? 0 } } /** * Your MapSum object will be instantiated and called as such: * let obj = MapSum() * obj.insert(key, val) * let ret_2: Int = obj.sum(prefix) */
mit
ed6530bb2593df3c2d1b808469ed0dd0
21.641791
62
0.479235
3.889744
false
false
false
false
zhou9734/Warm
Warm/Classes/Home/View/CUserCell.swift
1
3556
// // CUserCell.swift // Warm // // Created by zhoucj on 16/9/25. // Copyright © 2016年 zhoucj. All rights reserved. // import UIKit class CUserCell: UITableViewCell { var offsetY: CGFloat = 10 var teacher: WTeacher?{ didSet{ guard let _teacher = teacher else{ return } setupUI(_teacher) } } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupUI(teacher: WTeacher){ let _width = ScreenWidth - 30 userLbl.frame = CGRect(x: 15.0, y: offsetY, width: _width, height: 30) contentView.addSubview(userLbl) offsetY = offsetY + 45 spliteLine.frame = CGRect(x: 15, y: offsetY, width: _width, height: 1) offsetY = offsetY + 15 contentView.addSubview(spliteLine) //头像 iconImageView.frame = CGRect(x: (ScreenWidth - 50) / 2, y: offsetY, width: 50, height: 50) iconImageView.sd_setImageWithURL(NSURL(string: teacher.avatar!)!, placeholderImage: placeholderImage) contentView.addSubview(iconImageView) offsetY = offsetY + 50 //昵称 nicknameLbl.frame = CGRect(x: (ScreenWidth - 200) / 2, y: offsetY, width: 200, height: 15) nicknameLbl.text = teacher.nickname contentView.addSubview(nicknameLbl) offsetY = offsetY + 30 //个性签名 let txt = teacher.signature //行距 let lineSpacing: CGFloat = 7 let height = signatureLbl.getHeightByWidthOfAttributedString(_width, title: txt, font: signatureLbl.font, lineSpacing: lineSpacing) signatureLbl.frame = CGRect(x: 15.0, y: offsetY, width: _width, height: height) let attrStr = NSMutableAttributedString(string: txt) let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineSpacing = lineSpacing attrStr.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSMakeRange(0, txt.characters.count)) signatureLbl.attributedText = attrStr contentView.addSubview(signatureLbl) offsetY = offsetY + height + 10 contentView.layoutIfNeeded() } private lazy var userLbl: UILabel = { let lbl = UILabel() lbl.textColor = UIColor.blackColor() lbl.textAlignment = .Left lbl.font = UIFont.systemFontOfSize(20) lbl.text = "手艺人" return lbl }() private lazy var spliteLine: UIView = { let v = UIView() v.backgroundColor = SpliteColor return v }() private lazy var iconImageView: UIImageView = { let iv = UIImageView() iv.layer.cornerRadius = 25 iv.layer.masksToBounds = true return iv }() private lazy var nicknameLbl: UILabel = { let lbl = UILabel() lbl.textColor = UIColor.grayColor() lbl.textAlignment = .Center lbl.font = UIFont.systemFontOfSize(14) return lbl }() private lazy var signatureLbl: UILabel = { let lbl = UILabel() lbl.textColor = UIColor.grayColor() lbl.textAlignment = .Left lbl.font = UIFont.systemFontOfSize(16) lbl.numberOfLines = 0 return lbl }() func calucateHeight(_teacher: WTeacher) -> CGFloat{ self.teacher = _teacher return offsetY } }
mit
9fefb5a5dbd7881ca6b0ce2296eed8f4
31.657407
139
0.623476
4.539254
false
false
false
false
RajmohanKathiresan/emotiphor_ios
Emotiphor/ViewController/HomeViewController.swift
1
3080
// // HomeViewController.swift // Emotiphor // // Created by Rajmohan Kathiresan on 22/10/16. // Copyright © 2016 Rajmohan Kathiresan. All rights reserved. // import UIKit class HomeViewController: UIViewController { let menus = HomeMenu.defaultItems() @IBOutlet weak var menuCollectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() self.title = "Emotiphor" self.menuCollectionView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension HomeViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return menus.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HomeMenuCell.kIdentifier, for: indexPath) as! HomeMenuCell cell.setContent(menus[indexPath.row]) return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { var width:CGFloat = (collectionView.frame.width/2.0) - 10 let height:CGFloat = width if(indexPath.row == menus.count-1 && (indexPath.row+1)%2 != 0) { width = collectionView.frame.width } return CGSize(width: width, height: height) } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let menu = menus[indexPath.row] switch menu.type { case .createCollage: let creatorController = UIViewController.GetViewController(instoryboard: CreatorViewController.kStoryboardName, withController: CreatorViewController.kControllerIdentifier) as! CreatorViewController self.navigationController?.pushViewController(creatorController, animated: true) break case .createEmojiWall: let emojiWallController = UIViewController.GetViewController(instoryboard: EmojiWallCreatorViewController.kStoryboardName, withController: EmojiWallCreatorViewController.kControllerIdentifier) as! EmojiWallCreatorViewController self.navigationController?.pushViewController(emojiWallController, animated: true) break default: let colorPickerColor = UIViewController.GetViewController(instoryboard: PantoneColorPickerController.kStoryboardName, withController: PantoneColorPickerController.kControllerIdentifier) as! PantoneColorPickerController self.navigationController?.pushViewController(colorPickerColor, animated: true) break } } }
mpl-2.0
b20dcb2c4c0520d83c0fa562ee562dab
42.366197
239
0.725235
5.468917
false
false
false
false
OscarSwanros/swift
test/decl/inherit/override.swift
3
3403
// RUN: %target-typecheck-verify-swift -parse-as-library -swift-version 4 @objc class ObjCClassA {} @objc class ObjCClassB : ObjCClassA {} class A { func f1() { } // expected-note{{overridden declaration is here}} func f2() -> A { } // expected-note{{overridden declaration is here}} @objc func f3() { } // expected-note{{overridden declaration is here}} @objc func f4() -> ObjCClassA { } // expected-note{{overridden declaration is here}} @objc var v1: Int { return 0 } // expected-note{{overridden declaration is here}} @objc var v2: Int { return 0 } // expected-note{{overridden declaration is here}} @objc var v3: Int = 0 // expected-note{{overridden declaration is here}} dynamic func f3D() { } // expected-error{{'dynamic' instance method 'f3D()' must also be '@objc'}}{{3-3=@objc }} dynamic func f4D() -> ObjCClassA { } // expected-error{{'dynamic' instance method 'f4D()' must also be '@objc'}}{{3-3=@objc }} } extension A { func f5() { } // expected-note{{overridden declaration is here}} func f6() -> A { } // expected-note{{overridden declaration is here}} @objc func f7() { } @objc func f8() -> ObjCClassA { } } class B : A { } extension B { func f1() { } // expected-error{{overriding declarations in extensions is not supported}} func f2() -> B { } // expected-error{{overriding declarations in extensions is not supported}} override func f3() { } // expected-error{{cannot override a non-dynamic class declaration from an extension}} override func f4() -> ObjCClassB { } // expected-error{{cannot override a non-dynamic class declaration from an extension}} override var v1: Int { return 1 } // expected-error{{cannot override a non-dynamic class declaration from an extension}} override var v2: Int { // expected-error{{cannot override a non-dynamic class declaration from an extension}} get { return 1 } set { } } override var v3: Int { // expected-error{{cannot override a non-dynamic class declaration from an extension}} willSet { } didSet { } } override func f3D() { } override func f4D() -> ObjCClassB { } func f5() { } // expected-error{{overriding declarations in extensions is not supported}} func f6() -> A { } // expected-error{{overriding declarations in extensions is not supported}} @objc override func f7() { } @objc override func f8() -> ObjCClassA { } } func callOverridden(_ b: B) { b.f3() _ = b.f4() b.f7() _ = b.f8() } @objc class Base { func meth(_ x: Undeclared) {} // expected-error {{use of undeclared type 'Undeclared'}} } @objc class Sub : Base { func meth(_ x: Undeclared) {} // expected-error {{use of undeclared type 'Undeclared'}} } // Objective-C method overriding @objc class ObjCSuper { func method(_ x: Int, withInt y: Int) { } func method2(_ x: Sub, withInt y: Int) { } @objc func method3(_ x: Base, withInt y: Int) { } // expected-note{{method 'method3(_:withInt:)' declared here}} } class ObjCSub : ObjCSuper { override func method(_ x: Int, withInt y: Int) { } // okay, overrides exactly override func method2(_ x: Base, withInt y: Int) { } // okay, overrides trivially @objc(method3:withInt:) func method3(_ x: Sub, with y: Int) { } // expected-error{{method3(_:with:)' with Objective-C selector 'method3:withInt:' conflicts with method 'method3(_:withInt:)' from superclass 'ObjCSuper' with the same Objective-C selector}} }
apache-2.0
26a6b39d823beda436a50fdc33ba0121
37.670455
256
0.666177
3.631804
false
false
false
false
byu-oit/ios-byuSuite
byuSuite/Apps/LockerRental/controller/LockerRentalMyLockersDetailViewController.swift
1
5357
// // LockerRentalMyLockersDetailViewController.swift // byuSuite // // Created by Erik Brady on 7/20/17. // Copyright © 2017 Brigham Young University. All rights reserved. // private let CONTACT_PHONE = "801-422-4000" //Cell Identifiers private let LOCATION = "locationCell" private let DETAIL = "detailCell" private let TUTORIAL = "tutorialCell" private let HELP = "helpCell" private let RENEWAL = "renewalCell" private let ACTIONS_HELPER = LockerRentalActionsHelper() class LockerRentalMyLockersDetailViewController: ByuTableDataViewController { //MARK: Public Properties var delegate: LockerRentalDelegate! var agreement: LockerRentalAgreement! //MARK: Private Properties var combination: String? var fees: [LockerRentalLockerFee]? override func viewDidLoad() { super.viewDidLoad() title = agreement.locker?.displayedLockerNumber //Load the tableData to display already loaded data while we wait for additional data (renewal fees and combination) to come back loadTableData() loadData() } //MARK: Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "myLockerMap", let vc = segue.destination as? LockerRentalLockerMapViewController, let locker = agreement.locker { vc.locker = locker } else if segue.identifier == "toLockerVideo", let vc = segue.destination as? LockerRentalTutorialWebViewController, let video = agreement.locker?.video { vc.videoUrlString = video } } //MARK: Custom Methods private func loadTableData() { if combination != nil && fees != nil { spinner?.stopAnimating() } //Overwrite tableData to empty it tableData = TableData() //Add Locker Information Section tableData.add(section: getLockerInfoSection()) //Add Get Locker Help Section tableData.add(section: getLockerHelpSection()) //Create the Fees Section if let fees = fees, fees.count > 0 { let feeRows = fees.map({ (fee) -> Row in return self.getFeeRow(fee: fee) }) tableData.add(section: Section(title: "Renew Locker", cellId: RENEWAL, rows: feeRows)) } tableView.reloadData() } private func getLockerInfoSection() -> Section { return Section(title: "Locker Information", rows: [ Row(text: "Location:", detailText: "\(agreement.locker?.building ?? "") Floor \(agreement.locker?.floor ?? "")", cellId: LOCATION), Row(text: "Position:", detailText: agreement.locker?.verticalPositionCode ?? "", cellId: DETAIL), Row(text: "Size:", detailText: agreement.locker?.lockerSizeCode ?? "", cellId: DETAIL), Row(text: "Combo:", detailText: combination ?? "Loading...", cellId: DETAIL), Row(text: "Expires On:", detailText: agreement.expirationDateString(), cellId: DETAIL) ]) } private func getLockerHelpSection() -> Section { var rows = [Row]() if agreement.locker?.video != nil { rows.append(Row(text: "View Tutorial Video", cellId: TUTORIAL)) } rows.append(Row(text: "Get Additional Help", cellId: HELP, action: { if let indexPath = self.tableView.indexPathForSelectedRow, let cell = self.tableView.cellForRow(at: indexPath) { self.displayActionSheet(from: cell, actions: [UIAlertAction(title: CONTACT_PHONE, style: .default, handler: { (action) in if let url = URL(string: "tel://\(CONTACT_PHONE)") { UIApplication.shared.openURL(url) } })]) self.tableView.deselectSelectedRow() } })) return Section(title: "Get Locker Help", rows: rows) } private func getFeeRow(fee: LockerRentalLockerFee) -> Row { return Row(text: "Renew \(fee.name ?? "")", detailText: "$\(fee.amount?.toString() ?? "").00", action: { if let locker = self.agreement.locker, let indexPath = self.tableView.indexPathForSelectedRow, let fee = self.fees?[indexPath.row] { ACTIONS_HELPER.rent(locker: locker, fee: fee, viewController: self, delegate: self.delegate, spinner: self.spinner) self.tableView.deselectSelectedRow() } else { super.displayAlert() } }) } private func loadData() { if let serialNumber = agreement.locker?.serialNumber { LockerRentalClient.getLockerCombination(serialNumber: serialNumber) { (combination, error) in if let combination = combination { self.combination = combination self.loadTableData() } else { super.displayAlert(error: error, title: "Unable to Load Combination", alertHandler: nil) } } } if let locker = agreement.locker { LockerRentalClient.getFees(locker: locker, callback: { (fees, error) in if let fees = fees { self.fees = fees self.loadTableData() } else { super.displayAlert(error: error, title: "Unable to Load Fees", alertHandler: nil) } }) } } }
apache-2.0
319f1e0078e68e655f25d2962506c165
37.811594
162
0.616131
4.493289
false
false
false
false
luckymore0520/GreenTea
Loyalty/Cards/Controller/MyCardViewController.swift
1
3782
// // MyCardViewController.swift // Loyalty // // Created by WangKun on 16/4/16. // Copyright © 2016年 WangKun. All rights reserved. // import UIKit import Koloda class MyCardViewController: UIViewController { @IBOutlet weak var kolodaView: KolodaView! @IBOutlet weak var currentNumLabel: UILabel! var cardDataSource = CardDataSource() override func viewDidLoad() { super.viewDidLoad() kolodaView.dataSource = cardDataSource kolodaView.delegate = self NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MyCardViewController.reloadData), name: "RELOADCARDS", object: nil) // Do any additional setup after loading the view. } deinit{ NSNotificationCenter.defaultCenter().removeObserver(self) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.navigationController?.navigationBarHidden = true self.reloadData() } func reloadData(){ self.cardDataSource.reloadData() self.kolodaView.resetCurrentCardIndex() if self.kolodaView.countOfCards > 0 { self.currentNumLabel.text = "\(self.kolodaView.currentCardIndex + 1)/\(self.kolodaView.countOfCards)" } else { self.currentNumLabel.text = "" } } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.kolodaView.reloadData() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) self.navigationController?.navigationBarHidden = false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func setSelectedActivity(activityId:String) { if self.cardDataSource.moveToCardActivity(activityId) { self.kolodaView.resetCurrentCardIndex() } } } extension MyCardViewController { @IBAction func onDeleteButtonClicked(sender: AnyObject) { let alertController = UIAlertController(title: "你确定要删除这张集点卡吗?", message: nil, preferredStyle: .Alert) alertController.addAction(UIAlertAction(title: "确定", style: .Default, handler: { (action) in let card = self.cardDataSource.cardList[self.kolodaView.currentCardIndex] UserInfoManager.sharedManager.currentUser?.exchangeCard(card.objectId) card.delete() self.reloadData() })) alertController.addAction(UIAlertAction(title: "取消", style: .Cancel, handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } @IBAction func onShareButtonClicked(sender: AnyObject) { let cardView = kolodaView.viewForCardAtIndex(kolodaView.currentCardIndex) as? CardView let card = self.cardDataSource.cardList[kolodaView.currentCardIndex] var activityItems:[AnyObject] = ["我在\"\(card.activity.name)\"活动中已经集齐了\(card.currentCount)个点!"] if let image = cardView?.imageView.image { activityItems.append(image) } let activityShareController = UIActivityViewController(activityItems: activityItems, applicationActivities: nil) self.presentViewController(activityShareController, animated: true, completion: nil) } } extension MyCardViewController:KolodaViewDelegate { func koloda(koloda: KolodaView, didShowCardAtIndex index: UInt) { self.currentNumLabel.text = "\(koloda.currentCardIndex + 1)/\(koloda.countOfCards)" } func kolodaDidRunOutOfCards(koloda: KolodaView) { koloda.resetCurrentCardIndex() } }
mit
bb6a4cd494df21e55041a3ee5268aaa0
34.419048
150
0.688088
4.906332
false
false
false
false
gregomni/swift
test/Generics/associated_type_typo.swift
2
3194
// RUN: %target-typecheck-verify-swift -requirement-machine-protocol-signatures=verify -requirement-machine-inferred-signatures=verify // RUN: not %target-swift-frontend -typecheck -debug-generic-signatures %s -requirement-machine-protocol-signatures=verify -requirement-machine-inferred-signatures=verify > %t.dump 2>&1 // RUN: %FileCheck -check-prefix CHECK-GENERIC %s < %t.dump protocol P1 { associatedtype Assoc } protocol P2 { associatedtype AssocP2 : P1 } protocol P3 { } protocol P4 { } // expected-error@+1{{'T' does not have a member type named 'assoc'; did you mean 'Assoc'?}} func typoAssoc1<T : P1>(x: T.assoc, _: T) { } // expected-error@+2{{'T' does not have a member type named 'assoc'; did you mean 'Assoc'?}}{{53-58=Assoc}} // expected-error@+1{{'U' does not have a member type named 'assoc'; did you mean 'Assoc'?}}{{64-69=Assoc}} func typoAssoc2<T : P1, U : P1>(_: T, _: U) where T.assoc == U.assoc {} // CHECK-GENERIC-LABEL: .typoAssoc2 // CHECK-GENERIC: Generic signature: <T, U where T : P1, U : P1> // expected-error@+3{{'T.AssocP2' does not have a member type named 'assoc'; did you mean 'Assoc'?}}{{42-47=Assoc}} // expected-error@+2{{'U.AssocP2' does not have a member type named 'assoc'; did you mean 'Assoc'?}}{{19-24=Assoc}} func typoAssoc3<T : P2, U : P2>(t: T, u: U) where U.AssocP2.assoc : P3, T.AssocP2.assoc : P4, T.AssocP2 == U.AssocP2 {} // expected-error@+2{{'T.AssocP2' does not have a member type named 'assoc'; did you mean 'Assoc'?}} // expected-error@+1{{'T' does not have a member type named 'Assocp2'; did you mean 'AssocP2'?}}{{39-46=AssocP2}} func typoAssoc4<T : P2>(_: T) where T.Assocp2.assoc : P3 {} // <rdar://problem/19620340> func typoFunc1<T : P1>(x: TypoType) { // expected-error{{cannot find type 'TypoType' in scope}} let _: (T.Assoc) -> () = { let _ = $0 } } func typoFunc2<T : P1>(x: TypoType, y: T) { // expected-error{{cannot find type 'TypoType' in scope}} let _: (T.Assoc) -> () = { let _ = $0 } } func typoFunc3<T : P1>(x: TypoType, y: (T.Assoc) -> ()) { // expected-error{{cannot find type 'TypoType' in scope}} } // rdar://problem/29261689 typealias Element_<S: Sequence> = S.Iterator.Element public protocol _Indexable1 { associatedtype Slice // expected-note{{declared here}} } public protocol Indexable : _Indexable1 { associatedtype Slice : _Indexable1 // expected-warning{{redeclaration of associated type 'Slice'}} } protocol Pattern { associatedtype Element : Equatable // FIXME: This works for all of the wrong reasons, but it is correct that // it works. func matched<C: Indexable>(atStartOf c: C) where Element_<C> == Element , Element_<C.Slice> == Element } class C { typealias SomeElement = Int } func typoSuperclass1<T : C>(_: T) where T.someElement: P3 { } // expected-error@-1{{'T' does not have a member type named 'someElement'; did you mean 'SomeElement'?}}{{43-54=SomeElement}} class D { typealias AElement = Int // expected-note{{did you mean 'AElement'?}} typealias BElement = Int // expected-note{{did you mean 'BElement'?}} } func typoSuperclass2<T : D>(_: T, _: T.Element) { } // expected-error{{'Element' is not a member type of type 'T'}}
apache-2.0
add1f2f40e30d51f5d7d503298001874
37.95122
186
0.671572
3.14061
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/Helpers/ZMConversationMessage+Announcement.swift
1
2309
// // Wire // Copyright (C) 2022 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 WireDataModel extension ZMConversationMessage { typealias ConversationAnnouncement = L10n.Accessibility.ConversationAnnouncement /// A notification should be posted when an announcement needs to be sent to VoiceOver. func postAnnouncementIfNeeded() { if let announcement = announcementText() { UIAccessibility.post(notification: .announcement, argument: announcement) } } private func announcementText() -> String? { if isKnock { return ConversationAnnouncement.Ping.description(senderName) } else if isText, let textMessageData = textMessageData { let messageText = NSAttributedString.format(message: textMessageData, isObfuscated: isObfuscated) return "\(ConversationAnnouncement.Text.description(senderName)), \(messageText.string)" } else if isImage { return ConversationAnnouncement.Picture.description(senderName) } else if isLocation { return ConversationAnnouncement.Location.description(senderName) } else if isAudio { return ConversationAnnouncement.Audio.description(senderName) } else if isVideo { return ConversationAnnouncement.Video.description(senderName) } else if isFile { return ConversationAnnouncement.File.description((filename ?? ""), senderName) } else if isSystem, let cellDescription = ConversationSystemMessageCellDescription.cells(for: self).first { return cellDescription.cellAccessibilityLabel } return nil } }
gpl-3.0
2f0882be4b1b87c3f55bf1ab56a709e7
40.981818
115
0.713296
5.154018
false
false
false
false
wireapp/wire-ios
Wire-iOS Share Extension/NSExtensionContext+Attachments.swift
1
2696
// // Wire // Copyright (C) 2017 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 MobileCoreServices extension NSExtensionContext { /// Get all the attachments to this post. var attachments: [NSItemProvider] { guard let items = inputItems as? [NSExtensionItem] else { return [] } return items.flatMap { $0.attachments ?? [] } } } // MARK: - Sorting extension Array where Element == NSItemProvider { /// Returns the attachments sorted by type. var sorted: [AttachmentType: [NSItemProvider]] { var attachments: [AttachmentType: [NSItemProvider]] = [:] for attachment in self { if attachment.hasImage { attachments[.image, default: []].append(attachment) } else if attachment.hasVideo { attachments[.video, default: []].append(attachment) } else if attachment.hasWalletPass { attachments[.walletPass, default: []].append(attachment) } else if attachment.hasRawFile { attachments[.rawFile, default: []].append(attachment) } else if attachment.hasURL { attachments[.url, default: []].append(attachment) } else if attachment.hasFileURL { attachments[.fileUrl, default: []].append(attachment) } } return attachments } } // MARK: - Preview Support extension Dictionary where Key == AttachmentType, Value == [NSItemProvider] { /** * Determines the main preview item for the post. * * We determine this using the following rules: * - media = video AND/OR photo * - passes OR media OR file * - passes OR media OR file > URL * - video > photo */ var main: (AttachmentType, NSItemProvider)? { let sortedAttachments = self for attachmentType in AttachmentType.allCases { if let item = sortedAttachments[attachmentType]?.first { return (attachmentType, item) } } return nil } }
gpl-3.0
81e35de6252c05ee22c7bad1f57f3787
29.988506
77
0.634644
4.771681
false
false
false
false
jasnig/DouYuTVMutate
DouYuTVMutate/DouYuTV/Home/Controller/GameController.swift
1
3240
// // GameController.swift // DouYuTVMutate // // Created by ZeroJ on 16/7/13. // Copyright © 2016年 ZeroJ. All rights reserved. // import UIKit class GameController: BaseViewController { let cellID = "cellID" var viewModel = GameViewModel() lazy var layout: UICollectionViewFlowLayout = { let cellMargin:CGFloat = 10.0 let layout = UICollectionViewFlowLayout() layout.minimumLineSpacing = cellMargin layout.minimumInteritemSpacing = 0 layout.itemSize = CGSize(width: (Constant.screenWidth - 2*cellMargin)/4, height: 95.0) layout.scrollDirection = .Vertical // 间距 layout.sectionInset = UIEdgeInsets(top: cellMargin, left: cellMargin, bottom: cellMargin, right: cellMargin) return layout }() private(set) lazy var collectionView: UICollectionView = { let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: self.layout) collectionView.registerNib(UINib(nibName: String(GameCell), bundle: nil), forCellWithReuseIdentifier: self.cellID) collectionView.delegate = self collectionView.dataSource = self collectionView.showsHorizontalScrollIndicator = false collectionView.backgroundColor = UIColor.whiteColor() return collectionView }() override func viewDidLoad() { super.viewDidLoad() view.addSubview(collectionView) // 加载数据 self.viewModel.loadDataWithHandler({[weak self] (loadState) in guard let `self` = self else { return } self.collectionView.reloadData() }) } override func addConstraints() { super.addConstraints() collectionView.snp_makeConstraints { (make) in make.leading.equalTo(view) make.top.equalTo(view) make.trailing.equalTo(view) make.bottom.equalTo(view) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension GameController: UICollectionViewDelegate, UICollectionViewDataSource { func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return viewModel.data.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellID, forIndexPath: indexPath) as! GameCell cell.confinCell(viewModel.data[indexPath.row]) return cell } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { let model = viewModel.data[indexPath.row] let allListViewModel = AllListViewModel(tagID: model.tag_id) let liveVc = AllListController(viewModel: allListViewModel) liveVc.title = model.tag_name self.showViewController(liveVc, sender: nil) } }
mit
1568e4e74f07f0782679b1224cc6e96b
32.947368
130
0.672868
5.357143
false
false
false
false
zeroc-ice/ice-demos
swift/Chat/views/LoginView.swift
1
2996
// // Copyright (c) ZeroC, Inc. All rights reserved. // import SwiftUI struct LoginView: View { @ObservedObject var client = Client() @State var showingAlert = false @State var loginError: String? var body: some View { NavigationView { VStack(spacing: 25) { Spacer() VStack(alignment: .leading, spacing: 25) { Text("ZeroC Chat Demo").font(.title).bold() Text("Username") TextField("Username", text: $client.loginViewModel.username) .textFieldStyle(.roundedBorder) Text("Password") TextField("Password", text: $client.loginViewModel.password) .textFieldStyle(.roundedBorder) } .padding() .offset(y: -35) HStack { Spacer() Button("Login") { client.attemptLogin { error in showingAlert = error != nil loginError = error } } .padding() .frame(maxWidth: .infinity, maxHeight: 55) .background(client.loginViewModel.isSigninComplete ? Color.activeBlue : Color.disabledBlue) .accentColor(.white) .cornerRadius(10.0) .disabled(!client.loginViewModel.isSigninComplete) .alert(isPresented: $showingAlert) { Alert(title: Text("Error"), message: Text(loginError ?? ""), dismissButton: .default(Text("Got it!"))) } Spacer() } NavigationLink("Chat View", destination: MessagesView().environmentObject(client).navigationTitle("Messages"), isActive: $client.isLoggedIn) .hidden() .onReceive(NotificationCenter.default.publisher(for: UIApplication.didEnterBackgroundNotification), perform: { _ in client.destroySession() }) Spacer() } .padding() }.navigationViewStyle(.stack) } } struct LoginView_Previews: PreviewProvider { static var previews: some View { LoginView() .previewDevice("iPhone 13 Pro") } } extension View { @ViewBuilder func isHidden(_ isHidden: Bool) -> some View { if isHidden { hidden() } else { self } } } extension Color { static let activeBlue = Color(UIColor(red: 0.27, green: 0.50, blue: 0.82, alpha: 1.00)) static let disabledBlue = Color(UIColor(red: 0.64, green: 0.75, blue: 0.91, alpha: 1.00)) }
gpl-2.0
7006fe52ff62fe87d18c3482cc6506d6
34.666667
119
0.471963
5.457195
false
false
false
false
frootloops/swift
stdlib/public/core/ClosedRange.swift
1
14326
//===--- ClosedRange.swift ------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // FIXME: swift-3-indexing-model: Generalize all tests to check both // [Closed]Range and [Closed]CountableRange. @_versioned internal enum _ClosedRangeIndexRepresentation<Bound> where Bound : Strideable, Bound.Stride : BinaryInteger { case pastEnd case inRange(Bound) } // FIXME(ABI)#23 (Nesting types in generics): should be a nested type in // `ClosedRange`. /// A position in a `CountableClosedRange` instance. @_fixed_layout public struct ClosedRangeIndex<Bound: Strideable> where Bound.Stride : SignedInteger { @_versioned internal var _value: _ClosedRangeIndexRepresentation<Bound> /// Creates the "past the end" position. @_inlineable @_versioned internal init() { _value = .pastEnd } /// Creates a position `p` for which `r[p] == x`. @_inlineable @_versioned internal init(_ x: Bound) { _value = .inRange(x) } @_inlineable @_versioned internal var _dereferenced: Bound { switch _value { case .inRange(let x): return x case .pastEnd: _preconditionFailure("Index out of range") } } } extension ClosedRangeIndex : Comparable { @_inlineable public static func == ( lhs: ClosedRangeIndex<Bound>, rhs: ClosedRangeIndex<Bound> ) -> Bool { switch (lhs._value, rhs._value) { case (.inRange(let l), .inRange(let r)): return l == r case (.pastEnd, .pastEnd): return true default: return false } } @_inlineable public static func < ( lhs: ClosedRangeIndex<Bound>, rhs: ClosedRangeIndex<Bound> ) -> Bool { switch (lhs._value, rhs._value) { case (.inRange(let l), .inRange(let r)): return l < r case (.inRange(_), .pastEnd): return true default: return false } } } extension ClosedRangeIndex : Hashable where Bound : Hashable { public var hashValue: Int { switch _value { case .inRange(let value): return value.hashValue case .pastEnd: return .max } } } /// A closed range that forms a collection of consecutive values. /// /// You create a `CountableClosedRange` instance by using the closed range /// operator (`...`). /// /// let throughFive = 0...5 /// /// A `CountableClosedRange` instance contains both its lower bound and its /// upper bound. /// /// print(throughFive.contains(3)) // Prints "true" /// print(throughFive.contains(10)) // Prints "false" /// print(throughFive.contains(5)) // Prints "true" /// /// Because a closed range includes its upper bound, a closed range whose lower /// bound is equal to the upper bound contains one element. Therefore, a /// `CountableClosedRange` instance cannot represent an empty range. /// /// let zeroInclusive = 0...0 /// print(zeroInclusive.isEmpty) /// // Prints "false" /// print(zeroInclusive.count) /// // Prints "1" /// /// You can use a `for`-`in` loop or any sequence or collection method with a /// countable range. The elements of the range are the consecutive values from /// its lower bound up to, and including, its upper bound. /// /// for n in throughFive.suffix(3) { /// print(n) /// } /// // Prints "3" /// // Prints "4" /// // Prints "5" /// /// You can create a countable range over any type that conforms to the /// `Strideable` protocol and uses an integer as its associated `Stride` type. /// By default, Swift's integer and pointer types are usable as the bounds of /// a countable range. /// /// Because floating-point types such as `Float` and `Double` are their own /// `Stride` types, they cannot be used as the bounds of a countable range. If /// you need to test whether values are contained within a closed interval /// bound by floating-point values, see the `ClosedRange` type. If you need to /// iterate over consecutive floating-point values, see the /// `stride(from:through:by:)` function. @_fixed_layout public struct CountableClosedRange<Bound: Strideable> where Bound.Stride : SignedInteger { /// The range's lower bound. public let lowerBound: Bound /// The range's upper bound. /// /// `upperBound` is always reachable from `lowerBound` by zero or /// more applications of `index(after:)`. public let upperBound: Bound /// Creates an instance with the given bounds. /// /// Because this initializer does not perform any checks, it should be used /// as an optimization only when you are absolutely certain that `lower` is /// less than or equal to `upper`. Using the closed range operator (`...`) /// to form `CountableClosedRange` instances is preferred. /// /// - Parameter bounds: A tuple of the lower and upper bounds of the range. @_inlineable public init(uncheckedBounds bounds: (lower: Bound, upper: Bound)) { self.lowerBound = bounds.lower self.upperBound = bounds.upper } } extension CountableClosedRange: RandomAccessCollection { /// The element type of the range; the same type as the range's bounds. public typealias Element = Bound /// A type that represents a position in the range. public typealias Index = ClosedRangeIndex<Bound> /// The position of the first element in the range. @_inlineable public var startIndex: ClosedRangeIndex<Bound> { return ClosedRangeIndex(lowerBound) } /// The range's "past the end" position---that is, the position one greater /// than the last valid subscript argument. @_inlineable public var endIndex: ClosedRangeIndex<Bound> { return ClosedRangeIndex() } @_inlineable public func index(after i: Index) -> Index { switch i._value { case .inRange(let x): return x == upperBound ? ClosedRangeIndex() : ClosedRangeIndex(x.advanced(by: 1)) case .pastEnd: _preconditionFailure("Incrementing past end index") } } @_inlineable public func index(before i: Index) -> Index { switch i._value { case .inRange(let x): _precondition(x > lowerBound, "Incrementing past start index") return ClosedRangeIndex(x.advanced(by: -1)) case .pastEnd: _precondition(upperBound >= lowerBound, "Incrementing past start index") return ClosedRangeIndex(upperBound) } } @_inlineable public func index(_ i: Index, offsetBy n: Int) -> Index { switch i._value { case .inRange(let x): let d = x.distance(to: upperBound) if n <= d { let newPosition = x.advanced(by: numericCast(n)) _precondition(newPosition >= lowerBound, "Advancing past start index") return ClosedRangeIndex(newPosition) } if d - -1 == n { return ClosedRangeIndex() } _preconditionFailure("Advancing past end index") case .pastEnd: if n == 0 { return i } if n < 0 { return index(ClosedRangeIndex(upperBound), offsetBy: numericCast(n + 1)) } _preconditionFailure("Advancing past end index") } } @_inlineable public func distance(from start: Index, to end: Index) -> Int { switch (start._value, end._value) { case let (.inRange(left), .inRange(right)): // in range <--> in range return numericCast(left.distance(to: right)) case let (.inRange(left), .pastEnd): // in range --> end return numericCast(1 + left.distance(to: upperBound)) case let (.pastEnd, .inRange(right)): // in range <-- end return numericCast(upperBound.distance(to: right) - 1) case (.pastEnd, .pastEnd): // end <--> end return 0 } } /// Accesses the element at specified position. /// /// You can subscript a collection with any valid index other than the /// collection's end index. The end index refers to the position one past /// the last element of a collection, so it doesn't correspond with an /// element. /// /// - Parameter position: The position of the element to access. `position` /// must be a valid index of the range, and must not equal the range's end /// index. @_inlineable public subscript(position: ClosedRangeIndex<Bound>) -> Bound { // FIXME: swift-3-indexing-model: range checks and tests. return position._dereferenced } @_inlineable public subscript(bounds: Range<Index>) -> Slice<CountableClosedRange<Bound>> { return Slice(base: self, bounds: bounds) } @_inlineable public func _customContainsEquatableElement(_ element: Bound) -> Bool? { return element >= self.lowerBound && element <= self.upperBound } /// A Boolean value indicating whether the range contains no elements. /// /// Because a closed range cannot represent an empty range, this property is /// always `false`. @_inlineable public var isEmpty: Bool { return false } /// Returns a Boolean value indicating whether the given element is contained /// within the range. /// /// A `CountableClosedRange` instance contains both its lower and upper bound. /// `element` is contained in the range if it is between the two bounds or /// equal to either bound. /// /// - Parameter element: The element to check for containment. /// - Returns: `true` if `element` is contained in the range; otherwise, /// `false`. @_inlineable public func contains(_ element: Bound) -> Bool { return element >= self.lowerBound && element <= self.upperBound } } /// An interval over a comparable type, from a lower bound up to, and /// including, an upper bound. /// /// You create instances of `ClosedRange` by using the closed range operator /// (`...`). /// /// let lowercase = "a"..."z" /// /// You can use a `ClosedRange` instance to quickly check if a value is /// contained in a particular range of values. For example: /// /// print(lowercase.contains("c")) // Prints "true" /// print(lowercase.contains("5")) // Prints "false" /// print(lowercase.contains("z")) // Prints "true" /// /// Unlike `Range`, instances of `ClosedRange` cannot represent an empty /// interval. /// /// let lowercaseA = "a"..."a" /// print(lowercaseA.isEmpty) /// // Prints "false" @_fixed_layout public struct ClosedRange<Bound : Comparable> { /// The range's lower bound. public let lowerBound: Bound /// The range's upper bound. public let upperBound: Bound /// Creates an instance with the given bounds. /// /// Because this initializer does not perform any checks, it should be used /// as an optimization only when you are absolutely certain that `lower` is /// less than or equal to `upper`. Using the closed range operator (`...`) /// to form `ClosedRange` instances is preferred. /// /// - Parameter bounds: A tuple of the lower and upper bounds of the range. @inline(__always) public init(uncheckedBounds bounds: (lower: Bound, upper: Bound)) { self.lowerBound = bounds.lower self.upperBound = bounds.upper } /// Returns a Boolean value indicating whether the given element is contained /// within the range. /// /// A `ClosedRange` instance contains both its lower and upper bound. /// `element` is contained in the range if it is between the two bounds or /// equal to either bound. /// /// - Parameter element: The element to check for containment. /// - Returns: `true` if `element` is contained in the range; otherwise, /// `false`. @_inlineable public func contains(_ element: Bound) -> Bool { return element >= self.lowerBound && element <= self.upperBound } /// A Boolean value indicating whether the range contains no elements. /// /// Because a closed range cannot represent an empty range, this property is /// always `false`. @_inlineable public var isEmpty: Bool { return false } } extension Comparable { /// Returns a closed range that contains both of its bounds. /// /// Use the closed range operator (`...`) to create a closed range of any type /// that conforms to the `Comparable` protocol. This example creates a /// `ClosedRange<Character>` from "a" up to, and including, "z". /// /// let lowercase = "a"..."z" /// print(lowercase.contains("z")) /// // Prints "true" /// /// - Parameters: /// - minimum: The lower bound for the range. /// - maximum: The upper bound for the range. @_inlineable // FIXME(sil-serialize-all) @_transparent public static func ... (minimum: Self, maximum: Self) -> ClosedRange<Self> { _precondition( minimum <= maximum, "Can't form Range with upperBound < lowerBound") return ClosedRange(uncheckedBounds: (lower: minimum, upper: maximum)) } } extension Strideable where Stride: SignedInteger { /// Returns a countable closed range that contains both of its bounds. /// /// Use the closed range operator (`...`) to create a closed range of any type /// that conforms to the `Strideable` protocol with an associated signed /// integer `Stride` type, such as any of the standard library's integer /// types. This example creates a `CountableClosedRange<Int>` from zero up to, /// and including, nine. /// /// let singleDigits = 0...9 /// print(singleDigits.contains(9)) /// // Prints "true" /// /// You can use sequence or collection methods on the `singleDigits` range. /// /// print(singleDigits.count) /// // Prints "10" /// print(singleDigits.last) /// // Prints "9" /// /// - Parameters: /// - minimum: The lower bound for the range. /// - maximum: The upper bound for the range. @_inlineable // FIXME(sil-serialize-all) @_transparent public static func ... ( minimum: Self, maximum: Self ) -> CountableClosedRange<Self> { // FIXME: swift-3-indexing-model: tests for traps. _precondition( minimum <= maximum, "Can't form Range with upperBound < lowerBound") return CountableClosedRange(uncheckedBounds: (lower: minimum, upper: maximum)) } }
apache-2.0
2b60a3fa8a332a1bb094416b608b1e2c
32.08545
82
0.654125
4.280251
false
false
false
false
FXSolutions/FXDemoXCodeInjectionPlugin
testinjection/Stevia+Constraints.swift
2
2715
// // Stevia+Constraints.swift // LoginNadir // // Created by Sacha Durand Saint Omer on 01/10/15. // Copyright © 2015 Sacha Durand Saint Omer. All rights reserved. // import UIKit // MARK: - Shortcut public extension UIView { public func c(item view1: AnyObject, attribute attr1: NSLayoutAttribute, relatedBy: NSLayoutRelation = .Equal, toItem view2: AnyObject? = nil, attribute attr2: NSLayoutAttribute? = nil, multiplier: CGFloat = 1, constant: CGFloat = 0) -> NSLayoutConstraint { let c = constraint(item: view1, attribute: attr1, relatedBy: relatedBy, toItem: view2, attribute: attr2, multiplier: multiplier, constant: constant) addConstraint(c) return c } } public func constraint(item view1: AnyObject, attribute attr1: NSLayoutAttribute, relatedBy: NSLayoutRelation = .Equal, toItem view2: AnyObject? = nil, attribute attr2: NSLayoutAttribute? = nil, // Not an attribute?? multiplier: CGFloat = 1, constant: CGFloat = 0) -> NSLayoutConstraint { return NSLayoutConstraint(item: view1, attribute: attr1, relatedBy: relatedBy, toItem: view2, attribute: ((attr2 == nil) ? attr1 : attr2! ), multiplier: multiplier, constant: constant) } // MARK: - Position public extension UIView { public func minimumBottomSpace(points:CGFloat) -> UIView { if let spv = superview { let c = constraint(item: self, attribute: .Bottom, relatedBy: .LessThanOrEqual, toItem: spv, attribute: .Bottom, constant: -points) spv.addConstraint(c) } return self } } // MARK: - Layout public extension UIView { public func layout(objects:[AnyObject]) -> [UIView] { return stackV(objects) } } //MARK: - Other public extension UIView { public func followEdges(otherView:UIView) { if let spv = superview { let cs = [ constraint(item: self, attribute: .Top, toItem: otherView), constraint(item: self, attribute: .Right, toItem: otherView), constraint(item: self, attribute: .Bottom, toItem: otherView), constraint(item: self, attribute: .Left, toItem: otherView) ] spv.addConstraints(cs) } } public func heightEqualsWidth() { if let spv = superview { let c = constraint(item: self, attribute: .Height, toItem: self, attribute: .Width) spv.addConstraint(c) } } } public func H(points:CGFloat) -> (v:UIView) -> UIView { return { v in return v.height(points) } } public func margin(x:CGFloat) -> CGFloat { return x }
mit
0d4cf0fb5d6bfd3f35eff91b8d3aba85
27.28125
192
0.622329
4.234009
false
false
false
false
Ehrippura/firefox-ios
StorageTests/TestBrowserDB.swift
2
4043
/* 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 @testable import Storage import XCGLogger import XCTest private let log = XCGLogger.default class TestBrowserDB: XCTestCase { let files = MockFiles() fileprivate func rm(_ path: String) { do { try files.remove(path) } catch { } } override func setUp() { super.setUp() rm("foo.db") rm("foo.db-shm") rm("foo.db-wal") rm("foo.db.bak.1") rm("foo.db.bak.1-shm") rm("foo.db.bak.1-wal") } class MockFailingSchema: Schema { var name: String { return "FAILURE" } var version: Int { return BrowserSchema.DefaultVersion + 1 } func drop(_ db: SQLiteDBConnection) -> Bool { return true } func create(_ db: SQLiteDBConnection) -> Bool { return false } func update(_ db: SQLiteDBConnection, from: Int) -> Bool { return false } } fileprivate class MockListener { var notification: Notification? @objc func onDatabaseWasRecreated(_ notification: Notification) { self.notification = notification } } func testMovesDB() { var db = BrowserDB(filename: "foo.db", schema: BrowserSchema(), files: self.files) db.run("CREATE TABLE foo (bar TEXT)").succeeded() // Just so we have writes in the WAL. XCTAssertTrue(files.exists("foo.db")) XCTAssertTrue(files.exists("foo.db-shm")) XCTAssertTrue(files.exists("foo.db-wal")) // Grab a pointer to the -shm so we can compare later. let shmAAttributes = try! files.attributesForFileAt(relativePath: "foo.db-shm") let creationA = shmAAttributes[FileAttributeKey.creationDate] as! Date let inodeA = (shmAAttributes[FileAttributeKey.systemFileNumber] as! NSNumber).uintValue XCTAssertFalse(files.exists("foo.db.bak.1")) XCTAssertFalse(files.exists("foo.db.bak.1-shm")) XCTAssertFalse(files.exists("foo.db.bak.1-wal")) let center = NotificationCenter.default let listener = MockListener() center.addObserver(listener, selector: #selector(MockListener.onDatabaseWasRecreated(_:)), name: NotificationDatabaseWasRecreated, object: nil) defer { center.removeObserver(listener) } // It'll still fail, but it moved our old DB. // Our current observation is that closing the DB deletes the .shm file and also // checkpoints the WAL. db.forceClose() db = BrowserDB(filename: "foo.db", schema: MockFailingSchema(), files: self.files) db.run("CREATE TABLE foo (bar TEXT)").failed() // This won't actually write since we'll get a failed connection db = BrowserDB(filename: "foo.db", schema: BrowserSchema(), files: self.files) db.run("CREATE TABLE foo (bar TEXT)").succeeded() // Just so we have writes in the WAL. XCTAssertTrue(files.exists("foo.db")) XCTAssertTrue(files.exists("foo.db-shm")) XCTAssertTrue(files.exists("foo.db-wal")) // But now it's been reopened, it's not the same -shm! let shmBAttributes = try! files.attributesForFileAt(relativePath: "foo.db-shm") let creationB = shmBAttributes[FileAttributeKey.creationDate] as! Date let inodeB = (shmBAttributes[FileAttributeKey.systemFileNumber] as! NSNumber).uintValue XCTAssertTrue(creationA.compare(creationB) != ComparisonResult.orderedDescending) XCTAssertNotEqual(inodeA, inodeB) XCTAssertTrue(files.exists("foo.db.bak.1")) XCTAssertFalse(files.exists("foo.db.bak.1-shm")) XCTAssertFalse(files.exists("foo.db.bak.1-wal")) // The right notification was issued. XCTAssertEqual("foo.db", (listener.notification?.object as? String)) } }
mpl-2.0
ade56a3a8c13bdf3c9046466c556430c
37.141509
151
0.643581
4.264768
false
false
false
false
alejandrogarin/ADGCloudKit
Pod/Classes/CloudSubscription.swift
1
3272
// // CloudSubscription.swift // ADGCloudKit // // Created by Alejandro Diego Garin // The MIT License (MIT) // // Copyright (c) 2015 Alejandro Garin @alejandrogarin // // 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 CloudKit public class CloudSubscription { private let database: CKDatabase init(usingDatabase database:CKDatabase) { self.database = database } public func createSubscriptionWithID(subscriptionID: String, entityName: String, predicate: NSPredicate?, completionHandler: (subscription: CKSubscription?, error: NSError?) -> Void) { let notificationInfo = CKNotificationInfo() notificationInfo.alertBody = "" self.createSubscriptionWithID(subscriptionID, notificationInfo: notificationInfo, entityName: entityName, predicate: predicate, completionHandler: completionHandler) } public func createSubscriptionWithID(subscriptionID: String, notificationInfo: CKNotificationInfo, entityName: String, var predicate: NSPredicate?, completionHandler: (subscription: CKSubscription?, error: NSError?) -> Void) { if (predicate == nil) { predicate = NSPredicate(value: true) } let options:CKSubscriptionOptions = [CKSubscriptionOptions.FiresOnRecordCreation, CKSubscriptionOptions.FiresOnRecordDeletion, CKSubscriptionOptions.FiresOnRecordUpdate] let subscription = CKSubscription(recordType: entityName, predicate: predicate!, subscriptionID: subscriptionID, options: options) subscription.notificationInfo = notificationInfo self.database.saveSubscription(subscription) { (subscription, error) -> Void in dispatch_async(dispatch_get_main_queue()) { completionHandler(subscription: subscription, error: error) } } } public func deleteSubscriptionWithID(subscriptionID: String, completionHandler: (result: String?, error: NSError?) -> Void) { self.database.deleteSubscriptionWithID(subscriptionID) { (subscription, error) -> Void in dispatch_async(dispatch_get_main_queue()) { completionHandler(result: subscription, error: error) } } } }
mit
581e1257b854b17b0f25943364636101
46.42029
230
0.726467
5.041602
false
false
false
false
SomeHero/Twurl-iOS
Twurl-iOS/AppDelegate.swift
1
6725
// // AppDelegate.swift // Twurl-iOS // // Created by James Rhodes on 6/6/15. // Copyright (c) 2015 James Rhodes. All rights reserved. // import UIKit import CoreData import Fabric import Crashlytics @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var categoryName: String? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { categoryName = "All Articles" UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent UIBarButtonItem.appearance().tintColor = UIColor.whiteColor() Fabric.with([Crashlytics()]) // GAI.sharedInstance().trackUncaughtExceptions = true // GAI.sharedInstance().dispatchInterval = 20 // GAI.sharedInstance().logger.logLevel = GAILogLevel.Verbose // GAI.sharedInstance().trackerWithTrackingId("UA-65265435-1") // GAI.sharedInstance().defaultTracker.allowIDFACollection = true // return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "net.twurl.Twurl_iOS" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as! NSURL }() 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("Twurl_iOS", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("Twurl_iOS.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { coordinator = nil // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges && !moc.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } }
mit
68a5de4220cc8e099ef888a902a69575
52.373016
290
0.710037
5.67032
false
false
false
false
ahoppen/swift
stdlib/private/OSLog/OSLogStringTypes.swift
2
7017
//===----------------- OSLogStringTypes.swift -----------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // This file defines extensions for interpolating strings into an OSLogMessage. // It defines `appendInterpolation` function for String type. It also defines // extensions for serializing strings into the argument buffer passed to // os_log ABIs. Note that os_log requires passing a stable pointer to an // interpolated string. // // The `appendInterpolation` function defined in this file accept privacy and // alignment options along with the interpolated expression as shown below: // // 1. "\(x, privacy: .private, align: .right\)" // 2. "\(x, align: .right(columns: 10)\)" extension OSLogInterpolation { /// Defines interpolation for expressions of type String. /// /// Do not call this function directly. It will be called automatically when interpolating /// a value of type `String` in the string interpolations passed to the log APIs. /// /// - Parameters: /// - argumentString: The interpolated expression of type String, which is autoclosured. /// - align: Left or right alignment with the minimum number of columns as /// defined by the type `OSLogStringAlignment`. /// - privacy: A privacy qualifier which is either private or public. /// It is auto-inferred by default. @_semantics("constant_evaluable") @inlinable @_optimize(none) @_semantics("oslog.requires_constant_arguments") public mutating func appendInterpolation( _ argumentString: @autoclosure @escaping () -> String, align: OSLogStringAlignment = .none, privacy: OSLogPrivacy = .auto ) { guard argumentCount < maxOSLogArgumentCount else { return } formatString += getStringFormatSpecifier(align, privacy) // If minimum column width is specified, append this value first. Note that the // format specifier would use a '*' for width e.g. %*s. if let minColumns = align.minimumColumnWidth { appendAlignmentArgument(minColumns) } // If the privacy has a mask, append the mask argument, which is a constant payload. // Note that this should come after the width but before the precision. if privacy.hasMask { appendMaskArgument(privacy) } // Append the string argument. addStringHeaders(privacy) arguments.append(argumentString) argumentCount += 1 stringArgumentCount += 1 } /// Update preamble and append argument headers based on the parameters of /// the interpolation. @_semantics("constant_evaluable") @inlinable @_optimize(none) internal mutating func addStringHeaders(_ privacy: OSLogPrivacy) { // Append argument header. let header = getArgumentHeader(privacy: privacy, type: .string) arguments.append(header) // Append number of bytes needed to serialize the argument. let byteCount = pointerSizeInBytes() arguments.append(UInt8(byteCount)) // Increment total byte size by the number of bytes needed for this // argument, which is the sum of the byte size of the argument and // two bytes needed for the headers. totalBytesForSerializingArguments += byteCount + 2 preamble = getUpdatedPreamble(privacy: privacy, isScalar: false) } /// Construct an os_log format specifier from the given parameters. /// This function must be constant evaluable and all its arguments /// must be known at compile time. @inlinable @_semantics("constant_evaluable") @_effects(readonly) @_optimize(none) internal func getStringFormatSpecifier( _ align: OSLogStringAlignment, _ privacy: OSLogPrivacy ) -> String { var specifier = "%" if let privacySpecifier = privacy.privacySpecifier { specifier += "{" specifier += privacySpecifier specifier += "}" } if case .start = align.anchor { specifier += "-" } if let _ = align.minimumColumnWidth { specifier += "*" } specifier += "s" return specifier } } extension OSLogArguments { /// Append an (autoclosured) interpolated expression of String type, passed to /// `OSLogMessage.appendInterpolation`, to the array of closures tracked /// by this instance. @_semantics("constant_evaluable") @inlinable @_optimize(none) internal mutating func append(_ value: @escaping () -> String) { argumentClosures.append({ (position, _, stringArgumentOwners) in serialize( value(), at: &position, storingStringOwnersIn: &stringArgumentOwners) }) } } /// Return the byte size of a pointer as strings are passed to the C os_log ABIs by /// a stable pointer to its UTF8 bytes. Since pointers do not have a public /// bitWidth property, and since MemoryLayout is not supported by the constant /// evaluator, this function returns the byte size of Int, which must equal the /// word length of the target architecture and hence the pointer size. /// This function must be constant evaluable. Note that it is marked transparent /// instead of @inline(__always) as it is used in optimize(none) functions. @_transparent @_alwaysEmitIntoClient internal func pointerSizeInBytes() -> Int { return Int.bitWidth &>> logBitsPerByte } /// Serialize a stable pointer to the string `stringValue` at the buffer location /// pointed to by `bufferPosition`. @_alwaysEmitIntoClient @inline(__always) internal func serialize( _ stringValue: String, at bufferPosition: inout UnsafeMutablePointer<UInt8>, storingStringOwnersIn stringArgumentOwners: inout ObjectStorage<Any> ) { let stringPointer = getNullTerminatedUTF8Pointer( stringValue, storingStringOwnersIn: &stringArgumentOwners) let byteCount = pointerSizeInBytes() let dest = UnsafeMutableRawBufferPointer(start: bufferPosition, count: byteCount) withUnsafeBytes(of: stringPointer) { dest.copyMemory(from: $0) } bufferPosition += byteCount } /// Return a pointer that points to a contiguous sequence of null-terminated, /// UTF8 characters. If necessary, extends the lifetime of `stringValue` by /// using `stringArgumentOwners`. @_alwaysEmitIntoClient @inline(never) internal func getNullTerminatedUTF8Pointer( _ stringValue: String, storingStringOwnersIn stringArgumentOwners: inout ObjectStorage<Any> ) -> UnsafeRawPointer { let (optStorage, bytePointer, _, _, _): (AnyObject?, UnsafeRawPointer, Int, Bool, Bool) = stringValue._deconstructUTF8(scratch: nil) if let storage = optStorage { initializeAndAdvance(&stringArgumentOwners, to: storage) } else { initializeAndAdvance(&stringArgumentOwners, to: stringValue._guts) } return bytePointer }
apache-2.0
6ce507bc3530753853fbe804231f7188
36.126984
92
0.70714
4.592277
false
false
false
false
natecook1000/swift
stdlib/public/core/UnsafeBitMap.swift
1
2578
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A wrapper around a bitmap storage with room for at least `bitCount` bits. @_fixed_layout @usableFromInline // @testable internal struct _UnsafeBitMap { @usableFromInline internal let values: UnsafeMutablePointer<UInt> @usableFromInline internal let bitCount: Int @inlinable @inline(__always) internal static func wordIndex(_ i: Int) -> Int { // Note: We perform the operation on UInts to get faster unsigned math // (shifts). return Int(bitPattern: UInt(bitPattern: i) / UInt(UInt.bitWidth)) } @inlinable @inline(__always) internal static func bitIndex(_ i: Int) -> UInt { // Note: We perform the operation on UInts to get faster unsigned math // (shifts). return UInt(bitPattern: i) % UInt(UInt.bitWidth) } @inlinable @inline(__always) internal static func sizeInWords(forSizeInBits bitCount: Int) -> Int { return (bitCount + Int.bitWidth - 1) / Int.bitWidth } @inlinable @inline(__always) internal init(storage: UnsafeMutablePointer<UInt>, bitCount: Int) { self.bitCount = bitCount self.values = storage } @inlinable internal var numberOfWords: Int { @inline(__always) get { return _UnsafeBitMap.sizeInWords(forSizeInBits: bitCount) } } @inlinable @inline(__always) internal func initializeToZero() { values.initialize(repeating: 0, count: numberOfWords) } @inlinable internal subscript(i: Int) -> Bool { @inline(__always) get { _sanityCheck(i < Int(bitCount) && i >= 0, "index out of bounds") let word = values[_UnsafeBitMap.wordIndex(i)] let bit = word & (1 << _UnsafeBitMap.bitIndex(i)) return bit != 0 } @inline(__always) nonmutating set { _sanityCheck(i < Int(bitCount) && i >= 0, "index out of bounds") let wordIdx = _UnsafeBitMap.wordIndex(i) let bitMask = (1 as UInt) &<< _UnsafeBitMap.bitIndex(i) if newValue { values[wordIdx] = values[wordIdx] | bitMask } else { values[wordIdx] = values[wordIdx] & ~bitMask } } } }
apache-2.0
0773ef06752e015d74005c7d774aed8f
28.632184
80
0.6218
4.22623
false
false
false
false
tomabuct/TAStackView
TAStackView/StackViewUtils.swift
1
2042
// // StackViewUtils.swift // TAStackView // // Created by Tom Abraham on 8/10/14. // Copyright (c) 2014 Tom Abraham. All rights reserved. // import UIKit // MARK: Public public enum StackViewVisibilityPriority : Float { case MustHold = 1000 case NotVisible = 0 } public enum TAUserInterfaceLayoutOrientation { case Horizontal case Vertical func toCharacter() -> Character { return self == .Horizontal ? "H" : "V" } func other() -> TAUserInterfaceLayoutOrientation { return self == .Horizontal ? .Vertical : .Horizontal; } func toAxis() -> UILayoutConstraintAxis { return self == .Horizontal ? .Horizontal : .Vertical; } } public enum StackViewGravityArea: Int { case Top case Leading case Center case Bottom case Trailing } public let TAStackViewSpacingUseDefault = FLT_MAX // MARK: Internal let LayoutPriorityDefaultLow : UILayoutPriority = 250 let LayoutPriorityDefaultHigh : UILayoutPriority = 750 let LayoutPriorityDefaultRequired : UILayoutPriority = 1000 let DefaultSpacing : Float = 8.0 let DefaultAlignment : NSLayoutAttribute = .CenterY let DefaultOrientation : TAUserInterfaceLayoutOrientation = .Horizontal let DefaultClippingResistancePriority : UILayoutPriority = LayoutPriorityDefaultRequired let DefaultHuggingPriority : UILayoutPriority = LayoutPriorityDefaultLow let EqualSpacingPriority : UILayoutPriority = LayoutPriorityDefaultLow let CenterGravityAreaCenteringPriority : UILayoutPriority = DefaultHuggingPriority extension NSLayoutConstraint { class func constraintsWithVisualFormats( vfls : [String], options : NSLayoutFormatOptions, metrics : Dictionary<String, Float>, views : Dictionary<String, UIView> ) -> [NSLayoutConstraint] { let views = views._bridgeToObjectiveC() let metrics = metrics._bridgeToObjectiveC() var cs : [NSLayoutConstraint] = [] for vfl in vfls { cs += constraintsWithVisualFormat(vfl, options: options, metrics: metrics, views: views) as [NSLayoutConstraint] } return cs } }
mit
ce2290c3389cf88f314e46802f1fd810
26.226667
118
0.746817
4.705069
false
false
false
false
2345Team/Swifter-Tips
8.操作符/Operator.playground/Contents.swift
1
2224
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" // 比如我们需要一个表示二位向量的数据结构 struct Vector2D { var x = 0.0 var y = 0.0 } // 一个很简单的需求是两个Vector2D相加: let v1 = Vector2D(x: 2.0, y: 3.0) let v2 = Vector2D(x: 1.0, y: 4.0) let v3 = Vector2D(x: v1.x + v2.x, y: v1.y + v2.y) print(v3) // 如果只坐一次的话似乎还好,但是一般情况我们会进行很多这种操作。 func -(left:Vector2D,right:Vector2D) -> Vector2D { return Vector2D(x: left.x - right.x, y: left.y - right.y) } let v4 = v1 - v2 print(v4) // 如果我们想定义一个全新的运算符的话,要做的事情会多一件。比如点积运算就是一个在适量运算中很常用的运算符,他表示两个向量对应坐标的乘积的和。根据定义,以及参考重载运算符的方法,我们选取 +* 来表示这个运算,不难写出: func %*(left:Vector2D,right:Vector2D) -> Double { return left.x * right.x + left.y * right.y } // 因为我们没有对这个操作符进行声明。之前可以直接重载像 +,-,*这样的操作符,是因为Swift中已经有定义了,如果我们要新加操作符的话,需要先对其进行声明,告诉编译器这个符号其实是一个操作符。 infix operator %* { associativity none precedence 160 } // infix // 表示要定义的是一个中位操作符,即前后都是输入;其他的修饰子还包括prefix和postfix // associativity // 定义了结合律,即如果多个同类的操作符顺序出现的计算顺序。比如常见的加法和减法都是left,就是说多个加法同时出现时按照从左往右的顺序计算(因为加法满足交换律,所以这个顺序无所谓,但是减法的话计算顺序就很重要了)点乘的结果是一个Double,不再会和其他点乘结合使用,所以这里写成none // precedence // 运算的优先级,越高的话越优先进行运算。Swift中乘法和除法的优先级是150.加法和减法是140,这里我们定义点积优先级160,就是说应该早于普通的乘除进行运算 // 点积运算 let result = v1 %* v2 print(result)
mit
b96c9df64ade0463b506b966c35ff32e
19
146
0.73254
2.006369
false
false
false
false
Witcast/witcast-ios
WiTcast/ViewController/Player/PlayerToolbarController.swift
1
3774
/* * Copyright (C) 2015 - 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit import Material class PlayerToolbarController: ToolbarController { fileprivate var downButton: IconButton! fileprivate var bellButton: IconButton! fileprivate var shareButton: IconButton! open override func prepare() { super.prepare() prepareDownButton() prepareShareButton() prepareStatusBar() prepareToolbar() } } extension PlayerToolbarController { fileprivate func prepareDownButton() { downButton = IconButton(image: Icon.cm.arrowDownward, tintColor: .black) downButton.pulseColor = .white } fileprivate func prepareShareButton() { bellButton = IconButton(image: Icon.cm.bell, tintColor: .black) bellButton.pulseColor = .white shareButton = IconButton(image: Icon.cm.share, tintColor: .black) shareButton.pulseColor = .white } fileprivate func prepareStatusBar() { statusBarStyle = .lightContent statusBar.backgroundColor = CustomFunc.UIColorFromRGB(rgbValue: colorMain) } fileprivate func prepareToolbar() { downButton.tag = 0 bellButton.tag = 1 shareButton.tag = 2 toolbar.title = "Track Detail" toolbar.titleLabel.textColor = .black toolbar.titleLabel.textAlignment = .center toolbar.titleLabel.font = UIFont(name: font_header_regular, size: 28); toolbar.depthPreset = .none toolbar.backgroundColor = CustomFunc.UIColorFromRGB(rgbValue: colorMain) toolbar.leftViews = [downButton] // toolbar.rightViews = [bellButton, shareButton] downButton.addTarget(self, action: #selector(buttonAction), for: .touchUpInside) // bellButton.addTarget(self, action: #selector(buttonAction), for: .touchUpInside) // shareButton.addTarget(self, action: #selector(buttonAction), for: .touchUpInside) } func buttonAction(sender: UIButton!) { if sender.tag == 0 { self.dismiss(animated: true, completion: nil) } else if sender.tag == 1 { } else { } } }
apache-2.0
350d31c66c27b806f47f8c6d2201ef5f
37.907216
91
0.695019
4.723404
false
false
false
false
bigL055/SPKit
Sources/UIView/UIView+Frame.swift
1
2668
// // SPKit // // Copyright (c) 2017 linhay - https:// github.com/linhay // // 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 import UIKit // MARK: - 设置ViewFarme相关属性 public extension UIView{ /// view的x public var x: CGFloat{ get{ return frame.origin.x } set{ self.frame.origin.x = newValue } } /// view的y public var y: CGFloat{ get{ return frame.origin.y } set{ self.frame.origin.y = newValue } } public var minX: CGFloat { get{ return self.frame.minX } set{ self.x = newValue } } public var midX: CGFloat { get{ return self.frame.midX } set{ self.x = newValue - self.width * 0.5 } } public var maxX: CGFloat { get{ return self.frame.maxX } set{ self.x = newValue - self.width } } public var minY: CGFloat { get{ return self.frame.minY } set{ self.y = newValue } } public var midY: CGFloat { get{ return self.frame.midY } set{ self.y = newValue - self.height * 0.5 } } public var maxY: CGFloat { get{ return self.frame.maxY } set{ self.y = newValue - self.height } } /// view的宽度 public var width: CGFloat { get{ return self.frame.size.width } set{ self.frame.size.width = newValue } } /// view的高度 public var height: CGFloat { get{ return self.frame.size.height } set{ self.frame.size.height = newValue } } /// view的size public var size: CGSize{ get{ return self.frame.size } set{ self.frame.size = newValue } } /// view的origin public var origin: CGPoint { get{ return self.frame.origin } set{ self.frame.origin = newValue } } }
apache-2.0
6e051a72704622e945662e4b06ffdaef
27.344086
82
0.672989
3.749644
false
false
false
false
PekanMmd/Pokemon-XD-Code
GoDToolOSX/Views/PopUp Buttons/GoDEvolutionConditionPopUpButton.swift
1
1087
// // GoDEvolutionConditionPopUpButton.swift // GoD Tool // // Created by StarsMmd on 09/09/2017. // // import Cocoa var allItems2 = [String]() func allItemsList() -> [String] { if allItems2.isEmpty { allItems2 = XGItems.allItems().map({ (item) -> String in return item.name.string }) } return allItems2 } let levelPopUp = GoDLevelPopUpButton() class GoDEvolutionConditionPopUpButton: GoDPopUpButton { var method = XGEvolutionMethods.none { didSet { self.setUpItems() } } var selectedValue : Int { return self.indexOfSelectedItem } func selectCondition(condition: Int) { self.selectItem(at: condition) } override func setUpItems() { var values = [String]() isEnabled = true switch method.conditionType { case .level: values = levelPopUp.itemTitles case .item: values = XGItems.allItems().map({ $0.name.unformattedString }) case .pokemon: values = XGPokemon.allPokemon().map({ $0.name.unformattedString }) default: values = ["-"] self.isEnabled = false } self.setTitles(values: values) } }
gpl-2.0
2601154be040604539a41ce66ac5889e
14.753623
69
0.674333
3.365325
false
false
false
false
acumenrev/CANNavApp
CANNavApp/CANNavAppTests/MainViewControllerTest.swift
1
4586
// // MainViewControllerTest.swift // CANNavApp // // Created by Tri Vo on 7/17/16. // Copyright © 2016 acumenvn. All rights reserved. // import XCTest import Nimble import GoogleMaps import CoreLocation class MainViewControllerTest: XCTestCase { var mVC : MainViewController? override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. self.mVC = MainViewController(nibName: "MainViewController", bundle: nil) } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. self.mVC = nil super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } func testInit() { expect(self.mVC).notTo(equal(nil)) self.mVC?.loadView() // mLocationManager if CLLocationManager.locationServicesEnabled() == true { expect(self.mVC?.mLocationManager).notTo(equal(nil)) expect(self.mVC?.mLocationManager?.desiredAccuracy == kCLLocationAccuracyKilometer).to(equal(true)) expect(self.mVC?.mLocationManager?.delegate != nil).to(equal(true)) } // mCurrentUserLocation expect(self.mVC?.mCurrentUserLocation).notTo(equal(nil)) // bDidGetUserLocationFirstTime expect(self.mVC?.bDidGetUserLocationFirstTime).to(equal(false)) // mMarkerFrom expect(self.mVC?.mMarkerFrom).to(equal(nil)) // mMarkerTo expect(self.mVC?.mMarkerTo).to(equal(nil)) // mMarkerUserLocation expect(self.mVC?.mMarkerUserLocation).to(equal(nil)) // mLocationFrom expect(self.mVC?.mLocationFrom).to(equal(nil)) // mLocationTo expect(self.mVC?.mLocationTo).to(equal(nil)) // mSearchViewControllerFrom expect(self.mVC?.mSearchViewControllerFrom).to(equal(nil)) // mSearchViewControllerTo expect(self.mVC?.mSearchViewControllerTo).to(equal(nil)) // mCurrentMovingMode expect(self.mVC?.mCurrentMovingMode.rawValue).to(equal("driving")) // mCurrentDirection expect(self.mVC?.mCurrentDirection == nil).to(equal(true)) // mDirectionDictionary expect(self.mVC?.mDirectionDictionary).to(equal(nil)) // mCurrentPolyline expect(self.mVC?.mCurrentPolyline == nil).to(equal(true)) // mSelectedColor expect(self.mVC?.mSelectedColor).notTo(equal(nil)) // mMapView expect(self.mVC?.mMapView).notTo(equal(nil)) // mViewFrom expect(self.mVC?.mViewFrom).notTo(equal(nil)) // mViewTo expect(self.mVC?.mViewTo).notTo(equal(nil)) // mTxtFrom expect(self.mVC?.mTxtFrom).notTo(equal(nil)) // mTxtTo expect(self.mVC?.mTxtTo).notTo(equal(nil)) // mViewCurrentLocation expect(self.mVC?.mViewCurrentLocation).notTo(equal(nil)) // mViewMovingModeCar expect(self.mVC?.mViewMovingModeCar).notTo(equal(nil)) // mViewMovingModeWalking expect(self.mVC?.mViewMovingModeWalking).notTo(equal(nil)) // mLblDistance expect(self.mVC?.mLblDistance).notTo(equal(nil)) // mLblDuration expect(self.mVC?.mLblDuration).notTo(equal(nil)) // mViewDistanceAndDuration expect(self.mVC?.mViewDistanceAndDuration).notTo(equal(nil)) // mViewVehicleBottomConstraint expect(self.mVC?.mViewVehicleBottomConstraint).notTo(equal(nil)) } func testConformingToSearchViewControllerDeleagate() { expect(self.mVC).notTo(equal(nil)) expect(self.mVC?.conformsToProtocol(SearchViewControllerDelegate)).to(equal(true)) } func testConformingToLocationManagerDelegate() { expect(self.mVC).notTo(equal(nil)) expect(self.mVC?.conformsToProtocol(CLLocationManagerDelegate)).to(equal(true)) } }
apache-2.0
66aa417e904f7789d8c980b9a4187c78
30.840278
111
0.61374
4.309211
false
true
false
false
jneyer/SimpleRestClient
SimpleRestClient/Classes/SimpleRestClient.swift
1
3832
// // SimpleRestClient.swift // Pods // // Created by John Neyer on 8/24/17. // // import Foundation import PromiseKit import Alamofire import ObjectMapper class SimpleRestClient : NSObject { private var url : String; private var apiKey : String?; private var headers : HTTPHeaders?; private init(url: String, apiKey: String?) { self.url = url; HTTPRouter.baseURLString = url if (apiKey != nil) { self.apiKey = apiKey; headers = [ "x-api-key": apiKey!, "Accept": "application/json" ] } } public static func defaultClient(url: String, apiKey: String?) -> SimpleRestClient { return SimpleRestClient(url: url, apiKey: apiKey); } //HTTP operations public func get<T : Mappable>(route : HTTPRouter, parameters : [String : AnyObject]? = nil, pathParams : String? = nil) -> Promise<T?> { return self.httpRequest(method: .get, route: route, parameters : parameters, pathParams: pathParams); } public func post<T : Mappable>(route : HTTPRouter, parameters : [String : AnyObject]? = nil, pathParams : String? = nil) -> Promise<T?> { return self.httpRequest(method: .post, route: route, parameters: parameters) } public func put<T : Mappable>(route : HTTPRouter, parameters : [String : AnyObject]? = nil, pathParams : String? = nil) -> Promise<T?> { return self.httpRequest(method: .put, route: route, parameters: parameters) } public func delete<T : Mappable>(route : HTTPRouter, parameters : [String : AnyObject]? = nil, pathParams : String? = nil) -> Promise<T?> { return self.httpRequest(method: .delete, route: route, parameters: parameters) } private func httpRequest<T : Mappable>(method : HTTPMethod, route : HTTPRouter, parameters : [String : AnyObject]? = nil, pathParams: String? = nil) -> Promise<T?> { return Promise<T?> { (fulfill, reject) -> Void in func parsingError(erroString : String) -> NSError { return NSError(domain: "org.septa.SimpleRestClient", code: -100, userInfo: nil) } var route = route.URLString; if let pparams = pathParams { route = route + "/" + pparams; } request(route, method: method, parameters: parameters, headers: headers).responseJSON { (response) -> Void in // debugPrint(response.result.value ?? "Warning: empty response") // dump the response if let error = response.result.error { reject(error) //network error } else { if let apiResponse = Mapper<T>().map(JSONObject: response.result.value) { let status = apiResponse as? RestResponse if (status != nil && status!.success) { fulfill(apiResponse) } else { if let logicalerror = status?.error { reject(ErrorResult(errorFromAPI: logicalerror)) } else { reject(ErrorResult(errorFromAPI: nil)) } } } else { let err = NSError(domain: "org.septa.SimpleRestClient", code: -101, userInfo: nil) reject(err) } } } } } }
mit
eb8f531a25ed74796e9ce467c846ac7a
35.150943
169
0.504697
5.048748
false
false
false
false
QuStudio/Vocabulaire
Sources/Vocabulaire/User.swift
1
943
// // User.swift // Vocabulaire // // Created by Oleg Dreyman on 23.03.16. // Copyright © 2016 Oleg Dreyman. All rights reserved. // /// Basic entity which represents a user of Qubular. public struct User { /// User identifier. public let id: Int /// Username. public let username: String /// Determines user privileges and access level. public let status: Status public init(id: Int, username: String, status: Status) { self.id = id self.username = username self.status = status } #if swift(>=3.0) public enum Status { case regular case boardMember } #else public enum Status { case Regular case BoardMember } #endif } extension User: Equatable { } public func == (left: User, right: User) -> Bool { return left.id == right.id && left.username == right.username && left.status == right.status }
mit
0b96a0c332d4ee5dc5bc4f9183a420dc
20.930233
96
0.602972
4.025641
false
false
false
false
yrchen/edx-app-ios
Source/CourseOutline.swift
1
7278
// // CourseOutline.swift // edX // // Created by Akiva Leffert on 4/29/15. // Copyright (c) 2015 edX. All rights reserved. // import Foundation public typealias CourseBlockID = String public struct CourseOutline { enum Fields : String, RawValueExtractable { case Root = "root" case Blocks = "blocks" case BlockCounts = "block_counts" case BlockType = "type" case Descendants = "descendants" case DisplayName = "display_name" case Format = "format" case Graded = "graded" case LMSWebURL = "lms_web_url" case StudentViewMultiDevice = "student_view_multi_device" case StudentViewURL = "student_view_url" case Summary = "summary" } public let root : CourseBlockID public let blocks : [CourseBlockID:CourseBlock] private let parents : [CourseBlockID:CourseBlockID] public init(root : CourseBlockID, blocks : [CourseBlockID:CourseBlock]) { self.root = root self.blocks = blocks var parents : [CourseBlockID:CourseBlockID] = [:] for (blockID, block) in blocks { for child in block.children { parents[child] = blockID } } self.parents = parents } public init?(json : JSON) { if let root = json[Fields.Root].string, blocks = json[Fields.Blocks].dictionaryObject { var validBlocks : [CourseBlockID:CourseBlock] = [:] for (blockID, blockBody) in blocks { let body = JSON(blockBody) let webURL = NSURL(string: body[Fields.LMSWebURL].stringValue) let children = body[Fields.Descendants].arrayObject as? [String] ?? [] let name = body[Fields.DisplayName].string let blockURL = body[Fields.StudentViewURL].string.flatMap { NSURL(string:$0) } let format = body[Fields.Format].string let typeName = body[Fields.BlockType].string ?? "" let multiDevice = body[Fields.StudentViewMultiDevice].bool ?? false let blockCounts : [String:Int] = (body[Fields.BlockCounts].object as? NSDictionary)?.mapValues { $0 as? Int ?? 0 } ?? [:] let graded = body[Fields.Graded].bool ?? false let type : CourseBlockType if let category = CourseBlock.Category(rawValue: typeName) { switch category { case CourseBlock.Category.Course: type = .Course case CourseBlock.Category.Chapter: type = .Chapter case CourseBlock.Category.Section: type = .Section case CourseBlock.Category.Unit: type = .Unit case CourseBlock.Category.HTML: type = .HTML case CourseBlock.Category.Problem: type = .Problem case CourseBlock.Category.Video : let bodyData = (body[Fields.StudentViewMultiDevice].object as? NSDictionary).map { [Fields.Summary.rawValue : $0 ] } let summary = OEXVideoSummary(dictionary: bodyData ?? [:], videoID: blockID, name : name ?? Strings.untitled) type = .Video(summary) } } else { type = .Unknown(typeName) } validBlocks[blockID] = CourseBlock( type: type, children: children, blockID: blockID, name: name, blockCounts : blockCounts, blockURL : blockURL, webURL: webURL, format : format, multiDevice : multiDevice, graded : graded ) } self = CourseOutline(root: root, blocks: validBlocks) } else { return nil } } func parentOfBlockWithID(blockID : CourseBlockID) -> CourseBlockID? { return self.parents[blockID] } } public enum CourseBlockType { case Unknown(String) case Course case Chapter case Section case Unit case Video(OEXVideoSummary) case Problem case HTML public var asVideo : OEXVideoSummary? { switch self { case let .Video(summary): return summary default: return nil } } } public class CourseBlock { /// Simple list of known block categories strings public enum Category : String { case Chapter = "chapter" case Course = "course" case HTML = "html" case Problem = "problem" case Section = "sequential" case Unit = "vertical" case Video = "video" } public let type : CourseBlockType public let blockID : CourseBlockID /// Children in the navigation hierarchy. /// Note that this may be different than the block's list of children, server side /// Since we flatten out the hierarchy for display public let children : [CourseBlockID] /// Title of block. Keep this private so people don't use it as the displayName by accident private let name : String? /// Actual title of the block. Not meant to be user facing - see displayName public var internalName : String? { return name } /// User visible name of the block. public var displayName : String { guard let name = name where !name.isEmpty else { return Strings.untitled } return name } /// TODO: Match final API name /// The type of graded component public let format : String? /// Mapping between block types and number of blocks of that type in this block's /// descendants (recursively) for example ["video" : 3] public let blockCounts : [String:Int] /// Just the block content itself as a web page. /// Suitable for embedding in a web view. public let blockURL : NSURL? /// If this is web content, can we actually display it. public let multiDevice : Bool /// A full web page for the block. /// Suitable for opening in a web browser. public let webURL : NSURL? /// Whether or not the block is graded. /// TODO: Match final API name public let graded : Bool? public init(type : CourseBlockType, children : [CourseBlockID], blockID : CourseBlockID, name : String?, blockCounts : [String:Int] = [:], blockURL : NSURL? = nil, webURL : NSURL? = nil, format : String? = nil, multiDevice : Bool, graded : Bool = false) { self.type = type self.children = children self.name = name self.blockCounts = blockCounts self.blockID = blockID self.blockURL = blockURL self.webURL = webURL self.graded = graded self.format = format self.multiDevice = multiDevice } }
apache-2.0
752d46068880518f4baf2ee610aa0240
32.694444
140
0.552487
5.10021
false
false
false
false
netguru/inbbbox-ios
Inbbbox/Source Files/Views/Controllers View/LoginView.swift
1
6046
// // LoginView.swift // Inbbbox // // Created by Patryk Kaczmarek on 28/12/15. // Copyright © 2015 Netguru Sp. z o.o. All rights reserved. // import UIKit import PureLayout class LoginView: UIView { fileprivate let cornerRadius = CGFloat(28) let loginButton = UIButton(type: .system) let loginAsGuestButton = UIButton(type: .system) let shotsView = AutoScrollableShotsView(numberOfColumns: 4) let dribbbleLogoImageView = UIImageView(image: UIImage(named: "ic-ball")) let orLabel = ORLoginLabel() let copyrightlabel = UILabel() let loadingLabel = UILabel() let logoImageView = UIImageView(image: UIImage(named: "logo-inbbbox")) let pinkOverlayView = UIImageView(image: UIImage(named: "bg-intro-gradient")) let sloganLabel = UILabel() let defaultWhiteColor = UIColor.RGBA(249, 212, 226, 1) var isAnimating = false override init(frame: CGRect) { super.init(frame: frame) addSubview(shotsView) addSubview(pinkOverlayView) addSubview(logoImageView) addSubview(orLabel) addSubview(dribbbleLogoImageView) loginButton.setTitle(Localized("LoginView.LoginButtonTitle", comment: "Title of log in button"), for: .normal) loginButton.backgroundColor = UIColor.white loginButton.layer.cornerRadius = cornerRadius loginButton.setTitleColor(UIColor.pinkColor(), for: .normal) loginButton.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: UIFontWeightMedium) loginButton.titleLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping loginButton.titleLabel?.textAlignment = NSTextAlignment.center loginButton.titleEdgeInsets.left = 2.5 * cornerRadius loginButton.titleEdgeInsets.right = cornerRadius insertSubview(loginButton, belowSubview: dribbbleLogoImageView) loginAsGuestButton.setTitle(Localized("LoginView.GuestButtonTitle", comment: "Title of guest button"), for: .normal) loginAsGuestButton.backgroundColor = UIColor.clear loginAsGuestButton.layer.cornerRadius = cornerRadius loginAsGuestButton.layer.borderWidth = 1 loginAsGuestButton.layer.borderColor = UIColor.white.cgColor loginAsGuestButton.setTitleColor(UIColor.white, for: .normal) loginButton.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: UIFontWeightMedium) addSubview(loginAsGuestButton) sloganLabel.text = Localized("LoginView.Slogan", comment: "Slogan") sloganLabel.textAlignment = .center sloganLabel.textColor = defaultWhiteColor sloganLabel.font = UIFont.systemFont(ofSize: 25, weight: UIFontWeightLight) addSubview(sloganLabel) loadingLabel.text = Localized("LoginView.Loading", comment: "") loadingLabel.textAlignment = .center loadingLabel.textColor = defaultWhiteColor loadingLabel.font = UIFont.systemFont(ofSize: 12, weight: UIFontWeightRegular) addSubview(loadingLabel) copyrightlabel.text = Localized("LoginView.Copyright", comment:"Describes copyright holder") copyrightlabel.textAlignment = .center copyrightlabel.textColor = defaultWhiteColor copyrightlabel.font = UIFont.systemFont(ofSize: 12, weight: UIFontWeightMedium) copyrightlabel.adjustsFontSizeToFitWidth = true addSubview(copyrightlabel) } @available(*, unavailable, message: "Use init(frame:) instead") required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() /** Sorry for using rects here, but autolayout is going crazy with animations provided by our designer... If you want to be devoured by UIKit mutable state, please refactor this to autolayout. */ if !isAnimating { let inset = CGFloat(30) let height = 2 * cornerRadius loginButton.frame = CGRect(x: inset, y: frame.maxY - height - 132, width: frame.width - 2 * inset, height: height ) let size = dribbbleLogoImageView.image?.size ?? CGSize.zero dribbbleLogoImageView.frame = CGRect(x: loginButton.frame.minX + 30, y: loginButton.frame.midY - size.height * 0.5, width: size.width, height: size.height ) loginAsGuestButton.frame = CGRect(x: inset, y: frame.maxY - 56 - height + 200, width: frame.width - 2 * inset, height: height ) let width = CGFloat(150) orLabel.frame = CGRect(x: frame.midX - width * 0.5, y: loginAsGuestButton.frame.minY - height, width: width, height: 60 ) loadingLabel.frame = CGRect(x: 0, y: frame.maxY - 65, width: frame.width, height: 20 ) let sloganHeight = CGFloat(40) sloganLabel.frame = CGRect(x: 0, y: frame.midY - sloganHeight * 0.5, width: frame.width, height: sloganHeight ) let imageSize = logoImageView.image!.size logoImageView.frame = CGRect(x: frame.midX - imageSize.width * 0.5, y: sloganLabel.frame.minY - 30 - imageSize.height, width: imageSize.width, height: imageSize.height ) shotsView.frame = frame pinkOverlayView.frame = frame let standardSpacing: CGFloat = 20 copyrightlabel.autoPinEdge(toSuperviewEdge: .bottom, withInset: standardSpacing) copyrightlabel.autoPinEdge(toSuperviewEdge: .leading, withInset: standardSpacing) copyrightlabel.autoPinEdge(toSuperviewEdge: .trailing, withInset: standardSpacing) copyrightlabel.autoSetDimension(.height, toSize: 14.5) copyrightlabel.autoAlignAxis(toSuperviewAxis: .vertical) } } }
gpl-3.0
fd938c62576e8ed61700716f1a7962d2
40.40411
110
0.65426
4.875
false
false
false
false
daher-alfawares/Chart
Chart/CompoundBar.swift
1
3530
// // CompoundBar.swift // Chart // // Created by Daher Alfawares on 4/18/16. // Copyright © 2016 Daher Alfawares. All rights reserved. // import UIKit fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } @IBDesignable class CompoundBar : UIView { @IBInspectable var v1 : CGFloat = CGFloat(100) @IBInspectable var C1 : UIColor = UIColor.blue @IBInspectable var v2 : CGFloat = CGFloat(100) @IBInspectable var C2 : UIColor = UIColor.green @IBInspectable var v3 : CGFloat = CGFloat(100) @IBInspectable var C3 : UIColor = UIColor.orange @IBInspectable var v4 : CGFloat = CGFloat(100) @IBInspectable var C4 : UIColor = UIColor.gray @IBInspectable var v5 : CGFloat = CGFloat(100) @IBInspectable var C5 : UIColor = UIColor.magenta @IBInspectable var seperator = CGFloat(2) override func draw(_ rect: CGRect) { super.draw(rect) if (current == nil) { current = [Double(v1),Double(v2),Double(v3),Double(v4),Double(v5)] } let calculator = CompoundBarChartCalculator( Values: current!, Height: Double(rect.size.height), Seperator: Double(seperator) ) let colors = [C1,C2,C3,C4,C5] let x0 = Double(0) let x1 = Double(rect.size.width) for (index,bar) in calculator.bars().enumerated() { let path = UIBezierPath() path.move( to: CGPoint(x: x0, y: bar.start)) path.addLine(to: CGPoint(x: x1, y: bar.start)) path.addLine(to: CGPoint(x: x1, y: bar.end)) path.addLine(to: CGPoint(x: x0, y: bar.end)) colors[index%colors.count].setFill() path.fill() } } // Animations fileprivate var current : [Double]? fileprivate var target : [Double]? fileprivate var displayLink : CADisplayLink! fileprivate var original : [Double]? fileprivate var startTime : TimeInterval = 0 fileprivate var duration : TimeInterval = 2 func setValues(_ values:[Double], animated:Bool){ if animated, let _ = current { original = current! target = values while current?.count < target?.count { current?.append(0) } displayLink = CADisplayLink(target: self, selector: #selector(CompoundBar.animateMe)) displayLink.add(to: RunLoop.main, forMode: RunLoopMode.defaultRunLoopMode) startTime = 0 } else { current = values } setNeedsDisplay() } func animateMe(){ guard startTime > 0 else { startTime = displayLink.timestamp return } let t1 = self.startTime let t2 = displayLink.timestamp let dt = t2 - t1 if dt > duration { displayLink?.invalidate() return } let r = Double( dt / duration ) var c = [Double]() for (i,_) in target!.enumerated() { let Ci = current?[i] ?? 0 let Ti = target![i] let Vi = Ci + r * ( Ti - Ci ) c.append(Vi) } current = c setNeedsDisplay() } }
apache-2.0
6a1c06efc99cf6df47804dde18aeb0b4
26.787402
97
0.534429
4.277576
false
false
false
false
melling/ios_topics
SimpleTableView/SimpleTableView/SimpleTableViewController.swift
1
2122
// // SimpleTableViewController.swift // SimpleTableViewController // // Created by Michael Mellinger on 3/8/16. // import UIKit class SimpleTableViewController: UITableViewController { private let rowData = ["one", "two", "three"] private let cellIdentifier = "Cell" // MARK: - View Management override func viewDidLoad() { super.viewDidLoad() tableView.backgroundColor = UIColor(red: 90/255.0, green: 200.0/255.0, blue: 250.0/255, alpha: 1.0) // Apple Videos tableView.rowHeight = 80 tableView.tableFooterView = UIView() // Remove "empty" table centers in footer self.tableView.register(UITableViewCell.self, forCellReuseIdentifier:cellIdentifier) } } // MARK: - Data source delegate extension SimpleTableViewController { // We can skip overriding this function and it will default to 1 override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return rowData.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) cell.backgroundColor = UIColor(red: 90/255.0, green: 120.0/255.0, blue: 250.0/255, alpha: 1.0) // Configure the cell... cell.textLabel?.text = rowData[indexPath.row] return cell } } // MARK: - Header Cell extension SimpleTableViewController { //: Optional Header title override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "Header" } override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { view.tintColor = .orange } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 60.0 } }
cc0-1.0
7ff8a9f5a45b6e386334239e7d7831d7
28.068493
123
0.663996
4.844749
false
false
false
false
syxc/ZhihuDaily
ZhihuDaily/Classes/Controllers/NewsDetailVC.swift
1
3185
// // NewsDetailVC.swift // ZhihuDaily // // Copyright (c) 2016年 syxc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit import PromiseKit /** 新闻详情 */ class NewsDetailVC: FYWebViewController { var newsID: String? override func viewDidLoad() { super.viewDidLoad() if newsID != nil && newsID?.length > 0 { loadNewsDetail(newsID!) } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } deinit { } /** 获取新闻详情 - parameter id: 新闻ID */ private func loadNewsDetail(id: String) { let client = AppClient.shareClient weak var weakSelf = self firstly { client.fetchNewsDetail(id) }.then { newsItem -> Void in log.info("newsItem=\(newsItem)") if let newsItem: News = newsItem { weakSelf!.renderNewsDetailTemplate(newsItem) } }.always { self.setNetworkActivityIndicatorVisible(false) }.error { error in log.error("error=\(error)") } } private func renderNewsDetailTemplate(newsItem: News) { self.htmlString = loadHTMLByMGTemplateEngine(newsItem) self.loadHTMLString(self.htmlString) } private func loadHTMLByMGTemplateEngine(data: News) -> String { let templatePath = NSBundle.mainBundle().pathForResource("news", ofType: "html") let engine = MGTemplateEngine.init() engine.matcher = ICUTemplateMatcher(templateEngine: engine) engine.setObject(objectOrBlank(data.title), forKey: "title") engine.setObject(objectOrBlank(data.css![0]), forKey: "css") engine.setObject(objectOrBlank(data.share_url), forKey: "share_url") engine.setObject(objectOrBlank(data.image), forKey: "image") engine.setObject(objectOrBlank(data.image_source), forKey: "image_source") engine.setObject(objectOrBlank(data.body), forKey: "content") return engine.processTemplateInFileAtPath(templatePath, withVariables: nil) } }
mit
f69371f863bc2afb8241ea4a04dbfee0
31.234694
84
0.702121
4.217623
false
false
false
false
younata/RSSClient
Tethys/Settings/SettingsSection.swift
1
2689
import UIKit import TethysKit enum SettingsSection: Int, CustomStringConvertible { case account = 0 case refresh = 1 case other = 2 case credits = 3 static func numberOfSettings() -> Int { return 4 } var rawValue: Int { switch self { case .account: return 0 case .refresh: return 1 case .other: return 2 case .credits: return 3 } } var description: String { switch self { case .account: return NSLocalizedString("SettingsViewController_Table_Header_Account", comment: "") case .refresh: return NSLocalizedString("SettingsViewController_Table_Header_Refresh", comment: "") case .other: return NSLocalizedString("SettingsViewController_Table_Header_Other", comment: "") case .credits: return NSLocalizedString("SettingsViewController_Table_Header_Credits", comment: "") } } } enum OtherSection: CustomStringConvertible { case showReadingTimes case exportOPML case appIcon case gitVersion var description: String { switch self { case .showReadingTimes: return NSLocalizedString("SettingsViewController_Other_ShowReadingTimes", comment: "") case .exportOPML: return NSLocalizedString("SettingsViewController_Other_ExportOPML", comment: "") case .appIcon: return NSLocalizedString("SettingsViewController_AlternateIcons_Title", comment: "") case .gitVersion: return NSLocalizedString("SettingsViewController_Credits_Version", comment: "") } } init?(rowIndex: Int, appIconChanger: AppIconChanger) { switch rowIndex { case 0: self = .showReadingTimes case 1: self = .exportOPML case 2: if appIconChanger.supportsAlternateIcons { self = .appIcon } else { self = .gitVersion } case 3: if appIconChanger.supportsAlternateIcons { self = .gitVersion } else { return nil } default: return nil } } func rowIndex(appIconChanger: AppIconChanger) -> Int { switch self { case .showReadingTimes: return 0 case .exportOPML: return 1 case .appIcon: return 2 case .gitVersion: return appIconChanger.supportsAlternateIcons ? 3 : 2 } } static func numberOfOptions(appIconChanger: AppIconChanger) -> Int { guard appIconChanger.supportsAlternateIcons else { return 3 } return 4 } }
mit
402f8614199c8d3f2421936a59304883
28.228261
98
0.599479
5.262231
false
false
false
false
CodeEagle/SSCacheControl
Source/SSCacheControl.swift
1
2886
// // SSCacheControl.swift // SSCacheControl // // Created by LawLincoln on 15/12/22. // Copyright © 2015年 SelfStudio. All rights reserved. // import Foundation import Alamofire public typealias SSCacheControlConfig = (maxAge: NSTimeInterval, ignoreExpires: Bool, requestNewAfterRetrunCache: Bool) private extension String { var date: NSDate! { let fmt = NSDateFormatter() fmt.dateFormat = "EEE, dd MMM yyyy HH:mm:ss z" fmt.locale = NSLocale(localeIdentifier: "en_US_POSIX") fmt.timeZone = NSTimeZone(abbreviation: "GMT") return fmt.dateFromString(self) } } public extension UIView { private struct AssociatedKeys { static var Config = "ss_firstTimeToken" } private var ss_firtime: Bool { get { return (objc_getAssociatedObject(self, &AssociatedKeys.Config) as? Bool) ?? true } set(max) { objc_setAssociatedObject(self, &AssociatedKeys.Config, max, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } public func ss_cacheControlConfig(maxAge: NSTimeInterval) -> SSCacheControlConfig { var permision = false if ss_firtime { ss_firtime = false permision = true } return SSCacheControlConfig(maxAge: maxAge, ignoreExpires: permision, requestNewAfterRetrunCache: permision) } } extension NSURLRequest { private struct AssociatedKeys { static var MaxAge = "MaxAge" } var ll_max_age: NSTimeInterval { get { return (objc_getAssociatedObject(self, &AssociatedKeys.MaxAge) as? NSTimeInterval) ?? 0 } set(max) { objc_setAssociatedObject(self, &AssociatedKeys.MaxAge, max, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /** Save NSHTTPURLResponse - parameter maxAge: NSTimeInterval - parameter resp: NSHTTPURLResponse to store - parameter data: data to store */ func ll_storeResponse(maxAge: NSTimeInterval, resp: NSHTTPURLResponse?, data: NSData?) { if let response = resp, url = response.URL, header = response.allHeaderFields as? [String: String], data = data { if let re = NSHTTPURLResponse(URL: url, statusCode: response.statusCode, HTTPVersion: nil, headerFields: header) { let cachedResponse = NSCachedURLResponse(response: re, data: data, userInfo: nil, storagePolicy: NSURLCacheStoragePolicy.Allowed) NSURLCache.sharedURLCache().storeCachedResponse(cachedResponse, forRequest: self) } } } func ll_lastCachedResponseDataIgnoreExpires(ignoreExpires: Bool = true) -> NSData? { let response = NSURLCache.sharedURLCache().cachedResponseForRequest(self) if ignoreExpires { return response?.data } let now = NSDate() var data: NSData! if let resp = response?.response as? NSHTTPURLResponse { if let dateString = resp.allHeaderFields["Date"] as? String, dateExpires = dateString.date { let expires = dateExpires.dateByAddingTimeInterval(ll_max_age) if now.compare(expires) == .OrderedAscending { data = response?.data } } } return data } }
mit
f2d5d672fc090210c2be84e541f063fd
28.721649
134
0.729795
3.710425
false
true
false
false
calkinssean/TIY-Assignments
Day 10/Calculator-Final/Calculator/ViewController.swift
1
8321
// // ViewController.swift // Calculator // // Created by Sean Calkins on 2/10/16. // Copyright © 2016 Sean Calkins. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var runningTotalLabel: UILabel! var value2: Double = 0 var value1: Double = 0 var runningTotal: Double = 0 var operatorString = "" var isFirstTap = true var hasPerformedCalculation = false var hasTypedNumber = false @IBAction func addButtonTapped(sender: BorderButton) { print("addButtonTapped") if hasPerformedCalculation == true { operatorString = "+" value1 = 0 updateUI() hasPerformedCalculation = false hasTypedNumber = false return } if isFirstTap == true { operatorString = "+" runningTotal = value1 value1 = 0 isFirstTap = false updateUI() hasTypedNumber = false return } else { calculate() operatorString = "+" value1 = 0 updateUI() hasTypedNumber = false return } } @IBAction func piButton(sender: BorderButton) { value1 = 3.1415926536 print(value1, runningTotal) } @IBAction func multiplicationTapped(sender: BorderButton) { if hasPerformedCalculation == true { operatorString = "*" value1 = 0 updateUI() hasPerformedCalculation = false print(value1, runningTotal) hasTypedNumber = false return } if isFirstTap == true { operatorString = "*" runningTotal = value1 value1 = 0 isFirstTap = false updateUI() print(value1, runningTotal) hasTypedNumber = false return } else if hasTypedNumber == true { calculate() operatorString = "*" value1 = 0 updateUI() print(value1, runningTotal) hasTypedNumber = false return } } @IBAction func divisionButton(sender: BorderButton) { if hasPerformedCalculation == true { operatorString = "/" value1 = 0 updateUI() hasPerformedCalculation = false print(value1, runningTotal) hasTypedNumber = false return } if isFirstTap == true { operatorString = "/" runningTotal = value1 value1 = 0 isFirstTap = false updateUI() print(value1, runningTotal) hasTypedNumber = false return } else if hasTypedNumber == true { calculate() operatorString = "/" value1 = 0 updateUI() print(value1, runningTotal) hasTypedNumber = false return } } @IBAction func minusButtonTapped(sender: BorderButton) { print("minusButtonTapped") if hasPerformedCalculation == true { operatorString = "-" value1 = 0 updateUI() hasPerformedCalculation = false hasTypedNumber = false return } if isFirstTap == true { operatorString = "-" runningTotal = value1 value1 = 0 updateUI() isFirstTap = false hasTypedNumber = false return } else { calculate() operatorString = "-" value1 = 0 updateUI() hasTypedNumber = false return } } @IBAction func numberButtons(sender: BorderButton) { value2 = 0 value1 = ((value1 * 10) + Double(sender.tag)) runningTotalLabel.text = "\(value1)" print(value1, runningTotal) hasTypedNumber = true } @IBAction func clearButton(sender: BorderButton) { runningTotal = 0 value1 = 0 value2 = 0 operatorString = "" isFirstTap = true hasPerformedCalculation = false hasTypedNumber = false updateUI() } @IBAction func sqrtButton(sender: BorderButton) { if hasTypedNumber == true { calculate() value1 = 0 operatorString = "sqrt" print(value1, runningTotal) calculate() hasTypedNumber = false updateUI() } } @IBAction func equalsButtonTapped(sender: BorderButton) { calculate() value1 = 0 updateUI() hasPerformedCalculation = true hasTypedNumber = false print(value1, runningTotal) } @IBAction func percentButton(sender: UIButton) { if hasPerformedCalculation == false { runningTotal = value1 / 100 value1 = 0 hasTypedNumber = false print(value1, runningTotal) return } runningTotal = runningTotal / 100 value1 = 0 print(value1, runningTotal) } @IBAction func negativeButton(sender: BorderButton) { operatorString = "(-)" if hasPerformedCalculation == false { runningTotal = value1 * -1 value1 = 0 print(value1, runningTotal) updateUI() hasTypedNumber = false return } else { runningTotal = runningTotal * -1 value1 = 0 updateUI() print(value1, runningTotal) hasTypedNumber = false } } func updateUI() { runningTotalLabel.text = "\(runningTotal)" } func convertStringToDouble(str: String?) -> Double { var returnDouble: Double = 0 if str == nil || str == "" { return returnDouble } returnDouble = Double(str!)! return returnDouble } func calculate () { if operatorString == "+" { runningTotal = runningTotal + value1 return } if operatorString == "(-)" { return } if operatorString == "-" { runningTotal = runningTotal - value1 return } if operatorString == "*" { runningTotal = runningTotal * value1 return } if operatorString == "/" { runningTotal = runningTotal / value1 return } if operatorString == "sqrt" { runningTotal = sqrt(runningTotal) return } if operatorString == "%" { runningTotal = runningTotal / 100 return } if hasPerformedCalculation == false || operatorString == "" { runningTotal = value1 } } }
cc0-1.0
8229b59d7ed25c82e2683ad9f89fb0b3
27.395904
73
0.428365
6.540881
false
false
false
false
AdaptiveMe/adaptive-arp-darwin
adaptive-arp-rt/AdaptiveArpRtiOS/MediaViewController.swift
1
1502
/* * =| ADAPTIVE RUNTIME PLATFORM |======================================================================================= * * (C) Copyright 2013-2014 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>. * * 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. * * Original author: * * * Carlos Lozano Diez * <http://github.com/carloslozano> * <http://twitter.com/adaptivecoder> * <mailto:[email protected]> * * Contributors: * * * Ferran Vila Conesa * <http://github.com/fnva> * <http://twitter.com/ferran_vila> * <mailto:[email protected]> * * ===================================================================================================================== */ import UIKit import AVKit import AVFoundation import AdaptiveArpApi public class MediaViewController: AVPlayerViewController { public func setAVPlayer(url:NSURL){ self.player = AVPlayer(URL: url) } }
apache-2.0
8ec5fb3c1be9bc796efcd9c18aba8440
33.930233
119
0.57723
4.551515
false
false
false
false
LeeShiYoung/LSYWeibo
LSYWeiBo/Profile/ProfileTableViewController.swift
1
2991
// // ProfileTableViewController.swift // LSYWeiBo // // Created by 李世洋 on 16/5/1. // Copyright © 2016年 李世洋. All rights reserved. // import UIKit class ProfileTableViewController: BaseTableViewController { override func viewDidLoad() { super.viewDidLoad() if !login { visitorView?.setupVisitorInfo(false, iconStr: "visitordiscover_image_profile", text: "登录后,你的微博、相册、个人资料会显示在这里,展示给别人") } } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
artistic-2.0
85c02c610d2fe359c5940e5cca73591b
31.087912
157
0.677055
5.387454
false
false
false
false
uasys/swift
test/IRGen/associated_types.swift
1
4144
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-ir -primary-file %s | %FileCheck %s // REQUIRES: CPU=i386 || CPU=x86_64 protocol Runcer { associatedtype Runcee } protocol Runcible { associatedtype RuncerType : Runcer associatedtype AltRuncerType : Runcer } struct Mince {} struct Quince : Runcer { typealias Runcee = Mince } struct Spoon : Runcible { typealias RuncerType = Quince typealias AltRuncerType = Quince } struct Owl<T : Runcible, U> { // CHECK: define hidden swiftcc void @_T016associated_types3OwlV3eat{{[_0-9a-zA-Z]*}}F(%swift.opaque* func eat(_ what: T.RuncerType.Runcee, and: T.RuncerType, with: T) { } } class Pussycat<T : Runcible, U> { init() {} // CHECK: define hidden swiftcc void @_T016associated_types8PussycatC3eat{{[_0-9a-zA-Z]*}}F(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %T16associated_types8PussycatC* swiftself) func eat(_ what: T.RuncerType.Runcee, and: T.RuncerType, with: T) { } } func owl() -> Owl<Spoon, Int> { return Owl() } func owl2() { Owl<Spoon, Int>().eat(Mince(), and: Quince(), with: Spoon()) } func pussycat() -> Pussycat<Spoon, Int> { return Pussycat() } func pussycat2() { Pussycat<Spoon, Int>().eat(Mince(), and: Quince(), with: Spoon()) } protocol Speedy { static func accelerate() } protocol FastRuncer { associatedtype Runcee : Speedy } protocol FastRuncible { associatedtype RuncerType : FastRuncer } // This is a complex example demonstrating the need to pull conformance // information for archetypes from all paths to that archetype, not just // its parent relationships. func testFastRuncible<T: Runcible, U: FastRuncible where T.RuncerType == U.RuncerType>(_ t: T, u: U) { U.RuncerType.Runcee.accelerate() } // CHECK: define hidden swiftcc void @_T016associated_types16testFastRuncibleyx_q_1utAA0E0RzAA0dE0R_10RuncerTypeQy_AFRtzr0_lF(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T, %swift.type* %U, i8** %T.Runcible, i8** %U.FastRuncible) #0 { // 1. Get the type metadata for U.RuncerType.Runcee. // 1a. Get the type metadata for U.RuncerType. // Note that we actually look things up in T, which is going to prove unfortunate. // CHECK: [[T0:%.*]] = load i8*, i8** %T.Runcible, // CHECK-NEXT: [[T1:%.*]] = bitcast i8* [[T0]] to %swift.type* (%swift.type*, i8**)* // CHECK-NEXT: %T.RuncerType = call %swift.type* [[T1]](%swift.type* %T, i8** %T.Runcible) // 2. Get the witness table for U.RuncerType.Runcee : Speedy // 2a. Get the protocol witness table for U.RuncerType : FastRuncer. // CHECK-NEXT: [[T0:%.*]] = getelementptr inbounds i8*, i8** %U.FastRuncible, i32 1 // CHECK-NEXT: [[T1:%.*]] = load i8*, i8** [[T0]], // CHECK-NEXT: [[T2:%.*]] = bitcast i8* [[T1]] to i8** (%swift.type*, %swift.type*, i8**)* // CHECK-NEXT: %T.RuncerType.FastRuncer = call i8** [[T2]](%swift.type* %T.RuncerType, %swift.type* %U, i8** %U.FastRuncible) // 1c. Get the type metadata for U.RuncerType.Runcee. // CHECK-NEXT: [[T0:%.*]] = load i8*, i8** %T.RuncerType.FastRuncer // CHECK-NEXT: [[T1:%.*]] = bitcast i8* [[T0]] to %swift.type* (%swift.type*, i8**)* // CHECK-NEXT: %T.RuncerType.Runcee = call %swift.type* [[T1]](%swift.type* %T.RuncerType, i8** %T.RuncerType.FastRuncer) // 2b. Get the witness table for U.RuncerType.Runcee : Speedy. // CHECK-NEXT: [[T0:%.*]] = getelementptr inbounds i8*, i8** %T.RuncerType.FastRuncer, i32 1 // CHECK-NEXT: [[T1:%.*]] = load i8*, i8** [[T0]], // CHECK-NEXT: [[T2:%.*]] = bitcast i8* [[T1]] to i8** (%swift.type*, %swift.type*, i8**)* // CHECK-NEXT: %T.RuncerType.Runcee.Speedy = call i8** [[T2]](%swift.type* %T.RuncerType.Runcee, %swift.type* %T.RuncerType, i8** %T.RuncerType.FastRuncer) // 3. Perform the actual call. // CHECK-NEXT: [[T0:%.*]] = load i8*, i8** %T.RuncerType.Runcee.Speedy, // CHECK-NEXT: [[T1:%.*]] = bitcast i8* [[T0]] to void (%swift.type*, %swift.type*, i8**)* // CHECK-NEXT: call swiftcc void [[T1]](%swift.type* swiftself %T.RuncerType.Runcee, %swift.type* %T.RuncerType.Runcee, i8** %T.RuncerType.Runcee.Speedy)
apache-2.0
338fc4752bb092eb0eeaa791837ade45
40.858586
272
0.66723
3.160946
false
false
false
false
apple/swift
test/Interop/Cxx/operators/member-inline-irgen.swift
4
4013
// RUN: %target-swift-emit-ir %s -I %S/Inputs -enable-experimental-cxx-interop | %FileCheck %s // // We should be able to support windows now. We will remove XFAIL in follow up // XFAIL: windows import MemberInline public func sub(_ lhs: inout LoadableIntWrapper, _ rhs: LoadableIntWrapper) -> LoadableIntWrapper { lhs - rhs } // CHECK: call [[RESA:i32|i64]] [[NAMEA:@(_ZN18LoadableIntWrappermiES_|"\?\?GLoadableIntWrapper@@QEAA\?AU0@U0@@Z")]](%struct.LoadableIntWrapper* {{%[0-9]+}}, {{i32|\[1 x i32\]|i64|%struct.LoadableIntWrapper\* byval\(.*\) align 4}} {{%[0-9]+}}) public func call(_ wrapper: inout LoadableIntWrapper, _ arg: Int32) -> Int32 { wrapper(arg) } // CHECK: call [[RES:i32|i64]] [[NAME:@(_ZN18LoadableIntWrapperclEi|"\?\?GLoadableIntWrapper@@QEAAHH@Z")]](%struct.LoadableIntWrapper* {{%[0-9]+}}, {{i32|\[1 x i32\]|i64|%struct.LoadableIntWrapper\* byval\(.*\)}}{{.*}}) // CHECK: define {{.*}}[[RES]] [[NAME]](%struct.LoadableIntWrapper* {{.*}}, {{i32|\[1 x i32\]|i64|%struct.LoadableIntWrapper\* byval\(%struct.LoadableIntWrapper\)}}{{.*}}) public func call(_ wrapper: inout AddressOnlyIntWrapper) -> Int32 { wrapper() } // CHECK: call [[RES:i32|i64]] [[NAME:@(_ZN21AddressOnlyIntWrapperclEv|"\?\?GAddressOnlyIntWrapper@@QEAAHXZ")]](%struct.AddressOnlyIntWrapper* {{.*}}) // CHECK: define {{.*}}[[RES]] [[NAME]](%struct.AddressOnlyIntWrapper* {{.*}}) public func index(_ arr: inout ReadOnlyIntArray, _ arg: Int32) -> Int32 { arr[arg] } // CHECK: call [[RES:i32|i64]]* [[NAME:@(_ZNK16ReadOnlyIntArrayixEi|"\?\?AReadOnlyIntArray@@QEBAAEBHH@Z")]](%struct.ReadOnlyIntArray* {{.*}}, {{i32|i64}}{{.*}}) // CHECK: define {{.*}}[[RES]]* [[NAME]](%struct.ReadOnlyIntArray* {{.*}}, {{i32|\[1 x i32\]|i64|%struct.ReadOnlyIntArray\* byval\(%struct.ReadOnlyIntArray\)}}{{.*}}) // CHECK: [[THIS:%.*]] = load %struct.ReadOnlyIntArray*, %struct.ReadOnlyIntArray** // CHECK: [[VALUES:%.*]] = getelementptr inbounds %struct.ReadOnlyIntArray, %struct.ReadOnlyIntArray* [[THIS]] // CHECK: [[VALUE:%.*]] = getelementptr inbounds [5 x {{i32|i64}}], [5 x {{i32|i64}}]* [[VALUES]] // CHECK: ret {{i32|i64}}* [[VALUE]] public func index(_ arr: inout ReadWriteIntArray, _ arg: Int32, _ val: Int32) { arr[arg] = val } // CHECK: call [[RES:i32|i64]]* [[NAME:@(_ZN17ReadWriteIntArrayixEi|"\?\?AReadWriteIntArray@@QEAAAEAHH@Z")]](%struct.ReadWriteIntArray* {{.*}}, {{i32|i64}}{{.*}}) // CHECK: define {{.*}}[[RES]]* [[NAME]](%struct.ReadWriteIntArray* {{.*}}, {{i32|\[1 x i32\]|i64|%struct.ReadWriteIntArray\* byval\(%struct.ReadWriteIntArray\)}}{{.*}}) // CHECK: [[THIS:%.*]] = load %struct.ReadWriteIntArray*, %struct.ReadWriteIntArray** // CHECK: [[VALUES:%.*]] = getelementptr inbounds %struct.ReadWriteIntArray, %struct.ReadWriteIntArray* [[THIS]] // CHECK: [[VALUE:%.*]] = getelementptr inbounds [5 x {{i32|i64}}], [5 x {{i32|i64}}]* [[VALUES]] // CHECK: ret {{i32|i64}}* [[VALUE]] public func index(_ arr: inout NonTrivialIntArrayByVal, _ arg: Int32) -> Int32 { arr[arg] } // CHECK: call [[RES:i32|i64]] [[NAME:@(_ZNK23NonTrivialIntArrayByValixEi|"\?\?ANonTrivialIntArrayByVal@@QEBAAEBHH@Z")]](%struct.NonTrivialIntArrayByVal* {{.*}}, {{i32|i64}}{{.*}}) // CHECK: define {{.*}}[[RES]] [[NAME]](%struct.NonTrivialIntArrayByVal* {{.*}}, {{i32|\[1 x i32\]|i64|%struct.NonTrivialIntArrayByVal\* byval\(%struct.NonTrivialIntArrayByVal\)}}{{.*}}) // CHECK: [[THIS:%.*]] = load %struct.NonTrivialIntArrayByVal*, %struct.NonTrivialIntArrayByVal** // CHECK: [[VALUES:%.*]] = getelementptr inbounds %struct.NonTrivialIntArrayByVal, %struct.NonTrivialIntArrayByVal* [[THIS]] // CHECK: [[VALUE:%.*]] = getelementptr inbounds [5 x {{i32|i64}}], [5 x {{i32|i64}}]* [[VALUES]] // CHECK: [[VALUE2:%.*]] = load {{i32|i64}}, {{i32|i64}}* [[VALUE]] // CHECK: ret {{i32|i64}} [[VALUE2]] // CHECK: define {{.*}}[[RESA]] [[NAMEA]](%struct.LoadableIntWrapper* {{.*}}, {{i32 .*%.*.coerce|\[1 x i32\] .*%.*.coerce|i64 .*%.*.coerce|%struct.LoadableIntWrapper\* .*byval\(%struct.LoadableIntWrapper\).*}})
apache-2.0
c1a8e1829cc6b153c37f82d557a1ecfe
77.686275
243
0.642163
3.32202
false
false
false
false
HaliteChallenge/Halite-II
airesources/Swift/Sources/hlt/Ship.swift
1
3350
import Foundation public enum DockingStatus: Int { case undocked = 0 case docking case docked case undocking } public struct Ship: Entity, HLTDeserializable { /// The id of the ship public let id: Int /// The x coordinate of the ship public let x: Double /// The y coordinate of the ship public let y: Double /// The radius of the ship public let radius: Double /// The health of the ship public let health: Int /// The docking status of the ship public let dockingStatus: DockingStatus /// The id of the planet that the ship is docked to, nil if it isn't docked public let dockedPlanetId: Int? /// The progress of docking public let dockingProgress: Int /// The weapon cooldown of the ship public let weaponCoolDown: Int static func deserialize(_ tokens: TokenStack) -> Ship { let id = Int(tokens.pop())! let x = Double(tokens.pop())! let y = Double(tokens.pop())! let health = Int(tokens.pop())! _ = Double(tokens.pop())! // XVel - deprecated _ = Double(tokens.pop())! // YVel - deprecated let dockingStatus = DockingStatus(rawValue: Int(tokens.pop())!)! let dockedPlanetId = Int(tokens.pop())! let dockingProgress = Int(tokens.pop())! let weaponCooldown = Int(tokens.pop())! return Ship(id: id, x: x, y: y, radius: Constants.ShipRadius, health: health, dockingStatus: dockingStatus, dockedPlanetId: dockingStatus == .docked ? dockedPlanetId : nil, dockingProgress: dockingProgress, weaponCoolDown: weaponCooldown) } /// Returns true if the ship can dock with the given planet public func canDock(withPlanet planet: Planet) -> Bool { return self.distance(to: planet) <= self.radius + Constants.DockRadius + planet.radius } // MARK: Ship Moves /// Creates a thrust move for the ship public func thrust(magnitude: Int, angle: Int) -> Move { return .thrust(self, angleDeg: angle, thrust: magnitude) } /// Creates a dock move for the ship with the given planet public func dock(_ planet: Planet) -> Move { return .dock(self, planet: planet) } /// Creates an undock move for the ship public func undock() -> Move { return .undock(self) } /// Creates a move that navigates towards the given target public func navigate(towards target: Entity, map: Map, maxThrust: Int, avoidObstacles: Bool) -> Move { let angularStepRad = Double.pi / 180.0 return navigateShipTowardsTarget(map: map, ship: self, target: target, maxThrust: maxThrust, avoidObstacles: avoidObstacles, maxCorrections: Constants.MaxNavigationCorrections, angularStepRad: angularStepRad) } }
mit
cea9e2e97b8fa876155a54cef93775fc
33.536082
94
0.544478
4.745042
false
false
false
false
GuitarPlayer-Ma/Swiftweibo
weibo/weibo/Classes/Home/View/Cell/HomeForwardCell.swift
1
2039
// // HomeForwardCell.swift // weibo // // Created by mada on 15/10/12. // Copyright © 2015年 MD. All rights reserved. // import UIKit class HomeForwardCell: HomeTableViewCell { override var status: Status? { didSet { let name = status?.retweeted_status?.user?.name let text = status?.retweeted_status?.text if name != nil && text != nil { retweetContentLabel.text = "@\(name!): " + text! } } } override func setupChildUI() { super.setupChildUI() // 添加自己的子控件 contentView.insertSubview(coverView, belowSubview: pictureView) coverView.addSubview(retweetContentLabel) // 布局子控件 // 整体内容 coverView.snp_makeConstraints { (make) -> Void in make.top.equalTo(contentLabel.snp_bottom).offset(10) make.left.equalTo(contentView) make.right.equalTo(contentView) make.bottom.equalTo(pictureView.snp_bottom).offset(10) } // 文字内容 retweetContentLabel.snp_makeConstraints { (make) -> Void in make.top.equalTo(coverView.snp_top).offset(10) make.left.equalTo(contentLabel) make.right.equalTo(contentLabel) } // 配图布局 pictureView.snp_makeConstraints { (make) -> Void in make.top.equalTo(retweetContentLabel.snp_bottom).offset(10) make.left.equalTo(retweetContentLabel) } } // MARK: - 懒加载 // 转发背景 private lazy var coverView: UIView = { let view = UIView() view.backgroundColor = UIColor.lightGrayColor() return view }() // 转发内容 private lazy var retweetContentLabel: UILabel = { let content = UILabel() content.text = "somethingsomethingsomethingsomethingsomethingsomethingsomethingsomething" content.numberOfLines = 0 return content }() }
mit
6b124e2e01f06f06962dd1880be2ce8e
27.882353
97
0.586558
4.610329
false
false
false
false
bengottlieb/stack-watcher
StackWatcher/Controllers/Main/MainController.swift
1
2952
// // MainController.swift // StackWatcher // // Created by Ben Gottlieb on 6/5/14. // Copyright (c) 2014 Stand Alone, Inc. All rights reserved. // import UIKit class MainController: UISplitViewController, UISplitViewControllerDelegate { var detailController = QuestionDetailsViewController() var masterController = QuestionListTableViewController(nibName: nil, bundle: nil) var hideMasterList = false init() { super.init(nibName: nil, bundle: nil) viewControllers = [ UINavigationController(rootViewController: masterController), UINavigationController(rootViewController: detailController) ] self.detailController.navigationItem.rightBarButtonItems = self.rightButtons self.delegate = self //self.detailController.navigationItem.leftBarButtonItem = self.displayModeButtonItem() } func splitViewController(svc: UISplitViewController!, willHideViewController aViewController: UIViewController!, withBarButtonItem barButtonItem: UIBarButtonItem!, forPopoverController pc: UIPopoverController!) { self.detailController.navigationItem.leftBarButtonItem = barButtonItem } func splitViewController(svc: UISplitViewController!, willShowViewController aViewController: UIViewController!, invalidatingBarButtonItem barButtonItem: UIBarButtonItem!) { if aViewController == masterController.navigationController { self.detailController.navigationItem.leftBarButtonItem = nil } } func toggleMasterList() { self.hideMasterList = !self.hideMasterList self.delegate = nil self.delegate = self self.view.setNeedsLayout() self.willRotateToInterfaceOrientation(UIApplication.sharedApplication().statusBarOrientation, duration: 1) self.detailController.navigationItem.rightBarButtonItems = self.rightButtons } override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) { super.didRotateFromInterfaceOrientation(fromInterfaceOrientation) self.detailController.navigationItem.rightBarButtonItems = self.rightButtons } func splitViewController(svc: UISplitViewController!, shouldHideViewController vc: UIViewController!, inOrientation orientation: UIInterfaceOrientation) -> Bool { if (vc == self.masterController.navigationController) { if self.hideMasterList { return true } if UIInterfaceOrientationIsPortrait(orientation) { return true } } return false } var rightButtons: [UIBarButtonItem] { if (UIInterfaceOrientationIsPortrait(self.interfaceOrientation)) { return [ self.detailController.reloadButton ] } return [ self.detailController.reloadButton, self.expandButton ] } var expandButton: UIBarButtonItem { var imageName = self.hideMasterList ? "show_tabs" : "hide_tabs" return UIBarButtonItem(title: self.hideMasterList ? ">" : "<", style: .Bordered, target: self, action: "toggleMasterList") // return UIBarButtonItem(image: UIImage(named: imageName), style: .Bordered, target: self, action: "toggleMasterList") } }
mit
24f9b3e04ef8f5b83c5b179f2d59b232
40.577465
213
0.799797
4.928214
false
false
false
false
vector-im/vector-ios
Riot/Modules/Common/KeyboardAvoiding/KeyboardAvoider.swift
1
5129
/* Copyright 2019 New Vector Ltd 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 @objcMembers /// Avoid keyboard overlap with scroll view content final class KeyboardAvoider: NSObject { // MARK: - Constants private enum KeyboardAnimation { static let defaultDuration: TimeInterval = 0.25 static let defaultAnimationCurveRawValue: Int = UIView.AnimationCurve.easeInOut.rawValue } // MARK: - Properties weak var scrollViewContainerView: UIView? weak var scrollView: UIScrollView? // MARK: - Setup /// Designated initializer. /// /// - Parameter scrollViewContainerView: The view that wraps the scroll view. /// - Parameter scrollView: The scroll view containing keyboard inputs and where content view overlap with keyboard should be avoided. init(scrollViewContainerView: UIView, scrollView: UIScrollView) { self.scrollViewContainerView = scrollViewContainerView self.scrollView = scrollView super.init() } // MARK: - Public /// Start keyboard avoiding func startAvoiding() { self.registerKeyboardNotifications() } /// Stop keyboard avoiding func stopAvoiding() { self.unregisterKeyboardNotifications() } // MARK: - Private private func registerKeyboardNotifications() { let notificationCenter = NotificationCenter.default notificationCenter.addObserver( self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil) notificationCenter.addObserver( self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil) } private func unregisterKeyboardNotifications() { NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil) } @objc private func keyboardWillShow(notification: Notification) { guard let view = self.scrollViewContainerView, let scrollView = self.scrollView else { return } guard let keyboardNotification = KeyboardNotification(notification: notification), let keyboardFrame = keyboardNotification.keyboardFrameEnd else { return } let animationDuration = keyboardNotification.animationDuration ?? KeyboardAnimation.defaultDuration let animationOptions = keyboardNotification.animationOptions(fallbackAnimationCurveValue: KeyboardAnimation.defaultAnimationCurveRawValue) // Transform the keyboard's frame into our view's coordinate system let keyboardFrameInView = view.convert(keyboardFrame, from: nil) // Find how much the keyboard overlaps the scroll view let scrollViewBottomInset = max(scrollView.frame.maxY - keyboardFrameInView.origin.y - view.safeAreaInsets.bottom, 0) UIView.animate(withDuration: animationDuration, delay: 0.0, options: animationOptions, animations: { scrollView.contentInset.bottom = scrollViewBottomInset scrollView.scrollIndicatorInsets.bottom = scrollViewBottomInset }, completion: nil) } @objc private func keyboardWillHide(notification: Notification) { guard let scrollView = self.scrollView else { return } guard let keyboardNotification = KeyboardNotification(notification: notification) else { return } let animationDuration = keyboardNotification.animationDuration ?? KeyboardAnimation.defaultDuration let animationOptions = keyboardNotification.animationOptions(fallbackAnimationCurveValue: KeyboardAnimation.defaultAnimationCurveRawValue) // Reset scroll view bottom inset to zero let scrollViewBottomInset: CGFloat = 0.0 UIView.animate(withDuration: animationDuration, delay: 0.0, options: animationOptions, animations: { scrollView.contentInset.bottom = scrollViewBottomInset scrollView.scrollIndicatorInsets.bottom = scrollViewBottomInset }, completion: nil) } }
apache-2.0
7f76fd7daede76d6d3accbdeaabe85ce
37.856061
146
0.672646
6.247259
false
false
false
false
burningmantech/ranger-ims-mac
Incidents/Location.swift
1
1700
// // Location.swift // Incidents // // © 2015 Burning Man and its contributors. All rights reserved. // See the file COPYRIGHT.md for terms. // struct Location: CustomStringConvertible, Hashable, NillishEquatable { var name: String? var address: Address? var hashValue: Int { var hash = 0 if let h = name? .hashValue { hash ^= h } if let h = address?.hashValue { hash ^= h } return hash } var description: String { var result = "" if let name = self.name { result += name if let address = self.address { if address.description != name { result += " (\(address))" } } } else { if let address = self.address { result += "(\(address))" } } return result } init( name : String? = nil, address: Address? = nil ) { self.name = name self.address = address } func isNillish() -> Bool { if name != nil { return false } return nillish(address) // return (name == nil && nillish(address)) } } func ==(lhs: Location, rhs: Location) -> Bool { return ( lhs.name == rhs.name && lhs.address == rhs.address ) } func <(lhs: Location, rhs: Location) -> Bool { if lhs.name == nil { return true } else if lhs.name < rhs.name { return true } else if lhs.name > rhs.name { return false } else if lhs.address == nil { return true } else { return lhs.address! < rhs.address! } }
apache-2.0
5b1cc68ce93f6463bea9d49cd44969d2
20.2375
70
0.490288
4.174447
false
false
false
false
roambotics/swift
test/Serialization/multi-file.swift
2
2014
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module -module-name Multi -o %t/multi-file.swiftmodule -primary-file %s %S/Inputs/multi-file-2.swift // RUN: %target-swift-frontend -emit-module -module-name Multi -o %t/multi-file-2.swiftmodule %s -primary-file %S/Inputs/multi-file-2.swift // RUN: llvm-bcanalyzer %t/multi-file.swiftmodule | %FileCheck %s -check-prefix=THIS-FILE // RUN: llvm-bcanalyzer %t/multi-file.swiftmodule | %FileCheck %s -check-prefix=THIS-FILE-NEG // RUN: llvm-bcanalyzer %t/multi-file-2.swiftmodule | %FileCheck %s -check-prefix=OTHER-FILE // RUN: llvm-bcanalyzer %t/multi-file-2.swiftmodule | %FileCheck %s -check-prefix=OTHER-FILE-NEG // RUN: %target-swift-frontend -emit-module -module-name Multi %t/multi-file.swiftmodule %t/multi-file-2.swiftmodule -o %t // RUN: llvm-bcanalyzer %t/Multi.swiftmodule | %FileCheck %s -check-prefix=THIS-FILE // RUN: llvm-bcanalyzer %t/Multi.swiftmodule | %FileCheck %s -check-prefix=OTHER-FILE // Do not put any enums in this file. It's part of the test that no enums // get serialized here. class MyClass { var value: TheEnum = .A } func foo<T: Equatable>(_ x: T) {} func bar() { foo(EquatableEnum.A) } // THIS-FILE-DAG: PROTOCOL_DECL // OTHER-FILE-NEG-NOT: PROTOCOL_DECL // OTHER-FILE-DAG: ENUM_DECL // THIS-FILE-NEG-NOT: ENUM_DECL // <rdar://problem/17251682> struct StructWithInheritedConformances: Sequence { struct EmptyIterator : IteratorProtocol { mutating func next() -> Int? { return nil } } func makeIterator() -> EmptyIterator { return EmptyIterator() } } // https://github.com/apple/swift/issues/45181 // An associated type inside a private protocol would cause crashes during // module merging. private protocol SomeProto { // THIS-FILE-DAG: ASSOCIATED_TYPE_DECL associatedtype Item } private struct Generic<T> { // THIS-FILE-DAG: GENERIC_TYPE_PARAM_DECL } class Sub: Base { override class var conflict: Int { return 100 } override var conflict: Int { return 200 } }
apache-2.0
5f58982695b52ab482a4c06a177cc0c8
32.566667
139
0.715492
3.2589
false
false
false
false
telip007/ChatFire
ChatFire/Modals/Chat.swift
1
1279
// // Chat.swift // ChatFire // // Created by Talip Göksu on 06.09.16. // Copyright © 2016 ChatFire. All rights reserved. // import Foundation import Firebase class Chat: NSObject{ var user1: String? var user2: String? var chatId: String? var lastMessage: String? var lastDate: String? var lastMessageDate: NSNumber?{ didSet{ getDate() } } var partner: String? override func setValuesForKeysWithDictionary(keyedValues: [String : AnyObject]) { super.setValuesForKeysWithDictionary(keyedValues) if self.user1! == currentUser?.uid{ self.partner = self.user2! } else{ self.partner = self.user1! } } func getDate(){ if let date = self.lastMessageDate as? NSTimeInterval{ let createDate = NSDate(timeIntervalSince1970: date/1000) let formatter = NSDateFormatter() formatter.dateFormat = "HH:mm" self.lastDate = formatter.stringFromDate(createDate) } } func getImage(imageUrl: (String) -> ()){ User.userFromId(self.partner!, user: { (user) in imageUrl(user.profile_image!) }) } }
apache-2.0
8e9935b8fce068487aee8cb7b29ad436
21.803571
85
0.571652
4.512367
false
false
false
false
gurenupet/hah-auth-ios-swift
hah-auth-ios-swift/Pods/Mixpanel-swift/Mixpanel/WebSocket.swift
2
34271
////////////////////////////////////////////////////////////////////////////////////////////////// // // Websocket.swift // // Created by Dalton Cherry on 7/16/14. // Copyright (c) 2014-2015 Dalton Cherry. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ////////////////////////////////////////////////////////////////////////////////////////////////// import Foundation import CoreFoundation import Security let WebsocketDidConnectNotification = "WebsocketDidConnectNotification" let WebsocketDidDisconnectNotification = "WebsocketDidDisconnectNotification" let WebsocketDisconnectionErrorKeyName = "WebsocketDisconnectionErrorKeyName" protocol WebSocketDelegate: class { func websocketDidConnect(_ socket: WebSocket) func websocketDidDisconnect(_ socket: WebSocket, error: NSError?) func websocketDidReceiveMessage(_ socket: WebSocket, text: String) func websocketDidReceiveData(_ socket: WebSocket, data: Data) } protocol WebSocketPongDelegate: class { func websocketDidReceivePong(_ socket: WebSocket) } class WebSocket: NSObject, StreamDelegate { enum OpCode: UInt8 { case continueFrame = 0x0 case textFrame = 0x1 case binaryFrame = 0x2 // 3-7 are reserved. case connectionClose = 0x8 case ping = 0x9 case pong = 0xA // B-F reserved. } enum CloseCode: UInt16 { case normal = 1000 case goingAway = 1001 case protocolError = 1002 case protocolUnhandledType = 1003 // 1004 reserved. case noStatusReceived = 1005 //1006 reserved. case encoding = 1007 case policyViolated = 1008 case messageTooBig = 1009 } static let ErrorDomain = "WebSocket" enum InternalErrorCode: UInt16 { // 0-999 WebSocket status codes not used case outputStreamWriteError = 1 } // Where the callback is executed. It defaults to the main UI thread queue. var callbackQueue = DispatchQueue.main var optionalProtocols: [String]? // MARK: - Constants let headerWSUpgradeName = "Upgrade" let headerWSUpgradeValue = "websocket" let headerWSHostName = "Host" let headerWSConnectionName = "Connection" let headerWSConnectionValue = "Upgrade" let headerWSProtocolName = "Sec-WebSocket-Protocol" let headerWSVersionName = "Sec-WebSocket-Version" let headerWSVersionValue = "13" let headerWSKeyName = "Sec-WebSocket-Key" let headerOriginName = "Origin" let headerWSAcceptName = "Sec-WebSocket-Accept" let BUFFER_MAX = 4096 let FinMask: UInt8 = 0x80 let OpCodeMask: UInt8 = 0x0F let RSVMask: UInt8 = 0x70 let MaskMask: UInt8 = 0x80 let PayloadLenMask: UInt8 = 0x7F let MaxFrameSize: Int = 32 let httpSwitchProtocolCode = 101 let supportedSSLSchemes = ["wss", "https"] class WSResponse { var isFin = false var code: OpCode = .continueFrame var bytesLeft = 0 var frameCount = 0 var buffer: NSMutableData? } // MARK: - Delegates /// Responds to callback about new messages coming in over the WebSocket /// and also connection/disconnect messages. weak var delegate: WebSocketDelegate? /// Recives a callback for each pong message recived. weak var pongDelegate: WebSocketPongDelegate? // MARK: - Block based API. var onConnect: ((Void) -> Void)? var onDisconnect: ((NSError?) -> Void)? var onText: ((String) -> Void)? var onData: ((Data) -> Void)? var onPong: ((Void) -> Void)? var headers = [String: String]() var voipEnabled = false var selfSignedSSL = false var security: SSLSecurity? var enabledSSLCipherSuites: [SSLCipherSuite]? var origin: String? var timeout = 5 var isConnected: Bool { return connected } var currentURL: URL { return url } // MARK: - Private private var url: URL private var inputStream: InputStream? private var outputStream: OutputStream? private var connected = false private var isConnecting = false private var writeQueue = OperationQueue() private var readStack = [WSResponse]() private var inputQueue = [Data]() private var fragBuffer: Data? private var certValidated = false private var didDisconnect = false private var readyToWrite = false private let mutex = NSLock() private let notificationCenter = NotificationCenter.default private var canDispatch: Bool { mutex.lock() let canWork = readyToWrite mutex.unlock() return canWork } /// The shared processing queue used for all WebSocket. private static let sharedWorkQueue = DispatchQueue(label: "com.vluxe.starscream.websocket", attributes: []) init(url: URL, protocols: [String]? = nil) { self.url = url self.origin = url.absoluteString writeQueue.maxConcurrentOperationCount = 1 optionalProtocols = protocols } /// Connect to the WebSocket server on a background thread. func connect() { guard !isConnecting else { return } didDisconnect = false isConnecting = true createHTTPRequest() isConnecting = false } /** Disconnect from the server. I send a Close control frame to the server, then expect the server to respond with a Close control frame and close the socket from its end. I notify my delegate once the socket has been closed. If you supply a non-nil `forceTimeout`, I wait at most that long (in seconds) for the server to close the socket. After the timeout expires, I close the socket and notify my delegate. If you supply a zero (or negative) `forceTimeout`, I immediately close the socket (without sending a Close control frame) and notify my delegate. - Parameter forceTimeout: Maximum time to wait for the server to close the socket. */ func disconnect(forceTimeout: TimeInterval? = nil) { switch forceTimeout { case .some(let seconds) where seconds > 0: callbackQueue.asyncAfter(deadline: .now() + Double(Int64(seconds * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { [weak self] in self?.disconnectStream(nil) } fallthrough case .none: writeError(CloseCode.normal.rawValue) default: disconnectStream(nil) break } } func write(string: String, completion: (() -> ())? = nil) { guard isConnected else { return } dequeueWrite(string.data(using: String.Encoding.utf8)!, code: .textFrame, writeCompletion: completion) } func write(data: Data, completion: (() -> ())? = nil) { guard isConnected else { return } dequeueWrite(data, code: .binaryFrame, writeCompletion: completion) } func write(_ ping: Data, completion: (() -> ())? = nil) { guard isConnected else { return } dequeueWrite(ping, code: .ping, writeCompletion: completion) } private func createHTTPRequest() { let urlRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, "GET" as CFString, url as CFURL, kCFHTTPVersion1_1).takeRetainedValue() var port = url.port if port == nil { if supportedSSLSchemes.contains(url.scheme!) { port = 443 } else { port = 80 } } addHeader(urlRequest, key: headerWSUpgradeName, val: headerWSUpgradeValue) addHeader(urlRequest, key: headerWSConnectionName, val: headerWSConnectionValue) if let protocols = optionalProtocols { addHeader(urlRequest, key: headerWSProtocolName, val: protocols.joined(separator: ",")) } addHeader(urlRequest, key: headerWSVersionName, val: headerWSVersionValue) addHeader(urlRequest, key: headerWSKeyName, val: generateWebSocketKey()) if let origin = origin { addHeader(urlRequest, key: headerOriginName, val: origin) } addHeader(urlRequest, key: headerWSHostName, val: "\(url.host!):\(port!)") for (key, value) in headers { addHeader(urlRequest, key: key, val: value) } if let cfHTTPMessage = CFHTTPMessageCopySerializedMessage(urlRequest) { let serializedRequest = cfHTTPMessage.takeRetainedValue() initStreamsWithData(serializedRequest as Data, Int(port!)) } } private func addHeader(_ urlRequest: CFHTTPMessage, key: String, val: String) { CFHTTPMessageSetHeaderFieldValue(urlRequest, key as CFString, val as CFString) } private func generateWebSocketKey() -> String { var key = "" let seed = 16 for _ in 0..<seed { let uni = UnicodeScalar(UInt32(97 + arc4random_uniform(25))) key += "\(Character(uni!))" } let data = key.data(using: String.Encoding.utf8) let baseKey = data?.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0)) return baseKey! } private func initStreamsWithData(_ data: Data, _ port: Int) { //higher level API we will cut over to at some point //NSStream.getStreamsToHostWithName(url.host, port: url.port.integerValue, inputStream: &inputStream, outputStream: &outputStream) var readStream: Unmanaged<CFReadStream>? var writeStream: Unmanaged<CFWriteStream>? let h = url.host! as NSString CFStreamCreatePairWithSocketToHost(nil, h, UInt32(port), &readStream, &writeStream) inputStream = readStream!.takeRetainedValue() outputStream = writeStream!.takeRetainedValue() guard let inStream = inputStream, let outStream = outputStream else { return } inStream.delegate = self outStream.delegate = self if supportedSSLSchemes.contains(url.scheme!) { inStream.setProperty(StreamSocketSecurityLevel.negotiatedSSL as AnyObject, forKey: Stream.PropertyKey.socketSecurityLevelKey) outStream.setProperty(StreamSocketSecurityLevel.negotiatedSSL as AnyObject, forKey: Stream.PropertyKey.socketSecurityLevelKey) } else { certValidated = true //not a https session, so no need to check SSL pinning } if voipEnabled { inStream.setProperty(StreamNetworkServiceTypeValue.voIP as AnyObject, forKey: Stream.PropertyKey.networkServiceType) outStream.setProperty(StreamNetworkServiceTypeValue.voIP as AnyObject, forKey: Stream.PropertyKey.networkServiceType) } if selfSignedSSL { let settings: [NSObject: NSObject] = [kCFStreamSSLValidatesCertificateChain: NSNumber(value: false), kCFStreamSSLPeerName: kCFNull] inStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as Stream.PropertyKey) outStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as Stream.PropertyKey) } if let cipherSuites = self.enabledSSLCipherSuites { if let sslContextIn = CFReadStreamCopyProperty(inputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext?, let sslContextOut = CFWriteStreamCopyProperty(outputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext? { let resIn = SSLSetEnabledCiphers(sslContextIn, cipherSuites, cipherSuites.count) let resOut = SSLSetEnabledCiphers(sslContextOut, cipherSuites, cipherSuites.count) if resIn != errSecSuccess { let error = self.errorWithDetail("Error setting ingoing cypher suites", code: UInt16(resIn)) disconnectStream(error) return } if resOut != errSecSuccess { let error = self.errorWithDetail("Error setting outgoing cypher suites", code: UInt16(resOut)) disconnectStream(error) return } } } CFReadStreamSetDispatchQueue(inStream, WebSocket.sharedWorkQueue) CFWriteStreamSetDispatchQueue(outStream, WebSocket.sharedWorkQueue) inStream.open() outStream.open() self.mutex.lock() self.readyToWrite = true self.mutex.unlock() let bytes = UnsafeRawPointer((data as NSData).bytes).assumingMemoryBound(to: UInt8.self) var out = timeout * 1000000 // wait 5 seconds before giving up writeQueue.addOperation { [weak self] in while !outStream.hasSpaceAvailable { usleep(100) // wait until the socket is ready out -= 100 if out < 0 { self?.cleanupStream() self?.doDisconnect(self?.errorWithDetail("write wait timed out", code: 2)) return } else if outStream.streamError != nil { return // disconnectStream will be called. } } outStream.write(bytes, maxLength: data.count) } } func stream(_ aStream: Stream, handle eventCode: Stream.Event) { if let sec = security, !certValidated && [.hasBytesAvailable, .hasSpaceAvailable].contains(eventCode) { let trust = aStream.property(forKey: kCFStreamPropertySSLPeerTrust as Stream.PropertyKey) as AnyObject let domain = aStream.property(forKey: kCFStreamSSLPeerName as Stream.PropertyKey) as? String if sec.isValid(trust as! SecTrust, domain: domain) { certValidated = true } else { let error = errorWithDetail("Invalid SSL certificate", code: 1) disconnectStream(error) return } } if eventCode == .hasBytesAvailable { if aStream == inputStream { processInputStream() } } else if eventCode == .errorOccurred { disconnectStream(aStream.streamError as NSError?) } else if eventCode == .endEncountered { disconnectStream(nil) } } private func disconnectStream(_ error: NSError?) { if error == nil { writeQueue.waitUntilAllOperationsAreFinished() } else { writeQueue.cancelAllOperations() } cleanupStream() doDisconnect(error) } private func cleanupStream() { outputStream?.delegate = nil inputStream?.delegate = nil if let stream = inputStream { CFReadStreamSetDispatchQueue(stream, nil) stream.close() } if let stream = outputStream { CFWriteStreamSetDispatchQueue(stream, nil) stream.close() } outputStream = nil inputStream = nil } private func processInputStream() { let buf = NSMutableData(capacity: BUFFER_MAX) let buffer = UnsafeMutableRawPointer(mutating: buf!.bytes).assumingMemoryBound(to: UInt8.self) let length = inputStream!.read(buffer, maxLength: BUFFER_MAX) guard length > 0 else { return } var process = false if inputQueue.isEmpty { process = true } inputQueue.append(Data(bytes: buffer, count: length)) if process { dequeueInput() } } private func dequeueInput() { while !inputQueue.isEmpty { let data = inputQueue[0] var work = data if let fragBuffer = fragBuffer { var combine = NSData(data: fragBuffer) as Data combine.append(data) work = combine self.fragBuffer = nil } let buffer = UnsafeRawPointer((work as NSData).bytes).assumingMemoryBound(to: UInt8.self) let length = work.count if !connected { processTCPHandshake(buffer, bufferLen: length) } else { processRawMessagesInBuffer(buffer, bufferLen: length) } inputQueue = inputQueue.filter { $0 != data } } } private func processTCPHandshake(_ buffer: UnsafePointer<UInt8>, bufferLen: Int) { let code = processHTTP(buffer, bufferLen: bufferLen) switch code { case 0: connected = true guard canDispatch else {return} callbackQueue.async { [weak self] in guard let s = self else { return } s.onConnect?() s.delegate?.websocketDidConnect(s) s.notificationCenter.post(name: NSNotification.Name(WebsocketDidConnectNotification), object: self) } case -1: fragBuffer = Data(bytes: buffer, count: bufferLen) break // do nothing, we are going to collect more data default: doDisconnect(errorWithDetail("Invalid HTTP upgrade", code: UInt16(code))) } } private func processHTTP(_ buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Int { let CRLFBytes = [UInt8(ascii: "\r"), UInt8(ascii: "\n"), UInt8(ascii: "\r"), UInt8(ascii: "\n")] var k = 0 var totalSize = 0 for i in 0..<bufferLen { if buffer[i] == CRLFBytes[k] { k += 1 if k == 3 { totalSize = i + 1 break } } else { k = 0 } } if totalSize > 0 { let code = validateResponse(buffer, bufferLen: totalSize) if code != 0 { return code } totalSize += 1 //skip the last \n let restSize = bufferLen - totalSize if restSize > 0 { processRawMessagesInBuffer(buffer + totalSize, bufferLen: restSize) } return 0 //success } return -1 // Was unable to find the full TCP header. } private func validateResponse(_ buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Int { let response = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, false).takeRetainedValue() CFHTTPMessageAppendBytes(response, buffer, bufferLen) let code = CFHTTPMessageGetResponseStatusCode(response) if code != httpSwitchProtocolCode { return code } if let cfHeaders = CFHTTPMessageCopyAllHeaderFields(response) { let headers = cfHeaders.takeRetainedValue() as NSDictionary if let acceptKey = headers[headerWSAcceptName as NSString] as? NSString { if acceptKey.length > 0 { return 0 } } } return -1 } private static func readUint16(_ buffer: UnsafePointer<UInt8>, offset: Int) -> UInt16 { return (UInt16(buffer[offset + 0]) << 8) | UInt16(buffer[offset + 1]) } private static func readUint64(_ buffer: UnsafePointer<UInt8>, offset: Int) -> UInt64 { var value = UInt64(0) for i in 0...7 { value = (value << 8) | UInt64(buffer[offset + i]) } return value } private static func writeUint16(_ buffer: UnsafeMutablePointer<UInt8>, offset: Int, value: UInt16) { buffer[offset + 0] = UInt8(value >> 8) buffer[offset + 1] = UInt8(value & 0xff) } private static func writeUint64(_ buffer: UnsafeMutablePointer<UInt8>, offset: Int, value: UInt64) { for i in 0...7 { buffer[offset + i] = UInt8((value >> (8*UInt64(7 - i))) & 0xff) } } private func processOneRawMessage(inBuffer buffer: UnsafeBufferPointer<UInt8>) -> UnsafeBufferPointer<UInt8> { let response = readStack.last guard let baseAddress = buffer.baseAddress else {return emptyBuffer} let bufferLen = buffer.count if response != nil && bufferLen < 2 { fragBuffer = Data(buffer: buffer) return emptyBuffer } if let response = response, response.bytesLeft > 0 { var len = response.bytesLeft var extra = bufferLen - response.bytesLeft if response.bytesLeft > bufferLen { len = bufferLen extra = 0 } response.bytesLeft -= len response.buffer?.append(Data(bytes: baseAddress, count: len)) _ = processResponse(response) return buffer.fromOffset(bufferLen - extra) } else { let isFin = (FinMask & baseAddress[0]) let receivedOpcode = OpCode(rawValue: (OpCodeMask & baseAddress[0])) let isMasked = (MaskMask & baseAddress[1]) let payloadLen = (PayloadLenMask & baseAddress[1]) var offset = 2 if (isMasked > 0 || (RSVMask & baseAddress[0]) > 0) && receivedOpcode != .pong { let errCode = CloseCode.protocolError.rawValue doDisconnect(errorWithDetail("masked and rsv data is not currently supported", code: errCode)) writeError(errCode) return emptyBuffer } let isControlFrame = (receivedOpcode == .connectionClose || receivedOpcode == .ping) if !isControlFrame && (receivedOpcode != .binaryFrame && receivedOpcode != .continueFrame && receivedOpcode != .textFrame && receivedOpcode != .pong) { let errCode = CloseCode.protocolError.rawValue let detail = (receivedOpcode != nil) ? "unknown opcode: \(receivedOpcode!)" : "unknown opcode" doDisconnect(errorWithDetail(detail, code: errCode)) writeError(errCode) return emptyBuffer } if isControlFrame && isFin == 0 { let errCode = CloseCode.protocolError.rawValue doDisconnect(errorWithDetail("control frames can't be fragmented", code: errCode)) writeError(errCode) return emptyBuffer } if receivedOpcode == .connectionClose { var code = CloseCode.normal.rawValue if payloadLen == 1 { code = CloseCode.protocolError.rawValue } else if payloadLen > 1 { code = WebSocket.readUint16(baseAddress, offset: offset) if code < 1000 || (code > 1003 && code < 1007) || (code > 1011 && code < 3000) { code = CloseCode.protocolError.rawValue } offset += 2 } var closeReason = "connection closed by server" if payloadLen > 2 { let len = Int(payloadLen - 2) if len > 0 { let bytes = baseAddress + offset if let customCloseReason = String(data: Data(bytes: bytes, count: len), encoding: .utf8) { closeReason = customCloseReason } else { code = CloseCode.protocolError.rawValue } } } doDisconnect(errorWithDetail(closeReason, code: code)) writeError(code) return emptyBuffer } if isControlFrame && payloadLen > 125 { writeError(CloseCode.protocolError.rawValue) return emptyBuffer } var dataLength = UInt64(payloadLen) if dataLength == 127 { dataLength = WebSocket.readUint64(baseAddress, offset: offset) offset += MemoryLayout<UInt64>.size } else if dataLength == 126 { dataLength = UInt64(WebSocket.readUint16(baseAddress, offset: offset)) offset += MemoryLayout<UInt16>.size } if bufferLen < offset || UInt64(bufferLen - offset) < dataLength { fragBuffer = Data(bytes: baseAddress, count: bufferLen) return emptyBuffer } var len = dataLength if dataLength > UInt64(bufferLen) { len = UInt64(bufferLen-offset) } let data = Data(bytes: baseAddress+offset, count: Int(len)) if receivedOpcode == .pong { if canDispatch { callbackQueue.async { [weak self] in guard let s = self else { return } s.onPong?() s.pongDelegate?.websocketDidReceivePong(s) } } return buffer.fromOffset(offset + Int(len)) } var response = readStack.last if isControlFrame { response = nil // Don't append pings. } if isFin == 0 && receivedOpcode == .continueFrame && response == nil { let errCode = CloseCode.protocolError.rawValue doDisconnect(errorWithDetail("continue frame before a binary or text frame", code: errCode)) writeError(errCode) return emptyBuffer } var isNew = false if response == nil { if receivedOpcode == .continueFrame { let errCode = CloseCode.protocolError.rawValue doDisconnect(errorWithDetail("first frame can't be a continue frame", code: errCode)) writeError(errCode) return emptyBuffer } isNew = true response = WSResponse() response!.code = receivedOpcode! response!.bytesLeft = Int(dataLength) response!.buffer = NSMutableData(data: data) } else { if receivedOpcode == .continueFrame { response!.bytesLeft = Int(dataLength) } else { let errCode = CloseCode.protocolError.rawValue doDisconnect(errorWithDetail("second and beyond of fragment message must be a continue frame", code: errCode)) writeError(errCode) return emptyBuffer } response!.buffer!.append(data) } if let response = response { response.bytesLeft -= Int(len) response.frameCount += 1 response.isFin = isFin > 0 ? true : false if isNew { readStack.append(response) } _ = processResponse(response) } let step = Int(offset + numericCast(len)) return buffer.fromOffset(step) } } private func processRawMessagesInBuffer(_ pointer: UnsafePointer<UInt8>, bufferLen: Int) { var buffer = UnsafeBufferPointer(start: pointer, count: bufferLen) repeat { buffer = processOneRawMessage(inBuffer: buffer) } while buffer.count >= 2 if !buffer.isEmpty { fragBuffer = Data(buffer: buffer) } } private func processResponse(_ response: WSResponse) -> Bool { if response.isFin && response.bytesLeft <= 0 { if response.code == .ping { let data = response.buffer! // local copy so it is perverse for writing dequeueWrite(data as Data, code: .pong) } else if response.code == .textFrame { let str: NSString? = NSString(data: response.buffer! as Data, encoding: String.Encoding.utf8.rawValue) if str == nil { writeError(CloseCode.encoding.rawValue) return false } if canDispatch { callbackQueue.async { [weak self] in guard let s = self else { return } s.onText?(str! as String) s.delegate?.websocketDidReceiveMessage(s, text: str! as String) } } } else if response.code == .binaryFrame { if canDispatch { let data = response.buffer! // local copy so it is perverse for writing callbackQueue.async { [weak self] in guard let s = self else { return } s.onData?(data as Data) s.delegate?.websocketDidReceiveData(s, data: data as Data) } } } readStack.removeLast() return true } return false } private func errorWithDetail(_ detail: String, code: UInt16) -> NSError { var details = [String: String]() details[NSLocalizedDescriptionKey] = detail return NSError(domain: WebSocket.ErrorDomain, code: Int(code), userInfo: details) } private func writeError(_ code: UInt16) { let buf = NSMutableData(capacity: MemoryLayout<UInt16>.size) let buffer = UnsafeMutableRawPointer(mutating: buf!.bytes).assumingMemoryBound(to: UInt8.self) WebSocket.writeUint16(buffer, offset: 0, value: code) dequeueWrite(Data(bytes: buffer, count: MemoryLayout<UInt16>.size), code: .connectionClose) } private func dequeueWrite(_ data: Data, code: OpCode, writeCompletion: (() -> ())? = nil) { writeQueue.addOperation { [weak self] in //stream isn't ready, let's wait guard let s = self else { return } var offset = 2 let dataLength = data.count let frame = NSMutableData(capacity: dataLength + s.MaxFrameSize) let buffer = UnsafeMutableRawPointer(frame!.mutableBytes).assumingMemoryBound(to: UInt8.self) buffer[0] = s.FinMask | code.rawValue if dataLength < 126 { buffer[1] = CUnsignedChar(dataLength) } else if dataLength <= Int(UInt16.max) { buffer[1] = 126 WebSocket.writeUint16(buffer, offset: offset, value: UInt16(dataLength)) offset += MemoryLayout<UInt16>.size } else { buffer[1] = 127 WebSocket.writeUint64(buffer, offset: offset, value: UInt64(dataLength)) offset += MemoryLayout<UInt64>.size } buffer[1] |= s.MaskMask let maskKey = UnsafeMutablePointer<UInt8>(buffer + offset) _ = SecRandomCopyBytes(kSecRandomDefault, Int(MemoryLayout<UInt32>.size), maskKey) offset += MemoryLayout<UInt32>.size for i in 0..<dataLength { buffer[offset] = data[i] ^ maskKey[i % MemoryLayout<UInt32>.size] offset += 1 } var total = 0 while true { guard let outStream = s.outputStream else { break } let writeBuffer = UnsafeRawPointer(frame!.bytes+total).assumingMemoryBound(to: UInt8.self) let len = outStream.write(writeBuffer, maxLength: offset-total) if len < 0 { var error: Error? if let streamError = outStream.streamError { error = streamError } else { let errCode = InternalErrorCode.outputStreamWriteError.rawValue error = s.errorWithDetail("output stream error during write", code: errCode) } s.doDisconnect(error as NSError?) break } else { total += len } if total >= offset { if let queue = self?.callbackQueue, let callback = writeCompletion { queue.async { callback() } } break } } } } private func doDisconnect(_ error: NSError?) { guard !didDisconnect else { return } didDisconnect = true connected = false guard canDispatch else {return} callbackQueue.async { [weak self] in guard let s = self else { return } s.onDisconnect?(error) s.delegate?.websocketDidDisconnect(s, error: error) let userInfo = error.map { [WebsocketDisconnectionErrorKeyName: $0] } s.notificationCenter.post(name: NSNotification.Name(WebsocketDidDisconnectNotification), object: self, userInfo: userInfo) } } // MARK: - Deinit deinit { mutex.lock() readyToWrite = false mutex.unlock() cleanupStream() } } private extension Data { init(buffer: UnsafeBufferPointer<UInt8>) { self.init(bytes: buffer.baseAddress!, count: buffer.count) } } private extension UnsafeBufferPointer { func fromOffset(_ offset: Int) -> UnsafeBufferPointer<Element> { return UnsafeBufferPointer<Element>(start: baseAddress?.advanced(by: offset), count: count - offset) } } private let emptyBuffer = UnsafeBufferPointer<UInt8>(start: nil, count: 0)
mit
7b186a79c70867d51526a125048d3604
39.945042
139
0.57518
5.471978
false
false
false
false
fabiomassimo/eidolon
Kiosk/Bid Fulfillment/ManualCreditCardInputViewModel.swift
1
2851
import Foundation import ReactiveCocoa import Swift_RAC_Macros import Stripe public class ManualCreditCardInputViewModel: NSObject { /// MARK: - Things the user is entering (expecting to be bound to signals) public dynamic var cardFullDigits = "" public dynamic var expirationMonth = "" public dynamic var expirationYear = "" public private(set) var bidDetails: BidDetails! public private(set) var finishedSubject: RACSubject? /// Mark: - Public members public init(bidDetails: BidDetails!, finishedSubject: RACSubject? = nil) { super.init() self.bidDetails = bidDetails self.finishedSubject = finishedSubject } public var creditCardNumberIsValidSignal: RACSignal { return RACObserve(self, "cardFullDigits").map(stripeManager.stringIsCreditCard) } public var expiryDatesAreValidSignal: RACSignal { let monthSignal = RACObserve(self, "expirationMonth").map(isStringLengthIn(1..<3)) let yearSignal = RACObserve(self, "expirationYear").map(isStringLengthOneOf([2,4])) return RACSignal.combineLatest([yearSignal, monthSignal]).and() } public var moveToYearSignal: RACSignal { return RACObserve(self, "expirationMonth").filter { (value) -> Bool in return count(value as! String) == 2 } } public func registerButtonCommand() -> RACCommand { let newUser = bidDetails.newUser let enabled = RACSignal.combineLatest([creditCardNumberIsValidSignal, expiryDatesAreValidSignal]).and() return RACCommand(enabled: enabled) { [weak self] _ in (self?.registerCardSignal(newUser) ?? RACSignal.empty())?.doCompleted { () -> Void in self?.finishedSubject?.sendCompleted() } } } public func isEntryValid(entry: String) -> Bool { // Allow delete if (count(entry) == 0) { return true } // the API doesn't accept chars let notNumberChars = NSCharacterSet.decimalDigitCharacterSet().invertedSet; return count(entry.stringByTrimmingCharactersInSet(notNumberChars)) != 0 } /// MARK: - Private Methods private func registerCardSignal(newUser: NewUser) -> RACSignal { let month = expirationMonth.toUInt(defaultValue: 0) let year = expirationYear.toUInt(defaultValue: 0) return stripeManager.registerCard(cardFullDigits, month: month, year: year).doNext() { (object) in let token = object as! STPToken newUser.creditCardName = token.card.name newUser.creditCardType = token.card.brand.name newUser.creditCardToken = token.tokenId newUser.creditCardDigit = token.card.last4 } } // Only public for testing purposes public lazy var stripeManager: StripeManager = StripeManager() }
mit
dd20a53433b972969f38c3f9c4a34ea6
34.6375
111
0.6745
4.865188
false
false
false
false
honghaoz/CrackingTheCodingInterview
Swift/LeetCode/Array/437_Path Sum III.swift
1
4229
// 437_Path Sum III // https://leetcode.com/problems/path-sum-iii // // Created by Honghao Zhang on 9/18/19. // Copyright © 2019 Honghaoz. All rights reserved. // // Description: // You are given a binary tree in which each node contains an integer value. // //Find the number of paths that sum to a given value. // //The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes). // //The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000. // //Example: // //root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8 // // 10 // / \ // 5 -3 // / \ \ // 3 2 11 // / \ \ //3 -2 1 // //Return 3. The paths that sum to 8 are: // //1. 5 -> 3 //2. 5 -> 2 -> 1 //3. -3 -> 11 // import Foundation class Num437 { /// Divide and conquer func pathSum(_ root: TreeNode?, _ sum: Int) -> Int { // base case if root == nil { return 0 } if root!.left == nil, root!.right == nil { return (sum == root!.val) ? 1 : 0 } // divide // case1, only in the left branch let leftCount = pathSum(root?.left, sum) // case2, only in the right branch let rightCount = pathSum(root?.right, sum) // case3, path contains root let leftCountWithoutRoot = pathSumFromRoot(root?.left, sum - root!.val) let rightCountWithoutRoot = pathSumFromRoot(root?.right, sum - root!.val) // case4, end at root // merge return leftCount + rightCount + leftCountWithoutRoot + rightCountWithoutRoot + ((sum == root!.val) ? 1 : 0) } /// Find paths count that starts with root private func pathSumFromRoot(_ root: TreeNode?, _ sum: Int) -> Int { if root == nil { return 0 } if root!.left == nil, root!.right == nil { return (root!.val == sum) ? 1 : 0 } let left = pathSumFromRoot(root!.left, sum - root!.val) let right = pathSumFromRoot(root!.right, sum - root!.val) return left + right + ((root!.val == sum) ? 1 : 0) } // https://leetcode.com/problems/path-sum-iii/discuss/91889/Simple-Java-DFS/284664 // 写递归的技巧是:明白一个函数的作用并相信它能完成这个任务,千万不要跳进这个函数里面企图探究更多细节,否则就会陷入无穷的细节无法自拔。你就算浑身是铁,能压几个栈? // // 按照前面说的技巧,先来定义清楚每个递归函数应该做的事: // pathSum 函数:给他一个节点和一个目标值,他返回以这个节点为根的树中,和为目标值的路径总数。 // count 函数:给他一个节点和一个目标值,他返回以这个节点为根的树中,能凑出几个以该节点为路径开头,和为目标值的路径总数。 // // /* 有了以上铺垫,详细注释一下代码 */ // int pathSum(TreeNode root, int sum) { // if (root == null) return 0; // int pathImLeading = count(root, sum); // 自己为开头的路径数 // int leftPathSum = pathSum(root.left, sum); // 左边路径总数(相信他能算出来) // int rightPathSum = pathSum(root.right, sum); // 右边路径总数(相信他能算出来) // return leftPathSum + rightPathSum + pathImLeading; // } // int count(TreeNode node, int sum) { // if (node == null) return 0; // // 我自己能不能独当一面,作为一条单独的路径呢? // int isMe = (node.val == sum) ? 1 : 0; // // 左边的小老弟,你那边能凑几个 sum - node.val 呀? // int leftBrother = count(node.left, sum - node.val); // // 右边的小老弟,你那边能凑几个 sum - node.val 呀? // int rightBrother = count(node.right, sum - node.val); // return isMe + leftBrother + rightBrother; // 我这能凑这么多个 // } // 还是那句话,明白每个函数能做的事,并相信他们能够完成。 // 我的公众号有篇长文讲如何写递归算法,希望能帮到大家。文章链接(https://mp.weixin.qq.com/s?__biz=MzU0MDg5OTYyOQ==&mid=100000105&idx=1&sn=83337f6a4486d4433378491a2ae395dc&chksm=7b33612b4c44e83d7afe591454829ff3e26253bdebd8304e5eb87d4083668cb0712a2c0b8096#rd) }
mit
4e6b771c4d592fa68183b9e9514ab501
32.728155
227
0.628382
2.602247
false
false
false
false
AKIRA-MIYAKE/SFObjectSwift
SFObjectSwift/Client.swift
1
6595
// // Client.swift // SFObjectSwift // // Created by MiyakeAkira on 2015/07/05. // Copyright (c) 2015年 Miyake Akira. All rights reserved. // import Foundation import Alamofire import Result import SFOAuth import SwiftyJSON public typealias Id = String public class Client<T: SObjectProtocol> { // MARK: - let private let createResponseParser: CreateResponseParser private let queryResponseParser: QueryResponseParser<T> // MARK: - Initialize public init(queryResponseParser: QueryResponseParser<T>) { self.createResponseParser = CreateResponseParser() self.queryResponseParser = queryResponseParser } public init(createResponseParser: CreateResponseParser, queryResponseParser: QueryResponseParser<T>) { self.createResponseParser = createResponseParser self.queryResponseParser = queryResponseParser } // MARK: - Public method public func create(sObject: T, _ completion: Result<Id, NSError> -> Void) { typealias CreateResut = Result<Id, NSError> if let credentail = OAuth.credentialStore.credential { getCreateRequest(sObject, credential: credentail) .responseJSON { (request, response, data, error) -> Void in if let error = error { let result = CreateResut.failure(error) completion(result) } else { if let data: AnyObject = data { if self.verifySessionId(data) { let result = self.createResponseParser.parse(data) completion(result) } else { OAuth.refresh { result in switch result { case .Success(let box): self.create(sObject, completion) case .Failure(let box): let result = CreateResut.failure(box.value) completion(result) } } } } else { // TODO: Add error code let error = NSError(domain: ErrorDomain, code: 0, userInfo: nil) let result = CreateResut.failure(error) completion(result) } } } } else { // TODO: Add error code let error = NSError(domain: ErrorDomain, code: 0, userInfo: nil) let result = CreateResut.failure(error) completion(result) } } public func query(#options: String?, _ completion: Result<[T], NSError> -> Void) { typealias QueryResult = Result<[T], NSError> if let credential = OAuth.credentialStore.credential { getQueryRequest(options: options, credential: credential) .responseJSON { (request, response, data, error) -> Void in if let error = error { let result = QueryResult.failure(error) completion(result) } else { if let data: AnyObject = data { if self.verifySessionId(data) { let result = self.queryResponseParser.parse(data) completion(result) } else { OAuth.refresh { result in switch result { case .Success(let box): self.query(options: options, completion) case .Failure(let box): let result = QueryResult.failure(box.value) completion(result) } } } } else { // TODO: Add error code let error = NSError(domain: ErrorDomain, code: 0, userInfo: nil) let result = QueryResult.failure(error) completion(result) } } } } else { // TODO: Add error code let error = NSError(domain: ErrorDomain, code: 0, userInfo: nil) let result = QueryResult.failure(error) completion(result) } } // MARK: - Private method private func verifySessionId(data: AnyObject) -> Bool { let json = JSON(data) if let errorCode = json[0]["errorCode"].string { if errorCode == "INVALID_SESSION_ID" { return false } else { return true } } else { return true } } private func getCreateRequest(sObject:T, credential: Credential) -> Alamofire.Request { let manager = Alamofire.Manager.sharedInstance manager.session.configuration.HTTPAdditionalHeaders = [ "Authorization": "Bearer \(credential.accessToken)" ] let URLString = "\(credential.instanceURL)/services/data/\(Service.appVersion)/sobjects/\(T.AppName)" let parameters = sObject.toDictionary() return Alamofire.request(.POST, URLString, parameters: parameters, encoding: .JSON) } private func getQueryRequest(#options: String?, credential: Credential) -> Alamofire.Request { let manager = Alamofire.Manager.sharedInstance manager.session.configuration.HTTPAdditionalHeaders = [ "Authorization": "Bearer \(credential.accessToken)" ] let URLString = "\(credential.instanceURL)/services/data/\(Service.appVersion)/query" let fields = ",".join(T.AppFieldNames) var q = "SELECT \(fields) FROM \(T.AppName)" if let options = options { q = q + " \(options)" } let parameters: [String: AnyObject] = ["q": q] return Alamofire.request(.GET, URLString, parameters: parameters) } }
mit
a823615338510ee498b89f062ec5fb0d
37.337209
109
0.487183
5.819064
false
false
false
false
sjf0213/DingShan
DingshanSwift/DingshanSwift/ForumReplyCell.swift
1
1275
// // ForumReplyCell.swift // DingshanSwift // // Created by song jufeng on 15/9/9. // Copyright (c) 2015年 song jufeng. All rights reserved. // import Foundation class ForumReplyCell : UITableViewCell{ private var content = UILabel() override init(style astyle:UITableViewCellStyle, reuseIdentifier str:String?) { super.init(style:astyle, reuseIdentifier:str) self.backgroundColor = UIColor.blueColor().colorWithAlphaComponent(0.2) content = UILabel(frame: CGRect(x: 89.0, y: 12, width: self.bounds.size.width - 89 - 15, height: 38)) content.font = UIFont.systemFontOfSize(15.0) content.numberOfLines = 2; content.text = "..." self.contentView.addSubview(content) let topline = UIView(frame: CGRect(x: 15.0, y: HomeRow_H-0.5, width: self.bounds.width - 30.0, height: 0.5)) topline.backgroundColor = UIColor(white: 216/255.0, alpha: 1.0) self.contentView.addSubview(topline) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func clearData() { content.text = "" } func loadCellData(data:ForumReplyData) { content.text = data.contentText } }
mit
db13350c0d2bb668bc5ef53e90951c0d
30.85
116
0.64022
3.892966
false
false
false
false
fgengine/quickly
Quickly/Extensions/NSNumber.swift
1
761
// // Quickly // public extension NSNumber { class func number(from string: String) -> NSNumber? { let formatter = NumberFormatter() formatter.locale = Locale.current; formatter.formatterBehavior = .behavior10_4; formatter.numberStyle = .none; var number = formatter.number(from: string) if number == nil { if formatter.decimalSeparator == "." { formatter.decimalSeparator = "," } else { formatter.decimalSeparator = "." } number = formatter.number(from: string) } return number } class func number(from string: Substring) -> NSNumber? { return self.number(from: String(string)) } }
mit
fbc7d2df6b9d9e0d68116c24192fafe7
25.241379
60
0.562418
4.878205
false
false
false
false
crspybits/SyncServerII
Tests/ServerTests/SharingAccountsController_RedeemSharingInvitation.swift
1
20331
// // SharingAccountsController_RedeemSharingInvitation.swift // Server // // Created by Christopher Prince on 4/12/17. // // import XCTest @testable import Server import LoggerAPI import Foundation import SyncServerShared class SharingAccountsController_RedeemSharingInvitation: ServerTestCase, LinuxTestable { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testThatRedeemingWithASharingAccountWorks() { let sharingUser:TestAccount = .primarySharingAccount let owningUser:TestAccount = .primaryOwningAccount var sharingGroupUUID: String! var newSharingUserId: UserId! createSharingUser(sharingUser: sharingUser, owningUserWhenCreating: owningUser) { userId, sid, _ in sharingGroupUUID = sid newSharingUserId = userId } guard sharingGroupUUID != nil else { XCTFail() return } checkOwingUserForSharingGroupUser(sharingGroupUUID: sharingGroupUUID, sharingUserId: newSharingUserId, sharingUser: sharingUser, owningUser: owningUser) } // Requires that Facebook creds be up to date. func testThatRedeemingWithANonOwningSharingAccountWorks() { let sharingUser:TestAccount = .nonOwningSharingAccount let owningUser:TestAccount = .primaryOwningAccount var sharingGroupUUID: String! var newSharingUserId: UserId! createSharingUser(sharingUser: sharingUser, owningUserWhenCreating: owningUser) { userId, sid, _ in sharingGroupUUID = sid newSharingUserId = userId } guard sharingGroupUUID != nil else { XCTFail() return } guard checkOwingUserForSharingGroupUser(sharingGroupUUID: sharingGroupUUID, sharingUserId: newSharingUserId, sharingUser: sharingUser, owningUser: owningUser) else { XCTFail() return } guard let (_, sharingGroups) = getIndex(testAccount: sharingUser), sharingGroups.count > 0 else { XCTFail() return } var found = false for sharingGroup in sharingGroups { if sharingGroup.sharingGroupUUID == sharingGroupUUID { guard let cloudStorageType = sharingGroup.cloudStorageType else { XCTFail() return } XCTAssert(owningUser.scheme.cloudStorageType == cloudStorageType) found = true } } XCTAssert(found) } func testThatRedeemingUsingGoogleAccountWithoutCloudFolderNameFails() { let permission:Permission = .write let sharingUser:TestAccount = .google2 let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } var sharingInvitationUUID:String! createSharingInvitation(permission: permission, sharingGroupUUID:sharingGroupUUID) { expectation, invitationUUID in sharingInvitationUUID = invitationUUID expectation.fulfill() } redeemSharingInvitation(sharingUser:sharingUser, canGiveCloudFolderName: false, sharingInvitationUUID: sharingInvitationUUID, errorExpected: true) { result, expectation in expectation.fulfill() } } func redeemingASharingInvitationWithoutGivingTheInvitationUUIDFails(sharingUser: TestAccount) { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } redeemSharingInvitation(sharingUser: sharingUser, errorExpected:true) { _, expectation in expectation.fulfill() } } func testThatRedeemingASharingInvitationByAUserWithoutGivingTheInvitationUUIDFails() { redeemingASharingInvitationWithoutGivingTheInvitationUUIDFails(sharingUser: .primarySharingAccount) } func testThatRedeemingWithTheSameAccountAsTheOwningAccountFails() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } var sharingInvitationUUID:String! createSharingInvitation(permission: .read, sharingGroupUUID: sharingGroupUUID) { expectation, invitationUUID in sharingInvitationUUID = invitationUUID expectation.fulfill() } redeemSharingInvitation(sharingUser: .primaryOwningAccount, sharingInvitationUUID: sharingInvitationUUID, errorExpected:true) { _, expectation in expectation.fulfill() } } // 8/12/18; This now works-- i.e., you can redeem with other owning accounts-- because each user can now be in multiple sharing groups. (Prior to this, it was a failure test!). func testThatRedeemingWithAnExistingOtherOwningAccountWorks() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID1 = Foundation.UUID().uuidString let owningAccount:TestAccount = .primaryOwningAccount guard let _ = self.addNewUser(testAccount: owningAccount, sharingGroupUUID: sharingGroupUUID1, deviceUUID:deviceUUID) else { XCTFail() return } var sharingInvitationUUID:String! createSharingInvitation(testAccount: owningAccount, permission: .read, sharingGroupUUID:sharingGroupUUID1) { expectation, invitationUUID in sharingInvitationUUID = invitationUUID expectation.fulfill() } let secondOwningAccount:TestAccount = .secondaryOwningAccount let deviceUUID2 = Foundation.UUID().uuidString let sharingGroupUUID2 = Foundation.UUID().uuidString addNewUser(testAccount: secondOwningAccount, sharingGroupUUID: sharingGroupUUID2, deviceUUID:deviceUUID2) var result: RedeemSharingInvitationResponse! redeemSharingInvitation(sharingUser: secondOwningAccount, sharingInvitationUUID: sharingInvitationUUID) { response, expectation in result = response expectation.fulfill() } guard result != nil else { XCTFail() return } checkOwingUserForSharingGroupUser(sharingGroupUUID: sharingGroupUUID2, sharingUserId: result.userId, sharingUser: secondOwningAccount, owningUser: owningAccount) } // Redeem sharing invitation for existing user: Works if user isn't already in sharing group func testThatRedeemingWithAnExistingOtherSharingAccountWorks() { redeemWithAnExistingOtherSharingAccount() } func redeemingForSameSharingGroupFails(sharingUser: TestAccount) { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } var sharingInvitationUUID:String! createSharingInvitation(permission: .read, sharingGroupUUID: sharingGroupUUID) { expectation, invitationUUID in sharingInvitationUUID = invitationUUID expectation.fulfill() } redeemSharingInvitation(sharingUser: sharingUser, sharingInvitationUUID: sharingInvitationUUID) { _, expectation in expectation.fulfill() } // Check to make sure we have a new user: let userKey = UserRepository.LookupKey.accountTypeInfo(accountType: sharingUser.scheme.accountName, credsId: sharingUser.id()) let userResults = UserRepository(self.db).lookup(key: userKey, modelInit: User.init) guard case .found(_) = userResults else { XCTFail() return } let key = SharingInvitationRepository.LookupKey.sharingInvitationUUID(uuid: sharingInvitationUUID) let results = SharingInvitationRepository(self.db).lookup(key: key, modelInit: SharingInvitation.init) guard case .noObjectFound = results else { XCTFail() return } createSharingInvitation(permission: .write, sharingGroupUUID: sharingGroupUUID) { expectation, invitationUUID in sharingInvitationUUID = invitationUUID expectation.fulfill() } // Since the user account represented by sharingUser is already a member of the sharing group referenced by the specific sharingGroupUUID, this redeem attempt will fail. redeemSharingInvitation(sharingUser: sharingUser, sharingInvitationUUID: sharingInvitationUUID, errorExpected: true) { _, expectation in expectation.fulfill() } } func testThatRedeemingForSameSharingGroupFails() { redeemingForSameSharingGroupFails(sharingUser: .primarySharingAccount) } func checkingCredsOnASharingUserGivesSharingPermission(sharingUser: TestAccount) { let perm:Permission = .write var actualSharingGroupUUID: String? var newSharingUserId:UserId! let owningUser:TestAccount = .primaryOwningAccount createSharingUser(withSharingPermission: perm, sharingUser: sharingUser, owningUserWhenCreating: owningUser) { userId, sharingGroupUUID, _ in actualSharingGroupUUID = sharingGroupUUID newSharingUserId = userId } guard newSharingUserId != nil, actualSharingGroupUUID != nil, let (_, groups) = getIndex(testAccount: sharingUser) else { XCTFail() return } let filtered = groups.filter {$0.sharingGroupUUID == actualSharingGroupUUID} guard filtered.count == 1 else { XCTFail() return } checkOwingUserForSharingGroupUser(sharingGroupUUID: actualSharingGroupUUID!, sharingUserId: newSharingUserId, sharingUser: sharingUser, owningUser: owningUser) XCTAssert(filtered[0].permission == perm, "Actual: \(String(describing: filtered[0].permission)); expected: \(perm)") } func testThatCheckingCredsOnASharingUserGivesSharingPermission() { checkingCredsOnASharingUserGivesSharingPermission(sharingUser: .primarySharingAccount) } func testThatCheckingCredsOnARootOwningUserGivesAdminSharingPermission() { let deviceUUID = Foundation.UUID().uuidString let sharingGroupUUID = Foundation.UUID().uuidString guard let _ = self.addNewUser(sharingGroupUUID: sharingGroupUUID, deviceUUID:deviceUUID) else { XCTFail() return } guard let (_, groups) = getIndex() else { XCTFail() return } let filtered = groups.filter {$0.sharingGroupUUID == sharingGroupUUID} guard filtered.count == 1 else { XCTFail() return } XCTAssert(filtered[0].permission == .admin) } func testThatDeletingSharingUserWorks() { createSharingUser(sharingUser: .primarySharingAccount) let deviceUUID = Foundation.UUID().uuidString // remove performServerTest(testAccount: .primarySharingAccount) { expectation, creds in let headers = self.setupHeaders(testUser: .primarySharingAccount, accessToken: creds.accessToken, deviceUUID:deviceUUID) self.performRequest(route: ServerEndpoints.removeUser, headers: headers) { response, dict in Log.info("Status code: \(response!.statusCode)") XCTAssert(response!.statusCode == .OK, "removeUser failed") expectation.fulfill() } } } func testThatRedeemingWithAnExistingOwningAccountWorks() { // Create an owning user, A -- this also creates sharing group 1 // Create another owning user, B (also creates a sharing group) // A creates sharing invitation to sharing group 1. // B redeems sharing invitation. let deviceUUID = Foundation.UUID().uuidString let permission:Permission = .read let sharingGroupUUID1 = Foundation.UUID().uuidString guard let _ = self.addNewUser(testAccount: .primaryOwningAccount, sharingGroupUUID: sharingGroupUUID1, deviceUUID:deviceUUID) else { XCTFail() return } let sharingGroupUUID2 = Foundation.UUID().uuidString guard let _ = self.addNewUser(testAccount: .secondaryOwningAccount, sharingGroupUUID: sharingGroupUUID2, deviceUUID:deviceUUID) else { XCTFail() return } var sharingInvitationUUID:String! createSharingInvitation(testAccount: .primaryOwningAccount, permission: permission, sharingGroupUUID:sharingGroupUUID1) { expectation, invitationUUID in sharingInvitationUUID = invitationUUID expectation.fulfill() } var redeemResult: RedeemSharingInvitationResponse? redeemSharingInvitation(sharingUser: .secondaryOwningAccount, sharingInvitationUUID: sharingInvitationUUID) { result, expectation in XCTAssert(result?.userId != nil && result?.sharingGroupUUID != nil) redeemResult = result expectation.fulfill() } guard redeemResult != nil else { XCTFail() return } checkOwingUserForSharingGroupUser(sharingGroupUUID: sharingGroupUUID1, sharingUserId: redeemResult!.userId, sharingUser: .secondaryOwningAccount, owningUser: .primaryOwningAccount) } func testRedeemingSharingInvitationThatHasAlreadyBeenRedeemedFails() { let sharingUser1:TestAccount = .primarySharingAccount let sharingUser2:TestAccount = .secondarySharingAccount let owningUser:TestAccount = .primaryOwningAccount var sharingGroupUUID: String! var newSharingUserId: UserId! var sharingInvitationUUID: String! createSharingUser(sharingUser: sharingUser1, owningUserWhenCreating: owningUser) { userId, sid, sharingInviteUUID in sharingGroupUUID = sid newSharingUserId = userId sharingInvitationUUID = sharingInviteUUID } guard sharingGroupUUID != nil, newSharingUserId != nil else { XCTFail() return } redeemSharingInvitation(sharingUser:sharingUser2, sharingInvitationUUID: sharingInvitationUUID, errorExpected: true) { result, expectation in expectation.fulfill() } } func testTwoAcceptorsSharingInvitationCanBeRedeemedTwice() { let sharingUser1:TestAccount = .primarySharingAccount let sharingUser2:TestAccount = .secondarySharingAccount let owningUser:TestAccount = .primaryOwningAccount var sharingGroupUUID: String! var newSharingUserId: UserId! var sharingInvitationUUID: String! createSharingUser(sharingUser: sharingUser1, owningUserWhenCreating: owningUser, numberAcceptors: 2) { userId, sid, sharingInviteUUID in sharingGroupUUID = sid newSharingUserId = userId sharingInvitationUUID = sharingInviteUUID } guard sharingGroupUUID != nil, newSharingUserId != nil else { XCTFail() return } redeemSharingInvitation(sharingUser:sharingUser2, sharingInvitationUUID: sharingInvitationUUID) { result, expectation in expectation.fulfill() } // Make sure the sharing invitation has now been removed. let key = SharingInvitationRepository.LookupKey.sharingInvitationUUID(uuid: sharingInvitationUUID) let results = SharingInvitationRepository(self.db).lookup(key: key, modelInit: SharingInvitation.init) guard case .noObjectFound = results else { XCTFail() return } } func testNonSocialSharingInvitationRedeemedSociallyFails() { let sharingUser:TestAccount = .nonOwningSharingAccount let owningUser:TestAccount = .primaryOwningAccount createSharingUser(sharingUser: sharingUser, owningUserWhenCreating: owningUser, allowSharingAcceptance: false, failureExpected: true) { userId, sid, sharingInviteUUID in } } func testNonSocialSharingInvitationRedeemedNonSociallyWorks() { let sharingUser:TestAccount = .secondaryOwningAccount let owningUser:TestAccount = .primaryOwningAccount createSharingUser(sharingUser: sharingUser, owningUserWhenCreating: owningUser, allowSharingAcceptance: false) { userId, sid, sharingInviteUUID in } } } extension SharingAccountsController_RedeemSharingInvitation { static var allTests : [(String, (SharingAccountsController_RedeemSharingInvitation) -> () throws -> Void)] { return [ ("testThatRedeemingWithASharingAccountWorks", testThatRedeemingWithASharingAccountWorks), ("testThatRedeemingWithANonOwningSharingAccountWorks", testThatRedeemingWithANonOwningSharingAccountWorks), ("testThatRedeemingUsingGoogleAccountWithoutCloudFolderNameFails", testThatRedeemingUsingGoogleAccountWithoutCloudFolderNameFails), ("testThatRedeemingASharingInvitationByAUserWithoutGivingTheInvitationUUIDFails", testThatRedeemingASharingInvitationByAUserWithoutGivingTheInvitationUUIDFails), ("testThatRedeemingWithTheSameAccountAsTheOwningAccountFails", testThatRedeemingWithTheSameAccountAsTheOwningAccountFails), ("testThatRedeemingWithAnExistingOtherOwningAccountWorks", testThatRedeemingWithAnExistingOtherOwningAccountWorks), ("testThatRedeemingWithAnExistingOtherSharingAccountWorks", testThatRedeemingWithAnExistingOtherSharingAccountWorks), ("testThatRedeemingForSameSharingGroupFails", testThatRedeemingForSameSharingGroupFails), ("testThatCheckingCredsOnASharingUserGivesSharingPermission", testThatCheckingCredsOnASharingUserGivesSharingPermission), ("testThatCheckingCredsOnARootOwningUserGivesAdminSharingPermission", testThatCheckingCredsOnARootOwningUserGivesAdminSharingPermission), ("testThatDeletingSharingUserWorks", testThatDeletingSharingUserWorks), ("testThatRedeemingWithAnExistingOwningAccountWorks", testThatRedeemingWithAnExistingOwningAccountWorks), ("testRedeemingSharingInvitationThatHasAlreadyBeenRedeemedFails", testRedeemingSharingInvitationThatHasAlreadyBeenRedeemedFails), ("testTwoAcceptorsSharingInvitationCanBeRedeemedTwice", testTwoAcceptorsSharingInvitationCanBeRedeemedTwice), ("testNonSocialSharingInvitationRedeemedSociallyFails", testNonSocialSharingInvitationRedeemedSociallyFails), ("testNonSocialSharingInvitationRedeemedNonSociallyWorks", testNonSocialSharingInvitationRedeemedNonSociallyWorks) ] } func testLinuxTestSuiteIncludesAllTests() { linuxTestSuiteIncludesAllTests(testType: SharingAccountsController_RedeemSharingInvitation.self) } }
mit
6e1d0d0b14e10bcf826d52f09d2bb9ce
40.833333
188
0.675717
5.550369
false
true
false
false
hayashi311/iosdcjp2016app
iOSApp/iOSDCJP2016/VoteCodeInputViewController.swift
1
2024
// // VoteCodeInputViewController.swift // iOSDCJP2016 // // Created by Ryota Hayashi on 2016/07/14. // Copyright © 2016年 hayashi311. All rights reserved. // import UIKit import APIKit import URLNavigator import SVProgressHUD class VoteCodeInputViewController: UIViewController { @IBOutlet weak var label: UILabel! @IBOutlet weak var textField: UITextField! @IBOutlet weak var doneButton: UIBarButtonItem! var nid: String! override func viewDidLoad() { super.viewDidLoad() label.attributedText = NSAttributedString(string: "投票コードを入力してください", style: .Body) textField.addTarget(self, action: #selector(self.handleInput(_:)), forControlEvents: .EditingChanged) doneButton.enabled = enableToSave() } override func viewDidAppear(animated: Bool) { textField.becomeFirstResponder() } func enableToSave() -> Bool { if let voteCode = textField.text where voteCode.characters.count > 3 { return true } return false } func handleInput(sender: UITextField) { doneButton.enabled = enableToSave() } @IBAction func handleSaveButtonTapped(sender: UIBarButtonItem) { guard let voteCode = textField.text else { return } NSUserDefaults.standardUserDefaults().vodeCode = voteCode textField.resignFirstResponder() SVProgressHUD.show() let r = WebAPI.VoteRequest(ono: voteCode, nid: nid) APIKit.Session.sendRequest(r) { [weak self] result in switch result { case .Success: SVProgressHUD.showSuccessWithStatus("Yeah!") SVProgressHUD.dismissWithDelay(0.5) self?.performSegueWithIdentifier("Exit", sender: self) case let .Failure(e): SVProgressHUD.showErrorWithStatus("oh...") } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
mit
fbfa48d29e43cf000875cf78628ef4af
29.19697
109
0.648269
4.896806
false
false
false
false
RickieL/learn-swift
swift-properties.playground/section-1.swift
1
4527
// Playground - noun: a place where people can play import UIKit var str = "Hello, playground" struct FixedLengthRange { var firstValue: Int let length: Int } // stored properties var rangeOfThreeItems = FixedLengthRange(firstValue: 0, length: 3) rangeOfThreeItems.firstValue = 6 for i in 0..<rangeOfThreeItems.length { println(rangeOfThreeItems.firstValue+i) } // stored properties of constant structure instances let rangeOfFourItems = FixedLengthRange(firstValue: 0, length: 4) // rangeOfFourItems.firstValue = 6 // The same is not true for classes, which are reference types. // If you assign an instance of a reference type to a constant, // you can still change that instance’s variable properties. // lazy stored properties class DataImporter { var fileName = "data.txt" } class DataManager { lazy var importer = DataImporter() var data = [String]() } let manager = DataManager() manager.data.append("Some data") manager.data.append("Some more data") println(manager.importer.fileName) // stored properties and instance variables // computed properties struct Point { var x = 0.0, y = 0.0 } struct Size { var width = 0.0, height = 0.0 } struct Rect { var origin = Point() var size = Size() var center: Point { get { let centerX = origin.x + (size.width / 2) let centerY = origin.y + (size.height / 2) return Point(x: centerX, y: centerY) } set(newCenter) { origin.x = newCenter.x - (size.width / 2) origin.y = newCenter.y - (size.height / 2) } } } var square = Rect(origin: Point(x: 0.0, y: 0.0), size: Size(width: 12.0, height: 8.0)) let initalSquareCenter = square.center square.center = Point(x: 20.0, y: 15.0) println("square.origin is now at (\(initalSquareCenter.x), \(initalSquareCenter.y))") // shorthand setter declaration struct AlternativeRect { var origin = Point() var size = Size() var center: Point { get { let centerX = origin.x + (size.width / 2) let centerY = origin.y + (size.height / 2) return Point(x: centerX, y: centerY) } set { origin.x = newValue.x - (size.width / 2) origin.y = newValue.y - (size.height / 2) } } } // read-only computed properties struct Cuboid { var width = 0.0, height = 0.0, depth = 0.0 var volume: Double { return width * height * depth } } let fourByFiveByTwo = Cuboid(width: 4.0, height: 5.0, depth: 2.0) println("the volume of the cuboid is \(fourByFiveByTwo.volume)") // property observers class StepCounter { var totalSteps: Int = 0 { willSet(newTotalSteps) { println("About to set totalSteps to \(newTotalSteps)") } didSet { if totalSteps > oldValue { println("Added \(totalSteps - oldValue) steps") } } } } let stepCounter = StepCounter() stepCounter.totalSteps = 200 stepCounter.totalSteps = 201 // global and local variables // type properties struct SomeStructure { static var storedTypeProperty = "Some value" static var computedTypeProperty: Int { // return Int value here return 40 } } enum SomeEnumeration { static var storedTypeProperty = "Some enum Value" static var computedTypeProperty: Int { return 41 } } class SomeClass { class var computedTypeProperty: Int { return 42 } } // querying and setting type properties println(SomeClass.computedTypeProperty) println(SomeStructure.storedTypeProperty) println(SomeEnumeration.storedTypeProperty) SomeStructure.storedTypeProperty = "Another value." println(SomeStructure.storedTypeProperty) struct AudioChannel { static let thresholdLevel = 10 static var maxInputLevelForAllChannels = 0 var currentLevel: Int = 0 { didSet { if currentLevel > AudioChannel.thresholdLevel { currentLevel = AudioChannel.thresholdLevel } if currentLevel > AudioChannel.maxInputLevelForAllChannels { AudioChannel.maxInputLevelForAllChannels = currentLevel } } } } var leftChannel = AudioChannel() var rightChannel = AudioChannel() leftChannel.currentLevel = 7 println(leftChannel.currentLevel) println(AudioChannel.maxInputLevelForAllChannels) rightChannel.currentLevel = 11 println(rightChannel.currentLevel) println(AudioChannel.maxInputLevelForAllChannels)
bsd-3-clause
2f9a97c615adc3a6c0fb08a79c19790e
24.421348
86
0.66011
3.962347
false
false
false
false
tnantoka/generative-swift
GenerativeSwift/Controllers/DrawingBrushViewController.swift
1
5216
// // DrawingBrushViewController.swift // GenerativeSwift // // Created by Tatsuya Tobioka on 5/3/16. // Copyright © 2016 tnantoka. All rights reserved. // import UIKit import C4 class DrawingBrushViewController: DensityAgentViewController { var lineLength = 0.0 var angle = 0.0 var angleSpeed = 0.0 var color = Color() let defaultColor = Color(red: 181, green: 157, blue: 0, alpha: 1) override init() { super.init() title = "Drawing with Animated Brushes" trash = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() let colorItems: [UIBarButtonItem] = (1...5).map { i in let item = UIBarButtonItem(title: "\(i)", style: .plain, target: self, action: #selector(colorTapped)) item.tag = i return item } let arrowItems: [UIBarButtonItem] = ["↑", "↓", "←", "→"].enumerated().map { i, t in let item = UIBarButtonItem(title: t, style: .plain, target: self, action: #selector(arrowTapped)) item.tag = i return item } let auto = UIBarButtonItem(title: "Auto", style: .plain, target: self, action: #selector(autoTapped)) let reverse = UIBarButtonItem(title: "Reverse", style: .plain, target: self, action: #selector(reverseTapped)) let flexible = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) toolbarItems = [flexible, auto, flexible, reverse, flexible] + colorItems + [flexible] + arrowItems + [flexible] } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) start() } override func setup() { super.setup() } override func draw() { guard mousePressed else { return } drawLine() } func drawLine() { let x = point.x + cos(degToRad(angle)) * lineLength let y = point.y + sin(degToRad(angle)) * lineLength let line = Line(begin: point, end: Point(x, y)) line.strokeColor = color canvas.add(line) angle += angleSpeed } override func clearPoints() { changeLength() angle = 0.0 angleSpeed = 1.0 color = defaultColor } func reverseTapped(_ sender: AnyObject) { reverse() } func colorTapped(_ sender: AnyObject) { changeColor(sender.tag) } func arrowTapped(_ sender: AnyObject) { switch sender.tag { case 0?: lineLength += 5 case 1?: lineLength -= 5 case 2?: angleSpeed -= 0.5 case 3?: angleSpeed += 0.5 default: fatalError() } } func changeLength() { lineLength = Double(random(min: 50, max: 160)) } func changeColor(_ tag: Int?) { switch tag { case 1?: color = defaultColor case 2?: color = Color(red: 0, green: 130, blue: 164, alpha: 1) case 3?: color = Color(red: 87, green: 35, blue: 129, alpha: 1) case 4?: color = Color(red: 197, green: 0, blue: 123, alpha: 1) case 5?: color = Color( red: random(min: 0, max: 255), green: random(min: 0, max: 255), blue: random(min: 0, max: 255), alpha: Double(random(min: 80, max: 150)) / 255.0 ) default: fatalError() } } func reverse() { angle += 180 angleSpeed *= -1 } func autoTapped(_ sender: AnyObject) { clear() mousePressed = false point = canvas.center let randomColor = random(min: 0, max: 3) != 0 ? true : false let randomLength = random(min: 0, max: 3) != 0 ? true : false let randomSpeed = random(min: 0, max: 3) == 0 ? true : false let decrease = (!randomLength && random(min: 0, max: 4) == 0) ? true : false let withReverse = random(min: 0, max: 5) == 0 ? true : false changeColor(random(min: 1, max: 6)) let count = random(min: 1, max: 50) (0..<count).forEach { i in let steps = random(min: 10, max: 40) (0..<steps).forEach { j in if randomColor && j % 5 == 0 { changeColor(random(min: 1, max: 6)) } if randomLength && j % 10 == 0 { changeLength() } if randomSpeed && j % 15 == 0 { angleSpeed += Double(random(min: -100, max: 100)) / 100 } drawLine() } if decrease { lineLength -= Double(random(min: 0, max: min(4, Int(lineLength)))) } if withReverse && i % 3 == 0 { reverse() } } } }
apache-2.0
b511ff3e280fe35d6d5a3282e8e8ee68
27.767956
120
0.498944
4.335554
false
false
false
false
PJayRushton/TeacherTools
TeacherTools/RandomizerDatasource.swift
1
4516
// // RandomizerDataSource.swift // TeacherTools // // Created by Parker Rushton on 11/6/16. // Copyright © 2016 AppsByPJ. All rights reserved. // import UIKit class RandomizerDataSource: NSObject, UICollectionViewDataSource { var core = App.core var students = [Student]() var absentStudents = [Student]() var teamSize = 2 var group: Group? { didSet { guard group != oldValue else { return } absentStudents.removeAll() } } var remainder: Int { return students.count % teamSize } deinit { core.remove(subscriber: self) } override init() { super.init() core.add(subscriber: self) } var numberOfTeams: Int { // Rule of thumb: if there are more than 2 remainder students, they form their own group var standardNumberOfTeams = students.count / teamSize if absentStudents.count > 0 { standardNumberOfTeams += 1 // Absent students have their own section } if remainder == 2 && teamSize == 3 { // If team size is 3 and there are exactly 2 remaining, they also form their own group return standardNumberOfTeams + 1 } return remainder > 2 ? standardNumberOfTeams + 1 : standardNumberOfTeams } func teamSize(forSection section: Int) -> Int { let hasAbsentSection = absentStudents.count > 0 let isLastSection = hasAbsentSection ? section == numberOfTeams - 2 : section == numberOfTeams - 1 if hasAbsentSection && section == numberOfTeams - 1 { return absentStudents.count } switch remainder { case 0: return teamSize case 1: if isLastSection { return teamSize + 1 } return teamSize default: if isLastSection { return remainder } return teamSize } } func students(inSection section: Int) -> [Student] { if absentStudents.count > 0 && section == numberOfTeams - 1 { return absentStudents } let lowBoundSection = section == 0 ? 0 : section - 1 let lowBound = section * teamSize(forSection: lowBoundSection) let highBound = lowBound + teamSize(forSection: section) return students.step(from: lowBound, to: highBound) } func student(at indexPath: IndexPath) -> Student { return students(inSection: indexPath.section)[indexPath.row] } func title(forSection section: Int) -> String { if section == numberOfTeams - 1 && absentStudents.count > 0 { return "ABSENT" } var headerString = "Team \(section + 1)" if teamSize(forSection: section) != teamSize { headerString += " (\(teamSize(forSection: section)))" } return headerString } func numberOfSections(in collectionView: UICollectionView) -> Int { return numberOfTeams } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return students(inSection: section).count } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: RandomizerHeaderView.reuseIdentifier, for: indexPath) as! RandomizerHeaderView header.update(with: title(forSection: indexPath.section), theme: core.state.theme) return header } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: RandomizerCollectionViewCell.reuseIdentifier, for: indexPath) as! RandomizerCollectionViewCell cell.update(with: student(at: indexPath), theme: core.state.theme) return cell } } // MARK: - Subscriber extension RandomizerDataSource: Subscriber { func update(with state: AppState) { students = state.currentStudents absentStudents = state.absentStudents guard let selectedGroup = state.selectedGroup else { teamSize = 2; return } teamSize = selectedGroup.teamSize group = selectedGroup } }
mit
a62d0de2a44e4082291b89cb5dd9e7a4
31.956204
182
0.627243
5.084459
false
false
false
false
lilongcnc/Swift-weibo2015
ILWEIBO04/ILWEIBO04/Classes/UI/Profile/ProfileViewController.swift
1
3312
// // ProfileViewController.swift // ILWEIBO04 // // Created by 李龙 on 15/3/6. // Copyright (c) 2015年 Lauren. All rights reserved. // import UIKit class ProfileViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return 0 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as! UITableViewCell // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ }
mit
229a6e15e4d028c9e8a6321ba0a1a5e9
33.082474
157
0.683303
5.519199
false
false
false
false
gregomni/swift
test/Generics/concrete_conflict.swift
2
1394
// RUN: %target-swift-frontend -typecheck -verify %s -debug-generic-signatures -requirement-machine-protocol-signatures=on -requirement-machine-inferred-signatures=on 2>&1 | %FileCheck %s protocol P1 { associatedtype T where T == Int } protocol P2 { associatedtype T where T == String } protocol P3 { associatedtype T where T == Float } // We end up with two redundant rules: // // [P4:T].[P1:T].[concrete: String] // [P4:T].[P1:T].[concrete: Float] // // These rules are unordered with respect to each other because concrete type // symbols are incomparable, but they conflict so we should not compare them; // just make sure we don't crash. // CHECK-LABEL: .P4@ // CHECK-LABEL: Requirement signature: <Self where Self.[P4]T : P1, Self.[P4]T : P2, Self.[P4]T : P3> // expected-error@+3{{no type for 'Self.T.T' can satisfy both 'Self.T.T == String' and 'Self.T.T == Int'}} // expected-error@+2{{no type for 'Self.T.T' can satisfy both 'Self.T.T == Float' and 'Self.T.T == Int'}} // expected-error@+1{{no type for 'Self.T.T' can satisfy both 'Self.T.T == Float' and 'Self.T.T == String'}} protocol P4 { associatedtype T : P1 & P2 & P3 } class Class<T> {} extension Class where T == Bool { // CHECK-LABEL: .badRequirement()@ // CHECK-NEXT: <T> func badRequirement() where T == Int { } // expected-error@-1 {{no type for 'T' can satisfy both 'T == Int' and 'T == Bool'}} }
apache-2.0
b330d0df6a5e6369a966802e4e39299a
33
187
0.664275
3.063736
false
false
false
false
dhanvi/firefox-ios
Sync/Synchronizers/ClientsSynchronizer.swift
2
14127
/* 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 import Storage import XCGLogger private let log = Logger.syncLogger private let ClientsStorageVersion = 1 // TODO public protocol Command { static func fromName(command: String, args: [JSON]) -> Command? func run(synchronizer: ClientsSynchronizer) -> Success static func commandFromSyncCommand(syncCommand: SyncCommand) -> Command? } // Shit. // We need a way to wipe or reset engines. // We need a way to log out the account. // So when we sync commands, we're gonna need a delegate of some kind. public class WipeCommand: Command { public init?(command: String, args: [JSON]) { return nil } public class func fromName(command: String, args: [JSON]) -> Command? { return WipeCommand(command: command, args: args) } public func run(synchronizer: ClientsSynchronizer) -> Success { return succeed() } public static func commandFromSyncCommand(syncCommand: SyncCommand) -> Command? { let json = JSON.parse(syncCommand.value) if let name = json["command"].asString, args = json["args"].asArray { return WipeCommand.fromName(name, args: args) } return nil } } public class DisplayURICommand: Command { let uri: NSURL let title: String public init?(command: String, args: [JSON]) { if let uri = args[0].asString?.asURL, title = args[2].asString { self.uri = uri self.title = title } else { // Oh, Swift. self.uri = "http://localhost/".asURL! self.title = "" return nil } } public class func fromName(command: String, args: [JSON]) -> Command? { return DisplayURICommand(command: command, args: args) } public func run(synchronizer: ClientsSynchronizer) -> Success { synchronizer.delegate.displaySentTabForURL(uri, title: title) return succeed() } public static func commandFromSyncCommand(syncCommand: SyncCommand) -> Command? { let json = JSON.parse(syncCommand.value) if let name = json["command"].asString, args = json["args"].asArray { return DisplayURICommand.fromName(name, args: args) } return nil } } let Commands: [String: (String, [JSON]) -> Command?] = [ "wipeAll": WipeCommand.fromName, "wipeEngine": WipeCommand.fromName, // resetEngine // resetAll // logout "displayURI": DisplayURICommand.fromName, ] public class ClientsSynchronizer: TimestampedSingleCollectionSynchronizer, Synchronizer { public required init(scratchpad: Scratchpad, delegate: SyncDelegate, basePrefs: Prefs) { super.init(scratchpad: scratchpad, delegate: delegate, basePrefs: basePrefs, collection: "clients") } override var storageVersion: Int { return ClientsStorageVersion } var clientRecordLastUpload: Timestamp { set(value) { self.prefs.setLong(value, forKey: "lastClientUpload") } get { return self.prefs.unsignedLongForKey("lastClientUpload") ?? 0 } } public func getOurClientRecord() -> Record<ClientPayload> { let guid = self.scratchpad.clientGUID let json = JSON([ "id": guid, "version": "0.1", // TODO "protocols": ["1.5"], "name": self.scratchpad.clientName, "os": "iOS", "commands": [JSON](), "type": "mobile", "appPackage": NSBundle.mainBundle().bundleIdentifier ?? "org.mozilla.ios.FennecUnknown", "application": DeviceInfo.appName(), "device": DeviceInfo.deviceModel(), // Do better here: Bug 1157518. "formfactor": DeviceInfo.isSimulator() ? "simulator" : "phone", ]) let payload = ClientPayload(json) return Record(id: guid, payload: payload, ttl: ThreeWeeksInSeconds) } private func clientRecordToLocalClientEntry(record: Record<ClientPayload>) -> RemoteClient { let modified = record.modified let payload = record.payload return RemoteClient(json: payload, modified: modified) } // If this is a fresh start, do a wipe. // N.B., we don't wipe outgoing commands! (TODO: check this when we implement commands!) // N.B., but perhaps we should discard outgoing wipe/reset commands! private func wipeIfNecessary(localClients: RemoteClientsAndTabs) -> Success { if self.lastFetched == 0 { return localClients.wipeClients() } return succeed() } /** * Returns whether any commands were found (and thus a replacement record * needs to be uploaded). Also returns the commands: we run them after we * upload a replacement record. */ private func processCommandsFromRecord(record: Record<ClientPayload>?, withServer storageClient: Sync15CollectionClient<ClientPayload>) -> Deferred<Maybe<(Bool, [Command])>> { log.debug("Processing commands from downloaded record.") // TODO: short-circuit based on the modified time of the record we uploaded, so we don't need to skip ahead. if let record = record { let commands = record.payload.commands if !commands.isEmpty { func parse(json: JSON) -> Command? { if let name = json["command"].asString, args = json["args"].asArray, constructor = Commands[name] { return constructor(name, args) } return nil } // TODO: can we do anything better if a command fails? return deferMaybe((true, optFilter(commands.map(parse)))) } } return deferMaybe((false, [])) } private func uploadClientCommands(toLocalClients localClients: RemoteClientsAndTabs, withServer storageClient: Sync15CollectionClient<ClientPayload>) -> Success { return localClients.getCommands() >>== { clientCommands in return clientCommands.map { (clientGUID, commands) -> Success in self.syncClientCommands(clientGUID, commands: commands, clientsAndTabs: localClients, withServer: storageClient) }.allSucceed() } } private func syncClientCommands(clientGUID: GUID, commands: [SyncCommand], clientsAndTabs: RemoteClientsAndTabs, withServer storageClient: Sync15CollectionClient<ClientPayload>) -> Success { let deleteCommands: () -> Success = { return clientsAndTabs.deleteCommands(clientGUID).bind({ x in return succeed() }) } log.debug("Fetching current client record for client \(clientGUID).") let fetch = storageClient.get(clientGUID) return fetch.bind() { result in if let response = result.successValue { let record = response.value if var clientRecord = record.payload.asDictionary { clientRecord["commands"] = JSON(record.payload.commands + commands.map { JSON.parse($0.value) }) let uploadRecord = Record(id: clientGUID, payload: ClientPayload(JSON(clientRecord)), ttl: ThreeWeeksInSeconds) return storageClient.put(uploadRecord, ifUnmodifiedSince: record.modified) >>== { resp in log.debug("Client \(clientGUID) commands upload succeeded.") // Always succeed, even if we couldn't delete the commands. return deleteCommands() } } } else { if let failure = result.failureValue { log.warning("Failed to fetch record with GUID \(clientGUID).") if failure is NotFound<NSHTTPURLResponse> { log.debug("Not waiting to see if the client comes back.") // TODO: keep these around and retry, expiring after a while. // For now we just throw them away so we don't fail every time. return deleteCommands() } if failure is BadRequestError<NSHTTPURLResponse> { log.debug("We made a bad request. Throwing away queued commands.") return deleteCommands() } } } log.error("Client \(clientGUID) commands upload failed: No remote client for GUID") return deferMaybe(UnknownError()) } } /** * Upload our record if either (a) we know we should upload, or (b) * our own notes tell us we're due to reupload. */ private func maybeUploadOurRecord(should: Bool, ifUnmodifiedSince: Timestamp?, toServer storageClient: Sync15CollectionClient<ClientPayload>) -> Success { let lastUpload = self.clientRecordLastUpload let expired = lastUpload < (NSDate.now() - (2 * OneDayInMilliseconds)) log.debug("Should we upload our client record? Caller = \(should), expired = \(expired).") if !should && !expired { return succeed() } let iUS: Timestamp? = ifUnmodifiedSince ?? ((lastUpload == 0) ? nil : lastUpload) return storageClient.put(getOurClientRecord(), ifUnmodifiedSince: iUS) >>== { resp in if let ts = resp.metadata.lastModifiedMilliseconds { // Protocol says this should always be present for success responses. log.debug("Client record upload succeeded. New timestamp: \(ts).") self.clientRecordLastUpload = ts } return succeed() } } private func applyStorageResponse(response: StorageResponse<[Record<ClientPayload>]>, toLocalClients localClients: RemoteClientsAndTabs, withServer storageClient: Sync15CollectionClient<ClientPayload>) -> Success { log.debug("Applying clients response.") let records = response.value let responseTimestamp = response.metadata.lastModifiedMilliseconds log.debug("Got \(records.count) client records.") let ourGUID = self.scratchpad.clientGUID var toInsert = [RemoteClient]() var ours: Record<ClientPayload>? = nil for (rec) in records { if rec.id == ourGUID { if rec.modified == self.clientRecordLastUpload { log.debug("Skipping our own unmodified record.") } else { log.debug("Saw our own record in response.") ours = rec } } else { toInsert.append(self.clientRecordToLocalClientEntry(rec)) } } // Apply remote changes. // Collect commands from our own record and reupload if necessary. // Then run the commands and return. return localClients.insertOrUpdateClients(toInsert) >>== { self.processCommandsFromRecord(ours, withServer: storageClient) } >>== { (shouldUpload, commands) in return self.maybeUploadOurRecord(shouldUpload, ifUnmodifiedSince: ours?.modified, toServer: storageClient) >>> { self.uploadClientCommands(toLocalClients: localClients, withServer: storageClient) } >>> { log.debug("Running \(commands.count) commands.") for (command) in commands { command.run(self) } self.lastFetched = responseTimestamp! return succeed() } } } public func synchronizeLocalClients(localClients: RemoteClientsAndTabs, withServer storageClient: Sync15StorageClient, info: InfoCollections) -> SyncResult { log.debug("Synchronizing clients.") if let reason = self.reasonToNotSync(storageClient) { switch reason { case .EngineRemotelyNotEnabled: // This is a hard error for us. return deferMaybe(FatalError(message: "clients not mentioned in meta/global. Server wiped?")) default: return deferMaybe(SyncStatus.NotStarted(reason)) } } let keys = self.scratchpad.keys?.value let encoder = RecordEncoder<ClientPayload>(decode: { ClientPayload($0) }, encode: { $0 }) let encrypter = keys?.encrypter(self.collection, encoder: encoder) if encrypter == nil { log.error("Couldn't make clients encrypter.") return deferMaybe(FatalError(message: "Couldn't make clients encrypter.")) } let clientsClient = storageClient.clientForCollection(self.collection, encrypter: encrypter!) if !self.remoteHasChanges(info) { log.debug("No remote changes for clients. (Last fetched \(self.lastFetched).)") return self.maybeUploadOurRecord(false, ifUnmodifiedSince: nil, toServer: clientsClient) >>> { self.uploadClientCommands(toLocalClients: localClients, withServer: clientsClient) } >>> { deferMaybe(.Completed) } } // TODO: some of the commands we process might involve wiping collections or the // entire profile. We should model this as an explicit status, and return it here // instead of .Completed. return clientsClient.getSince(self.lastFetched) >>== { response in return self.wipeIfNecessary(localClients) >>> { self.applyStorageResponse(response, toLocalClients: localClients, withServer: clientsClient) } } >>> { deferMaybe(.Completed) } } }
mpl-2.0
28bd0a6a576c367284ad9216cdbc23d0
40.307018
218
0.603667
5.265375
false
false
false
false
ACChe/eidolon
Kiosk/Bid Fulfillment/RegisterViewController.swift
1
2532
import UIKit import ReactiveCocoa @objc protocol RegistrationSubController { // I know, leaky abstraction, but the amount // of useless syntax to change it isn't worth it. var finishedSignal: RACSubject { get } } class RegisterViewController: UIViewController { @IBOutlet var flowView: RegisterFlowView! @IBOutlet var bidDetailsPreviewView: BidDetailsPreviewView! @IBOutlet var confirmButton: UIButton! let coordinator = RegistrationCoordinator() dynamic var placingBid = true func internalNavController() -> UINavigationController? { return self.childViewControllers.first as? UINavigationController } override func viewDidLoad() { super.viewDidLoad() coordinator.storyboard = self.storyboard! let registerIndexSignal = RACObserve(coordinator, "currentIndex").takeUntil(viewWillDisappearSignal()) let indexIsConfirmSignal = registerIndexSignal.map { return ($0 as! Int == RegistrationIndex.ConfirmVC.toInt()) } RAC(confirmButton, "hidden") <~ indexIsConfirmSignal.not() RAC(flowView, "highlightedIndex") <~ registerIndexSignal let details = self.fulfillmentNav().bidDetails flowView.details = details bidDetailsPreviewView.bidDetails = details flowView.jumpToIndexSignal.subscribeNext { [weak self] (index) -> Void in if let _ = self?.fulfillmentNav() { let registrationIndex = RegistrationIndex.fromInt(index as! Int) let nextVC = self?.coordinator.viewControllerForIndex(registrationIndex) self?.goToViewController(nextVC!) } } goToNextVC() } func goToNextVC() { let nextVC = coordinator.nextViewControllerForBidDetails(fulfillmentNav().bidDetails) goToViewController(nextVC) } func goToViewController(controller: UIViewController) { self.internalNavController()!.viewControllers = [controller] if let subscribableVC = controller as? RegistrationSubController { subscribableVC.finishedSignal.subscribeCompleted { [weak self] in self?.goToNextVC() self?.flowView.update() } } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue == .ShowLoadingView { let nextViewController = segue.destinationViewController as! LoadingViewController nextViewController.placingBid = placingBid } } }
mit
5ea179a1783bfee5867aedb8b2a73b45
33.216216
121
0.680095
5.51634
false
false
false
false
insidegui/XPNotificationCenter
DemoApp/XPNCDemoApp/ViewController.swift
1
2379
// // ViewController.swift // XPNCDemoApp // // Created by Guilherme Rambo on 23/08/15. // Copyright (c) 2015 Guilherme Rambo. All rights reserved. // import UIKit class ViewController: UITableViewController { let dataSource = ItemDataSource() var items: [String] { get { return dataSource.items } set { dataSource.items = newValue } } @IBAction func addItem(sender: AnyObject) { var mutableItems = items mutableItems.append("Item \(items.count+1)") items = mutableItems tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: items.count-1, inSection: 0)], withRowAnimation: .Left) // send a notification to the watch extension so it knows the item list has changed XPNotificationCenter.defaultCenter.postNotificationName(NotificationNames.itemListAdded, sender: self) } func removeItem(index: Int) { var mutableItems = items mutableItems.removeAtIndex(index) items = mutableItems tableView.deleteRowsAtIndexPaths([NSIndexPath(forRow: index, inSection: 0)], withRowAnimation: .Right) // send a notification to the watch extension so it knows the item list has changed XPNotificationCenter.defaultCenter.postNotificationName(NotificationNames.itemListDeleted, sender: self) } override func viewDidLoad() { super.viewDidLoad() } deinit { XPNotificationCenter.defaultCenter.removeObserver(self) } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("row") as! UITableViewCell cell.textLabel?.text = items[indexPath.row] return cell } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { removeItem(indexPath.row) } } }
bsd-2-clause
96a6440e353a1b51d7d88f774658fe8f
29.896104
157
0.662884
5.443936
false
false
false
false
DylanSecreast/uoregon-cis-portfolio
uoregon-cis-399/examples/LendingLibrary/LendingLibrary/Source/Controller/LentItemDetailViewController.swift
1
19291
// // LentItemDetailViewController.swift // LendingLibrary // // Created by Charles Augustine. // // import Contacts import ContactsUI import MessageUI import MobileCoreServices import UIKit import UserNotifications class LentItemDetailViewController: UITableViewController, UITextFieldDelegate, CNContactPickerDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, MFMailComposeViewControllerDelegate { // MARK: IBAction @IBAction private func cancel(_ sender: AnyObject) { delegate.lentItemDetailViewControllerDidFinish(self) } @IBAction private func save(_ sender: AnyObject) { if let someBorrowerID = borrowerID { do { try LendingLibraryService.shared.addLentItem(withName: name, borrower: borrower, borrowerID: someBorrowerID, dateBorrowed: dateBorrowed, dateToReturn: dateToReturn, reminder: reminder, and: picture, in: selectedCategory) delegate.lentItemDetailViewControllerDidFinish(self) } catch _ { let alertController = UIAlertController(title: "Save failed", message: "Failed to save the new lent item", preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) present(alertController, animated: true, completion: nil) } } else { let alertController = UIAlertController(title: "Borrower required", message: "Please select a borrower from your contacts", preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) present(alertController, animated: true, completion: nil) } } @IBAction private func datePickerDidChange(_ sender: UIDatePicker) { if dateBorrowedTextField.isFirstResponder { dateBorrowed = sender.date dateBorrowedLabel.text = dateFormatter.string(from: dateBorrowed) if (dateToReturn as NSDate).earlierDate(dateBorrowed) == dateToReturn { dateToReturn = dateBorrowed dateToReturnLabel.text = dateFormatter.string(from: dateToReturn) } } else { dateToReturn = sender.date dateToReturnLabel.text = dateFormatter.string(from: dateToReturn) if (dateToReturn as NSDate).earlierDate(dateBorrowed) == dateToReturn { dateBorrowed = dateToReturn dateBorrowedLabel.text = dateFormatter.string(from: dateBorrowed) } } } @IBAction private func datePickerDidFinish(_ sender: AnyObject) { view.endEditing(true) } @IBAction private func reminderSwitchToggled(_ sender: AnyObject) { checkNotificationAuthorizationStatus { (authorized) in if authorized { self.reminder = self.reminderSwitch.isOn } else { self.reminder = false self.reminderSwitch.setOn(false, animated: true) } } } @IBAction private func clearPicture(_ sender: AnyObject) { self.view.endEditing(true) let alertController = UIAlertController(title: nil, message: "Are you sure you want to delete the picture?", preferredStyle: .actionSheet) alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) alertController.addAction(UIAlertAction(title: "Delete Picture", style: .destructive, handler: { (action: UIAlertAction) -> Void in self.picture = nil self.updateUIForPicture() })) present(alertController, animated: true, completion: nil) } @IBAction private func sendReminderEmail(_ sender: AnyObject) { checkContactAuthorizationStatus() { var success = false if let borrowerID = self.borrowerID { let fetchRequest = CNContactFetchRequest(keysToFetch: [CNContactEmailAddressesKey as CNKeyDescriptor]) fetchRequest.predicate = CNContact.predicateForContacts(withIdentifiers: [borrowerID]) let contactStore = CNContactStore() var borrowerContact: CNContact? = nil do { try contactStore.enumerateContacts(with: fetchRequest, usingBlock: { (contact, stop) -> Void in borrowerContact = contact stop.pointee = true }) if let someBorrowerContact = borrowerContact, let emailAddress = someBorrowerContact.emailAddresses.first?.value as? String { success = true self.presentMailCompositionView(withRecipient: emailAddress) } else { print("Contact not found or contact has no email address") } } catch let error { print("Error trying to enumerate contacts: \(error as NSError)") } } else { print("No borrower ID set") } if !success { let alertController = UIAlertController(title: "No Recipient Found", message: "Could not send reminder to \(self.borrower)", preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) self.present(alertController, animated: true, completion: nil) } } } // MARK: UITableViewDelegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch LentItemRow.items[indexPath.row] { case .name: nameTextField.becomeFirstResponder() case .borrower: self.presentContactPicker() case .dateBorrowed: datePicker.date = dateBorrowed dateBorrowedTextField.becomeFirstResponder() case .dateToReturn: datePicker.date = dateToReturn dateToReturnTextField.becomeFirstResponder() case .reminder: checkNotificationAuthorizationStatus({ (authorized) in if authorized { self.reminder = !self.reminder self.reminderSwitch.setOn(self.reminder, animated: true) } else { self.reminder = false self.reminderSwitch.setOn(false, animated: true) } }) case .picture: if picture == nil { let alertController = UIAlertController(title: nil, message: "Pick Image Source", preferredStyle: .actionSheet) let checkSourceType = { (sourceType: UIImagePickerControllerSourceType, buttonText: String) -> Void in if UIImagePickerController.isSourceTypeAvailable(sourceType) { alertController.addAction(UIAlertAction(title: buttonText, style: .default, handler: self.imagePickerControllerSourceTypeActionHandler(for: sourceType))) } } checkSourceType(.camera, "Camera") checkSourceType(.photoLibrary, "Photo Library") checkSourceType(.savedPhotosAlbum, "Saved Photos Album") if !alertController.actions.isEmpty { alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) present(alertController, animated: true, completion: nil) } } } } // MARK: UITextFieldDelegate func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { name = ((textField.text ?? "") as NSString).replacingCharacters(in: range, with: string) return true } func textFieldShouldClear(_ textField: UITextField) -> Bool { return true } func textFieldShouldReturn(_ textField: UITextField) -> Bool { nameTextField.resignFirstResponder() return false } // MARK: CNContactPickerDelegate func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) { borrowerID = contact.identifier let contactFormatter = CNContactFormatter() contactFormatter.style = .fullName if let someName = contactFormatter.string(from: contact) { borrower = someName } else { borrower = "Unnamed" } dismiss(animated: true, completion: nil) } func contactPickerDidCancel(_ picker: CNContactPickerViewController) { dismiss(animated: true, completion: nil) } // MARK: UIImagePickerControllerDelegate func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { // First check for an edited image, then the original image if let image = info[UIImagePickerControllerEditedImage] as? UIImage { picture = image } else if let image = info[UIImagePickerControllerOriginalImage] as? UIImage { picture = image } updateUIForPicture() dismiss(animated: true, completion: nil) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true, completion: nil) } // MARK: MFMailComposeViewControllerDelegate func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { dismiss(animated: true, completion: nil) } // MARK: Private private func checkContactAuthorizationStatus(_ contactOperation: @escaping () -> Void) { switch CNContactStore.authorizationStatus(for: .contacts) { case .authorized: contactOperation() case .notDetermined: let contactStore = CNContactStore() contactStore.requestAccess(for: .contacts, completionHandler: { (granted: Bool, error: Error?) -> Void in if granted { contactOperation() } else { let alertController = UIAlertController(title: "Contacts Error", message: "Contacts access is required, please check your privacy settings and try again.", preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) self.present(alertController, animated: true, completion: nil) } }) default: let alertController = UIAlertController(title: "Contacts Error", message: "Contacts access is required, please check your privacy settings and try again.", preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) present(alertController, animated: true, completion: nil) } } private func presentContactPicker() { checkContactAuthorizationStatus { let contactPickerViewController = CNContactPickerViewController() contactPickerViewController.delegate = self self.present(contactPickerViewController, animated: true, completion: nil) } } private func updateUIForPicture(animated: Bool = true) { if animated { if let somePicture = picture, pictureImageView.isHidden { pictureImageView.image = somePicture self.pictureImageView.transform = CGAffineTransform(scaleX: 0.01, y: 0.01).rotated(by: CGFloat(-M_PI)) pictureImageView.isHidden = false clearPictureButton.alpha = 0.0 clearPictureButton.isHidden = false UIView.animate(withDuration: 0.2, animations: { () -> Void in self.pictureImageView.transform = CGAffineTransform.identity self.clearPictureButton.alpha = 1.0 self.addPictureLabel.alpha = 0.0 }, completion: { (complete) -> Void in self.addPictureLabel.alpha = 1.0 self.addPictureLabel.isHidden = true }) } else { addPictureLabel.alpha = 0.0 addPictureLabel.isHidden = false UIView.animate(withDuration: 0.2, animations: { () -> Void in self.pictureImageView.transform = CGAffineTransform(scaleX: 0.01, y: 0.01).rotated(by: CGFloat(M_PI)) self.clearPictureButton.alpha = 0.0 self.addPictureLabel.alpha = 1.0 }, completion: { (complete) -> Void in self.pictureImageView.image = nil self.pictureImageView.transform = CGAffineTransform.identity self.pictureImageView.isHidden = true self.clearPictureButton.alpha = 1.0 self.clearPictureButton.isHidden = true }) } } else { if let somePicture = picture { pictureImageView.isHidden = false pictureImageView.image = somePicture clearPictureButton.isHidden = false addPictureLabel.isHidden = true } else { pictureImageView.isHidden = true pictureImageView.image = nil clearPictureButton.isHidden = true addPictureLabel.isHidden = false } } } private func checkNotificationAuthorizationStatus(_ notificationOperation: @escaping (Bool) -> Void) { UNUserNotificationCenter.current().getNotificationSettings { (settings) in let authorized = settings.authorizationStatus == .authorized if !authorized { let alertController = UIAlertController(title: "Notifications Not Allowed", message: "Check your privacy settings and try again", preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) self.present(alertController, animated: true, completion: nil) } // This callback happens off the main queue, so dispatch the notification operation back to the main queue DispatchQueue.main.async { notificationOperation(authorized) } } } private func presentMailCompositionView(withRecipient recipient: String) { if MFMailComposeViewController.canSendMail() { let mailComposeViewController = MFMailComposeViewController() mailComposeViewController.mailComposeDelegate = self mailComposeViewController.setToRecipients([recipient]) mailComposeViewController.setSubject("Reminder") mailComposeViewController.setMessageBody("Please remember to return \(name) at your earliest convenience", isHTML: false) present(mailComposeViewController, animated: true, completion: nil) } else { let alertController = UIAlertController(title: "Cannot Send Email", message: "Please got to your Settings app and configure an email account", preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) present(alertController, animated: true, completion: nil) } } private func imagePickerControllerSourceTypeActionHandler(for sourceType: UIImagePickerControllerSourceType) -> (_ action: UIAlertAction) -> Void { return { (action) in let imagePickerController = UIImagePickerController() imagePickerController.delegate = self imagePickerController.sourceType = sourceType imagePickerController.mediaTypes = [kUTTypeImage as String] // Import the MobileCoreServices framework to use kUTTypeImage (see top of file) imagePickerController.allowsEditing = true self.present(imagePickerController, animated: true, completion: nil) } } // MARK: View Management override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if selectedLentItem != nil { navigationItem.title = "Edit Lent Item" navigationItem.leftBarButtonItem = nil navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .compose, target: self, action: #selector(LentItemDetailViewController.sendReminderEmail(_:))) } else { navigationItem.title = "Add Lent Item" navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(LentItemDetailViewController.cancel(_:))) navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(LentItemDetailViewController.save(_:))) } nameTextField.text = name borrowerLabel.text = borrower dateBorrowedLabel.text = dateFormatter.string(from: dateBorrowed) dateToReturnLabel.text = dateFormatter.string(from: dateToReturn) reminderSwitch.isOn = reminder updateUIForPicture(animated: false) } override func viewWillDisappear(_ animated: Bool) { if isMovingFromParentViewController { if let someLentItem = selectedLentItem, let someBorrowerID = borrowerID { do { try LendingLibraryService.shared.update(someLentItem, withName: name, borrower: borrower, borrowerID: someBorrowerID, dateBorrowed: dateBorrowed, dateToReturn: dateToReturn, reminder: reminder, and: picture) } catch _ { let alertController = UIAlertController(title: "Save Failed", message: "Failed to update the lent item", preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) present(alertController, animated: true, completion: nil) } } } super.viewWillDisappear(animated) } // MARK: View Life Cycle override func viewDidLoad() { super.viewDidLoad() // Setup the accessory and accessory input views for the hidden text fields associated with the date labels datePicker = UIDatePicker(frame: CGRect.zero) datePicker.datePickerMode = .dateAndTime datePicker.addTarget(self, action: #selector(LentItemDetailViewController.datePickerDidChange(_:)), for: .valueChanged) let toolbar = UIToolbar(frame: CGRect(x: 0.0, y: 0.0, width: 0.0, height: 44.0)) toolbar.items = [UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil), UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(LentItemDetailViewController.datePickerDidFinish(_:)))] dateBorrowedTextField.inputView = datePicker dateBorrowedTextField.inputAccessoryView = toolbar dateToReturnTextField.inputView = datePicker dateToReturnTextField.inputAccessoryView = toolbar dateFormatter.dateStyle = .long dateFormatter.timeStyle = .medium } // MARK: Initialization required init!(coder aDecoder: NSCoder) { let now = Date() dateBorrowed = now var dateComponents = DateComponents() dateComponents.weekOfYear = 2 if let later = (Calendar.current as NSCalendar).date(byAdding: dateComponents, to: now, options: []) { dateToReturn = later } else { dateToReturn = now } super.init(coder: aDecoder) } // MARK: Properties var selectedCategory: Category! var selectedLentItem: LentItem? { didSet { if let someLentItem = selectedLentItem { name = someLentItem.name! borrower = someLentItem.borrower! borrowerID = someLentItem.borrowerID dateBorrowed = someLentItem.dateBorrowed! as Date dateToReturn = someLentItem.dateToReturn! as Date reminder = someLentItem.notify?.boolValue ?? false if let pictureData = someLentItem.picture?.data { picture = UIImage(data: pictureData as Data) } else { picture = nil } } else { name = LentItemDetailViewController.defaultName borrower = LentItemDetailViewController.defaultBorrower borrowerID = nil let now = Date() dateBorrowed = now var dateComponents = DateComponents() dateComponents.weekOfYear = 2 if let later = (Calendar.current as NSCalendar).date(byAdding: dateComponents, to: now, options: []) { dateToReturn = later } else { dateToReturn = now } reminder = false } } } var delegate: LentItemDetailViewControllerDelegate! // MARK: Properties (Private) private var name = LentItemDetailViewController.defaultName private var borrower = LentItemDetailViewController.defaultBorrower private var borrowerID: String? private var dateBorrowed: Date private var dateToReturn: Date private var reminder = false private var picture: UIImage? private var datePicker: UIDatePicker! private var dateFormatter = DateFormatter() // MARK: Properties (IBOutlet) @IBOutlet private weak var nameTextField: UITextField! @IBOutlet private weak var borrowerLabel: UILabel! @IBOutlet private weak var dateBorrowedLabel: UILabel! @IBOutlet private weak var dateBorrowedTextField: UITextField! @IBOutlet private weak var dateToReturnLabel: UILabel! @IBOutlet private weak var dateToReturnTextField: UITextField! @IBOutlet private weak var reminderSwitch: UISwitch! @IBOutlet private weak var pictureImageView: UIImageView! @IBOutlet private weak var addPictureLabel: UILabel! @IBOutlet private weak var clearPictureButton: UIButton! // MARK: Properties (Private Static Constant) private static let defaultName = "New Item" private static let defaultBorrower = "Someone Trustworthy" // LentItemRow private enum LentItemRow { case name case borrower case dateBorrowed case dateToReturn case reminder case picture static let items: Array<LentItemRow> = [.name, .borrower, .dateBorrowed, .dateToReturn, .reminder, .picture] } }
gpl-3.0
7bb3d7a91bdcc93a89d6226920d11866
35.955939
230
0.749883
4.208333
false
false
false
false
Monnoroch/Cuckoo
Generator/Dependencies/SourceKitten/Source/SourceKittenFramework/SourceLocation.swift
1
1843
// // SourceLocation.swift // SourceKitten // // Created by JP Simard on 10/27/15. // Copyright © 2015 SourceKitten. All rights reserved. // #if SWIFT_PACKAGE import Clang_C #endif import Foundation public struct SourceLocation { let file: String let line: UInt32 let column: UInt32 let offset: UInt32 public func range(toEnd end: SourceLocation) -> NSRange { return NSRange(location: Int(offset), length: Int(end.offset - offset)) } } extension SourceLocation { init(clangLocation: CXSourceLocation) { var cxfile: CXFile? = nil var line: UInt32 = 0 var column: UInt32 = 0 var offset: UInt32 = 0 clang_getSpellingLocation(clangLocation, &cxfile, &line, &column, &offset) self.init(file: clang_getFileName(cxfile).str() ?? "<none>", line: line, column: column, offset: offset) } } // MARK: Comparable extension SourceLocation: Comparable {} public func ==(lhs: SourceLocation, rhs: SourceLocation) -> Bool { return lhs.file.compare(rhs.file) == .orderedSame && lhs.line == rhs.line && lhs.column == rhs.column && lhs.offset == rhs.offset } /// A [strict total order](http://en.wikipedia.org/wiki/Total_order#Strict_total_order) /// over instances of `Self`. public func <(lhs: SourceLocation, rhs: SourceLocation) -> Bool { // Sort by file path. switch lhs.file.compare(rhs.file) { case .orderedDescending: return false case .orderedAscending: return true case .orderedSame: break } // Then offset. return lhs.offset < rhs.offset } // MARK: - migration support extension SourceLocation { @available(*, unavailable, renamed: "range(toEnd:)") public func rangeToEndLocation(_ end: SourceLocation) -> NSRange { fatalError() } }
mit
bf919b9ce5b4b45dd61a6ee48f786c9f
24.943662
87
0.64658
3.919149
false
false
false
false
PhilippeBoisney/SimpleFloatingActionButton
SimpleFloatingActionButton/SimpleFloatingActionButton.swift
1
9172
// // SimpleFloatingActionButton.swift // SimpleFloatingActionButton // // Created by Phil on 14/08/2015. // Copyright © 2015 CookMinute. All rights reserved. // import UIKit import QuartzCore @IBDesignable public class SimpleButton: UIButton { //PROPERTIES RIPPLE EFFECT - USAGE PROGRAMMATICALY public var ripplePercent: Float = 2.0 { didSet { setupRippleView() } } public var rippleColor: UIColor = UIColor(white: 0.9, alpha: 1) { didSet { rippleView.backgroundColor = rippleColor } } public var rippleBackgroundColor: UIColor = UIColor(white: 0.95, alpha: 1) { didSet { rippleBackgroundView.backgroundColor = rippleBackgroundColor } } private var rippleMask: CAShapeLayer? { get { if !rippleOverBounds { let maskLayer = CAShapeLayer() maskLayer.path = UIBezierPath(roundedRect: bounds, cornerRadius: layer.cornerRadius).CGPath return maskLayer } else { return nil } } } //PROPERTIES RIPPLE EFFECT - USAGE INTERFACE BUILDER @IBInspectable public var rippleOverBounds: Bool = false @IBInspectable public var shadowRippleRadius: Float = 1 @IBInspectable public var shadowRippleEnable: Bool = true @IBInspectable public var trackTouchLocation: Bool = false @IBInspectable public var buttonBackgroundColor: UIColor = UIColor(red:0.96, green:0.26, blue:0.21, alpha:1.0) //Red Color Material Design //FOR DESIGN private let rippleView = UIView() private let rippleBackgroundView = UIView() //FOR DATA private var tempShadowRadius: CGFloat = 0 private var tempShadowOpacity: Float = 0 //MARK: INITIALISERS required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! setup() } override init(frame: CGRect) { super.init(frame: frame) setup() } init () { super.init(frame: CGRectZero) setup() } //MARK: LIFE OF VIEW override public func layoutSubviews() { super.layoutSubviews() setupRippleView() let oldCenter = rippleView.center rippleView.center = oldCenter rippleBackgroundView.layer.frame = bounds rippleBackgroundView.layer.mask = rippleMask } //MARK: SETUP SimpleFloatingButton //General setup of the view private func setup() { setupViewFrame() setupRippleView() rippleBackgroundView.backgroundColor = rippleBackgroundColor rippleBackgroundView.frame = bounds layer.addSublayer(rippleBackgroundView.layer) layer.shadowOpacity = 0.5 layer.shadowOffset = CGSize(width: 0.0, height: 1.0) rippleBackgroundView.layer.addSublayer(rippleView.layer) rippleBackgroundView.alpha = 0 } //Setup the frame view private func setupViewFrame(){ //Defaull Value var dim: CGFloat = UIScreen.mainScreen().bounds.height / 8 var y: CGFloat = UIScreen.mainScreen().bounds.height - dim - 20 var x: CGFloat = UIScreen.mainScreen().bounds.width - dim - 20 if(UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation)) { dim = UIScreen.mainScreen().bounds.height / 6 y = UIScreen.mainScreen().bounds.height - dim - 20 x = UIScreen.mainScreen().bounds.width - dim - 20 } let newFrame: CGRect = CGRectMake(0, 0, dim, dim) self.frame = newFrame self.frame = CGRectMake(x, y, self.frame.height, self.frame.height) self.layer.cornerRadius = 0.5 * self.frame.height } //Setup the ripple effect private func setupRippleView() { let size: CGFloat = CGRectGetWidth(bounds) * CGFloat(ripplePercent) let x: CGFloat = (CGRectGetWidth(bounds)/2) - (size/2) let y: CGFloat = (CGRectGetHeight(bounds)/2) - (size/2) let corner: CGFloat = size/2 rippleView.backgroundColor = rippleColor rippleView.frame = CGRectMake(x, y, size, size) rippleView.layer.cornerRadius = corner } //Draw the cross on button override public func drawRect(rect: CGRect) { let path = UIBezierPath(ovalInRect: rect) buttonBackgroundColor.setFill() path.fill() //set up the width and height variables //for the horizontal stroke let plusHeight: CGFloat = 1.0 let plusWidth: CGFloat = min(bounds.width, bounds.height) * 0.3 //create the path let plusPath = UIBezierPath() //set the path's line width to the height of the stroke plusPath.lineWidth = plusHeight //move the initial point of the path //to the start of the horizontal stroke plusPath.moveToPoint(CGPoint( x:bounds.width/2 - plusWidth/2 + 0.5, y:bounds.height/2 + 0.5)) //add a point to the path at the end of the stroke plusPath.addLineToPoint(CGPoint( x:bounds.width/2 + plusWidth/2 + 0.5, y:bounds.height/2 + 0.5)) //Vertical Line //move to the start of the vertical stroke plusPath.moveToPoint(CGPoint( x:bounds.width/2 + 0.5, y:bounds.height/2 - plusWidth/2 + 0.5)) //add the end point to the vertical stroke plusPath.addLineToPoint(CGPoint( x:bounds.width/2 + 0.5, y:bounds.height/2 + plusWidth/2 + 0.5)) //set the stroke color UIColor.whiteColor().setStroke() //draw the stroke plusPath.stroke() } //MARK: Handles Touch Tracking and Animations override public func beginTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool { if trackTouchLocation { rippleView.center = touch.locationInView(self) } UIView.animateWithDuration(0.1, animations: { self.rippleBackgroundView.alpha = 1 }, completion: nil) rippleView.transform = CGAffineTransformMakeScale(0.1, 0.1) UIView.animateWithDuration(0.7, delay: 0, options: .CurveEaseOut, animations: { self.rippleView.transform = CGAffineTransformIdentity }, completion: nil) if shadowRippleEnable { tempShadowRadius = layer.shadowRadius tempShadowOpacity = layer.shadowOpacity let shadowAnim = CABasicAnimation(keyPath:"shadowRadius") shadowAnim.toValue = shadowRippleRadius let opacityAnim = CABasicAnimation(keyPath:"shadowOpacity") opacityAnim.toValue = 1 let groupAnim = CAAnimationGroup() groupAnim.duration = 0.7 groupAnim.fillMode = kCAFillModeForwards groupAnim.removedOnCompletion = false groupAnim.animations = [shadowAnim, opacityAnim] layer.addAnimation(groupAnim, forKey:"shadow") } return super.beginTrackingWithTouch(touch, withEvent: event) } override public func cancelTrackingWithEvent(event: UIEvent?) { super.cancelTrackingWithEvent(event) animateToNormal() } override public func endTrackingWithTouch(touch: UITouch?, withEvent event: UIEvent?) { super.endTrackingWithTouch(touch, withEvent: event) animateToNormal() } private func animateToNormal(){ UIView.animateWithDuration(0.1, animations: { self.rippleBackgroundView.alpha = 1 }, completion: {(success: Bool) -> () in UIView.animateWithDuration(0.6 , animations: { self.rippleBackgroundView.alpha = 0 }, completion: nil) } ) UIView.animateWithDuration(0.7, delay: 0, options: .CurveEaseOut, animations: { self.rippleView.transform = CGAffineTransformIdentity let shadowAnim = CABasicAnimation(keyPath:"shadowRadius") shadowAnim.toValue = self.tempShadowRadius let opacityAnim = CABasicAnimation(keyPath:"shadowOpacity") opacityAnim.toValue = self.tempShadowOpacity let groupAnim = CAAnimationGroup() groupAnim.duration = 0.7 groupAnim.fillMode = kCAFillModeForwards groupAnim.removedOnCompletion = false groupAnim.animations = [shadowAnim, opacityAnim] self.layer.addAnimation(groupAnim, forKey:"shadowBack") }, completion: nil) } }
mit
9833fcb51cdf6fdff75abe1484234ebd
32.231884
142
0.587831
5.216724
false
false
false
false
almazrafi/Metatron
Sources/Types/TagPeriod.swift
1
3175
// // TagPeriod.swift // Metatron // // Copyright (c) 2016 Almaz Ibragimov // // 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 public protocol TagPeriodable : Comparable, Equatable { // MARK: Instance Properties var isValid: Bool {get} // MARK: Initializers init() // MARK: Instance Methods mutating func reset() } public struct TagPeriod<T: TagPeriodable> : Comparable, Equatable { // MARK: Instance Properties public var start: T public var end: T // MARK: public var isValid: Bool { if !self.start.isValid { return false } if !self.end.isValid { return false } if self.start > self.end { return false } return true } // MARK: Initializers public init(start: T, end: T) { self.start = start self.end = end } public init() { self.start = T() self.end = T() } // MARK: Instance Methods public mutating func reset() { self.start.reset() self.end.reset() } } public func > <T: TagPeriodable>(left: TagPeriod<T>, right: TagPeriod<T>) -> Bool { return (left.start > right.start) } public func < <T: TagPeriodable>(left: TagPeriod<T>, right: TagPeriod<T>) -> Bool { return (left.start < right.start) } public func >= <T: TagPeriodable>(left: TagPeriod<T>, right: TagPeriod<T>) -> Bool { return (left.start >= right.start) } public func <= <T: TagPeriodable>(left: TagPeriod<T>, right: TagPeriod<T>) -> Bool { return (left.start <= right.start) } public func == <T: TagPeriodable>(left: TagPeriod<T>, right: TagPeriod<T>) -> Bool { if left.start != right.start { return false } if left.end != right.end { return false } return true } public func != <T: TagPeriodable>(left: TagPeriod<T>, right: TagPeriod<T>) -> Bool { return !(left == right) } extension TagTime: TagPeriodable {} extension TagDate: TagPeriodable {} public typealias TagTimePeriod = TagPeriod<TagTime> public typealias TagDatePeriod = TagPeriod<TagDate>
mit
ebb9d69053ada2603d6ec32e14ebc5a3
24.604839
84
0.656693
3.876679
false
false
false
false
akupara/Vishnu
Vishnu/Matsya/String+DLExtension.swift
1
1168
// // String+DLExtension.swift // DLControl // // Created by Daniel Lu on 2/18/16. // Copyright © 2016 Daniel Lu. All rights reserved. // import Foundation import CommonCrypto public extension String { // func md5() -> String { // var digest = [UInt8](count: Int(CC_MD5_DIGEST_LENGTH), repeatedValue: 0) // if let data = self.dataUsingEncoding(NSUTF8StringEncoding) { // CC_MD5(data.bytes, CC_LONG(data.length), &digest) // } // // var digestHex = "" // for index in 0..<Int(CC_MD5_DIGEST_LENGTH) { // // digestHex += String(format: "%02x", digest[index]) // } // // return digestHex // } public func upperCaseFirst() -> String { if characters.count < 1 { return "" } let firstCharacter = characters.first! let first = String([firstCharacter]).uppercaseString if characters.count < 2 { return first } let suffixIndex = startIndex.advancedBy(1) let suffix = substringFromIndex(suffixIndex) return "\(first)\(suffix)" } }
mit
84974c1127dba64cc73ec7d1bf3098bf
25.522727
82
0.549272
3.982935
false
false
false
false
bluejava/GeoTools4iOS
GeoTools4iOS/GeometryBuilder.swift
1
6529
// // GeometryBuilder.swift // GeoTools4iOS // // Created by Glenn Crownover on 5/4/15. // Copyright (c) 2015 bluejava. All rights reserved. // // This class helps in the building of custom geometry import SceneKit class GeometryBuilder { var quads: [Quad] var textureSize: CGPoint enum UVModeType { case StretchToFitXY, StretchToFitX, StretchToFitY, SizeToWorldUnitsXY, SizeToWorldUnitsX} var uvMode = UVModeType.StretchToFitXY init(uvMode: UVModeType = .StretchToFitXY) { self.uvMode = uvMode quads = [] textureSize = CGPoint(x: 1.0,y: 1.0) // Number of world units represents the textures are mapped to geometry as one full image per unit square } // Add a quad to the geometry - list verticies in counter-clockwise order when looking from the // "outside" of the square func addQuad(quad: Quad) { quads.append(quad) } func getGeometry() -> SCNGeometry { // This one structure holds the position, normal and UV Texture Mapping for a single vertice // - This is called "Interleaving Vertex Data" as explained on the SCNGeometrySource Reference Doc struct Vertex { var position: Float3 var normal: Float3 var tcoord: Float2 } func debugVertex(label: String, v: Vertex) { println("\(label).position: \(v.position.x),\(v.position.y),\(v.position.z)") println("\(label).normal: \(v.normal.x),\(v.normal.y),\(v.normal.z)") println("\(label).tcoord: \(v.tcoord.s),\(v.tcoord.t)") } var verts: [Vertex] = [] var faceIndices: [CInt] = [] // Walk through the quads, adding 4 vertices, 2 faces and 4 normals per quad // v1 --------------v0 // | __/ | // | face __/ | // | 1 __/ | // | __/ face | // | __/ 2 | // v2 ------------- v3 for quad in quads { // first, calculate normals for each vertice (compute seperately for face1 and face2 - common edge gets avg) var nvf1 = SCNUtils.getNormal(quad.v0, v1: quad.v1, v2: quad.v2) var nvf2 = SCNUtils.getNormal(quad.v0, v1: quad.v2, v2: quad.v3) // next, the texture coordinates var uv0: Float2 var uv1: Float2 var uv2: Float2 var uv3: Float2 switch uvMode { // The longest sides dictate the texture tiling, then it is stretched (if nec) across case .SizeToWorldUnitsX: var longestUEdgeLength = max( (quad.v1-quad.v0).length(), (quad.v2-quad.v3).length() ) var longestVEdgeLength = max( (quad.v1-quad.v2).length(), (quad.v0-quad.v3).length() ) uv0 = Float2(s: longestUEdgeLength,t: longestVEdgeLength) uv1 = Float2(s: 0,t: longestVEdgeLength) uv2 = Float2(s: 0,t: 0) uv3 = Float2(s: longestUEdgeLength, t:0) case .SizeToWorldUnitsXY: // For this uvMode, we allign the texture to the "upper left corner" (v1) and tile // it to the "right" and "down" (and "up") based on the coordinate units and the // texture/units ratio let v2v0 = quad.v0 - quad.v2 // v2 to v0 edge let v2v1 = quad.v1 - quad.v2 // v2 to v1 edge let v2v3 = quad.v3 - quad.v2 // v2 to v3 edge let v2v0Mag = v2v0.length() // length of v2 to v0 edge let v2v1Mag = v2v1.length() // length of v2 to v1 edge let v2v3Mag = v2v3.length() // length of v2 to v3 edge let v0angle = v2v3.angle(v2v0) // angle of v2v0 edge against v2v3 edge let v1angle = v2v3.angle(v2v1) // angle of v2v1 edge against v2v3 edge // now its just some simple trig - yay! uv0 = Float2(s: cos(v0angle) * v2v0Mag, t: sin(v0angle)*v2v0Mag) uv1 = Float2(s: cos(v1angle) * v2v1Mag, t: sin(v1angle)*v2v1Mag) uv2 = Float2(s: 0,t: 0) uv3 = Float2(s: v2v3Mag, t: 0) case .StretchToFitXY: uv0 = Float2(s: 1,t: 1) uv1 = Float2(s: 0,t: 1) uv2 = Float2(s: 0,t: 0) uv3 = Float2(s: 1,t: 0) default: println("Unknown uv mode \(uvMode)") // no uv mapping for you! uv0 = Float2(s: 1,t: 1) uv1 = Float2(s: 0,t: 1) uv2 = Float2(s: 0,t: 0) uv3 = Float2(s: 1,t: 0) } var v0norm = nvf1 + nvf2 var v2norm = nvf1 + nvf2 var v0 = Vertex(position: Quad.vector3ToFloat3(quad.v0), normal: Quad.vector3ToFloat3(v0norm.normalize()!), tcoord: uv0) var v1 = Vertex(position: Quad.vector3ToFloat3(quad.v1), normal: Quad.vector3ToFloat3(nvf1.normalize()!), tcoord: uv1) var v2 = Vertex(position: Quad.vector3ToFloat3(quad.v2), normal: Quad.vector3ToFloat3(v2norm.normalize()!), tcoord: uv2) var v3 = Vertex(position: Quad.vector3ToFloat3(quad.v3), normal: Quad.vector3ToFloat3(nvf2.normalize()!), tcoord: uv3) debugVertex("v0", v0) debugVertex("v1", v1) debugVertex("v2", v2) debugVertex("v3", v3) verts.append(v0) verts.append(v1) verts.append(v2) verts.append(v3) // add face 1 faceIndices.append(CInt(verts.count-4)) // v0 faceIndices.append(CInt(verts.count-3)) // v1 faceIndices.append(CInt(verts.count-2)) // v2 // add face 2 faceIndices.append(CInt(verts.count-4)) // v0 faceIndices.append(CInt(verts.count-2)) // v2 faceIndices.append(CInt(verts.count-1)) // v3 } // Define our sources let data = NSData(bytes: verts, length: verts.count * sizeof(Vertex)) var vertexSource = SCNGeometrySource( data: data, semantic: SCNGeometrySourceSemanticVertex, vectorCount: verts.count, floatComponents: true, componentsPerVector: 3, bytesPerComponent: sizeof(GLfloat), dataOffset: 0, // position is first member in Vertex dataStride: sizeof(Vertex)) let normalSource = SCNGeometrySource( data: data, semantic: SCNGeometrySourceSemanticNormal, vectorCount: verts.count, floatComponents: true, componentsPerVector: 3, bytesPerComponent: sizeof(GLfloat), dataOffset: sizeof(Float3), // one Float3 before normal in Vertex dataStride: sizeof(Vertex)) let tcoordSource = SCNGeometrySource( data: data, semantic: SCNGeometrySourceSemanticTexcoord, vectorCount: verts.count, floatComponents: true, componentsPerVector: 2, bytesPerComponent: sizeof(GLfloat), dataOffset: 2 * sizeof(Float3), // 2 Float3s before tcoord in Vertex dataStride: sizeof(Vertex)) // Define elements Data var indexData = NSData(bytes: faceIndices, length: sizeof(CInt) * faceIndices.count) var element = SCNGeometryElement(data: indexData, primitiveType: .Triangles, primitiveCount: faceIndices.count / 3, bytesPerIndex: sizeof(CInt)) var geometry = SCNGeometry(sources: [vertexSource, normalSource, tcoordSource], elements: [element]) return geometry } }
mit
a725a07b52a1268e2a71a3e8b11c1ae1
32.829016
146
0.663195
2.92256
false
false
false
false
lacklock/ResponseMock
ResponseMock/ResponseMock/MapLocalURLProtocol.swift
1
2611
// // MapLocalURLProtocol.swift // RequestDemo // // Created by 卓同学 on 2017/5/15. // Copyright © 2017年 卓同学. All rights reserved. // import UIKit class MapLocalURLProtocol: URLProtocol { override class func canInit(with request: URLRequest) -> Bool { if request.url != nil { if ResponseMockManager.loadMockFilesEachRequest { ResponseMockManager.loadConfig() } if let _ = ResponseMockManager.isMockFor(request: request){ return true } } return false } override class func canonicalRequest(for request: URLRequest) -> URLRequest { return request } override func startLoading() { guard let mock = ResponseMockManager.isMockFor(request: request) else { return } var responseData: Data! if let response = mock.response { switch mock.contentType { case .json: guard let jsonData = try? JSONSerialization.data(withJSONObject: response) else { return } responseData = jsonData case .plain: guard let stringResponse = response as? String else { return } responseData = stringResponse.data(using: .utf8) case .file: guard let filePath = response as? String else { return } let sourceURL = ResponseMockManager.resoureDirectory.appendingPathComponent(filePath) do { responseData = try Data(contentsOf: sourceURL) }catch { assertionFailure("read file failed") } } }else { assertionFailure("haven't specify response content") return } func response() { let urlResponse = HTTPURLResponse(url: request.url!, statusCode: mock.statusCode, httpVersion: nil, headerFields: mock.headers) client?.urlProtocol(self, didReceive: urlResponse!, cacheStoragePolicy: .notAllowed) client?.urlProtocol(self, didLoad: responseData) client?.urlProtocolDidFinishLoading(self) } if let delay = mock.delay { DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + delay, execute: { response() }) }else { response() } } override func stopLoading() { } }
mit
a60f22427da632e5e369e62f39b550b3
30.658537
139
0.543529
5.606911
false
false
false
false
JohnEstropia/CoreStore
Sources/DiffableDataSource.CollectionViewAdapter-UIKit.swift
1
9057
// // DiffableDataSource.CollectionViewAdapter-UIKit.swift // CoreStore // // Copyright © 2018 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. // #if canImport(UIKit) && (os(iOS) || os(tvOS)) import UIKit import CoreData // MARK: - DiffableDataSource extension DiffableDataSource { // MARK: - CollectionView /** The `DiffableDataSource.CollectionViewAdapter` serves as a `UICollectionViewDataSource` that handles `ListPublisher` snapshots for a `UICollectionView`. Subclasses of `DiffableDataSource.CollectionViewAdapter` may override some `UICollectionViewDataSource` methods as needed. The `DiffableDataSource.CollectionViewAdapter` instance needs to be held on (retained) for as long as the `UICollectionView`'s lifecycle. ``` self.dataSource = DiffableDataSource.CollectionViewAdapter<Person>( collectionView: self.collectionView, dataStack: CoreStoreDefaults.dataStack, cellProvider: { (collectionView, indexPath, person) in let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PersonCell") as! PersonCell cell.setPerson(person) return cell } ) ``` The dataSource can then apply changes from a `ListPublisher` as shown: ``` listPublisher.addObserver(self) { [weak self] (listPublisher) in self?.dataSource?.apply( listPublisher.snapshot, animatingDifferences: true ) } ``` `DiffableDataSource.CollectionViewAdapter` fully handles the reload animations. - SeeAlso: CoreStore's DiffableDataSource implementation is based on https://github.com/ra1028/DiffableDataSources */ open class CollectionViewAdapter<O: DynamicObject>: BaseAdapter<O, DefaultCollectionViewTarget<UICollectionView>>, UICollectionViewDataSource { // MARK: Public /** Initializes the `DiffableDataSource.CollectionViewAdapter`. This instance needs to be held on (retained) for as long as the `UICollectionView`'s lifecycle. ``` self.dataSource = DiffableDataSource.CollectionViewAdapter<Person>( collectionView: self.collectionView, dataStack: CoreStoreDefaults.dataStack, cellProvider: { (collectionView, indexPath, person) in let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PersonCell") as! PersonCell cell.setPerson(person) return cell } ) ``` - parameter collectionView: the `UICollectionView` to set the `dataSource` of. This instance is not retained by the `DiffableDataSource.CollectionViewAdapter`. - parameter dataStack: the `DataStack` instance that the dataSource will fetch objects from - parameter cellProvider: a closure that configures and returns the `UICollectionViewCell` for the object - parameter supplementaryViewProvider: an optional closure for providing `UICollectionReusableView` supplementary views. If not set, defaults to returning `nil` */ public init( collectionView: UICollectionView, dataStack: DataStack, cellProvider: @escaping (UICollectionView, IndexPath, O) -> UICollectionViewCell?, supplementaryViewProvider: @escaping (UICollectionView, String, IndexPath) -> UICollectionReusableView? = { _, _, _ in nil } ) { self.cellProvider = cellProvider self.supplementaryViewProvider = supplementaryViewProvider super.init(target: .init(collectionView), dataStack: dataStack) collectionView.dataSource = self } // MARK: - UICollectionViewDataSource @objc @MainActor public dynamic func numberOfSections( in collectionView: UICollectionView ) -> Int { return self.numberOfSections() } @objc @MainActor public dynamic func collectionView( _ collectionView: UICollectionView, numberOfItemsInSection section: Int ) -> Int { return self.numberOfItems(inSection: section) ?? 0 } @objc @MainActor open dynamic func collectionView( _ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath ) -> UICollectionViewCell { guard let objectID = self.itemID(for: indexPath) else { Internals.abort("Object at \(Internals.typeName(IndexPath.self)) \(indexPath) already removed from list") } guard let object = self.dataStack.fetchExisting(objectID) as O? else { Internals.abort("Object at \(Internals.typeName(IndexPath.self)) \(indexPath) has been deleted") } guard let cell = self.cellProvider(collectionView, indexPath, object) else { Internals.abort("\(Internals.typeName(UICollectionViewDataSource.self)) returned a `nil` cell for \(Internals.typeName(IndexPath.self)) \(indexPath)") } return cell } @objc @MainActor open dynamic func collectionView( _ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath ) -> UICollectionReusableView { guard let view = self.supplementaryViewProvider(collectionView, kind, indexPath) else { return UICollectionReusableView() } return view } // MARK: Private private let cellProvider: (UICollectionView, IndexPath, O) -> UICollectionViewCell? private let supplementaryViewProvider: (UICollectionView, String, IndexPath) -> UICollectionReusableView? } // MARK: - DefaultCollectionViewTarget public struct DefaultCollectionViewTarget<T: UICollectionView>: Target { // MARK: Public public typealias Base = T public private(set) weak var base: Base? public init(_ base: Base) { self.base = base } // MARK: DiffableDataSource.Target public var shouldSuspendBatchUpdates: Bool { return self.base?.window == nil } public func deleteSections(at indices: IndexSet, animated: Bool) { self.base?.deleteSections(indices) } public func insertSections(at indices: IndexSet, animated: Bool) { self.base?.insertSections(indices) } public func reloadSections(at indices: IndexSet, animated: Bool) { self.base?.reloadSections(indices) } public func moveSection(at index: IndexSet.Element, to newIndex: IndexSet.Element, animated: Bool) { self.base?.moveSection(index, toSection: newIndex) } public func deleteItems(at indexPaths: [IndexPath], animated: Bool) { self.base?.deleteItems(at: indexPaths) } public func insertItems(at indexPaths: [IndexPath], animated: Bool) { self.base?.insertItems(at: indexPaths) } public func reloadItems(at indexPaths: [IndexPath], animated: Bool) { self.base?.reloadItems(at: indexPaths) } public func moveItem(at indexPath: IndexPath, to newIndexPath: IndexPath, animated: Bool) { self.base?.moveItem(at: indexPath, to: newIndexPath) } public func performBatchUpdates(updates: () -> Void, animated: Bool, completion: @escaping () -> Void) { self.base?.performBatchUpdates(updates, completion: { _ in completion() }) } public func reloadData() { self.base?.reloadData() } } } // MARK: Deprecated extension DiffableDataSource { @available(*, deprecated, renamed: "CollectionViewAdapter") public typealias CollectionView = CollectionViewAdapter } #endif
mit
fa398f01d0872c8ea2f2acaa052b5a94
34.936508
280
0.658679
5.44558
false
false
false
false
hilen/TSWeChat
TSWeChat/Classes/Discover/TSDiscoverViewController.swift
1
3360
// // TSDiscoverViewController.swift // TSWeChat // // Created by Hilen on 1/8/16. // Copyright © 2016 Hilen. All rights reserved. // import UIKit class TSDiscoverViewController: UIViewController { @IBOutlet weak var listTableView: UITableView! fileprivate let itemDataSouce: [[(name: String, iconImage: UIImage)]] = [ [ ("朋友圈", TSAsset.Ff_IconShowAlbum.image), ], [ ("扫一扫", TSAsset.Ff_IconQRCode.image), ("摇一摇", TSAsset.Ff_IconShake.image), ], [ ("附近的人", TSAsset.Ff_IconLocationService.image), ("漂流瓶", TSAsset.Ff_IconBottle.image), ], [ // ("购物", TSAsset.Icon_bustime.image), ("游戏", TSAsset.MoreGame.image), ], ] override func viewDidLoad() { super.viewDidLoad() self.title = "发现" self.view.backgroundColor = UIColor.viewBackgroundColor self.listTableView.ts_registerCellNib(TSImageTextTableViewCell.self) self.listTableView.estimatedRowHeight = 44 self.listTableView.tableFooterView = UIView() // Do any additional setup after loading the view. } deinit { log.verbose("deinit") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } // MARK: @protocol - UITableViewDelegate extension TSDiscoverViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if section == 0 { return 15 } else { return 20 } } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0.00001 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } } // MARK: @protocol - UITableViewDataSource extension TSDiscoverViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return self.itemDataSouce.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let rows = self.itemDataSouce[section] return rows.count } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return self.listTableView.estimatedRowHeight } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell :TSImageTextTableViewCell = tableView.ts_dequeueReusableCell(TSImageTextTableViewCell.self) let item = self.itemDataSouce[indexPath.section][indexPath.row] cell.iconImageView.image = item.iconImage cell.titleLabel.text = item.name return cell } }
mit
d4dd09d7f6848dff584e5f4d6fe80130
29.981308
108
0.64917
4.940387
false
false
false
false
PlutoMa/SwiftProjects
006.Video Player/VideoPlayer/VideoPlayer/ViewController.swift
1
3728
// // ViewController.swift // VideoPlayer // // Created by Dareway on 2017/11/8. // Copyright © 2017年 Pluto. All rights reserved. // import UIKit import AVFoundation import AVKit import MediaPlayer class ViewController: UIViewController, AVAudioPlayerDelegate { var audioPlayer: AVAudioPlayer? override func viewDidLoad() { super.viewDidLoad() let videoButton = UIButton() videoButton.setTitleColor(UIColor.blue, for: UIControlState.normal) videoButton.setTitle("Play Video", for: UIControlState.normal) videoButton.frame = CGRect(x: 50, y: 50, width: 100, height: 50) self.view.addSubview(videoButton) videoButton.addTarget(self, action: #selector(playVideo), for: UIControlEvents.touchUpInside) let audioPlayButton = UIButton() audioPlayButton.setTitleColor(UIColor.red, for: UIControlState.normal) audioPlayButton.setTitle("Play Audio", for: UIControlState.normal) audioPlayButton.frame = CGRect(x: 50, y: 150, width: 100, height: 50) self.view.addSubview(audioPlayButton) audioPlayButton.addTarget(self, action: #selector(playAudio), for: UIControlEvents.touchUpInside) let audioPauseButton = UIButton() audioPauseButton.setTitleColor(UIColor.red, for: UIControlState.normal) audioPauseButton.setTitle("Pause Audio", for: UIControlState.normal) audioPauseButton.frame = CGRect(x: 50, y: 250, width: 100, height: 50) self.view.addSubview(audioPauseButton) audioPauseButton.addTarget(self, action: #selector(pauseAudio), for: UIControlEvents.touchUpInside) initAudio() UIApplication.shared.beginReceivingRemoteControlEvents() initForLockScreen() } @objc func playVideo() { let videoUrl = URL(string: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4") let player = AVPlayer(url: videoUrl!) let playerViewController = AVPlayerViewController() playerViewController.player = player self.present(playerViewController, animated: true) {} } func initAudio() { let audioPath = Bundle.main .path(forResource: "live", ofType: "mp3") let audioUrl = URL(fileURLWithPath: audioPath!) do { audioPlayer = try AVAudioPlayer(contentsOf: audioUrl) } catch { audioPlayer = nil } do { try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord) try AVAudioSession.sharedInstance().setActive(true) } catch { print("error") } } func initForLockScreen() { MPNowPlayingInfoCenter.default().nowPlayingInfo = [ MPMediaItemPropertyTitle:"皇后大道东", MPMediaItemPropertyArtist:"罗大佑", MPMediaItemPropertyArtwork:MPMediaItemArtwork(image: UIImage(named: "thumb.jpg")!), MPNowPlayingInfoPropertyPlaybackRate:1.0, MPMediaItemPropertyPlaybackDuration:audioPlayer?.duration, MPNowPlayingInfoPropertyElapsedPlaybackTime:audioPlayer?.currentTime ] } @objc func playAudio() { audioPlayer?.play() } @objc func pauseAudio() { audioPlayer?.pause() } override func remoteControlReceived(with event: UIEvent?) { switch event!.subtype { case .remoteControlPlay: audioPlayer?.play() case .remoteControlPause: audioPlayer?.pause() case .remoteControlStop: audioPlayer?.stop() default: break } } }
mit
ed667791de9f48d72d4485efa237b65a
33.342593
107
0.642222
5.151389
false
false
false
false
nifti/CinchKit
CinchKit/Serializers/ErrorResponseSerializer.swift
1
765
// // ErrorResponseSerializer.swift // CinchKit // // Created by Ryan Fitzgerald on 2/19/15. // Copyright (c) 2015 cinch. All rights reserved. // import Foundation import SwiftyJSON class ErrorResponseSerializer : JSONObjectSerializer { func jsonToObject(json: SwiftyJSON.JSON) -> NSError? { let statusCode = json["statusCode"].intValue var userInfo = [String : String]() if let err = json["error"].string { userInfo[NSLocalizedDescriptionKey] = err } if let message = json["message"].string { userInfo[NSLocalizedFailureReasonErrorKey] = message } return NSError(domain: CinchKitErrorDomain, code: statusCode, userInfo: userInfo) } }
mit
8e9b15a65702e8517b5acc244dca1982
24.533333
89
0.63268
4.78125
false
false
false
false
HQL-yunyunyun/SinaWeiBo
SinaWeiBo/SinaWeiBo/Class/Module/NewFeature/Model/HQLWelcomeViewController.swift
1
4946
// // HQLWelcomeViewController.swift // SinaWeiBo // // Created by 何启亮 on 16/5/14. // Copyright © 2016年 HQL. All rights reserved. // import UIKit import SnapKit import SDWebImage class HQLWelcomeViewController: UIViewController { // ==================MARK: - 生命周期方法 override func viewDidLoad() { // 加载控件 super.viewDidLoad() self.prepareUI() // 即使头像在本地缓存了图片,刚开始会用占位图片,只有网路请求完成后才会使用SDWebImage设置图片 // 解决方法,在获取用户信息之前,也使用SDWebImage去设置一下头像的图片 setIcon() // 获取用户信息 HQLUserAccountViewModel.shareInstance.loadUserInfo { self.setIcon() } } // 获取头像 private func setIcon(){ if let avatar_large = HQLUserAccountViewModel.shareInstance.userAccount?.avatar_large{ // 获取到用户数据 let url = NSURL(string: avatar_large) self.iconView.sd_setImageWithURL(url, placeholderImage: UIImage(named: "avatar_default_big")) } } // 在这个方法----视图已经显示----这样动画才会动 override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) // 调用动画 self.moveAnimation() } // ==================MARK: - 类的私有方法 // 动画 private func moveAnimation(){ // 移动动画 // 弹簧动画 // usingSpringWithDamping: 弹簧的明显程度 0 - 1 // initialSpringVelocity: 初始速度 UIView.animateWithDuration(2, delay: 0.1, usingSpringWithDamping: 0.5, initialSpringVelocity: 5, options: UIViewAnimationOptions(rawValue: 0), animations: { // 动画 // 更新约束 self.iconView.snp_updateConstraints(closure: { (make) in make.bottom.equalTo(self.view).offset(-(UIScreen.mainScreen().bounds.height - 160)) }) // 更新约束后调用这个方法 Lays out the subviews immediately. 重新布局 self.view.layoutIfNeeded() }) { (_) in CZPrint(items: "弹簧动画完成, label渐变动画") UIView.animateWithDuration(0.5, animations: { // 显示label self.messageLabel.alpha = 1 }, completion: { (_) in // 显示完就直接跳转 let appdelegate = (UIApplication.sharedApplication().delegate as! AppDelegate) // 把window的根控制器替换成tabBarController appdelegate.switchRootViewController(HQLTabBarController()) }) } } // 加载控件 private func prepareUI(){ self.view.addSubview(bgView) self.view.addSubview(iconView) self.view.addSubview(messageLabel) // 设置约束 // autolayout // 背景 // bkgView: 要添加约束的view // snp_makeConstraints: 要添加约束 // make: 要添加约束的view bgView.snp_makeConstraints { (make) in make.edges.equalTo(self.view) } // 头像 iconView.snp_makeConstraints { (make) in // make.centerX: 要约束view的centerX属性 // equalTo: 参照 // self.view: 参照的view // snp_centerX: 参照View的哪个属性, 参照view的属性需要添加snp_make.centerX.equalTo(self.view.snp_centerX) make.centerX.equalTo(self.view) make.bottom.equalTo(self.view).offset(-160) } // 消息 messageLabel.snp_makeConstraints { (make) -> Void in make.centerX.equalTo(iconView) make.top.equalTo(iconView.snp_bottom).offset(16) } } // ==================MARK: - 懒加载控件 // 背景 private lazy var bgView: UIImageView = UIImageView(image: UIImage(named: "ad_background")) // 头像 private lazy var iconView: UIImageView = { let imageView = UIImageView(image: UIImage(named: "avatar_default_big")) // 圆角 imageView.layer.cornerRadius = 42.5 // 实现这个属性才会有圆角 imageView.layer.masksToBounds = true return imageView }() // label控件 private lazy var messageLabel: UILabel = { let label = UILabel() // 设置label属性 label.text = "欢迎回来" label.textColor = UIColor.blackColor() label.font = UIFont.systemFontOfSize(15) label.sizeToFit() label.alpha = 0 return label }() }
apache-2.0
cba469be73baca5a849c3c36e908bdd6
28.979452
165
0.541924
4.592865
false
false
false
false
Hearsayer/YLDrawer
Drawer/DrawerViewController.swift
1
10795
// // ViewController.swift // Drawer // // Created by he on 2017/7/13. // Copyright © 2017年 hezongjiang. All rights reserved. // import UIKit // 菜单状态枚举 enum MenuState { /// 折叠 case collapsed /// 展开中 case expanding /// 已展开 case expanded } enum CascadingStyles { case mainViewInTop case letfViewInTop } public class DrawerViewController: UIViewController { /// 主视图控制器 fileprivate let mainViewController: UIViewController /// 左侧视图控制器 fileprivate let leftViewController: UIViewController /// 菜单打开后主页在屏幕右侧露出部分的宽度 public var menuViewExpandedOffset: CGFloat = 100 /// 菜单黑色半透明遮罩层最小透明度(0 ~ 1) public var coverMinAlpha: CGFloat = 0.1 /// 背景颜色 public var backGoundColor: UIColor = .white /// 背景图片 public var backGoundImage: UIImage? { didSet { let imageView = UIImageView(image: backGoundImage) imageView.frame = view.bounds view.insertSubview(imageView, at: 0) } } public var hideStatusBarWhenExpanded = false /// 侧滑开始时,菜单视图起始的偏移量 fileprivate let menuViewStartOffset: CGFloat = 60 /// 最小缩放比例 fileprivate let minProportion: CGFloat = 0.8 /// 侧滑菜单黑色半透明遮罩层 fileprivate lazy var blackCover: UIVisualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .dark)) /// 主页遮盖 fileprivate lazy var mainViewCover: UIVisualEffectView = { let effect = UIVisualEffectView(effect: UIBlurEffect(style: .dark)) effect.alpha = 0 let tap = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture)) effect.addGestureRecognizer(tap) return effect }() /// 菜单页当前状态 fileprivate var currentState = MenuState.collapsed { didSet { UIView.animate(withDuration: 0.5) { self.setNeedsStatusBarAppearanceUpdate() } // 菜单展开的时候,给主页面边缘添加阴影 let shouldShowShadow = currentState != .collapsed showShadowForMainViewController(shouldShowShadow) } } public init(mainViewController: UIViewController, leftViewController: UIViewController) { self.mainViewController = mainViewController self.leftViewController = leftViewController super.init(nibName: nil, bundle: nil) // 添加主视图 let mainView = mainViewController.view! mainView.frame = view.bounds view.addSubview(mainView) addChildViewController(mainViewController) // 添加拖拽手势 let pan = UIPanGestureRecognizer(target: self, action: #selector(handlePanGesture(_:))) mainView.addGestureRecognizer(pan) // 添加左侧视图 let leftView = leftViewController.view! view.backgroundColor = leftView.backgroundColor leftView.frame = view.bounds addChildViewController(leftViewController) } /// 单击手势响应 @objc fileprivate func handleTapGesture() { // 如果菜单是展开的点击主页部分则会收起 if currentState == .expanded { animateMainView(shouldExpand: false) } } /// 拖拽手势 @objc fileprivate func handlePanGesture(_ recognizer: UIPanGestureRecognizer) { switch(recognizer.state) { case .began: // 刚刚开始滑动 // 判断拖动方向 let dragFromLeftToRight = (recognizer.velocity(in: view).x > 0) // 如果刚刚开始滑动的时候还处于主页面,从左向右滑动加入侧面菜单 if (currentState == .collapsed && dragFromLeftToRight) { currentState = .expanding addMenuViewController() } case .changed: // 如果是正在滑动,则偏移主视图的坐标实现跟随手指位置移动 let screenWidth = view.frame.width let halfScreenWidth = screenWidth * 0.5 var centerX = recognizer.view!.center.x + recognizer.translation(in: view).x // 页面滑到最左侧的话就不许要继续往左移动 if centerX < halfScreenWidth { centerX = halfScreenWidth } // 计算缩放比例 let percent: CGFloat = (centerX - halfScreenWidth) / (screenWidth - menuViewExpandedOffset) let proportion = 1 - (1 - minProportion) * percent // 执行视差特效 let alpha = (proportion - minProportion) / (1 - minProportion) - coverMinAlpha blackCover.alpha = alpha mainViewCover.alpha = 1 - alpha - coverMinAlpha recognizer.view!.center.x = centerX recognizer.setTranslation(CGPoint.zero, in: view) // 缩放主页面 // recognizer.view!.transform = CGAffineTransform.identity.scaledBy(x: proportion, y: proportion) // 菜单视图移动 leftViewController.view.center.x = halfScreenWidth - menuViewStartOffset * (1 - percent) // 菜单视图缩放 let menuProportion = (1 + minProportion) - proportion leftViewController.view.transform = CGAffineTransform.identity.scaledBy(x: menuProportion, y: menuProportion) case .ended: // 如果滑动结束 // 根据页面滑动是否过半,判断后面是自动展开还是收缩 let hasMovedhanHalfway = recognizer.view!.center.x > view.frame.width animateMainView(shouldExpand: hasMovedhanHalfway) default: break } } /// 侧滑开始时,添加菜单页 fileprivate func addMenuViewController() { let mianView = mainViewController.view! mainViewCover.frame = mianView.bounds mianView.addSubview(mainViewCover) leftViewController.view.center.x = view.frame.width * 0.5 * (1 - (1 - minProportion) * 0.5) - menuViewStartOffset leftViewController.view.transform = CGAffineTransform.identity.scaledBy(x: minProportion, y: minProportion) // 插入当前视图并置顶 view.insertSubview(leftViewController.view, belowSubview: mainViewController.view) // 在侧滑菜单之上增加黑色遮罩层,目的是实现视差特效 blackCover.frame = view.frame.offsetBy(dx: 0, dy: 0) view.insertSubview(blackCover, belowSubview: mainViewController.view) } /// 主页自动展开、收起动画 /// /// - Parameter shouldExpand: 是否展开,true:展开,false:折叠 public func animateMainView(shouldExpand: Bool) { if (shouldExpand) { // 如果是用来展开 // 更新当前状态 currentState = .expanded // 动画 let mainPosition = view.frame.width * (1 + minProportion * 0.5) - menuViewExpandedOffset * 0.5 doTheAnimate(mainPosition, mainProportion: minProportion, menuPosition: view.bounds.width * 0.5, menuProportion: 1, blackCoverAlpha: 0, usingSpringWithDamping: 0.6) { finished in } } else { // 如果是用于隐藏 let menuPosition = view.frame.width * 0.5 * (1 - (1 - minProportion) * 0.5) - menuViewStartOffset // 动画 doTheAnimate(view.frame.width * 0.5, mainProportion: 1, menuPosition: menuPosition, menuProportion: minProportion, blackCoverAlpha: 1 - coverMinAlpha, usingSpringWithDamping: 1) { finished in // 动画结束之后更新状态 self.currentState = .collapsed // 移除左侧视图 self.leftViewController.view.removeFromSuperview() // 移除黑色遮罩层 self.blackCover.removeFromSuperview() // 移除主视图透明遮罩 self.mainViewCover.removeFromSuperview() } } } /// 主页移动动画、黑色遮罩层动画、菜单页移动动画 fileprivate func doTheAnimate(_ mainPosition: CGFloat, mainProportion: CGFloat, menuPosition: CGFloat, menuProportion: CGFloat, blackCoverAlpha: CGFloat, usingSpringWithDamping: CGFloat, completion: ((Bool) -> Void)? = nil) { // usingSpringWithDamping:1.0表示没有弹簧震动动画 UIView.animate(withDuration: 0.6, delay: 0, usingSpringWithDamping: usingSpringWithDamping, initialSpringVelocity: 0, options: UIViewAnimationOptions(), animations: { self.mainViewController.view.center.x = mainPosition self.blackCover.alpha = blackCoverAlpha self.mainViewCover.alpha = 1 - blackCoverAlpha - self.coverMinAlpha // 缩放主页面 // self.mainNavigationController.view.transform = CGAffineTransform.identity.scaledBy(x: mainProportion, y: mainProportion) // 菜单页移动 self.leftViewController.view.center.x = menuPosition // 菜单页缩放 self.leftViewController.view.transform = CGAffineTransform.identity.scaledBy(x: menuProportion, y: menuProportion) }, completion: completion) } /// 给主页面边缘添加、取消阴影 fileprivate func showShadowForMainViewController(_ shouldShowShadow: Bool) { if (shouldShowShadow) { mainViewController.view.layer.shadowOpacity = 1 } else { mainViewController.view.layer.shadowOpacity = 0 } } public override var prefersStatusBarHidden: Bool { return (currentState != .collapsed) ? hideStatusBarWhenExpanded : false } public override var preferredStatusBarStyle: UIStatusBarStyle { return (currentState != .expanded) ? .default : .lightContent } public override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation { return .slide } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override public func viewDidLoad() { super.viewDidLoad() } }
mit
6a4c54b10ab151a3875cc0aed6c5f617
33.195804
229
0.605317
4.88024
false
false
false
false
zhouxj6112/ARKit
ARKitInteraction/ARKitInteraction/ViewController+Actions.swift
1
3489
/* See LICENSE folder for this sample’s licensing information. Abstract: UI Actions for the main view controller. */ import UIKit import SceneKit extension ViewController: UIGestureRecognizerDelegate { enum SegueIdentifier: String { case showObjects } // MARK: - Interface Actions /// Displays the `VirtualObjectSelectionViewController` from the `addObjectButton` or in response to a tap gesture in the `sceneView`. @IBAction func showVirtualObjectSelectionViewController() { // Ensure adding objects is an available action and we are not loading another object (to avoid concurrent modifications of the scene). guard !addObjectButton.isHidden && !virtualObjectLoader.isLoading else { return } statusViewController.cancelScheduledMessage(for: .contentPlacement) performSegue(withIdentifier: SegueIdentifier.showObjects.rawValue, sender: addObjectButton) } /// Determines if the tap gesture for presenting the `VirtualObjectSelectionViewController` should be used. func gestureRecognizerShouldBegin(_: UIGestureRecognizer) -> Bool { return virtualObjectLoader.loadedObjects.isEmpty } func gestureRecognizer(_: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith _: UIGestureRecognizer) -> Bool { return true } /// - Tag: restartExperience func restartExperience() { guard isRestartAvailable, !virtualObjectLoader.isLoading else { return } isRestartAvailable = false statusViewController.cancelAllScheduledMessages() virtualObjectLoader.removeAllVirtualObjects() addObjectButton.setImage(#imageLiteral(resourceName: "add"), for: []) addObjectButton.setImage(#imageLiteral(resourceName: "addPressed"), for: [.highlighted]) resetTracking() // Disable restart for a while in order to give the session time to restart. DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) { self.isRestartAvailable = true } } } extension ViewController: UIPopoverPresentationControllerDelegate { // MARK: - UIPopoverPresentationControllerDelegate func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle { return .none } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // All menus should be popovers (even on iPhone). if let popoverController = segue.destination.popoverPresentationController, let button = sender as? UIButton { popoverController.delegate = self popoverController.sourceView = button popoverController.sourceRect = button.bounds } guard let identifier = segue.identifier, let segueIdentifer = SegueIdentifier(rawValue: identifier), segueIdentifer == .showObjects else { return } let objectsViewController = segue.destination as! VirtualObjectSelectionViewController objectsViewController.virtualObjects = VirtualObject.availableObjects objectsViewController.delegate = self // Set all rows of currently placed objects to selected. for object in virtualObjectLoader.loadedObjects { guard let index = VirtualObject.availableObjects.index(of: object) else { continue } objectsViewController.selectedVirtualObjectRows.insert(index) } } }
apache-2.0
255ad4440cfb651ce41813103671d629
38.625
143
0.706625
5.981132
false
false
false
false
andriitishchenko/DownloadManager
OPF/DataSource.swift
1
5820
// // DataSource.swift // OPF // // Created by Andrii Tishchenko on 31.08.15. // Copyright (c) 2015 Andrii Tishchenko. All rights reserved. // import Cocoa //enum AwfulError: ErrorType { // case Bad // case Worse // case Terrible //} class DownloadItem:NSObject { let stringURL:String var temporaryURL:NSURL? = nil var progress:Double = 0.0 var error:NSError? var size:Double = 0.0 let filename:String // init (_ stringURL:String) throws { // throws init (_ stringURL:String) { // throws self.stringURL = stringURL; self.progress = 0.0; self.size = 0.0; self.error = nil; // do { if( ((stringURL.lastPathComponent as String?) != nil) && (count(stringURL.pathExtension) == 3)){ self.filename=stringURL.lastPathComponent } else { let url = NSURL(string:stringURL) self.filename = url!.lastPathComponent! } // } catch { // self.filename = "" // // var e = NSException(name:"name", reason:"reason", userInfo:nil) // e.raise() // } } } class DataSource { var dataSource: [DownloadItem]? var fileHandle : NSFileHandle! let buffer : NSMutableData! let delimData : NSData! let encoding : UInt = NSUTF8StringEncoding let chunkSize : Int = 4096 init?(path: String, delimiter: String = "\n") { if let fileHandle = NSFileHandle(forReadingAtPath: path), delimData = delimiter.dataUsingEncoding(NSUTF8StringEncoding), buffer = NSMutableData(capacity: 4096) { self.fileHandle = fileHandle self.delimData = delimData self.buffer = buffer } else { self.fileHandle = nil self.delimData = nil self.buffer = nil self.dataSource = nil return nil } } deinit { self.fileHandle?.closeFile() self.fileHandle = nil self.dataSource = nil } func parce(completion:()->(Void)) { // self.dataSource = nil self.dataSource = [DownloadItem]() self.fileHandle.seekToFileOffset(0) buffer.length = 0 // let regex = NSRegularExpression(pattern: "/^",options: nil, error: nil)! var atEof = false while(!atEof){ // Read data chunks from file until a line delimiter is found: var range = buffer.rangeOfData(delimData, options: nil, range: NSMakeRange(0, buffer.length)) while range.location == NSNotFound { let tmpData = fileHandle.readDataOfLength(chunkSize) if tmpData.length == 0 { // EOF or read error. atEof = true if buffer.length > 0 { // Buffer contains last line in file (not terminated by delimiter). let line = NSString(data: buffer, encoding: encoding) buffer.length = 0 // let item = DownloadItem(line! as String) let element:DownloadItem // do { element = DownloadItem(line! as String) // } catch { // print(1); // continue; // } self.dataSource?.append(element) // self.dataSource?.append(element) // self.dataSource!.addObject(DownloadItem(line! as String)) // self.dataSource!.addObject(item) // (line as String?)!) } // No more lines. completion() return } buffer.appendData(tmpData) range = buffer.rangeOfData(delimData, options: nil, range: NSMakeRange(0, buffer.length)) } // Convert complete line (excluding the delimiter) to a string: let line = NSString(data: buffer.subdataWithRange(NSMakeRange(0, range.location)), encoding: encoding) // Remove line (and the delimiter) from the buffer: buffer.replaceBytesInRange(NSMakeRange(0, range.location + range.length), withBytes: nil, length: 0) // if regex.firstMatchInString(line! as String, options: nil, range: NSMakeRange(0, line!.length)) != nil { // // } self.dataSource?.append(DownloadItem(line! as String)) } } // // func openFile(filename:String)->Bool // { // var error:NSError? // var content:String = NSString(contentsOfFile: filename, encoding: NSUTF8StringEncoding, error: nil) as! String // // // // if let fileHandle = NSFileHandle(forReadingAtPath: filename), // let delimData = "\n".dataUsingEncoding(NSUTF8StringEncoding), // let buffer = NSMutableData(capacity: 4096) // { // self.fileHandle = fileHandle // self.delimData = delimData // self.buffer = buffer // // self.dataSource = NSMutableArray() // // // // // // // // } else { // self.fileHandle = nil // self.delimData = nil // self.buffer = nil // return nil // } // // // // // // // // // // // // // // return error == nil; // } }
mit
636dc1b0964d23c03b8a592260b3b518
27.390244
120
0.493814
4.63745
false
false
false
false
cache0928/CCWeibo
CCWeibo/CCWeibo/Classes/Common/Notifications/Notifications.swift
1
581
// // HomeNotifications.swift // CCWeibo // // Created by 徐才超 on 16/2/5. // Copyright © 2016年 徐才超. All rights reserved. // import Foundation struct HomeNotifications { static let TitleViewWillShow = "Home.TitleViewWillShow" static let TitleViewWillHide = "Home.TitleViewWillHide" static let DidSelectCollectionImage = "Home.DidSelectCollectionImage" } struct ImageBrowserNotifications { static let TapToClose = "ImageBrowser.TapToClose" } struct NewPostNotifications { static let NewPostTextItemDidClick = "NewPostTab.NewPostTextItem" }
mit
0576100f45b16456edfd4322556aaa01
26
73
0.759717
4.042857
false
false
false
false
Staance/Swell
Swell/LogLocation.swift
1
4304
// // LogLocation.swift // Swell // // Created by Hubert Rabago on 6/26/14. // Copyright (c) 2014 Minute Apps LLC. All rights reserved. // import Foundation public protocol LogLocation { //class func getInstance(param: AnyObject? = nil) -> LogLocation func log(@autoclosure message: () -> String); func enable(); func disable(); func description() -> String } public class ConsoleLocation: LogLocation { var enabled = true // Use the static-inside-class-var approach to getting a class var instance class var instance: ConsoleLocation { struct Static { static let internalInstance = ConsoleLocation() } return Static.internalInstance } public class func getInstance() -> LogLocation { return instance } public func log(@autoclosure message: () -> String) { if enabled { print(message()) } } public func enable() { enabled = true } public func disable() { enabled = false } public func description() -> String { return "ConsoleLocation" } } // Use the globally-defined-var approach to getting a class var dictionary var internalFileLocationDictionary = Dictionary<String, FileLocation>() public class FileLocation: LogLocation { var enabled = true var filename: String var fileHandle: NSFileHandle? public class func getInstance(filename: String) -> LogLocation { let temp = internalFileLocationDictionary[filename] if let result = temp { return result } else { let result: FileLocation = FileLocation(filename: filename) internalFileLocationDictionary[filename] = result return result } } init(filename: String) { self.filename = filename self.setDirectory() fileHandle = nil openFile() } deinit { closeFile() } public func log(@autoclosure message: () -> String) { //message.writeToFile(filename, atomically: false, encoding: NSUTF8StringEncoding, error: nil); if (!enabled) { return } let output = message() + "\n" if let handle = fileHandle { handle.seekToEndOfFile() if let data = output.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) { handle.writeData(data) } } } func setDirectory() { let temp: NSString = self.filename if temp.rangeOfString("/").location != Foundation.NSNotFound { // "/" was found in the filename, so we use whatever path is already there if (self.filename.hasPrefix("~/")) { self.filename = (self.filename as NSString).stringByExpandingTildeInPath } return } //let dirs : [String]? = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .AllDomainsMask, true) as? [String] let dirs:AnyObject = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] if let dir: String = dirs as? String { //let dir = directories[0]; //documents directory let path = (dir as NSString).stringByAppendingPathComponent(self.filename); self.filename = path; } } func openFile() { // open our file //Swell.info("Opening \(self.filename)") if !NSFileManager.defaultManager().fileExistsAtPath(self.filename) { NSFileManager.defaultManager().createFileAtPath(self.filename, contents: nil, attributes: nil) } fileHandle = NSFileHandle(forWritingAtPath:self.filename); //Swell.debug("fileHandle is now \(fileHandle)") } func closeFile() { // close the file, if it's open if let handle = fileHandle { handle.closeFile() } fileHandle = nil } public func enable() { enabled = true } public func disable() { enabled = false } public func description() -> String { return "FileLocation filename=\(filename)" } }
apache-2.0
403572efc1c2bb799cfc9f8ab64180c7
26.414013
124
0.58829
5.160671
false
false
false
false
Sensoro/Beacon-Passbook-iOS
BeaconPassbook-Swift/BeaconPassbook-Swift/ViewController.swift
1
2310
// // ViewController.swift // BeaconPassbook-Swift // // Created by David Yang on 15/3/30. // Copyright (c) 2015年 Sensoro. All rights reserved. // import UIKit import PassKit class ViewController: UIViewController, PKAddPassesViewControllerDelegate { @IBOutlet weak var image: UIImageView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func addPassbook(sender: AnyObject) { if let passPath = Bundle.main.url(forResource: "Generic", withExtension: "pkpass"){ var error : NSError?; if let passData = try? Data(contentsOf: passPath) { let pkPass = PKPass(data : passData, error: &error); let pkLibrary = PKPassLibrary(); if pkLibrary.containsPass(pkPass) { UIApplication.shared.openURL(pkPass.passURL!); }else{ let vc = PKAddPassesViewController(pass: pkPass); vc.delegate = self; present(vc, animated: true, completion: nil); } } } } @IBAction func saveToAlbum(sender: AnyObject) { UIImageWriteToSavedPhotosAlbum(image.image!, self,#selector(image(image:didFinishSavingWithError:contextInfo:)),nil); } //MARK: PKAddPassesViewControllerDelegate func addPassesViewControllerDidFinish(_ controller: PKAddPassesViewController) { controller.dismiss(animated: true, completion: nil); } @objc func image(image : UIImage, didFinishSavingWithError error : NSError!, contextInfo info: UnsafeRawPointer) { if error == nil { let alert = UIAlertView(title: "提示", message: "保存成功", delegate: nil, cancelButtonTitle: "OK"); alert.show(); }else{ let alert = UIAlertView(title: "提示", message: "保存失败", delegate: nil, cancelButtonTitle: "OK"); alert.show(); } } }
mit
481fd2bb66f311db06eb229b5f91444e
32.588235
118
0.588441
4.997812
false
false
false
false
kusl/swift
validation-test/compiler_crashers_fixed/1315-swift-parser-parsebraceitems.swift
12
1324
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing >()) func g<1 { let f = D> a { } extension A { } class func a<d = g<j : () { f<b(n: l.B = [" } get { } enum b { protocol c == [0) """"\() { self.a<Int>) { var f.advance() import Foundation var d where S(i(v: B<T.Type) { import Foundation func a case c>: a { enum b { return !) class func c<T.e == B d(n: A? = g<d return nil public var f(i: A { } } a() { typealias h, () struct c { } map(true } print())-> String { b(b(() -> V { } func a case A" class A> e() { func i: () enum B : end)) { class A? { self.e where l) -> String { } } class func f.d { } return [1): } } convenience init() { print() { let a { } let a { } } protocol A { let a var b<T) -> Self { default: typealias B S.Generator.f : S<b(A(A>() -> T { protocol b { } init(#object1, k : AnyObject.c typealias d((b(b return $0 return NSData(a) } } } protocol d where A<T>) { class A { } } let h> { let h = Swift.advance(A, length: A<D> : B) var d { func f.Generator.A" func e<d<D>() } protocol a { S<d typealias B } } func d func e(false)) func e! } } } class A<T where T : String { func f: a { typealias b = b: d { } class B : SequenceType> () } } }
apache-2.0
03e76a58751153efe4246dd989ba3fe8
11.259259
87
0.589124
2.394213
false
false
false
false
ntnmrndn/R.swift
Sources/RswiftCore/Generators/AssetSubfolders.swift
4
1160
// // AssetSubfolders.swift // R.swift // // Created by Tom Lokhorst on 2017-06-06. // From: https://github.com/mac-cain13/R.swift // License: MIT License // import Foundation struct AssetSubfolders { let folders: [NamespacedAssetSubfolder] let duplicates: [NamespacedAssetSubfolder] init(all subfolders: [NamespacedAssetSubfolder], assetIdentifiers: [SwiftIdentifier]) { var dict: [SwiftIdentifier: NamespacedAssetSubfolder] = [:] for subfolder in subfolders { let name = SwiftIdentifier(name: subfolder.name) if let duplicate = dict[name] { duplicate.subfolders += subfolder.subfolders duplicate.imageAssets += subfolder.imageAssets } else { dict[name] = subfolder } } self.folders = dict.values.filter { !assetIdentifiers.contains(SwiftIdentifier(name: $0.name)) } self.duplicates = dict.values.filter { assetIdentifiers.contains(SwiftIdentifier(name: $0.name)) } } func printWarningsForDuplicates() { for subfolder in duplicates { warn("Skipping asset subfolder because symbol '\(subfolder.name)' would conflict with image: \(subfolder.name)") } } }
mit
658d1ae445d2079a2f2306797d73fb16
28.74359
118
0.698276
4.202899
false
false
false
false
ReactiveKit/ReactiveGitter
Interactors/Authentication.swift
1
1157
// // Authentication.swift // ReactiveGitter // // Created by Srdan Rasic on 15/01/2017. // Copyright © 2017 ReactiveKit. All rights reserved. // import Entities import Networking import ReactiveKit private let clientID = "31625d251b64ec0f01b19577c150f8bcb8c5f6a3" private let secret = "e629e37430a3a37905f642972caf3e6dce28d819" private let redirectURI = "reactive-gitter://token" public class Authentication { public enum AuthorizationResponse { case authorized(String) case unauthorized(String) } public let token: SafeSignal<Token> public init(client: SafeClient, authorizationCode: SafeSignal<AuthorizationResponse>) { token = authorizationCode .flatMapLatest { code -> SafeSignal<Token> in if case .authorized(let code) = code { return Token .get(clientID: clientID, secret: secret, code: code, redirectURI: redirectURI) .response(using: client) .debug() } else { return .never() } } } public var authorizationURL: URL { return AuthenticationAPIClient.authorizationURL(clientID: clientID, redirectURI: redirectURI) } }
mit
c1a23359b0156669097075489e83b95b
25.272727
97
0.700692
3.986207
false
false
false
false
qualaroo/QualarooSDKiOS
Qualaroo/Survey/Body/Question/Text/AnswerTextInteractor.swift
1
1252
// // AnswerTextInteractor.swift // Qualaroo // // Copyright (c) 2018, Qualaroo, Inc. All Rights Reserved. // // Please refer to the LICENSE.md file for the terms and conditions // under which redistribution and use of this file is permitted. // import Foundation class AnswerTextInteractor { private let responseBuilder: AnswerTextResponseBuilder private let validator: AnswerTextValidator private weak var buttonHandler: SurveyButtonHandler? private weak var answerHandler: SurveyAnswerHandler? init(responseBuilder: AnswerTextResponseBuilder, validator: AnswerTextValidator, buttonHandler: SurveyButtonHandler, answerHandler: SurveyAnswerHandler) { self.responseBuilder = responseBuilder self.validator = validator self.buttonHandler = buttonHandler self.answerHandler = answerHandler validateAnswer("") } private func validateAnswer(_ text: String) { let isValid = validator.isValid(text: text) if isValid { buttonHandler?.enableButton() } else { buttonHandler?.disableButton() } } func setAnswer(_ text: String) { validateAnswer(text) let response = responseBuilder.response(text: text) answerHandler?.answerChanged(response) } }
mit
4f4752ac51c7ae73536d48637151364f
27.454545
68
0.731629
4.519856
false
false
false
false
Allow2CEO/browser-ios
brave/src/webview/PrivateBrowsing.swift
1
9972
import Shared import Deferred import Shared private let _singleton = PrivateBrowsing() class PrivateBrowsing { class var singleton: PrivateBrowsing { return _singleton } fileprivate(set) var isOn = false { didSet { getApp().braveTopViewController.setNeedsStatusBarAppearanceUpdate() } } var nonprivateCookies = [HTTPCookie: Bool]() // On startup we are no longer in private mode, if there is a .public cookies file, it means app was killed in private mode, so restore the cookies file func startupCheckIfKilledWhileInPBMode() { webkitDirLocker(false) cookiesFileDiskOperation(.restore) } enum MoveCookies { case savePublicBackup case restore case deletePublicBackup } // GeolocationSites.plist cannot be blocked any other way than locking the filesystem so that webkit can't write it out // TODO: after unlocking, verify that sites from PB are not in the written out GeolocationSites.plist, based on manual testing this // doesn't seem to be the case, but more rigourous test cases are needed fileprivate func webkitDirLocker(_ lock: Bool) { let fm = FileManager.default let baseDir = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true)[0] let webkitDirs = [baseDir + "/WebKit", baseDir + "/Caches"] for dir in webkitDirs { do { try fm.setAttributes([FileAttributeKey.posixPermissions: (lock ? NSNumber(value: 0 as Int16) : NSNumber(value: 0o755 as Int16))], ofItemAtPath: dir) } catch { print(error) } } } fileprivate func cookiesFileDiskOperation( _ type: MoveCookies) { let fm = FileManager.default let baseDir = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true)[0] let cookiesDir = baseDir + "/Cookies" let originSuffix = type == .savePublicBackup ? "cookies" : ".public" do { let contents = try fm.contentsOfDirectory(atPath: cookiesDir) for item in contents { if item.hasSuffix(originSuffix) { if type == .deletePublicBackup { try fm.removeItem(atPath: cookiesDir + "/" + item) } else { var toPath = cookiesDir + "/" if type == .restore { toPath += NSString(string: item).deletingPathExtension } else { toPath += item + ".public" } if fm.fileExists(atPath: toPath) { do { try fm.removeItem(atPath: toPath) } catch {} } try fm.moveItem(atPath: cookiesDir + "/" + item, toPath: toPath) } } } } catch { print(error) } } func enter() { if isOn { return } postAsyncToMain(1.3) { getApp().browserViewController.presentBrowserLockCallout() } isOn = true getApp().tabManager.enterPrivateBrowsingMode(self) cookiesFileDiskOperation(.savePublicBackup) URLCache.shared.memoryCapacity = 0; URLCache.shared.diskCapacity = 0; let storage = HTTPCookieStorage.shared if let cookies = storage.cookies { for cookie in cookies { nonprivateCookies[cookie] = true storage.deleteCookie(cookie) } } NotificationCenter.default.addObserver(self, selector: #selector(PrivateBrowsing.cookiesChanged(_:)), name: NSNotification.Name.NSHTTPCookieManagerCookiesChanged, object: nil) webkitDirLocker(true) UserDefaults.standard.set(true, forKey: "WebKitPrivateBrowsingEnabled") NotificationCenter.default.post(name: NotificationPrivacyModeChanged, object: nil) } fileprivate var exitDeferred = Deferred<Void>() @discardableResult func exit() -> Deferred<Void> { let isAlwaysPrivate = getApp().profile?.prefs.boolForKey(kPrefKeyPrivateBrowsingAlwaysOn) ?? false if isAlwaysPrivate || !isOn { let immediateExit = Deferred<Void>() immediateExit.fill(()) return immediateExit } // Since this an instance var, it needs to be used carefully. // The usage of this deferred, is async, and is generally handled, by a response to a notification // if it is overwritten, it will lead to race conditions, and generally a dropped deferment, since the // notification will be executed on _only_ the newest version of this property exitDeferred = Deferred<Void>() UserDefaults.standard.set(false, forKey: "WebKitPrivateBrowsingEnabled") NotificationCenter.default.removeObserver(self) NotificationCenter.default.addObserver(self, selector: #selector(allWebViewsKilled), name: NSNotification.Name(rawValue: kNotificationAllWebViewsDeallocated), object: nil) if getApp().tabManager.tabs.privateTabs.count < 1 { postAsyncToMain { self.allWebViewsKilled() } } else { getApp().tabManager.removeAllPrivateTabsAndNotify(false) postAsyncToMain(2) { if !self.exitDeferred.isFilled { #if DEBUG BraveApp.showErrorAlert(title: "PrivateBrowsing", error: "exit failed") #endif self.allWebViewsKilled() } } } isOn = false NotificationCenter.default.post(name: NotificationPrivacyModeChanged, object: nil) return exitDeferred } @objc func allWebViewsKilled() { struct ReentrantGuard { static var inFunc = false } if ReentrantGuard.inFunc { // This is kind of a predicament // On one hand, we cannot drop promises, // on the other, if processes are killing webviews, this could end up executing logic that should not happen // so quickly. A better refactor would be to propogate some piece of data (e.g. Bool), that indicates // the current state of promise chain (e.g. ReentrantGuard value) self.exitDeferred.fillIfUnfilled(()) return } ReentrantGuard.inFunc = true NotificationCenter.default.removeObserver(self) postAsyncToMain(0.1) { // just in case any other webkit object cleanup needs to complete if let clazz = NSClassFromString("Web" + "StorageManager") as? NSObjectProtocol { if clazz.responds(to: Selector("shared" + "WebStorageManager")) { if let storage = clazz.perform(Selector("shared" + "WebStorageManager")) { let o = storage.takeUnretainedValue() o.perform(Selector("delete" + "AllOrigins")) } } } if let clazz = NSClassFromString("Web" + "History") as? NSObjectProtocol { if clazz.responds(to: Selector("optional" + "SharedHistory")) { if let webHistory = clazz.perform(Selector("optional" + "SharedHistory")) { let o = webHistory.takeUnretainedValue() o.perform(Selector("remove" + "AllItems")) } } } self.webkitDirLocker(false) getApp().profile?.shutdown() getApp().profile?.db.reopenIfClosed() BraveApp.setupCacheDefaults() // clears PB in-memory-only shield data, loads from disk Domain.loadShieldsIntoMemory { let clear: [Clearable] = [CookiesClearable()] ClearPrivateDataTableViewController.clearPrivateData(clear).uponQueue(DispatchQueue.main) { _ in self.cookiesFileDiskOperation(.deletePublicBackup) let storage = HTTPCookieStorage.shared for cookie in self.nonprivateCookies { storage.setCookie(cookie.0) } self.nonprivateCookies = [HTTPCookie: Bool]() getApp().tabManager.exitPrivateBrowsingMode(self) self.exitDeferred.fillIfUnfilled(()) ReentrantGuard.inFunc = false } } TabMO.clearAllPrivate() } } @objc func cookiesChanged(_ info: Notification) { NotificationCenter.default.removeObserver(self) let storage = HTTPCookieStorage.shared var newCookies = [HTTPCookie]() if let cookies = storage.cookies { for cookie in cookies { if let readOnlyProps = cookie.properties { var props = readOnlyProps as [HTTPCookiePropertyKey: Any] let discard = props[HTTPCookiePropertyKey.discard] as? String if discard == nil || discard! != "TRUE" { props.removeValue(forKey: HTTPCookiePropertyKey.expires) props[HTTPCookiePropertyKey.discard] = "TRUE" storage.deleteCookie(cookie) if let newCookie = HTTPCookie(properties: props) { newCookies.append(newCookie) } } } } } for c in newCookies { storage.setCookie(c) } NotificationCenter.default.addObserver(self, selector: #selector(PrivateBrowsing.cookiesChanged(_:)), name: NSNotification.Name.NSHTTPCookieManagerCookiesChanged, object: nil) } }
mpl-2.0
86eb13bbbb291bc24a365d431fb4c9d9
39.536585
183
0.580024
5.324079
false
false
false
false
yonasstephen/swift-of-airbnb
airbnb-main/airbnb-main/BaseTableController.swift
1
5304
// // BaseTableController.swift // airbnb-main // // Created by Yonas Stephen on 13/3/17. // Copyright © 2017 Yonas Stephen. All rights reserved. // import UIKit protocol BaseTableControllerDelegate { var headerViewHeightConstraint: NSLayoutConstraint? { get set } var headerView: AirbnbExploreHeaderView { get set } var maxHeaderHeight: CGFloat { get } var midHeaderHeight: CGFloat { get } var minHeaderHeight: CGFloat { get } func layoutViews() func updateStatusBar() } class BaseTableController: UIViewController { var headerDelegate: BaseTableControllerDelegate! var previousScrollOffset: CGFloat = 0 var isHiddenStatusBar: Bool = false var statusBarStyle: UIStatusBarStyle = .lightContent override func didMove(toParentViewController parent: UIViewController?) { if let del = parent as? BaseTableControllerDelegate { self.headerDelegate = del } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) UIApplication.shared.statusBarStyle = .default } override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation { return .fade } override var preferredStatusBarStyle: UIStatusBarStyle { return statusBarStyle } override var prefersStatusBarHidden: Bool { return isHiddenStatusBar } func setStatusBarHidden(_ isHidden: Bool, withStyle style: UIStatusBarStyle) { if isHidden != isHiddenStatusBar || statusBarStyle != style { statusBarStyle = style isHiddenStatusBar = isHidden UIView.animate(withDuration: 0.5, animations: { self.headerDelegate.updateStatusBar() }) } } func updateStatusBar() { let curHeight = headerDelegate.headerViewHeightConstraint!.constant if curHeight == headerDelegate.minHeaderHeight { setStatusBarHidden(false, withStyle: .default) } else if curHeight > headerDelegate.minHeaderHeight, curHeight < headerDelegate.midHeaderHeight { setStatusBarHidden(true, withStyle: .lightContent) } else { setStatusBarHidden(false, withStyle: .lightContent) } } } extension BaseTableController: UITableViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { let absoluteTop: CGFloat = 0 let absoluteBottom: CGFloat = max(0, scrollView.contentSize.height - scrollView.frame.height) let scrollDif = scrollView.contentOffset.y - previousScrollOffset let isScrollUp = scrollDif < 0 && scrollView.contentOffset.y < absoluteBottom // swipe down - header expands let isScrollDown = scrollDif > 0 && scrollView.contentOffset.y > absoluteTop // swipe up - header shrinks var newHeight = headerDelegate.headerViewHeightConstraint!.constant if isScrollUp { newHeight = min(headerDelegate.maxHeaderHeight, (headerDelegate.headerViewHeightConstraint!.constant + abs(scrollDif))) } else if isScrollDown { newHeight = max(headerDelegate.minHeaderHeight, (headerDelegate.headerViewHeightConstraint!.constant - abs(scrollDif))) } if newHeight != headerDelegate.headerViewHeightConstraint!.constant { headerDelegate.headerViewHeightConstraint?.constant = newHeight headerDelegate.headerView.updateHeader(newHeight: newHeight, offset: scrollDif) setScrollPosition(scrollView, toPosition: previousScrollOffset) updateStatusBar() } previousScrollOffset = scrollView.contentOffset.y } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { scrollViewDidStopScrolling(scrollView) } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { if !decelerate { scrollViewDidStopScrolling(scrollView) } } func setScrollPosition(_ scrollView: UIScrollView, toPosition position: CGFloat) { scrollView.contentOffset = CGPoint(x: scrollView.contentOffset.x, y: position) } func scrollViewDidStopScrolling(_ scrollView: UIScrollView) { let curHeight = headerDelegate.headerViewHeightConstraint!.constant if curHeight < headerDelegate.midHeaderHeight { setHeaderHeight(scrollView, height: headerDelegate.minHeaderHeight) } else if curHeight < headerDelegate.maxHeaderHeight - headerDelegate.headerView.headerInputHeight { setHeaderHeight(scrollView, height: headerDelegate.midHeaderHeight) } else { setHeaderHeight(scrollView, height: headerDelegate.maxHeaderHeight) } updateStatusBar() } func setHeaderHeight(_ scrollView: UIScrollView, height: CGFloat) { self.headerDelegate.layoutViews() UIView.animate(withDuration: 0.2, animations: { self.headerDelegate.headerViewHeightConstraint?.constant = height self.headerDelegate.headerView.updateHeader(newHeight: height, offset: scrollView.contentOffset.y - self.previousScrollOffset) self.headerDelegate.layoutViews() }) } }
mit
2acad965128d77e35b9cead00d3637dc
37.992647
138
0.688478
5.512474
false
false
false
false
wenghengcong/Coderpursue
BeeFun/Pods/SkeletonView/Sources/SkeletonLayer.swift
1
2046
// // SkeletonLayer.swift // SkeletonView-iOS // // Created by Juanpe Catalán on 02/11/2017. // Copyright © 2017 SkeletonView. All rights reserved. // import UIKit public typealias SkeletonLayerAnimation = (CALayer) -> CAAnimation public enum SkeletonType { case solid case gradient var layer: CALayer { switch self { case .solid: return CALayer() case .gradient: return CAGradientLayer() } } var layerAnimation: SkeletonLayerAnimation { switch self { case .solid: return { $0.pulse } case .gradient: return { $0.sliding } } } } struct SkeletonLayer { private var maskLayer: CALayer private weak var holder: UIView? var type: SkeletonType { return maskLayer is CAGradientLayer ? .gradient : .solid } var contentLayer: CALayer { return maskLayer } init(withType type: SkeletonType, usingColors colors: [UIColor], andSkeletonHolder holder: UIView) { self.holder = holder self.maskLayer = type.layer self.maskLayer.anchorPoint = .zero self.maskLayer.bounds = holder.maxBoundsEstimated addMultilinesIfNeeded() self.maskLayer.tint(withColors: colors) } func removeLayer() { maskLayer.removeFromSuperlayer() } func addMultilinesIfNeeded() { guard let multiLineView = holder as? ContainsMultilineText else { return } maskLayer.addMultilinesLayers(lines: multiLineView.numLines, type: type, lastLineFillPercent: multiLineView.lastLineFillingPercent, multilineCornerRadius: multiLineView.multilineCornerRadius) } } extension SkeletonLayer { func start(_ anim: SkeletonLayerAnimation? = nil) { let animation = anim ?? type.layerAnimation contentLayer.playAnimation(animation, key: "skeletonAnimation") } func stopAnimation() { contentLayer.stopAnimation(forKey: "skeletonAnimation") } }
mit
98e9c2258ec776c713e08667459b6173
25.205128
199
0.646282
4.878282
false
false
false
false
MadAppGang/SmartLog
iOS/Pods/Charts/Source/Charts/Data/Implementations/Standard/ChartDataSet.swift
25
16055
// // ChartDataSet.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation /// Determines how to round DataSet index values for `ChartDataSet.entryIndex(x, rounding)` when an exact x-value is not found. @objc public enum ChartDataSetRounding: Int { case up = 0 case down = 1 case closest = 2 } /// The DataSet class represents one group or type of entries (Entry) in the Chart that belong together. /// It is designed to logically separate different groups of values inside the Chart (e.g. the values for a specific line in the LineChart, or the values of a specific group of bars in the BarChart). open class ChartDataSet: ChartBaseDataSet { public required init() { super.init() _values = [ChartDataEntry]() } public override init(label: String?) { super.init(label: label) _values = [ChartDataEntry]() } public init(values: [ChartDataEntry]?, label: String?) { super.init(label: label) _values = values == nil ? [ChartDataEntry]() : values self.calcMinMax() } public convenience init(values: [ChartDataEntry]?) { self.init(values: values, label: "DataSet") } // MARK: - Data functions and accessors /// the entries that this dataset represents / holds together internal var _values: [ChartDataEntry]! /// maximum y-value in the value array internal var _yMax: Double = -Double.greatestFiniteMagnitude /// minimum y-value in the value array internal var _yMin: Double = Double.greatestFiniteMagnitude /// maximum x-value in the value array internal var _xMax: Double = -Double.greatestFiniteMagnitude /// minimum x-value in the value array internal var _xMin: Double = Double.greatestFiniteMagnitude /// * /// - note: Calls `notifyDataSetChanged()` after setting a new value. /// - returns: The array of y-values that this DataSet represents. open var values: [ChartDataEntry] { get { return _values } set { _values = newValue notifyDataSetChanged() } } /// Use this method to tell the data set that the underlying data has changed open override func notifyDataSetChanged() { calcMinMax() } open override func calcMinMax() { if _values.count == 0 { return } _yMax = -Double.greatestFiniteMagnitude _yMin = Double.greatestFiniteMagnitude _xMax = -Double.greatestFiniteMagnitude _xMin = Double.greatestFiniteMagnitude for e in _values { calcMinMax(entry: e) } } open override func calcMinMaxY(fromX: Double, toX: Double) { if _values.count == 0 { return } _yMax = -Double.greatestFiniteMagnitude _yMin = Double.greatestFiniteMagnitude let indexFrom = entryIndex(x: fromX, closestToY: Double.nan, rounding: .down) let indexTo = entryIndex(x: toX, closestToY: Double.nan, rounding: .up) if indexTo <= indexFrom { return } for i in indexFrom..<indexTo { // only recalculate y calcMinMaxY(entry: _values[i]) } } open func calcMinMaxX(entry e: ChartDataEntry) { if e.x < _xMin { _xMin = e.x } if e.x > _xMax { _xMax = e.x } } open func calcMinMaxY(entry e: ChartDataEntry) { if e.y < _yMin { _yMin = e.y } if e.y > _yMax { _yMax = e.y } } /// Updates the min and max x and y value of this DataSet based on the given Entry. /// /// - parameter e: internal func calcMinMax(entry e: ChartDataEntry) { calcMinMaxX(entry: e) calcMinMaxY(entry: e) } /// - returns: The minimum y-value this DataSet holds open override var yMin: Double { return _yMin } /// - returns: The maximum y-value this DataSet holds open override var yMax: Double { return _yMax } /// - returns: The minimum x-value this DataSet holds open override var xMin: Double { return _xMin } /// - returns: The maximum x-value this DataSet holds open override var xMax: Double { return _xMax } /// - returns: The number of y-values this DataSet represents open override var entryCount: Int { return _values?.count ?? 0 } /// - returns: The entry object found at the given index (not x-value!) /// - throws: out of bounds /// if `i` is out of bounds, it may throw an out-of-bounds exception open override func entryForIndex(_ i: Int) -> ChartDataEntry? { guard i >= 0 && i < _values.count else { return nil } return _values[i] } /// - returns: The first Entry object found at the given x-value with binary search. /// If the no Entry at the specified x-value is found, this method returns the Entry at the closest x-value according to the rounding. /// nil if no Entry object at that x-value. /// - parameter xValue: the x-value /// - parameter closestToY: If there are multiple y-values for the specified x-value, /// - parameter rounding: determine whether to round up/down/closest if there is no Entry matching the provided x-value open override func entryForXValue( _ xValue: Double, closestToY yValue: Double, rounding: ChartDataSetRounding) -> ChartDataEntry? { let index = self.entryIndex(x: xValue, closestToY: yValue, rounding: rounding) if index > -1 { return _values[index] } return nil } /// - returns: The first Entry object found at the given x-value with binary search. /// If the no Entry at the specified x-value is found, this method returns the Entry at the closest x-value. /// nil if no Entry object at that x-value. /// - parameter xValue: the x-value /// - parameter closestToY: If there are multiple y-values for the specified x-value, open override func entryForXValue( _ xValue: Double, closestToY yValue: Double) -> ChartDataEntry? { return entryForXValue(xValue, closestToY: yValue, rounding: .closest) } /// - returns: All Entry objects found at the given xIndex with binary search. /// An empty array if no Entry object at that index. open override func entriesForXValue(_ xValue: Double) -> [ChartDataEntry] { var entries = [ChartDataEntry]() var low = 0 var high = _values.count - 1 while low <= high { var m = (high + low) / 2 var entry = _values[m] // if we have a match if xValue == entry.x { while m > 0 && _values[m - 1].x == xValue { m -= 1 } high = _values.count // loop over all "equal" entries while m < high { entry = _values[m] if entry.x == xValue { entries.append(entry) } else { break } m += 1 } break } else { if xValue > entry.x { low = m + 1 } else { high = m - 1 } } } return entries } /// - returns: The array-index of the specified entry. /// If the no Entry at the specified x-value is found, this method returns the index of the Entry at the closest x-value according to the rounding. /// /// - parameter xValue: x-value of the entry to search for /// - parameter closestToY: If there are multiple y-values for the specified x-value, /// - parameter rounding: Rounding method if exact value was not found open override func entryIndex( x xValue: Double, closestToY yValue: Double, rounding: ChartDataSetRounding) -> Int { var low = 0 var high = _values.count - 1 var closest = high while low < high { let m = (low + high) / 2 let d1 = _values[m].x - xValue let d2 = _values[m + 1].x - xValue let ad1 = abs(d1), ad2 = abs(d2) if ad2 < ad1 { // [m + 1] is closer to xValue // Search in an higher place low = m + 1 } else if ad1 < ad2 { // [m] is closer to xValue // Search in a lower place high = m } else { // We have multiple sequential x-value with same distance if d1 >= 0.0 { // Search in a lower place high = m } else if d1 < 0.0 { // Search in an higher place low = m + 1 } } closest = high } if closest != -1 { let closestXValue = _values[closest].x if rounding == .up { // If rounding up, and found x-value is lower than specified x, and we can go upper... if closestXValue < xValue && closest < _values.count - 1 { closest += 1 } } else if rounding == .down { // If rounding down, and found x-value is upper than specified x, and we can go lower... if closestXValue > xValue && closest > 0 { closest -= 1 } } // Search by closest to y-value if !yValue.isNaN { while closest > 0 && _values[closest - 1].x == closestXValue { closest -= 1 } var closestYValue = _values[closest].y var closestYIndex = closest while true { closest += 1 if closest >= _values.count { break } let value = _values[closest] if value.x != closestXValue { break } if abs(value.y - yValue) < abs(closestYValue - yValue) { closestYValue = yValue closestYIndex = closest } } closest = closestYIndex } } return closest } /// - returns: The array-index of the specified entry /// /// - parameter e: the entry to search for open override func entryIndex(entry e: ChartDataEntry) -> Int { for i in 0 ..< _values.count { if _values[i] === e { return i } } return -1 } /// Adds an Entry to the DataSet dynamically. /// Entries are added to the end of the list. /// This will also recalculate the current minimum and maximum values of the DataSet and the value-sum. /// - parameter e: the entry to add /// - returns: True open override func addEntry(_ e: ChartDataEntry) -> Bool { if _values == nil { _values = [ChartDataEntry]() } calcMinMax(entry: e) _values.append(e) return true } /// Adds an Entry to the DataSet dynamically. /// Entries are added to their appropriate index respective to it's x-index. /// This will also recalculate the current minimum and maximum values of the DataSet and the value-sum. /// - parameter e: the entry to add /// - returns: True open override func addEntryOrdered(_ e: ChartDataEntry) -> Bool { if _values == nil { _values = [ChartDataEntry]() } calcMinMax(entry: e) if _values.count > 0 && _values.last!.x > e.x { var closestIndex = entryIndex(x: e.x, closestToY: e.y, rounding: .up) while _values[closestIndex].x < e.x { closestIndex += 1 } _values.insert(e, at: closestIndex) } else { _values.append(e) } return true } /// Removes an Entry from the DataSet dynamically. /// This will also recalculate the current minimum and maximum values of the DataSet and the value-sum. /// - parameter entry: the entry to remove /// - returns: `true` if the entry was removed successfully, else if the entry does not exist open override func removeEntry(_ entry: ChartDataEntry) -> Bool { var removed = false for i in 0 ..< _values.count { if _values[i] === entry { _values.remove(at: i) removed = true break } } if removed { calcMinMax() } return removed } /// Removes the first Entry (at index 0) of this DataSet from the entries array. /// /// - returns: `true` if successful, `false` ifnot. open override func removeFirst() -> Bool { let entry: ChartDataEntry? = _values.isEmpty ? nil : _values.removeFirst() let removed = entry != nil if removed { calcMinMax() } return removed } /// Removes the last Entry (at index size-1) of this DataSet from the entries array. /// /// - returns: `true` if successful, `false` ifnot. open override func removeLast() -> Bool { let entry: ChartDataEntry? = _values.isEmpty ? nil : _values.removeLast() let removed = entry != nil if removed { calcMinMax() } return removed } /// Checks if this DataSet contains the specified Entry. /// - returns: `true` if contains the entry, `false` ifnot. open override func contains(_ e: ChartDataEntry) -> Bool { for entry in _values { if (entry.isEqual(e)) { return true } } return false } /// Removes all values from this DataSet and recalculates min and max value. open override func clear() { _values.removeAll(keepingCapacity: true) notifyDataSetChanged() } // MARK: - Data functions and accessors // MARK: - NSCopying open override func copyWithZone(_ zone: NSZone?) -> AnyObject { let copy = super.copyWithZone(zone) as! ChartDataSet copy._values = _values copy._yMax = _yMax copy._yMin = _yMin return copy } }
mit
9f4697f846d8057513e83a2fa966b373
27.980144
199
0.503893
5
false
false
false
false
victorpimentel/SwiftLint
Source/SwiftLintFramework/Rules/CyclomaticComplexityRule.swift
2
4420
// // CyclomaticComplexityRule.swift // SwiftLint // // Created by Denis Lebedev on 24/1/16. // Copyright © 2016 Realm. All rights reserved. // import Foundation import SourceKittenFramework public struct CyclomaticComplexityRule: ASTRule, ConfigurationProviderRule { public var configuration = CyclomaticComplexityConfiguration(warning: 10, error: 20) public init() {} public static let description = RuleDescription( identifier: "cyclomatic_complexity", name: "Cyclomatic Complexity", description: "Complexity of function bodies should be limited.", nonTriggeringExamples: [ "func f1() {\nif true {\nfor _ in 1..5 { } }\nif false { }\n}", "func f(code: Int) -> Int {" + "switch code {\n case 0: fallthrough\ncase 0: return 1\ncase 0: return 1\n" + "case 0: return 1\ncase 0: return 1\ncase 0: return 1\ncase 0: return 1\n" + "case 0: return 1\ncase 0: return 1\ndefault: return 1}}", "func f1() {" + "if true {}; if true {}; if true {}; if true {}; if true {}; if true {}\n" + "func f2() {\n" + "if true {}; if true {}; if true {}; if true {}; if true {}\n" + "}}" ], triggeringExamples: [ "↓func f1() {\n if true {\n if true {\n if false {}\n }\n" + " }\n if false {}\n let i = 0\n\n switch i {\n case 1: break\n" + " case 2: break\n case 3: break\n case 4: break\n default: break\n }\n" + " for _ in 1...5 {\n guard true else {\n return\n }\n }\n}\n" ] ) public func validate(file: File, kind: SwiftDeclarationKind, dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] { guard SwiftDeclarationKind.functionKinds().contains(kind) else { return [] } let complexity = measureComplexity(in: file, dictionary: dictionary) for parameter in configuration.params where complexity > parameter.value { let offset = dictionary.offset ?? 0 return [StyleViolation(ruleDescription: type(of: self).description, severity: parameter.severity, location: Location(file: file, byteOffset: offset), reason: "Function should have complexity \(configuration.length.warning) or less: " + "currently complexity equals \(complexity)")] } return [] } private func measureComplexity(in file: File, dictionary: [String: SourceKitRepresentable]) -> Int { var hasSwitchStatements = false let complexity = dictionary.substructure.reduce(0) { complexity, subDict in guard let kind = subDict.kind else { return complexity } if let declarationKind = SwiftDeclarationKind(rawValue: kind), SwiftDeclarationKind.functionKinds().contains(declarationKind) { return complexity } guard let statementKind = StatementKind(rawValue: kind) else { return complexity + measureComplexity(in: file, dictionary: subDict) } if statementKind == .switch { hasSwitchStatements = true } let score = configuration.complexityStatements.contains(statementKind) ? 1 : 0 return complexity + score + measureComplexity(in: file, dictionary: subDict) } if hasSwitchStatements && !configuration.ignoresCaseStatements { return reduceSwitchComplexity(initialComplexity: complexity, file: file, dictionary: dictionary) } return complexity } // Switch complexity is reduced by `fallthrough` cases private func reduceSwitchComplexity(initialComplexity complexity: Int, file: File, dictionary: [String: SourceKitRepresentable]) -> Int { let bodyOffset = dictionary.bodyOffset ?? 0 let bodyLength = dictionary.bodyLength ?? 0 let c = file.contents.bridge() .substringWithByteRange(start: bodyOffset, length: bodyLength) ?? "" let fallthroughCount = c.components(separatedBy: "fallthrough").count - 1 return complexity - fallthroughCount } }
mit
6e6b2f46897a8fe670596a9891cb4872
39.898148
108
0.584107
4.785482
false
true
false
false
gkaimakas/SwiftyForms
SwiftyForms/Classes/Sections/Section.swift
1
3973
// // Section.swift // Pods // // Created by Γιώργος Καϊμακάς on 24/05/16. // // import Foundation open class Section { open let name: String open var data: [String: Any] { return _inputs .map() { $0.data } .filter() { $0 != nil } .map() { $0! } .reduce([String: Any]()) { return $0.0.mergeWith($0.1) } } open var enabled: Bool { didSet { for event in _enabledEvents { event(self) } } } open var errors: [String] { var array: [String] = [] for input in _inputs { array.append(contentsOf: input.errors) } return array } open var hidden: Bool { didSet { for event in _hiddenEvents { event(self) } } } open var isSubmitted: Bool { return _submitted } open var isValid: Bool { _validate() return _valid } open var numberOfInputs: Int { return _inputs .filter() { $0.hidden == false } .count } fileprivate var _valid: Bool = true fileprivate var _submitted: Bool = false fileprivate var _inputs: [Input] = [] fileprivate var _enabledEvents: [(Section) -> Void] = [] fileprivate var _hiddenEvents: [(Section) -> Void] = [] fileprivate var _valueEvents: [(Section, Input) -> Void] = [] fileprivate var _validateEvents: [(Section) -> Void] = [] fileprivate var _submitEvents: [(Section) -> Void] = [] fileprivate var _inputAddedEvents: [(Section, Input, Int) -> Void] = [] fileprivate var _inputRemovedEvents: [(Section, Input, Int) -> Void] = [] fileprivate var _inputHiddenEvents: [(Section, Input, Int) -> Void] = [] public init(name: String, inputs: [Input] = []) { self.name = name self.enabled = true self.hidden = false for input in inputs { let _ = addInput(input) } } @discardableResult open func addInput(_ input: Input) -> Self { let _ = input .on(value: { input in let _ = self._valueEvents .map() { $0(self, input) } }) .on(hidden: { input in self._inputHiddenEvents .iterate() { event in } }) if input.hidden == true { _inputs.append(input) } if input.hidden == false { let index = _inputs.count _inputs.append(input) for event in _inputAddedEvents { event(self, input, index) } } return self } @discardableResult open func inputAtIndex(_ index: Int) -> Input { let visibleInputs = _inputs .filter() { $0.hidden == false } return visibleInputs[index] } @discardableResult open func on(value: ((Section, Input)-> Void)? = nil, validated: ((Section) -> Void)? = nil, enabled: ((Section) -> Void)? = nil, hidden: ((Section) -> Void)? = nil, submit: ((Section) -> Void)? = nil ) -> Self { if let event = value { _valueEvents.append(event) } if let event = validated { _validateEvents.append(event) } if let event = enabled { _enabledEvents.append(event) } if let event = hidden { _enabledEvents.append(event) } if let event = submit { _submitEvents.append(event) } return self } @discardableResult open func on(inputAdded: ((Section, Input, Int) -> Void)? = nil, inputHidden: ((Section, Input, Int) -> Void)? = nil, inputRemoved: ((Section, Input, Int) -> Void)? = nil) -> Self { if let event = inputAdded { _inputAddedEvents.append(event) } if let event = inputHidden { _inputHiddenEvents.append(event) } if let event = inputRemoved { _inputRemovedEvents.append(event) } return self } open func submit() { let _ = _inputs .map() { $0.submit() } for event in _submitEvents { event(self) } } open func validate() -> Bool { _validate() for event in _validateEvents { event(self) } return _valid } fileprivate func _validate() { _valid = _inputs .map() { $0.validate() } .reduce(true) { $0 && $1 } } }
mit
840fbf8cb4c55999cb1b6bc53aa57317
18.120773
90
0.578322
3.14127
false
false
false
false
diwu/LeetCode-Solutions-in-Swift
Solutions/SolutionsTests/Easy/Easy_009_Palindrome_Number_Test.swift
1
2395
// // Easy_009_Palindrome_Number_Test.swift // Solutions // // Created by Wu, Di on 3/27/15. // Copyright (c) 2015 diwu. All rights reserved. // import XCTest class Easy_009_Palindrome_Number_Test: XCTestCase, SolutionsTestCase { func test_001() { let input: Int = -121 let expected: Bool = true asyncHelper(input: input, expected: expected) } func test_002() { let input: Int = 121 let expected: Bool = true asyncHelper(input: input, expected: expected) } func test_003() { let input: Int = 0 let expected: Bool = true asyncHelper(input: input, expected: expected) } func test_004() { let input: Int = Int.max let expected: Bool = false asyncHelper(input: input, expected: expected) } func test_005() { let input: Int = Int.min let expected: Bool = false asyncHelper(input: input, expected: expected) } func test_006() { let input: Int = 1999999999999999999 let expected: Bool = false asyncHelper(input: input, expected: expected) } func test_007() { let input: Int = -1999999999999999999 let expected: Bool = false asyncHelper(input: input, expected: expected) } func test_008() { let input: Int = Int.min let expected: Bool = false asyncHelper(input: input, expected: expected) } func test_009() { let input: Int = Int.max let expected: Bool = false asyncHelper(input: input, expected: expected) } func asyncHelper(input: Int, expected: Bool ) { weak var expectation: XCTestExpectation? = self.expectation(description:timeOutName()) serialQueue().async(execute: { () -> Void in let result: Bool = Easy_009_Palindrome_Number.isPalindrome(input) assertHelper(result == expected, problemName:self.problemName(), input: input, resultValue: result, expectedValue: expected) if let unwrapped = expectation { unwrapped.fulfill() } }) waitForExpectations(timeout:timeOut()) { (error: Error?) -> Void in if error != nil { assertHelper(false, problemName:self.problemName(), input: input, resultValue:self.timeOutName(), expectedValue: expected) } } } }
mit
512547468f39ab54ff7fedd9f1b7c4f0
31.364865
138
0.59833
4.323105
false
true
false
false
narner/AudioKit
AudioKit/Common/Nodes/Effects/Filters/Low Shelf Parametric Equalizer Filter/AKLowShelfParametricEqualizerFilter.swift
1
4973
// // AKLowShelfParametricEqualizerFilter.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright © 2017 Aurelius Prochazka. All rights reserved. // /// This is an implementation of Zoelzer's parametric equalizer filter. /// open class AKLowShelfParametricEqualizerFilter: AKNode, AKToggleable, AKComponent, AKInput { public typealias AKAudioUnitType = AKLowShelfParametricEqualizerFilterAudioUnit /// Four letter unique description of the node public static let ComponentDescription = AudioComponentDescription(effect: "peq1") // MARK: - Properties private var internalAU: AKAudioUnitType? private var token: AUParameterObserverToken? fileprivate var cornerFrequencyParameter: AUParameter? fileprivate var gainParameter: AUParameter? fileprivate var qParameter: AUParameter? /// Ramp Time represents the speed at which parameters are allowed to change @objc open dynamic var rampTime: Double = AKSettings.rampTime { willSet { internalAU?.rampTime = newValue } } /// Corner frequency. @objc open dynamic var cornerFrequency: Double = 1_000 { willSet { if cornerFrequency != newValue { if internalAU?.isSetUp() ?? false { if let existingToken = token { cornerFrequencyParameter?.setValue(Float(newValue), originator: existingToken) } } else { internalAU?.cornerFrequency = Float(newValue) } } } } /// Amount at which the corner frequency value shall be increased or decreased. A value of 1 is a flat response. @objc open dynamic var gain: Double = 1.0 { willSet { if gain != newValue { if internalAU?.isSetUp() ?? false { if let existingToken = token { gainParameter?.setValue(Float(newValue), originator: existingToken) } } else { internalAU?.gain = Float(newValue) } } } } /// Q of the filter. sqrt(0.5) is no resonance. @objc open dynamic var q: Double = 0.707 { willSet { if q != newValue { if internalAU?.isSetUp() ?? false { if let existingToken = token { qParameter?.setValue(Float(newValue), originator: existingToken) } } else { internalAU?.q = Float(newValue) } } } } /// Tells whether the node is processing (ie. started, playing, or active) @objc open dynamic var isStarted: Bool { return internalAU?.isPlaying() ?? false } // MARK: - Initialization /// Initialize this equalizer node /// /// - Parameters: /// - input: Input node to process /// - cornerFrequency: Corner frequency. /// - gain: Amount at which the corner frequency value shall be increased or decreased. /// A value of 1 is a flat response. /// - q: Q of the filter. sqrt(0.5) is no resonance. /// @objc public init( _ input: AKNode? = nil, cornerFrequency: Double = 1_000, gain: Double = 1.0, q: Double = 0.707) { self.cornerFrequency = cornerFrequency self.gain = gain self.q = q _Self.register() super.init() AVAudioUnit._instantiate(with: _Self.ComponentDescription) { [weak self] avAudioUnit in self?.avAudioNode = avAudioUnit self?.internalAU = avAudioUnit.auAudioUnit as? AKAudioUnitType input?.connect(to: self!) } guard let tree = internalAU?.parameterTree else { AKLog("Parameter Tree Failed") return } cornerFrequencyParameter = tree["cornerFrequency"] gainParameter = tree["gain"] qParameter = tree["q"] token = tree.token(byAddingParameterObserver: { [weak self] _, _ in guard let _ = self else { AKLog("Unable to create strong reference to self") return } // Replace _ with strongSelf if needed DispatchQueue.main.async { // This node does not change its own values so we won't add any // value observing, but if you need to, this is where that goes. } }) internalAU?.cornerFrequency = Float(cornerFrequency) internalAU?.gain = Float(gain) internalAU?.q = Float(q) } // MARK: - Control /// Function to start, play, or activate the node, all do the same thing @objc open func start() { internalAU?.start() } /// Function to stop or bypass the node, both are equivalent @objc open func stop() { internalAU?.stop() } }
mit
e2b4b1b6195b7bf21f0ca9e6e1a3613c
32.369128
116
0.576629
5.068298
false
false
false
false
apple/swift-experimental-string-processing
Tests/MatchingEngineTests/UtilTests.swift
1
2388
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2021-2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // //===----------------------------------------------------------------------===// import XCTest @testable import _RegexParser class UtilTests: XCTestCase { func testTupleTypeConstruction() { XCTAssertTrue(TypeConstruction.tupleType( of: []) == Void.self) XCTAssertTrue(TypeConstruction.tupleType( of: [Int.self, Any.self]) == (Int, Any).self) XCTAssertTrue( TypeConstruction.tupleType( of: [[Int].self, [Int: Int].self, Void.self, Any.self]) == ([Int], [Int: Int], Void, Any).self) } func testTypeErasedTupleConstruction() throws { do { let tupleErased = TypeConstruction.tuple(of: [1, 2, 3]) let tuple = try XCTUnwrap(tupleErased as? (Int, Int, Int)) XCTAssertEqual(tuple.0, 1) XCTAssertEqual(tuple.1, 2) XCTAssertEqual(tuple.2, 3) } do { let tupleErased = TypeConstruction.tuple( of: [[1, 2], [true, false], [3.0, 4.0]]) XCTAssertTrue(type(of: tupleErased) == ([Int], [Bool], [Double]).self) let tuple = try XCTUnwrap(tupleErased as? ([Int], [Bool], [Double])) XCTAssertEqual(tuple.0, [1, 2]) XCTAssertEqual(tuple.1, [true, false]) XCTAssertEqual(tuple.2, [3.0, 4.0]) } // Reproducer for a memory corruption bug with transformed captures. do { enum GraphemeBreakProperty: UInt32 { case control = 0 case prepend = 1 } let tupleErased = TypeConstruction.tuple(of: [ "a"[...], // Substring Unicode.Scalar(0xA6F0)!, // Unicode.Scalar Unicode.Scalar(0xA6F0) as Any, // Unicode.Scalar? GraphemeBreakProperty.prepend // GraphemeBreakProperty ]) let tuple = try XCTUnwrap( tupleErased as? (Substring, Unicode.Scalar, Unicode.Scalar, GraphemeBreakProperty)) XCTAssertEqual(tuple.0, "a") XCTAssertEqual(tuple.1, Unicode.Scalar(0xA6F0)!) XCTAssertEqual(tuple.2, Unicode.Scalar(0xA6F0)!) XCTAssertEqual(tuple.3, .prepend) } } }
apache-2.0
148edd6d2ecbbe2109a9dd1ae57f68b6
34.641791
80
0.586683
4.054329
false
true
false
false
stephentyrone/swift
test/ClangImporter/objc_ir.swift
2
19255
// RUN: %empty-directory(%t) // RUN: %build-clang-importer-objc-overlays // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -module-name objc_ir -I %S/Inputs/custom-modules -emit-ir -g -o - -primary-file %s | %FileCheck %s // REQUIRES: objc_interop // REQUIRES: OS=macosx // CHECK: %TSo1BC = type import ObjectiveC import Foundation import objc_ext import TestProtocols import ObjCIRExtras import objc_generics // CHECK: @"\01L_selector_data(method:withFloat:)" = private global [18 x i8] c"method:withFloat:\00" // CHECK: @"\01L_selector_data(method:withDouble:)" = private global [19 x i8] c"method:withDouble:\00" // CHECK: @"\01L_selector_data(method:separateExtMethod:)" = private global [26 x i8] c"method:separateExtMethod:\00", section "__TEXT,__objc_methname,cstring_literals" // Instance method invocation // CHECK-LABEL: define hidden swiftcc void @"$s7objc_ir15instanceMethodsyySo1BCF"(%TSo1BC* func instanceMethods(_ b: B) { // CHECK: load i8*, i8** @"\01L_selector(method:withFloat:)" // CHECK: call i32 bitcast (void ()* @objc_msgSend to i32 var i = b.method(1, with: 2.5 as Float) // CHECK: load i8*, i8** @"\01L_selector(method:withDouble:)" // CHECK: call i32 bitcast (void ()* @objc_msgSend to i32 i = i + b.method(1, with: 2.5 as Double) } // CHECK-LABEL: define hidden swiftcc void @"$s7objc_ir16extensionMethods1bySo1BC_tF" func extensionMethods(b b: B) { // CHECK: load i8*, i8** @"\01L_selector(method:separateExtMethod:)", align 8 // CHECK: [[T0:%.*]] = call i8* bitcast (void ()* @objc_msgSend to i8* // CHECK-NEXT: [[T1:%.*]] = {{.*}}call i8* @llvm.objc.retainAutoreleasedReturnValue(i8* [[T0]]) // CHECK-NOT: [[T0]] // CHECK: [[T1]] b.method(1, separateExtMethod:1.5) } // CHECK-LABEL: define hidden swiftcc void @"$s7objc_ir19initCallToAllocInit1iys5Int32V_tF" func initCallToAllocInit(i i: CInt) { // CHECK: call {{.*}} @"$sSo1BC3intABSgs5Int32V_tcfC" B(int: i) } // CHECK-LABEL: linkonce_odr hidden {{.*}} @"$sSo1BC3intABSgs5Int32V_tcfC" // CHECK: call [[OPAQUE:%.*]]* @objc_allocWithZone // Indexed subscripting // CHECK-LABEL: define hidden swiftcc void @"$s7objc_ir19indexedSubscripting1b3idx1aySo1BC_SiSo1ACtF" func indexedSubscripting(b b: B, idx: Int, a: A) { // CHECK: load i8*, i8** @"\01L_selector(setObject:atIndexedSubscript:)", align 8 b[idx] = a // CHECK: load i8*, i8** @"\01L_selector(objectAtIndexedSubscript:)" var a2 = b[idx] as! A } // CHECK-LABEL: define hidden swiftcc void @"$s7objc_ir17keyedSubscripting1b3idx1aySo1BC_So1ACAItF" func keyedSubscripting(b b: B, idx: A, a: A) { // CHECK: load i8*, i8** @"\01L_selector(setObject:forKeyedSubscript:)" b[a] = a // CHECK: load i8*, i8** @"\01L_selector(objectForKeyedSubscript:)" var a2 = b[a] as! A } // CHECK-LABEL: define hidden swiftcc void @"$s7objc_ir14propertyAccess1bySo1BC_tF" func propertyAccess(b b: B) { // CHECK: load i8*, i8** @"\01L_selector(counter)" // CHECK: load i8*, i8** @"\01L_selector(setCounter:)" b.counter = b.counter + 1 // CHECK: load %objc_class*, %objc_class** @"OBJC_CLASS_REF_$_B" // CHECK: load i8*, i8** @"\01L_selector(sharedCounter)" // CHECK: load i8*, i8** @"\01L_selector(setSharedCounter:)" B.sharedCounter = B.sharedCounter + 1 } // CHECK-LABEL: define hidden swiftcc %TSo1BC* @"$s7objc_ir8downcast1aSo1BCSo1AC_tF"( func downcast(a a: A) -> B { // CHECK: [[CLASS:%.*]] = load %objc_class*, %objc_class** @"OBJC_CLASS_REF_$_B" // CHECK: [[T0:%.*]] = call %objc_class* @{{.*}}(%objc_class* [[CLASS]]) // CHECK: [[T1:%.*]] = bitcast %objc_class* [[T0]] to i8* // CHECK: call i8* @swift_dynamicCastObjCClassUnconditional(i8* [[A:%.*]], i8* [[T1]], {{.*}}) [[NOUNWIND:#[0-9]+]] return a as! B } // CHECK-LABEL: define hidden swiftcc void @"$s7objc_ir19almostSubscriptable3as11aySo06AlmostD0C_So1ACtF" func almostSubscriptable(as1 as1: AlmostSubscriptable, a: A) { as1.objectForKeyedSubscript(a) } // CHECK-LABEL: define hidden swiftcc void @"$s7objc_ir13protocolTypes1a1bySo7NSMinceC_So9NSRuncing_ptF"(%TSo7NSMinceC* %0, %objc_object* %1) {{.*}} { func protocolTypes(a a: NSMince, b: NSRuncing) { // - (void)eatWith:(id <NSRuncing>)runcer; a.eat(with: b) // CHECK: [[SEL:%.*]] = load i8*, i8** @"\01L_selector(eatWith:)", align 8 // CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OPAQUE:%.*]]*, i8*, i8*)*)([[OPAQUE:%.*]]* {{%.*}}, i8* [[SEL]], i8* {{%.*}}) } // CHECK-LABEL: define hidden swiftcc void @"$s7objc_ir6getset1pySo8FooProto_p_tF"(%objc_object* %0) {{.*}} { func getset(p p: FooProto) { // CHECK: load i8*, i8** @"\01L_selector(bar)" // CHECK: load i8*, i8** @"\01L_selector(setBar:)" let prop = p.bar p.bar = prop } // CHECK-LABEL: define hidden swiftcc %swift.type* @"$s7objc_ir16protocolMetatype1pSo8FooProto_pXpSoAD_p_tF"(%objc_object* %0) {{.*}} { func protocolMetatype(p: FooProto) -> FooProto.Type { // CHECK: = call %swift.type* @swift_getObjectType(%objc_object* %0) // CHECK-NOT: {{retain|release}} // CHECK: [[RAW_RESULT:%.+]] = call i8* @processFooType(i8* {{%.+}}) // CHECK: [[CASTED_RESULT:%.+]] = bitcast i8* [[RAW_RESULT]] to %objc_class* // CHECK: [[SWIFT_RESULT:%.+]] = call %swift.type* @swift_getObjCClassMetadata(%objc_class* [[CASTED_RESULT]]) // CHECK-NOT: call void @swift_unknownObjectRelease(%objc_object* %0) // CHECK: ret %swift.type* [[SWIFT_RESULT]] let type = processFooType(Swift.type(of: p)) return type } // CHECK: } class Impl: FooProto, AnotherProto { @objc var bar: Int32 = 0 } // CHECK-LABEL: define hidden swiftcc %swift.type* @"$s7objc_ir27protocolCompositionMetatype1pSo12AnotherProto_So03FooG0pXpAA4ImplC_tF"(%T7objc_ir4ImplC* %0) {{.*}} { func protocolCompositionMetatype(p: Impl) -> (FooProto & AnotherProto).Type { // CHECK: = getelementptr inbounds %T7objc_ir4ImplC, %T7objc_ir4ImplC* %0, i32 0, i32 0, i32 0 // CHECK-NOT: {{retain|release}} // CHECK: [[RAW_RESULT:%.+]] = call i8* @processComboType(i8* {{%.+}}) // CHECK: [[CASTED_RESULT:%.+]] = bitcast i8* [[RAW_RESULT]] to %objc_class* // CHECK: [[SWIFT_RESULT:%.+]] = call %swift.type* @swift_getObjCClassMetadata(%objc_class* [[CASTED_RESULT]]) // CHECK-NOT: call void bitcast (void (%swift.refcounted*)* @swift_release to void (%T7objc_ir4ImplC*)*)(%T7objc_ir4ImplC* %0) // CHECK: ret %swift.type* [[SWIFT_RESULT]] let type = processComboType(Swift.type(of: p)) return type } // CHECK: } // CHECK-LABEL: define hidden swiftcc %swift.type* @"$s7objc_ir28protocolCompositionMetatype21pSo12AnotherProto_So03FooG0pXpAA4ImplC_tF"(%T7objc_ir4ImplC* %0) {{.*}} { func protocolCompositionMetatype2(p: Impl) -> (FooProto & AnotherProto).Type { // CHECK: = getelementptr inbounds %T7objc_ir4ImplC, %T7objc_ir4ImplC* %0, i32 0, i32 0, i32 0 // CHECK-NOT: {{retain|release}} // CHECK: [[RAW_RESULT:%.+]] = call i8* @processComboType2(i8* {{%.+}}) // CHECK: [[CASTED_RESULT:%.+]] = bitcast i8* [[RAW_RESULT]] to %objc_class* // CHECK: [[SWIFT_RESULT:%.+]] = call %swift.type* @swift_getObjCClassMetadata(%objc_class* [[CASTED_RESULT]]) // CHECK-NOT: @swift_release // CHECK: ret %swift.type* [[SWIFT_RESULT]] let type = processComboType2(Swift.type(of: p)) return type } // CHECK: } // CHECK-LABEL: define hidden swiftcc void @"$s7objc_ir17pointerPropertiesyySo14PointerWrapperCF"(%TSo14PointerWrapperC* %0) {{.*}} { func pointerProperties(_ obj: PointerWrapper) { // CHECK: load i8*, i8** @"\01L_selector(setVoidPtr:)" // CHECK: load i8*, i8** @"\01L_selector(setIntPtr:)" // CHECK: load i8*, i8** @"\01L_selector(setIdPtr:)" obj.voidPtr = nil as UnsafeMutableRawPointer? obj.intPtr = nil as UnsafeMutablePointer? obj.idPtr = nil as AutoreleasingUnsafeMutablePointer? } // CHECK-LABEL: define hidden swiftcc void @"$s7objc_ir16strangeSelectorsyySo13SwiftNameTestCF"(%TSo13SwiftNameTestC* %0) {{.*}} { func strangeSelectors(_ obj: SwiftNameTest) { // CHECK: load i8*, i8** @"\01L_selector(:b:)" obj.empty(a: 0, b: 0) } // CHECK-LABEL: define hidden swiftcc void @"$s7objc_ir20customFactoryMethodsyyF"() {{.*}} { func customFactoryMethods() { // CHECK: call swiftcc %TSo13SwiftNameTestC* @"$sSo13SwiftNameTestC10dummyParamAByt_tcfCTO" // CHECK: call swiftcc %TSo13SwiftNameTestC* @"$sSo13SwiftNameTestC2ccABypSg_tcfCTO" // CHECK: call swiftcc %TSo13SwiftNameTestC* @"$sSo13SwiftNameTestC5emptyABs5Int32V_tcfCTO" _ = SwiftNameTest(dummyParam: ()) _ = SwiftNameTest(cc: nil) _ = SwiftNameTest(empty: 0) // CHECK: load i8*, i8** @"\01L_selector(testZ)" // CHECK: load i8*, i8** @"\01L_selector(testY:)" // CHECK: load i8*, i8** @"\01L_selector(testX:xx:)" // CHECK: load i8*, i8** @"\01L_selector(::)" _ = SwiftNameTest.zz() _ = SwiftNameTest.yy(aa: nil) _ = SwiftNameTest.xx(nil, bb: nil) _ = SwiftNameTest.empty(1, 2) do { // CHECK: call swiftcc %TSo18SwiftNameTestErrorC* @"$sSo18SwiftNameTestErrorC5errorAByt_tKcfCTO" // CHECK: call swiftcc %TSo18SwiftNameTestErrorC* @"$sSo18SwiftNameTestErrorC2aa5errorABypSg_yttKcfCTO" // CHECK: call swiftcc %TSo18SwiftNameTestErrorC* @"$sSo18SwiftNameTestErrorC2aa5error5blockABypSg_ytyyctKcfCTO" // CHECK: call swiftcc %TSo18SwiftNameTestErrorC* @"$sSo18SwiftNameTestErrorC5error5blockAByt_yyctKcfCTO" // CHECK: call swiftcc %TSo18SwiftNameTestErrorC* @"$sSo18SwiftNameTestErrorC2aaABypSg_tKcfCTO" // CHECK: call swiftcc %TSo18SwiftNameTestErrorC* @"$sSo18SwiftNameTestErrorC2aa5blockABypSg_yyctKcfCTO" // CHECK: call swiftcc %TSo18SwiftNameTestErrorC* @"$sSo18SwiftNameTestErrorC5blockAByyc_tKcfCTO" _ = try SwiftNameTestError(error: ()) _ = try SwiftNameTestError(aa: nil, error: ()) _ = try SwiftNameTestError(aa: nil, error: (), block: {}) _ = try SwiftNameTestError(error: (), block: {}) _ = try SwiftNameTestError(aa: nil) _ = try SwiftNameTestError(aa: nil, block: {}) _ = try SwiftNameTestError(block: {}) // CHECK: load i8*, i8** @"\01L_selector(testW:error:)" // CHECK: load i8*, i8** @"\01L_selector(testW2:error:)" // CHECK: load i8*, i8** @"\01L_selector(testV:)" // CHECK: load i8*, i8** @"\01L_selector(testV2:)" _ = try SwiftNameTestError.ww(nil) _ = try SwiftNameTestError.w2(nil, error: ()) _ = try SwiftNameTestError.vv() _ = try SwiftNameTestError.v2(error: ()) } catch _ { } } // CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo13SwiftNameTestC* @"$sSo13SwiftNameTestC10dummyParamAByt_tcfCTO" // CHECK: load i8*, i8** @"\01L_selector(b)" // CHECK: } // CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo13SwiftNameTestC* @"$sSo13SwiftNameTestC2ccABypSg_tcfCTO" // CHECK: load i8*, i8** @"\01L_selector(c:)" // CHECK: } // CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo18SwiftNameTestErrorC* @"$sSo18SwiftNameTestErrorC5errorAByt_tKcfCTO" // CHECK: load i8*, i8** @"\01L_selector(err1:)" // CHECK: } // CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo18SwiftNameTestErrorC* @"$sSo18SwiftNameTestErrorC2aa5errorABypSg_yttKcfCTO" // CHECK: load i8*, i8** @"\01L_selector(err2:error:)" // CHECK: } // CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo18SwiftNameTestErrorC* @"$sSo18SwiftNameTestErrorC2aa5error5blockABypSg_ytyyctKcfCTO" // CHECK: load i8*, i8** @"\01L_selector(err3:error:callback:)" // CHECK: } // CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo18SwiftNameTestErrorC* @"$sSo18SwiftNameTestErrorC5error5blockAByt_yyctKcfCTO" // CHECK: load i8*, i8** @"\01L_selector(err4:callback:)" // CHECK: } // CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo18SwiftNameTestErrorC* @"$sSo18SwiftNameTestErrorC2aaABypSg_tKcfCTO" // CHECK: load i8*, i8** @"\01L_selector(err5:error:)" // CHECK: } // CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo18SwiftNameTestErrorC* @"$sSo18SwiftNameTestErrorC2aa5blockABypSg_yyctKcfCTO" // CHECK: load i8*, i8** @"\01L_selector(err6:error:callback:)" // CHECK: } // CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo18SwiftNameTestErrorC* @"$sSo18SwiftNameTestErrorC5blockAByyc_tKcfCTO" // CHECK: load i8*, i8** @"\01L_selector(err7:callback:)" // CHECK: } // CHECK-LABEL: define hidden swiftcc void @"$s7objc_ir29customFactoryMethodsInheritedyyF"() {{.*}} { func customFactoryMethodsInherited() { // CHECK: call swiftcc %TSo16SwiftNameTestSubC* @"$sSo16SwiftNameTestSubC10dummyParamAByt_tcfCTO" // CHECK: call swiftcc %TSo16SwiftNameTestSubC* @"$sSo16SwiftNameTestSubC2ccABypSg_tcfCTO" _ = SwiftNameTestSub(dummyParam: ()) _ = SwiftNameTestSub(cc: nil) // CHECK: load i8*, i8** @"\01L_selector(testZ)" // CHECK: load i8*, i8** @"\01L_selector(testY:)" // CHECK: load i8*, i8** @"\01L_selector(testX:xx:)" _ = SwiftNameTestSub.zz() _ = SwiftNameTestSub.yy(aa: nil) _ = SwiftNameTestSub.xx(nil, bb: nil) do { // CHECK: call swiftcc %TSo21SwiftNameTestErrorSubC* @"$sSo21SwiftNameTestErrorSubC5errorAByt_tKcfCTO" // CHECK: call swiftcc %TSo21SwiftNameTestErrorSubC* @"$sSo21SwiftNameTestErrorSubC2aa5errorABypSg_yttKcfCTO" // CHECK: call swiftcc %TSo21SwiftNameTestErrorSubC* @"$sSo21SwiftNameTestErrorSubC2aa5error5blockABypSg_ytyyctKcfCTO" // CHECK: call swiftcc %TSo21SwiftNameTestErrorSubC* @"$sSo21SwiftNameTestErrorSubC5error5blockAByt_yyctKcfCTO" // CHECK: call swiftcc %TSo21SwiftNameTestErrorSubC* @"$sSo21SwiftNameTestErrorSubC2aaABypSg_tKcfCTO" // CHECK: call swiftcc %TSo21SwiftNameTestErrorSubC* @"$sSo21SwiftNameTestErrorSubC2aa5blockABypSg_yyctKcfCTO" // CHECK: call swiftcc %TSo21SwiftNameTestErrorSubC* @"$sSo21SwiftNameTestErrorSubC5blockAByyc_tKcfCTO" _ = try SwiftNameTestErrorSub(error: ()) _ = try SwiftNameTestErrorSub(aa: nil, error: ()) _ = try SwiftNameTestErrorSub(aa: nil, error: (), block: {}) _ = try SwiftNameTestErrorSub(error: (), block: {}) _ = try SwiftNameTestErrorSub(aa: nil) _ = try SwiftNameTestErrorSub(aa: nil, block: {}) _ = try SwiftNameTestErrorSub(block: {}) // CHECK: load i8*, i8** @"\01L_selector(testW:error:)" // CHECK: load i8*, i8** @"\01L_selector(testW2:error:)" // CHECK: load i8*, i8** @"\01L_selector(testV:)" // CHECK: load i8*, i8** @"\01L_selector(testV2:)" _ = try SwiftNameTestErrorSub.ww(nil) _ = try SwiftNameTestErrorSub.w2(nil, error: ()) _ = try SwiftNameTestErrorSub.vv() _ = try SwiftNameTestErrorSub.v2(error: ()) } catch _ { } } // CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo16SwiftNameTestSubC* @"$sSo16SwiftNameTestSubC10dummyParamAByt_tcfCTO" // CHECK: load i8*, i8** @"\01L_selector(b)" // CHECK: } // CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo16SwiftNameTestSubC* @"$sSo16SwiftNameTestSubC2ccABypSg_tcfCTO" // CHECK: load i8*, i8** @"\01L_selector(c:)" // CHECK: } // CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo21SwiftNameTestErrorSubC* @"$sSo21SwiftNameTestErrorSubC5errorAByt_tKcfCTO" // CHECK: load i8*, i8** @"\01L_selector(err1:)" // CHECK: } // CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo21SwiftNameTestErrorSubC* @"$sSo21SwiftNameTestErrorSubC2aa5errorABypSg_yttKcfCTO" // CHECK: load i8*, i8** @"\01L_selector(err2:error:)" // CHECK: } // CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo21SwiftNameTestErrorSubC* @"$sSo21SwiftNameTestErrorSubC2aa5error5blockABypSg_ytyyctKcfCTO" // CHECK: load i8*, i8** @"\01L_selector(err3:error:callback:)" // CHECK: } // CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo21SwiftNameTestErrorSubC* @"$sSo21SwiftNameTestErrorSubC5error5blockAByt_yyctKcfCTO" // CHECK: load i8*, i8** @"\01L_selector(err4:callback:)" // CHECK: } // CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo21SwiftNameTestErrorSubC* @"$sSo21SwiftNameTestErrorSubC2aaABypSg_tKcfCTO" // CHECK: load i8*, i8** @"\01L_selector(err5:error:)" // CHECK: } // CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo21SwiftNameTestErrorSubC* @"$sSo21SwiftNameTestErrorSubC2aa5blockABypSg_yyctKcfCTO" // CHECK: load i8*, i8** @"\01L_selector(err6:error:callback:)" // CHECK: } // CHECK-LABEL: define linkonce_odr hidden swiftcc %TSo21SwiftNameTestErrorSubC* @"$sSo21SwiftNameTestErrorSubC5blockAByyc_tKcfCTO" // CHECK: load i8*, i8** @"\01L_selector(err7:callback:)" // CHECK: } // CHECK-LABEL: define hidden swiftcc void @"$s7objc_ir30testCompatibilityAliasMangling3objySo13SwiftNameTestC_tF" func testCompatibilityAliasMangling(obj: SwiftNameAlias) { // CHECK: call void @llvm.dbg.declare(metadata %TSo13SwiftNameTestC** {{%.+}}, metadata ![[SWIFT_NAME_ALIAS_VAR:[0-9]+]], metadata !DIExpression()) } func testGenericCompatibilityAliasMangling(generic_obj: SwiftGenericNameAlias<NSNumber>) { // CHECK: call void @llvm.dbg.declare(metadata %TSo20SwiftGenericNameTestCySo8NSNumberCG** {{%.+}}, metadata ![[SWIFT_GENERIC_NAME_ALIAS_VAR:[0-9]+]], metadata !DIExpression()) } func testConstrGenericCompatibilityAliasMangling(constr_generic_obj: SwiftConstrGenericNameAlias<NSNumber>) { // CHECK: call void @llvm.dbg.declare(metadata %TSo26SwiftConstrGenericNameTestCySo8NSNumberCG** {{%.+}}, metadata ![[SWIFT_CONSTR_GENERIC_NAME_ALIAS_VAR:[0-9]+]], metadata !DIExpression()) } // CHECK-LABEL: s7objc_ir22testBlocksWithGenerics3hbaypSo13HasBlockArrayC_tF func testBlocksWithGenerics(hba: HasBlockArray) -> Any { // CHECK: s7objc_ir22testBlocksWithGenerics3hbaypSo13HasBlockArrayC_tFSayyyXBGycAEcfu_AFycfu0_TA let _ = hba.blockPointerType() return hba.blockArray } // CHECK-LABEL: linkonce_odr hidden {{.*}} @"$sSo1BC3intABSgs5Int32V_tcfcTO" // CHECK: load i8*, i8** @"\01L_selector(initWithInt:)" // CHECK: call [[OPAQUE:%.*]]* bitcast (void ()* @objc_msgSend // CHECK: attributes [[NOUNWIND]] = { nounwind } // CHECK: ![[SWIFT_NAME_ALIAS_VAR]] = !DILocalVariable(name: "obj", arg: 1, scope: !{{[0-9]+}}, file: !{{[0-9]+}}, line: {{[0-9]+}}, type: ![[SWIFT_NAME_ALIAS_TYPE:[0-9]+]]) // CHECK: ![[LET_SWIFT_NAME_ALIAS_TYPE:[0-9]+]] = !DIDerivedType(tag: DW_TAG_const_type, baseType: ![[SWIFT_NAME_ALIAS_TYPE:[0-9]+]]) // CHECK: ![[SWIFT_NAME_ALIAS_TYPE]] = !DIDerivedType(tag: DW_TAG_typedef, name: "$sSo14SwiftNameAliasaD", scope: !{{[0-9]+}}, file: !{{[0-9]+}}, baseType: !{{[0-9]+}}) // CHECK: ![[SWIFT_GENERIC_NAME_ALIAS_VAR]] = !DILocalVariable(name: "generic_obj", arg: 1, scope: !{{[0-9]+}}, file: !{{[0-9]+}}, line: {{[0-9]+}}, type: ![[LET_SWIFT_GENERIC_NAME_ALIAS_TYPE:[0-9]+]]) // CHECK: ![[LET_SWIFT_GENERIC_NAME_ALIAS_TYPE:[0-9]+]] = !DIDerivedType(tag: DW_TAG_const_type, baseType: ![[SWIFT_GENERIC_NAME_ALIAS_TYPE:[0-9]+]]) // CHECK: ![[SWIFT_GENERIC_NAME_ALIAS_TYPE]] = !DIDerivedType(tag: DW_TAG_typedef, name: "$sSo21SwiftGenericNameAliasaySo8NSNumberCGD", scope: !{{[0-9]+}}, file: !{{[0-9]+}}, baseType: !{{[0-9]+}}) // CHECK: ![[SWIFT_CONSTR_GENERIC_NAME_ALIAS_VAR]] = !DILocalVariable(name: "constr_generic_obj", arg: 1, scope: !{{[0-9]+}}, file: !{{[0-9]+}}, line: {{[0-9]+}}, type: ![[LET_SWIFT_CONSTR_GENERIC_NAME_ALIAS_TYPE:[0-9]+]]) // CHECK: ![[LET_SWIFT_CONSTR_GENERIC_NAME_ALIAS_TYPE:[0-9]+]] = !DIDerivedType(tag: DW_TAG_const_type, baseType: ![[SWIFT_CONSTR_GENERIC_NAME_ALIAS_TYPE:[0-9]+]]) // CHECK: ![[SWIFT_CONSTR_GENERIC_NAME_ALIAS_TYPE]] = !DIDerivedType(tag: DW_TAG_typedef, name: "$sSo27SwiftConstrGenericNameAliasaySo8NSNumberCGD", scope: !{{[0-9]+}}, file: !{{[0-9]+}}, baseType: !{{[0-9]+}})
apache-2.0
837cc389f27c6620c6e8748c9d548ae1
50.760753
222
0.69208
3.353945
false
true
false
false
jvivas/OraChallenge
OraChallenge/Pods/DTZFloatingActionButton/DTZFloatingActionButton/Classes/DTZFABManager.swift
1
960
// // DTZFABManager.swift // DTZFloatingActionButton // // Created by hintoz on 10.02.17. // Copyright © 2017 Evgeny Dats. All rights reserved. // import UIKit open class DTZFABManager { static open let shared = DTZFABManager() private init() {} var fabWindow = DTZFABWindow(frame: UIScreen.main.bounds) var fabController = DTZFABViewController() open func show() { fabWindow.rootViewController = fabController fabWindow.isHidden = false UIView.animate(withDuration: 0.3, animations: { () -> Void in self.fabWindow.alpha = 1 }) } open func hide() { UIView.animate(withDuration: 0.3, animations: { () -> Void in self.fabWindow.alpha = 0 }, completion: { finished in self.fabWindow.isHidden = true }) } open func button() -> DTZFloatingActionButton { return fabController.fab } }
apache-2.0
e169dcd8c364d3337415b37da998ac9d
22.975
69
0.601668
4.133621
false
false
false
false