repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
gewill/Feeyue
refs/heads/develop
Feeyue/Main/Weibo/Views/GWStatusOnePhotoCell.swift
mit
1
// // GWStatusOnePhotoCell.swift // Feeyue // // Created by Will on 11/05/2017. // Copyright © 2017 Will. All rights reserved. // import UIKit import SnapKit protocol GWStatusOnePhotoCellDelegate: class { func statusOnePhotoCelDidClickPhoto(_ cell: GWStatusOnePhotoCell) } class GWStatusOnePhotoCell: UICollectionViewCell { var oneImageView: UIImageView! weak var delegate: GWStatusOnePhotoCellDelegate? var status: Status? { didSet { if self.status?.hasRetweetedPics == true { self.backgroundColor = GWColor.f2 } else { self.backgroundColor = UIColor.white } if let status = status { setupImageWith(urlArray: status.largePics) } } } // MARK: - life cycle override init(frame: CGRect) { super.init(frame: frame) setupViews() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupViews() } private func setupViews() { oneImageView = UIImageView() oneImageView.clipsToBounds = true oneImageView.contentMode = .scaleAspectFill oneImageView.gw_addTapGestureRecognizer(target: self, action: #selector(self.oneImageViewClick(_:))) self.addSubview(oneImageView) oneImageView.snp.makeConstraints { (make) in make.edges.equalToSuperview().inset(UIEdgeInsets(top: 0, left: 16, bottom: 16, right: 16)) } } // MARK: - config methods static func cellSize() -> CGSize { return CGSize(width: ScreenWidth, height: ScreenWidth - 16 * 2 + 16) } // MARK: - response methods @objc func oneImageViewClick(_ sender: UITapGestureRecognizer) { delegate?.statusOnePhotoCelDidClickPhoto(self) } // MARK: - private methods private func setupImageWith(urlArray array: [String]) { if array.count == 1 { var string = array[0] if array[0].hasSuffix(".gif") == true { let playImageView = UIImageView() playImageView.image = UIImage(named: "MMVideoPreviewPlayHL") self.oneImageView.addSubview(playImageView) playImageView.snp.makeConstraints({ (make) in make.center.equalToSuperview() make.width.height.equalTo(60) }) string = string.replacingOccurrences(of: "/bmiddle/", with: "/or480/") } if let url = URL(string: string) { self.oneImageView.kf.setImage(with: url, placeholder: PlaceholderView.randomColor()) } } } }
08573ac93c06e3738b4283589c60bd40
28.163043
108
0.600447
false
false
false
false
biohazardlover/ByTrain
refs/heads/master
ByTrain/Entities/Train.swift
mit
1
import SwiftyJSON public struct Train { public var train_no: String? /// 车次 public var station_train_code: String? public var start_station_telecode: String? /// 出发站 public var start_station_name: String? public var end_station_telecode: String? /// 到达站 public var end_station_name: String? public var from_station_telecode: String? public var from_station_name: String? public var to_station_telecode: String? public var to_station_name: String? /// 出发时间 public var start_time: String? /// 到达时间 public var arrive_time: String? public var day_difference: String? public var train_class_name: String? /// 历时 public var lishi: String? public var canWebBuy: String? public var lishiValue: String? /// 余票信息 public var yp_info: String? public var control_train_day: String? public var start_train_date: String? public var seat_feature: String? public var yp_ex: String? public var train_seat_feature: String? public var seat_types: String? public var location_code: String? public var from_station_no: String? public var to_station_no: String? public var control_day: String? public var sale_time: String? public var is_support_card: String? public var gg_num: String? /// 高级软卧 public var gr_num: String? /// 其他 public var qt_num: String? /// 软卧 public var rw_num: String? /// 软座 public var rz_num: String? /// 特等座 public var tz_num: String? /// 无座 public var wz_num: String? public var yb_num: String? /// 硬卧 public var yw_num: String? /// 硬座 public var yz_num: String? /// 二等座 public var ze_num: String? /// 一等座 public var zy_num: String? /// 商务座 public var swz_num: String? public var secretStr: String? public var buttonTextInfo: String? public var distance: String? public var fromStation: Station? public var toStation: Station? public var departureDate: Date? public var businessClassSeatType: SeatType public var specialClassSeatType: SeatType public var firstClassSeatType: SeatType public var secondClassSeatType: SeatType public var premiumSoftRoometteType: SeatType public var softRoometteType: SeatType public var hardRoometteType: SeatType public var softSeatType: SeatType public var hardSeatType: SeatType public var noSeatType: SeatType public var otherType: SeatType public var allSeatTypes: [SeatType] public var duration: String? { if let durationInMinutes = Int(lishiValue ?? "") { let days = durationInMinutes / (60 * 24) let hours = (durationInMinutes % (60 * 24)) / 60 let minutes = (durationInMinutes % (60 * 24)) % 60 var duration = "" if days > 0 { duration += "\(days)天" } if hours > 0 { duration += "\(hours)小时" } duration += "\(minutes)分" return duration } return nil } /// yyyy-MM-dd public var departureDateString: String? { if let start_train_date = start_train_date { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyyMMdd" if let departureDate = dateFormatter.date(from: start_train_date) { dateFormatter.dateFormat = "yyyy-MM-dd" return dateFormatter.string(from: departureDate) } } return nil } public var availableSeatTypes: [SeatType] { let availableSeatTypes = allSeatTypes.filter { (seatType) -> Bool in return seatType.leftSeats != "--" } return availableSeatTypes } public var highlightedSeatType: SeatType? { for seatType in availableSeatTypes.reversed() { if seatType.leftSeats != "无" { return seatType } } return availableSeatTypes.last } public init() { businessClassSeatType = SeatType(identifier: SeatTypeIdentifierBusinessClassSeat) specialClassSeatType = SeatType(identifier: SeatTypeIdentifierSpecialClassSeat) firstClassSeatType = SeatType(identifier: SeatTypeIdentifierFirstClassSeat) secondClassSeatType = SeatType(identifier: SeatTypeIdentifierSecondClassSeat) premiumSoftRoometteType = SeatType(identifier: SeatTypeIdentifierPremiumSoftRoomette) softRoometteType = SeatType(identifier: SeatTypeIdentifierSoftRoomette) hardRoometteType = SeatType(identifier: SeatTypeIdentifierHardRoomette) softSeatType = SeatType(identifier: SeatTypeIdentifierSoftSeat) hardSeatType = SeatType(identifier: SeatTypeIdentifierHardSeat) noSeatType = SeatType(identifier: SeatTypeIdentifierNoSeat) otherType = SeatType(identifier: SeatTypeIdentifierOther) allSeatTypes = [businessClassSeatType, specialClassSeatType, firstClassSeatType, secondClassSeatType, premiumSoftRoometteType, softRoometteType, hardRoometteType, softSeatType, hardSeatType, noSeatType, otherType] } } extension Train: Equatable { public static func ==(lhs: Train, rhs: Train) -> Bool { return lhs.train_no == rhs.train_no } } extension Train: ResponseObjectSerializable { init?(response: HTTPURLResponse, representation: Any) { guard let representation = representation as? JSON else { return nil } self.init() let queryLeftNewDTO = representation["queryLeftNewDTO"] train_no = queryLeftNewDTO["train_no"].string station_train_code = queryLeftNewDTO["station_train_code"].string start_station_telecode = queryLeftNewDTO["start_station_telecode"].string start_station_name = queryLeftNewDTO["start_station_name"].string end_station_telecode = queryLeftNewDTO["end_station_telecode"].string end_station_name = queryLeftNewDTO["end_station_name"].string from_station_telecode = queryLeftNewDTO["from_station_telecode"].string from_station_name = queryLeftNewDTO["from_station_name"].string to_station_telecode = queryLeftNewDTO["to_station_telecode"].string to_station_name = queryLeftNewDTO["to_station_name"].string start_time = queryLeftNewDTO["start_time"].string arrive_time = queryLeftNewDTO["arrive_time"].string day_difference = queryLeftNewDTO["day_difference"].string train_class_name = queryLeftNewDTO["train_class_name"].string lishi = queryLeftNewDTO["lishi"].string canWebBuy = queryLeftNewDTO["canWebBuy"].string lishiValue = queryLeftNewDTO["lishiValue"].string yp_info = queryLeftNewDTO["yp_info"].string control_train_day = queryLeftNewDTO["control_train_day"].string start_train_date = queryLeftNewDTO["start_train_date"].string seat_feature = queryLeftNewDTO["seat_feature"].string yp_ex = queryLeftNewDTO["yp_ex"].string train_seat_feature = queryLeftNewDTO["train_seat_feature"].string seat_types = queryLeftNewDTO["seat_types"].string location_code = queryLeftNewDTO["location_code"].string from_station_no = queryLeftNewDTO["from_station_no"].string to_station_no = queryLeftNewDTO["to_station_no"].string control_day = queryLeftNewDTO["control_day"].string sale_time = queryLeftNewDTO["sale_time"].string is_support_card = queryLeftNewDTO["is_support_card"].string gg_num = queryLeftNewDTO["gg_num"].string gr_num = queryLeftNewDTO["gr_num"].string qt_num = queryLeftNewDTO["qt_num"].string rw_num = queryLeftNewDTO["rw_num"].string rz_num = queryLeftNewDTO["rz_num"].string tz_num = queryLeftNewDTO["tz_num"].string wz_num = queryLeftNewDTO["wz_num"].string yb_num = queryLeftNewDTO["yb_num"].string yw_num = queryLeftNewDTO["yw_num"].string yz_num = queryLeftNewDTO["yz_num"].string ze_num = queryLeftNewDTO["ze_num"].string zy_num = queryLeftNewDTO["zy_num"].string swz_num = queryLeftNewDTO["swz_num"].string secretStr = representation["secretStr"].string buttonTextInfo = representation["buttonTextInfo"].string businessClassSeatType.leftSeats = swz_num specialClassSeatType.leftSeats = tz_num firstClassSeatType.leftSeats = zy_num secondClassSeatType.leftSeats = ze_num premiumSoftRoometteType.leftSeats = gr_num softRoometteType.leftSeats = rw_num hardRoometteType.leftSeats = yw_num softSeatType.leftSeats = rz_num hardSeatType.leftSeats = yz_num noSeatType.leftSeats = wz_num otherType.leftSeats = qt_num } }
9c10dd202038f8f7664c52341aad5237
32.606618
221
0.640958
false
false
false
false
richy486/EndlessPageView
refs/heads/master
EndlessPageView/EndlessPageView.swift
mit
1
// // EndlessPageView.swift // EndlessPageView // // Created by Richard Adem on 6/21/16. // Copyright © 2016 Richard Adem. All rights reserved. // import UIKit import Interpolate public struct IndexLocation : Hashable { public var column:Int public var row:Int public var hashValue: Int { if MemoryLayout<Int>.size == MemoryLayout<Int64>.size { return column.hashValue | (row.hashValue << 32) } else { return column.hashValue | (row.hashValue << 16) } } public init(column: Int, row: Int) { self.column = column self.row = row } } public func == (lhs: IndexLocation, rhs: IndexLocation) -> Bool { return lhs.column == rhs.column && lhs.row == rhs.row } public protocol EndlessPageViewDataSource : class { func endlessPageView(_ endlessPageView:EndlessPageView, cellForIndexLocation indexLocation: IndexLocation) -> EndlessPageCell? } public protocol EndlessPageViewDelegate : class { func endlessPageViewDidSelectItemAtIndex(_ indexLocation: IndexLocation) func endlessPageViewWillScroll(_ endlessPageView: EndlessPageView) func endlessPageViewDidScroll(_ endlessPageView: EndlessPageView) func endlessPageViewShouldScroll(_ endlessPageView: EndlessPageView, scrollingDirection: EndlessPageScrollDirectionRules) -> EndlessPageScrollDirectionRules func endlessPageView(_ endlessPageView: EndlessPageView, willDisplayCell cell: EndlessPageCell, forItemAtIndexLocation indexLocation: IndexLocation) func endlessPageView(_ endlessPageView: EndlessPageView, didEndDisplayingCell cell: EndlessPageCell, forItemAtIndexLocation indexLocation: IndexLocation) func endlessPageViewDidEndDecelerating(_ endlessPageView: EndlessPageView) } public struct EndlessPageScrollDirectionRules : OptionSet { public var rawValue : UInt8 public init(rawValue: UInt8) { self.rawValue = rawValue } public static let Horizontal = EndlessPageScrollDirectionRules(rawValue: 1 << 0) public static let Vertical = EndlessPageScrollDirectionRules(rawValue: 1 << 2) public static var Both : EndlessPageScrollDirectionRules = [ .Horizontal, .Vertical ] } @IBDesignable open class EndlessPageView : UIView, UIGestureRecognizerDelegate, _EndlessPageCellDelegate { // - Public - // Protocols open weak var dataSource:EndlessPageViewDataSource? open weak var delegate:EndlessPageViewDelegate? // Public settings open var printDebugInfo = false open var scrollDirection:EndlessPageScrollDirectionRules = .Both open var pagingEnabled = true open var directionalLockEnabled = true fileprivate(set) open var directionLockedTo:EndlessPageScrollDirectionRules = .Both // - Private - // Offset position open var contentOffset = CGPoint.zero { didSet { if contentOffset.x.isNaN || contentOffset.y.isNaN { contentOffset = oldValue } updateBounds() updateCells() } } fileprivate var panStartContentOffset = CGPoint.zero open var scrollingInDirection: CGFloat { get { if directionLockedTo == .Horizontal { return self.bounds.origin.x - panStartContentOffset.x } else if directionLockedTo == .Vertical { return self.bounds.origin.y - panStartContentOffset.y } return CGFloat(0) } } // Cell pool fileprivate var cellPool = [String: [EndlessPageCell]]() fileprivate var registeredCellClasses = [String: EndlessPageCell.Type]() fileprivate var visibleCellsFromLocation = [IndexLocation: EndlessPageCell]() // Animation fileprivate var offsetChangeAnimation:Interpolate? fileprivate var hasDoneFirstReload = false // MARK: View lifecycle override public init(frame: CGRect) { super.init(frame: frame) setup() } convenience public init () { self.init(frame:CGRect.zero) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } fileprivate func setup() { let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(panGesture_scroll(_:))) panGestureRecognizer.delegate = self addGestureRecognizer(panGestureRecognizer) clipsToBounds = true } override open func layoutSubviews() { super.layoutSubviews() if !hasDoneFirstReload { hasDoneFirstReload = true reloadData() } } override open func prepareForInterfaceBuilder() { print("prepareForInterfaceBuilder") } // MARK: Actions func panGesture_scroll(_ panGesture: UIPanGestureRecognizer) { if let gestureView = panGesture.view, let holder = gestureView.superview { let translatePoint = panGesture.translation(in: holder) var runCompletion = false if panGesture.state == UIGestureRecognizerState.began { panStartContentOffset = contentOffset if let offsetChangeAnimation = offsetChangeAnimation { runCompletion = false offsetChangeAnimation.stopAnimation() } delegate?.endlessPageViewWillScroll(self) } if panGesture.state == UIGestureRecognizerState.changed { contentOffset = { var point = contentOffset guard scrollDirection != [] else { return panStartContentOffset } if scrollDirection.contains(.Horizontal) { point.x = (panStartContentOffset - translatePoint).x } if scrollDirection.contains(.Vertical) { point.y = (panStartContentOffset - translatePoint).y } if directionalLockEnabled { if directionLockedTo == .Both { let deltaX = abs(panStartContentOffset.x - point.x) let deltaY = abs(panStartContentOffset.y - point.y) if deltaX != 0 && deltaY != 0 { if deltaX >= deltaY { directionLockedTo = [.Horizontal] } else { directionLockedTo = [.Vertical] } } } } guard directionLockedTo != [] else { return panStartContentOffset } if let allowedScrollDirection = delegate?.endlessPageViewShouldScroll(self, scrollingDirection: directionLockedTo) { guard allowedScrollDirection != [] else { return panStartContentOffset } if !allowedScrollDirection.contains(.Horizontal) { point.x = panStartContentOffset.x } if !allowedScrollDirection.contains(.Vertical) { point.y = panStartContentOffset.y } } return point }() } if panGesture.state == UIGestureRecognizerState.ended { if let offsetChangeAnimation = offsetChangeAnimation { runCompletion = false offsetChangeAnimation.stopAnimation() } if pagingEnabled { let offsetPage = floor((panStartContentOffset / self.bounds.size) + 0.5) var targetColumn = Int(offsetPage.x) var targetRow = Int(offsetPage.y) let localizedOffset = contentOffset - (CGPoint(x: targetColumn, y: targetRow) * self.bounds.size) let triggerPercent = CGFloat(0.1) if abs(localizedOffset.x) > self.bounds.size.width * triggerPercent { if contentOffset.x > panStartContentOffset.x { targetColumn += 1 } else if contentOffset.x < panStartContentOffset.x { targetColumn -= 1 } } else if abs(localizedOffset.y) > self.bounds.size.height * triggerPercent { if contentOffset.y > panStartContentOffset.y { targetRow += 1 } else if contentOffset.y < panStartContentOffset.y { targetRow -= 1 } } var pagePoint = CGPoint(x: CGFloat(targetColumn), y: CGFloat(targetRow)) * self.bounds.size // Check if cell exists, we already have loaded the visible cells if visibleCellsFromLocation[IndexLocation(column: targetColumn, row: targetRow)] == nil { let targetColumn = Int(offsetPage.x) let targetRow = Int(offsetPage.y) pagePoint = CGPoint(x: CGFloat(targetColumn), y: CGFloat(targetRow)) * self.bounds.size } if printDebugInfo { print("targetColumn: \(targetColumn), targetRow: \(targetRow)") } let animationTime:TimeInterval = 0.2 runCompletion = true offsetChangeAnimation = Interpolate(from: contentOffset , to: pagePoint , function: BasicInterpolation.easeOut , apply: { [weak self] (pos) in self?.contentOffset = pos self?.updateBounds() self?.updateCells() }) offsetChangeAnimation?.animate(1.0, duration: CGFloat(animationTime), completion: { [weak self] in if runCompletion { if let strongSelf = self { strongSelf.directionLockedTo = .Both strongSelf.delegate?.endlessPageViewDidEndDecelerating(strongSelf) } } }) } else { let velocity = panGesture.velocity(in: holder) * -1 let magnitude = sqrt(pow(velocity.x, 2) + pow(velocity.y, 2)) let slideMult = magnitude / 200 let slideFactor = 0.1 * slideMult let animationTime = TimeInterval(slideFactor * 2) let slideToPoint:CGPoint = { var point = contentOffset if scrollDirection.contains(.Horizontal) { point.x = contentOffset.x + (velocity.x * slideFactor) } if scrollDirection.contains(.Vertical) { point.y = contentOffset.y + (velocity.y * slideFactor) } return point }() offsetChangeAnimation = Interpolate(from: contentOffset , to: slideToPoint , function: BasicInterpolation.easeOut , apply: { [weak self] (pos) in self?.contentOffset = pos }) offsetChangeAnimation?.animate(1.0, duration: CGFloat(animationTime), completion: { [weak self] in if let strongSelf = self { strongSelf.directionLockedTo = .Both strongSelf.delegate?.endlessPageViewDidEndDecelerating(strongSelf) } }) } } } } // MARK: Public getters open func visibleCells() -> [EndlessPageCell] { return Array(visibleCellsFromLocation.values) } open func indexLocationsForVisibleItems() -> [IndexLocation] { return Array(visibleCellsFromLocation.keys) } open func indexLocationForCell(_ cell: EndlessPageCell) -> IndexLocation? { let pagePoint = round(cell.frame.origin / self.bounds.size, tollerence: 0.0001) if !pagePoint.x.isNaN && !pagePoint.y.isNaN { let indexLocation = IndexLocation(column: Int(pagePoint.x), row: Int(pagePoint.y)) return indexLocation } return nil } open func setContentOffset(_ offset: CGPoint, animated: Bool) { if let indexLocation = indexLocationForItemAtPoint(offset) { scrollToItemAtIndexLocation(indexLocation, animated: animated) } } open func indexLocationForItemAtPoint(_ point: CGPoint) -> IndexLocation? { let pagePoint = round(point / self.bounds.size, tollerence: 0.0001) if !pagePoint.x.isNaN && !pagePoint.y.isNaN { let indexLocation = IndexLocation(column: Int(pagePoint.x), row: Int(pagePoint.y)) return indexLocation } return nil } open func indexLocationFromContentOffset() -> IndexLocation? { return indexLocationForItemAtPoint(contentOffset) } open func cellForItemAtIndexLocation(_ indexLocation: IndexLocation) -> EndlessPageCell? { if let cell = visibleCellsFromLocation[indexLocation] { return cell } else if let cell = dataSource?.endlessPageView(self, cellForIndexLocation: indexLocation) { visibleCellsFromLocation[indexLocation] = cell addSubview(cell) delegate?.endlessPageView(self, willDisplayCell: cell, forItemAtIndexLocation: indexLocation) return cell } return nil } open func scrollToItemAtIndexLocation(_ indexLocation: IndexLocation, animated:Bool) { let animationTime = TimeInterval(animated ? 0.25 : 0.0) let pagePoint = CGPoint(x: indexLocation.column, y: indexLocation.row) * self.bounds.size if let offsetChangeAnimation = offsetChangeAnimation { offsetChangeAnimation.stopAnimation() offsetChangeAnimation.invalidate() } if animated { if contentOffset.x != pagePoint.x && contentOffset.y == pagePoint.y { directionLockedTo = [.Horizontal] } else if contentOffset.x == pagePoint.x && contentOffset.y != pagePoint.y { directionLockedTo = [.Vertical] } else { directionLockedTo = .Both } } offsetChangeAnimation = Interpolate(from: contentOffset , to: pagePoint , function: BasicInterpolation.easeOut , apply: { [weak self] (pos) in self?.contentOffset = pos }) offsetChangeAnimation?.animate(1.0, duration: CGFloat(animationTime), completion: { [weak self] in if let strongSelf = self { strongSelf.contentOffset = pagePoint strongSelf.delegate?.endlessPageViewDidEndDecelerating(strongSelf) } }) } // MARK: Data cache open func reloadData() { let keys = visibleCellsFromLocation.keys keys.forEach({ (indexLocation) in if let cell = visibleCellsFromLocation[indexLocation] { delegate?.endlessPageView(self, didEndDisplayingCell: cell, forItemAtIndexLocation: indexLocation) cell.removeFromSuperview() } visibleCellsFromLocation[indexLocation] = nil }) contentOffset = CGPoint.zero updateBounds() updateCells() } open func setIndexLocation(_ indexLocation: IndexLocation) { let position = CGPoint(x: CGFloat(indexLocation.column) * self.frame.width , y: CGFloat(indexLocation.row) * self.frame.height) contentOffset = position updateBounds() } open func registerClass(_ cellClass: EndlessPageCell.Type?, forViewWithReuseIdentifier identifier: String) { registeredCellClasses[identifier] = cellClass } open func registerNib(_ nib: UINib?, forViewWithReuseIdentifier identifier: String) { fatalError("registerNib(nib:forViewWithReuseIdentifier:) has not been implemented") } open func dequeueReusableCellWithReuseIdentifier(_ identifier: String) -> EndlessPageCell { if cellPool[identifier] == nil { cellPool[identifier] = [EndlessPageCell]() } // This could probably be faster with two arrays for is use and not in use if let cells = cellPool[identifier] { for cell in cells { if cell.superview == nil { cell.prepareForReuse() return cell } } } if let cellClass = registeredCellClasses[identifier] { let cell = cellClass.init(frame: bounds) cell.privateDelegate = self cellPool[identifier]?.append(cell) if printDebugInfo { print("generated cell for identifer: \(identifier), pool size: ", cellPool[identifier]?.count) } return cell } fatalError(String(format: "Did not register class %@ for EndlessPageView ", identifier)) } // MARK: Update cells fileprivate func updateBounds() { bounds = CGRect(origin: contentOffset, size: bounds.size) delegate?.endlessPageViewDidScroll(self) } fileprivate func updateCells() { let pageOffset = round(contentOffset / CGPoint(x: self.frame.width, y: self.frame.height) , tollerence: 0.0001) if !pageOffset.x.isNaN && !pageOffset.y.isNaN { let rows:[Int] = { if pageOffset.y >= 0 { return floor(pageOffset.y) == pageOffset.y ? [Int(pageOffset.y)] : [Int(pageOffset.y), Int(pageOffset.y + 1)] } return floor(pageOffset.y) == pageOffset.y ? [Int(pageOffset.y)] : [Int(pageOffset.y), Int(pageOffset.y - 1)] }() let columns:[Int] = { if pageOffset.x >= 0 { return floor(pageOffset.x) == pageOffset.x ? [Int(pageOffset.x)] : [Int(pageOffset.x), Int(pageOffset.x + 1)] } return floor(pageOffset.x) == pageOffset.x ? [Int(pageOffset.x)] : [Int(pageOffset.x), Int(pageOffset.x - 1)] }() var updatedVisibleCellIndexLocations = [IndexLocation]() for row in rows { for column in columns { let indexLocation = IndexLocation(column: column, row: row) if let cell = cellForItemAtIndexLocation(indexLocation) { cell.frame = CGRect(x: self.frame.width * CGFloat(column) , y: self.frame.height * CGFloat(row) , width: self.frame.width , height: self.frame.height) updatedVisibleCellIndexLocations.append(indexLocation) } } } let oldCount = visibleCellsFromLocation.count let previousKeys = visibleCellsFromLocation.keys let removedKeys = previousKeys.filter( { !updatedVisibleCellIndexLocations.contains($0) } ) removedKeys.forEach({ (indexLocation) in if let cell = visibleCellsFromLocation[indexLocation] { delegate?.endlessPageView(self, didEndDisplayingCell: cell, forItemAtIndexLocation: indexLocation) cell.removeFromSuperview() } visibleCellsFromLocation[indexLocation] = nil }) if printDebugInfo { if oldCount != visibleCellsFromLocation.count { print("removed \(oldCount - visibleCellsFromLocation.count) cells") } } } else { print("Error in page offset: \(pageOffset)") } } // MARK: Gesture delegate open func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } // MARK: Endless page cell delegate internal func didSelectCell(_ cell: EndlessPageCell) { if let indexLocation = self.indexLocationForCell(cell) { delegate?.endlessPageViewDidSelectItemAtIndex(indexLocation) } } }
d480d4597cb93c5e2156f559cccd6565
37.798276
162
0.532018
false
false
false
false
kharrison/CodeExamples
refs/heads/master
Playgrounds/ContentMode.playground/Sources/CircleView.swift
bsd-3-clause
1
import UIKit public class CircleView: UIView { var lineWidth: CGFloat = 5 { didSet { setNeedsDisplay() } } var color: UIColor = .red { didSet { setNeedsDisplay() } } public override func draw(_ rect: CGRect) { let circleCenter = convert(center, from: superview) let circleRadius = min(bounds.size.width,bounds.size.height)/2 * 0.80 let circlePath = UIBezierPath(arcCenter: circleCenter, radius: circleRadius, startAngle: 0, endAngle: CGFloat(2*Double.pi), clockwise: true) circlePath.lineWidth = lineWidth color.set() circlePath.stroke() } }
275f8f11c3a4a220b1d342674a6b2f32
28.590909
148
0.626728
false
false
false
false
Baglan/MCViewport
refs/heads/master
Classes/MCViewportItem.swift
mit
1
// // MCViewportItem.swift // MCViewport // // Created by Baglan on 2/11/16. // Copyright © 2016 Mobile Creators. All rights reserved. // import Foundation import UIKit extension MCViewport { /// The general inmlementation of a viewport item class Item: Hashable { /// Reference to the viewport weak var viewport: MCViewport? /// The original frame of the item /// /// Position calculations will be based on it var originalFrame = CGRect.zero /// The parallax ratio of the item in the XY coordinate space var parallax = CGPoint(x: 1, y: 1) /// Item z-index for stacking var zIndex: CGFloat = 0 /// The current calculated frame var frame: CGRect { guard let viewport = viewport else { return originalFrame } var transformedFrame = originalFrame.applying(transformForContentOffset(viewport.contentOffset)) for movementConstraint in movementConstraints { transformedFrame = movementConstraint.applyToFrame(transformedFrame, viewport: viewport) } return transformedFrame } /// Calculate the affine transform for a given content offset of the viewport /// - Parameter contentOffset: The content offset of the viewport to calculate for /// - Returns: The affine transform func transformForContentOffset(_ contentOffset: CGPoint) -> CGAffineTransform { return CGAffineTransform(translationX: -contentOffset.x * (parallax.x - 1), y: -contentOffset.y * (parallax.y - 1)) } /// Position the item in the viewport /// - Parameter frame: The frame rect of the item /// - Parameter viewportOffset: Offset of the viewport for which the frame is set /// - Parameter parallax: The parallax ratio of the item func place(frame: CGRect, viewportOffset: CGPoint = CGPoint.zero, parallax: CGPoint = CGPoint(x: 1, y: 1)) { self.parallax = parallax let referenceOffset = CGPoint.zero.applying(transformForContentOffset(viewportOffset)) originalFrame = frame.applying(CGAffineTransform(translationX: viewportOffset.x - referenceOffset.x, y: viewportOffset.y - referenceOffset.y)) } /// The associated view, if any var view: UIView? { return nil } // MARK: - Distances /// Distances to viewport lazy var distances: Distances = { return Distances(item: self) }() // MARK: - Movement constraints /// The current movement constraints fileprivate var movementConstraints = [MovementConstraint]() /// Add a movement constraint func addMovementConstraint(_ movementConstraint: MovementConstraint) { movementConstraints.append(movementConstraint) movementConstraints.sort { (a, b) -> Bool in a.priority < b.priority } viewport?.setNeedsLayout() } // MARK: - Visibility /// Whether the item is currently visible on the screen var isVisible: Bool { if let viewport = viewport { return viewport.isItemVisible(self) } return false } /// Hook just before the item appears on the screen func willBecomeVisible() { } /// Hook right after the item leaves the screen func didBecomeInvisible() { } // MARK: - Updates /// Update the item position func update() { guard let view = view else { return } view.center = CGPoint(x: frame.midX, y: frame.midY) } // MARK: - Hashable compliance func hash(into hasher: inout Hasher) { hasher.combine(ObjectIdentifier(Item.self).hashValue) } } /// An item based on a UIView class ViewItem: Item { /// The associated view fileprivate var _view: UIView? override var view: UIView? { return _view } /// Create a new view /// /// To be implemented by descendants; the default implmenetation returns a simlpe UIView. /// /// - Returns: a new view func newView() -> UIView { return UIView() } override func willBecomeVisible() { guard let viewport = viewport else { return } // Create of dequeue a view _view = viewport.recycler.dequeue(String(describing: type(of: self))) as? UIView ?? newView() guard let view = view else { return } // Reset view.isHidden = false view.alpha = 1 view.transform = CGAffineTransform.identity // Set bounds and zPosition view.frame = originalFrame view.layer.zPosition = zIndex // Add view to viewport viewport.addSubview(view) } override func didBecomeInvisible() { guard let view = view, let viewport = viewport else { return } viewport.hiddenPocket.addSubview(view) viewport.recycler.recycle(String(describing: type(of: self)), object: view) } } /// An item based on a UIViewController class ViewControllerItem: Item { /// The associated view controller, if any var viewController: UIViewController? override var view: UIView? { return viewController?.view } /// Create a new view controller /// /// To beimplemented by descendants; the default implementation returns nil /// /// - Returns: A new view controller or nil func newViewController() -> UIViewController? { return nil } override func willBecomeVisible() { guard let viewport = viewport else { return } // Create of dequeue a view controller viewController = viewport.recycler.dequeue(String(describing: type(of: self))) as? UIViewController ?? newViewController() guard let viewController = viewController, let view = viewController.view else { return } // Reset view.isHidden = false view.alpha = 1 view.transform = CGAffineTransform.identity // Set bounds and zPosition view.frame = originalFrame view.layer.zPosition = zIndex // Add view to viewport viewport.addSubview(view) } override func didBecomeInvisible() { guard let view = view, let viewController = viewController, let viewport = viewport else { return } viewport.hiddenPocket.addSubview(view) viewport.recycler.recycle(String(describing: type(of: self)), object: viewController) } } } /// Check if items are the same func ==(lhs: MCViewport.Item, rhs: MCViewport.Item) -> Bool { return lhs === rhs }
5d99b8d0a14d67aa07f01f66c96935c7
32.873303
154
0.561715
false
false
false
false
mauryat/firefox-ios
refs/heads/master
Account/FxAPushMessageHandler.swift
mpl-2.0
1
/* 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 Deferred import Foundation import Shared import SwiftyJSON import Sync import XCGLogger private let log = Logger.syncLogger let PendingAccountDisconnectedKey = "PendingAccountDisconnect" /// This class provides handles push messages from FxA. /// For reference, the [message schema][0] and [Android implementation][1] are both useful resources. /// [0]: https://github.com/mozilla/fxa-auth-server/blob/master/docs/pushpayloads.schema.json#L26 /// [1]: https://dxr.mozilla.org/mozilla-central/source/mobile/android/services/src/main/java/org/mozilla/gecko/fxa/FxAccountPushHandler.java /// The main entry points are `handle` methods, to accept the raw APNS `userInfo` and then to process the resulting JSON. class FxAPushMessageHandler { let profile: Profile init(with profile: Profile) { self.profile = profile } } extension FxAPushMessageHandler { /// Accepts the raw Push message from Autopush. /// This method then decrypts it according to the content-encoding (aes128gcm or aesgcm) /// and then effects changes on the logged in account. @discardableResult func handle(userInfo: [AnyHashable: Any]) -> PushMessageResult { guard let subscription = profile.getAccount()?.pushRegistration?.defaultSubscription else { return deferMaybe(PushMessageError.notDecrypted) } guard let encoding = userInfo["con"] as? String, // content-encoding let payload = userInfo["body"] as? String else { return deferMaybe(PushMessageError.messageIncomplete) } // ver == endpointURL path, chid == channel id, aps == alert text and content_available. let plaintext: String? if let cryptoKeyHeader = userInfo["cryptokey"] as? String, // crypto-key let encryptionHeader = userInfo["enc"] as? String, // encryption encoding == "aesgcm" { plaintext = subscription.aesgcm(payload: payload, encryptionHeader: encryptionHeader, cryptoHeader: cryptoKeyHeader) } else if encoding == "aes128gcm" { plaintext = subscription.aes128gcm(payload: payload) } else { plaintext = nil } guard let string = plaintext else { return deferMaybe(PushMessageError.notDecrypted) } return handle(plaintext: string) } func handle(plaintext: String) -> PushMessageResult { return handle(message: JSON(parseJSON: plaintext)) } /// The main entry point to the handler for decrypted messages. func handle(message json: JSON) -> PushMessageResult { if !json.isDictionary() || json.isEmpty { return handleVerification() } let rawValue = json["command"].stringValue guard let command = PushMessageType(rawValue: rawValue) else { log.warning("Command \(rawValue) received but not recognized") return deferMaybe(PushMessageError.messageIncomplete) } let result: PushMessageResult switch command { case .deviceConnected: result = handleDeviceConnected(json["data"]) case .deviceDisconnected: result = handleDeviceDisconnected(json["data"]) case .profileUpdated: result = handleProfileUpdated() case .passwordChanged: result = handlePasswordChanged() case .passwordReset: result = handlePasswordReset() case .collectionChanged: result = handleCollectionChanged(json["data"]) case .accountVerified: result = handleVerification() } return result } } extension FxAPushMessageHandler { func handleVerification() -> PushMessageResult { guard let account = profile.getAccount(), account.actionNeeded == .needsVerification else { log.info("Account verified by server either doesn't exist or doesn't need verifying") return deferMaybe(.accountVerified) } // Progress through the FxAStateMachine, then explicitly sync. // We need a better solution than calling out to FxALoginHelper, because that class isn't // available in NotificationService, where this class is also used. // Since verification via Push has never been seen to work, we can be comfortable // leaving this as unimplemented. return unimplemented(.accountVerified) } } /// An extension to handle each of the messages. extension FxAPushMessageHandler { func handleDeviceConnected(_ data: JSON?) -> PushMessageResult { guard let deviceName = data?["deviceName"].string else { return messageIncomplete(.deviceConnected) } let message = PushMessage.deviceConnected(deviceName) return deferMaybe(message) } } extension FxAPushMessageHandler { func handleDeviceDisconnected(_ data: JSON?) -> PushMessageResult { guard let deviceId = data?["id"].string else { return messageIncomplete(.deviceDisconnected) } if let ourDeviceId = self.getOurDeviceId(), deviceId == ourDeviceId { // We can't disconnect the device from the account until we have // access to the application, so we'll handle this properly in the AppDelegate, // by calling the FxALoginHelper.applicationDidDisonnect(application). profile.prefs.setBool(true, forKey: PendingAccountDisconnectedKey) return deferMaybe(PushMessage.thisDeviceDisconnected) } guard let profile = self.profile as? BrowserProfile else { // We can't look up a name in testing, so this is the same as // not knowing about it. return deferMaybe(PushMessage.deviceDisconnected(nil)) } let clients = profile.remoteClientsAndTabs let getClient = clients.getClient(fxaDeviceId: deviceId) return getClient >>== { device in let message = PushMessage.deviceDisconnected(device?.name) if let id = device?.guid { return clients.deleteClient(guid: id) >>== { _ in deferMaybe(message) } } return deferMaybe(message) } } fileprivate func getOurDeviceId() -> String? { return profile.getAccount()?.deviceRegistration?.id } } extension FxAPushMessageHandler { func handleProfileUpdated() -> PushMessageResult { return unimplemented(.profileUpdated) } } extension FxAPushMessageHandler { func handlePasswordChanged() -> PushMessageResult { return unimplemented(.passwordChanged) } } extension FxAPushMessageHandler { func handlePasswordReset() -> PushMessageResult { return unimplemented(.passwordReset) } } extension FxAPushMessageHandler { func handleCollectionChanged(_ data: JSON?) -> PushMessageResult { guard let collections = data?["collections"].arrayObject as? [String] else { log.warning("collections_changed received but incomplete: \(data ?? "nil")") return deferMaybe(PushMessageError.messageIncomplete) } // Possible values: "addons", "bookmarks", "history", "forms", "prefs", "tabs", "passwords", "clients" // syncManager will only do a subset; others will be ignored. return profile.syncManager.syncNamedCollections(why: .push, names: collections) >>== { deferMaybe(.collectionChanged(collections: collections)) } } } /// Some utility methods fileprivate extension FxAPushMessageHandler { func unimplemented(_ messageType: PushMessageType, with param: String? = nil) -> PushMessageResult { if let param = param { log.warning("\(messageType) message received with parameter = \(param), but unimplemented") } else { log.warning("\(messageType) message received, but unimplemented") } return deferMaybe(PushMessageError.unimplemented(messageType)) } func messageIncomplete(_ messageType: PushMessageType) -> PushMessageResult { log.info("\(messageType) message received, but incomplete") return deferMaybe(PushMessageError.messageIncomplete) } } enum PushMessageType: String { case deviceConnected = "fxaccounts:device_connected" case deviceDisconnected = "fxaccounts:device_disconnected" case profileUpdated = "fxaccounts:profile_updated" case passwordChanged = "fxaccounts:password_changed" case passwordReset = "fxaccounts:password_reset" case collectionChanged = "sync:collection_changed" // This isn't a real message type, just the absence of one. case accountVerified = "account_verified" } enum PushMessage: Equatable { case deviceConnected(String) case deviceDisconnected(String?) case profileUpdated case passwordChanged case passwordReset case collectionChanged(collections: [String]) case accountVerified // This is returned when we detect that it is us that has been disconnected. case thisDeviceDisconnected var messageType: PushMessageType { switch self { case .deviceConnected(_): return .deviceConnected case .deviceDisconnected(_): return .deviceDisconnected case .thisDeviceDisconnected: return .deviceDisconnected case .profileUpdated: return .profileUpdated case .passwordChanged: return .passwordChanged case .passwordReset: return .passwordReset case .collectionChanged(collections: _): return .collectionChanged case .accountVerified: return .accountVerified } } public static func ==(lhs: PushMessage, rhs: PushMessage) -> Bool { guard lhs.messageType == rhs.messageType else { return false } switch (lhs, rhs) { case (.deviceConnected(let lName), .deviceConnected(let rName)): return lName == rName case (.collectionChanged(let lList), .collectionChanged(let rList)): return lList == rList default: return true } } } typealias PushMessageResult = Deferred<Maybe<PushMessage>> enum PushMessageError: MaybeErrorType { case notDecrypted case messageIncomplete case unimplemented(PushMessageType) case timeout case accountError public var description: String { switch self { case .notDecrypted: return "notDecrypted" case .messageIncomplete: return "messageIncomplete" case .unimplemented(let what): return "unimplemented=\(what)" case .timeout: return "timeout" case .accountError: return "accountError" } } }
f2e25771967026cc9c0ad7e32b7a66d3
36.696552
153
0.668039
false
false
false
false
iOSWizards/AwesomeUIMagic
refs/heads/master
AwesomeUIMagic/Classes/Custom/UIViewAnimations.swift
mit
1
// // UIViewAnimations.swift // Quests // // Created by Evandro Harrison Hoffmann on 3/20/17. // Copyright © 2017 Mindvalley. All rights reserved. // import UIKit // MARK: - Animations extension UIView{ public func animateShowPopingUp(duration: Double = 0.4, scaleIn: CGFloat = 0.1, scaleOut: CGFloat = 1.05, alphaIn: CGFloat = 0, _ completion:(() -> Void)? = nil){ DispatchQueue.main.async { self.isHidden = false self.alpha = alphaIn self.transform = CGAffineTransform(scaleX: scaleIn, y: scaleIn) UIView.animate(withDuration: duration*0.7, animations: { self.transform = CGAffineTransform(scaleX: scaleOut, y: scaleOut) self.alpha = 1 }, completion: { (didComplete) in UIView.animate(withDuration: duration*0.3, animations: { self.transform = CGAffineTransform(scaleX: 1, y: 1) }, completion: { (didComplete) in completion?() }) }) } } public func animateValueChange(duration: Double = 0.3, scaleIn: CGFloat = 1.1, alphaIn: CGFloat = 0.9, _ completion:(() -> Void)? = nil){ isHidden = false UIView.animate(withDuration: duration*0.7, animations: { self.transform = CGAffineTransform(scaleX: scaleIn, y: scaleIn) self.alpha = alphaIn }, completion: { (didComplete) in UIView.animate(withDuration: duration*0.3, animations: { self.transform = CGAffineTransform(scaleX: 1, y: 1) self.alpha = 1 }, completion: { (didComplete) in completion?() }) }) } public func animateFadeInUp(duration: Double = 0.3, alphaIn: CGFloat = 0, _ completion:(() -> Void)? = nil){ self.alpha = alphaIn let center = self.center if let superview = self.superview { self.center = CGPoint(x: self.center.x, y: superview.frame.size.height) } UIView.animate(withDuration: duration, animations: { self.center = center self.alpha = 1 }, completion: { (didComplete) in //if didComplete { completion?() //} }) } public func animateFadeInUpGrowing(duration: Double = 0.2, alphaIn: CGFloat = 0, startScale: CGFloat = 0.8, _ completion:(() -> Void)? = nil) { self.alpha = alphaIn self.transform = CGAffineTransform(scaleX: startScale, y: startScale) .concatenating(CGAffineTransform(translationX: 0, y: 100)) UIView.animate(withDuration: duration, animations: { self.alpha = 1 self.transform = CGAffineTransform.identity }, completion: { (_) in completion?() }) } public func animateFadeIn(duration: Double = 0.3, alphaIn: CGFloat = 0, _ completion:(() -> Void)? = nil){ // if !self.isHidden { // return // } self.isHidden = false self.alpha = alphaIn UIView.animate(withDuration: duration, animations: { self.alpha = 1 }, completion: { (didComplete) in //if didComplete { completion?() //} }) } public func animateFadeInLeftToRight(duration: Double = 0.35, alphaIn: CGFloat = 0, damping: CGFloat = 0.68, _ completion:(() -> Void)? = nil){ self.alpha = alphaIn let center = CGRect(x: self.superview!.frame.origin.x, y: self.superview!.frame.size.height-self.frame.size.height, width: self.frame.width, height: self.frame.height) self.frame = CGRect(x: self.superview!.frame.origin.x-self.frame.width, y: self.superview!.frame.size.height-self.frame.size.height, width: self.frame.width, height: self.frame.height) UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: damping, initialSpringVelocity: 0, options: .curveLinear, animations: { self.frame = center self.alpha = 1 }, completion: { (didComplete) in //if didComplete { completion?() //} }) } public func animateFadeInRightToLeft(duration: Double = 0.75, alphaIn: CGFloat = 0, damping: CGFloat = 0.98, _ completion:(() -> Void)? = nil){ self.alpha = alphaIn let center = CGRect(x: self.superview!.frame.origin.x, y: self.superview!.frame.size.height-self.frame.size.height, width: self.frame.width, height: self.frame.height) self.frame = CGRect(x: self.superview!.frame.origin.x+self.frame.width, y: self.superview!.frame.size.height-self.frame.size.height, width: self.frame.width, height: self.frame.height) UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: damping, initialSpringVelocity: 0.4, options: .curveLinear, animations: { self.frame = center self.alpha = 1 }, completion: { (didComplete) in //if didComplete { completion?() //} }) } public func animateFadeOut(duration: Double = 0.3, _ completion:(() -> Void)? = nil){ UIView.animate(withDuration: duration, animations: { self.alpha = 0 }, completion: { (didComplete) in //if didComplete { completion?() //} }) } public func animateFadeOutDown(duration: Double = 0.3, _ completion:(() -> Void)? = nil){ UIView.animate(withDuration: duration, animations: { if let superview = self.superview { self.center = CGPoint(x: self.center.x, y: superview.frame.size.height) } self.alpha = 0 }, completion: { (didComplete) in //if didComplete { completion?() //} }) } public func animateFadeAway(_ completion:(() -> Void)? = nil){ UIView.animate(withDuration: 0.2, animations: { self.transform = CGAffineTransform(scaleX: 1.1, y: 1.1) }, completion: { (didComplete) in //if didComplete { UIView.animate(withDuration: 0.2, animations: { self.transform = CGAffineTransform(scaleX: 0.9, y: 0.9) self.alpha = 0 }, completion: { (didComplete) in //if didComplete { self.isHidden = true completion?() //} }) //} }) } public func animateTouchDown(duration: Double = 0.1, durationOut: Double = 0.2, scaleIn: CGFloat = 0.9, alphaIn: CGFloat = 0.9, autoAnimateUp: Bool = true, halfWay:(() -> Void)? = nil, _ completed:(() -> Void)? = nil){ UIView.animate(withDuration: duration, animations: { self.alpha = alphaIn self.transform = CGAffineTransform(scaleX: scaleIn, y: scaleIn) }, completion: { (didComplete) in //if didComplete { halfWay?() if autoAnimateUp{ self.animateTouchUp(duration: durationOut, { completed?() }) } //} }) } public func animateTouchUp(duration: Double = 0.2, _ completed:(() -> Void)? = nil){ UIView .animate(withDuration: duration, animations: { self.alpha = 1 self.transform = CGAffineTransform(scaleX: 1, y: 1) }, completion: { (didComplete) in //if didComplete { completed?() //} }) } public func animateFadeOutRightToLeft(duration: Double = 0.3, _ completion:(() -> Void)? = nil){ UIView.animate(withDuration: duration, animations: { if let superview = self.superview { self.frame = CGRect(x: superview.frame.origin.x-self.frame.width, y: superview.frame.size.height-self.frame.size.height, width: self.frame.width, height: self.frame.height) } self.alpha = 0 }, completion: { (didComplete) in //if didComplete { completion?() //} }) } public func animateFadeOutLeftToRight(duration: Double = 0.3, _ completion:(() -> Void)? = nil){ UIView.animate(withDuration: duration, animations: { if let superview = self.superview { self.frame = CGRect(x: superview.frame.size.width+self.frame.width, y: superview.frame.size.height-self.frame.size.height, width: self.frame.width, height: self.frame.height) } self.alpha = 0 }, completion: { (didComplete) in //if didComplete { completion?() //} }) } public func animateShakeUpDown(duration: Double = 0.17) { let shake = CAKeyframeAnimation(keyPath: "transform.translation.y") shake.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear) shake.duration = 0.17 shake.values = [-20.0, 20.0, 0.0] self.layer.add(shake, forKey: "AwesomeMagicUIShakeUpDown") } }
51074929c76ce6dd8ffe2e8171a8b788
38.617021
222
0.55478
false
false
false
false
avenwu/jk-address-book
refs/heads/master
Source/libxml/libxmlHTMLDocument.swift
apache-2.0
2
/**@file libxmlHTMLDocument.swift Kanna Copyright (c) 2015 Atsushi Kiwaki (@_tid_) 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 /* libxmlHTMLDocument */ internal final class libxmlHTMLDocument: HTMLDocument { private var docPtr: htmlDocPtr = nil private var rootNode: XMLElement? private var html: String private var url: String? private var encoding: UInt var text: String? { return rootNode?.text } var toHTML: String? { return html } var innerHTML: String? { return rootNode?.innerHTML } var className: String? { return nil } var tagName: String? { return nil } init?(html: String, url: String?, encoding: UInt, option: UInt) { self.html = html self.url = url self.encoding = encoding if html.lengthOfBytesUsingEncoding(encoding) <= 0 { return nil } let cfenc : CFStringEncoding = CFStringConvertNSStringEncodingToEncoding(encoding) let cfencstr = CFStringConvertEncodingToIANACharSetName(cfenc) if let cur = html.cStringUsingEncoding(encoding) { let url : String = "" docPtr = htmlReadDoc(UnsafePointer<xmlChar>(cur), url, String(cfencstr), CInt(option)) rootNode = libxmlHTMLNode(docPtr: docPtr) } else { return nil } } deinit { xmlFreeDoc(self.docPtr) } var title: String? { return at_xpath("//title")?.text } var head: XMLElement? { return at_xpath("//head") } var body: XMLElement? { return at_xpath("//body") } func xpath(xpath: String, namespaces: [String:String]?) -> XMLNodeSet { return rootNode?.xpath(xpath, namespaces: namespaces) ?? XMLNodeSet() } func xpath(xpath: String) -> XMLNodeSet { return self.xpath(xpath, namespaces: nil) } func at_xpath(xpath: String, namespaces: [String:String]?) -> XMLElement? { return rootNode?.at_xpath(xpath, namespaces: namespaces) } func at_xpath(xpath: String) -> XMLElement? { return self.at_xpath(xpath, namespaces: nil) } func css(selector: String, namespaces: [String:String]?) -> XMLNodeSet { return rootNode?.css(selector, namespaces: namespaces) ?? XMLNodeSet() } func css(selector: String) -> XMLNodeSet { return self.css(selector, namespaces: nil) } func at_css(selector: String, namespaces: [String:String]?) -> XMLElement? { return rootNode?.at_css(selector, namespaces: namespaces) } func at_css(selector: String) -> XMLElement? { return self.at_css(selector, namespaces: nil) } } /* libxmlXMLDocument */ internal final class libxmlXMLDocument: XMLDocument { private var docPtr: xmlDocPtr = nil private var rootNode: XMLElement? private var xml: String private var url: String? private var encoding: UInt var text: String? { return rootNode?.text } var toHTML: String? { return xml } var innerHTML: String? { return rootNode?.innerHTML } var className: String? { return nil } var tagName: String? { return nil } init?(xml: String, url: String?, encoding: UInt, option: UInt) { self.xml = xml self.url = url self.encoding = encoding if xml.lengthOfBytesUsingEncoding(encoding) <= 0 { return nil } let cfenc : CFStringEncoding = CFStringConvertNSStringEncodingToEncoding(encoding) let cfencstr = CFStringConvertEncodingToIANACharSetName(cfenc) if let cur = xml.cStringUsingEncoding(encoding) { let url : String = "" docPtr = xmlReadDoc(UnsafePointer<xmlChar>(cur), url, String(cfencstr), CInt(option)) rootNode = libxmlHTMLNode(docPtr: docPtr) } else { return nil } } func xpath(xpath: String, namespaces: [String:String]?) -> XMLNodeSet { return rootNode?.xpath(xpath, namespaces: namespaces) ?? XMLNodeSet() } func xpath(xpath: String) -> XMLNodeSet { return self.xpath(xpath, namespaces: nil) } func at_xpath(xpath: String, namespaces: [String:String]?) -> XMLElement? { return rootNode?.at_xpath(xpath, namespaces: namespaces) } func at_xpath(xpath: String) -> XMLElement? { return self.at_xpath(xpath, namespaces: nil) } func css(selector: String, namespaces: [String:String]?) -> XMLNodeSet { return rootNode?.css(selector, namespaces: namespaces) ?? XMLNodeSet() } func css(selector: String) -> XMLNodeSet { return self.css(selector, namespaces: nil) } func at_css(selector: String, namespaces: [String:String]?) -> XMLElement? { return rootNode?.at_css(selector, namespaces: namespaces) } func at_css(selector: String) -> XMLElement? { return self.at_css(selector, namespaces: nil) } }
9d2153cbb01d39138aac24dcd2014ff4
29.839196
98
0.637549
false
false
false
false
ryanspillsbury90/OmahaTutorial
refs/heads/master
ios/OmahaPokerTutorial/OmahaPokerTutorial/ENSideMenu.swift
mit
1
// // SideMenu.swift // SwiftSideMenu // // Created by Evgeny on 24.07.14. // Copyright (c) 2014 Evgeny Nazarov. All rights reserved. // import UIKit @objc public protocol ENSideMenuDelegate { optional func sideMenuWillOpen() optional func sideMenuWillClose() optional func sideMenuShouldOpenSideMenu () -> Bool } @objc public protocol ENSideMenuProtocol { var sideMenu : ENSideMenu? { get } func setContentViewController(contentViewController: UIViewController) func getOrCreateSideMenu() -> ENSideMenu? } public enum ENSideMenuAnimation : Int { case None case Default } public enum ENSideMenuPosition : Int { case Left case Right } public extension UIViewController { public func toggleSideMenuView () { sideMenuController()?.sideMenu?.toggleMenu() } public func hideSideMenuView () { sideMenuController()?.sideMenu?.hideSideMenu() } public func showSideMenuView () { sideMenuController()?.sideMenu?.showSideMenu() } public func isSideMenuOpen () -> Bool { let sieMenuOpen = self.sideMenuController()?.sideMenu?.isMenuOpen return sieMenuOpen! } /** * You must call this method from viewDidLayoutSubviews in your content view controlers so it fixes size and position of the side menu when the screen * rotates. * A convenient way to do it might be creating a subclass of UIViewController that does precisely that and then subclassing your view controllers from it. */ func fixSideMenuSize() { if let navController = self.navigationController as? ENSideMenuNavigationController { navController.sideMenu?.updateFrame() } } public func sideMenuController () -> ENSideMenuProtocol? { var iteration : UIViewController? = self.parentViewController if (iteration == nil) { return topMostController() } repeat { if (iteration is ENSideMenuProtocol) { return iteration as? ENSideMenuProtocol } else if (iteration?.parentViewController != nil && iteration?.parentViewController != iteration) { iteration = iteration!.parentViewController } else { iteration = nil } } while (iteration != nil) return iteration as? ENSideMenuProtocol } internal func topMostController () -> ENSideMenuProtocol? { var topController : UIViewController? = UIApplication.sharedApplication().keyWindow?.rootViewController while (topController?.presentedViewController is ENSideMenuProtocol) { topController = topController?.presentedViewController } return topController as? ENSideMenuProtocol } } public class ENSideMenu : NSObject, UIGestureRecognizerDelegate { public var menuWidth : CGFloat = 160.0 { didSet { needUpdateApperance = true updateFrame() } } private var menuPosition:ENSideMenuPosition = .Left public var bouncingEnabled :Bool = true public var animationDuration = 0.4 private let sideMenuContainerView = UIView() private var menuViewController : UIViewController! private var animator : UIDynamicAnimator! private var sourceView : UIView! private var needUpdateApperance : Bool = false public weak var delegate : ENSideMenuDelegate? private(set) var isMenuOpen : Bool = false public var allowLeftSwipe : Bool = true public var allowRightSwipe : Bool = true public init(sourceView: UIView, menuPosition: ENSideMenuPosition) { super.init() self.sourceView = sourceView self.menuPosition = menuPosition self.setupMenuView() animator = UIDynamicAnimator(referenceView:sourceView) } public convenience init(sourceView: UIView, menuViewController: UIViewController, menuPosition: ENSideMenuPosition) { self.init(sourceView: sourceView, menuPosition: menuPosition) self.menuViewController = menuViewController self.menuViewController.view.frame = sideMenuContainerView.bounds self.menuViewController.view.autoresizingMask = [.FlexibleHeight, .FlexibleWidth] sideMenuContainerView.addSubview(self.menuViewController.view) } public convenience init(sourceView: UIView, view: UIView, menuPosition: ENSideMenuPosition) { self.init(sourceView: sourceView, menuPosition: menuPosition) view.frame = sideMenuContainerView.bounds view.autoresizingMask = [.FlexibleHeight, .FlexibleWidth] sideMenuContainerView.addSubview(view) } /** * Do not make this function private, it must be called from your own UIViewControllers (using the fixSideMenuSize function of the extension). */ func updateFrame() { var width:CGFloat var height:CGFloat (width, height) = adjustFrameDimensions( sourceView.frame.size.width, height: sourceView.frame.size.height) let menuFrame = CGRectMake( (menuPosition == .Left) ? isMenuOpen ? 0 : -menuWidth-1.0 : isMenuOpen ? width - menuWidth : width+1.0, sourceView.frame.origin.y, menuWidth, height ) sideMenuContainerView.frame = menuFrame } private func adjustFrameDimensions( width: CGFloat, height: CGFloat ) -> (CGFloat,CGFloat) { if floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1 && (UIApplication.sharedApplication().statusBarOrientation == UIInterfaceOrientation.LandscapeRight || UIApplication.sharedApplication().statusBarOrientation == UIInterfaceOrientation.LandscapeLeft) { // iOS 7.1 or lower and landscape mode -> interchange width and height return (height, width) } else { return (width, height) } } private func setupMenuView() { // Configure side menu container updateFrame() sideMenuContainerView.backgroundColor = UIColor.clearColor() sideMenuContainerView.clipsToBounds = false sideMenuContainerView.layer.masksToBounds = false sideMenuContainerView.layer.shadowOffset = (menuPosition == .Left) ? CGSizeMake(1.0, 1.0) : CGSizeMake(-1.0, -1.0) sideMenuContainerView.layer.shadowRadius = 1.0 sideMenuContainerView.layer.shadowOpacity = 0.125 sideMenuContainerView.layer.shadowPath = UIBezierPath(rect: sideMenuContainerView.bounds).CGPath sourceView.addSubview(sideMenuContainerView) if (NSClassFromString("UIVisualEffectView") != nil) { // Add blur view let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .Light)) as UIVisualEffectView visualEffectView.frame = sideMenuContainerView.bounds visualEffectView.autoresizingMask = [.FlexibleHeight, .FlexibleWidth] sideMenuContainerView.addSubview(visualEffectView) } else { // TODO: add blur for ios 7 } } private func toggleMenu (shouldOpen: Bool) { if (shouldOpen && delegate?.sideMenuShouldOpenSideMenu?() == false) { return } updateSideMenuApperanceIfNeeded() isMenuOpen = shouldOpen var width:CGFloat var height:CGFloat (width, height) = adjustFrameDimensions( sourceView.frame.size.width, height: sourceView.frame.size.height) if (bouncingEnabled) { animator.removeAllBehaviors() var gravityDirectionX: CGFloat var pushMagnitude: CGFloat var boundaryPointX: CGFloat var boundaryPointY: CGFloat if (menuPosition == .Left) { // Left side menu gravityDirectionX = (shouldOpen) ? 1 : -1 pushMagnitude = (shouldOpen) ? 20 : -20 boundaryPointX = (shouldOpen) ? menuWidth : -menuWidth-2 boundaryPointY = 20 } else { // Right side menu gravityDirectionX = (shouldOpen) ? -1 : 1 pushMagnitude = (shouldOpen) ? -20 : 20 boundaryPointX = (shouldOpen) ? width-menuWidth : width+menuWidth+2 boundaryPointY = -20 } let gravityBehavior = UIGravityBehavior(items: [sideMenuContainerView]) gravityBehavior.gravityDirection = CGVectorMake(gravityDirectionX, 0) animator.addBehavior(gravityBehavior) let collisionBehavior = UICollisionBehavior(items: [sideMenuContainerView]) collisionBehavior.addBoundaryWithIdentifier("menuBoundary", fromPoint: CGPointMake(boundaryPointX, boundaryPointY), toPoint: CGPointMake(boundaryPointX, height)) animator.addBehavior(collisionBehavior) let pushBehavior = UIPushBehavior(items: [sideMenuContainerView], mode: UIPushBehaviorMode.Instantaneous) pushBehavior.magnitude = pushMagnitude animator.addBehavior(pushBehavior) let menuViewBehavior = UIDynamicItemBehavior(items: [sideMenuContainerView]) menuViewBehavior.elasticity = 0.25 animator.addBehavior(menuViewBehavior) } else { var destFrame :CGRect if (menuPosition == .Left) { destFrame = CGRectMake((shouldOpen) ? -2.0 : -menuWidth, 0, menuWidth, height) } else { destFrame = CGRectMake((shouldOpen) ? width-menuWidth : width+2.0, 0, menuWidth, height) } UIView.animateWithDuration(animationDuration, animations: { () -> Void in self.sideMenuContainerView.frame = destFrame }) } if (shouldOpen) { delegate?.sideMenuWillOpen?() } else { delegate?.sideMenuWillClose?() } } private func updateSideMenuApperanceIfNeeded () { if (needUpdateApperance) { var frame = sideMenuContainerView.frame frame.size.width = menuWidth sideMenuContainerView.frame = frame sideMenuContainerView.layer.shadowPath = UIBezierPath(rect: sideMenuContainerView.bounds).CGPath needUpdateApperance = false } } public func toggleMenu () { if (isMenuOpen) { toggleMenu(false) } else { updateSideMenuApperanceIfNeeded() toggleMenu(true) } } public func showSideMenu () { if (!isMenuOpen) { toggleMenu(true) } } public func hideSideMenu () { if (isMenuOpen) { toggleMenu(false) } } }
262fd3d1bab50e6db6a33e033edc1054
35.603279
157
0.625224
false
false
false
false
IBM-MIL/IBM-Ready-App-for-Insurance
refs/heads/master
PerchReadyApp/apps/Perch/iphone/native/Perch/Controllers/HybridTools/NativeViewController.swift
epl-1.0
1
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2015. All Rights Reserved. */ import UIKit /** * View Controller wrapper around the HybridViewController that smooths the transition to a hybrid view */ class NativeViewController: PerchViewController { weak var appDelegate: AppDelegate! var pollingTimer: NSTimer! /// Allows only one request at a time to be sent to worklight for the getCurrentAssetDetail procedure var requestInProcess = false /// Allows hybrid view to essentially be reset when leaving the asset detail / asset history flow var leavingAssetDetailFlow = false override func viewDidLoad() { super.viewDidLoad() appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate } // MARK: Lifecycle override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) MQALogger.log("NativeViewController#viewWillAppear(Bool) invoked!") self.setUpContainer() if let sensorID = appDelegate.hybridViewController.deviceID { self.pollCurrentSensor() self.pollingTimer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: "pollCurrentSensor", userInfo: nil, repeats: true) HistoricalDataManager.sharedInstance.getAllHistoricalData(sensorID, callback: nil) } } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) self.pollingTimer.invalidate() } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) if leavingAssetDetailFlow { let otherRoute = ["route":"loading"] WL.sharedInstance().sendActionToJS("changePage", withData: otherRoute) leavingAssetDetailFlow = false appDelegate.hybridViewController.deviceID = nil } } /** This method sets up the container to hold the hybridViewController within the nativeViewController. */ func setUpContainer(){ self.addChildViewController(appDelegate.hybridViewController) appDelegate.hybridViewController.view.frame = CGRectMake(self.view.frame.origin.x, 0, self.view.frame.size.width, self.view.frame.size.height) self.view.addSubview(appDelegate.hybridViewController.view) appDelegate.hybridViewController.didMoveToParentViewController(self) } // MARK: Perch specific methods /** Polling method called every 5 seconds to query server (on a background thread) for new sensor value */ func pollCurrentSensor() { if let sensorID = appDelegate.hybridViewController.deviceID { if !requestInProcess { let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT dispatch_async(dispatch_get_global_queue(priority, 0)) { self.requestInProcess = true CurrentSensorDataManager.sharedInstance.getCurrentAssetDetail(sensorID, callback: {[weak self] in self?.sensorPollingResult($0)}) } } } } /** CurrentSensorDataManager callback to inform native view controller if query worked, useful in detecting asset status change - parameter success: boolean representing if query succeeded */ func sensorPollingResult(success: Bool) { dispatch_async(dispatch_get_main_queue()) { self.requestInProcess = false if success { if CurrentSensorDataManager.sharedInstance.prevSensorStatus != CurrentSensorDataManager.sharedInstance.currentSensorStatus { // Update native separtor color and mark asset overview page to be updated on re-appearing if let parentVC = self.parentViewController as? NavHandlerViewController { parentVC.updateSepartorColor(CurrentSensorDataManager.sharedInstance.currentSensorStatus) } AssetOverviewDataManager.sharedInstance.shouldReload = true } // reset to detect future changesd CurrentSensorDataManager.sharedInstance.prevSensorStatus = CurrentSensorDataManager.sharedInstance.currentSensorStatus } else { MQALogger.log("Call to getCurrentAssetDetail has failed") } } } } extension NativeViewController: UIGestureRecognizerDelegate { func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } }
7016cc930f67c7f95e61780294939115
37.658537
172
0.671924
false
false
false
false
alblue/swift
refs/heads/master
stdlib/public/Darwin/Network/NWParameters.swift
apache-2.0
4
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2018 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 // //===----------------------------------------------------------------------===// /// An NWParameters object contains the parameters necessary to create /// a network connection or listener. NWParameters include any preferences for /// network paths (such as required, prohibited, and preferred networks, and local /// endpoint requirements); preferences for data transfer and quality of service; /// and the protocols to be used for a connection along with any protocol-specific /// options. @available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) public final class NWParameters : CustomDebugStringConvertible { public var debugDescription: String { return String("\(self.nw)") } internal let nw : nw_parameters_t /// Creates a parameters object that is configured for TLS and TCP. The caller can use /// the default configuration for TLS and TCP, or set specific options for each protocol, /// or disable TLS. /// /// - Parameter tls: TLS options or nil for no TLS /// - Parameter tcp: TCP options. Defaults to NWProtocolTCP.Options() with no options overridden. /// - Returns: NWParameters object that can be used for creating a connection or listener public convenience init(tls: NWProtocolTLS.Options?, tcp: NWProtocolTCP.Options = NWProtocolTCP.Options()) { self.init() let protocolStack = self.defaultProtocolStack protocolStack.transportProtocol = tcp if let tls = tls { protocolStack.applicationProtocols = [tls] } else { protocolStack.applicationProtocols = [] } } /// Creates a parameters object that is configured for DTLS and UDP. The caller can use /// the default configuration for DTLS and UDP, or set specific options for each protocol, /// or disable TLS. /// /// - Parameter dtls: DTLS options or nil for no DTLS /// - Parameter udp: UDP options. Defaults to NWProtocolUDP.Options() with no options overridden. /// - Returns: NWParameters object that can be used for create a connection or listener public convenience init(dtls: NWProtocolTLS.Options?, udp: NWProtocolUDP.Options = NWProtocolUDP.Options()) { self.init() let protocolStack = self.defaultProtocolStack protocolStack.transportProtocol = udp if let dtls = dtls { protocolStack.applicationProtocols = [dtls] } else { protocolStack.applicationProtocols = [] } } /// Creates a generic NWParameters object. Note that in order to use parameters /// with a NWConnection or a NetworkListener, the parameters must have protocols /// added into the defaultProtocolStack. Clients using standard protocol /// configurations should use init(tls:tcp:) or init(dtls:udp:). public init() { self.nw = nw_parameters_create() } private init(nw: nw_parameters_t) { self.nw = nw } /// Default set of parameters for TLS over TCP /// This is equivalent to calling init(tls:NWProtocolTLS.Options(), tcp:NWProtocolTCP.Options()) public class var tls: NWParameters { return NWParameters(tls:NWProtocolTLS.Options()) } /// Default set of parameters for DTLS over UDP /// This is equivalent to calling init(dtls:NWProtocolTLS.Options(), udp:NWProtocolUDP.Options()) public class var dtls: NWParameters { return NWParameters(dtls:NWProtocolTLS.Options()) } /// Default set of parameters for TCP /// This is equivalent to calling init(tls:nil, tcp:NWProtocolTCP.Options()) public class var tcp: NWParameters { return NWParameters(tls:nil) } /// Default set of parameters for UDP /// This is equivalent to calling init(dtls:nil, udp:NWProtocolUDP.Options()) public class var udp: NWParameters { return NWParameters(dtls:nil) } /// Require a connection to use a specific interface, or fail if not available public var requiredInterface: NWInterface? { set { if let interface = newValue { nw_parameters_require_interface(self.nw, interface.nw) } else { nw_parameters_require_interface(self.nw, nil) } } get { if let interface = nw_parameters_copy_required_interface(self.nw) { return NWInterface(interface) } else { return nil } } } /// Require a connection to use a specific interface type, or fail if not available public var requiredInterfaceType: NWInterface.InterfaceType { set { nw_parameters_set_required_interface_type(self.nw, newValue.nw) } get { return NWInterface.InterfaceType(nw_parameters_get_required_interface_type(self.nw)) } } /// Define one or more interfaces that a connection will not be allowed to use public var prohibitedInterfaces: [NWInterface]? { set { nw_parameters_clear_prohibited_interfaces(self.nw) if let prohibitedInterfaces = newValue { for prohibitedInterface in prohibitedInterfaces { nw_parameters_prohibit_interface(self.nw, prohibitedInterface.nw) } } } get { var interfaces = [NWInterface]() nw_parameters_iterate_prohibited_interfaces(self.nw) { (interface) in interfaces.append(NWInterface(interface)) return true } return interfaces } } /// Define one or more interface types that a connection will not be allowed to use public var prohibitedInterfaceTypes: [NWInterface.InterfaceType]? { set { nw_parameters_clear_prohibited_interface_types(self.nw) if let prohibitedInterfaceTypes = newValue { for prohibitedInterfaceType in prohibitedInterfaceTypes { nw_parameters_prohibit_interface_type(self.nw, prohibitedInterfaceType.nw) } } } get { var interfaceTypes = [NWInterface.InterfaceType]() nw_parameters_iterate_prohibited_interface_types(self.nw) { (interfaceType) in interfaceTypes.append(NWInterface.InterfaceType(interfaceType)) return true } return interfaceTypes } } /// Disallow connection from using interfaces considered expensive public var prohibitExpensivePaths: Bool { set { nw_parameters_set_prohibit_expensive(self.nw, newValue) } get { return nw_parameters_get_prohibit_expensive(self.nw) } } /// If true, a direct connection will be attempted first even if proxies are configured. If the direct connection /// fails, connecting through the proxies will still be attempted. public var preferNoProxies: Bool { set { nw_parameters_set_prefer_no_proxy(self.nw, newValue) } get { return nw_parameters_get_prefer_no_proxy(self.nw) } } /// Force a specific local address to be used. This value is nil by /// default, in which case the system selects the most appropriate /// local address and selects a local port. public var requiredLocalEndpoint: NWEndpoint? { set { if let endpoint = newValue { nw_parameters_set_local_endpoint(self.nw, endpoint.nw) } else { nw_parameters_set_local_endpoint(self.nw, nil) } } get { if let endpoint = nw_parameters_copy_local_endpoint(self.nw) { return NWEndpoint(endpoint) } else { return nil } } } /// Allow multiple connections to use the same local address and port /// (SO_REUSEADDR and SO_REUSEPORT). public var allowLocalEndpointReuse: Bool { set { nw_parameters_set_reuse_local_address(self.nw, newValue) } get { return nw_parameters_get_reuse_local_address(self.nw) } } /// Cause an NWListener to only advertise services on the local link, /// and only accept connections from the local link. public var acceptLocalOnly: Bool { set { nw_parameters_set_local_only(self.nw, newValue) } get { return nw_parameters_get_local_only(self.nw) } } /// Allow the inclusion of peer-to-peer interfaces when /// listening or establishing outbound connections. This parameter /// will not take effect if a specific interface is required. /// This parameter is applicable when advertising a Bonjour service /// on a listener, or connecting to a Bonjour service. public var includePeerToPeer: Bool { set { nw_parameters_set_include_peer_to_peer(self.nw, newValue) } get { return nw_parameters_get_include_peer_to_peer(self.nw) } } /// The ServiceClass represents the network queuing priority to use /// for traffic generated by a NWConnection. public enum ServiceClass { /// Default priority traffic case bestEffort /// Bulk traffic, or traffic that can be de-prioritized behind foreground traffic case background /// Interactive video traffic case interactiveVideo /// Interactive voice traffic case interactiveVoice /// Responsive data case responsiveData /// Signaling case signaling internal var nw: nw_service_class_t { switch self { case .bestEffort: return Network.nw_service_class_best_effort case .background: return Network.nw_service_class_background case .interactiveVideo: return Network.nw_service_class_interactive_video case .interactiveVoice: return Network.nw_service_class_interactive_voice case .responsiveData: return Network.nw_service_class_responsive_data case .signaling: return Network.nw_service_class_signaling } } internal init(_ nw: nw_service_class_t) { switch nw { case Network.nw_service_class_best_effort: self = .bestEffort case Network.nw_service_class_background: self = .background case Network.nw_service_class_interactive_video: self = .interactiveVideo case Network.nw_service_class_interactive_voice: self = .interactiveVoice case Network.nw_service_class_responsive_data: self = .responsiveData case Network.nw_service_class_signaling: self = .signaling default: self = .bestEffort } } } public var serviceClass: NWParameters.ServiceClass { set { nw_parameters_set_service_class(self.nw, newValue.nw) } get { return NWParameters.ServiceClass(nw_parameters_get_service_class(self.nw)) } } /// Multipath services represent the modes of multipath usage that are /// allowed for connections. public enum MultipathServiceType { /// No multipath transport will be attempted case disabled /// Only use the expensive interface when the when the primary one is not available case handover /// Use the expensive interface more aggressively to reduce latency case interactive /// Use all available interfaces to provide the highest throughput and lowest latency case aggregate internal var nw: nw_multipath_service_t { switch self { case .disabled: return Network.nw_multipath_service_disabled case .handover: return Network.nw_multipath_service_handover case .interactive: return Network.nw_multipath_service_interactive case .aggregate: return Network.nw_multipath_service_aggregate } } internal init(_ nw: nw_multipath_service_t) { switch nw { case Network.nw_multipath_service_disabled: self = .disabled case Network.nw_multipath_service_handover: self = .handover case Network.nw_multipath_service_interactive: self = .interactive case Network.nw_multipath_service_aggregate: self = .aggregate default: self = .disabled } } } public var multipathServiceType: NWParameters.MultipathServiceType { set { nw_parameters_set_multipath_service(self.nw, newValue.nw) } get { return NWParameters.MultipathServiceType(nw_parameters_get_multipath_service(self.nw)) } } /// Use fast open for an outbound NWConnection, which may be done at any /// protocol level. Use of fast open requires that the caller send /// idempotent data on the connection before the connection may move /// into ready state. As a side effect, this may implicitly enable /// fast open for protocols in the stack, even if they did not have /// fast open explicitly enabled on them (such as the option to enable /// TCP Fast Open). public var allowFastOpen: Bool { set { nw_parameters_set_fast_open_enabled(self.nw, newValue) } get { return nw_parameters_get_fast_open_enabled(self.nw) } } /// Allow or prohibit the use of expired DNS answers during connection establishment. /// If allowed, a DNS answer that was previously returned may be re-used for new /// connections even after the answers are considered expired. A query for fresh answers /// will be sent in parallel, and the fresh answers will be used as alternate addresses /// in case the expired answers do not result in successful connections. /// By default, this value is .systemDefault, which allows the system to determine /// if it is appropriate to use expired answers. public enum ExpiredDNSBehavior { /// Let the system determine whether or not to allow expired DNS answers case systemDefault /// Explicitly allow the use of expired DNS answers case allow /// Explicitly prohibit the use of expired DNS answers case prohibit internal var nw: nw_parameters_expired_dns_behavior_t { switch self { case .systemDefault: return Network.nw_parameters_expired_dns_behavior_default case .allow: return Network.nw_parameters_expired_dns_behavior_allow case .prohibit: return Network.nw_parameters_expired_dns_behavior_prohibit } } internal init(_ nw: nw_parameters_expired_dns_behavior_t) { switch nw { case Network.nw_parameters_expired_dns_behavior_default: self = .systemDefault case Network.nw_parameters_expired_dns_behavior_allow: self = .allow case Network.nw_parameters_expired_dns_behavior_prohibit: self = .prohibit default: self = .systemDefault } } } public var expiredDNSBehavior: NWParameters.ExpiredDNSBehavior { set { nw_parameters_set_expired_dns_behavior(self.nw, newValue.nw) } get { return NWParameters.ExpiredDNSBehavior(nw_parameters_get_expired_dns_behavior(self.nw)) } } /// A ProtocolStack contains a list of protocols to use for a connection. /// The members of the protocol stack are NWProtocolOptions objects, each /// defining which protocol to use within the stack along with any protocol-specific /// options. Each stack includes an array of application-level protocols, a single /// transport-level protocol, and an optional internet-level protocol. If the internet- /// level protocol is not specified, any available and applicable IP address family /// may be used. public class ProtocolStack { public var applicationProtocols: [NWProtocolOptions] { set { nw_protocol_stack_clear_application_protocols(self.nw) for applicationProtocol in newValue.reversed() { nw_protocol_stack_prepend_application_protocol(self.nw, applicationProtocol.nw) } } get { var applicationProtocols = [NWProtocolOptions]() nw_protocol_stack_iterate_application_protocols(self.nw) { (protocolOptions) in let applicationDefinition = nw_protocol_options_copy_definition(protocolOptions) if (nw_protocol_definition_is_equal(applicationDefinition, NWProtocolTLS.definition.nw)) { applicationProtocols.append(NWProtocolTLS.Options(protocolOptions)) } } return applicationProtocols } } public var transportProtocol: NWProtocolOptions? { set { if let transport = newValue { nw_protocol_stack_set_transport_protocol(self.nw, transport.nw) } } get { if let transport = nw_protocol_stack_copy_transport_protocol(nw) { let transportDefinition = nw_protocol_options_copy_definition(transport) if (nw_protocol_definition_is_equal(transportDefinition, NWProtocolTCP.definition.nw)) { return NWProtocolTCP.Options(transport) } else if (nw_protocol_definition_is_equal(transportDefinition, NWProtocolUDP.definition.nw)) { return NWProtocolUDP.Options(transport) } } return nil } } public var internetProtocol: NWProtocolOptions? { set { // Not currently allowed return } get { if let ip = nw_protocol_stack_copy_internet_protocol(nw) { if (nw_protocol_definition_is_equal(nw_protocol_options_copy_definition(ip), NWProtocolIP.definition.nw)) { return NWProtocolIP.Options(ip) } } return nil } } internal let nw: nw_protocol_stack_t internal init(_ nw: nw_protocol_stack_t) { self.nw = nw } } /// Every NWParameters has a default protocol stack, although it may start out empty. public var defaultProtocolStack: NWParameters.ProtocolStack { get { return NWParameters.ProtocolStack(nw_parameters_copy_default_protocol_stack(self.nw)) } } /// Perform a deep copy of parameters public func copy() -> NWParameters { return NWParameters(nw: nw_parameters_copy(self.nw)) } }
6f180aee6ebd1c118a3beb96cecd872b
33.038229
114
0.716735
false
false
false
false
IngmarStein/swift
refs/heads/master
test/DebugInfo/return.swift
apache-2.0
1
// RUN: %target-swift-frontend %s -g -emit-ir -o - | %FileCheck %s class X { init (i : Int64) { x = i } var x : Int64 } // CHECK: define {{.*}}ifelseexpr public func ifelseexpr() -> Int64 { var x = X(i:0) // CHECK: [[META:%.*]] = call %swift.type* @_TMaC6return1X() // CHECK: [[X:%.*]] = call %C6return1X* @_TFC6return1XCfT1iVs5Int64_S0_( // CHECK-SAME: i64 0, %swift.type* [[META]]) // CHECK: @rt_swift_release to void (%C6return1X*)*)(%C6return1X* [[X]]) if true { x.x += 1 } else { x.x -= 1 } // CHECK: @rt_swift_release to void (%C6return1X*)*)(%C6return1X* [[X]]) // CHECK: @rt_swift_release to void (%C6return1X*)*)(%C6return1X* [[X]]) // CHECK-SAME: , !dbg ![[RELEASE:.*]] // The ret instruction should be in the same scope as the return expression. // CHECK: ret{{.*}}, !dbg ![[RELEASE]] return x.x // CHECK: ![[RELEASE]] = !DILocation(line: [[@LINE]], column: 3 }
cd4d44d2f8a94e49d49937ec9796f592
33.785714
79
0.539014
false
false
false
false
HabitRPG/habitrpg-ios
refs/heads/develop
Habitica API Client/Habitica API Client/Models/Content/APIQuestProgress.swift
gpl-3.0
1
// // File.swift // Habitica API Client // // Created by Phillip Thelen on 13.03.18. // Copyright © 2018 HabitRPG Inc. All rights reserved. // import Foundation import Habitica_Models class APIQuestProgress: QuestProgressProtocol, Decodable { var health: Float = 0 var rage: Float = 0 var up: Float = 0 var collect: [QuestProgressCollectProtocol] enum CodingKeys: String, CodingKey { case health = "hp" case rage case up case collect } public required init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) health = (try? values.decode(Float.self, forKey: .health)) ?? 0 rage = (try? values.decode(Float.self, forKey: .rage)) ?? 0 up = (try? values.decode(Float.self, forKey: .up)) ?? 0 collect = (try? values.decode([String: Int].self, forKey: .collect).map({ (collect) in return APIQuestProgressCollect(key: collect.key, count: collect.value) })) ?? [] } }
8a57bbafc3927d9e896cf720e2353c79
29.647059
94
0.627639
false
false
false
false
CraigZheng/KomicaViewer
refs/heads/master
KomicaViewer/KomicaViewer/ViewController/AddForumTableViewController.swift
mit
1
// // AddForumTableViewController.swift // KomicaViewer // // Created by Craig Zheng on 21/08/2016. // Copyright © 2016 Craig. All rights reserved. // import UIKit import KomicaEngine import DTCoreText enum ForumField: String { case name = "Name" case indexURL = "Index URL" case listURL = "Page URL" case responseURL = "Response URL" case parserType = "Page Style" } enum AddForumViewControllerType { case readonly case edit } class AddForumTableViewController: UITableViewController, SVWebViewProtocol { // MARK: UI elements. @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var indexLabel: UILabel! @IBOutlet weak var pageURLLabel: UILabel! @IBOutlet weak var responseURLLabel: UILabel! @IBOutlet weak var pageStyleLabel: UILabel! @IBOutlet weak var nameDetailLabel: UILabel! @IBOutlet weak var indexDetailLabel: UILabel! @IBOutlet weak var pageDetailLabel: UILabel! @IBOutlet weak var responseDetailLabel: UILabel! @IBOutlet weak var parserPickerView: UIPickerView! @IBOutlet weak var addForumHelpButtonItem: UIBarButtonItem! @IBOutlet weak var addButton: UIButton! @IBOutlet weak var resetButton: UIButton! @IBOutlet weak var addButtonTableViewCell: UITableViewCell! @IBOutlet weak var qrButtonTableViewCell: UITableViewCell! var newForum: KomicaForum! var unmodifiedForum: KomicaForum? var displayType = AddForumViewControllerType.edit // MARK: Private. fileprivate let pausedForumKey = "pausedForumKey" fileprivate let parserTypes = KomicaForum.parserNames fileprivate struct SegueIdentifier { static let name = "name" static let index = "index" static let page = "page" static let response = "response" static let showQRCode = "showQRCode" } // MARK: SVWebViewProtocol var svWebViewURL: URL? { set {} get { return Configuration.singleton.addForumHelpURL as URL? } } var svWebViewGuardDog: WebViewGuardDog? = { let guardDog = WebViewGuardDog() guardDog.showWarningOnBlock = true guardDog.home = Configuration.singleton.addForumHelpURL?.host return guardDog }() override func viewDidLoad() { super.viewDidLoad() if newForum == nil { // Restore from cache. if let jsonString = UserDefaults.standard.object(forKey: pausedForumKey) as? String, !jsonString.isEmpty { if let jsonData = jsonString.data(using: String.Encoding.utf8), let rawDict = try? JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) as? Dictionary<String, AnyObject>, let jsonDict = rawDict { newForum = KomicaForum(jsonDict: jsonDict) } } else { // Cannot read from cache, create a new KomicaForum object. newForum = KomicaForum() } } else { unmodifiedForum = newForum addButton.setTitle("Edit", for: .normal) } reload() } deinit { // Save the incompleted forum to NSUserDefaults. if displayType == .edit && newForum.isModified() { if newForum.parserType == nil { newForum.parserType = KomicaForum.parserTypes[parserPickerView.selectedRow(inComponent: 0)] } if let jsonString = newForum.jsonEncode(), !jsonString.isEmpty { UserDefaults.standard.set(jsonString, forKey: pausedForumKey) UserDefaults.standard.synchronize() } } } override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool { var should = true if identifier == SegueIdentifier.showQRCode { should = newForum.isReady() } return should } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let segueIdentifier = segue.identifier, let textInputViewController = segue.destination as? ForumTextInputViewController { textInputViewController.delegate = self textInputViewController.allowEditing = displayType == .edit switch segueIdentifier { case SegueIdentifier.name: textInputViewController.field = ForumField.name textInputViewController.prefilledString = newForum.name case SegueIdentifier.index: textInputViewController.field = ForumField.indexURL textInputViewController.prefilledString = newForum.indexURL case SegueIdentifier.page: textInputViewController.field = ForumField.listURL textInputViewController.prefilledString = newForum.listURL case SegueIdentifier.response: textInputViewController.field = ForumField.responseURL textInputViewController.prefilledString = newForum.responseURL default: break } } else if segue.identifier == SegueIdentifier.showQRCode, let destinationViewController = segue.destination as? ShowForumQRCodeViewController { destinationViewController.forum = newForum } } func reload() { addForumHelpButtonItem.isEnabled = Configuration.singleton.addForumHelpURL != nil let incompleted = "Incompleted..." title = newForum.name nameDetailLabel.text = !(newForum.name ?? "").isEmpty ? newForum.name : incompleted indexDetailLabel.text = !(newForum.indexURL ?? "").isEmpty ? newForum.indexURL : incompleted pageDetailLabel.text = !(newForum.listURL ?? "").isEmpty ? newForum.listURL : incompleted responseDetailLabel.text = !(newForum.responseURL ?? "").isEmpty ? newForum.responseURL : incompleted var selectRow = 0 if let parserType = newForum.parserType { selectRow = KomicaForum.parserTypes.index(where: { $0 == parserType }) ?? 0 } parserPickerView.selectRow(selectRow, inComponent: 0, animated: false) addButton.isEnabled = displayType == .edit resetButton.isEnabled = displayType == .edit } fileprivate func reportAdded(_ customForum: KomicaForum) { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm" let timeString = dateFormatter.string(from: Date()) let nameString = "KV_ADD_CUSTOM_FORUM" if let vendorIDString = UIDevice.current.identifierForVendor?.uuidString, let contentString = customForum.jsonEncode(), let targetURL = URL(string: "http://civ.atwebpages.com/KomicaViewer/kv_add_custom_forum.php"), var targetURLComponent = URLComponents(url: targetURL, resolvingAgainstBaseURL: false) { let vendorQueryItem = URLQueryItem(name: "vendorID", value: vendorIDString) let nameQueryItem = URLQueryItem(name: "name", value: nameString) let timeQueryItem = URLQueryItem(name: "time", value: timeString) let contentQueryItem = URLQueryItem(name: "content", value: contentString) targetURLComponent.queryItems = [vendorQueryItem, nameQueryItem, timeQueryItem, contentQueryItem] // Create a quick and dirty connection to upload the content to server. if let url = targetURLComponent.url { NSURLConnection.sendAsynchronousRequest(URLRequest(url: url), queue: OperationQueue.main) {(response, data, error) in } } } } } // MARK: UI actions. extension AddForumTableViewController { @IBAction func addForumHelpAction(_ sender: AnyObject) { presentSVWebView() } @IBAction func addForumAction(_ sender: UIButton) { DLog("") if !newForum.isReady() { let warning = "Supplied information not enough to construct a new board" DLog(warning) ProgressHUD.showMessage(warning) } else { newForum.parserType = KomicaForum.parserTypes[parserPickerView.selectedRow(inComponent: 0)] // Remove the original unmodified forum when it's presented. if let unmodifiedForum = unmodifiedForum { Forums.customForumGroup.forums?.removeObject(unmodifiedForum) Forums.saveCustomForums() } Forums.addCustomForum(newForum) // Report a custom forum has been added. reportAdded(newForum) _ = navigationController?.popToRootViewController(animated: true) // The forum has been added, reset the forum. newForum = KomicaForum() // Remove the paused forum from the user default. UserDefaults.standard.removeObject(forKey: self.pausedForumKey) UserDefaults.standard.synchronize() OperationQueue.main.addOperation({ ProgressHUD.showMessage("\(self.newForum.name ?? "A new board") has been added") }) } } @IBAction func resetForumAction(_ sender: AnyObject) { let alertController = UIAlertController(title: "Reset?", message: nil, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "Confirm", style: .default, handler: { (_) in self.newForum = KomicaForum() self.reload() // Remove the paused forum from the user default. UserDefaults.standard.removeObject(forKey: self.pausedForumKey) UserDefaults.standard.synchronize() })) alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) alertController.popoverPresentationController?.sourceView = view alertController.popoverPresentationController?.sourceRect = view.bounds if let topViewController = UIApplication.topViewController { topViewController.present(alertController, animated: true, completion: nil) } } } // MARK: ForumTextInputViewControllerProtocol extension AddForumTableViewController: ForumTextInputViewControllerProtocol { func forumDetailEntered(_ inputViewController: ForumTextInputViewController, enteredDetails: String, forField field: ForumField) { // Safe guard. if enteredDetails.isEmpty { return } DLog("\(enteredDetails) - \(field)") switch field { case .indexURL: newForum.indexURL = enteredDetails case .listURL: newForum.listURL = enteredDetails case .name: newForum.name = enteredDetails case .responseURL: newForum.responseURL = enteredDetails default: break } reload() } } // MARK: UIPickerViewDelegate, UIPickerViewDataSource extension AddForumTableViewController: UIPickerViewDelegate, UIPickerViewDataSource { func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return parserTypes.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return parserTypes[row] } } // MARK: UITableViewDelegate extension AddForumTableViewController { override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let cell = super.tableView(tableView, cellForRowAt: indexPath) // When the display type is editing, hide QR button. // When the display type is readyonly, hide the add/reset buttons. if (displayType == .edit && cell == qrButtonTableViewCell) || (displayType == .readonly && cell == addButtonTableViewCell) { return 0 } return super.tableView(tableView, heightForRowAt: indexPath) } } extension KomicaForum { func isReady() -> Bool { var isReady = true if (name ?? "").isEmpty || (indexURL ?? "" ).isEmpty || (listURL ?? "").isEmpty || (responseURL ?? "").isEmpty { isReady = false } return isReady } func isModified() -> Bool { var isModified = false if !(name ?? "").isEmpty || !(indexURL ?? "" ).isEmpty || !(listURL ?? "").isEmpty || !(responseURL ?? "").isEmpty { isModified = true } return isModified } }
f086c3efd8c6ad3856eb584fae62dd78
38.646875
144
0.639789
false
false
false
false
uasys/swift
refs/heads/master
stdlib/public/core/StringSwitch.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // This file contains compiler intrinsics for optimized string switch // implementations. All functions and types declared in this file are not // intended to be used by switch source directly. /// The compiler intrinsic which is called to lookup a string in a table /// of static string case values. @_semantics("stdlib_binary_only") @_semantics("findStringSwitchCase") public // COMPILER_INTRINSIC func _findStringSwitchCase( cases: [StaticString], string: String) -> Int { for (idx, s) in cases.enumerated() { if String(_builtinStringLiteral: s.utf8Start._rawValue, utf8CodeUnitCount: s._utf8CodeUnitCount, isASCII: s.isASCII._value) == string { return idx } } return -1 } public // used by COMPILER_INTRINSIC struct _OpaqueStringSwitchCache { var a: Builtin.Word var b: Builtin.Word } internal typealias _StringSwitchCache = Dictionary<String, Int> internal struct _StringSwitchContext { let cases: [StaticString] let cachePtr: UnsafeMutablePointer<_StringSwitchCache> } /// The compiler intrinsic which is called to lookup a string in a table /// of static string case values. /// /// The first time this function is called, a cache is built and stored /// in \p cache. Consecutive calls use the cache for faster lookup. /// The \p cases array must not change between subsequent calls with the /// same \p cache. @_semantics("stdlib_binary_only") @_semantics("findStringSwitchCaseWithCache") public // COMPILER_INTRINSIC func _findStringSwitchCaseWithCache( cases: [StaticString], string: String, cache: inout _OpaqueStringSwitchCache) -> Int { return withUnsafeMutableBytes(of: &cache) { (bufPtr: UnsafeMutableRawBufferPointer) -> Int in let oncePtr = bufPtr.baseAddress! let cacheRawPtr = oncePtr + MemoryLayout<Builtin.Word>.stride let cachePtr = cacheRawPtr.bindMemory(to: _StringSwitchCache.self, capacity: 1) var context = _StringSwitchContext(cases: cases, cachePtr: cachePtr) withUnsafeMutablePointer(to: &context) { (context) -> () in Builtin.onceWithContext(oncePtr._rawValue, _createStringTableCache, context._rawValue) } let cache = cachePtr.pointee; if let idx = cache[string] { return idx } return -1 } } /// Builds the string switch case. internal func _createStringTableCache(_ cacheRawPtr: Builtin.RawPointer) { let context = UnsafePointer<_StringSwitchContext>(cacheRawPtr).pointee var cache = _StringSwitchCache() cache.reserveCapacity(context.cases.count) assert(MemoryLayout<_StringSwitchCache>.size <= MemoryLayout<Builtin.Word>.size) for (idx, s) in context.cases.enumerated() { let key = String(_builtinStringLiteral: s.utf8Start._rawValue, utf8CodeUnitCount: s._utf8CodeUnitCount, isASCII: s.isASCII._value) cache[key] = idx } context.cachePtr.initialize(to: cache) }
3ea65eeec2483aabae17ae4681bde2b8
34.193878
83
0.683097
false
false
false
false
LawrenceHan/iOS-project-playground
refs/heads/master
Swift_A_Big_Nerd_Ranch_Guide/MonsterTown property/MonsterTown/Zombie.swift
mit
1
// // Zombie.swift // MonsterTown // // Created by Hanguang on 3/1/16. // Copyright © 2016 Hanguang. All rights reserved. // import Foundation class Zombie: Monster { override class var spookyNoise: String { return "Brains..." } var walksWithLimp: Bool private(set) var isFallingApart: Bool init(limp: Bool, fallingApart: Bool, town: Town?, monsterName: String) { walksWithLimp = limp isFallingApart = fallingApart super.init(town: town, monsterName: monsterName) } convenience init(limp: Bool, fallingApart: Bool) { self.init(limp: limp, fallingApart: fallingApart, town: nil, monsterName: "Fred") if walksWithLimp { print("This zombie has a bad knee.") } } required init(town: Town?, monsterName: String) { walksWithLimp = false isFallingApart = false super.init(town: town, monsterName: monsterName) } final override func terrorizeTown() { if !isFallingApart { town?.changePopulation(-10) } super.terrorizeTown() } func changeName(name: String, walksWithLimp: Bool) { self.name = name self.walksWithLimp = walksWithLimp } deinit { print("Zombie named \(name) is no longer with us.") } }
6f3a596da613541db9de55ce79ae978a
24.037037
89
0.602517
false
false
false
false
h-n-y/BigNerdRanch-SwiftProgramming
refs/heads/master
chapter-22/GoldChallenge.playground/Contents.swift
mit
1
/* GOLD CHALLENGE The return type for this function is changed from [Int] to [C.Index], where C.Index is the type used to subscript the *CollectionType*. *CollectionType*s have an *Index* property because they conform to the *Indexable* protocol. The Index type for Array<Element> is defined to be Int, but this is not the case for all collection types. For example, the index for *Set<Element: Hashable>* is defined as a *SetIndex<Element>*. *Note: This function will not work with *Dictionary<Key: Hashable, Value>* types, because the *Element* for a Dictionary is defined as the tuple (Key, Value). Tuples do not conform to the *Equatable* protocol by default, so the constraint T: Equatable below precludes dictionary collection types from being used as the first argument to the function. */ import Cocoa func findAll<T: Equatable, C: CollectionType where C.Generator.Element == T>(collection: C, item: T) -> [C.Index] { var matchingIndices: Array<C.Index> = [] var currentIndex: C.Index = collection.startIndex for element in collection { if element == item { matchingIndices.append(currentIndex) } currentIndex = currentIndex.advancedBy(1) } return matchingIndices } print(findAll([5, 3, 7, 3, 9], item: 3)) var mySet = Set<Double>() for num in [1.1, 2.2, 3.3] { mySet.insert(num) } print(findAll(mySet, item: 2.2))
03aaca6e9f05ca60965734004e1cc9e8
29.5
115
0.678279
false
false
false
false
ben-ng/swift
refs/heads/master
validation-test/compiler_crashers_fixed/00097-swift-clangmoduleunit-getimportedmodules.swift
apache-2.0
1
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck import Foundation class gfe<u>: hg { ji nm: u ba(nm: u) { wv.nm = nm t.ba() } } func ts<u : on>(ml: u) { } ts(v w on) ({}) lk fed<xw : ihg> { ji ml: xw } func ay<xw>() -> [fed<xw>] { kj [] } protocol ay { class func fed() } class ml: ay { class func fed() { } } (ml() w ay).ay.fed() protocol ml { class func sr() } lk fed { ji xw: ml.ut func sr() { xw.sr() } } ji ts = cb ji dcb: o -> o = { kj $dc } edc fed: o = { (ml: o, ts: o -> o) -> o yx kj ts(ml) }(ts, dcb) edc cb: o = { ml, ts yx kj ts(ml) }(ts, dcb) ts sr) func ts<fed>() -> (fed, fed -> fed) -> fed { xw ml xw.v = { } { fed) { sr } } protocol ts { class func v() } class xw: ts{ class func v {} protocol ay { } protocol ml : ay { } protocol fed : ay { } protocol xw { r ts = ay } lk sr : xw { r ts = ml } func v<ml : ml, wv : xw qp wv.ts == ml> (ih: wv) { } func v<ml : xw qp ml.ts == fed> (ih: ml) { } v(sr()) func fed<xw { enum fed { func sr ji _ = sr } } class fed { func ml((x, fed))(ay: (x, ed)) { ml(ay) } } func ay(ml: x, rq: x) -> (((x, x) -> x) -> x) { kj { (edc: (x, x) -> x) -> x yx kj edc(ml, rq) } } func ml(p: (((x, x) -> x) -> x)) -> x { kj p({ (ih: x, kj:x) -> x yx kj ih }) } ml(ay(cb, ay(s, rq))) protocol xw { r B func ml(B) } lk fe<po> : xw { func ml(ml: fe.ut) { } } class xw<u : xw> { } protocol xw { } lk B : xw { } lk sr<gf, ml: xw qp gf.sr == ml> { } protocol xw { r ml } lk B<u : xw> { edc sr: u edc v: u.ml } protocol sr { r vu func fed<u qp u.ml == vu>(ts: B<u>) } lk gf : sr { r vu = o func fed<u qp u.ml == vu>(ts: B<u>) { } } class ay<ts : ml, fed : ml qp ts.xw == fed> { } protocol ml { r xw r sr } lk fed<sr : ml> : ml { hgf r ts = xw } class ml<sr : fed, v
642fcbe0e084b9c17130ced36800417b
14.456376
79
0.488059
false
false
false
false
PureSwift/BlueZ
refs/heads/master
Sources/BluetoothLinux/DeviceCommand.swift
mit
2
// // DeviceCommand.swift // BluetoothLinux // // Created by Alsey Coleman Miller on 3/2/16. // Copyright © 2016 PureSwift. All rights reserved. // #if os(Linux) import Glibc #elseif os(OSX) || os(iOS) import Darwin.C #endif import Foundation import Bluetooth public extension HostController { func deviceCommand<T: HCICommand>(_ command: T) throws { try HCISendCommand(internalSocket, command: command) } func deviceCommand<T: HCICommandParameter>(_ commandParameter: T) throws { let command = T.command let parameterData = commandParameter.data try HCISendCommand(internalSocket, command: command, parameterData: parameterData) } } // MARK: - Internal HCI Function internal func HCISendCommand <T: HCICommand> (_ deviceDescriptor: CInt, command: T, parameterData: Data = Data()) throws { let packetType = HCIPacketType.Command.rawValue let header = HCICommandHeader(command: command, parameterLength: UInt8(parameterData.count)) /// data sent to host controller interface var data = [UInt8]([packetType]) + [UInt8](header.data) + [UInt8](parameterData) // write to device descriptor socket guard write(deviceDescriptor, &data, data.count) >= 0 // should we check if all data was written? else { throw POSIXError.errorno } }
45590a9475fdbc6afc59b96a6af57093
27.372549
101
0.648238
false
false
false
false
LoveZYForever/HXWeiboPhotoPicker
refs/heads/master
Pods/HXPHPicker/Sources/HXPHPicker/Core/Util/AssetManager+AssetCollection.swift
mit
1
// // AssetManager+AssetCollection.swift // HXPHPickerExample // // Created by Slience on 2020/12/29. // Copyright © 2020 Silence. All rights reserved. // import Photos import UIKit public extension AssetManager { /// 获取系统相册 /// - Parameter options: 选型 /// - Returns: 相册列表 static func fetchSmartAlbums( options: PHFetchOptions? ) -> PHFetchResult<PHAssetCollection> { return PHAssetCollection.fetchAssetCollections( with: .smartAlbum, subtype: .any, options: options ) } /// 获取用户创建的相册 /// - Parameter options: 选项 /// - Returns: 相册列表 static func fetchUserAlbums( options: PHFetchOptions? ) -> PHFetchResult<PHAssetCollection> { return PHAssetCollection.fetchAssetCollections( with: .album, subtype: .any, options: options ) } /// 获取所有相册 /// - Parameters: /// - filterInvalid: 过滤无效的相册 /// - options: 可选项 /// - usingBlock: 枚举每一个相册集合 static func enumerateAllAlbums( filterInvalid: Bool, options: PHFetchOptions?, usingBlock :@escaping (PHAssetCollection, Int, UnsafeMutablePointer<ObjCBool>) -> Void ) { let smartAlbums = fetchSmartAlbums(options: nil) let userAlbums = fetchUserAlbums(options: nil) let albums = [smartAlbums, userAlbums] var stopAblums: Bool = false for result in albums { result.enumerateObjects { (collection, index, stop) in if !collection.isKind(of: PHAssetCollection.self) { return } if filterInvalid { if collection.estimatedAssetCount <= 0 || collection.assetCollectionSubtype.rawValue == 205 || collection.assetCollectionSubtype.rawValue == 215 || collection.assetCollectionSubtype.rawValue == 212 || collection.assetCollectionSubtype.rawValue == 204 || collection.assetCollectionSubtype.rawValue == 1000000201 { return } } usingBlock(collection, index, stop) stopAblums = stop.pointee.boolValue } if stopAblums { break } } } /// 获取相机胶卷资源集合 /// - Parameter options: 可选项 /// - Returns: 相机胶卷集合 static func fetchCameraRollAlbum( options: PHFetchOptions? ) -> PHAssetCollection? { let smartAlbums = fetchSmartAlbums(options: options) var assetCollection: PHAssetCollection? smartAlbums.enumerateObjects { (collection, index, stop) in if !collection.isKind(of: PHAssetCollection.self) || collection.estimatedAssetCount <= 0 { return } if collection.isCameraRoll { assetCollection = collection stop.initialize(to: true) } } return assetCollection } /// 创建相册 /// - Parameter collectionName: 相册名 /// - Returns: 对应的 PHAssetCollection 数据 static func createAssetCollection( for collectionName: String ) -> PHAssetCollection? { let collections = PHAssetCollection.fetchAssetCollections( with: .album, subtype: .albumRegular, options: nil ) var assetCollection: PHAssetCollection? collections.enumerateObjects { (collection, index, stop) in if collection.localizedTitle == collectionName { assetCollection = collection stop.pointee = true } } if assetCollection == nil { do { var createCollectionID: String? try PHPhotoLibrary.shared().performChangesAndWait { createCollectionID = PHAssetCollectionChangeRequest.creationRequestForAssetCollection( withTitle: collectionName ).placeholderForCreatedAssetCollection.localIdentifier } if let createCollectionID = createCollectionID { assetCollection = PHAssetCollection.fetchAssetCollections( withLocalIdentifiers: [createCollectionID], options: nil ).firstObject } }catch {} } return assetCollection } }
86db7f736f19011e61ae15e28ad5dcf0
32.8
106
0.558843
false
false
false
false
warnerbros/cpe-manifest-ios-experience
refs/heads/master
Source/Utilities/BundleUtils.swift
apache-2.0
1
// // BundleUtils.swift // import Foundation extension Bundle { static var frameworkResources: Bundle { // CocoaPod using bundles if let resourcesBundleURL = Bundle(for: HomeViewController.self).url(forResource: "CPEExperience", withExtension: "bundle"), let resourcesBundle = Bundle(url: resourcesBundleURL) { return resourcesBundle } // Init resourcesBundle let resourcesBundle = Bundle(for: HomeViewController.self) // Carthage / Dynamic Framework if !resourcesBundle.bundlePath.isEmpty && resourcesBundle.bundleURL.pathExtension == "framework" { return resourcesBundle } // All Else return Bundle.main } }
b63ad1ba6307c1fd4b762689fe47e10e
25.964286
188
0.638411
false
false
false
false
J-Mendes/Weather
refs/heads/master
Weather/Weather/Views/WeatherTableViewController.swift
gpl-3.0
1
// // WeatherTableViewController.swift // Weather // // Created by Jorge Mendes on 05/07/17. // Copyright © 2017 Jorge Mendes. All rights reserved. // import UIKit class WeatherTableViewController: UITableViewController { internal var dataService: DataService? fileprivate enum Segues: String { case Settings = "showSettingsSegue" } fileprivate enum TableSections: Int { case Info = 0, Details, Forecast, Count } fileprivate enum DetailItems: Int { case Humidity = 0, Visibility, Wind, Sunrise, Sunset, Count } fileprivate var place: String! fileprivate var unitsType: Int! fileprivate var dataNeedsUpdate: Bool = false fileprivate var weatherInfo: WeatherData? { didSet { if self.weatherInfo != nil { DispatchQueue.main.async() { () -> Void in self.title = "\(self.weatherInfo!.city!), \(self.weatherInfo!.country!)" } } } } override func loadView() { super.loadView() // Init layout self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "settings"), style: .done, target: self, action: #selector(showSettings(_:))) self.refreshControl?.addTarget(self, action: #selector(WeatherTableViewController.getWeatherInfo), for: .valueChanged) self.refreshControl?.attributedTitle = NSAttributedString(string: NSLocalizedString("updating_wheather", comment: ""), attributes: [NSForegroundColorAttributeName: UIColor.white]) self.tableView.backgroundView = UIImageView(image: #imageLiteral(resourceName: "sky")) // Register custom table view cells self.tableView.register(WeatherInfoTableViewCell.nib, forCellReuseIdentifier: WeatherInfoTableViewCell.key) self.tableView.register(DetailTableViewCell.nib, forCellReuseIdentifier: DetailTableViewCell.key) self.tableView.register(ForecastTableViewCell.nib, forCellReuseIdentifier: ForecastTableViewCell.key) } override func viewDidLoad() { super.viewDidLoad() // Load place if let place: String = UserDefaults.standard.string(forKey: Constants.UserDefaultsKeys.location) { self.place = place } else { self.place = Constants.DefaultValues.defaultLocation UserDefaults.standard.set(self.place, forKey: Constants.UserDefaultsKeys.location) UserDefaults.standard.synchronize() } // Load units let units: Int = UserDefaults.standard.integer(forKey: Constants.UserDefaultsKeys.units) if units > 0 { self.unitsType = units } else { self.unitsType = Constants.DefaultValues.defaultUnit UserDefaults.standard.set(self.unitsType, forKey: Constants.UserDefaultsKeys.units) UserDefaults.standard.synchronize() } // Load weather data self.refreshControl?.beginRefreshing() self.getWeatherInfo() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if self.dataNeedsUpdate { self.refreshControl?.beginRefreshing() self.getWeatherInfo() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return self.weatherInfo != nil ? TableSections.Count.rawValue : 0 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case TableSections.Info.rawValue: return 1 case TableSections.Details.rawValue: return DetailItems.Count.rawValue case TableSections.Forecast.rawValue: return self.weatherInfo!.weather.forecastPrevisions.count default: return 0 } } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { var view: UIView? = nil switch section { case TableSections.Details.rawValue: let aView: HeaderView = HeaderView.create() aView.title = NSLocalizedString("details", comment: "") view = aView case TableSections.Forecast.rawValue: let aView: HeaderView = HeaderView.create() aView.title = NSLocalizedString("forecast", comment: "") view = aView default: break } return view } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return TableSections.Info.rawValue == section ? 0.0 : HeaderView.height } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell: UITableViewCell? = nil switch indexPath.section { case TableSections.Info.rawValue: let aCell: WeatherInfoTableViewCell = tableView.dequeueReusableCell(withIdentifier: WeatherInfoTableViewCell.key, for: indexPath) as! WeatherInfoTableViewCell aCell.configure(weatherData: self.weatherInfo!) cell = aCell case TableSections.Details.rawValue: let aCell: DetailTableViewCell = tableView.dequeueReusableCell(withIdentifier: DetailTableViewCell.key, for: indexPath) as! DetailTableViewCell switch indexPath.row { case DetailItems.Humidity.rawValue: aCell.configure(title: NSLocalizedString("humidity", comment: ""), value: self.weatherInfo!.atmosphere.humidity, unit: "%") case DetailItems.Visibility.rawValue: aCell.configure(title: NSLocalizedString("visibility", comment: ""), value: self.weatherInfo!.atmosphere.visibility, unit: self.weatherInfo!.units.distance) case DetailItems.Wind.rawValue: aCell.configure(title: NSLocalizedString("wind", comment: ""), value: self.weatherInfo!.wind.speed, unit: self.weatherInfo!.units.speed) case DetailItems.Sunrise.rawValue: aCell.configure(title: NSLocalizedString("sunrise", comment: ""), value: self.weatherInfo!.astronomy.sunrise.hourFormat(), unit: "h") case DetailItems.Sunset.rawValue: aCell.configure(title: NSLocalizedString("sunset", comment: ""), value: self.weatherInfo!.astronomy.sunset.hourFormat(), unit: "h") default: break } cell = aCell case TableSections.Forecast.rawValue: let aCell: ForecastTableViewCell = tableView.dequeueReusableCell(withIdentifier: ForecastTableViewCell.key, for: indexPath) as! ForecastTableViewCell aCell.configure(forecast: self.weatherInfo!.weather.forecastPrevisions[indexPath.row]) cell = aCell default: break } return cell! } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { switch indexPath.section { case TableSections.Info.rawValue: return WeatherInfoTableViewCell.height case TableSections.Details.rawValue: return DetailTableViewCell.height case TableSections.Forecast.rawValue: return ForecastTableViewCell.height default: return 0.0 } } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == Segues.Settings.rawValue { let settingsViewController: SettingsTableViewController = segue.destination as! SettingsTableViewController settingsViewController.delegate = self settingsViewController.currentLocation = self.place settingsViewController.currentUnit = self.unitsType } } @IBAction func showSettings(_ sender: Any?) { self.performSegue(withIdentifier: Segues.Settings.rawValue, sender: self) } // MARK: - Private methods @objc fileprivate func getWeatherInfo() { guard self.dataService != nil else { ErrorView.show(view: self.view) self.refreshControl?.endRefreshing() return } self.dataService?.getWeather(place: self.place, units: self.unitsType, completion: { (weatherData: WeatherData?, error: Error?) in if error == nil { if weatherData != nil { self.weatherInfo = weatherData; self.tableView.reloadData() } else { ErrorView.show(view: self.view, title: NSLocalizedString("error_place", comment: "")) } } else { DispatchQueue.main.async { ErrorView.show(view: self.view) } } ErrorView.dismiss(view: self.view) self.refreshControl?.endRefreshing() self.dataNeedsUpdate = false }) } } extension WeatherTableViewController: SettingsChangedDelegate { // MARK: - SettingsChangedDelegate func unitTypeChanged(unitType: Int) { self.unitsType = unitType self.dataNeedsUpdate = true } func locationChanged(place: String) { self.place = place DispatchQueue.main.async { self.title = self.place } self.dataNeedsUpdate = true } }
c91764300e053dfab70670026702525d
38.246964
187
0.639365
false
false
false
false
realDogbert/myScore
refs/heads/master
myScore/ScoreViewController.swift
mit
1
// // ViewController.swift // myScore // // Created by Frank on 20.07.14. // Copyright (c) 2014 Frank von Eitzen. All rights reserved. // import UIKit class ScoreViewController: UIViewController { @IBOutlet weak var lblHits: UILabel! @IBOutlet weak var lblPutts: UILabel! @IBOutlet weak var lblPenalty: UILabel! @IBOutlet weak var lblHole: UILabel! @IBOutlet weak var lblTotal: UILabel! @IBOutlet weak var lblLength: UILabel! @IBOutlet weak var lblPar: UILabel! @IBOutlet weak var stepperHits: UIStepper! @IBOutlet weak var stepperPutts: UIStepper! @IBOutlet weak var stepperPenalties: UIStepper! @IBOutlet weak var imgAverage: UIImageView! @IBOutlet weak var imgTotalAverage: UIImageView! var hole: Hole! var match: Match! var imgArrowUp = UIImage(named: "Arrow_Up") var imgArrowDown = UIImage(named: "Arrow_Down") var imgArrowSame = UIImage(named: "Arrow_Same") override func viewDidLoad() { super.viewDidLoad() lblHits.text = "\(hole.score.strokes)" lblPutts.text = "\(hole.score.putts)" lblPenalty.text = "\(hole.score.penalties)" stepperHits.value = Double(hole.score.strokes) stepperPutts.value = Double(hole.score.putts) stepperPenalties.value = Double(hole.score.penalties) lblHole.text = "Nr. \(hole.number)" lblPar.text = "Par: \(hole.par)" lblLength.text = "Len: \(hole.length)" } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) updateScore() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func updateTotalScore() { lblTotal.text = "Ges: \(match.getTotalScore())" } func updateHitsColor() { if hole.score.strokes <= hole.par { lblHits.textColor = UIColor.greenColor() } else { lblHits.textColor = UIColor.blackColor() } } func updateScore() { stepperHits.value = Double(hole.score.strokes) stepperPutts.value = Double(hole.score.putts) stepperPenalties.value = Double(hole.score.penalties) lblHits.text = hole.score.strokes.description lblPutts.text = hole.score.putts.description lblPenalty.text = hole.score.penalties.description //imgAverage.hidden = !(hole.score.strokes > hole.average) switch (hole.score.strokes - hole.average) { case -100...(-1): imgAverage.image = imgArrowUp case 1...100: imgAverage.image = imgArrowDown default: imgAverage.image = imgArrowSame } switch match.getCalculatedAverage() { case -1: imgTotalAverage.image = imgArrowUp case 1: imgTotalAverage.image = imgArrowDown default: imgTotalAverage.image = imgArrowSame } updateHitsColor() updateTotalScore() } @IBAction func updateHits(sender: AnyObject) { hole.score.strokes = Int(stepperHits.value) updateScore() } @IBAction func updatePutts(sender: AnyObject) { hole.score.putts = Int(stepperPutts.value) updateScore() } @IBAction func updatePenalties(sender: AnyObject) { hole.score.penalties = Int(stepperPenalties.value) updateScore() } }
cf5d7d163900c19838489474516b719a
26.529851
66
0.594199
false
false
false
false
seeaya/Simplex
refs/heads/master
Simplex/Drawing.swift
gpl-3.0
1
// // Drawing.swift // Simplex // // Created by Connor Barnes on 5/22/17. // Copyright © 2017 Connor Barnes. All rights reserved. // import Cocoa import CoreGraphics import CoreText /// The view that Simplex renders to on macOS. open class GameView: NSView { var mouse = Mouse() var keyboard = Keyboard() /// An array of drawable objects that are called upon in the draw loop to draw. var toDraw: [Drawable] = [] var context = Context() /// Where each draw function is called for nodes in the same hierarchy as the root node. /// /// - Parameter dirtyRect: A rectangle defining the portion of the view that requires redrawing open override func draw(_ dirtyRect: NSRect) { // Sorts the toDraw array by depth toDraw.sort { (lhs, rhs) -> Bool in return lhs.depth > rhs.depth } // Sets the context let context = NSGraphicsContext.current?.cgContext // Used to only update the new CGContext once var hasUpdatedContext = false for var drawable in toDraw { // Updates the CGContext with values of the current context contextUpdate: if !hasUpdatedContext { hasUpdatedContext = true guard let superContext = drawable.context else { break contextUpdate } // Set the stroke width context?.setLineWidth(CGFloat(superContext.strokeWidth)) // Set the stroke color and alpha context?.setStrokeColor(red: CGFloat(superContext.strokeColor.rgb.red), green: CGFloat(superContext.strokeColor.rgb.green), blue: CGFloat(superContext.strokeColor.rgb.blue), alpha: CGFloat(superContext.strokeAlpha)) // Set the fill color and alpha context?.setFillColor(red: CGFloat(superContext.fillColor.rgb.red), green: CGFloat(superContext.fillColor.rgb.green), blue: CGFloat(superContext.fillColor.rgb.blue), alpha: CGFloat(superContext.fillAlpha)) } // Sets each drawable object's context to the current cntext and runs its draw function drawable.context = self.context drawable.context?.cgContext = context drawable.draw() } // Reset the toDraw Array toDraw = [] } override public init(frame frameRect: NSRect) { super.init(frame: frameRect) let trackingArea: NSTrackingArea = NSTrackingArea(rect: bounds, options: [NSTrackingArea.Options.activeAlways, NSTrackingArea.Options.mouseMoved, NSTrackingArea.Options.enabledDuringMouseDrag], owner: self, userInfo: nil) addTrackingArea(trackingArea) } required public init?(coder: NSCoder) { let frame = NSRect(x: 0, y: 0, width: 0, height: 0) super.init(frame: frame) print("GameView.init(coder:) does not implement full mouse support!") } } /// Context for drawing including colors and alpha public class Context { // The Core Graphics Context for drawing on macOS and iOS var cgContext: CGContext? // Private variables that hold the actual values of drawing customizations var _strokeWidth = 1.0 var _strokeAlpha = 1.0 var _strokeColor = Color.black var _fillAlpha = 1.0 var _fillColor = Color.white var _font = Font(.system, ofSize: 12) var _fontColor = Color.black var _fontSize = 12.0 var _fontAlignStyle = FontAlignStyle(horizontalAlign: .left, verticalAlign: .top) /// The width of lines and outlines of shapes. public var strokeWidth: Double { get { return _strokeWidth } set { _strokeWidth = newValue cgContext?.setLineWidth(CGFloat(newValue)) } } /// The transparency of lines and outlines of shapes from 0 to 1, with 0 being fully transparent and 1 being fully opaque. public var strokeAlpha: Double { get { return _strokeAlpha } set { _strokeAlpha = newValue cgContext?.setStrokeColor(red: CGFloat(strokeColor.rgb.red), green: CGFloat(strokeColor.rgb.green), blue: CGFloat(strokeColor.rgb.blue), alpha: CGFloat(newValue)) } } /// The color of lines and outlines of shapes (The alpha value is ignored). public var strokeColor: Color { get { return _strokeColor } set { _strokeColor = newValue cgContext?.setStrokeColor(red: CGFloat(newValue.rgb.red), green: CGFloat(newValue.rgb.green), blue: CGFloat(newValue.rgb.blue), alpha: CGFloat(strokeAlpha)) } } /// The transparency the inside of shapes from 0 to 1, with 0 being fully transparent and 1 being fully opaque. public var fillAlpha: Double { get { return _fillAlpha } set { _fillAlpha = newValue cgContext?.setFillColor(red: CGFloat(fillColor.rgb.red), green: CGFloat(fillColor.rgb.green), blue: CGFloat(fillColor.rgb.blue), alpha: CGFloat(newValue)) } } /// The color of the inside of shapes. public var fillColor: Color { get { return _fillColor } set { _fillColor = newValue cgContext?.setFillColor(red: CGFloat(newValue.rgb.red), green: CGFloat(newValue.rgb.green), blue: CGFloat(newValue.rgb.blue), alpha: CGFloat(fillAlpha)) } } /// The font used for drawing text. public var font: Font { get { return _font } set { _font = newValue } } /// The color of text. public var fontColor: Color { get { return _fontColor } set { _fontColor = newValue } } /// The size of text. public var fontSize: Double { get { return _fontSize } set { _fontSize = newValue } } /// The alignment style of text. public var fontAlignStyle: FontAlignStyle { get { return _fontAlignStyle } set { _fontAlignStyle = newValue } } // Users should not create their own instances of Context, so no initializers are public init(with cgContext: CGContext) { self.cgContext = cgContext } init() { self.cgContext = nil } } /// The protocol that is adopted by nodes which are to draw to the screen. public protocol Drawable { /// The function called each render loop. Place all drawing functions and logic here. For non-drawing logic adopt the Updatable protocol and use its update(deltaTime:) method instead. func draw() /// The depth to draw at. Greater depths will be drawn first, and smaller depths will be drawn on top of greater depths. var depth: Double { get } /// The Current Context, used for drawing. var context: Context? { get set } } // Implements the draw loop that is called each render extension Node { // Executes the draw function for each drawable node in the hierarchy func superDraw(in view: GameView) { for child in children { child.superDraw(in: view) } if let drawableSelf = self as? Drawable { // Add self to the toDraw array in the GameView view.toDraw.append(drawableSelf) } } } // Implements geometric drawing functions which drawable objects can call extension Drawable { // MARK: Drawing functions /// Draws a line between two points. /// /// - Parameters: /// - start: The first point /// - end: The second point public func drawLine(from start: Vector2D, to end: Vector2D) { context?.cgContext?.move(to: CGPoint(start)) context?.cgContext?.addLine(to: CGPoint(end)) context?.cgContext?.strokePath() } /// Draws a rectangle with a given x and y position, and a given width and height. /// /// - Parameters: /// - x: The horizontal position of the top left of the rectangle /// - y: The vertival position of the bottom right of the rectangle /// - width: The width of the rectangle /// - height: The height of the rectangle public func drawRectangle(x: Double, y: Double, width: Double, height: Double) { context?.cgContext?.addRect(CGRect(x: x, y: y, width: width, height: height)) context?.cgContext?.fillPath() } /// Draws a rectangle at a given position, and with a given size. /// /// - Parameters: /// - origin: The position of the top left corner of the rectangle /// - size: The size of the rectangle public func drawRectangle(at position: Vector2D, withSize size: Size2D) { drawRectangle(x: position.x, y: position.y, width: size.width, height: size.height) context?.cgContext?.fillPath() } /// Draws a cricle with a given center position, and radius. /// /// - Parameters: /// - center: The position of the center of the circle /// - radius: The radius of the circle public func drawCircle(centeredAt center: Vector2D, withRadius radius: Double) { context?.cgContext?.addEllipse(in: CGRect(x: center.x - radius, y: center.y - radius, width: 2 * radius, height: 2 * radius)) context?.cgContext?.fillPath() } /// Draws an ellipse with a given center and size. /// /// - Parameters: /// - center: The position of the center of teh circle /// - size: The size of the ellipse public func drawEllipse(centeredAt center: Vector2D, withSize size: Size2D) { context?.cgContext?.addEllipse(in: CGRect(x: center.x - size.width/2, y: center.y - size.height/2, width: size.width, height: size.height)) context?.cgContext?.fillPath() } /// Draws a path between a number of verticies. /// /// - Parameters: /// - verticies: The verticies to draw a path between /// - curved: Wheather to draw curved or straight lines between verticies public func drawPath(between verticies: [Vector2D], curved: Bool) { guard let origin = verticies.first else { return } if curved { // TODO: Implement curved paths print("Curved paths not yet supported") } else { context?.cgContext?.move(to: CGPoint(origin)) for vertex in verticies { context?.cgContext?.addLine(to: CGPoint(vertex)) } context?.cgContext?.strokePath() } } /// Draws a regular polygon with its bottommost side parallel to the horizontal axis. /// /// - Parameters: /// - center: The position of the center of the polygon /// - sides: The number of sides of the polygon /// - radius: The radius from the center of the polygon to any vertex public func drawRegularPolygon(centeredAt center: Vector2D, sides: Int, radius: Double) { var angle = pi/Double(sides) - pi/2 let origin = Vector2D(x: center.x + radius * cos(angle), y: center.y + radius * sin(angle)) // Draw filled polygon context?.cgContext?.move(to: CGPoint(origin)) for _ in 0..<sides { angle += 2*pi/Double(sides) let point = Vector2D(x: center.x + radius * cos(angle), y: center.y + radius * sin(angle)) context?.cgContext?.addLine(to: CGPoint(point)) } context?.cgContext?.fillPath() // Draw stoked polygon angle = pi/Double(sides) - pi/2 context?.cgContext?.move(to: CGPoint(origin)) for _ in 0..<sides { angle += 2*pi/Double(sides) let point = Vector2D(x: center.x + radius * cos(angle), y: center.y + radius * sin(angle)) context?.cgContext?.addLine(to: CGPoint(point)) } context?.cgContext?.strokePath() } /// Draws a closed shape from a number of verticies. /// /// - Parameters: /// - verticies: the vertices the edge of the shape passes though /// - curved: Whether to draw a shape with straight or curved edges public func drawShape(between verticies: [Vector2D], curved: Bool) { guard let origin = verticies.first, let finalVertex = verticies.last else { return } if curved { // TODO: Implement curved shapes print("Curved shapes not yet supported") } else { // Draw filled shape context?.cgContext?.move(to: CGPoint(origin)) for vertex in verticies { context?.cgContext?.addLine(to: CGPoint(vertex)) } // Connect path back to origin if origin != finalVertex { context?.cgContext?.addLine(to: CGPoint(origin)) } context?.cgContext?.fillPath() // Draw stroked shape context?.cgContext?.move(to: CGPoint(origin)) for vertex in verticies { context?.cgContext?.addLine(to: CGPoint(vertex)) } // Connect path back to origin if origin != finalVertex { context?.cgContext?.addLine(to: CGPoint(origin)) } context?.cgContext?.strokePath() } } } // MARK: CoreGraphics Type Conversions // Converts Vector2D into CGPoint extension CGPoint { init(_ vector: Vector2D) { self.init(x: vector.x, y: vector.y) } } // Converts Color into cgColor extension Color { var cgColor: CGColor { get { return CGColor(red: CGFloat(rgb.red), green: CGFloat(rgb.green), blue: CGFloat(rgb.blue), alpha: CGFloat(alpha)) } } }
8e44d63f6fcf72ff7c834259efa19808
29.560914
223
0.694544
false
false
false
false
AfricanSwift/TUIKit
refs/heads/master
TUIKit/Source/UIElements/Foundation/TUIGeometry.swift
mit
1
// // File: TUIGeometry.swift // Created by: African Swift import Darwin // MARK: TUIVec2 - /// Vector in the two-dimensional Euclidean space – R×R /// /// - x: horizontal offset /// - y: vertical offset public struct TUIVec2 { public var x: Double public var y: Double /// Default TUIVec2 Initializer /// /// - parameters: /// - x: Int /// - y: Int public init(x: Int = 0, y: Int = 0) { self.x = Double(x) self.y = Double(y) } /// Default TUIVec2 Initializer /// /// - parameters: /// - x: Double /// - y: Double public init(x: Double, y: Double) { self.x = x self.y = y } } // MARK: - // MARK: TUIVec2 CustomStringConvertible - extension TUIVec2: CustomStringConvertible { public var description: String { return "(x: \(self.x), y: \(self.y))" } } // MARK: - // MARK: TUIVec2 Equatable - extension TUIVec2: Equatable { } /// Equatable Operator for TUIVec2 /// /// - parameters: /// - lhs: TUIVec2 /// - rhs: TUIVec2 /// - returns: Bool, True if lhs and rhs are equivalent public func == (lhs: TUIVec2, rhs: TUIVec2) -> Bool { return lhs.x == rhs.x && lhs.y == rhs.y } /// Plus Operator for TUIVec2 /// /// - parameters: /// - lhs: TUIVec2 /// - rhs: TUIVec2 /// - returns: Product of two TUIVec2 public func + (lhs: TUIVec2, rhs: TUIVec2) -> TUIVec2 { return TUIVec2(x: lhs.x + rhs.x, y: lhs.y + rhs.y) } /// Minus Operator for TUIVec2 /// /// - parameters: /// - lhs: TUIVec2 /// - rhs: TUIVec2 /// - returns: Difference of two TUIVec2 public func - (lhs: TUIVec2, rhs: TUIVec2) -> TUIVec2 { return TUIVec2(x: lhs.x - rhs.x, y: lhs.y - rhs.y) } /// Multiply Vector by Factor (Scale) /// /// - parameters: /// - lhs: TUIVec2 /// - rhs: Double /// - returns: Factor increase of TUIVec2 public func * (lhs: TUIVec2, rhs: Double) -> TUIVec2 { return TUIVec2(x: lhs.x * rhs, y: lhs.y * rhs) } /// Dot Product of two TUIVec2 /// /// - parameters: /// - lhs: TUIVec2 /// - rhs: TUIVec2 /// - returns: dot product of the two TUIVec2 vectors public func * (lhs: TUIVec2, rhs: TUIVec2) -> Double { return (lhs.x * rhs.x) + (lhs.y * rhs.y) } // MARK: - // MARK: TUIVec3 - /// Vector in the three-dimensional Euclidean space – R×R×R /// /// - x: X axis offset /// - y: Y axis offset /// - z: Z axis offset public struct TUIVec3 { public var x: Double public var y: Double public var z: Double /// Default TUIVec3 Initializer /// /// - parameters: /// - x: Double /// - y: Double /// - z: Double public init(x: Double = 0, y: Double = 0, z: Double = 0) { self.x = x self.y = y self.z = z } private func norm() -> Double { return sqrt(self.x * self.x + self.y * self.y + self.z * self.z) } public func normalize() -> TUIVec3 { return self * (1 / self.norm()) } } // MARK: - // MARK: TUIVec3 CustomStringConvertible - extension TUIVec3: CustomStringConvertible { public var description: String { return "(x: \(self.x), y: \(self.y), z: \(self.z))" } } // MARK: - // MARK: TUIVec3 Equatable - extension TUIVec3: Equatable { } /// Equatable Operator for TUIVec3 /// /// - parameters: /// - lhs: TUIVec3 /// - rhs: TUIVec3 /// - returns: Bool, True if lhs and rhs are equivalent public func == (lhs: TUIVec3, rhs: TUIVec3) -> Bool { return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z } /// Cross Product of two TUIVec3 infix operator ** { associativity left precedence 150 } /// Cross Product of two TUIVec3 /// /// - parameters: /// - lhs: TUIVec3 /// - rhs: TUIVec3 /// - returns: cross product of the two TUIVec3 vectors public func ** (lhs: TUIVec3, rhs: TUIVec3) -> TUIVec3 { return TUIVec3(x: lhs.y * rhs.z - lhs.z * rhs.y, y: lhs.z * rhs.x - lhs.x * rhs.z, z: lhs.x * rhs.y - lhs.y * rhs.x) } /// Plus Operator for TUIVec3 /// /// - parameters: /// - lhs: TUIVec3 /// - rhs: TUIVec3 /// - returns: Product of two TUIVec3 vectors public func + (lhs: TUIVec3, rhs: TUIVec3) -> TUIVec3 { return TUIVec3(x: lhs.x + rhs.x, y: lhs.y + rhs.y, z: lhs.z + rhs.z) } /// Minus Operator for TUIVec3 /// /// - parameters: /// - lhs: TUIVec3 /// - rhs: TUIVec3 /// - returns: Difference of two TUIVec3 vectors public func - (lhs: TUIVec3, rhs: TUIVec3) -> TUIVec3 { return TUIVec3(x: lhs.x - rhs.x, y: lhs.y - rhs.y, z: lhs.z - rhs.z) } /// Multiply Vector by Factor (Scale) /// /// - parameters: /// - lhs: TUIVec3 /// - rhs: Double (factor) /// - returns: Factor increase of TUIVec3 vector public func * (lhs: TUIVec3, rhs: Double) -> TUIVec3 { return TUIVec3(x: lhs.x * rhs, y: lhs.y * rhs, z: lhs.z * rhs) } /// Dot Product of two TUIVec3 /// /// - parameters: /// - lhs: TUIVec3 /// - rhs: TUIVec3 /// - returns: dot product of the two vectors public func * (lhs: TUIVec3, rhs: TUIVec3) -> Double { return lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z } /// Radian Angle between two TUIVec3 vectors infix operator *> { associativity left precedence 150 } /// Radian Angle between two TUIVec3 vectors /// /// - parameters: /// - lhs: TUIVec3 /// - rhs: TUIVec3 /// - returns: Radian Angle of two vectors public func *> (lhs: TUIVec3, rhs: TUIVec3) -> Double { return acos((lhs * rhs) / (lhs.norm() * rhs.norm())) } // MARK: - // MARK: TUISize - /// Terminal UI Size /// /// - width: horizontal size /// - size: vertical size public struct TUISize { public private(set) var width: Double public private(set) var height: Double /// Default Initializer /// /// - parameters: /// - width: Int /// - height: Int public init(width: Int = 0, height: Int = 0) { self.width = Double(width) self.height = Double(height) } /// Default Initializer /// /// - parameters: /// - width: Double /// - height: Double public init(width: Double, height: Double) { self.width = width self.height = height } } // MARK: - // MARK: TUISize Equatable - /// TUISize equatable extension TUISize: Equatable {} /// Equatable Operator for TUISize /// /// - parameters: /// = lhs: TUISize /// - rhs: TUISize /// - returns: Bool, True if lhs and rhs are equivalent public func == (lhs: TUISize, rhs: TUISize) -> Bool { return lhs.height == rhs.height && lhs.width == rhs.width } // MARL: - // MARK: TUIViewSize - /// Terminal UI Viewsize with two size accessors: pixel vs. character /// /// - pixel is based on the braille symbols /// - 2 x 4 pixels per character (width x height) public struct TUIWindowSize { public var pixel: TUISize public var character: TUISize /// Default initializer /// /// - parameters: /// - width: Int (pixel width) /// - height: Int (pixel height) public init(width: Int, height: Int) { let w = Int(ceil(Double(width) / 2.0)) let h = Int(ceil(Double(height) / 4.0)) self.pixel = TUISize(width: w * 2, height: h * 4) self.character = TUISize(width: w, height: h) } /// Default initializer /// /// - parameters: /// - width: Double (pixel width) /// - height: Double (pixel height) public init(width: Double, height: Double) { self.init(width: Int(width), height: Int(height)) } /// Default initializer /// /// - parameters: /// - columns: Int (character width) /// - rows: Int (character height) public init(columns: Int, rows: Int) { self.init(width: columns * 2, height: rows * 4) } } // MARK: - // MARK: TUIRectangle - /// Terminal UI Rectangle // /// - origin (TUIVec2): left / top origin /// - size (TUISize): width / height public struct TUIRectangle { public private(set) var origin = TUIVec2() public private(set) var size = TUISize() /// Default Initializer /// /// - parameters: /// - x: Int /// - y: Int /// - width: Int /// - height: Int public init(x: Int = 0, y: Int = 0, width: Int = 0, height: Int = 0) { self.origin = TUIVec2(x: x, y: y) self.size = TUISize(width: width, height: height) } /// Default Initializer /// /// - parameters: /// - x: Double /// - y: Double /// - width: Double /// - height: Double public init(x: Double = 0.0, y: Double = 0.0, width: Double = 0.0, height: Double = 0.0) { self.origin = TUIVec2(x: x, y: y) self.size = TUISize(width: width, height: height) } /// Default Initializer /// /// - parameters: /// - origin: TUIVec2 /// - size: TUISize public init(origin: TUIVec2, size: TUISize) { self.origin = origin self.size = size } } // MARK: - // MARK: TUIRectangle Equatable - extension TUIRectangle: Equatable {} /// Equatable Operator for TUIRectangle /// /// - parameters: /// - lhs: TUIRectangle /// - rhs: TUIRectangle /// - returns: Bool, True if lhs and rhs are equivalent public func == (lhs: TUIRectangle, rhs: TUIRectangle) -> Bool { return lhs.origin == rhs.origin && lhs.size == rhs.size }
f60670fed1bf8aa13b34ff82f1566e89
21.037037
90
0.594398
false
false
false
false
blstream/StudyBox_iOS
refs/heads/master
StudyBox_iOS/DecksCollectionViewLayout.swift
apache-2.0
1
// // DecksCollectionViewLayout.swift // StudyBox_iOS // // Created by Damian Malarczyk on 26.04.2016. // Copyright © 2016 BLStream. All rights reserved. // import UIKit protocol DecksCollectionLayoutDelegate: class { func shouldStrech() -> Bool } class DecksCollectionViewLayout: UICollectionViewFlowLayout { weak var delegate: DecksCollectionLayoutDelegate? override func collectionViewContentSize() -> CGSize { let expectedSize = super.collectionViewContentSize() if let collectionView = collectionView, delegate = delegate where delegate.shouldStrech() { var targetSize = collectionView.bounds.size let height = expectedSize.height if height < targetSize.height { let sharedApp = UIApplication.sharedApplication() if !sharedApp.statusBarHidden { targetSize.height -= UIApplication.sharedApplication().statusBarFrame.height } return targetSize } } return expectedSize } }
b0bff4f65cfe425e5efdfa0353a79873
27.45
99
0.618629
false
false
false
false
timothydang/SwiftLinksMenuBar
refs/heads/master
SwiftLinksMenuBar/AppDelegate.swift
mit
1
// // AppDelegate.swift // SwiftLinksMenuBar // // Created by Timothy Dang on 28/05/2015. // Copyright (c) 2015 Timothy Dang. All rights reserved. // import Cocoa import SwiftyJSON struct MenuBarItem:NilLiteralConvertible { let title:String? let url:String? let items:Array<MenuBarItem> init(nilLiteral: ()) { self.title = nil self.url = nil self.items = [] } init(title: String?, url: String?, items: Array<MenuBarItem>) { self.title = title self.url = url self.items = items } } @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet weak var window: NSWindow! var statusBarItem: NSStatusItem = NSStatusBar.systemStatusBar().statusItemWithLength(-1) var menu = NSMenu() var menuItems:Array<MenuBarItem> = [] func applicationDidFinishLaunching(aNotification: NSNotification) { let icon = NSImage(named: "statusIcon") icon?.setTemplate(true) self.statusBarItem.image = icon NSApp.setActivationPolicy(NSApplicationActivationPolicy.Accessory) parseJson() initMenu() } func parseJson() { let bundle = NSBundle.mainBundle() let path = bundle.pathForResource("links", ofType: "json") var error:NSError? let data: NSData? = NSData(contentsOfFile: path!) let content = JSON(data: data!, options: NSJSONReadingOptions.allZeros, error: &error) var json = content.dictionary! as Dictionary<String, JSON> let values = json.values.first?.array! for i in 0...((values?.count)!-1) { var itemJSON = values?[i] as JSON? var itemName = itemJSON?.dictionary?.keys.first var itemLink = itemJSON?.dictionary?.values.array as Array? var menuItem:MenuBarItem = nil var childMenuItems:Array<MenuBarItem> = [] if itemName == nil { menuItems.append(nil) } if(itemLink?.first?.array != nil) { // Having child menu items var subItems = itemLink?.first?.array var subItem:MenuBarItem = nil for j in 0...(subItems?.count)!-1 { var subItemJSON = subItems?[j] as JSON? var subItemName = subItemJSON?.dictionary?.keys.first var subItemLink = subItemJSON?.dictionary?.values.first?.string subItem = MenuBarItem(title: subItemName, url: subItemLink, items: []) childMenuItems.append(subItem) } } menuItem = MenuBarItem(title: itemName, url: itemLink?.first?.string, items: childMenuItems) menuItems.append(menuItem) } } func initMenu() { for i in 0...self.menuItems.count-1 { var item = self.menuItems[i] as MenuBarItem if item.items.count > 0 { let subMenu = NSMenu() for j in 0...item.items.count-1 { var subMenuItem = NSMenuItem(title: item.items[j].title!, action: Selector("clickMenuItem:"), keyEquivalent: "") subMenuItem.representedObject = item.items[j].url subMenu.addItem(subMenuItem) } var menuItem = NSMenuItem(title: item.title!, action: nil, keyEquivalent: "") menuItem.submenu = subMenu menu.addItem(menuItem) } else if item.title == nil { menu.addItem(NSMenuItem.separatorItem()) } else { var menuItem = NSMenuItem(title: item.title!, action: Selector("clickMenuItem:"), keyEquivalent: "") menuItem.representedObject = item.url menu.addItem(menuItem) } } menu.addItem(NSMenuItem.separatorItem()) menu.addItemWithTitle("Quit", action: Selector("terminate:"), keyEquivalent: "") self.statusBarItem.menu = menu } func applicationWillTerminate(aNotification: NSNotification) { // Insert code here to tear down your application } func clickMenuItem(sender: NSMenuItem) { var itemUrl = sender.representedObject as! String NSWorkspace.sharedWorkspace().openURL(NSURL(string: itemUrl)!) } }
dae1d240f5cf3beae7ca843839df5b06
33.066667
132
0.559904
false
false
false
false
BiteCoda/icebreaker-app
refs/heads/master
IceBreaker-iOS/IceBreaker/Utilities/RESTManager.swift
gpl-3.0
1
// // RESTManager.swift // IceBreaker // // Created by Jacob Chen on 2/21/15. // Copyright (c) 2015 floridapoly.IceMakers. All rights reserved. // import UIKit private let BASE_URL:String = "http://icebreaker.duckdns.org" private let _SingletonSharedRESTManager = RESTManager() private let USER_ID_KEY = "userId" private let DEVICE_TOKEN_KEY = "deviceToken" private let DEVICE_TYPE_KEY = "deviceType" private let PASSWORD_KEY = "password" private let TARGET_USER_ID_KEY = "targetUserId" class RESTManager { let manager: AFHTTPRequestOperationManager = AFHTTPRequestOperationManager() var hasRegistered: Bool = false var deviceToken: String? class var sharedRESTManager : RESTManager { return _SingletonSharedRESTManager } init() { } func register(deviceToken: String, password: String, completionClosure:(success: Bool) ->()) { println("Subscribing") let majorID: NSNumber = Beacon.sharedBeacon.majorID! let minorID: NSNumber = Beacon.sharedBeacon.minorID! var parameters: [String: String] = [ USER_ID_KEY:"(major:\(majorID), minor:\(minorID))", DEVICE_TOKEN_KEY:deviceToken, DEVICE_TYPE_KEY:"ios", PASSWORD_KEY: password ] manager.POST( BASE_URL + "/subscribe", parameters: parameters, success: { (operation: AFHTTPRequestOperation!, responseObj: AnyObject!) -> Void in var result: NSDictionary = responseObj as NSDictionary var success: Bool = result.objectForKey(API_SUCCESS) as Bool if (success) { if !self.hasRegistered { self.hasRegistered = true println("Registered with server") completionClosure(success: true) } } else { completionClosure(success: false) } }) { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in println(error) } } func request(targetMajorID: NSNumber, targetMinorID: NSNumber) { let majorID: NSNumber = Beacon.sharedBeacon.majorID! let minorID: NSNumber = Beacon.sharedBeacon.minorID! var parameters: [String: String] = [ USER_ID_KEY:"(major:\(majorID), minor:\(minorID))", TARGET_USER_ID_KEY:"(major:\(targetMajorID), minor:\(targetMinorID))" ] println("Messaging: \(parameters)") manager.POST( BASE_URL + "/message", parameters: parameters, success: { (operation: AFHTTPRequestOperation!, responseObj: AnyObject!) -> Void in var response: NSDictionary = responseObj as NSDictionary var success: Bool = response.objectForKey(API_SUCCESS) as Bool if (success) { var object: NSDictionary = response.objectForKey(API_OBJECT) as NSDictionary var question: String = object.objectForKey(API_QUESTION) as String var author: String = object.objectForKey(API_AUTHOR) as String var category: String = object.objectForKey(API_CATEGORY) as String var content = "Quote: \(question)\nAuthor: \(author)\nCategory: \(category)" var info: [String: String] = [NOTIF_CONTENT_KEY: content] NSNotificationCenter.defaultCenter().postNotificationName( NOTIF_BEACON_PAIRED, object: nil, userInfo: info ) println(responseObj) } else { var errors: [String] = response.objectForKey(API_ERRORS) as [String] for error in errors { switch error { case ERROR_PAIR_EXISTS_SOURCE: NSNotificationCenter.defaultCenter().postNotificationName(NOTIF_ERROR_PAIR_EXISTS_SOURCE, object: nil) break; case ERROR_PAIR_EXISTS_TARGET: NSNotificationCenter.defaultCenter().postNotificationName(NOTIF_ERROR_PAIR_EXISTS_TARGET, object: nil) break; case ERROR_INVALID_REQUEST: NSNotificationCenter.defaultCenter().postNotificationName(NOTIF_ERROR_INVALID_REQUEST, object: nil) break; case ERROR_TARGET_NOT_SUBSCRIBED: NSNotificationCenter.defaultCenter().postNotificationName(NOTIF_ERROR_TARGET_NOT_SUBSCRIBED, object: nil) break; default: break; } } } }) { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in println(error) } } func unpair() { println("Unpairing") let majorID: NSNumber = Beacon.sharedBeacon.majorID! let minorID: NSNumber = Beacon.sharedBeacon.minorID! var parameters: [String: String] = [ USER_ID_KEY:"(major:\(majorID), minor:\(minorID))" ] manager.POST( BASE_URL + "/unpair", parameters: parameters, success: { (operation: AFHTTPRequestOperation!, responseObj: AnyObject!) -> Void in println("Pairing Successful") }) { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in println(error) } } }
31ce2f1d429dbf23461ca24b3895483d
33.919355
133
0.488297
false
false
false
false
shitoudev/v2ex
refs/heads/master
v2ex/NodeModel.swift
mit
1
// // NodeModel.swift // v2ex // // Created by zhenwen on 5/8/15. // Copyright (c) 2015 zhenwen. All rights reserved. // import Foundation import Kanna class NodeModel: NSObject { var name: String, title: String var node_id: Int?, header: String?, url: String?, topics: Int?, avatar_large: String? init(fromDictionary dictionary: NSDictionary) { self.node_id = dictionary["id"] as? Int self.name = dictionary["name"] as! String self.title = dictionary["title"] as! String self.url = dictionary["url"] as? String self.topics = dictionary["topics"] as? Int self.avatar_large = dictionary["avatar_large"] as? String if let header = dictionary["header"] as? String { self.header = header } } static func getNodeList(completionHandler:(obj: [AnyObject]?, NSError?)->Void) { let url = APIManage.baseURLString var result = [AnyObject]() let mgr = APIManage.sharedManager mgr.request(.GET, url, parameters: nil).responseString(encoding: nil, completionHandler: { (response) -> Void in if response.result.isSuccess { guard let doc = HTML(html: response.result.value!, encoding: NSUTF8StringEncoding) else { completionHandler(obj: result, nil) return } let body = doc.body! // parsing navi var data = ["title":"导航", "node":[], "type":NSNumber(integer: 2)] var nodeArr = [NodeModel]() for aNode in body.css("a[class='tab']") { let title = aNode.text! let href = aNode["href"]!.componentsSeparatedByString("=") let name = href.last! let nodeInfo = ["name":name, "title":title] as NSDictionary let nodeModel = NodeModel(fromDictionary: nodeInfo) nodeArr.append(nodeModel) } data["node"] = nodeArr if nodeArr.count > 0 { result.append(data) } // parsing node var titleArr = [String]() for divNode in body.css("div[class='cell']") { if let table = divNode.at_css("table"), tdFirst = table.css("td").first, span = tdFirst.at_css("span[class='fade']") { let a = table.css("td").last!.css("a") if a.count > 0 { var canAdd = true for titleStr in titleArr { if titleStr == span.text { canAdd = false } } if canAdd { titleArr.append(span.text!) var data = ["title":span.text!, "node":[], "type":NSNumber(integer: 1)] var nodeArr = [NodeModel]() for aNode in a { let title = aNode.text! let href = aNode["href"]!.componentsSeparatedByString("/") let name = href.last! let nodeInfo = ["name":name, "title":title] as NSDictionary let nodeModel = NodeModel(fromDictionary: nodeInfo) nodeArr.append(nodeModel) } data["node"] = nodeArr result.append(data) } } } } } completionHandler(obj: result, nil) }) } }
1fba8ee029d7428c4af12a50d548c097
39.42
138
0.434933
false
false
false
false
imzyf/99-projects-of-swift
refs/heads/master
021-marslink/Marslink/ViewControllers/FeedViewController.swift
mit
1
// // FeedViewController.swift // Marslink // // Created by moma on 2017/11/23. // Copyright © 2017年 Ray Wenderlich. All rights reserved. // import UIKit import IGListKit class FeedViewController: UIViewController { let loader = JournalEntryLoader() // acts as messaging system let pathfinder = Pathfinder() let wxScanner = WxScanner() let collectionView: IGListCollectionView = { let view = IGListCollectionView(frame: CGRect.zero, collectionViewLayout: UICollectionViewFlowLayout()) view.backgroundColor = UIColor.black return view }() lazy var adapter: IGListAdapter = { return IGListAdapter(updater: IGListAdapterUpdater(), viewController: self, workingRangeSize: 0) }() override func viewDidLoad() { super.viewDidLoad() loader.loadLatest() view.addSubview(collectionView) adapter.collectionView = collectionView adapter.dataSource = self pathfinder.delegate = self pathfinder.connect() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() collectionView.frame = view.bounds } } extension FeedViewController: IGListAdapterDataSource { // returns an array of data objects the should show up in the collection view. func objects(for listAdapter: IGListAdapter) -> [IGListDiffable] { var items: [IGListDiffable] = [wxScanner.currentWeather] items += loader.entries as [IGListDiffable] items += pathfinder.messages as [IGListDiffable] return items.sorted(by: { (left: Any, right: Any) -> Bool in if let left = left as? DateSortable, let right = right as? DateSortable { return left.date > right.date } return false }) } // for each data object, must return a new instance of a section controller. func listAdapter(_ listAdapter: IGListAdapter, sectionControllerFor object: Any) -> IGListSectionController { if object is Message { return MessageSectionController() } else if object is Weather { return WeatherSectionController() } else { return JournalSectionController() } } // returns a view that should be displayed when the list is empty func emptyView(for listAdapter: IGListAdapter) -> UIView? { return nil } } extension FeedViewController: PathfinderDelegate { func pathfinderDidUpdateMessages(pathfinder: Pathfinder) { adapter.performUpdates(animated: true) } }
ed0753ba3e7e2d6e08d9ba1efef31479
29.287356
113
0.653131
false
false
false
false
nineteen-apps/swift
refs/heads/master
lessons-01/lesson5/Sources/main.swift
mit
1
// -*-swift-*- // The MIT License (MIT) // // Copyright (c) 2017 - Nineteen // // 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. // // Created: 2017-06-21 by Ronaldo Faria Lima // This file purpose: Demonstração do uso de coleções e tuplas import Foundation typealias MenuItem = (title: String, action: ()->()) var stop = false let menuItems: [MenuItem] = [ (title: "A - Mostrar Versão" , action: { print("Versão 1.0") }), (title: "B - Hora do Sistema", action: { print("\(Date())") }), (title: "X - Sair do Sistema", action: { stop = true }) ] let menuMap: [Character:Int] = ["A":0, "B":1, "X":2] func printMenu(menu: [MenuItem]) { for item in menu { print (item.title) } print ("Escolha sua opção: ", terminator: "") } while !stop { printMenu(menu: menuItems) if let input = readLine() { if let letter = input.uppercased().characters.first { if let index = menuMap[letter] { let menuItem = menuItems[index] menuItem.action() } else { print("Opção inválida!") } } } }
bbaf8280500e353b1a055b5caa62238b
36.421053
81
0.666667
false
false
false
false
KrishMunot/swift
refs/heads/master
test/Driver/linker.swift
apache-2.0
3
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 %s 2>&1 > %t.simple.txt // RUN: FileCheck %s < %t.simple.txt // RUN: FileCheck -check-prefix SIMPLE %s < %t.simple.txt // RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-ios7.1 %s 2>&1 > %t.simple.txt // RUN: FileCheck -check-prefix IOS_SIMPLE %s < %t.simple.txt // RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-tvos9.0 %s 2>&1 > %t.simple.txt // RUN: FileCheck -check-prefix tvOS_SIMPLE %s < %t.simple.txt // RUN: %swiftc_driver -driver-print-jobs -target i386-apple-watchos2.0 %s 2>&1 > %t.simple.txt // RUN: FileCheck -check-prefix watchOS_SIMPLE %s < %t.simple.txt // RUN: %swiftc_driver -driver-print-jobs -target x86_64-unknown-linux-gnu -Ffoo -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.linux.txt // RUN: FileCheck -check-prefix LINUX-x86_64 %s < %t.linux.txt // RUN: %swiftc_driver -driver-print-jobs -target armv6-unknown-linux-gnueabihf -Ffoo -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.linux.txt // RUN: FileCheck -check-prefix LINUX-armv6 %s < %t.linux.txt // RUN: %swiftc_driver -driver-print-jobs -target armv7-unknown-linux-gnueabihf -Ffoo -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.linux.txt // RUN: FileCheck -check-prefix LINUX-armv7 %s < %t.linux.txt // RUN: %swiftc_driver -driver-print-jobs -target thumbv7-unknown-linux-gnueabihf -Ffoo -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.linux.txt // RUN: FileCheck -check-prefix LINUX-thumbv7 %s < %t.linux.txt // RUN: %swiftc_driver -driver-print-jobs -emit-library -target x86_64-apple-macosx10.9.1 %s -sdk %S/../Inputs/clang-importer-sdk -lfoo -framework bar -Lbaz -Fgarply -Xlinker -undefined -Xlinker dynamic_lookup -o sdk.out 2>&1 > %t.complex.txt // RUN: FileCheck %s < %t.complex.txt // RUN: FileCheck -check-prefix COMPLEX %s < %t.complex.txt // RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 -g %s | FileCheck -check-prefix DEBUG %s // RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.10 %s | FileCheck -check-prefix NO_ARCLITE %s // RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-ios8.0 %s | FileCheck -check-prefix NO_ARCLITE %s // RUN: rm -rf %t && mkdir %t // RUN: touch %t/a.o // RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 %s %t/a.o -o linker 2>&1 | FileCheck -check-prefix COMPILE_AND_LINK %s // RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 %s %t/a.o -driver-use-filelists -o linker 2>&1 | FileCheck -check-prefix FILELIST %s // RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 -emit-library %s -module-name LINKER | FileCheck -check-prefix INFERRED_NAME %s // RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 -emit-library %s -o libLINKER.dylib | FileCheck -check-prefix INFERRED_NAME %s // There are more RUN lines further down in the file. // REQUIRES: X86 // FIXME: Need to set up a sysroot for osx so the DEBUG checks work on linux/freebsd // rdar://problem/19692770 // XFAIL: freebsd, linux // CHECK: swift // CHECK: -o [[OBJECTFILE:.*]] // CHECK-NEXT: bin/ld{{"? }} // CHECK-DAG: [[OBJECTFILE]] // CHECK-DAG: -L [[STDLIB_PATH:[^ ]+/lib/swift/macosx]] // CHECK-DAG: -rpath [[STDLIB_PATH]] // CHECK-DAG: -lSystem // CHECK-DAG: -arch x86_64 // CHECK-DAG: -force_load {{[^ ]+/lib/arc/libarclite_macosx.a}} -framework CoreFoundation // CHECK: -o {{[^ ]+}} // SIMPLE: bin/ld{{"? }} // SIMPLE-NOT: -syslibroot // SIMPLE-DAG: -macosx_version_min 10.{{[0-9]+}}.{{[0-9]+}} // SIMPLE-NOT: -syslibroot // SIMPLE: -o linker // IOS_SIMPLE: swift // IOS_SIMPLE: -o [[OBJECTFILE:.*]] // IOS_SIMPLE: bin/ld{{"? }} // IOS_SIMPLE-DAG: [[OBJECTFILE]] // IOS_SIMPLE-DAG: -L {{[^ ]+/lib/swift/iphonesimulator}} // IOS_SIMPLE-DAG: -lSystem // IOS_SIMPLE-DAG: -arch x86_64 // IOS_SIMPLE-DAG: -ios_simulator_version_min 7.1.{{[0-9]+}} // IOS_SIMPLE: -o linker // tvOS_SIMPLE: swift // tvOS_SIMPLE: -o [[OBJECTFILE:.*]] // tvOS_SIMPLE: bin/ld{{"? }} // tvOS_SIMPLE-DAG: [[OBJECTFILE]] // tvOS_SIMPLE-DAG: -L {{[^ ]+/lib/swift/appletvsimulator}} // tvOS_SIMPLE-DAG: -lSystem // tvOS_SIMPLE-DAG: -arch x86_64 // tvOS_SIMPLE-DAG: -tvos_simulator_version_min 9.0.{{[0-9]+}} // tvOS_SIMPLE: -o linker // watchOS_SIMPLE: swift // watchOS_SIMPLE: -o [[OBJECTFILE:.*]] // watchOS_SIMPLE: bin/ld{{"? }} // watchOS_SIMPLE-DAG: [[OBJECTFILE]] // watchOS_SIMPLE-DAG: -L {{[^ ]+/lib/swift/watchsimulator}} // watchOS_SIMPLE-DAG: -lSystem // watchOS_SIMPLE-DAG: -arch i386 // watchOS_SIMPLE-DAG: -watchos_simulator_version_min 2.0.{{[0-9]+}} // watchOS_SIMPLE: -o linker // LINUX-x86_64: swift // LINUX-x86_64: -o [[OBJECTFILE:.*]] // LINUX-x86_64: clang++{{"? }} // LINUX-x86_64-DAG: [[OBJECTFILE]] // LINUX-x86_64-DAG: -lswiftCore // LINUX-x86_64-DAG: -L [[STDLIB_PATH:[^ ]+/lib/swift]] // LINUX-x86_64-DAG: -Xlinker -rpath -Xlinker [[STDLIB_PATH]] // LINUX-x86_64-DAG: -F foo // LINUX-x86_64-DAG: -framework bar // LINUX-x86_64-DAG: -L baz // LINUX-x86_64-DAG: -lboo // LINUX-x86_64-DAG: -Xlinker -undefined // LINUX-x86_64: -o linker // LINUX-armv6: swift // LINUX-armv6: -o [[OBJECTFILE:.*]] // LINUX-armv6: clang++{{"? }} // LINUX-armv6-DAG: [[OBJECTFILE]] // LINUX-armv6-DAG: -lswiftCore // LINUX-armv6-DAG: -L [[STDLIB_PATH:[^ ]+/lib/swift]] // LINUX-armv6-DAG: --target=armv6-unknown-linux-gnueabihf // LINUX-armv6-DAG: -Xlinker -rpath -Xlinker [[STDLIB_PATH]] // LINUX-armv6-DAG: -F foo // LINUX-armv6-DAG: -framework bar // LINUX-armv6-DAG: -L baz // LINUX-armv6-DAG: -lboo // LINUX-armv6-DAG: -Xlinker -undefined // LINUX-armv6: -o linker // LINUX-armv7: swift // LINUX-armv7: -o [[OBJECTFILE:.*]] // LINUX-armv7: clang++{{"? }} // LINUX-armv7-DAG: [[OBJECTFILE]] // LINUX-armv7-DAG: -lswiftCore // LINUX-armv7-DAG: -L [[STDLIB_PATH:[^ ]+/lib/swift]] // LINUX-armv7-DAG: --target=armv7-unknown-linux-gnueabihf // LINUX-armv7-DAG: -Xlinker -rpath -Xlinker [[STDLIB_PATH]] // LINUX-armv7-DAG: -F foo // LINUX-armv7-DAG: -framework bar // LINUX-armv7-DAG: -L baz // LINUX-armv7-DAG: -lboo // LINUX-armv7-DAG: -Xlinker -undefined // LINUX-armv7: -o linker // LINUX-thumbv7: swift // LINUX-thumbv7: -o [[OBJECTFILE:.*]] // LINUX-thumbv7: clang++{{"? }} // LINUX-thumbv7-DAG: [[OBJECTFILE]] // LINUX-thumbv7-DAG: -lswiftCore // LINUX-thumbv7-DAG: -L [[STDLIB_PATH:[^ ]+/lib/swift]] // LINUX-thumbv7-DAG: --target=thumbv7-unknown-linux-gnueabihf // LINUX-thumbv7-DAG: -Xlinker -rpath -Xlinker [[STDLIB_PATH]] // LINUX-thumbv7-DAG: -F foo // LINUX-thumbv7-DAG: -framework bar // LINUX-thumbv7-DAG: -L baz // LINUX-thumbv7-DAG: -lboo // LINUX-thumbv7-DAG: -Xlinker -undefined // LINUX-thumbv7: -o linker // COMPLEX: bin/ld{{"? }} // COMPLEX-DAG: -dylib // COMPLEX-DAG: -syslibroot {{.*}}/Inputs/clang-importer-sdk // COMPLEX-DAG: -lfoo // COMPLEX-DAG: -framework bar // COMPLEX-DAG: -L baz // COMPLEX-DAG: -F garply // COMPLEX-DAG: -undefined dynamic_lookup // COMPLEX-DAG: -macosx_version_min 10.9.1 // COMPLEX: -o sdk.out // DEBUG: bin/swift // DEBUG-NEXT: bin/swift // DEBUG-NEXT: bin/ld{{"? }} // DEBUG: -add_ast_path {{.*}}/{{[^/]+}}.swiftmodule // DEBUG: -o linker // DEBUG-NEXT: bin/dsymutil // DEBUG: linker // DEBUG: -o linker.dSYM // NO_ARCLITE: bin/ld{{"? }} // NO_ARCLITE-NOT: arclite // NO_ARCLITE: -o {{[^ ]+}} // COMPILE_AND_LINK: bin/swift // COMPILE_AND_LINK-NOT: /a.o // COMPILE_AND_LINK: linker.swift // COMPILE_AND_LINK-NOT: /a.o // COMPILE_AND_LINK-NEXT: bin/ld{{"? }} // COMPILE_AND_LINK-DAG: /a.o // COMPILE_AND_LINK-DAG: .o // COMPILE_AND_LINK: -o linker // FILELIST: bin/ld{{"? }} // FILELIST-NOT: .o // FILELIST: -filelist {{"?[^-]}} // FILELIST-NOT: .o // FILELIST: /a.o // FILELIST-NOT: .o // FILELIST: -o linker // INFERRED_NAME: bin/swift // INFERRED_NAME: -module-name LINKER // INFERRED_NAME: bin/ld{{"? }} // INFERRED_NAME: -o libLINKER.dylib // Test ld detection. We use hard links to make sure // the Swift driver really thinks it's been moved. // RUN: rm -rf %t // RUN: mkdir -p %t/DISTINCTIVE-PATH/usr/bin/ // RUN: touch %t/DISTINCTIVE-PATH/usr/bin/ld // RUN: chmod +x %t/DISTINCTIVE-PATH/usr/bin/ld // RUN: ln %swift_driver_plain %t/DISTINCTIVE-PATH/usr/bin/swiftc // RUN: %t/DISTINCTIVE-PATH/usr/bin/swiftc %s -### | FileCheck -check-prefix=RELATIVE-LINKER %s // RELATIVE-LINKER: /DISTINCTIVE-PATH/usr/bin/swift // RELATIVE-LINKER: /DISTINCTIVE-PATH/usr/bin/ld // RELATIVE-LINKER: -o {{[^ ]+}} // Also test arclite detection. This uses xcrun to find arclite when it's not // next to Swift. // RUN: mkdir -p %t/ANOTHER-DISTINCTIVE-PATH/usr/bin // RUN: mkdir -p %t/ANOTHER-DISTINCTIVE-PATH/usr/lib/arc // RUN: cp %S/Inputs/xcrun-return-self.sh %t/ANOTHER-DISTINCTIVE-PATH/usr/bin/xcrun // RUN: env PATH=%t/ANOTHER-DISTINCTIVE-PATH/usr/bin %t/DISTINCTIVE-PATH/usr/bin/swiftc -target x86_64-apple-macosx10.9 %s -### | FileCheck -check-prefix=XCRUN_ARCLITE %s // XCRUN_ARCLITE: bin/ld{{"? }} // XCRUN_ARCLITE: /ANOTHER-DISTINCTIVE-PATH/usr/lib/arc/libarclite_macosx.a // XCRUN_ARCLITE: -o {{[^ ]+}} // RUN: mkdir -p %t/DISTINCTIVE-PATH/usr/lib/arc // RUN: env PATH=%t/ANOTHER-DISTINCTIVE-PATH/usr/bin %t/DISTINCTIVE-PATH/usr/bin/swiftc -target x86_64-apple-macosx10.9 %s -### | FileCheck -check-prefix=RELATIVE_ARCLITE %s // RELATIVE_ARCLITE: bin/ld{{"? }} // RELATIVE_ARCLITE: /DISTINCTIVE-PATH/usr/lib/arc/libarclite_macosx.a // RELATIVE_ARCLITE: -o {{[^ ]+}} // Clean up the test executable because hard links are expensive. // RUN: rm -rf %t/DISTINCTIVE-PATH/usr/bin/swiftc
0655d1583b507cc1bead11cde9d3c071
36.023256
242
0.669284
false
false
false
false
18775134221/SwiftBase
refs/heads/master
SwiftTest/SwiftTest/Classes/Main/VC/BaseTabBarVC.swift
apache-2.0
2
// // BaseTabBarVC.swift // SwiftTest // // Created by MAC on 2016/12/10. // Copyright © 2016年 MAC. All rights reserved. // import UIKit class BaseTabBarVC: UITabBarController { fileprivate var homeVC: HomeVC? = nil fileprivate var typesVC: TypesVC? = nil fileprivate var shoppingCartVC: ShoppingCartVC? = nil fileprivate var mineVC: MineVC? = nil override func viewDidLoad() { super.viewDidLoad() setupUI() } } extension BaseTabBarVC { fileprivate func setupUI() { setupChildVCs() setupTabBar() } // 设置自定义的TabBar private func setupTabBar() { UITabBar.appearance().tintColor = UIColor.orange let baseTabBar: BaseTabBar = BaseTabBar() baseTabBar.type = .plusDefault // 隐藏系统顶部tabBar的黑线 baseTabBar.shadowImage = UIImage() baseTabBar.backgroundImage = UIImage() baseTabBar.backgroundColor = UIColor(r: 0.62, g: 0.03, b: 0.05) setValue(baseTabBar, forKey: "tabBar") } private func setupChildVCs() { homeVC = UIStoryboard(name: "Home", bundle: nil).instantiateViewController(withIdentifier: "HomeVC") as? HomeVC addChildVC(homeVC!,"首页","icon_home_normal","icon_home_selected") typesVC = UIStoryboard(name: "Types", bundle: nil).instantiateViewController(withIdentifier: "TypesVC") as? TypesVC addChildVC(typesVC!,"分类","iocn_classification_normal","iocn_classification_selected") shoppingCartVC = UIStoryboard(name: "ShoppingCart", bundle: nil).instantiateViewController(withIdentifier: "ShoppingCartVC") as? ShoppingCartVC addChildVC(shoppingCartVC!,"购物车","icon_shopping-cart_normal","icon_shopping-cart_selected") mineVC = UIStoryboard(name: "Mine", bundle: nil).instantiateViewController(withIdentifier: "MineVC") as? MineVC addChildVC(mineVC!,"我的","icon_personal-center_normal","icon_personal-center_selected") } private func addChildVC(_ vc: UIViewController, _ title: String = "", _ normalImage: String = "",_ selectedImage: String = "") { vc.title = title; vc.tabBarItem.selectedImage = UIImage(named: selectedImage) vc.tabBarItem.image = UIImage(named: normalImage) let baseNaviVC: BaseNavigationVC = BaseNavigationVC(rootViewController: vc) addChildViewController(baseNaviVC) } } extension BaseTabBarVC: UITabBarControllerDelegate { // 选中底部导航按钮回调 override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) { } }
68f767070cf7527ebf6af0f2cc72e46e
30.317647
151
0.648009
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/UIComponents/UIComponentsKit/Views/EmptyStateView.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import SwiftUI /// A view which represents the lack of content public struct EmptyStateView: View { let title: String let subHeading: String let image: Image private let layout = Layout() public init(title: String, subHeading: String, image: Image) { self.title = title self.subHeading = subHeading self.image = image } public var body: some View { VStack { Text(title) .textStyle(.title) .foregroundColor(.textTitle) Spacer() .frame(height: layout.textSpacing) Text(subHeading) .textStyle(.subheading) .foregroundColor(.textSubheading) Spacer() .frame(height: layout.imageSpacing) image } } } extension EmptyStateView { struct Layout { let textSpacing: CGFloat = 8 let imageSpacing: CGFloat = 24 } } struct EmptyStateView_Previews: PreviewProvider { static var previews: some View { EmptyStateView( title: "You Have No Activity", subHeading: "All your transactions will show up here.", image: ImageAsset.emptyActivity.image ) } }
5b87d307e90125e16542e9df098d1c76
22.535714
67
0.580425
false
false
false
false
motylevm/skstylekit
refs/heads/master
Sources/SKStyleKitSource.swift
mit
1
// // SKStyleKitSource.swift // SKStyleKit // // Created by Мотылёв Михаил on 09/03/2017. // Copyright © 2017 mmotylev. All rights reserved. // import Foundation enum SKStyleKitSourceLocation { case bundle(Bundle) case file(String) } enum SKStylesSourceType: Int { case main = 1 case styleKit = -1 case other = 0 } public final class SKStyleKitSource { // MARK: - Properties - let location: SKStyleKitSourceLocation let type: SKStylesSourceType let zIndex: Int // MARK: - Init - private init(location: SKStyleKitSourceLocation, type: SKStylesSourceType, zIndex: Int) { self.location = location self.type = type self.zIndex = zIndex } // MARK: - Providers - func getProviders() -> [SKStylesSourceProvider] { let files: [String] switch location { case .bundle(let bundle): guard let bundleFiles = try? FileManager.default.contentsOfDirectory(atPath: bundle.bundlePath) else { return [] } files = bundleFiles.filter({ $0.hasPrefix("style") && $0.hasSuffix(".json") }).compactMap({ bundle.path(forResource: $0, ofType: nil) }) case .file(let path): files = [path] } return files.compactMap { SKStylesSourceProvider(filePath: $0, sourceType: type, zIndex: zIndex) } } // MARK: - Factory - public class func main() -> SKStyleKitSource { return SKStyleKitSource(location: .bundle(Bundle.main), type: .main, zIndex: 0) } public class func styleKit() -> SKStyleKitSource { return SKStyleKitSource(location: .bundle(Bundle(for: SKStyleKitSource.self)), type: .styleKit, zIndex: 0) } public class func file(_ path: String, zIndex: Int = 0) -> SKStyleKitSource { return SKStyleKitSource(location: .file(path), type: .other, zIndex: zIndex) } public class func bundle(_ bundle: Bundle, zIndex: Int = 0)-> SKStyleKitSource { return SKStyleKitSource(location: .bundle(bundle), type: .other, zIndex: zIndex) } }
9691c3a95abb5a211ef334fb712fc69e
28.643836
152
0.61414
false
false
false
false
marty-suzuki/FluxCapacitor
refs/heads/master
Examples/Flux+MVVM/FluxCapacitorSample/Sources/UI/Search/SearchViewController.swift
mit
1
// // SearchViewController.swift // FluxCapacitorSample // // Created by marty-suzuki on 2017/08/01. // Copyright © 2017年 marty-suzuki. All rights reserved. // import UIKit import RxSwift import RxCocoa import NoticeObserveKit final class SearchViewController: UIViewController { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var tableViewBottomConstraint: NSLayoutConstraint! @IBOutlet weak var counterLabel: UILabel! private let searchBar: UISearchBar = UISearchBar(frame: .zero) private let disposeBag = DisposeBag() private let selectUserRowAt = PublishSubject<IndexPath>() private let fetchMoreUsers = PublishSubject<Void>() private(set) lazy var dataSource: SearchViewDataSource = .init(viewModel: self.viewModel) private(set) lazy var viewModel: SearchViewModel = { let viewWillAppear = self.rx .methodInvoked(#selector(SearchViewController.viewWillAppear(_:))) .map { _ in } let viewWillDisappear = self.rx .methodInvoked(#selector(SearchViewController.viewWillDisappear(_:))) .map { _ in } return .init(viewWillAppear: viewWillAppear, viewWillDisappear: viewWillDisappear, searchText: self.searchBar.rx.text.orEmpty, selectUserRowAt: self.selectUserRowAt, fetchMoreUsers: self.fetchMoreUsers) }() override func viewDidLoad() { super.viewDidLoad() navigationItem.titleView = searchBar searchBar.placeholder = "Input user name" tableView.contentInset.top = 44 configureDataSource() observeUI() observeViewModel() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) if searchBar.isFirstResponder { searchBar.resignFirstResponder() } } private func configureDataSource() { dataSource.selectUserRowAt .bind(to: selectUserRowAt) .disposed(by: disposeBag) dataSource.fetchMoreUsers .bind(to: fetchMoreUsers) .disposed(by: disposeBag) dataSource.configure(with: tableView) } private func observeViewModel() { viewModel.keyboardWillShow .bind(to: keyboardWillShow) .disposed(by: disposeBag) viewModel.keyboardWillHide .bind(to: keyboardWillHide) .disposed(by: disposeBag) viewModel.showUserRepository .bind(to: showUserRepository) .disposed(by: disposeBag) viewModel.counterText .bind(to: counterLabel.rx.text) .disposed(by: disposeBag) viewModel.reloadData .bind(to: reloadData) .disposed(by: disposeBag) } private func observeUI() { Observable.merge(searchBar.rx.cancelButtonClicked.asObservable(), searchBar.rx.searchButtonClicked.asObservable()) .bind(to: resignFirstResponder) .disposed(by: disposeBag) searchBar.rx.textDidBeginEditing .map { true } .bind(to: showsCancelButton) .disposed(by: disposeBag) searchBar.rx.textDidEndEditing .map { false } .bind(to: showsCancelButton) .disposed(by: disposeBag) } private var keyboardWillShow: AnyObserver<UIKeyboardInfo> { return Binder(self) { me, keyboardInfo in me.view.layoutIfNeeded() let extra = me.tabBarController?.tabBar.bounds.height ?? 0 me.tableViewBottomConstraint.constant = keyboardInfo.frame.size.height - extra UIView.animate(withDuration: keyboardInfo.animationDuration, delay: 0, options: keyboardInfo.animationCurve, animations: { me.view.layoutIfNeeded() }, completion: nil) }.asObserver() } private var keyboardWillHide: AnyObserver<UIKeyboardInfo> { return Binder(self) { me, keyboardInfo in me.view.layoutIfNeeded() me.tableViewBottomConstraint.constant = 0 UIView.animate(withDuration: keyboardInfo.animationDuration, delay: 0, options: keyboardInfo.animationCurve, animations: { me.view.layoutIfNeeded() }, completion: nil) }.asObserver() } private var reloadData: AnyObserver<Void> { return Binder(self) { me, _ in me.tableView.reloadData() }.asObserver() } private var resignFirstResponder: AnyObserver<Void> { return Binder(self) { me, _ in me.searchBar.resignFirstResponder() }.asObserver() } private var showsCancelButton: AnyObserver<Bool> { return Binder(self) { me, showsCancelButton in me.searchBar.showsScopeBar = showsCancelButton }.asObserver() } private var showUserRepository: AnyObserver<Void> { return Binder(self) { me, _ in let vc = UserRepositoryViewController() me.navigationController?.pushViewController(vc, animated: true) }.asObserver() } }
a93eeef23f6a42f0aa5ab8d561937e1c
32.987421
93
0.605848
false
false
false
false
Constantine-Fry/das-quadrat
refs/heads/develop
Source/Shared/Endpoints/Endpoint.swift
bsd-2-clause
1
// // Endpoint.swift // Quadrat // // Created by Constantine Fry on 06/11/14. // Copyright (c) 2014 Constantine Fry. All rights reserved. // import Foundation public func +=<K, V> (left: inout Dictionary<K, V>, right: Dictionary<K, V>?) { right?.forEach { left.updateValue($1, forKey: $0) } } open class Endpoint { weak var session: Session? fileprivate let baseURL: URL var endpoint: String { return "" } init(session: Session) { self.session = session guard let baseURL = URL(string:session.configuration.server.apiBaseURL) else { fatalError("Not an URL") } self.baseURL = baseURL } func getWithPath(_ path: String, parameters: Parameters?, completionHandler: ResponseClosure?) -> Task { return self.taskWithPath(path, parameters: parameters, httpMethod: "GET", completionHandler: completionHandler) } func postWithPath(_ path: String, parameters: Parameters?, completionHandler: ResponseClosure?) -> Task { return self.taskWithPath(path, parameters: parameters, httpMethod: "POST", completionHandler: completionHandler) } func uploadTaskFromURL(_ fromURL: URL, path: String, parameters: Parameters?, completionHandler: ResponseClosure?) -> Task { let request = self.requestWithPath(path, parameters: parameters, httpMethod: "POST") let task = UploadTask(session: self.session!, request: request, completionHandler: completionHandler) task.fileURL = fromURL return task } fileprivate func taskWithPath(_ path: String, parameters: Parameters?, httpMethod: String, completionHandler: ResponseClosure?) -> Task { let request = self.requestWithPath(path, parameters: parameters, httpMethod: httpMethod) return DataTask(session: self.session!, request: request, completionHandler: completionHandler) } fileprivate func requestWithPath(_ path: String, parameters: Parameters?, httpMethod: String) -> Request { var sessionParameters = session!.configuration.parameters() if sessionParameters[Parameter.oauth_token] == nil { do { let accessToken = try session!.keychain.accessToken() if let accessToken = accessToken { sessionParameters[Parameter.oauth_token] = accessToken } } catch { } } let request = Request(baseURL: self.baseURL, path: (self.endpoint + "/" + path), parameters: parameters, sessionParameters: sessionParameters, HTTPMethod: httpMethod) request.timeoutInterval = session!.configuration.timeoutInterval return request } }
5da54fb98936525454d3b04458fb3f96
37.847222
120
0.644262
false
false
false
false
GustavoAlvarez/Universe-Atlas
refs/heads/master
Universe Atlas/BWWalkthroughViewController.swift
mit
1
/* The MIT License (MIT) Copyright (c) 2015 Yari D'areglia @bitwaker 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 // MARK: - Protocols - /// Walkthrough Delegate: /// This delegate performs basic operations such as dismissing the Walkthrough or call whatever action on page change. /// Probably the Walkthrough is presented by this delegate. @objc public protocol BWWalkthroughViewControllerDelegate{ @objc optional func walkthroughCloseButtonPressed() // If the skipRequest(sender:) action is connected to a button, this function is called when that button is pressed. @objc optional func walkthroughNextButtonPressed() // Called when the "next page" button is pressed @objc optional func walkthroughPrevButtonPressed() // Called when the "previous page" button is pressed @objc optional func walkthroughPageDidChange(_ pageNumber:Int) // Called when current page changes } /// Walkthrough Page: /// The walkthrough page represents any page added to the Walkthrough. @objc public protocol BWWalkthroughPage{ /// While sliding to the "next" slide (from right to left), the "current" slide changes its offset from 1.0 to 2.0 while the "next" slide changes it from 0.0 to 1.0 /// While sliding to the "previous" slide (left to right), the current slide changes its offset from 1.0 to 0.0 while the "previous" slide changes it from 2.0 to 1.0 /// The other pages update their offsets whith values like 2.0, 3.0, -2.0... depending on their positions and on the status of the walkthrough /// This value can be used on the previous, current and next page to perform custom animations on page's subviews. @objc func walkthroughDidScroll(to:CGFloat, offset:CGFloat) // Called when the main Scrollview...scrolls } @objc open class BWWalkthroughViewController: UIViewController, UIScrollViewDelegate{ // MARK: - Public properties - weak open var delegate:BWWalkthroughViewControllerDelegate? // If you need a page control, next or prev buttons, add them via IB and connect with these Outlets @IBOutlet open var pageControl:UIPageControl? @IBOutlet open var nextButton:UIButton? @IBOutlet open var prevButton:UIButton? @IBOutlet open var closeButton:UIButton? open var currentPage: Int { // The index of the current page (readonly) get{ let page = Int((scrollview.contentOffset.x / view.bounds.size.width)) return page } } open var currentViewController:UIViewController{ //the controller for the currently visible page get{ let currentPage = self.currentPage; return controllers[currentPage]; } } open var numberOfPages:Int{ //the total number of pages in the walkthrough get { return self.controllers.count } } // MARK: - Private properties - open let scrollview = UIScrollView() private var controllers = [UIViewController]() private var lastViewConstraint: [NSLayoutConstraint]? // MARK: - Overrides - required public init?(coder aDecoder: NSCoder) { // Setup the scrollview scrollview.showsHorizontalScrollIndicator = false scrollview.showsVerticalScrollIndicator = false scrollview.isPagingEnabled = true super.init(coder: aDecoder) } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } override open func viewDidLoad() { super.viewDidLoad() // Initialize UI Elements pageControl?.addTarget(self, action: #selector(BWWalkthroughViewController.pageControlDidTouch), for: UIControlEvents.touchUpInside) // Scrollview scrollview.delegate = self scrollview.translatesAutoresizingMaskIntoConstraints = false view.insertSubview(scrollview, at: 0) //scrollview is inserted as first view of the hierarchy // Set scrollview related constraints view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[scrollview]-0-|", options:[], metrics: nil, views: ["scrollview":scrollview] as [String: UIView])) view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[scrollview]-0-|", options:[], metrics: nil, views: ["scrollview":scrollview] as [String: UIView])) } override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated); updateUI() pageControl?.numberOfPages = controllers.count pageControl?.currentPage = 0 } // MARK: - Internal methods - @IBAction open func nextPage(){ if (currentPage + 1) < controllers.count { delegate?.walkthroughNextButtonPressed?() gotoPage(currentPage + 1) } } @IBAction open func prevPage(){ if currentPage > 0 { delegate?.walkthroughPrevButtonPressed?() gotoPage(currentPage - 1) } } /// If you want to implement a "skip" button /// connect the button to this IBAction and implement the delegate with the skipWalkthrough @IBAction open func close(_ sender: AnyObject) { delegate?.walkthroughCloseButtonPressed?() } func pageControlDidTouch(){ if let pc = pageControl{ gotoPage(pc.currentPage) } } fileprivate func gotoPage(_ page:Int){ if page < controllers.count{ var frame = scrollview.frame frame.origin.x = CGFloat(page) * frame.size.width scrollview.scrollRectToVisible(frame, animated: true) } } /// Add a new page to the walkthrough. /// To have information about the current position of the page in the walkthrough add a UIViewController which implements BWWalkthroughPage /// - viewController: The view controller that will be added at the end of the view controllers list. open func add(viewController:UIViewController)->Void{ controllers.append(viewController) // Make children aware of the parent addChildViewController(viewController) viewController.didMove(toParentViewController: self) // Setup the viewController view viewController.view.translatesAutoresizingMaskIntoConstraints = false scrollview.addSubview(viewController.view) // Constraints let metricDict = ["w":viewController.view.bounds.size.width,"h":viewController.view.bounds.size.height] // Generic cnst let viewsDict: [String: UIView] = ["view":viewController.view, "container": scrollview] scrollview.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[view(==container)]", options:[], metrics: metricDict, views: viewsDict)) scrollview.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[view(==container)]", options:[], metrics: metricDict, views: viewsDict)) scrollview.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[view]|", options:[], metrics: nil, views: viewsDict)) // cnst for position: 1st element if controllers.count == 1{ scrollview.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[view]", options:[], metrics: nil, views: ["view":viewController.view])) // cnst for position: other elements } else { let previousVC = controllers[controllers.count-2] if let previousView = previousVC.view { // For this constraint to work, previousView can not be optional scrollview.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[previousView]-0-[view]", options:[], metrics: nil, views: ["previousView":previousView,"view":viewController.view])) } if let cst = lastViewConstraint { scrollview.removeConstraints(cst) } lastViewConstraint = NSLayoutConstraint.constraints(withVisualFormat: "H:[view]-0-|", options:[], metrics: nil, views: ["view":viewController.view]) scrollview.addConstraints(lastViewConstraint!) } } /// Update the UI to reflect the current walkthrough status fileprivate func updateUI(){ pageControl?.currentPage = currentPage delegate?.walkthroughPageDidChange?(currentPage) // Hide/Show navigation buttons if currentPage == controllers.count - 1{ //nextButton?.isHidden = true }else{ //nextButton?.isHidden = false } if currentPage == 0{ //prevButton?.isHidden = true }else{ //prevButton?.isHidden = false } } // MARK: - Scrollview Delegate - open func scrollViewDidScroll(_ sv: UIScrollView) { for i in 0 ..< controllers.count { if let vc = controllers[i] as? BWWalkthroughPage{ let mx = ((scrollview.contentOffset.x + view.bounds.size.width) - (view.bounds.size.width * CGFloat(i))) / view.bounds.size.width // While sliding to the "next" slide (from right to left), the "current" slide changes its offset from 1.0 to 2.0 while the "next" slide changes it from 0.0 to 1.0 // While sliding to the "previous" slide (left to right), the current slide changes its offset from 1.0 to 0.0 while the "previous" slide changes it from 2.0 to 1.0 // The other pages update their offsets whith values like 2.0, 3.0, -2.0... depending on their positions and on the status of the walkthrough // This value can be used on the previous, current and next page to perform custom animations on page's subviews. // print the mx value to get more info. // println("\(i):\(mx)") // We animate only the previous, current and next page if(mx < 2 && mx > -2.0){ vc.walkthroughDidScroll(to:scrollview.contentOffset.x, offset: mx) } } } } open func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { updateUI() } open func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { updateUI() } fileprivate func adjustOffsetForTransition() { // Get the current page before the transition occurs, otherwise the new size of content will change the index let currentPage = self.currentPage let popTime = DispatchTime.now() + Double(Int64( Double(NSEC_PER_SEC) * 0.1 )) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: popTime) { [weak self] in self?.gotoPage(currentPage) } } override open func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) { adjustOffsetForTransition() } override open func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { adjustOffsetForTransition() } }
553373df12ef8454351fb497ea2c0c88
40.906667
211
0.655504
false
false
false
false
Darren-chenchen/CLImagePickerTool
refs/heads/master
CLImagePickerTool/CLImagePickerTool/CLImagePickerTool.swift
mit
1
// // CLPickerTool.swift // ImageDeal // // Created by darren on 2017/8/3. // Copyright © 2017年 陈亮陈亮. All rights reserved. // import UIKit import Photos import PhotosUI public enum CLImagePickerToolType { case singlePicture // 图片单选 case singlePictureCrop // 单选并裁剪 } public enum CLImagePickerToolStatusBarType { case black // 黑色 case white // 白色 } public typealias CLPickerToolClouse = (Array<PHAsset>,UIImage?)->() public class CLImagePickerTool: NSObject,UIImagePickerControllerDelegate,UINavigationControllerDelegate { @objc var cameraPicker: UIImagePickerController! private weak var superVC: UIViewController? public var clPickerToolClouse: CLPickerToolClouse? // 是否隐藏视频文件,默认不隐藏 @objc public var isHiddenVideo: Bool = false // 是否隐藏图片文件,显示视频文件,默认不隐藏 @objc public var isHiddenImage: Bool = false // 设置单选图片,单选图片并裁剪属性,默认多选 public var singleImageChooseType: CLImagePickerToolType? // 设置相机在外部,默认不在外部 @objc public var cameraOut: Bool = false // 单选模式下图片并且可裁剪。默认裁剪比例是1:1,也可以设置如下参数 public var singlePictureCropScale: CGFloat? // 视频和照片只能选择一种,不能同时选择,默认可以同时选择 @objc public var onlyChooseImageOrVideo: Bool = false // 单选模式下,图片可以编辑,默认不可编辑 @objc public var singleModelImageCanEditor: Bool = false // 配置导航栏的颜色,默认是毛玻璃效果 public var navColor: UIColor? = nil // 配置导航栏文字的颜色 public var navTitleColor: UIColor? = nil // 配置状态栏的颜色 public var statusBarType: CLImagePickerToolStatusBarType = .black // 相册中是否展示拍照图片 public var showCamaroInPicture = true // 文字和图片的颜色 85 182 55 public var tineColor = UIColor.init(red: 85/255.0, green: 182/255.0, blue: 55/255.0, alpha: 1) { didSet { CLPickersTools.instence.tineColor = tineColor } } private let isPad: Bool = UIDevice.current.model == "iPad" // 第二种弹出方式 @available(*, deprecated, message: "Use 'cl_setupImagePickerAnotherWayWith' instead.") public func setupImagePickerAnotherWayWith(maxImagesCount: Int,superVC: UIViewController,didChooseImageSuccess:@escaping (Array<PHAsset>,UIImage?)->()) { CLPickersTools.instence.authorize(authorizeClouse: { (state) in if state == .authorized { let anotherVC = CLImagePickerAnotherViewController.init(nibName: "CLImagePickerAnotherViewController", bundle: BundleUtil.getCurrentBundle()) anotherVC.modalPresentationStyle = .custom anotherVC.transitioningDelegate = CLPresent.instance anotherVC.MaxImagesCount = maxImagesCount anotherVC.isHiddenVideo = self.isHiddenVideo anotherVC.isHiddenImage = self.isHiddenImage anotherVC.onlyChooseImageOrVideo = self.onlyChooseImageOrVideo anotherVC.singleChooseImageCompleteClouse = { (assetArr:Array<PHAsset>,image) in didChooseImageSuccess(assetArr,image) } anotherVC.modalPresentationStyle = .fullScreen superVC.present(anotherVC, animated: true, completion: nil) } }) } public func cl_setupImagePickerAnotherWayWith(maxImagesCount: Int,superVC: UIViewController? = nil, didChooseImageSuccess:@escaping (Array<PHAsset>,UIImage?)->()) { CLPickersTools.instence.authorize(authorizeClouse: { (state) in self.superVC = superVC if self.superVC == nil { self.superVC = self.getCurrentViewcontroller() } if state == .authorized { let anotherVC = CLImagePickerAnotherViewController.init(nibName: "CLImagePickerAnotherViewController", bundle: BundleUtil.getCurrentBundle()) anotherVC.modalPresentationStyle = .custom anotherVC.transitioningDelegate = CLPresent.instance anotherVC.MaxImagesCount = maxImagesCount anotherVC.isHiddenVideo = self.isHiddenVideo anotherVC.isHiddenImage = self.isHiddenImage anotherVC.onlyChooseImageOrVideo = self.onlyChooseImageOrVideo anotherVC.singleChooseImageCompleteClouse = { (assetArr:Array<PHAsset>,image) in didChooseImageSuccess(assetArr,image) } self.superVC?.present(anotherVC, animated: true, completion: nil) } }) } // 判断相机是放在外面还是内部 @available(*, deprecated, message: "Use 'cl_setupImagePickerWith' instead.") @objc public func setupImagePickerWith(MaxImagesCount: Int,superVC:UIViewController,didChooseImageSuccess:@escaping (Array<PHAsset>,UIImage?)->()) { self.superVC = superVC self.clPickerToolClouse = didChooseImageSuccess if self.cameraOut == true { // 拍照功能在外面 var alert: UIAlertController! alert = UIAlertController(title: nil, message: nil, preferredStyle: isPad ? .alert : .actionSheet) let cleanAction = UIAlertAction(title: cancelStr, style: UIAlertAction.Style.cancel,handler:nil) let photoAction = UIAlertAction(title: tackPhotoStr, style: UIAlertAction.Style.default){ (action:UIAlertAction)in // 访问相机 self.camera(superVC:superVC) } let choseAction = UIAlertAction(title: chooseStr, style: UIAlertAction.Style.default){ (action:UIAlertAction)in self.gotoPhoto(MaxImagesCount: MaxImagesCount) } alert.addAction(cleanAction) alert.addAction(photoAction) alert.addAction(choseAction) alert.modalPresentationStyle = .fullScreen superVC.present(alert, animated: true, completion: nil) } else { self.gotoPhoto(MaxImagesCount: MaxImagesCount) } } @objc public func cl_setupImagePickerWith(MaxImagesCount: Int,superVC:UIViewController? = nil,didChooseImageSuccess:@escaping (Array<PHAsset>,UIImage?)->()) { self.superVC = superVC if self.superVC == nil { self.superVC = self.getCurrentViewcontroller() } if self.superVC == nil { print("未获取到当前控制器") return } self.clPickerToolClouse = didChooseImageSuccess if self.cameraOut == true { // 拍照功能在外面 var alert: UIAlertController! alert = UIAlertController(title: nil, message: nil, preferredStyle: isPad ? .alert : .actionSheet) let cleanAction = UIAlertAction(title: cancelStr, style: UIAlertAction.Style.cancel,handler:nil) let photoAction = UIAlertAction(title: tackPhotoStr, style: UIAlertAction.Style.default){ (action:UIAlertAction)in // 访问相机 self.cl_camera(superVC: self.superVC) } let choseAction = UIAlertAction(title: chooseStr, style: UIAlertAction.Style.default){ (action:UIAlertAction)in self.gotoPhoto(MaxImagesCount: MaxImagesCount) } alert.addAction(cleanAction) alert.addAction(photoAction) alert.addAction(choseAction) alert.modalPresentationStyle = .fullScreen self.superVC!.present(alert, animated: true, completion: nil) } else { self.gotoPhoto(MaxImagesCount: MaxImagesCount) } } // 访问相册 func gotoPhoto(MaxImagesCount: Int) { // 判断用户是否开启访问相册功能 CLPickersTools.instence.authorize(authorizeClouse: { (state) in if state == .authorized { let photo = CLImagePickersViewController.share.initWith( MaxImagesCount: MaxImagesCount, isHiddenVideo:self.isHiddenVideo, cameraOut:self.cameraOut, singleType:self.singleImageChooseType, singlePictureCropScale:self.singlePictureCropScale, onlyChooseImageOrVideo:self.onlyChooseImageOrVideo, singleModelImageCanEditor:self.singleModelImageCanEditor, showCamaroInPicture: self.showCamaroInPicture, isHiddenImage:self.isHiddenImage, navColor:self.navColor, navTitleColor:self.navTitleColor, statusBarType:self.statusBarType ) { (assetArr,cutImage) in if self.clPickerToolClouse != nil { self.clPickerToolClouse!(assetArr,cutImage) } } photo.modalPresentationStyle = .fullScreen self.superVC?.present(photo, animated: true, completion: nil) } }) } // 访问相机 @available(*, deprecated, message: "Use 'cl_camera' instead.") @objc public func camera(superVC:UIViewController) { CLPickersTools.instence.authorizeCamaro { (state) in if state == .authorized { if self.isCameraAvailable() == false { PopViewUtil.alert(message: "相机不可用", leftTitle: "", rightTitle: "确定", leftHandler: nil, rightHandler: nil) return } DispatchQueue.main.async { self.cameraPicker = UIImagePickerController() self.cameraPicker.delegate = self self.cameraPicker.sourceType = .camera self.cameraPicker.modalPresentationStyle = .fullScreen superVC.present((self.cameraPicker)!, animated: true, completion: nil) } } } } @objc public func cl_camera(superVC:UIViewController? = nil) { self.superVC = superVC if self.superVC == nil { self.superVC = self.getCurrentViewcontroller() } if self.superVC == nil { print("未获取到当前控制器") return } CLPickersTools.instence.authorizeCamaro { (state) in if state == .authorized { if self.isCameraAvailable() == false { PopViewUtil.alert(message: "相机不可用", leftTitle: "", rightTitle: "确定", leftHandler: nil, rightHandler: nil) return } DispatchQueue.main.async { self.cameraPicker = UIImagePickerController() self.cameraPicker.delegate = self self.cameraPicker.sourceType = .camera self.cameraPicker.modalPresentationStyle = .fullScreen self.superVC!.present((self.cameraPicker)!, animated: true, completion: nil) } } } } func isCameraAvailable() -> Bool{ return UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.camera) } //MARK: - 提供asset数组转图片的方法供外界使用---原图,异步方法,每转换成一张图片就返回出去 @objc public static func convertAssetArrToOriginImage(assetArr:Array<PHAsset>,scale:CGFloat,successClouse:@escaping (UIImage,PHAsset)->(),failedClouse:@escaping ()->()) { for item in assetArr { CLImagePickerTool.getAssetOrigin(asset: item, dealImageSuccess: { (img, info) in if img != nil { // 对图片压缩 if img!.jpegData(compressionQuality: scale) == nil { } else { let zipImageData = img!.jpegData(compressionQuality: scale)! let image = UIImage(data: zipImageData) successClouse(image!,item) } } }, dealImageFailed: { failedClouse() }) } } //MARK: - 提供asset数组转图片的方法供外界使用---缩略图 @objc public static func convertAssetArrToThumbnailImage(assetArr:Array<PHAsset>,targetSize:CGSize) -> [UIImage] { var imageArr = [UIImage]() for item in assetArr { if item.mediaType == .image { // 如果是图片 CLPickersTools.instence.getAssetThumbnail(targetSize: targetSize, asset: item, dealImageSuccess: { (img, info) in imageArr.append(img ?? UIImage()) }) } } return imageArr } //MARK: - 提供asset数组中的视频文件转为AVPlayerItem数组 @objc public static func convertAssetToAvPlayerItem(asset:PHAsset,successClouse:@escaping (AVPlayerItem)->(),failedClouse:@escaping ()->(),progressClouse:@escaping (Double)->()) { if asset.mediaType == .video { let manager = PHImageManager.default() let videoRequestOptions = PHVideoRequestOptions() videoRequestOptions.deliveryMode = .automatic videoRequestOptions.version = .current videoRequestOptions.isNetworkAccessAllowed = true videoRequestOptions.progressHandler = { (progress, error, stop, info) in DispatchQueue.main.async(execute: { if (error != nil) { failedClouse() } else { progressClouse(progress) } }) } manager.requestPlayerItem(forVideo: asset, options: videoRequestOptions) { (playItem, info) in DispatchQueue.main.async(execute: { if playItem != nil { successClouse(playItem!) } }) } } } // 获取原图的方法 同步 @objc static func getAssetOrigin(asset:PHAsset,dealImageSuccess:@escaping (UIImage?,[AnyHashable:Any]?) -> (),dealImageFailed:@escaping () -> ()) -> Void { //获取原图 let manager = PHImageManager.default() let option = PHImageRequestOptions() //可以设置图像的质量、版本、也会有参数控制图像的裁剪 option.isNetworkAccessAllowed = true // iCloud上的照片需要下载 option.resizeMode = .fast option.isSynchronous = true option.progressHandler = { (progress, error, stop, info) in DispatchQueue.main.async(execute: { print(progress, "异步获取icloud中的照片文件",error ?? "error") if (error != nil) { dealImageFailed() } }) } manager.requestImage(for: asset, targetSize:PHImageManagerMaximumSize, contentMode: .aspectFit, options: option) { (originImage, info) in dealImageSuccess(originImage,info) } } // 获取缩略图的方法 异步 @objc static func getAssetThumbnail(targetSize:CGSize,asset:PHAsset,dealImageSuccess:@escaping (UIImage?,[AnyHashable:Any]?) -> ()) -> Void { let imageSize: CGSize? if targetSize.width < KScreenWidth && targetSize.width < 600 { imageSize = CGSize(width: targetSize.width*UIScreen.main.scale, height: targetSize.height*UIScreen.main.scale) } else { let aspectRatio = CGFloat(asset.pixelWidth) / CGFloat(asset.pixelHeight) var pixelWidth = targetSize.width * UIScreen.main.scale * 1.5; // 超宽图片 if (aspectRatio > 1.8) { pixelWidth = pixelWidth * aspectRatio } // 超高图片 if (aspectRatio < 0.2) { pixelWidth = pixelWidth * 0.5 } let pixelHeight = pixelWidth / aspectRatio imageSize = CGSize(width:pixelWidth, height:pixelHeight) } //获取缩略图 let manager = PHImageManager.default() let option = PHImageRequestOptions() //可以设置图像的质量、版本、也会有参数控制图像的裁剪 option.resizeMode = .fast option.isNetworkAccessAllowed = false manager.requestImage(for: asset, targetSize:imageSize!, contentMode: .aspectFill, options: option) { (thumbnailImage, info) in dealImageSuccess(thumbnailImage,info) } } public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { // Local variable inserted by Swift 4.2 migrator. let info = convertFromUIImagePickerControllerInfoKeyDictionary(info) PopViewUtil.share.showLoading() // 保存到相册 let type = info[convertFromUIImagePickerControllerInfoKey(UIImagePickerController.InfoKey.mediaType)] as? String if type == "public.image" { CLPickersTools.instence.authorizeSave { (state) in if state == .authorized { let photo = info[convertFromUIImagePickerControllerInfoKey(UIImagePickerController.InfoKey.originalImage)] UIImageWriteToSavedPhotosAlbum(photo as! UIImage, self, #selector(CLImagePickerTool.image(_:didFinishSavingWithError:contextInfo:)), nil) } else { DispatchQueue.main.async(execute: { PopViewUtil.alert(title: photoLimitStr, message: clickSetStr, leftTitle: cancelStr, rightTitle: setStr, leftHandler: { // 点击了取消 PopViewUtil.share.stopLoading() picker.dismiss(animated: true, completion: nil) }, rightHandler: { PopViewUtil.share.stopLoading() picker.dismiss(animated: true, completion: nil) let url = URL(string: UIApplication.openSettingsURLString) if let url = url, UIApplication.shared.canOpenURL(url) { if #available(iOS 10, *) { UIApplication.shared.open(url, options: convertToUIApplicationOpenExternalURLOptionsKeyDictionary([:]), completionHandler: { (success) in }) } else { UIApplication.shared.openURL(url) } } }) }) } } } } public func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { picker.dismiss(animated: true, completion: nil) } // 保存图片的结果 @objc func image(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo:UnsafeRawPointer) { if let err = error { PopViewUtil.share.stopLoading() UIAlertView(title: errorStr, message: err.localizedDescription, delegate: nil, cancelButtonTitle: sureStr).show() } else { let dataArr = CLPickersTools.instence.loadData() let newModel = dataArr.first?.values.first?.last guard let phasset = newModel?.phAsset else {return} if phasset.mediaType == .video { return } print("22222222222222") var cameroImage: UIImage? CLPickersTools.instence.getAssetOrigin(asset: phasset) { (img, info) in PopViewUtil.share.stopLoading() print("333333333333") if img != nil { cameroImage = img if self.singleImageChooseType == .singlePictureCrop && self.singleModelImageCanEditor != true { // 单选 self.crop(image: cameroImage!, phasset: phasset) print("裁剪") } else if self.singleImageChooseType != .singlePictureCrop && self.singleModelImageCanEditor == true { // 编辑 print("编辑") self.editor(image: cameroImage!, phasset: phasset) } else if self.singleImageChooseType == .singlePictureCrop && self.singleModelImageCanEditor == true { // 编辑并裁剪 print("编辑并裁剪") self.crop(image: cameroImage!, phasset: phasset) } else { print("其他") self.cameraPicker.dismiss(animated: true, completion: nil) if self.clPickerToolClouse != nil { self.clPickerToolClouse!([phasset],image) } } } else { // 说明本地没有需要到iCloud下载 } } } } // 相机-裁剪 func crop(image: UIImage,phasset: PHAsset) { let cutVC = CLCropViewController() if self.singlePictureCropScale != nil { cutVC.scale = (self.singlePictureCropScale)! } cutVC.originalImage = image cutVC.enterType = .camero cutVC.asset = phasset cutVC.clCropClouse = {[weak self] (cutImg) in if self?.clPickerToolClouse != nil { self?.clPickerToolClouse!([phasset],cutImg) } self?.cameraPicker.dismiss(animated: true, completion: nil) } cutVC.cancelClouse = {[weak self]() in self?.cameraPicker.dismiss(animated: true, completion: nil) } self.cameraPicker.pushViewController(cutVC, animated: true) } // 相机-编辑 func editor(image: UIImage,phasset: PHAsset) { let editorVC = EditorViewController.init(nibName: "EditorViewController", bundle: BundleUtil.getCurrentBundle()) editorVC.editorImage = image editorVC.editorImageComplete = {[weak self](img) in self?.cameraPicker.dismiss(animated: true, completion: nil) if self?.clPickerToolClouse != nil { self?.clPickerToolClouse!([phasset],img) } } self.cameraPicker.pushViewController(editorVC, animated: true) } // 获取当前控制器 func getCurrentViewcontroller() -> UIViewController?{ let rootController = UIApplication.shared.keyWindow?.rootViewController if let tabController = rootController as? UITabBarController { if let navController = tabController.selectedViewController as? UINavigationController{ return navController.children.last }else{ return tabController } }else if let navController = rootController as? UINavigationController { return navController.children.last }else{ return rootController } } } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertFromUIImagePickerControllerInfoKeyDictionary(_ input: [UIImagePickerController.InfoKey: Any]) -> [String: Any] { return Dictionary(uniqueKeysWithValues: input.map {key, value in (key.rawValue, value)}) } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertFromUIImagePickerControllerInfoKey(_ input: UIImagePickerController.InfoKey) -> String { return input.rawValue } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertToUIApplicationOpenExternalURLOptionsKeyDictionary(_ input: [String: Any]) -> [UIApplication.OpenExternalURLOptionsKey: Any] { return Dictionary(uniqueKeysWithValues: input.map { key, value in (UIApplication.OpenExternalURLOptionsKey(rawValue: key), value)}) }
af1291e7b6e448115163345a75c962b5
42.642593
183
0.586201
false
false
false
false
hejunbinlan/Operations
refs/heads/development
Operations/Operations/GroupOperation.swift
mit
1
// // GroupOperation.swift // Operations // // Created by Daniel Thorpe on 18/07/2015. // Copyright © 2015 Daniel Thorpe. All rights reserved. // import Foundation /** An `Operation` subclass which enables the grouping of other operations. Use `GroupOperation`s to associate related operations together, thereby creating higher levels of abstractions. Additionally, `GroupOperation`s are useful as a way of creating Operations which may repeat themselves before subsequent operations can run. For example, authentication operations. */ public class GroupOperation: Operation { private let queue = OperationQueue() private let operations: [NSOperation] private let finishingOperation = NSBlockOperation(block: {}) private var aggregateErrors = Array<ErrorType>() /** Designated initializer. :park: operations, an array of `NSOperation`s. */ public init(operations ops: [NSOperation]) { operations = ops super.init() queue.suspended = true queue.delegate = self } public convenience init(operations: NSOperation...) { self.init(operations: operations) } /** Cancels all the groups operations. */ public override func cancel() { queue.cancelAllOperations() super.cancel() } public override func execute() { for operation in operations { queue.addOperation(operation) } queue.suspended = false queue.addOperation(finishingOperation) } /** Add an `NSOperation` to the group's queue. :param: operation, an `NSOperation` */ public func addOperation(operation: NSOperation) { queue.addOperation(operation) } public func addOperations(operations: [NSOperation]) { queue.addOperations(operations, waitUntilFinished: false) } final func aggregateError(error: ErrorType) { aggregateErrors.append(error) } /** This method is called every time one of the groups child operations finish. Over-ride this method to enable the following sort of behavior: ## Error handling. Typically you will want to have code like this: if !errors.isEmpty { if operation is MyOperation, let error = errors.first as? MyOperation.Error { switch error { case .AnError: println("Handle the error case") } } } So, if the errors array is not empty, it is important to know which kind of errors the operation may have encountered, and then implement handling of any that are necessary. Note that if an operation has conditions, which fail, they will be returned as the first errors. ## Move results between operations. Typically we use `GroupOperation` to compose and manage multiple operations into a single unit. This might often need to move the results of one operation into the next one. So this can be done here. :param: operation, an `NSOperation` :param:, errors, an array of `ErrorType`s. */ public func operationDidFinish(operation: NSOperation, withErrors errors: [ErrorType]) { // no-op, subclasses can override for their own functionality. } } extension GroupOperation: OperationQueueDelegate { public func operationQueue(queue: OperationQueue, willAddOperation operation: NSOperation) { assert(!finishingOperation.finished && !finishingOperation.executing, "Cannot add new operations to a group after the group has completed.") if operation !== finishingOperation { finishingOperation.addDependency(operation) } } public func operationQueue(queue: OperationQueue, operationDidFinish operation: NSOperation, withErrors errors: [ErrorType]) { aggregateErrors.appendContentsOf(errors) if operation === finishingOperation { queue.suspended = true finish(aggregateErrors) } else { operationDidFinish(operation, withErrors: errors) } } }
af9a0861ae10227ccf13647ff785212e
28.140845
148
0.666989
false
false
false
false
carabina/ActionSwift3
refs/heads/master
ActionSwift3/media/Sound.swift
mit
1
// // Sound.swift // ActionSwift // // Created by Craig on 6/08/2015. // Copyright (c) 2015 Interactive Coconut. All rights reserved. // import SpriteKit /** Be sure to store either the sound or soundChannel in an instance variable, as the sound will be "garbage collected" (or the Swift equivalent at least, *deinitialized* when there are no references to it) */ public class Sound: EventDispatcher { private var name:String private var soundChannel:SoundChannel = SoundChannel() public init(name:String) { self.name = name } public func load(name:String) { self.name = name } ///Returns a SoundChannel, which you can use to *stop* the Sound. public func play(startTime:Number = 0, loops:int = 0)->SoundChannel { soundChannel = SoundChannel() soundChannel.play(self.name,startTime:startTime, loops:loops) return soundChannel } }
5e007bad8e03f2030ef7a734941b2c47
27.9375
115
0.677106
false
false
false
false
zwaldowski/ParksAndRecreation
refs/heads/master
Swift-2/UI Geometry.playground/Sources/Scaling.swift
mit
1
import UIKit private func rroundBy<T: GeometricMeasure>(value: T, _ scale: T = T.identity, _ function: T -> T) -> T { return (scale > T.identity) ? (function(value * scale) / scale) : function(value) } public func rround(value: CGFloat, scale: CGFloat = CGFloat.identity) -> CGFloat { return rroundBy(value, scale, round) } public func rceil(value: CGFloat, scale: CGFloat = CGFloat.identity) -> CGFloat { return rroundBy(value, scale, ceil) } public func rfloor(value: CGFloat, scale: CGFloat = CGFloat.identity) -> CGFloat { return rroundBy(value, scale, floor) } func rceilSmart(value: CGFloat, scale: CGFloat = CGFloat.identity) -> CGFloat { return rroundBy(value, scale) { v in let vFloor = floor(v) if vFloor ~== v { return vFloor } return ceil(v) } } public extension UIView { func rround(value: CGFloat) -> CGFloat { return rroundBy(value, scale, round) } func rceil(value: CGFloat) -> CGFloat { return rroundBy(value, scale, ceil) } func rfloor(value: CGFloat) -> CGFloat { return rroundBy(value, scale, floor) } } public extension UIViewController { func rround(value: CGFloat) -> CGFloat { return rroundBy(value, view.scale, round) } func rceil(value: CGFloat) -> CGFloat { return rroundBy(value, view.scale, ceil) } func rfloor(value: CGFloat) -> CGFloat { return rroundBy(value, view.scale, floor) } } // MARK: Rotations public func toRadians<T: GeometricMeasure>(value: T) -> T { return (value * T(M_PI)) / T(180.0) } public func toDegrees<T: GeometricMeasure>(value: T) -> T { return ((value * T(180.0)) / T(M_PI)) }
11c53310b935c687f583a9961a2c0135
36.860465
121
0.66769
false
false
false
false
youngsoft/TangramKit
refs/heads/master
TangramKitDemo/FloatLayoutDemo/FOLTest2ViewController.swift
mit
1
// // FOLTest2ViewController.swift // TangramKit // // Created by apple on 16/5/8. // Copyright © 2016年 youngsoft. All rights reserved. // import UIKit //布局模型类,用于实现不同的布局展示风格 struct FOLTest2LayoutTemplate { var layoutSelector:Selector //布局实现的方法 var width:CGFloat //布局宽度,如果设置的值<=1则是相对宽度 var height:CGFloat //布局高度,如果设置的值<=1则是相对高度 } //数据模型。 @objcMembers class FOLTest2DataModel : NSObject { @objc var title:String! //标题 @objc var subTitle:String! //副标题 @objc var desc:String! //描述 @objc var price:String! //价格 @objc var image:String! //图片 @objc var subImage:String! //子图片 @objc var templateIndex = 0 //数据模型使用布局的索引。通常由服务端决定使用的布局模型,所以这里作为一个属性保存在模型数据结构中。 } //数据片段模型 @objcMembers class FOLTest2SectionModel:NSObject { var title:String! var datas:[FOLTest2DataModel]! } /** *2.FloatLayout - Jagged */ class FOLTest2ViewController: UIViewController { weak var rootLayout:TGLinearLayout! static var sItemLayoutHeight = 90.0 static var sBaseTag = 100000 lazy var layoutTemplates:[FOLTest2LayoutTemplate]={ //所有的布局模板数组 let templateSources:[[String:Any]] = [ [ "selector":#selector(createItemLayout1_1), "width":CGFloat(0.5), "height":CGFloat(FOLTest2ViewController.sItemLayoutHeight*2) ], [ "selector":#selector(createItemLayout1_2), "width":CGFloat(0.5), "height":CGFloat(FOLTest2ViewController.sItemLayoutHeight), ], [ "selector":#selector(createItemLayout1_3), "width":CGFloat(0.5), "height":CGFloat(FOLTest2ViewController.sItemLayoutHeight), ], [ "selector":#selector(createItemLayout2_1), "width":CGFloat(0.5), "height":CGFloat(FOLTest2ViewController.sItemLayoutHeight * 2), ], [ "selector":#selector(createItemLayout2_1), "width":CGFloat(0.25), "height":CGFloat(FOLTest2ViewController.sItemLayoutHeight * 2), ], [ "selector":#selector(createItemLayout2_1), "width":CGFloat(1.0), "height":CGFloat(FOLTest2ViewController.sItemLayoutHeight), ], [ "selector":#selector(createItemLayout3_1), "width":CGFloat(0.4), "height":CGFloat(FOLTest2ViewController.sItemLayoutHeight * 2), ], [ "selector":#selector(createItemLayout3_2), "width":CGFloat(0.6), "height":CGFloat(FOLTest2ViewController.sItemLayoutHeight), ], [ "selector":#selector(createItemLayout3_2), "width":CGFloat(0.4), "height":CGFloat(FOLTest2ViewController.sItemLayoutHeight), ], [ "selector":#selector(createItemLayout4_1), "width":CGFloat(0.5), "height":CGFloat(FOLTest2ViewController.sItemLayoutHeight), ], [ "selector":#selector(createItemLayout4_2), "width":CGFloat(0.25), "height":CGFloat(FOLTest2ViewController.sItemLayoutHeight + 20), ], [ "selector":#selector(createItemLayout5_1), "width":CGFloat(0.25), "height":CGFloat(FOLTest2ViewController.sItemLayoutHeight + 20), ] ] var _layoutTemplates = [FOLTest2LayoutTemplate]() for dict in templateSources { let template = FOLTest2LayoutTemplate(layoutSelector:dict["selector"] as! Selector, width:CGFloat(dict["width"] as! CGFloat), height:dict["height"] as! CGFloat) _layoutTemplates.append(template) } return _layoutTemplates; }() lazy var sectionDatas:[FOLTest2SectionModel] = { //片段数据数组,FOLTest2SectionModel类型的元素。 let file:String! = Bundle.main.path(forResource: "FOLTest2DataModel",ofType:"plist") let dataSources = NSArray(contentsOfFile: file) as! [[String:AnyObject]] var _sectionDatas = [FOLTest2SectionModel]() for sectionDict:[String:AnyObject] in dataSources { let sectionModel = FOLTest2SectionModel() sectionModel.title = sectionDict["title"] as? String sectionModel.datas = [FOLTest2DataModel]() let dicts = sectionDict["datas"] as! [[String:AnyObject]] for dict in dicts { let model = FOLTest2DataModel() for (key,val) in dict { model.setValue(val, forKey:key) } sectionModel.datas.append(model); } _sectionDatas.append(sectionModel) } return _sectionDatas }() override func loadView() { let scrollView = UIScrollView() self.view = scrollView; let rootLayout = TGLinearLayout(.vert) rootLayout.tg_width.equal(.fill) rootLayout.tg_height.equal(.wrap) rootLayout.tg_gravity = TGGravity.horz.fill rootLayout.backgroundColor = UIColor(white:0xe7/255.0, alpha:1) rootLayout.tg_intelligentBorderline = TGBorderline(color: .lightGray) //设置智能边界线,布局里面的子视图会根据布局自动产生边界线。 scrollView.addSubview(rootLayout) self.rootLayout = rootLayout } override func viewDidLoad() { super.viewDidLoad() for i in 0 ..< self.sectionDatas.count { self.addSectionLayout(sectionIndex: i) } // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } //MARK: Layout Construction extension FOLTest2ViewController { //添加片段布局 func addSectionLayout(sectionIndex:Int) { let sectionModel = self.sectionDatas[sectionIndex] //如果有标题则创建标题文本 if sectionModel.title != nil { let sectionTitleLabel = UILabel() sectionTitleLabel.text = sectionModel.title; sectionTitleLabel.font = .boldSystemFont(ofSize: 15) sectionTitleLabel.backgroundColor = .white sectionTitleLabel.tg_height.equal(30) sectionTitleLabel.tg_top.equal(10) self.rootLayout.addSubview(sectionTitleLabel) } //创建条目容器布局。 let itemContainerLayout = TGFloatLayout(.vert) itemContainerLayout.backgroundColor = .white itemContainerLayout.tg_height.equal(.wrap) itemContainerLayout.tg_intelligentBorderline = TGBorderline(color: .lightGray) self.rootLayout.addSubview(itemContainerLayout) //创建条目布局,并加入到容器布局中去。 for i in 0 ..< sectionModel.datas.count { let model = sectionModel.datas[i]; let layoutTemplate = self.layoutTemplates[model.templateIndex]; //取出数据模型对应的布局模板对象。 //布局模型对象的layoutSelector负责建立布局,并返回一个布局条目布局视图。 let itemLayout = self.perform(layoutTemplate.layoutSelector,with:model).takeUnretainedValue() as! TGBaseLayout itemLayout.tag = sectionIndex * FOLTest2ViewController.sBaseTag + i; itemLayout.tg_setTarget(self,action:#selector(handleItemLayoutTap), for:.touchUpInside) itemLayout.tg_highlightedOpacity = 0.4 //根据上面布局模型对高度和宽度的定义指定条目布局的尺寸。如果小于等于1则用相对尺寸,否则用绝对尺寸。 if layoutTemplate.width <= 1 { itemLayout.tg_width.equal(itemContainerLayout.tg_width, multiple:layoutTemplate.width) } else { itemLayout.tg_width.equal(layoutTemplate.width) } if layoutTemplate.height <= 1 { itemLayout.tg_height.equal(itemContainerLayout.tg_height, multiple:layoutTemplate.height) } else { itemLayout.tg_height.equal(layoutTemplate.height) } itemContainerLayout.addSubview(itemLayout) } } //品牌特卖主条目布局,这是一个从上到下的布局,因此可以用上下浮动来实现。 @objc func createItemLayout1_1(_ dataModel:FOLTest2DataModel) ->TGFloatLayout { /* 这个例子是为了重点演示浮动布局,所以里面的所有条目布局都用了浮动布局。您也可以使用其他布局来建立您的条目布局。 */ //建立上下浮动布局 let itemLayout = TGFloatLayout(.horz) //向上浮动,左边顶部边距为5 let titleLabel = UILabel() titleLabel.text = dataModel.title; titleLabel.font = .boldSystemFont(ofSize: 15) titleLabel.tg_leading.equal(5) titleLabel.tg_top.equal(5) titleLabel.sizeToFit() itemLayout.addSubview(titleLabel) //向上浮动,左边顶部边距为5,高度为20 let subImageView = UIImageView(image:UIImage(named:dataModel.subImage)) subImageView.tg_leading.equal(5) subImageView.tg_top.equal(5) subImageView.tg_height.equal(20) subImageView.sizeToFit() itemLayout.addSubview(subImageView) //向上浮动,高度占用剩余的高度,宽度和父布局保持一致。 let imageView = UIImageView(image:UIImage(named:dataModel.image)) imageView.tg_height.equal(.fill) imageView.tg_width.equal(itemLayout.tg_width) itemLayout.addSubview(imageView) return itemLayout; } //天猫超时条目布局,这是一个整体左右结构,因此用左右浮动布局来实现。 @objc func createItemLayout1_2(_ dataModel:FOLTest2DataModel) ->TGFloatLayout { //建立左右浮动布局 let itemLayout = TGFloatLayout(.vert) //向左浮动,宽度和父视图宽度保持一致,顶部和左边距为5 let titleLabel = UILabel() titleLabel.text = dataModel.title; titleLabel.font = UIFont.boldSystemFont(ofSize: 15) titleLabel.tg_width.equal(itemLayout.tg_width) titleLabel.tg_leading.equal(5) titleLabel.tg_top.equal(5) titleLabel.sizeToFit() itemLayout.addSubview(titleLabel) //向左浮动,因为上面占据了全部宽度,这里会自动换行显示并且也是全宽。 let subTitleLabel = UILabel() subTitleLabel.text = dataModel.subTitle; subTitleLabel.font = UIFont.systemFont(ofSize: 12) subTitleLabel.textColor = .lightGray subTitleLabel.tg_width.equal(itemLayout.tg_width) subTitleLabel.tg_leading.equal(5) subTitleLabel.sizeToFit() itemLayout.addSubview(subTitleLabel) //图片向右浮动,并且右边距为5,上面因为占据了全宽,因此这里会另起一行向右浮动。 let imageView = UIImageView(image:UIImage(named:dataModel.image)) imageView.tg_reverseFloat = true imageView.tg_trailing.equal(5) imageView.sizeToFit() itemLayout.addSubview(imageView) return itemLayout; } //建立品牌特卖的其他条目布局,这种布局整体是左右结构,因此建立左右浮动布局。 @objc func createItemLayout1_3(_ dataModel:FOLTest2DataModel) ->TGFloatLayout { let itemLayout = TGFloatLayout(.vert) //因为图片要占据全高,所以必须优先向右浮动。 let imageView = UIImageView(image:UIImage(named:dataModel.image)) imageView.tg_height.equal(itemLayout.tg_height) imageView.tg_reverseFloat = true; imageView.sizeToFit() itemLayout.addSubview(imageView) //向左浮动,并占据剩余的宽度,边距为5 let titleLabel = UILabel() titleLabel.text = dataModel.title; titleLabel.font = UIFont.boldSystemFont(ofSize: 15) titleLabel.tg_leading.equal(5) titleLabel.tg_top.equal(5) titleLabel.tg_width.equal(.fill) titleLabel.sizeToFit() itemLayout.addSubview(titleLabel) //向左浮动,直接另起一行,占据剩余宽度,内容高度动态。 let subTitleLabel = UILabel() subTitleLabel.text = dataModel.subTitle; subTitleLabel.font = UIFont.systemFont(ofSize: 12) subTitleLabel.textColor = UIColor.lightGray; subTitleLabel.tg_leading.equal(5) subTitleLabel.tg_clearFloat = true; subTitleLabel.tg_width.equal(.fill) subTitleLabel.tg_height.equal(.wrap) itemLayout.addSubview(subTitleLabel) //如果有小图片则图片另起一行,向左浮动。 if (dataModel.subImage != nil) { let subImageView = UIImageView(image:UIImage(named:dataModel.subImage)) subImageView.tg_clearFloat = true; subImageView.tg_leading.equal(5) subImageView.sizeToFit() itemLayout.addSubview(subImageView) } return itemLayout; } //建立超级品牌日布局,这里因为就只有一张图,所以设置布局的背景图片即可。 @objc func createItemLayout2_1(_ dataModel:FOLTest2DataModel) ->TGFloatLayout { let itemLayout = TGFloatLayout(.vert) //直接设置背景图片。 itemLayout.tg_backgroundImage = UIImage(named:dataModel.image) return itemLayout; } //精选市场主条目布局,这个布局整体从上到下因此用上下浮动布局建立。 @objc func createItemLayout3_1(_ dataModel:FOLTest2DataModel) ->TGFloatLayout { let itemLayout = TGFloatLayout(.horz) //向上浮动 let titleLabel = UILabel() titleLabel.text = dataModel.title; titleLabel.font = UIFont.boldSystemFont(ofSize: 15) titleLabel.tg_leading.equal(5) titleLabel.tg_top.equal(5) titleLabel.sizeToFit() itemLayout.addSubview(titleLabel) //继续向上浮动。 let subTitleLabel = UILabel() subTitleLabel.text = dataModel.title; subTitleLabel.font = UIFont.systemFont(ofSize: 11) subTitleLabel.tg_leading.equal(5) subTitleLabel.tg_top.equal(5) subTitleLabel.sizeToFit() itemLayout.addSubview(subTitleLabel) //价格部分在底部,因此改为向下浮动。 let priceLabel = UILabel() priceLabel.text = dataModel.price; priceLabel.font = UIFont.systemFont(ofSize: 11) priceLabel.textColor = UIColor.red priceLabel.tg_leading.equal(5) priceLabel.tg_bottom.equal(5) priceLabel.tg_reverseFloat = true priceLabel.sizeToFit() itemLayout.addSubview(priceLabel) //描述部分在价格的上面,因此改为向下浮动。 let descLabel = UILabel() descLabel.text = dataModel.desc; descLabel.font = UIFont.systemFont(ofSize: 11) descLabel.textColor = UIColor.lightGray descLabel.tg_leading.equal(5) descLabel.tg_reverseFloat = true descLabel.sizeToFit() itemLayout.addSubview(descLabel) //向上浮动,并占用剩余的空间高度。 let imageView = UIImageView(image:UIImage(named:dataModel.image)) imageView.tg_width.equal(itemLayout.tg_width); imageView.tg_height.equal(100%) itemLayout.addSubview(imageView) return itemLayout; } //建立精选市场其他条目布局,这个布局整体还是从上到下,因此用上下浮动布局 @objc func createItemLayout3_2(_ dataModel:FOLTest2DataModel) ->TGFloatLayout { let itemLayout = TGFloatLayout(.horz) //向上浮动 let titleLabel = UILabel() titleLabel.text = dataModel.title; titleLabel.font = UIFont.boldSystemFont(ofSize: 15) titleLabel.tg_leading.equal(5) titleLabel.tg_top.equal(5) titleLabel.tg_width.equal(itemLayout.tg_width,increment:-2.5, multiple:0.5) titleLabel.sizeToFit() itemLayout.addSubview(titleLabel) //继续向上浮动 let subTitleLabel = UILabel() subTitleLabel.text = dataModel.subTitle; subTitleLabel.font = UIFont.systemFont(ofSize: 11) subTitleLabel.tg_leading.equal(5) subTitleLabel.tg_top.equal(5) subTitleLabel.tg_width.equal(itemLayout.tg_width,increment:-2.5,multiple:0.5) subTitleLabel.sizeToFit() itemLayout.addSubview(subTitleLabel) //价格向下浮动 let priceLabel = UILabel() priceLabel.text = dataModel.price; priceLabel.font = UIFont.systemFont(ofSize: 11) priceLabel.textColor = UIColor.red priceLabel.tg_leading.equal(5) priceLabel.tg_bottom.equal(5) priceLabel.tg_reverseFloat = true priceLabel.tg_width.equal(itemLayout.tg_width,increment:-2.5,multiple:0.5) priceLabel.sizeToFit() itemLayout.addSubview(priceLabel) //描述向下浮动 let descLabel = UILabel() descLabel.text = dataModel.desc; descLabel.font = UIFont.systemFont(ofSize: 11) descLabel.textColor = UIColor.lightGray descLabel.tg_leading.equal(5) descLabel.tg_reverseFloat = true descLabel.tg_width.equal(itemLayout.tg_width,increment:-2.5,multiple:0.5) descLabel.sizeToFit() itemLayout.addSubview(descLabel) //向上浮动,因为宽度无法再容纳,所以这里会换列继续向上浮动。 let imageView = UIImageView(image:UIImage(named:dataModel.image)) imageView.tg_width.equal(itemLayout.tg_width,increment:-2.5,multiple:0.5) imageView.tg_height.equal(itemLayout.tg_height); itemLayout.addSubview(imageView) return itemLayout; } //热门市场主条目布局,这个结构可以用上下浮动布局也可以用左右浮动布局。 @objc func createItemLayout4_1(_ dataModel:FOLTest2DataModel) ->TGFloatLayout { let itemLayout = TGFloatLayout(.horz) let titleLabel = UILabel() titleLabel.text = dataModel.title; titleLabel.font = UIFont.boldSystemFont(ofSize: 15) titleLabel.tg_leading.equal(5) titleLabel.tg_top.equal(5) titleLabel.tg_width.equal(itemLayout.tg_width,increment:-2.5,multiple:0.5) titleLabel.sizeToFit() itemLayout.addSubview(titleLabel) let subTitleLabel = UILabel() subTitleLabel.text = dataModel.subTitle; subTitleLabel.font = UIFont.systemFont(ofSize: 11) subTitleLabel.tg_leading.equal(5) subTitleLabel.tg_top.equal(5) subTitleLabel.tg_width.equal(itemLayout.tg_width,increment:-2.5,multiple:0.5) subTitleLabel.sizeToFit() itemLayout.addSubview(subTitleLabel) //继续向上浮动,这里因为高度和父布局高度一致,因此会换列浮动。 let imageView = UIImageView(image:UIImage(named:dataModel.image)) imageView.tg_width.equal(itemLayout.tg_width,increment:-2.5,multiple:0.5) imageView.tg_height.equal(itemLayout.tg_height); itemLayout.addSubview(imageView) return itemLayout; } //热门市场其他条目布局,这个整体是上下布局,因此用上下浮动布局。 @objc func createItemLayout4_2(_ dataModel:FOLTest2DataModel) ->TGFloatLayout { let itemLayout = TGFloatLayout(.horz) let titleLabel = UILabel() titleLabel.text = dataModel.title; titleLabel.font = UIFont.boldSystemFont(ofSize: 15) titleLabel.tg_leading.equal(5) titleLabel.tg_top.equal(5) titleLabel.sizeToFit() itemLayout.addSubview(titleLabel) let subTitleLabel = UILabel() subTitleLabel.text = dataModel.subTitle; subTitleLabel.font = UIFont.systemFont(ofSize: 11) subTitleLabel.tg_leading.equal(5) subTitleLabel.tg_top.equal(5) subTitleLabel.sizeToFit() itemLayout.addSubview(subTitleLabel) //继续向上浮动,占据剩余高度。 let imageView = UIImageView(image:UIImage(named:dataModel.image)) imageView.tg_width.equal(itemLayout.tg_width) imageView.tg_height.equal(100%) itemLayout.addSubview(imageView) return itemLayout; } //主题市场条目布局,这个整体就是上下浮动布局 @objc func createItemLayout5_1(_ dataModel:FOLTest2DataModel) ->TGFloatLayout { let itemLayout = TGFloatLayout(.horz) let titleLabel = UILabel() titleLabel.text = dataModel.title; titleLabel.font = UIFont.boldSystemFont(ofSize: 15) titleLabel.tg_leading.equal(5) titleLabel.tg_top.equal(5) titleLabel.sizeToFit() itemLayout.addSubview(titleLabel) let subTitleLabel = UILabel() subTitleLabel.text = dataModel.subTitle; subTitleLabel.font = UIFont.systemFont(ofSize: 11) subTitleLabel.textColor = UIColor.red subTitleLabel.tg_leading.equal(5) subTitleLabel.tg_top.equal(5) subTitleLabel.sizeToFit() itemLayout.addSubview(subTitleLabel) let imageView = UIImageView(image:UIImage(named:dataModel.image)) imageView.tg_width.equal(itemLayout.tg_width) imageView.tg_height.equal(100%) //图片占用剩余的全部高度 itemLayout.addSubview(imageView) return itemLayout; } } //MARK: Handle Method extension FOLTest2ViewController { @objc func handleItemLayoutTap(sender:UIView!) { let sectionIndex = sender.tag / FOLTest2ViewController.sBaseTag; let itemIndex = sender.tag % FOLTest2ViewController.sBaseTag; let message = "You have select\nSectionIndex:\(sectionIndex) ItemIndex:\(itemIndex)" UIAlertView(title: nil, message: message, delegate: nil, cancelButtonTitle: "OK").show() } }
9620365615240204489c08212851205f
33.130568
122
0.599307
false
true
false
false
ngageoint/mage-ios
refs/heads/master
MageTests/Categories/LocationUtilitiesTests.swift
apache-2.0
1
// // CoordinateDisplayTests.swift // MAGETests // // Created by Daniel Barela on 1/7/22. // Copyright © 2022 National Geospatial Intelligence Agency. All rights reserved. // import Foundation import Quick import Nimble import CoreLocation @testable import MAGE class LocationUtilitiesTests: QuickSpec { override func spec() { describe("LocationUtilitiesTests Tests") { it("should display the coordinate") { UserDefaults.standard.locationDisplay = .latlng expect(CLLocationCoordinate2D(latitude: 15.48, longitude: 20.47).toDisplay()).to(equal("15.48000, 20.47000")) UserDefaults.standard.locationDisplay = .mgrs expect(CLLocationCoordinate2D(latitude: 15.48, longitude: 20.47).toDisplay()).to(equal("34PDC4314911487")) UserDefaults.standard.locationDisplay = .dms expect(CLLocationCoordinate2D(latitude: 15.48, longitude: 20.47).toDisplay()).to(equal("15° 28' 48\" N, 20° 28' 12\" E")) expect(CLLocationCoordinate2D(latitude: 15.48, longitude: 20.47).toDisplay(short: true)).to(equal("15° 28' 48\" N, 20° 28' 12\" E")) UserDefaults.standard.locationDisplay = .dms expect(LocationUtilities.latitudeDMSString(coordinate:11.186388888888889)).to(equal("11° 11' 11\" N")) expect(CLLocationCoordinate2D.parse(coordinates:"111111N, 121212E").toDisplay()).to(equal("11° 11' 11\" N, 12° 12' 12\" E")) expect(LocationUtilities.latitudeDMSString(coordinate:0.186388888888889)).to(equal("0° 11' 11\" N")) expect(CLLocationCoordinate2D.parse(coordinates:"01111N, 01212E").toDisplay()).to(equal("0° 11' 11\" N, 0° 12' 12\" E")) } it("should split the coordinate string") { expect(CLLocationCoordinate2D.splitCoordinates(coordinates: nil)).to(equal([])) var coordinates = "112233N 0152144W" expect(CLLocationCoordinate2D.splitCoordinates(coordinates: coordinates)).to(equal(["112233N","0152144W"])) coordinates = "N 11 ° 22'33 \"- W 15 ° 21'44" expect(CLLocationCoordinate2D.splitCoordinates(coordinates: coordinates)).to(equal(["N11°22'33\"","W15°21'44"])) coordinates = "N 11 ° 22'30 \"" expect(CLLocationCoordinate2D.splitCoordinates(coordinates: coordinates)).to(equal(["N11°22'30\""])) coordinates = "11 ° 22'33 \"N - 15 ° 21'44\" W" expect(CLLocationCoordinate2D.splitCoordinates(coordinates: coordinates)).to(equal(["11°22'33\"N","15°21'44\"W"])) coordinates = "11° 22'33 N 015° 21'44 W" expect(CLLocationCoordinate2D.splitCoordinates(coordinates: coordinates)).to(equal(["11°22'33N","015°21'44W"])) coordinates = "11.4584 15.6827" expect(CLLocationCoordinate2D.splitCoordinates(coordinates: coordinates)).to(equal(["11.4584","15.6827"])) coordinates = "-11.4584 15.6827" expect(CLLocationCoordinate2D.splitCoordinates(coordinates: coordinates)).to(equal(["-11.4584","15.6827"])) coordinates = "11.4584 -15.6827" expect(CLLocationCoordinate2D.splitCoordinates(coordinates: coordinates)).to(equal(["11.4584","-15.6827"])) coordinates = "11.4584, 15.6827" expect(CLLocationCoordinate2D.splitCoordinates(coordinates: coordinates)).to(equal(["11.4584","15.6827"])) coordinates = "-11.4584, 15.6827" expect(CLLocationCoordinate2D.splitCoordinates(coordinates: coordinates)).to(equal(["-11.4584","15.6827"])) coordinates = "11.4584, -15.6827" expect(CLLocationCoordinate2D.splitCoordinates(coordinates: coordinates)).to(equal(["11.4584","-15.6827"])) } it("should parse the coordinate string") { expect(CLLocationCoordinate2D.parse(coordinate:nil)).to(beNil()) var coordinates = "112230N" expect(CLLocationCoordinate2D.parse(coordinate: coordinates)).to(equal(11.375)) coordinates = "112230" expect(CLLocationCoordinate2D.parse(coordinate: coordinates)).to(equal(11.375)) coordinates = "purple" expect(CLLocationCoordinate2D.parse(coordinate: coordinates)).to(beNil()) coordinates = "N 11 ° 22'30 \"" expect(CLLocationCoordinate2D.parse(coordinate: coordinates)).to(equal(CLLocationDegrees(11.375))) coordinates = "N 11 ° 22'30.36 \"" expect(CLLocationCoordinate2D.parse(coordinate: coordinates)).to(equal(CLLocationDegrees(11.375))) coordinates = "N 11 ° 22'30.remove \"" expect(CLLocationCoordinate2D.parse(coordinate: coordinates)).to(equal(CLLocationDegrees(11.375))) coordinates = "11 ° 22'30 \"N" expect(CLLocationCoordinate2D.parse(coordinate: coordinates)).to(equal(CLLocationDegrees(11.375))) coordinates = "11° 22'30 N" expect(CLLocationCoordinate2D.parse(coordinate: coordinates)).to(equal(CLLocationDegrees(11.375))) coordinates = "11.4584" expect(CLLocationCoordinate2D.parse(coordinate: coordinates)).to(equal(CLLocationDegrees(11.4584))) coordinates = "-11.4584" expect(CLLocationCoordinate2D.parse(coordinate: coordinates)).to(equal(CLLocationDegrees(-11.4584))) coordinates = "0151545W" expect(CLLocationCoordinate2D.parse(coordinate: coordinates)).to(equal(CLLocationDegrees(-15.2625))) coordinates = "W 15 ° 15'45" expect(CLLocationCoordinate2D.parse(coordinate: coordinates)).to(equal(CLLocationDegrees(-15.2625))) coordinates = "15 ° 15'45\" W" expect(CLLocationCoordinate2D.parse(coordinate: coordinates)).to(equal(CLLocationDegrees(-15.2625))) coordinates = "015° 15'45 W" expect(CLLocationCoordinate2D.parse(coordinate: coordinates)).to(equal(CLLocationDegrees(-15.2625))) coordinates = "15.6827" expect(CLLocationCoordinate2D.parse(coordinate: coordinates)).to(equal(CLLocationDegrees(15.6827))) coordinates = "-15.6827" expect(CLLocationCoordinate2D.parse(coordinate: coordinates)).to(equal(CLLocationDegrees(-15.6827))) coordinates = "0.186388888888889" expect(CLLocationCoordinate2D.parse(coordinate: coordinates)).to(equal(CLLocationDegrees(0.186388888888889))) coordinates = "0° 11' 11\" N" expect(CLLocationCoordinate2D.parse(coordinate: coordinates)).to(beCloseTo(CLLocationDegrees(0.186388888888889))) coordinates = "705600N" expect(CLLocationCoordinate2D.parse(coordinate: coordinates)).to(beCloseTo(CLLocationDegrees(70.9333))) } it("should parse the coordinate string to a DMS string") { expect(LocationUtilities.parseToDMSString(nil)).to(beNil()) var coordinates = "112230N" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("11° 22' 30\" N")) coordinates = "112230" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("11° 22' 30\" ")) coordinates = "30N" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("30° N")) coordinates = "3030N" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("30° 30' N")) coordinates = "purple" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("E")) coordinates = "" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("")) coordinates = "N 11 ° 22'30 \"" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("11° 22' 30\" N")) coordinates = "N 11 ° 22'30.36 \"" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("11° 22' 30\" N")) coordinates = "112233.99N" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("11° 22' 34\" N")) coordinates = "11.999999N" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("12° 00' 00\" N")) coordinates = "N 11 ° 22'30.remove \"" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("11° 22' 30\" N")) coordinates = "11 ° 22'30 \"N" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("11° 22' 30\" N")) coordinates = "11° 22'30 N" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("11° 22' 30\" N")) coordinates = "11" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("11° ")) coordinates = "11.4584" expect(LocationUtilities.parseToDMSString(coordinates, addDirection: true, latitude: true)).to(equal("11° 27' 30\" N")) coordinates = "-11.4584" expect(LocationUtilities.parseToDMSString(coordinates, addDirection: true, latitude: true)).to(equal("11° 27' 30\" S")) coordinates = "11.4584" expect(LocationUtilities.parseToDMSString(coordinates, addDirection: true)).to(equal("11° 27' 30\" E")) coordinates = "-11.4584" expect(LocationUtilities.parseToDMSString(coordinates, addDirection: true)).to(equal("11° 27' 30\" W")) coordinates = "11.4584" expect(LocationUtilities.parseToDMSString(coordinates, addDirection: true, latitude: true)).to(equal("11° 27' 30\" N")) coordinates = "-11.4584" expect(LocationUtilities.parseToDMSString(coordinates, addDirection: true, latitude: true)).to(equal("11° 27' 30\" S")) coordinates = "0151545W" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("015° 15' 45\" W")) coordinates = "113000W" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("11° 30' 00\" W")) coordinates = "W 15 ° 15'45" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("15° 15' 45\" W")) coordinates = "15 ° 15'45\" W" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("15° 15' 45\" W")) coordinates = "015° 15'45 W" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("015° 15' 45\" W")) coordinates = "15.6827" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("15° 40' 58\" ")) coordinates = "-15.6827" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("15° 40' 58\" ")) coordinates = "15.6827" expect(LocationUtilities.parseToDMSString(coordinates, addDirection: true)).to(equal("15° 40' 58\" E")) coordinates = "-15.6827" expect(LocationUtilities.parseToDMSString(coordinates, addDirection: true)).to(equal("15° 40' 58\" W")) coordinates = "113000NNNN" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("11° 30' 00\" N")) coordinates = "0.186388888888889" expect(LocationUtilities.parseToDMSString(coordinates, addDirection: true)).to(equal("0° 11' 11\" E")) coordinates = "0° 11' 11\" N" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("0° 11' 11\" N")) coordinates = "705600N" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("70° 56' 00\" N")) coordinates = "70° 560'" expect(LocationUtilities.parseToDMSString(coordinates)).to(equal("7° 05' 60\" ")) } it("should parse to DMS") { let coordinate = "113000NNNN" let parsed = LocationUtilities.parseDMS(coordinate: coordinate) expect(parsed.direction).to(equal("N")) expect(parsed.seconds).to(equal(0)) expect(parsed.minutes).to(equal(30)) expect(parsed.degrees).to(equal(11)) } it("should parse to DMS 2") { let coordinate = "70560" let parsed = LocationUtilities.parseDMS(coordinate: coordinate) expect(parsed.direction).to(beNil()) expect(parsed.seconds).to(equal(60)) expect(parsed.minutes).to(equal(5)) expect(parsed.degrees).to(equal(7)) } it("should split the coordinate string") { var coordinates = "112230N 0151545W" var parsed = CLLocationCoordinate2D.parse(coordinates: coordinates) expect(parsed.latitude).to(equal(11.375)) expect(parsed.longitude).to(equal(-15.2625)) coordinates = "N 11 ° 22'30 \"- W 15 ° 15'45" parsed = CLLocationCoordinate2D.parse(coordinates: coordinates) expect(parsed.latitude).to(equal(11.375)) expect(parsed.longitude).to(equal(-15.2625)) coordinates = "11 ° 22'30 \"N - 15 ° 15'45\" W" parsed = CLLocationCoordinate2D.parse(coordinates: coordinates) expect(parsed.latitude).to(equal(11.375)) expect(parsed.longitude).to(equal(-15.2625)) coordinates = "11° 22'30 N 015° 15'45 W" parsed = CLLocationCoordinate2D.parse(coordinates: coordinates) expect(parsed.latitude).to(equal(11.375)) expect(parsed.longitude).to(equal(-15.2625)) coordinates = "N 11° 22'30 W 015° 15'45 " parsed = CLLocationCoordinate2D.parse(coordinates: coordinates) expect(parsed.latitude).to(equal(11.375)) expect(parsed.longitude).to(equal(-15.2625)) coordinates = "11.4584 15.6827" parsed = CLLocationCoordinate2D.parse(coordinates: coordinates) expect(parsed.latitude).to(equal(11.4584)) expect(parsed.longitude).to(equal(15.6827)) coordinates = "-11.4584 15.6827" parsed = CLLocationCoordinate2D.parse(coordinates: coordinates) expect(parsed.latitude).to(equal(-11.4584)) expect(parsed.longitude).to(equal(15.6827)) coordinates = "11.4584 -15.6827" parsed = CLLocationCoordinate2D.parse(coordinates: coordinates) expect(parsed.latitude).to(equal(11.4584)) expect(parsed.longitude).to(equal(-15.6827)) coordinates = "11.4584, 15.6827" parsed = CLLocationCoordinate2D.parse(coordinates: coordinates) expect(parsed.latitude).to(equal(11.4584)) expect(parsed.longitude).to(equal(15.6827)) coordinates = "-11.4584, 15.6827" parsed = CLLocationCoordinate2D.parse(coordinates: coordinates) expect(parsed.latitude).to(equal(-11.4584)) expect(parsed.longitude).to(equal(15.6827)) coordinates = "11.4584, -15.6827" parsed = CLLocationCoordinate2D.parse(coordinates: coordinates) expect(parsed.latitude).to(equal(11.4584)) expect(parsed.longitude).to(equal(-15.6827)) coordinates = "11.4584" parsed = CLLocationCoordinate2D.parse(coordinates: coordinates) expect(parsed.latitude.isNaN).to(beTrue()) expect(parsed.longitude).to(equal(11.4584)) coordinates = "11 ° 22'30 \"N" parsed = CLLocationCoordinate2D.parse(coordinates: coordinates) expect(parsed.latitude.isNaN).to(beTrue()) // TODO: is this wrong? shouldn't this be latitude? expect(parsed.longitude).to(equal(11.375)) // future test // coordinates = "11-22-30N 015-15-45W" // parsed = CLLocationCoordinate2D.parse(coordinates: coordinates) // expect(parsed.latitude.isNaN).to(beTrue()) // expect(parsed.latitude).to(equal(11.375)) // expect(parsed.longitude).to(equal(-15.2625)) } it("should validate DMS latitude input") { expect(LocationUtilities.validateLatitudeFromDMS(latitude: nil)).to(beFalse()) expect(LocationUtilities.validateLatitudeFromDMS(latitude: "NS1122N")).to(beFalse()) expect(LocationUtilities.validateLatitudeFromDMS(latitude: "002233.NS")).to(beFalse()) expect(LocationUtilities.validateLatitudeFromDMS(latitude: "ABCDEF.NS")).to(beFalse()) expect(LocationUtilities.validateLatitudeFromDMS(latitude: "11NSNS.1N")).to(beFalse()) expect(LocationUtilities.validateLatitudeFromDMS(latitude: "1111NS.1N")).to(beFalse()) expect(LocationUtilities.validateLatitudeFromDMS(latitude: "113000NNN")).to(beFalse()) var validString = "112233N" expect(LocationUtilities.validateLatitudeFromDMS(latitude: validString)).to(beTrue()) validString = "002233N" expect(LocationUtilities.validateLatitudeFromDMS(latitude: validString)).to(beTrue()) validString = "02233N" expect(LocationUtilities.validateLatitudeFromDMS(latitude: validString)).to(beTrue()) validString = "12233N" expect(LocationUtilities.validateLatitudeFromDMS(latitude: validString)).to(beTrue()) validString = "002233S" expect(LocationUtilities.validateLatitudeFromDMS(latitude: validString)).to(beTrue()) validString = "002233.2384S" expect(LocationUtilities.validateLatitudeFromDMS(latitude: validString)).to(beTrue()) validString = "1800000E" expect(LocationUtilities.validateLongitudeFromDMS(longitude: validString)).to(beTrue()) validString = "1800000W" expect(LocationUtilities.validateLongitudeFromDMS(longitude: validString)).to(beTrue()) validString = "900000S" expect(LocationUtilities.validateLatitudeFromDMS(latitude: validString)).to(beTrue()) validString = "900000N" expect(LocationUtilities.validateLatitudeFromDMS(latitude: validString)).to(beTrue()) var invalidString = "2233N" expect(LocationUtilities.validateLatitudeFromDMS(latitude: invalidString)).to(beFalse()) invalidString = "33N" expect(LocationUtilities.validateLatitudeFromDMS(latitude: invalidString)).to(beFalse()) invalidString = "2N" expect(LocationUtilities.validateLatitudeFromDMS(latitude: invalidString)).to(beFalse()) invalidString = "233N" expect(LocationUtilities.validateLatitudeFromDMS(latitude: invalidString)).to(beFalse()) invalidString = "N" expect(LocationUtilities.validateLatitudeFromDMS(latitude: invalidString)).to(beFalse()) invalidString = ".123N" expect(LocationUtilities.validateLatitudeFromDMS(latitude: invalidString)).to(beFalse()) invalidString = "" expect(LocationUtilities.validateLatitudeFromDMS(latitude: invalidString)).to(beFalse()) invalidString = "2233W" expect(LocationUtilities.validateLongitudeFromDMS(longitude: invalidString)).to(beFalse()) invalidString = "33W" expect(LocationUtilities.validateLongitudeFromDMS(longitude: invalidString)).to(beFalse()) invalidString = "2W" expect(LocationUtilities.validateLongitudeFromDMS(longitude: invalidString)).to(beFalse()) invalidString = "233W" expect(LocationUtilities.validateLongitudeFromDMS(longitude: invalidString)).to(beFalse()) invalidString = "W" expect(LocationUtilities.validateLongitudeFromDMS(longitude: invalidString)).to(beFalse()) invalidString = ".123W" expect(LocationUtilities.validateLongitudeFromDMS(longitude: invalidString)).to(beFalse()) invalidString = "" expect(LocationUtilities.validateLongitudeFromDMS(longitude: invalidString)).to(beFalse()) invalidString = "112233" expect(LocationUtilities.validateLatitudeFromDMS(latitude: invalidString)).to(beFalse()) invalidString = "1a2233N" expect(LocationUtilities.validateLatitudeFromDMS(latitude: invalidString)).to(beFalse()) invalidString = "1a2233N" expect(LocationUtilities.validateLatitudeFromDMS(latitude: invalidString)).to(beFalse()) invalidString = "11a233N" expect(LocationUtilities.validateLatitudeFromDMS(latitude: invalidString)).to(beFalse()) invalidString = "1122a3N" expect(LocationUtilities.validateLatitudeFromDMS(latitude: invalidString)).to(beFalse()) invalidString = "912233N" expect(LocationUtilities.validateLatitudeFromDMS(latitude: invalidString)).to(beFalse()) invalidString = "-112233N" expect(LocationUtilities.validateLatitudeFromDMS(latitude: invalidString)).to(beFalse()) invalidString = "116033N" expect(LocationUtilities.validateLatitudeFromDMS(latitude: invalidString)).to(beFalse()) invalidString = "112260N" expect(LocationUtilities.validateLatitudeFromDMS(latitude: invalidString)).to(beFalse()) invalidString = "1812233W" expect(LocationUtilities.validateLongitudeFromDMS(longitude: invalidString)).to(beFalse()) invalidString = "-112233W" expect(LocationUtilities.validateLongitudeFromDMS(longitude: invalidString)).to(beFalse()) invalidString = "002233E" expect(LocationUtilities.validateLatitudeFromDMS(latitude: invalidString)).to(beFalse()) invalidString = "002233N" expect(LocationUtilities.validateLongitudeFromDMS(longitude: invalidString)).to(beFalse()) invalidString = "1800001E" expect(LocationUtilities.validateLongitudeFromDMS(longitude: invalidString)).to(beFalse()) invalidString = "1800000.1E" expect(LocationUtilities.validateLongitudeFromDMS(longitude: invalidString)).to(beFalse()) invalidString = "1800001W" expect(LocationUtilities.validateLongitudeFromDMS(longitude: invalidString)).to(beFalse()) invalidString = "1800000.1W" expect(LocationUtilities.validateLongitudeFromDMS(longitude: invalidString)).to(beFalse()) invalidString = "900001N" expect(LocationUtilities.validateLatitudeFromDMS(latitude: invalidString)).to(beFalse()) invalidString = "900000.1N" expect(LocationUtilities.validateLatitudeFromDMS(latitude: invalidString)).to(beFalse()) invalidString = "900001S" expect(LocationUtilities.validateLatitudeFromDMS(latitude: invalidString)).to(beFalse()) invalidString = "900000.1S" expect(LocationUtilities.validateLatitudeFromDMS(latitude: invalidString)).to(beFalse()) invalidString = "108900S" expect(LocationUtilities.validateLatitudeFromDMS(latitude: invalidString)).to(beFalse()) invalidString = "100089S" expect(LocationUtilities.validateLatitudeFromDMS(latitude: invalidString)).to(beFalse()) } it("should return a latitude dms string") { var coordinate = CLLocationDegrees(11.1) expect(LocationUtilities.latitudeDMSString(coordinate:coordinate)).to(equal("11° 06' 00\" N")) coordinate = CLLocationDegrees(-11.1) expect(LocationUtilities.latitudeDMSString(coordinate:coordinate)).to(equal("11° 06' 00\" S")) } it("should return a longitude dms string") { var coordinate = CLLocationDegrees(11.1) expect(LocationUtilities.longitudeDMSString(coordinate:coordinate)).to(equal("11° 06' 00\" E")) coordinate = CLLocationDegrees(-11.1) expect(LocationUtilities.longitudeDMSString(coordinate:coordinate)).to(equal("11° 06' 00\" W")) coordinate = CLLocationDegrees(18.077251) expect(LocationUtilities.longitudeDMSString(coordinate:coordinate)).to(equal("18° 04' 38\" E")) } } } }
dba5d8bee9b0e4925063786c54ea5995
55.012876
148
0.598345
false
false
false
false
exchangegroup/calayer-with-tint-colored-image
refs/heads/master
calayer-with-tint-colored-image/ViewController.swift
mit
2
// // ViewController.swift // calayer-with-tint-colored-image // // Created by Evgenii Neumerzhitckii on 17/11/2014. // Copyright (c) 2014 The Exchange Group Pty Ltd. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var viewForCALayer: UIView! override func viewDidLoad() { super.viewDidLoad() viewForCALayer.backgroundColor = nil if let currentImage = UIImage(named: "star.png") { ViewController.setImageViewImage(imageView, image: currentImage) ViewController.setCALayerImage(viewForCALayer.layer, image: currentImage) } } private class func setImageViewImage(imageView: UIImageView, image: UIImage) { imageView.image = image.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) } private class func setCALayerImage(layer: CALayer, image: UIImage) { let tintedImage = image.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) layer.contents = tintedImage.CGImage } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
e6fe879dc1f6fe618f0ae9d8ff5bb898
27.380952
87
0.744128
false
false
false
false
samuraisam/breadwallet
refs/heads/master
BreadWallet/BRAPIProxy.swift
mit
1
// // BRAPIProxy.swift // BreadWallet // // Created by Samuel Sutch on 2/8/16. // Copyright (c) 2016 breadwallet LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation // Add this middleware to a BRHTTPServer to expose a proxy to the breadwallet HTTP api // It has all the capabilities of the real API but with the ability to authenticate // requests using the users private keys stored on device. // // Clients should set the "X-Should-Verify" to enable response verification and can set // "X-Should-Authenticate" to sign requests with the users private authentication key @objc open class BRAPIProxy: NSObject, BRHTTPMiddleware { var mountPoint: String var apiInstance: BRAPIClient var shouldVerifyHeader: String = "x-should-verify" var shouldAuthHeader: String = "x-should-authenticate" var bannedSendHeaders: [String] { return [ shouldVerifyHeader, shouldAuthHeader, "connection", "authorization", "host", "user-agent" ] } var bannedReceiveHeaders: [String] = ["content-length", "content-encoding", "connection"] init(mountAt: String, client: BRAPIClient) { mountPoint = mountAt if mountPoint.hasSuffix("/") { mountPoint = mountPoint.substring(to: mountPoint.characters.index(mountPoint.endIndex, offsetBy: -1)) } apiInstance = client super.init() } open func handle(_ request: BRHTTPRequest, next: @escaping (BRHTTPMiddlewareResponse) -> Void) { if request.path.hasPrefix(mountPoint) { let idx = request.path.characters.index(request.path.startIndex, offsetBy: mountPoint.characters.count) var path = request.path.substring(from: idx) if request.queryString.utf8.count > 0 { path += "?\(request.queryString)" } var nsReq = URLRequest(url: apiInstance.url(path)) nsReq.httpMethod = request.method // copy body if request.hasBody { nsReq.httpBody = request.body() } // copy headers for (hdrName, hdrs) in request.headers { if bannedSendHeaders.contains(hdrName) { continue } for hdr in hdrs { nsReq.setValue(hdr, forHTTPHeaderField: hdrName) } } var auth = false if let authHeader = request.headers[shouldAuthHeader] , authHeader.count > 0 { if authHeader[0].lowercased() == "yes" || authHeader[0].lowercased() == "true" { auth = true } } apiInstance.dataTaskWithRequest(nsReq, authenticated: auth, retryCount: 0, handler: { (nsData, nsHttpResponse, nsError) -> Void in if let httpResp = nsHttpResponse { var hdrs = [String: [String]]() for (k, v) in httpResp.allHeaderFields { if self.bannedReceiveHeaders.contains((k as! String).lowercased()) { continue } hdrs[k as! String] = [v as! String] } var body: [UInt8]? = nil if let bod = nsData { let bp = (bod as NSData).bytes.bindMemory(to: UInt8.self, capacity: bod.count) let b = UnsafeBufferPointer<UInt8>(start: bp, count: bod.count) body = Array(b) } let resp = BRHTTPResponse( request: request, statusCode: httpResp.statusCode, statusReason: HTTPURLResponse.localizedString(forStatusCode: httpResp.statusCode), headers: hdrs, body: body) return next(BRHTTPMiddlewareResponse(request: request, response: resp)) } else { print("[BRAPIProxy] error getting response from backend: \(nsError)") return next(BRHTTPMiddlewareResponse(request: request, response: nil)) } }).resume() } else { return next(BRHTTPMiddlewareResponse(request: request, response: nil)) } } }
4776750a81fdf9307673cdc07ccaa911
45.418803
115
0.59547
false
false
false
false
GroundSpeed/BreakingGround
refs/heads/master
CodeMashQuality/CodeMashQuality/Products.swift
mit
1
// // Products.swift // CodeMashQuality // // Created by Don Miller on 1/7/16. // Copyright © 2016 GroundSpeed. All rights reserved. // import UIKit import Parse class Products { var objectId : String? var productId : Int? var photo : String? var photoFile : PFFile = PFFile() var photoImage : UIImage? var title : String? var flyer : String? var productDesc : String? var itemCode : String? var packagingOptions : String? var fragrances : String? var categories : String? var location : String? var msdsLink : String? var videoLink : String? var innerCase : Int? var masterCase : Int? func getAllProductsFromParse() -> Array<Products> { let query = PFQuery(className:"Products") var arrayProducts : Array<Products> = [] do { let objects = try query.findObjects() for object in objects { self.objectId = object["objectId"] as? String self.productId = object["Id"] as? Int self.photoImage = object["PhotoImage"] as? UIImage self.title = object["Title"] as? String self.productDesc = object["Description"] as? String arrayProducts.append(self) } } catch let e as NSError { print("Parse load error: \(e)") } return arrayProducts } }
33558015255493a7df2458f4df35fa15
26.576923
67
0.576011
false
false
false
false
Sajjon/ViewComposer
refs/heads/master
Example/Source/ViewControllers/ViewComposer/LoginViewController.swift
mit
1
// // LoginViewController.swift // Example // // Created by Alexander Cyon on 2017-06-10. // Copyright © 2017 Alexander Cyon. All rights reserved. // import UIKit import ViewComposer private let height: CGFloat = 50 private let style: ViewStyle = [.font(.big), .height(height), .clipsToBounds(true) ] private let borderStyle = style <<- .borderWidth(2) private let borderColorNormal: UIColor = .blue final class LoginViewController: UIViewController, StackViewOwner { lazy var emailField: UITextField = borderStyle <<- [.placeholder("Email"), .delegate(self)] lazy var passwordField: UITextField = borderStyle <<- [.placeholder("Password"), .delegate(self)] lazy var loginButton: Button = borderStyle <<- .states([ Normal("Login", titleColor: .blue, backgroundColor: .green, borderColor: borderColorNormal), Highlighted("Logging in...", titleColor: .red, backgroundColor: .yellow, borderColor: .red) ]) <- .target(self.target(#selector(loginButtonPressed))) <- [.roundedBy(.height)] var views: [UIView] { return [emailField, passwordField, loginButton] } lazy var stackView: UIStackView = .axis(.vertical) <- .views(self.views) <- [.spacing(20), .margin(20)] override func viewDidLoad() { super.viewDidLoad() setupViews() title = "ViewComposer - LoginViewController" } } extension LoginViewController: UITextFieldDelegate { public func textFieldDidEndEditing(_ textField: UITextField) { textField.validate() } } private extension LoginViewController { @objc func loginButtonPressed() { print("should login") } }
e34687fc60bb875409a67ec915069da3
32.117647
104
0.672587
false
false
false
false
ashfurrow/RxSwift
refs/heads/master
Rx.playground/Pages/Introduction.xcplaygroundpage/Contents.swift
mit
2
//: [<< Index](@previous) import RxSwift import Foundation /*: # Introduction ## Why use RxSwift? A vast majority of the code we write revolves around responding to external actions. When a user manipulates a control, we need to write an @IBAction to respond to that. We need to observe Notifications to detect when the keyboard changes position. We must provide blocks to execute when URL Sessions respond with data. And we use KVO to detect changes in variables. All of these various systems makes our code needlessly complex. Wouldn't it be better if there was one consistent system that handled all of our call/response code? Rx is such a system. ## Observables The key to understanding RxSwift is in understanding the notion of Observables. Creating them, manipulating them, and subscribing to them in order to react to changes. ## Creating and Subscribing to Observables The first step in understanding this library is in understanding how to create Observables. There are a number of functions available to make Observables. Creating an Observable is one thing, but if nothing subscribes to the observable, then nothing will come of it so both are explained simultaneously. */ /*: ### empty `empty` creates an empty sequence. The only message it sends is the `.Completed` message. */ example("empty") { let emptySequence: Observable<Int> = empty() let subscription = emptySequence .subscribe { event in print(event) } } /*: ### never `never` creates a sequence that never sends any element or completes. */ example("never") { let neverSequence: Observable<String> = never() let subscription = neverSequence .subscribe { _ in print("This block is never called.") } } /*: ### just `just` represents sequence that contains one element. It sends two messages to subscribers. The first message is the value of single element and the second message is `.Completed`. */ example("just") { let singleElementSequence = just(32) let subscription = singleElementSequence .subscribe { event in print(event) } } /*: ### sequenceOf `sequenceOf` creates a sequence of a fixed number of elements. */ example("sequenceOf") { let sequenceOfElements/* : Observable<Int> */ = sequenceOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) let subscription = sequenceOfElements .subscribe { event in print(event) } } /*: ### from `from` creates a sequence from `SequenceType` */ example("toObservable") { let sequenceFromArray = [1, 2, 3, 4, 5].toObservable() let subscription = sequenceFromArray .subscribe { event in print(event) } } /*: ### create `create` creates sequence using Swift closure. This examples creates custom version of `just` operator. */ example("create") { let myJust = { (singleElement: Int) -> Observable<Int> in return create { observer in observer.on(.Next(singleElement)) observer.on(.Completed) return NopDisposable.instance } } let subscription = myJust(5) .subscribe { event in print(event) } } /*: ### failWith create an Observable that emits no items and terminates with an error */ example("failWith") { let error = NSError(domain: "Test", code: -1, userInfo: nil) let erroredSequence: Observable<Int> = failWith(error) let subscription = erroredSequence .subscribe { event in print(event) } } /*: ### `deferred` do not create the Observable until the observer subscribes, and create a fresh Observable for each observer ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/defer.png) [More info in reactive.io website]( http://reactivex.io/documentation/operators/defer.html ) */ example("deferred") { let deferredSequence: Observable<Int> = deferred { print("creating") return create { observer in print("emmiting") observer.on(.Next(0)) observer.on(.Next(1)) observer.on(.Next(2)) return NopDisposable.instance } } _ = deferredSequence .subscribe { event in print(event) } _ = deferredSequence .subscribe { event in print(event) } } /*: There is a lot more useful methods in the RxCocoa library, so check them out: * `rx_observe` exist on every NSObject and wraps KVO. * `rx_tap` exists on buttons and wraps @IBActions * `rx_notification` wraps NotificationCenter events * ... and many others */ //: [Index](Index) - [Next >>](@next)
07af8c1f751583e9df9fa1b5bb7b87c0
26.467836
366
0.664892
false
false
false
false
sammeadley/TopStories
refs/heads/master
TopStories/Story.swift
mit
1
// // Story.swift // TopStories // // Created by Sam Meadley on 20/04/2016. // Copyright © 2016 Sam Meadley. All rights reserved. // import Foundation import CoreData class Story: NSManagedObject { /** Default fetch request for Story entities. Returns a fetch request configured to return Story entities, sorted by date created descending. - returns: NSFetchRequest instance for Story entities. */ override class func fetchRequest() -> NSFetchRequest<NSFetchRequestResult> { let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: String(describing: self)) fetchRequest.sortDescriptors = [ NSSortDescriptor(key: "createdDate", ascending: false) ] return fetchRequest } /** Lookup Story instances by contentURL value. Looks up Story instances based on contentURL value. Ideally we would use something like a unique identifier here to refer to unique instances. The API doesn't provide us with such, so we'll key off contentURL. - parameter URLs: Array of contentURLs used to perform the story lookup. - parameter managedObjectContext: The managedObjectContext instance to execute a fetch against. - returns: Array Story entities matching the contentURLs. */ class func instancesForContentURLs(_ URLs: [String], managedObjectContext: NSManagedObjectContext) -> [Story]? { let results = self.instancesInManagedObjectContext(managedObjectContext, predicate: NSPredicate(format: "contentURL in %@", URLs)) return results } /** Lookup Story instances by predicate. Looks up Story instances based on a supplied predicate. - parameter managedObjectContext: The managedObjectContext instance to execute a fetch against. - parameter predicate: The predicate to use in the fetch request. - returns: Array Story entities matching the predicate. */ class func instancesInManagedObjectContext(_ managedObjectContext: NSManagedObjectContext, predicate: NSPredicate? = nil) -> [Story]? { let fetchRequest = self.fetchRequest() fetchRequest.predicate = predicate do { let results = try managedObjectContext.fetch(fetchRequest) return results as? [Story] } catch { // TODO: Handle error return nil } } /** Return image URL by desired size. - parameter imageSize: The desired image size, see ImageSize for options. - returns: Image URL string. */ func imageURL(for imageSize: ImageSize) -> String? { switch imageSize { case .default: return imageURL case .thumbnail: return thumbnailURL } } /** Use with imageURLForSize(_:) to return the correct URL for the desired size. */ enum ImageSize: Int { case `default` case thumbnail } }
03254539e611815e670ee56a378024a5
31.272727
116
0.620344
false
false
false
false
SoCM/iOS-FastTrack-2014-2015
refs/heads/master
03-Single View App/Swift 3/BMI-Step10/BMI/ViewController.swift
mit
1
// // ViewController.swift // BMI // // Created by Nicholas Outram on 30/12/2014. // Copyright (c) 2014 Plymouth University. All rights reserved. // // 04-11-2015 Updated for Swift 2 import UIKit class ViewController: UIViewController, UITextFieldDelegate, UIPickerViewDelegate, UIPickerViewDataSource { class func doDiv100(_ u : Int) -> Double { return Double(u) * 0.01 } class func doDiv2(_ u : Int) -> Double { return Double(u) * 0.5 } var weight : Double? var height : Double? var bmi : Double? { get { if (weight != nil) && (height != nil) { return weight! / (height! * height!) } else { return nil } } } let listOfHeightsInM = Array(140...220).map(ViewController.doDiv100) let listOfWeightsInKg = Array(80...240).map(ViewController.doDiv2) @IBOutlet weak var bmiLabel: UILabel! @IBOutlet weak var heightTextField: UITextField! @IBOutlet weak var weightTextField: UITextField! @IBOutlet weak var heightPickerView: UIPickerView! @IBOutlet weak var weightPickerView: UIPickerView! 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. } //This function dismissed the keyboard func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } func updateUI() { if let b = self.bmi { self.bmiLabel.text = String(format: "%4.1f", b) } } //Called when ever the textField looses focus func textFieldDidEndEditing(_ textField: UITextField) { //First we check if textField.text actually contains a (wrapped) String guard let txt : String = textField.text else { //Simply return if not return } //At this point, txt is of type String. Here is a nested function that will be used //to parse this string, and convert it to a wrapped Double if possible. func conv(_ numString : String) -> Double? { let result : Double? = NumberFormatter().number(from: numString)?.doubleValue return result } //Which textField is being edit? switch (textField) { case heightTextField: self.height = conv(txt) case weightTextField: self.weight = conv(txt) //default must be here to give complete coverage. A safety precaution. default: print("Something bad happened!") } //end of switch //Last of all, update the user interface. updateUI() } func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { switch (pickerView) { case heightPickerView: return self.listOfHeightsInM.count case weightPickerView: return self.listOfWeightsInKg.count default: return 1 } } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { switch (pickerView) { case heightPickerView: return String(format: "%4.2f", self.listOfHeightsInM[row]) case weightPickerView: return String(format: "%4.1f", self.listOfWeightsInKg[row]) default: return "" } } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { switch (pickerView) { case heightPickerView: self.height = self.listOfHeightsInM[row] case weightPickerView: self.weight = self.listOfWeightsInKg[row] default: break } updateUI() } }
5cbf8b1d839fa65ab05b4d6ade576e75
25.79085
110
0.607465
false
false
false
false
koba-uy/chivia-app-ios
refs/heads/master
src/Chivia/Views/ReportTypeCollectionViewCell.swift
lgpl-3.0
1
// // ReportTypeCollectionViewCell.swift // Chivia // // Created by Agustín Rodríguez on 10/29/17. // Copyright © 2017 Agustín Rodríguez. All rights reserved. // import LGButton import UIKit class ReportTypeCollectionViewCell : UICollectionViewCell { @IBOutlet var view: UIView! @IBOutlet var button: LGButton! @IBOutlet var label: UILabel! public var delegate: ReportTypeCollectionViewCellDelegate? public var reportType: ReportType? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) Bundle.main.loadNibNamed("ReportTypeCollectionViewCell", owner: self, options: nil) addSubview(view) view.frame = self.bounds view.autoresizingMask = [.flexibleWidth, .flexibleHeight] } override func layoutSubviews() { super.layoutSubviews() button.bgColor = reportType!.iconColor button.leftIconString = reportType!.iconString label.text = reportType!.name } @IBAction func button(_ sender: LGButton) { delegate?.reportTypeCollectionViewCell(clicked: reportType!) } }
cf636af783bd725919f11f87b7fc3cee
25.813953
91
0.67216
false
false
false
false
gxf2015/DYZB
refs/heads/master
DYZB/DYZB/Classes/Main/View/CollectionBaseCell.swift
mit
1
// // CollectionBaseCell.swift // DYZB // // Created by guo xiaofei on 2017/8/14. // Copyright © 2017年 guo xiaofei. All rights reserved. // import UIKit import Kingfisher class CollectionBaseCell: UICollectionViewCell { @IBOutlet weak var iconImageView: UIImageView! @IBOutlet weak var onlineBtn: UIButton! @IBOutlet weak var nickNameLabel: UILabel! var anchor : AncnorModel? { didSet{ //0 guard let anchor = anchor else { return } //1 var onlineStr : String = "" if anchor.online >= 10000 { onlineStr = "\(Int(anchor.online / 10000))万在线" }else{ onlineStr = "\(anchor.online)万在线" } onlineBtn.setTitle(onlineStr, for: .normal) nickNameLabel.text = anchor.nickname guard let iconURL = URL(string: anchor.vertical_src) else { return } iconImageView.kf.setImage(with: iconURL) } } }
ab414218add941ec3248520938a40512
24.204545
71
0.52119
false
false
false
false
Bouke/HAP
refs/heads/master
Sources/HAP/Base/Predefined/Characteristics/Characteristic.TargetHumidifierDehumidifierState.swift
mit
1
import Foundation public extension AnyCharacteristic { static func targetHumidifierDehumidifierState( _ value: Enums.TargetHumidifierDehumidifierState = .auto, permissions: [CharacteristicPermission] = [.read, .write, .events], description: String? = "Target Humidifier-Dehumidifier State", format: CharacteristicFormat? = .uint8, unit: CharacteristicUnit? = nil, maxLength: Int? = nil, maxValue: Double? = 2, minValue: Double? = 0, minStep: Double? = 1, validValues: [Double] = [], validValuesRange: Range<Double>? = nil ) -> AnyCharacteristic { AnyCharacteristic( PredefinedCharacteristic.targetHumidifierDehumidifierState( value, permissions: permissions, description: description, format: format, unit: unit, maxLength: maxLength, maxValue: maxValue, minValue: minValue, minStep: minStep, validValues: validValues, validValuesRange: validValuesRange) as Characteristic) } } public extension PredefinedCharacteristic { static func targetHumidifierDehumidifierState( _ value: Enums.TargetHumidifierDehumidifierState = .auto, permissions: [CharacteristicPermission] = [.read, .write, .events], description: String? = "Target Humidifier-Dehumidifier State", format: CharacteristicFormat? = .uint8, unit: CharacteristicUnit? = nil, maxLength: Int? = nil, maxValue: Double? = 2, minValue: Double? = 0, minStep: Double? = 1, validValues: [Double] = [], validValuesRange: Range<Double>? = nil ) -> GenericCharacteristic<Enums.TargetHumidifierDehumidifierState> { GenericCharacteristic<Enums.TargetHumidifierDehumidifierState>( type: .targetHumidifierDehumidifierState, value: value, permissions: permissions, description: description, format: format, unit: unit, maxLength: maxLength, maxValue: maxValue, minValue: minValue, minStep: minStep, validValues: validValues, validValuesRange: validValuesRange) } }
dc62afb512846544c655bc41689619d4
36.885246
75
0.619645
false
false
false
false
hlts2/SwiftyLogger
refs/heads/master
Sources/LoggerSettings.swift
mit
1
import Foundation public struct LoggerSettings { public var dateFormat = "yyyy-MM-dd HH:mm:ss.SSS" public var filePath = "/tmp/SwiftyLogger.log" public var logHidden = false public var showEmoji = true public var showDate = true public var showFunctionName = true public var showFileName = true public var isFileWrite = false }
6110a67cb530a4f5bc06504380546ff2
33.076923
63
0.582393
false
false
false
false
meetkei/KeiSwiftFramework
refs/heads/master
KeiSwiftFramework/Notification/KNotification.swift
mit
1
// // KNotification.swift // // Copyright (c) 2016 Keun young Kim <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation open class KNotification { open class func post(_ name: String, object: AnyObject? = nil) { NotificationCenter.default.post(name: Notification.Name(rawValue: name), object: object) } open class func postDelayedOnMainQueue(_ name: String, delay: Double = 0.3, object: AnyObject? = nil) { AsyncGCD.performDelayedOnMainQueue(delay) { NotificationCenter.default.post(name: Notification.Name(rawValue: name), object: object) } } open class func postDelayedOnGlobalQueue(_ name: String, delay: Double = 0.3, object: AnyObject? = nil) { AsyncGCD.performDelayedOnGlobalQueue(delay) { NotificationCenter.default.post(name: Notification.Name(rawValue: name), object: object) } } }
9bad44fb9592e6fdd861f9ae764e5b24
41.297872
109
0.712777
false
false
false
false
accatyyc/Buildasaur
refs/heads/master
BuildaKit/PersistenceMigrator.swift
mit
2
// // PersistenceMigrator.swift // Buildasaur // // Created by Honza Dvorsky on 10/12/15. // Copyright © 2015 Honza Dvorsky. All rights reserved. // import Foundation import BuildaUtils public protocol MigratorType { init(persistence: Persistence) var persistence: Persistence { get set } func isMigrationRequired() -> Bool func attemptMigration() throws } extension MigratorType { func config() -> NSDictionary { let config = self.persistence.loadDictionaryFromFile("Config.json") ?? [:] return config } func persistenceVersion() -> Int? { let config = self.config() let version = config.optionalIntForKey(kPersistenceVersion) return version } } public class CompositeMigrator: MigratorType { public var persistence: Persistence { get { preconditionFailure("No persistence here") } set { for var i in self.childMigrators { i.persistence = newValue } } } internal let childMigrators: [MigratorType] public required init(persistence: Persistence) { self.childMigrators = [ Migrator_v0_v1(persistence: persistence), Migrator_v1_v2(persistence: persistence) ] } public func isMigrationRequired() -> Bool { return self.childMigrators.filter { $0.isMigrationRequired() }.count > 0 } public func attemptMigration() throws { try self.childMigrators.forEach { try $0.attemptMigration() } } } let kPersistenceVersion = "persistence_version" /* - Config.json: persistence_version: null -> 1 */ class Migrator_v0_v1: MigratorType { internal var persistence: Persistence required init(persistence: Persistence) { self.persistence = persistence } func isMigrationRequired() -> Bool { //we need to migrate if there's no persistence version, assume 1 let version = self.persistenceVersion() return (version == nil) } func attemptMigration() throws { let pers = self.persistence //make sure the config file has a persistence version number let version = self.persistenceVersion() guard version == nil else { //all good return } let config = self.config() let mutableConfig = config.mutableCopy() as! NSMutableDictionary mutableConfig[kPersistenceVersion] = 1 //save the updated config pers.saveDictionary("Config.json", item: mutableConfig) //copy the rest pers.copyFileToWriteLocation("Builda.log", isDirectory: false) pers.copyFileToWriteLocation("Projects.json", isDirectory: false) pers.copyFileToWriteLocation("ServerConfigs.json", isDirectory: false) pers.copyFileToWriteLocation("Syncers.json", isDirectory: false) pers.copyFileToWriteLocation("BuildTemplates", isDirectory: true) } } /* - ServerConfigs.json: each server now has an id - Config.json: persistence_version: 1 -> 2 */ class Migrator_v1_v2: MigratorType { internal var persistence: Persistence required init(persistence: Persistence) { self.persistence = persistence } func isMigrationRequired() -> Bool { return self.persistenceVersion() == 1 } func attemptMigration() throws { let serverRef = self.migrateServers() let (templateRef, projectRef) = self.migrateProjects() self.migrateSyncers(serverRef, project: projectRef, template: templateRef) self.migrateBuildTemplates() self.migrateConfigAndLog() } func fixPath(path: String) -> String { let oldUrl = NSURL(string: path) let newPath = oldUrl!.path! return newPath } func migrateBuildTemplates() { //first pull all triggers from all build templates and save them //as separate files, keeping the ids around. let templates = self.persistence.loadArrayOfDictionariesFromFolder("BuildTemplates") ?? [] guard templates.count > 0 else { return } let mutableTemplates = templates.map { $0.mutableCopy() as! NSMutableDictionary } //go through templates and replace full triggers with just ids var triggers = [NSDictionary]() for template in mutableTemplates { guard let tempTriggers = template["triggers"] as? [NSDictionary] else { continue } let mutableTempTriggers = tempTriggers.map { $0.mutableCopy() as! NSMutableDictionary } //go through each trigger and each one an id let trigWithIds = mutableTempTriggers.map { trigger -> NSDictionary in trigger["id"] = Ref.new() return trigger.copy() as! NSDictionary } //add them to the big list of triggers that we'll save later triggers.appendContentsOf(trigWithIds) //now gather those ids let triggerIds = trigWithIds.map { $0.stringForKey("id") } //and replace the "triggers" array in the build template with these ids template["triggers"] = triggerIds } //now save all triggers into their own folder self.persistence.saveArrayIntoFolder("Triggers", items: triggers, itemFileName: { $0.stringForKey("id") }, serialize: { $0 }) //and save the build templates self.persistence.saveArrayIntoFolder("BuildTemplates", items: mutableTemplates, itemFileName: { $0.stringForKey("id") }, serialize: { $0 }) } func migrateSyncers(server: RefType?, project: RefType?, template: RefType?) { let syncers = self.persistence.loadArrayOfDictionariesFromFile("Syncers.json") ?? [] let mutableSyncers = syncers.map { $0.mutableCopy() as! NSMutableDictionary } //give each an id let withIds = mutableSyncers.map { syncer -> NSMutableDictionary in syncer["id"] = Ref.new() return syncer } //remove server host and project path and add new ids let updated = withIds.map { syncer -> NSMutableDictionary in syncer.removeObjectForKey("server_host") syncer.removeObjectForKey("project_path") syncer.optionallyAddValueForKey(server, key: "server_ref") syncer.optionallyAddValueForKey(project, key: "project_ref") syncer.optionallyAddValueForKey(template, key: "preferred_template_ref") return syncer } self.persistence.saveArray("Syncers.json", items: updated) } func migrateProjects() -> (template: RefType?, project: RefType?) { let projects = self.persistence.loadArrayOfDictionariesFromFile("Projects.json") ?? [] let mutableProjects = projects.map { $0.mutableCopy() as! NSMutableDictionary } //give each an id let withIds = mutableProjects.map { project -> NSMutableDictionary in project["id"] = Ref.new() return project } //fix internal urls to be normal paths instead of the file:/// paths let withFixedUrls = withIds.map { project -> NSMutableDictionary in project["url"] = self.fixPath(project.stringForKey("url")) project["ssh_public_key_url"] = self.fixPath(project.stringForKey("ssh_public_key_url")) project["ssh_private_key_url"] = self.fixPath(project.stringForKey("ssh_private_key_url")) return project } //remove preferred_template_id, will be moved to syncer let removedTemplate = withFixedUrls.map { project -> (RefType?, NSMutableDictionary) in let template = project["preferred_template_id"] as? RefType project.removeObjectForKey("preferred_template_id") return (template, project) } //get just the projects let finalProjects = removedTemplate.map { $0.1 } let firstTemplate = removedTemplate.map { $0.0 }.first ?? nil let firstProject = finalProjects.first?["id"] as? RefType //save self.persistence.saveArray("Projects.json", items: finalProjects) return (firstTemplate, firstProject) } func migrateServers() -> (RefType?) { let servers = self.persistence.loadArrayOfDictionariesFromFile("ServerConfigs.json") ?? [] let mutableServers = servers.map { $0.mutableCopy() as! NSMutableDictionary } //give each an id let withIds = mutableServers.map { server -> NSMutableDictionary in server["id"] = Ref.new() return server } //save self.persistence.saveArray("ServerConfigs.json", items: withIds) //return the first/only one (there should be 0 or 1) let firstId = withIds.first?["id"] as? RefType return firstId } func migrateConfigAndLog() { //copy log self.persistence.copyFileToWriteLocation("Builda.log", isDirectory: false) let config = self.config() let mutableConfig = config.mutableCopy() as! NSMutableDictionary mutableConfig[kPersistenceVersion] = 2 //save the updated config self.persistence.saveDictionary("Config.json", item: mutableConfig) } }
31a5c915ffb14a3f65a739f334b25f79
34.205128
147
0.618458
false
true
false
false
PrimarySA/Hackaton2015
refs/heads/master
stocker/BachiTrading/OrdersViewController.swift
gpl-3.0
1
// // OrdersViewController.swift // BachiTrading // // Created by Emiliano Bivachi on 15/11/15. // Copyright (c) 2015 Emiliano Bivachi. All rights reserved. // import UIKit class OrdersViewController: UIViewController { private var orders: [Order]? { didSet { tableView.reloadData() } } @IBOutlet private weak var tableView: UITableView! init() { super.init(nibName: "MarketDataViewController", bundle: nil) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() tableView.registerNib(OrderCell.cellNib(), forCellReuseIdentifier: OrderCell.identifier()) title = "Ordenes" navigationItem.leftBarButtonItem?.tintColor = Styler.Color.greenColor OrderStore.sharedInstance().getOrdersForAccountId("20", withCompletionBlock: { [weak self] (ordersResponse, error) -> Void in if let ordersResponse = ordersResponse as? ListOfOrdersResponse, let orders = ordersResponse.orders as? [Order], let weakSelf = self { weakSelf.orders = orders } }) } } extension OrdersViewController: UITableViewDelegate, UITableViewDataSource { //TableView Delegate and Datasource func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return orders?.count ?? 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(OrderCell.identifier(), forIndexPath: indexPath) as! OrderCell if let orders = self.orders { cell.order = orders[indexPath.row] } return cell } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return OrderCell.cellHeight() } func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0.01 } }
25f4aa93f1618cbb7de8fb9c514d84d5
30.09589
133
0.657269
false
false
false
false
KrishMunot/swift
refs/heads/master
test/SILGen/optional-cast.swift
apache-2.0
3
// RUN: %target-swift-frontend -emit-silgen %s | FileCheck %s class A {} class B : A {} // CHECK-LABEL: sil hidden @_TF4main3foo // CHECK: [[X:%.*]] = alloc_box $Optional<B>, var, name "x" // CHECK-NEXT: [[PB:%.*]] = project_box [[X]] // Check whether the temporary holds a value. // CHECK: [[T1:%.*]] = select_enum %0 // CHECK-NEXT: cond_br [[T1]], [[IS_PRESENT:bb.*]], [[NOT_PRESENT:bb[0-9]+]] // If so, pull the value out and check whether it's a B. // CHECK: [[IS_PRESENT]]: // CHECK-NEXT: [[VAL:%.*]] = unchecked_enum_data %0 : $Optional<A>, #Optional.some!enumelt.1 // CHECK-NEXT: [[X_VALUE:%.*]] = init_enum_data_addr [[PB]] : $*Optional<B>, #Optional.some // CHECK-NEXT: checked_cast_br [[VAL]] : $A to $B, [[IS_B:bb.*]], [[NOT_B:bb[0-9]+]] // If so, materialize that and inject it into x. // CHECK: [[IS_B]]([[T0:%.*]] : $B): // CHECK-NEXT: store [[T0]] to [[X_VALUE]] : $*B // CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<B>, #Optional.some // CHECK-NEXT: br [[CONT:bb[0-9]+]] // If not, release the A and inject nothing into x. // CHECK: [[NOT_B]]: // CHECK-NEXT: strong_release [[VAL]] // CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<B>, #Optional.none // CHECK-NEXT: br [[CONT]] // Finish the present path. // CHECK: [[CONT]]: // CHECK-NEXT: br [[CONT2:bb[0-9]+]] // Finish. // CHECK: [[CONT2]]: // CHECK-NEXT: strong_release [[X]] // CHECK-NEXT: release_value %0 // Finish the not-present path. // CHECK: [[NOT_PRESENT]]: // CHECK-NEXT: inject_enum_addr [[PB]] {{.*}}none // CHECK-NEXT: br [[CONT2]] func foo(_ y : A?) { var x = (y as? B) } // CHECK-LABEL: sil hidden @_TF4main3bar // CHECK: [[X:%.*]] = alloc_box $Optional<Optional<Optional<B>>>, var, name "x" // CHECK-NEXT: [[PB:%.*]] = project_box [[X]] // Check for some(...) // CHECK-NEXT: retain_value %0 // CHECK: [[T1:%.*]] = select_enum %0 // CHECK-NEXT: cond_br [[T1]], [[P:bb.*]], [[NIL_DEPTH2:bb[0-9]+]] // If so, drill down another level and check for some(some(...)). // CHECK: [[P]]: // CHECK-NEXT: [[VALUE_OOOA:%.*]] = unchecked_enum_data %0 // CHECK: [[T1:%.*]] = select_enum [[VALUE_OOOA]] // CHECK-NEXT: cond_br [[T1]], [[PP:bb.*]], [[NIL_DEPTH2:bb[0-9]+]] // If so, drill down another level and check for some(some(some(...))). // CHECK: [[PP]]: // CHECK-NEXT: [[VALUE_OOA:%.*]] = unchecked_enum_data [[VALUE_OOOA]] // CHECK: [[T1:%.*]] = select_enum [[VALUE_OOA]] // CHECK-NEXT: cond_br [[T1]], [[PPP:bb.*]], [[NIL_DEPTH1:bb[0-9]+]] // If so, drill down another level and check for some(some(some(some(...)))). // CHECK: [[PPP]]: // CHECK-NEXT: [[VALUE_OA:%.*]] = unchecked_enum_data [[VALUE_OOA]] // CHECK: [[T1:%.*]] = select_enum [[VALUE_OA]] // CHECK-NEXT: cond_br [[T1]], [[PPPP:bb.*]], [[NIL_DEPTH0:bb[0-9]+]] // If so, pull out the A and check whether it's a B. // CHECK: [[PPPP]]: // CHECK-NEXT: [[VAL:%.*]] = unchecked_enum_data [[VALUE_OA]] // CHECK-NEXT: checked_cast_br [[VAL]] : $A to $B, [[IS_B:bb.*]], [[NOT_B:bb[0-9]+]] // If so, inject it back into an optional. // TODO: We're going to switch back out of this; we really should peephole it. // CHECK: [[IS_B]]([[T0:%.*]] : $B): // CHECK-NEXT: enum $Optional<B>, #Optional.some!enumelt.1, [[T0]] // CHECK-NEXT: br [[SWITCH_OB2:bb[0-9]+]]( // If not, inject nothing into an optional. // CHECK: [[NOT_B]]: // CHECK-NEXT: strong_release [[VAL]] // CHECK-NEXT: enum $Optional<B>, #Optional.none!enumelt // CHECK-NEXT: br [[SWITCH_OB2]]( // Switch out on the value in [[OB2]]. // CHECK: [[SWITCH_OB2]]([[VAL:%[0-9]+]] : $Optional<B>): // CHECK: br [[DONE_DEPTH0:bb[0-9]+]] // CHECK: [[DONE_DEPTH0]]( // CHECK-NEXT: enum $Optional<Optional<B>>, #Optional.some!enumelt.1, // CHECK-NEXT: br [[DONE_DEPTH1:bb[0-9]+]] // Set X := some(OOB). // CHECK: [[DONE_DEPTH1]] // CHECK-NEXT: enum $Optional<Optional<Optional<B>>>, #Optional.some!enumelt.1, // CHECK: br [[DONE_DEPTH2:bb[0-9]+]] // CHECK: [[DONE_DEPTH2]] // CHECK-NEXT: strong_release [[X]] // CHECK-NEXT: release_value %0 // CHECK: return // On various failure paths, set OOB := nil. // CHECK: [[NIL_DEPTH1]]: // CHECK-NEXT: enum $Optional<Optional<B>>, #Optional.none!enumelt // CHECK-NEXT: br [[DONE_DEPTH1]] // On various failure paths, set X := nil. // CHECK: [[NIL_DEPTH2]]: // CHECK-NEXT: inject_enum_addr [[PB]] {{.*}}none // CHECK-NEXT: br [[DONE_DEPTH2]] // Done. func bar(_ y : A????) { var x = (y as? B??) } // CHECK-LABEL: sil hidden @_TF4main3baz // CHECK: [[X:%.*]] = alloc_box $Optional<B>, var, name "x" // CHECK-NEXT: [[PB:%.*]] = project_box [[X]] // CHECK-NEXT: retain_value %0 // CHECK: [[T1:%.*]] = select_enum %0 // CHECK: [[VAL:%.*]] = unchecked_enum_data %0 // CHECK-NEXT: [[X_VALUE:%.*]] = init_enum_data_addr [[PB]] : $*Optional<B>, #Optional.some // CHECK-NEXT: checked_cast_br [[VAL]] : $AnyObject to $B, [[IS_B:bb.*]], [[NOT_B:bb[0-9]+]] func baz(_ y : AnyObject?) { var x = (y as? B) } // <rdar://problem/17013042> T! <-> T? conversions should not produce a diamond // CHECK-LABEL: sil hidden @_TF4main18opt_to_opt_trivialFGSqSi_GSQSi_ // CHECK: bb0(%0 : $Optional<Int>): // CHECK-NEXT: debug_value %0 : $Optional<Int>, let, name "x" // CHECK-NEXT: %2 = unchecked_trivial_bit_cast %0 : $Optional<Int> to $ImplicitlyUnwrappedOptional<Int> // CHECK-NEXT: return %2 : $ImplicitlyUnwrappedOptional<Int> // CHECK-NEXT:} func opt_to_opt_trivial(_ x: Int?) -> Int! { return x } // CHECK-LABEL: sil hidden @_TF4main20opt_to_opt_referenceFGSQCS_1C_GSqS0__ // CHECK: bb0(%0 : $ImplicitlyUnwrappedOptional<C>): // CHECK-NEXT: debug_value %0 : $ImplicitlyUnwrappedOptional<C>, let, name "x" // CHECK-NEXT: %2 = unchecked_ref_cast %0 : $ImplicitlyUnwrappedOptional<C> to $Optional<C> // CHECK-NEXT: return %2 : $Optional<C> // CHECK-NEXT:} func opt_to_opt_reference(_ x : C!) -> C? { return x } // CHECK-LABEL: sil hidden @_TF4main22opt_to_opt_addressOnly // CHECK: bb0(%0 : $*Optional<T>, %1 : $*ImplicitlyUnwrappedOptional<T>): // CHECK-NEXT: debug_value_addr %1 : $*ImplicitlyUnwrappedOptional<T>, let, name "x" // CHECK-NEXT: %3 = unchecked_addr_cast %0 : $*Optional<T> to $*ImplicitlyUnwrappedOptional<T> // CHECK-NEXT: copy_addr [take] %1 to [initialization] %3 func opt_to_opt_addressOnly<T>(_ x : T!) -> T? { return x } class C {} public struct TestAddressOnlyStruct<T> { func f(_ a : T?) {} // CHECK-LABEL: sil hidden @_TFV4main21TestAddressOnlyStruct8testCall // CHECK: bb0(%0 : $*ImplicitlyUnwrappedOptional<T>, %1 : $TestAddressOnlyStruct<T>): // CHECK: [[TMPBUF:%.*]] = alloc_stack $Optional<T> // CHECK: [[TMPCAST:%.*]] = unchecked_addr_cast [[TMPBUF]] // CHECK-NEXT: copy_addr %0 to [initialization] [[TMPCAST]] // CHECK-NEXT: apply {{.*}}<T>([[TMPBUF]], %1) func testCall(_ a : T!) { f(a) } } // CHECK-LABEL: sil hidden @_TF4main35testContextualInitOfNonAddrOnlyTypeFGSqSi_T_ // CHECK: bb0(%0 : $Optional<Int>): // CHECK-NEXT: debug_value %0 : $Optional<Int>, let, name "a" // CHECK-NEXT: [[X:%.*]] = alloc_box $ImplicitlyUnwrappedOptional<Int>, var, name "x" // CHECK-NEXT: [[PB:%.*]] = project_box [[X]] // CHECK-NEXT: [[CAST:%.*]] = unchecked_addr_cast [[PB]] : $*ImplicitlyUnwrappedOptional<Int> to $*Optional<Int> // CHECK-NEXT: store %0 to [[CAST]] : $*Optional<Int> // CHECK-NEXT: strong_release [[X]] : $@box ImplicitlyUnwrappedOptional<Int> func testContextualInitOfNonAddrOnlyType(_ a : Int?) { var x = a as Int! }
54c4f17ce321b1d64b40d8d5bb5496c3
42.283237
112
0.596955
false
false
false
false
lovesunstar/network
refs/heads/master
Network/Classes/HTTPBuilder.swift
mit
1
// // HTTPBuilder.swift // Alamofire // // Created by 孙江挺 on 2018/6/6. // import Foundation import Alamofire public extension Network { public class HTTPBuilder: NSObject { internal let manager: AFManager internal init(url: String, manager: AFManager) { urlString = url self.manager = manager super.init() } @discardableResult open func method(_ method: Alamofire.HTTPMethod) -> Self { httpMethod = method return self } @discardableResult open func appendCommonParameters(_ append: Bool) -> Self { vappendCommonParameters = append return self } @discardableResult open func query(_ parameters: [String : Any]?) -> Self { queryParameters = parameters return self } @discardableResult open func post(_ parameters: [String : Any]?) -> Self { postParameters = parameters if let p = parameters , !p.isEmpty { let _ = method(.post) } return self } @discardableResult open func headers(_ headers: [String : String]?) -> Self { vheaders = headers return self } @discardableResult open func gzipEnabled(_ enabled: Bool) -> Self { vgzipEnabled = enabled return self } @discardableResult open func retry(_ retryTimes: UInt16) -> Self { self.retryTimes = retryTimes return self } @discardableResult open func timeout(_ timeout: TimeInterval) -> Self { timeoutInterval = timeout return self } @discardableResult open func cachePolicy(_ policy: NSURLRequest.CachePolicy) -> Self { vcachePolicy = policy return self } @discardableResult open func priority(_ priority: Network.Priority) -> Self { vpriority = priority return self } @discardableResult open func downloadProgress(on queue: DispatchQueue = DispatchQueue.main, callback:((Progress)->Void)?) -> Self { downloadProgressQueue = queue downloadProgressCallback = callback return self } fileprivate func append(_ parameters: [String : Any]?, to absoluteString: String) -> String { guard let parameters = parameters , !parameters.isEmpty else { return absoluteString } var results = absoluteString var components: [(String, String)] = [] for key in Array(parameters.keys).sorted(by: <) { let value = parameters[key]! components += Alamofire.URLEncoding.queryString.queryComponents(fromKey: key, value: value) } let query = (components.map { "\($0)=\($1)" } as [String]).joined(separator: "&") if !query.isEmpty { if absoluteString.contains("?") { results.append("&") } else { results.append("?") } results.append(query) } return results } open func build() -> Request? { return nil } internal var urlString: String internal var vheaders: [String : String]? internal var queryParameters: [String : Any]? internal var parameterEncoding: ParameterEncoding = .url internal var vappendCommonParameters = true internal var retryTimes: UInt16 = 0 internal var timeoutInterval: TimeInterval = 30 internal var vcachePolicy = NSURLRequest.CachePolicy.useProtocolCachePolicy internal var vpriority = Network.Priority.default internal var downloadProgressQueue: DispatchQueue? internal var downloadProgressCallback: ((Progress)->Void)? internal var vgzipEnabled = true /// 发送请求的时间(unix时间戳) internal var requestTimestamp: TimeInterval = 0 internal var httpMethod: AFMethod = .get internal var postParameters: [String : Any]? } /** 网络请求 <br /> Usage: <br /> NewsMaster.Network.request(url) .method([GET|POST|HEAD|PATCH|DELETE...])?<br /> .get([String:Any])?<br /> .post([String:Any])?<br /> .retry(retryTimes)?<br /> .headers(["Accept": "xxx"])?<br /> .encoding(FormData|Mutilpart|JSON|...)?<br /> .priority(Network.Default)?<br /> .timeout(seconds)?<br /> .append(commonParameters)?<br /> .pack() unwrap?.pon_response { _, _, results, error in logic } */ public class RequestBuilder: HTTPBuilder { @discardableResult open func encoding(_ encoding: ParameterEncoding) -> Self { parameterEncoding = encoding return self } /// NOTE: never use this way on main thread open func syncResponseJSON(options: JSONSerialization.ReadingOptions = .allowFragments) -> (URLResponse?, Any?, NSError?) { if let request = build() { var response: URLResponse? var responseData: Any? var responseError: NSError? let semaphore = DispatchSemaphore(value: 0) let _ = request.responseJSON(queue: DispatchQueue.global(qos: .default), options: options, completionHandler: { (_, URLResponse, data, error) -> Void in response = URLResponse responseData = data responseError = error semaphore.signal() }) let _ = semaphore.wait(timeout: DispatchTime.distantFuture) return (response, responseData, responseError) } return (nil, nil, nil) } open override func build() -> Request? { if self.urlString.isEmpty { return nil } var absoluteString = append(queryParameters, to: self.urlString) if vappendCommonParameters { // 从CommonParams中删除 getParameters if let commonParameters = Network.client?.commonParameters { let restCommonParameters = commonParameters - queryParameters absoluteString = append(restCommonParameters, to: absoluteString) } } var headers = [String : String]() if let defaultHeaders = Network.client?.requestHeaders { headers += defaultHeaders } headers += vheaders var URLString = absoluteString as String var postParameters = self.postParameters Network.client?.willProcessRequestWithURL(&URLString, headers: &headers, parameters: &postParameters) guard var mutableURLRequest = mutableRequest(URLString, method: httpMethod, headers: headers) else { return nil } requestTimestamp = Date().timeIntervalSince1970 if timeoutInterval != 0 { mutableURLRequest.timeoutInterval = timeoutInterval } mutableURLRequest.cachePolicy = vcachePolicy guard var encodedURLRequest = try? parameterEncoding.asAFParameterEncoding().encode(mutableURLRequest, with: postParameters) else { return nil } // GZIP Compress if vgzipEnabled { if let HTTPBody = encodedURLRequest.httpBody, let client = Network.client { var newHTTPBody = HTTPBody let compressed = client.compressDataUsingGZip(&newHTTPBody) if newHTTPBody.count > 0 && compressed { encodedURLRequest.setValue("gzip", forHTTPHeaderField: "Content-Encoding") encodedURLRequest.httpBody = newHTTPBody } } } let afRequest = manager.request(encodedURLRequest) afRequest.task?.priority = vpriority.rawValue if let dc = downloadProgressCallback { afRequest.downloadProgress(queue: downloadProgressQueue ?? DispatchQueue.main, closure: dc) } let resultRequest = Network.NormalRequest(builder: self, request: afRequest) resultRequest.maximumNumberOfRetryTimes = retryTimes return resultRequest } fileprivate func mutableRequest(_ URLString: String, method: AFMethod, headers: [String : String]?) -> URLRequest? { guard let URL = URL(string: URLString) else { return nil } var request = URLRequest(url: URL) request.httpMethod = method.rawValue if let headers = headers { for (headerField, headerValue) in headers { request.setValue(headerValue, forHTTPHeaderField: headerField) } } return request } } public class UploadBuilder: HTTPBuilder { private class Part { var name: String var fileName: String? var mimeType: String? init(name: String) { self.name = name } } internal var uploadProgressQueue: DispatchQueue? internal var uploadProgressCallback: ((Progress)->Void)? private class Data: Part { var data: Foundation.Data init(name: String, data: Foundation.Data) { self.data = data super.init(name: name) } } override init(url: String, manager: AFManager) { super.init(url: url, manager: manager) timeoutInterval = 180 } open func append(data: Foundation.Data, name: String, fileName: String? = nil, mimeType: String? = nil) -> Self { let part = Data(name: name, data: data) part.fileName = fileName part.mimeType = mimeType dataParts.append(part) return self } private class File: Part { var fileURL: URL init(name: String, fileURL: URL) { self.fileURL = fileURL super.init(name: name) } } open func append(file fileURL: URL, name: String, fileName: String, mimeType: String? = nil) -> Self { let part = File(name: name, fileURL: fileURL) part.fileName = fileName part.mimeType = mimeType fileParts.append(part) return self } @discardableResult open func uploadProgress(on queue: DispatchQueue = DispatchQueue.main, callback:((Progress)->Void)?) -> Self { uploadProgressQueue = queue uploadProgressCallback = callback return self } open override func build() -> Request? { if self.urlString.isEmpty { return nil } let request = Network.UploadRequest(builder: self) request.maximumNumberOfRetryTimes = retryTimes var absoluteString = append(queryParameters, to: self.urlString) if vappendCommonParameters { // 从CommonParams中删除 getParameters if let commonParameters = Network.client?.commonParameters { let restCommonParameters = commonParameters - queryParameters absoluteString = append(restCommonParameters, to: absoluteString) } } var headers = [String : String]() if let defaultHeaders = Network.client?.requestHeaders { headers += defaultHeaders } headers += vheaders var postParameters = self.postParameters Network.client?.willProcessRequestWithURL(&absoluteString, headers: &headers, parameters: &postParameters) let dataParts = self.dataParts let fileParts = self.fileParts let postParts = postParameters guard let url = URL(string: absoluteString) else { return nil } var urlRequest = URLRequest(url: url) for (headerField, headerValue) in headers { urlRequest.setValue(headerValue, forHTTPHeaderField: headerField) } urlRequest.httpMethod = "POST" Alamofire.upload(multipartFormData: { (multipartFormData) in postParts?.forEach({ k, v in if let data = ((v as? String) ?? "\(v)").data(using: .utf8) { multipartFormData.append(data, withName: k) } }) dataParts.forEach({self.append($0, to: multipartFormData)}) fileParts.forEach({self.append($0, to: multipartFormData)}) }, usingThreshold:UInt64(2_000_000), with: urlRequest) { (encodingResult) in switch encodingResult { case .success(let upload, _, _): upload.task?.priority = self.vpriority.rawValue self.requestTimestamp = NSDate().timeIntervalSince1970 if let pq = self.uploadProgressCallback { upload.uploadProgress(queue: self.uploadProgressQueue ?? DispatchQueue.main, closure: pq) } if let dc = self.downloadProgressCallback { upload.downloadProgress(queue: self.downloadProgressQueue ?? DispatchQueue.main, closure: dc) } request.request = upload request.startUploading() case .failure(let encodingError): request.notifyError(encodingError) } } request.maximumNumberOfRetryTimes = self.retryTimes return request } private func append(_ data: Data, to multipartFormData: Alamofire.MultipartFormData) { if let mimeType = data.mimeType { if let fileName = data.fileName { multipartFormData.append(data.data, withName: data.name, fileName: fileName, mimeType: mimeType) } else { multipartFormData.append(data.data, withName: data.name, mimeType: mimeType) } } else { multipartFormData.append(data.data, withName: data.name) } } private func append(_ file: File, to multipartFormData: Alamofire.MultipartFormData) { if let mimeType = file.mimeType { if let fileName = file.fileName { multipartFormData.append(file.fileURL, withName: file.name, fileName: fileName, mimeType: mimeType) } else { multipartFormData.append(file.fileURL, withName: file.name, fileName: "\(Date().timeIntervalSince1970)", mimeType: mimeType) } } else { multipartFormData.append(file.fileURL, withName: file.name) } } private var dataParts = [Data]() private var fileParts = [File]() } }
05c54150aa23177580dd72e9d3f7ee94
38.089552
168
0.547665
false
false
false
false
russbishop/Swift-Flow
refs/heads/master
SwiftFlowTests/TestFakes.swift
mit
1
// // Fakes.swift // SwiftFlow // // Created by Benji Encz on 12/24/15. // Copyright © 2015 Benjamin Encz. All rights reserved. // import Foundation @testable import SwiftFlow struct TestAppState: StateType { var testValue: Int? init() { testValue = nil } } struct TestStringAppState: StateType { var testValue: String? init() { testValue = nil } } struct SetValueAction: StandardActionConvertible { let value: Int static let type = "SetValueAction" init (_ value: Int) { self.value = value } init(_ standardAction: StandardAction) { self.value = standardAction.payload!["value"] as! Int } func toStandardAction() -> StandardAction { return StandardAction(type: SetValueAction.type, payload: ["value": value]) } } struct SetValueStringAction: StandardActionConvertible { var value: String static let type = "SetValueStringAction" init (_ value: String) { self.value = value } init(_ standardAction: StandardAction) { self.value = standardAction.payload!["value"] as! String } func toStandardAction() -> StandardAction { return StandardAction(type: SetValueStringAction.type, payload: ["value": value]) } } struct TestReducer: Reducer { func handleAction(var state: TestAppState, action: Action) -> TestAppState { switch action { case let action as SetValueAction: state.testValue = action.value return state default: return state } } } struct TestValueStringReducer: Reducer { func handleAction(var state: TestStringAppState, action: Action) -> TestStringAppState { switch action { case let action as SetValueStringAction: state.testValue = action.value return state default: return state } } } class TestStoreSubscriber<T>: StoreSubscriber { var receivedStates: [T] = [] func newState(state: T) { receivedStates.append(state) } }
c4efda643483f608a63335da6c8854be
20.666667
92
0.631731
false
true
false
false
Ben21hao/edx-app-ios-new
refs/heads/master
Source/JSONFormBuilderTextEditor.swift
apache-2.0
1
// // JSONFormBuilderTextEditor.swift // edX // // Created by Michael Katz on 10/1/15. // Copyright © 2015 edX. All rights reserved. // import Foundation class JSONFormBuilderTextEditorViewController: TDSwiftBaseViewController { let textView = OEXPlaceholderTextView() let handInBtn = UIButton.init(type: .Custom) var text: String { return textView.text } var doneEditing: ((value: String)->())? init(text: String?, placeholder: String?) { super.init(nibName: nil, bundle: nil) self.view = UIView() self.view.backgroundColor = UIColor.whiteColor() textView.textContainer.lineFragmentPadding = 0 textView.textContainerInset = OEXStyles.sharedStyles().standardTextViewInsets textView.typingAttributes = OEXStyles.sharedStyles().textAreaBodyStyle.attributes // textView.placeholder = "请输入昵称" textView.placeholderTextColor = OEXStyles.sharedStyles().neutralBase() textView.textColor = OEXStyles.sharedStyles().neutralBlackT() textView.font = UIFont.init(name: "OpenSans", size: 16) textView.backgroundColor = UIColor.whiteColor() textView.layer.cornerRadius = 4.0 textView.layer.borderColor = UIColor.init(RGBHex: 0xccd1d9, alpha: 1).CGColor textView.layer.borderWidth = 0.5; textView.delegate = self textView.text = text ?? "" if let placeholder = placeholder { textView.placeholder = placeholder } handInBtn.setTitle(Strings.submit, forState: .Normal) handInBtn.addTarget(self, action: #selector(JSONFormBuilderTextEditorViewController.handinButtonAction), forControlEvents: .TouchUpInside) handInBtn.backgroundColor = OEXStyles.sharedStyles().baseColor1() handInBtn.layer.cornerRadius = 4.0 setupViews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) OEXAnalytics.sharedAnalytics().trackScreenWithName(OEXAnalyticsScreenEditTextFormValue) } private func setupViews() { view.addSubview(textView) textView.snp_makeConstraints { (make) -> Void in make.top.equalTo(view.snp_topMargin).offset(18) make.leading.equalTo(view.snp_leadingMargin) make.trailing.equalTo(view.snp_trailingMargin) make.height.equalTo(41) } view.addSubview(handInBtn) handInBtn.snp_makeConstraints { (make) in make.top.equalTo(view.snp_topMargin).offset(77) make.leading.equalTo(view.snp_leadingMargin) make.trailing.equalTo(view.snp_trailingMargin) make.height.equalTo(41) } } func handinButtonAction() { self.textView.resignFirstResponder() if textView.text.characters.count == 0 { //昵称不能为空 let alertView = UIAlertView.init(title: Strings.reminder, message: Strings.nicknameNull, delegate: self, cancelButtonTitle: Strings.ok) alertView.show() } else if textView.text.characters.count <= 6 { let baseTool = TDBaseToolModel.init() baseTool.checkNickname(textView.text, view: self.view) baseTool.checkNickNameHandle = {(AnyObject) -> () in if AnyObject == true { self.doneEditing?(value: self.textView.text) //block 反向传值 let dic : NSDictionary = ["nickName" : self.textView.text] NSNotificationCenter.defaultCenter().postNotificationName("NiNameNotification_Change", object:dic) self.navigationController?.popViewControllerAnimated(true) } } } else { //不能超过六个字 let alertView = UIAlertView.init(title: Strings.reminder, message: Strings.nicknameNumber, delegate: self, cancelButtonTitle: Strings.ok) alertView.show() } } // override func willMoveToParentViewController(parent: UIViewController?) { // if parent == nil { //removing from the hierarchy // doneEditing?(value: textView.text) // } // } } extension JSONFormBuilderTextEditorViewController : UITextViewDelegate { func textViewShouldEndEditing(textView: UITextView) -> Bool { textView.resignFirstResponder() return true } }
a580fb9b05db4b5a668201354629c64d
37.813559
149
0.637773
false
false
false
false
LiuDeng/LazyCocoa
refs/heads/master
Source/LazyCocoa-MacApp/Core/NewScanningMechanism.swift
mit
2
// // NewScanningMechanism.swift // The Lazy Cocoa Project // // Copyright (c) 2015 Yichi Zhang. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // import Foundation class ConfigurationModel: Printable { var key = "" var value = "" init(key:String, value:String) { self.key = key self.value = value } var description:String { return "\n<Configuration: Key = \(key), Value = \(value)>" } } class StatementModel: Printable { var added = false var index:Int = -1 var identifiers:[String] = [] // Strings within double quotation marks; "strings that contains white spaces" var names:[String] = [] var colorCodes:[String] = [] var numbers:[String] = [] func copy() -> StatementModel { let s = StatementModel() s.index = self.index s.identifiers = self.identifiers s.names = self.names s.colorCodes = self.colorCodes s.numbers = self.numbers return s } var isEmpty:Bool { if identifiers.count + names.count + colorCodes.count + numbers.count > 0 { return false } else { return true } } var description:String { let arrayToString = { (array:[String]) -> String in if array.isEmpty { return "NONE" } else { return "(" + join(", ", array) + ")" } } return "\n<Statement #\(index): IDS = \(arrayToString(identifiers)), names = \(arrayToString(names)), colorCodes = \(arrayToString(colorCodes)), numbers = \(arrayToString(numbers))>" } func add(#statementItem:String) { if statementItem.isValidNumber { numbers.append(statementItem) } else if statementItem.isValidColorCode { colorCodes.append(statementItem) } else { identifiers.append(statementItem) } } func addAsName(#statementItem:String) { names.append(statementItem) } } class SourceCodeScanner { // statementArray contains StatementModel, ConfigurationModel and String objects var statementArray = [AnyObject]() var statementCounter = 0 var currentStatementModel:StatementModel! private func addProcessMode(processMode:String) { statementArray.append(processMode) } private func createNewStatementModel() { currentStatementModel = StatementModel() } private func addCurrentStatementModel() { if !currentStatementModel.added && !currentStatementModel.isEmpty { statementArray.append(currentStatementModel) currentStatementModel.index = statementCounter++ currentStatementModel.added == true } } private func add(#statementItem:String) { currentStatementModel.add(statementItem: statementItem) } private func addAsName(#statementItem:String) { currentStatementModel.addAsName(statementItem: statementItem) } private func addParameter(#parameterKey:String, parameterValue:String) { statementArray.append(ConfigurationModel(key: parameterKey, value: parameterValue)) } func processSourceString(string:String) { statementArray.removeAll(keepCapacity: true) statementCounter = 0 currentStatementModel = StatementModel() let scanner = NSScanner(string: string) let whitespaceAndNewline = NSCharacterSet.whitespaceAndNewlineCharacterSet() let whitespace = NSCharacterSet.whitespaceCharacterSet() let newline = NSCharacterSet.newlineCharacterSet() let whitespaceNewlineAndSemicolon = whitespaceAndNewline.mutableCopy() as! NSMutableCharacterSet whitespaceNewlineAndSemicolon.addCharactersInString(";") let newlineAndSemicolon = newline.mutableCopy() as! NSMutableCharacterSet newlineAndSemicolon.addCharactersInString(";") var resultString:NSString? while scanner.scanLocation < count(scanner.string) { let currentChar = scanner.string.characterAtIndex(scanner.scanLocation) let twoCharString = scanner.string.safeSubstring(start: scanner.scanLocation, length: 2) let threeCharString = scanner.string.safeSubstring(start: scanner.scanLocation, length: 3) if threeCharString == "!!!" { //This is the string after !!!, before any white space or new line characters. scanner.scanLocation += threeCharString.length scanner.scanUpToCharactersFromSet(whitespaceAndNewline, intoString: &resultString) if let resultString = resultString { addProcessMode(resultString as String) } } else if twoCharString == StringConst.SigleLineComment { scanner.scanLocation += twoCharString.length scanner.scanUpToCharactersFromSet(newline, intoString: &resultString) } else if twoCharString == StringConst.MultiLineCommentStart { scanner.scanLocation += twoCharString.length scanner.scanUpToString(StringConst.MultiLineCommentEnd, intoString: &resultString) scanner.scanLocation += StringConst.MultiLineCommentEnd.length } else if twoCharString == "!!" { //This is a parameter scanner.scanLocation += twoCharString.length scanner.scanUpToCharactersFromSet(whitespace, intoString: &resultString) let parameterKey = resultString scanner.scanUpToCharactersFromSet(newline, intoString: &resultString) let parameterValue = resultString if parameterKey != nil && parameterValue != nil { let processedParameterValue = (parameterValue as! String).stringByRemovingSingleLineComment() self.addParameter(parameterKey: parameterKey as! String, parameterValue: processedParameterValue) } } else { if currentChar == Character(StringConst.DoubleQuote) { scanner.scanLocation++ scanner.scanUpToString(StringConst.DoubleQuote, intoString: &resultString) scanner.scanLocation += StringConst.DoubleQuote.length addAsName(statementItem: resultString as! String) } else { scanner.scanUpToCharactersFromSet(whitespaceNewlineAndSemicolon, intoString: &resultString) add(statementItem: resultString as! String) } } var oneCharString = scanner.string.safeSubstring(start: scanner.scanLocation, length: 1) if oneCharString.containsCharactersInSet(newlineAndSemicolon) { addCurrentStatementModel() createNewStatementModel() } while scanner.scanLocation < count(scanner.string) && oneCharString.containsCharactersInSet(whitespaceNewlineAndSemicolon) { scanner.scanLocation++ oneCharString = scanner.string.safeSubstring(start: scanner.scanLocation, length: 1) } } addCurrentStatementModel() // println("--\n\n\n--") // println(self.statementArray) } }
aba87191247ca093889caa1722ee54f2
30.315126
184
0.73497
false
false
false
false
manavgabhawala/swift
refs/heads/master
test/IRGen/objc_class_export.swift
apache-2.0
1
// RUN: rm -rf %t && mkdir -p %t // RUN: %build-irgen-test-overlays // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -sdk %S/Inputs -I %t -primary-file %s -emit-ir -disable-objc-attr-requires-foundation-module | %FileCheck %s // REQUIRES: CPU=x86_64 // REQUIRES: objc_interop // CHECK: %swift.refcounted = type // CHECK: [[HOOZIT:%T17objc_class_export6HoozitC]] = type <{ [[REF:%swift.refcounted]] }> // CHECK: [[FOO:%T17objc_class_export3FooC]] = type <{ [[REF]], %TSi }> // CHECK: [[INT:%TSi]] = type <{ i64 }> // CHECK: [[DOUBLE:%TSd]] = type <{ double }> // CHECK: [[NSRECT:%TSC6NSRectV]] = type <{ %TSC7NSPointV, %TSC6NSSizeV }> // CHECK: [[NSPOINT:%TSC7NSPointV]] = type <{ %TSd, %TSd }> // CHECK: [[NSSIZE:%TSC6NSSizeV]] = type <{ %TSd, %TSd }> // CHECK: [[OBJC:%objc_object]] = type opaque // CHECK: @"OBJC_METACLASS_$__TtC17objc_class_export3Foo" = hidden global %objc_class { // CHECK: %objc_class* @"OBJC_METACLASS_$_SwiftObject", // CHECK: %objc_class* @"OBJC_METACLASS_$_SwiftObject", // CHECK: %swift.opaque* @_objc_empty_cache, // CHECK: %swift.opaque* null, // CHECK: i64 ptrtoint ({{.*}}* @_METACLASS_DATA__TtC17objc_class_export3Foo to i64) // CHECK: } // CHECK: [[FOO_NAME:@.*]] = private unnamed_addr constant [28 x i8] c"_TtC17objc_class_export3Foo\00" // CHECK: @_METACLASS_DATA__TtC17objc_class_export3Foo = private constant {{.*\*}} } { // CHECK: i32 129, // CHECK: i32 40, // CHECK: i32 40, // CHECK: i32 0, // CHECK: i8* null, // CHECK: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* [[FOO_NAME]], i64 0, i64 0), // CHECK: @_CLASS_METHODS__TtC17objc_class_export3Foo, // CHECK: i8* null, // CHECK: i8* null, // CHECK: i8* null, // CHECK: i8* null // CHECK: }, section "__DATA, __objc_const", align 8 // CHECK: @_DATA__TtC17objc_class_export3Foo = private constant {{.*\*}} } { // CHECK: i32 128, // CHECK: i32 16, // CHECK: i32 24, // CHECK: i32 0, // CHECK: i8* null, // CHECK: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* [[FOO_NAME]], i64 0, i64 0), // CHECK: { i32, i32, [6 x { i8*, i8*, i8* }] }* @_INSTANCE_METHODS__TtC17objc_class_export3Foo, // CHECK: i8* null, // CHECK: @_IVARS__TtC17objc_class_export3Foo, // CHECK: i8* null, // CHECK: _PROPERTIES__TtC17objc_class_export3Foo // CHECK: }, section "__DATA, __objc_const", align 8 // CHECK: @_TMfC17objc_class_export3Foo = internal global <{{.*i64}} }> <{ // CHECK: void ([[FOO]]*)* @_TFC17objc_class_export3FooD, // CHECK: i8** @_TWVBO, // CHECK: i64 ptrtoint (%objc_class* @"OBJC_METACLASS_$__TtC17objc_class_export3Foo" to i64), // CHECK: %objc_class* @"OBJC_CLASS_$_SwiftObject", // CHECK: %swift.opaque* @_objc_empty_cache, // CHECK: %swift.opaque* null, // CHECK: i64 add (i64 ptrtoint ({{.*}}* @_DATA__TtC17objc_class_export3Foo to i64), i64 1), // CHECK: [[FOO]]* (%swift.type*)* @_TZFC17objc_class_export3Foo6createfT_S0_, // CHECK: void (double, double, double, double, [[FOO]]*)* @_TFC17objc_class_export3Foo10drawInRectfT5dirtyVSC6NSRect_T_ // CHECK: }>, section "__DATA,__objc_data, regular" // -- TODO: The OBJC_CLASS symbol should reflect the qualified runtime name of // Foo. // CHECK: @_TMC17objc_class_export3Foo = hidden alias %swift.type, bitcast (i64* getelementptr inbounds ({{.*}} @_TMfC17objc_class_export3Foo, i32 0, i32 2) to %swift.type*) // CHECK: @"OBJC_CLASS_$__TtC17objc_class_export3Foo" = alias %swift.type, %swift.type* @_TMC17objc_class_export3Foo import gizmo class Hoozit {} struct BigStructWithNativeObjects { var x, y, w : Double var h : Hoozit } @objc class Foo { var x = 0 class func create() -> Foo { return Foo() } func drawInRect(dirty dirty: NSRect) { } // CHECK: define internal void @_TToFC17objc_class_export3Foo10drawInRectfT5dirtyVSC6NSRect_T_([[OPAQUE:%.*]]*, i8*, [[NSRECT]]* byval align 8) unnamed_addr {{.*}} { // CHECK: [[CAST:%[a-zA-Z0-9]+]] = bitcast [[OPAQUE]]* %0 to [[FOO]]* // CHECK: call swiftcc void @_TFC17objc_class_export3Foo10drawInRectfT5dirtyVSC6NSRect_T_(double {{.*}}, double {{.*}}, double {{.*}}, double {{.*}}, [[FOO]]* swiftself [[CAST]]) // CHECK: } func bounds() -> NSRect { return NSRect(origin: NSPoint(x: 0, y: 0), size: NSSize(width: 0, height: 0)) } // CHECK: define internal void @_TToFC17objc_class_export3Foo6boundsfT_VSC6NSRect([[NSRECT]]* noalias nocapture sret, [[OPAQUE4:%.*]]*, i8*) unnamed_addr {{.*}} { // CHECK: [[CAST:%[a-zA-Z0-9]+]] = bitcast [[OPAQUE4]]* %1 to [[FOO]]* // CHECK: call swiftcc { double, double, double, double } @_TFC17objc_class_export3Foo6boundsfT_VSC6NSRect([[FOO]]* swiftself [[CAST]]) func convertRectToBacking(r r: NSRect) -> NSRect { return r } // CHECK: define internal void @_TToFC17objc_class_export3Foo20convertRectToBackingfT1rVSC6NSRect_S1_([[NSRECT]]* noalias nocapture sret, [[OPAQUE5:%.*]]*, i8*, [[NSRECT]]* byval align 8) unnamed_addr {{.*}} { // CHECK: [[CAST:%[a-zA-Z0-9]+]] = bitcast [[OPAQUE5]]* %1 to [[FOO]]* // CHECK: call swiftcc { double, double, double, double } @_TFC17objc_class_export3Foo20convertRectToBackingfT1rVSC6NSRect_S1_(double {{.*}}, double {{.*}}, double {{.*}}, double {{.*}}, [[FOO]]* swiftself [[CAST]]) func doStuffToSwiftSlice(f f: [Int]) { } // This function is not representable in Objective-C, so don't emit the objc entry point. // CHECK-NOT: @_TToFC17objc_class_export3Foo19doStuffToSwiftSlicefS_FT1fGSaSi__T_ func doStuffToBigSwiftStruct(f f: BigStructWithNativeObjects) { } // This function is not representable in Objective-C, so don't emit the objc entry point. // CHECK-NOT: @_TToFC17objc_class_export3Foo23doStuffToBigSwiftStructfS_FT1fV17objc_class_export27BigStructWithNativeObjects_T_ init() { } }
5a48db1a14ae52fb8eb237eaacebd62f
48.675214
219
0.640399
false
false
false
false
3vts/OnTheMap
refs/heads/master
OnTheMap/Student.swift
mit
1
// // Student.swift // OnTheMap // // Created by Alvaro Santiesteban on 6/16/17. // Copyright © 2017 3vts. All rights reserved. // import Foundation struct Student { let createdAt: Date let firstName: String let lastName: String let latitude: Double let longitude: Double let mapString: String let mediaURL: String let objectId: String let uniqueKey: String let updatedAt: Date init(dictionary: [String:AnyObject]) { let isoFormatter = ISO8601DateFormatter() createdAt = isoFormatter.date(from: dictionary[UdacityClient.JSONResponseKeys.createdAt] as! String) ?? Date(timeIntervalSince1970: 0) firstName = dictionary[UdacityClient.JSONResponseKeys.firstName] as? String ?? "" lastName = dictionary[UdacityClient.JSONResponseKeys.lastName] as? String ?? "" latitude = dictionary[UdacityClient.JSONResponseKeys.latitude] as? Double ?? 0 longitude = dictionary[UdacityClient.JSONResponseKeys.longitude] as? Double ?? 0 mapString = dictionary[UdacityClient.JSONResponseKeys.mapString] as? String ?? "" mediaURL = dictionary[UdacityClient.JSONResponseKeys.mediaURL] as? String ?? "" objectId = dictionary[UdacityClient.JSONResponseKeys.objectId] as? String ?? "" uniqueKey = dictionary[UdacityClient.JSONResponseKeys.uniqueKey] as? String ?? "" updatedAt = isoFormatter.date(from: dictionary[UdacityClient.JSONResponseKeys.updatedAt] as! String) ?? Date(timeIntervalSince1970: 0) } static func studentsFromResults(_ results: [[String:AnyObject]]) -> [Student] { var students = [Student]() for result in results { students.append(Student(dictionary: result)) } return students } } extension Student: Equatable {} func ==(lhs: Student, rhs: Student) -> Bool { return lhs.uniqueKey == rhs.uniqueKey }
ccc1cd94d0926590eddb49b1b08851e3
33.446429
142
0.682737
false
false
false
false
askari01/DailySwift
refs/heads/master
oddOccurenceInArray.swift
mit
1
// pair same occurence in array and point the odd var count = 0 var odd = 0 public func solution(_ A : [Int]) -> Int{ odd = A[0] if (A.count == 1){ return A[0] } for i in 1...((A.count)-1){ odd = odd ^ A[i] } return odd } var a = [-1] count = solution(a) print(count)
27ca54053299f94c6bb3f89b26fd6f10
13.714286
49
0.521036
false
false
false
false
coderQuanjun/PigTV
refs/heads/master
GYJTV/GYJTV/Classes/Live/Model/GiftAnimationModel.swift
mit
1
// // GiftAnimationModel.swift // GYJTV // // Created by zcm_iOS on 2017/6/8. // Copyright © 2017年 Quanjun. All rights reserved. // import UIKit class GiftAnimationModel: NSObject { var senderName : String = "" //送礼物者 var senderUrl : String = "" // var giftName : String = "" //礼物名称 var giftUrl : String = "" init(senderName : String, senderUrl : String, giftName : String, giftUrl : String) { self.senderName = senderName self.senderUrl = senderUrl self.giftName = giftName self.giftUrl = giftUrl } override func isEqual(_ object: Any?) -> Bool { guard let obj = object as? GiftAnimationModel else { return false } guard obj.senderName == senderName && obj.giftName == giftName else { return false } return true } }
ea6b1c11ad83d1dd4fa12b35fef61ed3
23.742857
88
0.590069
false
false
false
false
crazypoo/PTools
refs/heads/master
Pods/CollectionViewPagingLayout/Lib/Snapshot/SnapshotTransformView.swift
mit
1
// // SnapshotTransformView.swift // CollectionViewPagingLayout // // Created by Amir on 07/03/2020. // Copyright © 2020 Amir Khorsandi. All rights reserved. // import UIKit public protocol SnapshotTransformView: TransformableView { /// Options for controlling the effects, see `SnapshotTransformViewOptions.swift` var snapshotOptions: SnapshotTransformViewOptions { get } /// The view to apply the effect on var targetView: UIView { get } /// A unique identifier for the snapshot, a new snapshot won't be made if /// there is a cashed snapshot with the same identifier var snapshotIdentifier: String { get } /// the function for getting the cached snapshot or make a new one and cache it func getSnapshot() -> SnapshotContainerView? /// the main function for applying transforms on the snapshot func applySnapshotTransform(snapshot: SnapshotContainerView, progress: CGFloat) /// Check if the snapshot can be reused func canReuse(snapshot: SnapshotContainerView) -> Bool } public extension SnapshotTransformView where Self: UICollectionViewCell { /// Default `targetView` for `UICollectionViewCell` is the first subview of /// `contentView` or the content view itself in case of no subviews var targetView: UIView { contentView.subviews.first ?? contentView } /// Default `identifier` for `UICollectionViewCell` is it's index /// if you have the same content with different indexes (like an infinite list) /// you should override this and provide a content-based identifier var snapshotIdentifier: String { var collectionView: UICollectionView? var superview = self.superview while superview != nil { if let view = superview as? UICollectionView { collectionView = view break } superview = superview?.superview } var identifier = "\(collectionView?.indexPath(for: self) ?? IndexPath())" if let scrollView = targetView as? UIScrollView { identifier.append("\(scrollView.contentOffset)") } if let scrollView = targetView.subviews.first(where: { $0 is UIScrollView }) as? UIScrollView { identifier.append("\(scrollView.contentOffset)") } return identifier } /// Default implementation only compares the size of snapshot with the view func canReuse(snapshot: SnapshotContainerView) -> Bool { snapshot.snapshotSize == targetView.bounds.size } } public extension SnapshotTransformView { // MARK: Properties var snapshotOptions: SnapshotTransformViewOptions { .init() } // MARK: TransformableView func transform(progress: CGFloat) { guard let snapshot = getSnapshot() else { return } applySnapshotTransform(snapshot: snapshot, progress: progress) } // MARK: Public functions func getSnapshot() -> SnapshotContainerView? { findSnapshot() ?? makeSnapshot() } func applySnapshotTransform(snapshot: SnapshotContainerView, progress: CGFloat) { if progress == 0 { targetView.transform = .identity snapshot.alpha = 0 } else { snapshot.alpha = 1 // hide the original view, we apply transform on the snapshot targetView.transform = CGAffineTransform.identity.translatedBy(x: 0, y: -2 * UIScreen.main.bounds.height) } snapshot.transform(progress: progress, options: snapshotOptions) } // MARK: Private functions private func hideOtherSnapshots() { targetView.superview?.subviews.filter { $0 is SnapshotContainerView }.forEach { guard let snapshot = $0 as? SnapshotContainerView else { return } if snapshot.identifier != snapshotIdentifier { snapshot.alpha = 0 } } } private func findSnapshot() -> SnapshotContainerView? { hideOtherSnapshots() let snapshot = targetView.superview?.subviews.first { ($0 as? SnapshotContainerView)?.identifier == snapshotIdentifier } as? SnapshotContainerView if let snapshot = snapshot, snapshot.pieceSizeRatio != snapshotOptions.pieceSizeRatio { snapshot.removeFromSuperview() return nil } if let snapshot = snapshot, !canReuse(snapshot: snapshot) { snapshot.removeFromSuperview() return nil } snapshot?.alpha = 1 return snapshot } private func makeSnapshot() -> SnapshotContainerView? { targetView.superview?.subviews.first { ($0 as? SnapshotContainerView)?.identifier == snapshotIdentifier }? .removeFromSuperview() guard let view = SnapshotContainerView(targetView: targetView, pieceSizeRatio: snapshotOptions.pieceSizeRatio, identifier: snapshotIdentifier) else { return nil } targetView.superview?.insertSubview(view, aboveSubview: targetView) targetView.equalSize(to: view) targetView.center(to: view) return view } } private extension SnapshotContainerView { func transform(progress: CGFloat, options: SnapshotTransformViewOptions) { let scale = max(1 - abs(progress) * options.containerScaleRatio, 0) var translateX = progress * frame.width * options.containerTranslationRatio.x var translateY = progress * frame.height * options.containerTranslationRatio.y if let min = options.containerMinTranslationRatio { translateX = max(translateX, frame.width * min.x) translateY = max(translateX, frame.width * min.y) } if let max = options.containerMaxTranslationRatio { translateX = min(translateX, frame.width * max.x) translateY = min(translateY, frame.height * max.y) } transform = CGAffineTransform.identity .translatedBy(x: translateX, y: translateY) .scaledBy(x: scale, y: scale) var sizeRatioRow = options.pieceSizeRatio.height if abs(sizeRatioRow) < 0.01 { sizeRatioRow = 0.01 } var sizeRatioColumn = options.pieceSizeRatio.width if abs(sizeRatioColumn) < 0.01 { sizeRatioColumn = 0.01 } let rowCount = Int(1.0 / sizeRatioRow) let columnCount = Int(1.0 / sizeRatioColumn) snapshots.enumerated().forEach { index, view in let position = SnapshotTransformViewOptions.PiecePosition( index: index, row: Int(index / columnCount), column: Int(index % columnCount), rowCount: rowCount, columnCount: columnCount ) let pieceScale = abs(progress) * options.piecesScaleRatio.getRatio(position: position) let pieceTransform = options.piecesTranslationRatio.getRatio(position: position) * abs(progress) let minPieceTransform = options.minPiecesTranslationRatio?.getRatio(position: position) let maxPieceTransform = options.maxPiecesTranslationRatio?.getRatio(position: position) var translateX = pieceTransform.x * view.frame.width var translateY = pieceTransform.y * view.frame.height if let min = minPieceTransform { translateX = max(translateX, view.frame.width * min.x) translateY = max(translateY, view.frame.height * min.y) } if let max = maxPieceTransform { translateX = min(translateX, view.frame.width * max.x) translateY = min(translateY, view.frame.height * max.y) } view.transform = CGAffineTransform.identity .translatedBy(x: translateX, y: translateY) .scaledBy(x: max(0, 1 - pieceScale.width), y: max(0, 1 - pieceScale.height)) view.alpha = 1 - options.piecesAlphaRatio.getRatio(position: position) * abs(progress) view.layer.cornerRadius = options.piecesCornerRadiusRatio.getRatio(position: position) * abs(progress) * min(view.frame.height, view.frame.width) view.layer.masksToBounds = true } } }
823d71998c39897181e9c86bd983523b
36.946667
157
0.627079
false
false
false
false
PureSwift/Bluetooth
refs/heads/master
Sources/BluetoothHCI/LowEnergyEvent.swift
mit
1
// // LowEnergyEvent.swift // Bluetooth // // Created by Alsey Coleman Miller on 3/2/16. // Copyright © 2016 PureSwift. All rights reserved. // /// Bluetooth Low Energy HCI Events @frozen public enum LowEnergyEvent: UInt8, HCIEvent { /// LE Connection Complete case connectionComplete = 0x01 /// LE Advertising Report case advertisingReport = 0x02 /// LE Connection Update Complete case connectionUpdateComplete = 0x03 /// LE Read Remote Used Features Complete case readRemoteUsedFeaturesComplete = 0x04 /// LE Long Term Key Request case longTermKeyRequest = 0x05 /// LE Remote Connection Parameter Request Event case remoteConnectionParameterRequest = 0x06 /// LE Data Length Change Event case dataLengthChange = 0x07 /// LE Read Local P-256 Public Key Complete Event case readLocalP256PublicKeyComplete = 0x08 /// LE Generate DHKey Complete Event case generateDHKeyComplete = 0x09 /// LE Enhanced Connection Complete Event case enhancedConnectionComplete = 0x0A /// LE Directed Advertising Report Event case directedAdvertisingReport = 0x0B /// LE PHY Update Complete Event case phyUpdateComplete = 0x0C /// LE Extended Advertising Report Event case extendedAdvertisingReport = 0x0D /// LE Periodic Advertising Sync Established Event case periodicAdvertisingSyncEstablished = 0x0E /// LE Periodic Advertising Report Event case periodicAdvertisingReport = 0x0F /// LE Periodic Advertising Sync Lost Event case periodicAdvertisingSyncLost = 0x10 /// LE Scan Timeout Event case scanTimeout = 0x11 /// LE Advertising Set Terminated Event case advertisingSetTerminated = 0x12 /// LE Scan Request Received Event case scanRequestReceived = 0x13 /// LE Channel Selection Algorithm Event case channelSelectionAlgorithm = 0x14 } // MARK: - Name public extension LowEnergyEvent { var name: String { switch self { case .connectionComplete: return "LE Connection Complete" case .advertisingReport: return "LE Advertising Report" case .connectionUpdateComplete: return "LE Connection Update Complete" case .readRemoteUsedFeaturesComplete: return "LE Read Remote Used Features Complete" case .longTermKeyRequest: return "LE Long Term Key Request" case .remoteConnectionParameterRequest: return "LE Remote Connection Parameter Request Event" case .dataLengthChange: return "LE Data Length Change Event" case .readLocalP256PublicKeyComplete: return "LE Read Local P-256 Public Key Complete Event" case .generateDHKeyComplete: return "LE Generate DHKey Complete Event" case .enhancedConnectionComplete: return "LE Enhanced Connection Complete" case .directedAdvertisingReport: return "LE Directed Advertising Report Event" case .phyUpdateComplete: return "LE PHY Update Complete" case .extendedAdvertisingReport: return "LE Extended Advertising Report Event" case .periodicAdvertisingSyncEstablished: return "LE Periodic Advertising Sync Established Event" case .periodicAdvertisingReport: return "LE Periodic Advertising Report Event" case .periodicAdvertisingSyncLost: return "LE Periodic Advertising Sync Lost Event" case .scanTimeout: return "LE Scan Timeout Event" case .advertisingSetTerminated: return "LE Advertising Set Terminated Event" case .scanRequestReceived: return "LE Scan Request Received Event" case .channelSelectionAlgorithm: return "LE Channel Selection Algorithm Event" } } }
29cd2997a53d6340bce72d8df51fc982
37.485437
105
0.672553
false
false
false
false
frootloops/swift
refs/heads/master
benchmark/single-source/Exclusivity.swift
apache-2.0
4
//===--- Exclusivity.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 // //===----------------------------------------------------------------------===// // // A set of tests for measuring the enforcement overhead of memory access // exclusivity rules. // //===----------------------------------------------------------------------===// import TestsUtils public let Exclusivity = [ // At -Onone // 25% swift_beginAccess // 15% tlv_get_addr // 15% swift_endAccess BenchmarkInfo( name: "ExclusivityGlobal", runFunction: run_accessGlobal, tags: [.runtime, .cpubench] ), // At -Onone // 23% swift_retain // 22% swift_release // 9% swift_beginAccess // 3% swift_endAccess BenchmarkInfo( name: "ExclusivityInMatSet", runFunction: run_accessInMatSet, tags: [.runtime, .cpubench, .unstable] ), // At -Onone // 25% swift_release // 23% swift_retain // 16% swift_beginAccess // 8% swift_endAccess BenchmarkInfo( name: "ExclusivityIndependent", runFunction: run_accessIndependent, tags: [.runtime, .cpubench] ), ] // Initially these benchmarks only measure access checks at -Onone. In // the future, access checks will also be emitted at -O. // Measure memory access checks on a trivial global. // --- public var globalCounter: Int = 0 // TODO: // - Merge begin/endAccess when no calls intervene (~2x speedup). // - Move Swift runtime into the OS (~2x speedup). // - Whole module analysis can remove exclusivity checks (> 10x speedup now, 4x speedup with runtime in OS). // (The global's "public" qualifier should make the benchmark immune to this optimization.) @inline(never) public func run_accessGlobal(_ N: Int) { globalCounter = 0 for _ in 1...10000*N { globalCounter += 1 } CheckResults(globalCounter == 10000*N) } // Measure memory access checks on a class property. // // Note: The end_unpaired_access forces a callback on the property's // materializeForSet! // --- // Hopefully the optimizer will not see this as "final" and optimize away the // materializeForSet. public class C { var counter = 0 func inc() { counter += 1 } } // Thunk @inline(never) func updateClass(_ c: C) { c.inc() } // TODO: Replacing materializeForSet accessors with yield-once // accessors should make the callback overhead go away. @inline(never) public func run_accessInMatSet(_ N: Int) { let c = C() for _ in 1...10000*N { updateClass(c) } CheckResults(c.counter == 10000*N) } // Measure nested access to independent objects. // // A single access set is still faster than hashing for up to four accesses. // --- struct Var { var val = 0 } @inline(never) func update(a: inout Var, b: inout Var, c: inout Var, d: inout Var) { a.val += 1 b.val += 1 c.val += 1 d.val += 1 } @inline(never) public func run_accessIndependent(_ N: Int) { var a = Var() var b = Var() var c = Var() var d = Var() let updateVars = { update(a: &a, b: &b, c: &c, d: &d) } for _ in 1...1000*N { updateVars() } CheckResults(a.val == 1000*N && b.val == 1000*N && c.val == 1000*N && d.val == 1000*N) }
b37249ba0b380bf5c9294553ec8144a5
24.275362
108
0.62156
false
false
false
false
belkhadir/Beloved
refs/heads/master
Beloved/FriendSearchViewController.swift
mit
1
// // FriendSearchViewController.swift // Beloved // // Created by Anas Belkhadir on 21/01/2016. // Copyright © 2016 Anas Belkhadir. All rights reserved. // import UIKit import CoreData class FriendSearchViewController: UITableViewController{ @IBOutlet weak var activityIndicator: UIActivityIndicatorView! let searchController = UISearchController(searchResultsController: nil) var friendUsers = [Friend]() var currentUser: CurrentUserConnected? //it's make easy to know fetchAllFriendFromFirebase function start getting data from the server var startGettingFriendFromFirebase: Bool = false { didSet { if startGettingFriendFromFirebase { activityIndicator.startAnimating() activityIndicator.hidden = false }else{ activityIndicator.stopAnimating() activityIndicator.hidden = true } } } override func viewDidLoad() { super.viewDidLoad() self.activityIndicator.hidden = true self.activityIndicator.stopAnimating() navigationController?.navigationBar.topItem?.title = "Logout" navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Logout", style: .Plain, target: self, action: "logOut:") tableView.tableHeaderView = searchController.searchBar searchController.searchBar.delegate = self friendUsers = fetchedAllFriend() //if ther's no friend saved in CoreData look at his friend on the server if friendUsers.count == 0 { fetchAllFriendFromFirebase() } } //fetch all friend from the server func fetchAllFriendFromFirebase() { //Mark- start getting data from server startGettingFriendFromFirebase = true FirebaseHelper.sharedInstance().getAllCurrentUserFirends({ userIdKey in for element in self.friendUsers { if element.uid == userIdKey! { self.startGettingFriendFromFirebase = false return } } FirebaseHelper.sharedInstance().getSingleUser(userIdKey!, completionHandler: { (error, userFriend) in guard error == nil else{ self.startGettingFriendFromFirebase = false self.showAlert(.custom("erro occur", error!)) return } //The user friend was picked from the server //we need to make a new Friend. To be easy to save in CoreData //The easiest way to do that is to make a dictionary. let dictionary: [String : AnyObject] = [ Friend.Keys.username: userFriend!.userName!, Friend.Keys.uid: userIdKey!, ] // Insert the Friend on the main thread dispatch_async(dispatch_get_main_queue(), { //Init - Friend user let friendToBeAdd = Friend(parameter: dictionary, context: self.sharedContext) friendToBeAdd.currentUser = CurrentUser.sharedInstance().currentUserConnected! self.friendUsers.append(friendToBeAdd) self.tableView.reloadData() self.startGettingFriendFromFirebase = false //Save in the context CoreDataStackManager.sharedInstance().saveContext() }) }) }) startGettingFriendFromFirebase = false //Mark- finishing getting data from server } var sharedContext: NSManagedObjectContext { return CoreDataStackManager.sharedInstance().managedObjectContext } //fetch all friend from the CoreData func fetchedAllFriend() -> [Friend] { let fetchedRequest = NSFetchRequest(entityName: "Friend") let predicate = NSPredicate(format: "currentUser = %@", CurrentUser.sharedInstance().currentUserConnected!) fetchedRequest.predicate = predicate do { return try sharedContext.executeFetchRequest(fetchedRequest) as! [Friend] }catch _ { return [Friend]() } } func logOut() { FirebaseHelper.sharedInstance().messageRef.removeAllObservers() FirebaseHelper.sharedInstance().userRef.removeAllObservers() FirebaseHelper.sharedInstance().ref.unauth() //using presentViewController instead of pushViewController because: //when the first time user singUp and try to logout it's showing the //previews task . let nvg = storyboard?.instantiateViewControllerWithIdentifier("singInViewController") as! SingInViewController navigationController?.presentViewController(nvg, animated: true, completion: nil) } // MARK: - Table View override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return friendUsers.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("userCell") as! FriendSearchTableViewCell cell.user = friendUsers[indexPath.row] cell.delegate = self return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let selectedUser = friendUsers[indexPath.row] let listOfMessageVC = self.storyboard?.instantiateViewControllerWithIdentifier("StartchattingViewController") as! StartChattingViewController listOfMessageVC.friend = selectedUser listOfMessageVC.senderId = CurrentUser.sharedInstance().user?.userName dispatch_async(dispatch_get_main_queue(), { self.navigationController?.pushViewController(listOfMessageVC, animated: true) }) } } extension FriendSearchViewController: FriendSearchTableViewCellDelegate { func cell(cell: FriendSearchTableViewCell, didSelectFriendUser user: Friend) { FirebaseHelper.sharedInstance().canBecomeFirend(user.uid!, willAccept: true, willBecomeFriend: { (_,_) in }) } func cell(cell: FriendSearchTableViewCell, didSelectUnFriendUser user: Friend){ FirebaseHelper.sharedInstance().canBecomeFirend(user.uid!, willAccept: false, willBecomeFriend:{ _,_ in }) } } extension FriendSearchViewController: UISearchBarDelegate{ func searchBarSearchButtonClicked(searchBar: UISearchBar) { if !isConnectedToNetwork() { showAlert(.connectivity) return } activityIndicator.startAnimating() activityIndicator.hidden = false let lowercaseSearchBarText = searchBar.text?.lowercaseString // Check to see if we already have this friend . If so , return if let _ = friendUsers.indexOf({$0.username == lowercaseSearchBarText}) { return } FirebaseHelper.sharedInstance().searchByUserName(lowercaseSearchBarText!, didPickUser: { (exist, user) in if exist { // Insert the Friend on the main thread dispatch_async(dispatch_get_main_queue()) { //init the friend user let userFriend = Friend(parameter: user!, context: self.sharedContext) //Mark - relation userFriend.currentUser = CurrentUser.sharedInstance().currentUserConnected! // append friendUser to array self.friendUsers.insert(userFriend, atIndex: 0) self.tableView.reloadData() // Save the context. do { try self.sharedContext.save() } catch _ {} } } self.activityIndicator.hidden = true self.activityIndicator.stopAnimating() }) } }
e23819d53639c9d0d8145cd8254cff57
30.773723
149
0.583735
false
false
false
false
MaddTheSane/WWDC
refs/heads/master
WWDC/VideoStore.swift
bsd-2-clause
1
// // VideoDownloader.swift // WWDC // // Created by Guilherme Rambo on 22/04/15. // Copyright (c) 2015 Guilherme Rambo. All rights reserved. // import Cocoa public let VideoStoreDownloadedFilesChangedNotification = "VideoStoreDownloadedFilesChangedNotification" public let VideoStoreNotificationDownloadStarted = "VideoStoreNotificationDownloadStarted" public let VideoStoreNotificationDownloadCancelled = "VideoStoreNotificationDownloadCancelled" public let VideoStoreNotificationDownloadPaused = "VideoStoreNotificationDownloadPaused" public let VideoStoreNotificationDownloadResumed = "VideoStoreNotificationDownloadResumed" public let VideoStoreNotificationDownloadFinished = "VideoStoreNotificationDownloadFinished" public let VideoStoreNotificationDownloadProgressChanged = "VideoStoreNotificationDownloadProgressChanged" private let _SharedVideoStore = VideoStore() private let _BackgroundSessionIdentifier = "WWDC Video Downloader" class VideoStore : NSObject, NSURLSessionDownloadDelegate { private let configuration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(_BackgroundSessionIdentifier) private var backgroundSession: NSURLSession! private var downloadTasks: [String : NSURLSessionDownloadTask] = [:] private let defaults = NSUserDefaults.standardUserDefaults() class func SharedStore() -> VideoStore { return _SharedVideoStore; } override init() { super.init() backgroundSession = NSURLSession(configuration: configuration, delegate: self, delegateQueue: NSOperationQueue.mainQueue()) } func initialize() { backgroundSession.getTasksWithCompletionHandler { _, _, pendingTasks in for task in pendingTasks { if let key = task.originalRequest?.URL!.absoluteString { self.downloadTasks[key] = task } } } NSNotificationCenter.defaultCenter().addObserverForName(LocalVideoStoragePathPreferenceChangedNotification, object: nil, queue: nil) { _ in self.monitorDownloadsFolder() NSNotificationCenter.defaultCenter().postNotificationName(VideoStoreDownloadedFilesChangedNotification, object: nil) } monitorDownloadsFolder() } // MARK: Public interface func allTasks() -> [NSURLSessionDownloadTask] { return Array(self.downloadTasks.values) } func download(url: String) { if isDownloading(url) || hasVideo(url) { return } let task = backgroundSession.downloadTaskWithURL(NSURL(string: url)!) if let key = task.originalRequest?.URL!.absoluteString { self.downloadTasks[key] = task } task.resume() NSNotificationCenter.defaultCenter().postNotificationName(VideoStoreNotificationDownloadStarted, object: url) } func pauseDownload(url: String) -> Bool { if let task = downloadTasks[url] { task.suspend() NSNotificationCenter.defaultCenter().postNotificationName(VideoStoreNotificationDownloadPaused, object: url) return true } print("VideoStore was asked to pause downloading URL \(url), but there's no task for that URL") return false } func resumeDownload(url: String) -> Bool { if let task = downloadTasks[url] { task.resume() NSNotificationCenter.defaultCenter().postNotificationName(VideoStoreNotificationDownloadResumed, object: url) return true } print("VideoStore was asked to resume downloading URL \(url), but there's no task for that URL") return false } func cancelDownload(url: String) -> Bool { if let task = downloadTasks[url] { task.cancel() self.downloadTasks.removeValueForKey(url) NSNotificationCenter.defaultCenter().postNotificationName(VideoStoreNotificationDownloadCancelled, object: url) return true } print("VideoStore was asked to cancel downloading URL \(url), but there's no task for that URL") return false } func isDownloading(url: String) -> Bool { let downloading = downloadTasks.keys.filter { taskURL in return url == taskURL } return (downloading.count > 0) } func localVideoPath(remoteURL: String) -> String { return (Preferences.SharedPreferences().localVideoStoragePath as NSString).stringByAppendingPathComponent((remoteURL as NSString).lastPathComponent) } func localVideoAbsoluteURLString(remoteURL: String) -> String { return NSURL(fileURLWithPath: localVideoPath(remoteURL)).absoluteString } func hasVideo(url: String) -> Bool { return (NSFileManager.defaultManager().fileExistsAtPath(localVideoPath(url))) } // MARK: URL Session func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) { let originalURL = downloadTask.originalRequest!.URL! let originalAbsoluteURLString = originalURL.absoluteString let fileManager = NSFileManager.defaultManager() if (fileManager.fileExistsAtPath(Preferences.SharedPreferences().localVideoStoragePath) == false) { do { try fileManager.createDirectoryAtPath(Preferences.SharedPreferences().localVideoStoragePath, withIntermediateDirectories: false, attributes: nil) } catch _ { } } let localURL = NSURL(fileURLWithPath: localVideoPath(originalAbsoluteURLString)) do { try fileManager.moveItemAtURL(location, toURL: localURL) WWDCDatabase.sharedDatabase.updateDownloadedStatusForSessionWithURL(originalAbsoluteURLString, downloaded: true) } catch _ { print("VideoStore was unable to move \(location) to \(localURL)") } downloadTasks.removeValueForKey(originalAbsoluteURLString) NSNotificationCenter.defaultCenter().postNotificationName(VideoStoreNotificationDownloadFinished, object: originalAbsoluteURLString) } func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { let originalURL = downloadTask.originalRequest!.URL!.absoluteString let info = ["totalBytesWritten": Int(totalBytesWritten), "totalBytesExpectedToWrite": Int(totalBytesExpectedToWrite)] NSNotificationCenter.defaultCenter().postNotificationName(VideoStoreNotificationDownloadProgressChanged, object: originalURL, userInfo: info) } // MARK: File observation private var folderMonitor: DTFolderMonitor! private var existingVideoFiles = [String]() func monitorDownloadsFolder() { if folderMonitor != nil { folderMonitor.stopMonitoring() folderMonitor = nil } let videosPath = Preferences.SharedPreferences().localVideoStoragePath enumerateVideoFiles(videosPath) folderMonitor = DTFolderMonitor(forURL: NSURL(fileURLWithPath: videosPath)) { self.enumerateVideoFiles(videosPath) NSNotificationCenter.defaultCenter().postNotificationName(VideoStoreDownloadedFilesChangedNotification, object: nil) } folderMonitor.startMonitoring() } /// Updates the downloaded status for the sessions on the database based on the existence of the downloaded video file private func enumerateVideoFiles(path: String) { guard let enumerator = NSFileManager.defaultManager().enumeratorAtPath(path) else { return } guard let files = enumerator.allObjects as? [String] else { return } // existing/added files for file in files { WWDCDatabase.sharedDatabase.updateDownloadedStatusForSessionWithLocalFileName(file, downloaded: true) } if existingVideoFiles.count == 0 { existingVideoFiles = files return } // removed files let removedFiles = existingVideoFiles.filter { !files.contains($0) } for file in removedFiles { WWDCDatabase.sharedDatabase.updateDownloadedStatusForSessionWithLocalFileName(file, downloaded: false) } } // MARK: Teardown deinit { if folderMonitor != nil { folderMonitor.stopMonitoring() } } }
69121b048f9444482286c16070db37af
38.231481
178
0.705688
false
false
false
false
krevi27/TestExerciseProject
refs/heads/master
TestStudyExerciseTests/CotacaoTests.swift
mit
1
// // CotacaoTests.swift // TestStudyExerciseTests // // Created by Marcos Fellipe Costa Silva on 19/10/17. // Copyright © 2017 Victor Oliveira Kreniski. All rights reserved. // import XCTest class CotacaoTests: XCTestCase { func testGetDolar(){ var retorno = "" let expect = XCTestExpectation(description: "Teste de integração") let url = URL(string: "http://api.promasters.net.br/cotacao/v1/valores?moedas=USD&alt=json") URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in expect.fulfill() guard let data = data, error == nil else { return } do { let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any] let dados = json["valores"] as! [String: Any] let moeda = dados["USD"] as! [String: Any] let valor = moeda["valor"] retorno = valor! as! String print(retorno) XCTAssert(!retorno.isEmpty, "") } catch let error as NSError { print(error) } }).resume() self.wait(for: [expect], timeout: 6) } }
f7d4277c8b296670ade6af7539af81a0
33.444444
114
0.568548
false
true
false
false
MobileToolkit/UIKitExtensions
refs/heads/master
Sources/UIColor+HexColor.swift
mit
1
// // UIColor+HexColor.swift // UIKitExtensions // // Created by Sebastian Owodzin on 04/08/2016. // Copyright © 2016 mobiletoolkit.org. All rights reserved. // import UIKit extension UIColor { public convenience init(rgba: UInt32) { let red = CGFloat((rgba & 0xFF000000) >> 24)/255 let green = CGFloat((rgba & 0xFF0000) >> 16)/255 let blue = CGFloat((rgba & 0xFF00) >> 8)/255 let alpha = CGFloat(rgba & 0xFF)/255 self.init(red: red, green: green, blue: blue, alpha: alpha) } public convenience init(argb: UInt32) { let alpha = CGFloat((argb & 0xFF000000) >> 24)/255 let red = CGFloat((argb & 0xFF0000) >> 16)/255 let green = CGFloat((argb & 0xFF00) >> 8)/255 let blue = CGFloat(argb & 0xFF)/255 self.init(red: red, green: green, blue: blue, alpha: alpha) } public convenience init(rgb: UInt32) { let red = CGFloat((rgb & 0xFF0000) >> 16)/255 let green = CGFloat((rgb & 0xFF00) >> 8)/255 let blue = CGFloat(rgb & 0xFF)/255 self.init(red: red, green: green, blue: blue, alpha: 1.0) } public convenience init(rgbaString: String) { let hexString = rgbaString.trimmingCharacters(in: CharacterSet.whitespaces) let scanner = Scanner(string: hexString) if hexString.hasPrefix("#") { scanner.scanLocation = 1 } var color: UInt32 = 0 scanner.scanHexInt32(&color) self.init(rgba: color) } public convenience init(argbString: String) { let hexString = argbString.trimmingCharacters(in: CharacterSet.whitespaces) let scanner = Scanner(string: hexString) if hexString.hasPrefix("#") { scanner.scanLocation = 1 } var color: UInt32 = 0 scanner.scanHexInt32(&color) self.init(argb: color) } public convenience init(rgbString: String) { let hexString = rgbString.trimmingCharacters(in: CharacterSet.whitespaces) let scanner = Scanner(string: hexString) if hexString.hasPrefix("#") { scanner.scanLocation = 1 } var color: UInt32 = 0 scanner.scanHexInt32(&color) self.init(rgb: color) } }
692a0118a85b21f231c31cb4fd651b19
26.888889
83
0.602922
false
false
false
false
LeoNatan/LNPopupController
refs/heads/master
LNPopupControllerExample/LNPopupControllerExample/ManualLayoutCustomBarViewController.swift
mit
1
// // ManualLayoutCustomBarViewController.swift // LNPopupControllerExample // // Created by Leo Natan on 9/1/20. // Copyright © 2015-2021 Leo Natan. All rights reserved. // #if LNPOPUP class ManualLayoutCustomBarViewController: LNPopupCustomBarViewController { let centeredButton = UIButton(type: .system) let leftButton = UIButton(type: .system) let backgroundView = UIVisualEffectView(effect: UIBlurEffect(style: .systemChromeMaterial)) override func viewDidLoad() { super.viewDidLoad() backgroundView.layer.masksToBounds = true backgroundView.layer.cornerCurve = .continuous backgroundView.layer.cornerRadius = 15 view.addSubview(backgroundView) centeredButton.setTitle("Centered", for: .normal) centeredButton.titleLabel?.font = UIFont.preferredFont(forTextStyle: .headline) centeredButton.sizeToFit() view.addSubview(centeredButton) leftButton.setTitle("<- Left", for: .normal) leftButton.titleLabel?.font = UIFont.preferredFont(forTextStyle: .headline) leftButton.sizeToFit() view.addSubview(leftButton) preferredContentSize = CGSize(width: 0, height: 50) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() backgroundView.frame = view.bounds.insetBy(dx: view.layoutMargins.left, dy: 0) centeredButton.center = view.center leftButton.frame = CGRect(x: view.layoutMargins.left + 20, y: view.center.y - leftButton.bounds.size.height / 2, width: leftButton.bounds.size.width, height: leftButton.bounds.size.height) } override var wantsDefaultTapGestureRecognizer: Bool { return false } override var wantsDefaultPanGestureRecognizer: Bool { return false } override var wantsDefaultHighlightGestureRecognizer: Bool { return false } } #endif
0e32573791baa5aef931fedda2171bfa
30.214286
190
0.768879
false
false
false
false
xivol/MCS-V3-Mobile
refs/heads/master
examples/graphics/ViewAnimation.playground/Pages/Untitled Page.xcplaygroundpage/Contents.swift
mit
1
// https://github.com/shu223/iOS-10-Sampler/blob/master/iOS-10-Sampler/Samples/PropertyAnimatorViewController.swift // // PropertyAnimatorViewController.swift // Created by Shuichi Tsutsumi on 9/10/16. // Copyright © 2016 Shuichi Tsutsumi. All rights reserved. // import UIKit import PlaygroundSupport class PropertyAnimatorViewController: UIViewController { private var targetLocation: CGPoint! private var objectView: UIView! private let spring = true override func viewDidLoad() { super.viewDidLoad() objectView = UIView(frame: CGRect(origin: view.bounds.origin, size: CGSize(width: 50, height: 50))) objectView.backgroundColor = colorAt(location: objectView.center) view.addSubview(objectView) targetLocation = objectView.center } private func colorAt(location: CGPoint) -> UIColor { let hue: CGFloat = (location.x / UIScreen.main.bounds.width + location.y / UIScreen.main.bounds.height) / 2 return UIColor(hue: hue, saturation: 0.78, brightness: 0.75, alpha: 1) } private func processTouches(_ touches: Set<UITouch>) { guard let touch = touches.first else {return} let loc = touch.location(in: view) if loc == targetLocation { return } animateTo(location: loc) } private func animateTo(location: CGPoint) { var duration: TimeInterval var timing: UITimingCurveProvider if !spring { duration = 0.4 timing = UICubicTimingParameters(animationCurve: .easeOut) } else { duration = 0.6 timing = UISpringTimingParameters(dampingRatio: 0.5) } let animator = UIViewPropertyAnimator( duration: duration, timingParameters: timing) animator.addAnimations { self.objectView.center = location self.objectView.backgroundColor = self.colorAt(location: location) } animator.startAnimation() targetLocation = location } // ========================================================================= // MARK: - Touch handlers override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { processTouches(touches) } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { processTouches(touches) } } // Present the view controller in the Live View window PlaygroundPage.current.liveView = PropertyAnimatorViewController()
ccdcfde97a1e742b6407724e6d50bb38
32.448718
116
0.620161
false
false
false
false
quaertym/Shark
refs/heads/master
Shark.swift
mit
1
#!/usr/bin/env xcrun -sdk macosx swift import Foundation struct EnumBuilder { private enum Resource { case File(String) case Directory((String, [Resource])) } private static let forbiddenCharacterSet: NSCharacterSet = { let validSet = NSMutableCharacterSet(charactersInString: "_") validSet.formUnionWithCharacterSet(NSCharacterSet.letterCharacterSet()) return validSet.invertedSet }() static func enumStringForPath(path: String, topLevelName: String = "Shark") throws -> String { let resources = try imageResourcesAtPath(path) if resources.isEmpty { return "" } let topLevelResource = Resource.Directory(topLevelName, resources) return createEnumDeclarationForResources([topLevelResource], indentLevel: 0) } private static func imageResourcesAtPath(path: String) throws -> [Resource] { var results = [Resource]() let URL = NSURL.fileURLWithPath(path) let contents = try NSFileManager.defaultManager().contentsOfDirectoryAtURL(URL, includingPropertiesForKeys: [NSURLNameKey, NSURLIsDirectoryKey], options: NSDirectoryEnumerationOptions.SkipsHiddenFiles) for fileURL in contents { var directoryKey: AnyObject? try fileURL.getResourceValue(&directoryKey, forKey: NSURLIsDirectoryKey) guard let isDirectory = directoryKey as? NSNumber else { continue } if isDirectory.integerValue == 1 { if fileURL.absoluteString.hasSuffix(".imageset/") { let name = fileURL.lastPathComponent!.componentsSeparatedByString(".imageset")[0] results.append(.File(name)) } else if !fileURL.absoluteString.hasSuffix(".appiconset/") { let folderName = fileURL.lastPathComponent! let subResources = try imageResourcesAtPath(fileURL.relativePath!) results.append(.Directory((folderName, subResources))) } } } return results } private static func correctedNameForString(string: String) -> String? { //First try replacing -'s with _'s only, then remove illegal characters if let _ = string.rangeOfString("-") { let replacedString = string.stringByReplacingOccurrencesOfString("-", withString: "_") if replacedString.rangeOfCharacterFromSet(forbiddenCharacterSet) == nil { return replacedString } } if let _ = string.rangeOfCharacterFromSet(forbiddenCharacterSet) { return "".join(string.componentsSeparatedByCharactersInSet(forbiddenCharacterSet)) } return nil } //An enum should extend String and conform to SharkImageConvertible if and only if it has at least on image asset in it. //We return empty string when we get a Directory of directories. private static func conformanceStringForResource(resource: Resource) -> String { switch resource { case .Directory(_, let subResources): let index = subResources.indexOf({ if case .File = $0 { return true } else { return false } }) if let _ = index { return ": String, SharkImageConvertible" } else { return "" } case _: return "" } } private static func createEnumDeclarationForResources(resources: [Resource], indentLevel: Int) -> String { let sortedResources = resources.sort { first, _ in if case .Directory = first { return true } return false } var resultString = "" for singleResource in sortedResources { switch singleResource { case .File(let name): print("Creating Case: \(name)") let indentationString = String(count: 4 * (indentLevel + 1), repeatedValue: Character(" ")) if let correctedName = correctedNameForString(name) { resultString += indentationString + "case \(correctedName) = \"\(name)\"\n" } else { resultString += indentationString + "case \(name)\n" } case .Directory(let (name, subResources)): let correctedName = name.stringByReplacingOccurrencesOfString(" ", withString: "") print("Creating Enum: \(correctedName)") let indentationString = String(count: 4 * (indentLevel), repeatedValue: Character(" ")) resultString += "\n" + indentationString + "public enum \(correctedName)" + conformanceStringForResource(singleResource) + " {" + "\n" resultString += createEnumDeclarationForResources(subResources, indentLevel: indentLevel + 1) resultString += indentationString + "}\n\n" } } return resultString } } struct FileBuilder { static func fileStringWithEnumString(enumString: String) -> String { return acknowledgementsString() + "\n\n" + importString() + "\n\n" + imageExtensionString() + "\n" + enumString } private static func importString() -> String { return "import UIKit" } private static func acknowledgementsString() -> String { return "//SharkImageNames.swift\n//Generated by Shark" } private static func imageExtensionString() -> String { return "public protocol SharkImageConvertible {}\n\npublic extension SharkImageConvertible where Self: RawRepresentable, Self.RawValue == String {\n public var image: UIImage? {\n return UIImage(named: self.rawValue)\n }\n}\n\npublic extension UIImage {\n convenience init?<T: RawRepresentable where T.RawValue == String>(shark: T) {\n self.init(named: shark.rawValue)\n }\n}\n" } } //-----------------------------------------------------------// //-----------------------------------------------------------// //Process arguments and run the script let arguments = Process.arguments if arguments.count != 3 { print("You must supply the path to the .xcassets folder, and the output path for the Shark file") print("\n\nExample Usage:\nswift Shark.swift /Users/john/Code/GameProject/GameProject/Images.xcassets/ /Users/john/Code/GameProject/GameProject/") exit(1) } let path = arguments[1] if !(path.hasSuffix(".xcassets") || path.hasSuffix(".xcassets/")) { print("The path should point to a .xcassets folder") exit(1) } let outputPath = arguments[2] var isDirectory: ObjCBool = false if NSFileManager.defaultManager().fileExistsAtPath(outputPath, isDirectory: &isDirectory) == false { print("The output path does not exist") exit(1) } if !isDirectory{ print("The output path is not a valid directory") exit(1) } //Create the file string let enumString = try EnumBuilder.enumStringForPath(path) let fileString = FileBuilder.fileStringWithEnumString(enumString) //Save the file string let outputURL = NSURL.fileURLWithPath(outputPath).URLByAppendingPathComponent("SharkImages.swift") try fileString.writeToURL(outputURL, atomically: true, encoding: NSUTF8StringEncoding)
20f7745ab2e2260c2b7adabd27518b1a
39.797814
412
0.615137
false
false
false
false
instant-solutions/ISTimeline
refs/heads/master
ISTimeline/ISTimeline/ISPoint.swift
apache-2.0
1
// // ISPoint.swift // ISTimeline // // Created by Max Holzleitner on 13.05.16. // Copyright © 2016 instant:solutions. All rights reserved. // import UIKit open class ISPoint { open var title:String open var description:String? open var pointColor:UIColor open var lineColor:UIColor open var touchUpInside:Optional<(_ point:ISPoint) -> Void> open var fill:Bool public init(title:String, description:String, pointColor:UIColor, lineColor:UIColor, touchUpInside:Optional<(_ point:ISPoint) -> Void>, fill:Bool) { self.title = title self.description = description self.pointColor = pointColor self.lineColor = lineColor self.touchUpInside = touchUpInside self.fill = fill } public convenience init(title:String, description:String, touchUpInside:Optional<(_ point:ISPoint) -> Void>) { let defaultColor = UIColor.init(red: 0.75, green: 0.75, blue: 0.75, alpha: 1.0) self.init(title: title, description: description, pointColor: defaultColor, lineColor: defaultColor, touchUpInside: touchUpInside, fill: false) } public convenience init(title:String, touchUpInside:Optional<(_ point:ISPoint) -> Void>) { self.init(title: title, description: "", touchUpInside: touchUpInside) } public convenience init(title:String) { self.init(title: title, touchUpInside: nil) } }
50a11d44d90ab9fb387ad9b9eae37636
33.780488
152
0.677419
false
false
false
false
TTVS/NightOut
refs/heads/master
Clubber/AFNetworking Usage Lines.swift
apache-2.0
1
// SwiftyJSON nicely wraps the result of the Alamofire JSON response handler: //Alamofire.request(.GET, url, parameters: parameters) // .responseJSON { (req, res, json, error) in // if(error != nil) { // NSLog("Error: \(error)") // println(req) // println(res) // } // else { // NSLog("Success: \(url)") // var json = JSON(json!) // } //} // COPY OF REQUEST (GET) //func makeSignInRequest() { // let manager = AFHTTPRequestOperationManager() // let url = "https://nightout.herokuapp.com/api/v1/" // let parameter = nil // // manager.requestSerializer = AFJSONRequestSerializer() // // manager.GET(url, // parameters: nil, // success: { (operation: AFHTTPRequestOperation!,responseObject: AnyObject!) in // print("JSON: " + responseObject.description) // // let paperNavController: UIViewController = self.storyboard!.instantiateViewControllerWithIdentifier("RootPaperNavigationVC") // self.presentViewController(paperNavController, animated: true, completion: nil) // // let successMenu = UIAlertController(title: nil, message: "Successfully get from server", preferredStyle: UIAlertControllerStyle.Alert) // let okAction = UIAlertAction(title: "Ok", style: .Cancel, handler: { // (alert: UIAlertAction) -> Void in // print("Success") // }) // successMenu.addAction(okAction) // // self.presentViewController(successMenu, animated: true, completion: nil) // // }, // failure: { (operation: AFHTTPRequestOperation!,error: NSError!) in // print("Error: " + error.localizedDescription) // // // let errorMenu = UIAlertController(title: nil, message: "Failed to get from server.", preferredStyle: UIAlertControllerStyle.Alert) // let okAction = UIAlertAction(title: "Ok", style: .Cancel, handler: { // (alert: UIAlertAction) -> Void in // print("Cancelled") // }) // errorMenu.addAction(okAction) // // self.presentViewController(errorMenu, animated: true, completion: nil) // }) // // // // COPY OF RESPONSE (POST) //func makeSignUpRequest() { // let manager = AFHTTPRequestOperationManager() // let url = "https://nightout.herokuapp.com/api/v1/users?" // let signUpParams = [ // "user[email]" : "\(emailTextField.text!)", // "user[password]" : "\(passwordTextField.text!)", // "user[password_confirmation]" : "\(passwordConfirmationTextField.text!)", // "user[first_name]" : "\(firstNameTextField.text!)", // "user[last_name]" : "\(lastNameTextField.text!)", // "user[type]" : "Guest" // ] // // print("\(emailTextField.text)") // print("\(passwordTextField.text)") // print("\(passwordConfirmationTextField.text)") // print("\(firstNameTextField.text)") // print("\(lastNameTextField.text)") // // manager.responseSerializer = AFJSONResponseSerializer() // // manager.POST(url, // parameters: signUpParams, // success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in // print("Yes this was a success.. \(responseObject.description)") // // self.displayAlertMessage("Success", alertDescription: "Account has been created") // // let paperNavController: UIViewController = self.storyboard!.instantiateViewControllerWithIdentifier("signInVC") // self.presentViewController(paperNavController, animated: true, completion: nil) // // }, // failure: { (operation: AFHTTPRequestOperation!, error: NSError!) in // print("We got an error here.. \(error.localizedDescription)") // }) //} // // // // // //[self GET:@"weather.ashx" parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) { // if ([self.delegate respondsToSelector:@selector(weatherHTTPClient:didUpdateWithWeather:)]) { // [self.delegate weatherHTTPClient:self didUpdateWithWeather:responseObject]; // } //} failure:^(NSURLSessionDataTask *task, NSError *error) { // if ([self.delegate respondsToSelector:@selector(weatherHTTPClient:didFailWithError:)]) { // [self.delegate weatherHTTPClient:self didFailWithError:error]; // } //}]; // ///////////////////////////// // //- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex //{ // if (buttonIndex == [actionSheet cancelButtonIndex]) { // // User pressed cancel -- abort // return; // } // // // 1 // NSURL *baseURL = [NSURL URLWithString:BaseURLString]; // NSDictionary *parameters = @{@"format": @"json"}; // // // 2 // AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:baseURL]; // manager.responseSerializer = [AFJSONResponseSerializer serializer]; // // // 3 //if (buttonIndex == 0) { // [manager GET:@"weather.php" parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) { // self.weather = responseObject; // self.title = @"HTTP GET"; // [self.tableView reloadData]; // } failure:^(NSURLSessionDataTask *task, NSError *error) { // UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather" // message:[error localizedDescription] // delegate:nil // cancelButtonTitle:@"Ok" // otherButtonTitles:nil]; // [alertView show]; // }]; //} // // // //
c11ac747a07e747d86e90100ce5b9f20
33.608434
148
0.604178
false
false
false
false
microtherion/Octarine
refs/heads/master
Octarine/OctTree.swift
bsd-2-clause
1
// // OctTree.swift // Octarine // // Created by Matthias Neeracher on 20/04/16. // Copyright © 2016 Matthias Neeracher. All rights reserved. // import AppKit let kOctPasteboardType = "OctPasteboardType" var gOctTreeRoots = [OctTreeNode]() class OctTreeNode : NSObject { var parent : OctTreeNode? let item : OctItem let path : NSIndexPath private init(parent: OctTreeNode?, index: Int) { self.parent = parent let parentItem = parent?.item ?? OctItem.rootFolder() self.item = parentItem.children![index] as! OctItem self.path = parent?.path.indexPathByAddingIndex(index) ?? NSIndexPath(index: index) super.init() } var isExpandable : Bool { return !item.isPart } var numberOfChildren : Int { return item.children?.count ?? 0 } var parentItem : OctItem { return parent?.item ?? OctItem.rootFolder() } var persistentIdentifier : String { return item.ident + "[" + parentItem.ident + "]" } class func numberOfRootItems() -> Int { if gOctTreeRoots.count == 0 { // Lazy initialization if let roots = OctItem.rootFolder().children { for index in 0..<roots.count { gOctTreeRoots.append(OctTreeNode(parent: nil, index: index)) } } } return gOctTreeRoots.count } class func rootItem(index: Int) -> OctTreeNode { return gOctTreeRoots[index] } var children = [OctTreeNode]() func child(index: Int) -> OctTreeNode { if children.count == 0 { // Lazy initialization for index in 0..<numberOfChildren { children.append(OctTreeNode(parent: self, index: index)) } } return children[index] } func isDescendantOf(node: OctTreeNode) -> Bool { if self == node { return true } else if path.length <= node.path.length { return false } else { return parent!.isDescendantOf(node) } } func isDescendantOfOneOf(nodes: [OctTreeNode]) -> Bool { for node in nodes { if isDescendantOf(node) { return true } } return false } func removeFromParent() { parentItem.mutableOrderedSetValueForKey("children").removeObject(item) } func deleteIfOrphaned() { if item.parents.count == 0 { item.managedObjectContext?.deleteObject(item) } } class func mapNode(node: OctTreeNode, f : (OctTreeNode) -> Bool) { if f(node) { for i in 0..<node.numberOfChildren { mapNode(node.child(i), f: f) } } } class func map(f : (OctTreeNode) -> Bool) { for i in 0..<numberOfRootItems() { mapNode(rootItem(i), f: f) } } } var OCT_FOLDER : NSImage? var OCT_PART : NSImage? class OctTree : NSObject, NSOutlineViewDataSource, NSOutlineViewDelegate { @IBOutlet weak var outline : NSOutlineView! @IBOutlet weak var search: OctSearch! @IBOutlet weak var details: OctDetails! @IBOutlet weak var sheets: OctSheets! @IBOutlet weak var octApp : OctApp! override func awakeFromNib() { outline.registerForDraggedTypes([kOctPasteboardType]) outline.setDraggingSourceOperationMask([.Move, .Copy], forLocal: true) outline.setDraggingSourceOperationMask([.Delete], forLocal: false) NSNotificationCenter.defaultCenter().addObserverForName(OCTARINE_DATABASE_RESET, object: nil, queue: NSOperationQueue.mainQueue()) { (_: NSNotification) in gOctTreeRoots = [] self.outline.reloadData() } } var oldTreeRoots = [OctTreeNode]() func reloadTree(expanding item: OctTreeNode? = nil) { var expandedGroups = [String]() for row in 0..<outline.numberOfRows { if outline.isItemExpanded(outline.itemAtRow(row)) { expandedGroups.append((outline.itemAtRow(row) as! OctTreeNode).persistentIdentifier) } } if let item=item { let identifier = item.persistentIdentifier if !expandedGroups.contains(identifier) { expandedGroups.append(identifier) } } oldTreeRoots = gOctTreeRoots gOctTreeRoots = [] outline.reloadData() OctTreeNode.map() { (group: OctTreeNode) -> Bool in if expandedGroups.contains(group.persistentIdentifier) { self.outline.expandItem(group) return true } else { return false } } } @IBAction func newGroup(sender: AnyObject) { let selectedNode = outline.itemAtRow(outline.selectedRowIndexes.firstIndex) as? OctTreeNode let parentItem = selectedNode?.parent?.item ?? OctItem.rootFolder() let insertAt : Int if let path = selectedNode?.path { insertAt = path.indexAtPosition(path.length-1)+sender.tag() } else { insertAt = parentItem.children?.count ?? 0 } let group = OctItem.createFolder("") group.name = "New Group "+group.ident.substringToIndex(group.ident.startIndex.advancedBy(6)) var contents = [OctTreeNode]() if sender.tag()==0 { for row in outline.selectedRowIndexes { contents.append(outline.itemAtRow(row) as! OctTreeNode) } } outline.beginUpdates() let kids = parentItem.mutableOrderedSetValueForKey("children") kids.insertObject(group, atIndex: insertAt) let groupKids = group.mutableOrderedSetValueForKey("children") for node in contents { node.removeFromParent() groupKids.addObject(node.item) } outline.endUpdates() reloadTree() OctTreeNode.map { (node: OctTreeNode) -> Bool in if node.item == group { self.outline.editColumn(0, row: self.outline.rowForItem(node), withEvent: nil, select: true) return false } else { return !node.item.isPart } } } func newCustomPart(part: OctItem) { let selectedNode = outline.itemAtRow(outline.selectedRowIndexes.firstIndex) as? OctTreeNode let parentItem = selectedNode?.parent?.item ?? OctItem.rootFolder() let insertAt : Int if let path = selectedNode?.path { insertAt = path.indexAtPosition(path.length-1)+1 } else { insertAt = parentItem.children?.count ?? 0 } outline.beginUpdates() let kids = parentItem.mutableOrderedSetValueForKey("children") kids.insertObject(part, atIndex: insertAt) outline.endUpdates() reloadTree() OctTreeNode.map { (node: OctTreeNode) -> Bool in if node.item == part { self.outline.selectRowIndexes(NSIndexSet(index: self.outline.rowForItem(node)), byExtendingSelection: false) } return !node.item.isPart } } func outlineView(outlineView: NSOutlineView, persistentObjectForItem item: AnyObject?) -> AnyObject? { return (item as? OctTreeNode)?.persistentIdentifier } func outlineView(outlineView: NSOutlineView, itemForPersistentObject object: AnyObject) -> AnyObject? { if let identifier = object as? String { var found : OctTreeNode? OctTreeNode.map() { (node: OctTreeNode) -> Bool in guard found==nil else { return false } if node.persistentIdentifier == identifier { found = node return false } else { return true } } return found } else { return nil } } func outlineView(outlineView: NSOutlineView, isItemExpandable item: AnyObject) -> Bool { return (item as! OctTreeNode).isExpandable } func outlineView(outlineView: NSOutlineView, numberOfChildrenOfItem item: AnyObject?) -> Int { return (item as? OctTreeNode)?.numberOfChildren ?? OctTreeNode.numberOfRootItems() } func outlineView(outlineView: NSOutlineView, child index: Int, ofItem item: AnyObject?) -> AnyObject { if let node = item as? OctTreeNode { return node.child(index) } else { return OctTreeNode.rootItem(index) } } func outlineView(outlineView: NSOutlineView, objectValueForTableColumn tableColumn: NSTableColumn?, byItem item: AnyObject?) -> AnyObject? { guard let tableColumn = tableColumn else { return nil } guard let octItem = (item as? OctTreeNode)?.item else { return nil } switch tableColumn.identifier { case "name": return octItem.name case "desc": return octItem.desc default: return nil } } @IBAction func updateOutlineValue(sender: AnyObject) { guard let view = sender as? NSView else { return } let row = outline.rowForView(view) let col = outline.columnForView(view) guard let octItem = (outline.itemAtRow(row) as? OctTreeNode)?.item else { return } guard let value = (sender as? NSTextField)?.stringValue else { return } let tableColumn = outline.tableColumns[col] switch tableColumn.identifier { case "name": octItem.name = value case "desc": octItem.desc = value default: break } outlineViewSelectionDidChange(NSNotification(name:"dummy", object:self)) } func outlineView(outlineView: NSOutlineView, viewForTableColumn tableColumn: NSTableColumn?, item: AnyObject) -> NSView? { guard let tableColumn = tableColumn else { return nil } let view = outlineView.makeViewWithIdentifier(tableColumn.identifier, owner: self) as! NSTableCellView guard let octItem = (item as? OctTreeNode)?.item else { return nil } switch tableColumn.identifier { case "name": if OCT_FOLDER == nil { let frameSize = view.imageView!.frame.size OCT_FOLDER = NSImage(named: "oct_folder") let folderSize = OCT_FOLDER!.size OCT_FOLDER!.size = NSMakeSize(folderSize.width*(frameSize.height/folderSize.height), frameSize.height) OCT_PART = NSImage(named: "oct_part") let partSize = OCT_PART!.size OCT_PART!.size = NSMakeSize(partSize.width*(frameSize.height/partSize.height), frameSize.height) } if octItem.isPart { view.imageView?.image = OCT_PART } else { view.imageView?.image = OCT_FOLDER } default: break } return view } var draggedItems = [OctItem]() var draggedNodes = [OctTreeNode]() func outlineView(outlineView: NSOutlineView, writeItems items: [AnyObject], toPasteboard pboard: NSPasteboard) -> Bool { draggedNodes = items as! [OctTreeNode] draggedItems = draggedNodes.map { (node: OctTreeNode) -> OctItem in node.item } let serialized = draggedItems.map { (item: OctItem) -> [String: AnyObject] in item.serialized() } pboard.declareTypes([kOctPasteboardType], owner: self) pboard.setPropertyList(serialized, forType: kOctPasteboardType) return true } func outlineView(outlineView: NSOutlineView, validateDrop info: NSDraggingInfo, proposedItem item: AnyObject?, proposedChildIndex index: Int) -> NSDragOperation { guard info.draggingPasteboard().availableTypeFromArray([kOctPasteboardType]) != nil else { return .None } guard let draggingSource = info.draggingSource() as? NSOutlineView where draggingSource == outlineView else { return [.Generic, .Copy] // Drags from outside the outline always OK } guard let octNode = item as? OctTreeNode else { return [.Move, .Copy] // Drags into root always OK } if !octNode.isExpandable { return .None // Don't allow dragging on a part } else if octNode.isDescendantOfOneOf(draggedNodes) { return .None // Don't allow drag on dragged items or their descendents } else { return [.Move, .Copy] // Otherwise we're good } } func outlineView(outlineView: NSOutlineView, acceptDrop info: NSDraggingInfo, item: AnyObject?, childIndex: Int) -> Bool { if let draggingSource = info.draggingSource() as? NSOutlineView where draggingSource == outlineView { // draggedNodes and draggedItems already contain an accurate representation } else { // Deserialize draggedItems from pasteboard draggedNodes = [] let serialized = info.draggingPasteboard().propertyListForType(kOctPasteboardType) as! [[String: AnyObject]] draggedItems = serialized.map({ (item: [String: AnyObject]) -> OctItem in return OctItem.itemFromSerialized(item) }) } let newParentNode = item as? OctTreeNode let newParent = newParentNode?.item ?? OctItem.rootFolder() var insertAtIndex = childIndex if insertAtIndex == NSOutlineViewDropOnItemIndex { insertAtIndex = newParent.children?.count ?? 0 } var insertAtRow = outlineView.rowForItem(item) if insertAtRow < 0 { insertAtRow = outlineView.numberOfRows } outlineView.beginUpdates() // // If this is a move, remove from previous parent, if any // if info.draggingSourceOperationMask().contains(.Move) { for node in draggedNodes.reverse() { let path = node.path let parent = node.parentItem let index = path.indexAtPosition(path.length-1) if parent == newParent && index < insertAtIndex { insertAtIndex -= 1 } if outlineView.rowForItem(node) < insertAtRow { insertAtRow -= 1 } node.removeFromParent() } } for item in draggedItems { let kids = newParent.mutableOrderedSetValueForKey("children") kids.insertObject(item, atIndex: insertAtIndex) insertAtIndex += 1 } outlineView.endUpdates() reloadTree(expanding: newParentNode) let insertedIndexes = NSIndexSet(indexesInRange: NSMakeRange(insertAtRow, draggedItems.count)) outlineView.selectRowIndexes(insertedIndexes, byExtendingSelection: false) return true } func outlineView(outlineView: NSOutlineView, draggingSession session: NSDraggingSession, endedAtPoint screenPoint: NSPoint, operation: NSDragOperation) { if operation.contains(.Delete) { outlineView.beginUpdates() for node in draggedNodes { node.removeFromParent() node.deleteIfOrphaned() } outlineView.endUpdates() reloadTree() } dispatch_async(dispatch_get_main_queue()) { self.oldTreeRoots = [] } } func selectedItems() -> [OctItem] { return outline.selectedRowIndexes.map() { (row: Int) -> OctItem in (outline.itemAtRow(row) as! OctTreeNode).item } } func outlineViewSelectionDidChange(_: NSNotification) { let selection = selectedItems() let standardParts = selection.filter { (item: OctItem) -> Bool in !item.isCustomPart } var newResults = selection.map { (item: OctItem) -> [String: AnyObject] in item.serialized() } dispatch_async(dispatch_get_main_queue()) { self.search.searchResults = newResults } guard standardParts.count > 0 else { return } search.partsFromUIDs(standardParts.map {$0.ident}) { (parts: [[String : AnyObject]]) in for part in parts { let index = try? newResults.indexOf { (result: [String : AnyObject]) throws -> Bool in return result["ident"] as! String == part["ident"] as! String } if let index = index ?? nil { let storedPart = newResults[index] var newPart = part newPart["name"] = storedPart["name"] newPart["desc"] = storedPart["desc"] newResults[index] = newPart } else { newResults.append(part) } } dispatch_async(dispatch_get_main_queue()) { self.search.searchResults = newResults } } } func selectedItem() -> OctItem { return (outline.itemAtRow(outline.selectedRow) as! OctTreeNode).item } } class OctOutlineView : NSOutlineView { @IBAction func delete(_: AnyObject) { let nodes = selectedRowIndexes.map { (index: Int) -> OctTreeNode in itemAtRow(index) as! OctTreeNode } beginUpdates() for node in nodes { node.removeFromParent() node.deleteIfOrphaned() } endUpdates() (dataSource() as? OctTree)?.reloadTree() } override func validateUserInterfaceItem(item: NSValidatedUserInterfaceItem) -> Bool { if item.action() == #selector(OctOutlineView.delete(_:)) { return selectedRowIndexes.count > 0 } return super.validateUserInterfaceItem(item) } }
fe13d8c89fa5b08ed3e0ab099ae89284
34.500978
163
0.586462
false
false
false
false
dduan/swift
refs/heads/master
test/SILGen/coverage_smoke.swift
apache-2.0
1
// RUN: rm -rf %t && mkdir %t // RUN: %target-build-swift %s -profile-generate -profile-coverage-mapping -o %t/main // RUN: env LLVM_PROFILE_FILE=%t/default.profraw %target-run %t/main // RUN: %llvm-profdata merge %t/default.profraw -o %t/default.profdata // RUN: %llvm-profdata show %t/default.profdata -function=main | FileCheck %s --check-prefix=CHECK-PROF // RUN: %llvm-cov show %t/main -instr-profile=%t/default.profdata | FileCheck %s --check-prefix=CHECK-COV // RUN: rm -rf %t // REQUIRES: profile_runtime // REQUIRES: OS=macosx func main() { // CHECK-PROF: Counters: 2 // CHECK-PROF: Function count: 1 // CHECK-COV: 1|{{.*}}[[@LINE+1]]|{{.*}}if (true) if (true) {} } main()
6a84dfb1f1dfef24bca9de65958b096a
37.111111
105
0.666181
false
false
false
false
jayb967/twitter-client-clone-
refs/heads/master
TwitterClient/TwitterClient/Tweet.swift
mit
1
// // Tweet.swift // TwitterClient // // Created by Rio Balderas on 3/20/17. // Copyright © 2017 Jay Balderas. All rights reserved. // import Foundation class Tweet { let text : String let id : String let retweeted : Bool var user : User? init?(json: [String: Any]) { //string is there to represent keys, any is the values in the JSON file if let text = json["text"] as? String, let id = json["id_str"] as? String {//retrieves it as a string self.text = text self.id = id if let userDictionary = json["user"] as? [String : Any] { self.user = User(json: userDictionary) } if json["retweeted_status"] == nil { self.retweeted = false }else { self.retweeted = true print("true") } } else { return nil } } }
6a79470370229cc80e418585c2165b40
21.097561
107
0.529801
false
false
false
false
artursDerkintis/Starfly
refs/heads/master
Starfly/SFSearchTable.swift
mit
1
// // SFSearchTable.swift // Starfly // // Created by Arturs Derkintis on 10/3/15. // Copyright © 2015 Starfly. All rights reserved. // import UIKit import CoreData let querie = "http://suggestqueries.google.com/complete/search?client=toolbar&hl=en&q=" class SFSearchTable: UIView, UITableViewDataSource, UITableViewDelegate, NSFetchedResultsControllerDelegate{ private var googleTable : UITableView? private var historyTable : UITableView? private var array = [String]() let app = UIApplication.sharedApplication().delegate as! AppDelegate private var fetchController : NSFetchedResultsController? private var textForSearch = "" override init(frame: CGRect) { super.init(frame: frame) fetchController = NSFetchedResultsController(fetchRequest: simpleHistoryRequest, managedObjectContext: SFDataHelper.sharedInstance.managedObjectContext, sectionNameKeyPath: nil, cacheName: nil) fetchController?.delegate = self googleTable = UITableView(frame: CGRect.zero) googleTable!.registerClass(SFSearchTableCell.self, forCellReuseIdentifier: "search") googleTable!.delegate = self googleTable!.dataSource = self googleTable!.backgroundColor = UIColor(white: 0.9, alpha: 0.0) googleTable?.separatorColor = UIColor.whiteColor().colorWithAlphaComponent(0.6) historyTable = UITableView(frame: CGRect.zero) historyTable!.registerClass(SFHistoryCellSearch.self, forCellReuseIdentifier: "search2") historyTable!.delegate = self historyTable!.dataSource = self historyTable!.backgroundColor = UIColor(white: 0.9, alpha: 0.0) historyTable?.separatorColor = UIColor.whiteColor().colorWithAlphaComponent(0.6) let stackView = UIStackView(arrangedSubviews: [googleTable!, historyTable!]) stackView.distribution = .FillEqually stackView.spacing = 20 addSubview(stackView) stackView.snp_makeConstraints { (make) -> Void in make.top.bottom.right.left.equalTo(0) } } lazy var simpleHistoryRequest : NSFetchRequest = { let request : NSFetchRequest = NSFetchRequest(entityName: "HistoryHit") request.sortDescriptors = [NSSortDescriptor(key: "arrangeIndex", ascending: false)] return request }() func getSuggestions(forText string : String){ if string != ""{ textForSearch = string let what : NSString = string.stringByReplacingOccurrencesOfString(" ", withString: "+") let set = NSCharacterSet.URLQueryAllowedCharacterSet() let formated : String = NSString(format: "%@%@", querie, what).stringByAddingPercentEncodingWithAllowedCharacters(set)! NSURLSession.sharedSession().dataTaskWithRequest(NSURLRequest(URL: NSURL(string: formated)!)) { (data : NSData?, res, error : NSError?) -> Void in if error == nil{ do { let xmlDoc = try AEXMLDocument(xmlData: data! as NSData) self.array.removeAll() for chilcd in xmlDoc["toplevel"].children { let string = chilcd["suggestion"].attributes["data"] as String? if let str = string{ self.array.append(str) } } dispatch_async(dispatch_get_main_queue(), { () -> Void in self.googleTable!.delegate = self self.googleTable!.reloadData() }) } catch _ { } }else{ print(error?.localizedDescription) } }.resume() let resultPredicate1 : NSPredicate = NSPredicate(format: "titleOfIt CONTAINS[cd] %@", string) let resultPredicate2 : NSPredicate = NSPredicate(format: "urlOfIt CONTAINS[cd] %@", string) let compound = NSCompoundPredicate(orPredicateWithSubpredicates: [resultPredicate1, resultPredicate2]) fetchController?.fetchRequest.predicate = compound do{ try fetchController?.performFetch() historyTable?.reloadData() }catch _{ } } } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: false) if tableView == googleTable{ if array.count > 0{ if let url = NSURL(string: parseUrl(array[indexPath.row])!){ print("google \(url)") NSNotificationCenter.defaultCenter().postNotificationName("OPEN", object:url) } } }else if tableView == historyTable{ let object = fetchController?.objectAtIndexPath(indexPath) as! HistoryHit print("google \(object.getURL())") NSNotificationCenter.defaultCenter().postNotificationName("OPEN", object: object.getURL()) } UIApplication.sharedApplication().delegate?.window!?.endEditing(true) } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if tableView == self.googleTable{ let cell = tableView.dequeueReusableCellWithIdentifier("search", forIndexPath: indexPath) as! SFSearchTableCell if array.count > indexPath.row{ let text = array[indexPath.row] cell.label?.text = text } return cell }else if tableView == self.historyTable{ let cell = tableView.dequeueReusableCellWithIdentifier("search2", forIndexPath: indexPath) as! SFHistoryCellSearch let object = fetchController?.objectAtIndexPath(indexPath) as! HistoryHit let title = NSMutableAttributedString(string: object.titleOfIt!) let rangeT = (object.titleOfIt! as NSString).rangeOfString(textForSearch, options: NSStringCompareOptions.CaseInsensitiveSearch) title.addAttribute(NSForegroundColorAttributeName, value: UIColor.whiteColor(), range: NSMakeRange(0, title.length)) title.addAttribute(NSForegroundColorAttributeName, value: UIColor(white: 0.75, alpha: 1.0), range: rangeT) let url = NSMutableAttributedString(string: object.urlOfIt!) let rangeU = (object.urlOfIt! as NSString).rangeOfString(textForSearch, options: NSStringCompareOptions.CaseInsensitiveSearch) url.addAttribute(NSForegroundColorAttributeName, value: UIColor(white: 0.9, alpha: 1.0), range: NSMakeRange(0, url.length)) url.addAttribute(NSForegroundColorAttributeName, value: UIColor(white: 0.8, alpha: 1.0), range: rangeU) cell.titleLabel?.textColor = nil cell.urlLabel?.textColor = nil cell.titleLabel?.attributedText = title cell.urlLabel?.attributedText = url return cell } return UITableViewCell() } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if tableView == googleTable{ return array.count }else if tableView == historyTable{ if self.fetchController!.sections != nil{ let sectionInfo = self.fetchController!.sections![section] as NSFetchedResultsSectionInfo return sectionInfo.numberOfObjects } } return 0 } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
0b8f430b00cdc5dde4b44b28fc8238db
46.390533
201
0.611437
false
false
false
false
danfsd/FolioReaderKit
refs/heads/master
Source/EPUBCore/FRMediaType.swift
bsd-3-clause
1
// // FRMediaType.swift // FolioReaderKit // // Created by Heberti Almeida on 29/04/15. // Copyright (c) 2015 Folio Reader. All rights reserved. // import UIKit /** MediaType is used to tell the type of content a resource is. Examples of mediatypes are image/gif, text/css and application/xhtml+xml */ struct MediaType { var name: String var defaultExtension: String! var extensions: [String]! init(name: String, defaultExtension: String) { self.name = name self.defaultExtension = defaultExtension self.extensions = [defaultExtension] } init(name: String, defaultExtension: String, extensions: [String]) { self.name = name self.defaultExtension = defaultExtension self.extensions = extensions } } // MARK: Equatable extension MediaType: Equatable {} /** Compare if two mediatypes are equal or different. */ func ==(lhs: MediaType, rhs: MediaType) -> Bool { return lhs.name == rhs.name && lhs.defaultExtension == rhs.defaultExtension } /** Manages mediatypes that are used by epubs. */ class FRMediaType: NSObject { static var XHTML = MediaType(name: "application/xhtml+xml", defaultExtension: ".xhtml", extensions: [".htm", ".html", ".xhtml", ".xml"]) static var EPUB = MediaType(name: "application/epub+zip", defaultExtension: ".epub") static var NCX = MediaType(name: "application/x-dtbncx+xml", defaultExtension: ".ncx") static var OPF = MediaType(name: "application/oebps-package+xml", defaultExtension: ".opf") static var JAVASCRIPT = MediaType(name: "text/javascript", defaultExtension: ".js") static var CSS = MediaType(name: "text/css", defaultExtension: ".css") // images static var JPG = MediaType(name: "image/jpeg", defaultExtension: ".jpg", extensions: [".jpg", ".jpeg"]) static var PNG = MediaType(name: "image/png", defaultExtension: ".png") static var GIF = MediaType(name: "image/gif", defaultExtension: ".gif") static var SVG = MediaType(name: "image/svg+xml", defaultExtension: ".svg") // fonts static var TTF = MediaType(name: "application/x-font-ttf", defaultExtension: ".ttf") static var TTF1 = MediaType(name: "application/x-font-truetype", defaultExtension: ".ttf") static var TTF2 = MediaType(name: "application/x-truetype-font", defaultExtension: ".ttf") static var OPENTYPE = MediaType(name: "application/vnd.ms-opentype", defaultExtension: ".otf") static var WOFF = MediaType(name: "application/font-woff", defaultExtension: ".woff") // audio static var MP3 = MediaType(name: "audio/mpeg", defaultExtension: ".mp3") static var MP4 = MediaType(name: "audio/mp4", defaultExtension: ".mp4") static var OGG = MediaType(name: "audio/ogg", defaultExtension: ".ogg") static var SMIL = MediaType(name: "application/smil+xml", defaultExtension: ".smil") static var XPGT = MediaType(name: "application/adobe-page-template+xml", defaultExtension: ".xpgt") static var PLS = MediaType(name: "application/pls+xml", defaultExtension: ".pls") static var mediatypes = [XHTML, EPUB, NCX, OPF, JPG, PNG, GIF, CSS, SVG, TTF, TTF1, TTF2, OPENTYPE, WOFF, SMIL, XPGT, PLS, JAVASCRIPT, MP3, MP4, OGG] /** Gets the MediaType based on the file mimetype. - parameter name: The mediaType name - parameter fileName: The file name to extract the extension - returns: A know mediatype or create a new one. */ static func mediaTypeByName(_ name: String, fileName: String) -> MediaType { for mediatype in mediatypes { if mediatype.name == name { return mediatype } } let ext = ".\(URL(string: fileName)!.pathExtension)" return MediaType(name: name, defaultExtension: ext) } /** Compare if the resource is a image. - returns: `true` if is a image and `false` if not */ static func isBitmapImage(_ mediaType: MediaType) -> Bool { return mediaType == JPG || mediaType == PNG || mediaType == GIF } /** Gets the MediaType based on the file extension. */ static func determineMediaType(_ fileName: String) -> MediaType? { for mediatype in mediatypes { let ext = "."+(fileName as NSString).pathExtension if mediatype.extensions.contains(ext) { return mediatype } } return nil } }
834d099a12eb0debc470868b50216c7c
35.54918
153
0.653734
false
false
false
false
hibu/apptentive-ios
refs/heads/master
Example/iOSExample/AppDelegate.swift
bsd-3-clause
1
// // AppDelegate.swift // ApptentiveExample // // Created by Frank Schmitt on 8/6/15. // Copyright (c) 2015 Apptentive, Inc. All rights reserved. // import UIKit import Apptentive @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UITabBarControllerDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { Apptentive.sharedConnection().APIKey = "<Your Apptentive API Key>" precondition(Apptentive.sharedConnection().APIKey != "<Your Apptentive API Key>", "Please set your Apptentive API key above") if let tabBarController = self.window?.rootViewController as? UITabBarController { tabBarController.delegate = self } return true } // MARK: Tab bar controller delegate func tabBarController(tabBarController: UITabBarController, didSelectViewController viewController: UIViewController) { if tabBarController.viewControllers?.indexOf(viewController) ?? 0 == 0 { Apptentive.sharedConnection().engage("photos_tab_selected", fromViewController: tabBarController) } else { Apptentive.sharedConnection().engage("favorites_tab_selected", fromViewController: tabBarController) } } }
05d89899ee1c7ff891713c61c4871320
31.763158
127
0.772691
false
false
false
false
mcxiaoke/learning-ios
refs/heads/master
cocoa_programming_for_osx/29_UnitTesting/RanchForecast/RanchForecast/Course.swift
apache-2.0
3
// // Course.swift // RanchForecast // // Created by mcxiaoke on 16/5/23. // Copyright © 2016年 mcxiaoke. All rights reserved. // import Foundation public class Course: NSObject { public let title:String public let url:NSURL public let nextStartDate: NSDate public init(title: String, url: NSURL, nextStartDate: NSDate) { self.title = title self.url = url self.nextStartDate = nextStartDate super.init() } override public var description: String { return "Course(title:\(title) url:\(url))" } } public func ==(lhs: Course, rhs: Course) -> Bool { return lhs.title == rhs.title && lhs.url == rhs.url && lhs.nextStartDate == rhs.nextStartDate }
7684bf7cbda3cd08369ad0a0ca360264
20.181818
65
0.664756
false
false
false
false
SomeSimpleSolutions/MemorizeItForever
refs/heads/Development
MemorizeItForever/MemorizeItForever/General/Extensions/SwinjectStoryboardExtension.swift
mit
1
// // SwinjectStoryboardExtension.swift // MemorizeItForever // // Created by Hadi Zamani on 11/12/16. // Copyright © 2016 SomeSimpleSolutions. All rights reserved. // import Swinject import SwinjectStoryboard import MemorizeItForeverCore import BaseLocalDataAccess import CoreData extension SwinjectStoryboard { @objc class func setup() { defaultContainer.storyboardInitCompleted(TabBarController.self) { r, c in c.setService = r.resolve(SetServiceProtocol.self) } defaultContainer.storyboardInitCompleted(MemorizeItViewController.self) { r, c in c.selectionFeedback = UISelectionFeedbackGenerator() } defaultContainer.storyboardInitCompleted(SetViewController.self) { r, c in c.setService = r.resolve(SetServiceProtocol.self) c.dataSource = r.resolve(SetTableDataSourceProtocol.self, name: "SetTableDataSource") } defaultContainer.storyboardInitCompleted(SetItemViewController.self) { r, c in c.setService = r.resolve(SetServiceProtocol.self) } defaultContainer.storyboardInitCompleted(ChangeSetViewController.self) { r, c in c.setService = r.resolve(SetServiceProtocol.self) c.dataSource = r.resolve(SetTableDataSourceProtocol.self, name: "ChangeSetTableDataSource") } defaultContainer.storyboardInitCompleted(AddPhraseViewController.self) { r, c in c.wordService = r.resolve(WordServiceProtocol.self) c.validator = r.resolve(ValidatorProtocol.self) c.notificationFeedback = UINotificationFeedbackGenerator() } defaultContainer.storyboardInitCompleted(ReviewPhraseViewController.self) { r, c in c.wordFlowService = r.resolve(WordFlowServiceProtocol.self) } defaultContainer.register(SetTableDataSourceProtocol.self, name: "SetTableDataSource") { r in SetTableDataSource(setService: r.resolve(SetServiceProtocol.self)) }.inObjectScope(.weak) defaultContainer.register(SetTableDataSourceProtocol.self, name: "ChangeSetTableDataSource") { r in ChangeSetTableDataSource(setService: r.resolve(SetServiceProtocol.self)) }.inObjectScope(.weak) defaultContainer.register(ValidatorProtocol.self){ r in Validator() } defaultContainer.storyboardInitCompleted(TakeTestViewController.self) { r, c in c.wordFlowService = r.resolve(WordFlowServiceProtocol.self) c.notificationFeedback = UINotificationFeedbackGenerator() } defaultContainer.storyboardInitCompleted(PhraseViewController.self) { r, c in c.dataSource = r.resolve(PhraseTableDataSourceProtocol.self, name: "PhraseTableDataSource") c.wordService = r.resolve(WordServiceProtocol.self) } defaultContainer.register(PhraseTableDataSourceProtocol.self, name: "PhraseTableDataSource"){ r in PhraseTableDataSource(wordService: r.resolve(WordServiceProtocol.self)) }.inObjectScope(.weak) defaultContainer.storyboardInitCompleted(PhraseHistoryViewController.self) { r, c in c.dataSource = r.resolve(PhraseTableDataSourceProtocol.self, name: "PhraseHistoryTableDataSource") c.wordService = r.resolve(WordServiceProtocol.self) } defaultContainer.register(PhraseTableDataSourceProtocol.self, name: "PhraseHistoryTableDataSource"){ r in PhraseHistoryTableDataSource(wordService: nil) }.inObjectScope(.weak) defaultContainer.register(ServiceFactoryProtocol.self, name: "SetServiceFactory"){ r in SetServiceFactory() } defaultContainer.register(ServiceFactoryProtocol.self, name: "WordServiceFactory"){ r in WordServiceFactory() } defaultContainer.register(ServiceFactoryProtocol.self, name: "WordFlowServiceFactory"){ r in WordFlowServiceFactory() } defaultContainer.register(ServiceFactoryProtocol.self, name: "DepotPhraseServiceFactory"){ r in DepotPhraseServiceFactory() } defaultContainer.register(SetServiceProtocol.self){ r in let setServiceFactory = r.resolve(ServiceFactoryProtocol.self, name: "SetServiceFactory")! let setService: SetService = setServiceFactory.create() return setService } defaultContainer.register(WordServiceProtocol.self){ r in let wordServiceFactory = r.resolve(ServiceFactoryProtocol.self, name: "WordServiceFactory")! let wordService: WordService = wordServiceFactory.create() return wordService } defaultContainer.register(WordFlowServiceProtocol.self){ r in let wordFlowServiceFactory = r.resolve(ServiceFactoryProtocol.self, name: "WordFlowServiceFactory")! let wordFlowService: WordFlowService = wordFlowServiceFactory.create() return wordFlowService } defaultContainer.storyboardInitCompleted(TemporaryPhraseListViewController.self) { r, c in c.dataSource = r.resolve(DepotTableDataSourceProtocol.self, name: "TemporaryPhraseListDataSource") c.service = r.resolve(DepotPhraseServiceProtocol.self) } defaultContainer.register(DepotPhraseServiceProtocol.self){ r in let depotPhraseServiceFactory = r.resolve(ServiceFactoryProtocol.self, name: "DepotPhraseServiceFactory")! let depotPhraseService: DepotPhraseService = depotPhraseServiceFactory.create() return depotPhraseService } defaultContainer.register(DepotTableDataSourceProtocol.self, name: "TemporaryPhraseListDataSource"){ r in TemporaryPhraseListDataSource() }.inObjectScope(.weak) defaultContainer.register(EditPhrasePickerViewDataSourceProtocol.self){ r in EditPhrasePickerViewDataSource() }.inObjectScope(.weak) defaultContainer.storyboardInitCompleted(EditPhraseViewController.self) { r, c in c.wordService = r.resolve(WordServiceProtocol.self) c.setService = r.resolve(SetServiceProtocol.self) c.pickerDataSource = r.resolve(EditPhrasePickerViewDataSourceProtocol.self) c.notificationFeedback = UINotificationFeedbackGenerator() } defaultContainer.storyboardInitCompleted(DepotViewController.self) { r, c in c.dataSource = r.resolve(DepotTableDataSourceProtocol.self, name: "DepotDataSource") c.service = r.resolve(DepotPhraseServiceProtocol.self) } defaultContainer.register(DepotTableDataSourceProtocol.self, name: "DepotDataSource"){ r in DepotDataSource(service: r.resolve(DepotPhraseServiceProtocol.self)!) }.inObjectScope(.weak) } }
64eaf217db7dec77f00515c856915f04
45.168831
118
0.683263
false
false
false
false
kstaring/swift
refs/heads/upstream-master
stdlib/public/SDK/Foundation/AffineTransform.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module #if os(OSX) private let ε: CGFloat = 2.22045e-16 public struct AffineTransform : ReferenceConvertible, Hashable, CustomStringConvertible { public var m11, m12, m21, m22, tX, tY: CGFloat public typealias ReferenceType = NSAffineTransform /** Creates an affine transformation. */ public init(m11: CGFloat, m12: CGFloat, m21: CGFloat, m22: CGFloat, tX: CGFloat, tY: CGFloat) { self.m11 = m11 self.m12 = m12 self.m21 = m21 self.m22 = m22 self.tX = tX self.tY = tY } fileprivate init(reference: NSAffineTransform) { m11 = reference.transformStruct.m11 m12 = reference.transformStruct.m12 m21 = reference.transformStruct.m21 m22 = reference.transformStruct.m22 tX = reference.transformStruct.tX tY = reference.transformStruct.tY } fileprivate var reference : NSAffineTransform { let ref = NSAffineTransform() ref.transformStruct = NSAffineTransformStruct(m11: m11, m12: m12, m21: m21, m22: m22, tX: tX, tY: tY) return ref } /** Creates an affine transformation matrix with identity values. - seealso: identity */ public init() { self.init(m11: CGFloat(1.0), m12: CGFloat(0.0), m21: CGFloat(0.0), m22: CGFloat(1.0), tX: CGFloat(0.0), tY: CGFloat(0.0)) } /** Creates an affine transformation matrix from translation values. The matrix takes the following form: [ 1 0 0 ] [ 0 1 0 ] [ x y 1 ] */ public init(translationByX x: CGFloat, byY y: CGFloat) { self.init(m11: CGFloat(1.0), m12: CGFloat(0.0), m21: CGFloat(0.0), m22: CGFloat(1.0), tX: x, tY: y) } /** Creates an affine transformation matrix from scaling values. The matrix takes the following form: [ x 0 0 ] [ 0 y 0 ] [ 0 0 1 ] */ public init(scaleByX x: CGFloat, byY y: CGFloat) { self.init(m11: x, m12: CGFloat(0.0), m21: CGFloat(0.0), m22: y, tX: CGFloat(0.0), tY: CGFloat(0.0)) } /** Creates an affine transformation matrix from scaling a single value. The matrix takes the following form: [ f 0 0 ] [ 0 f 0 ] [ 0 0 1 ] */ public init(scale factor: CGFloat) { self.init(scaleByX: factor, byY: factor) } /** Creates an affine transformation matrix from rotation value (angle in radians). The matrix takes the following form: [ cos α sin α 0 ] [ -sin α cos α 0 ] [ 0 0 1 ] */ public init(rotationByRadians angle: CGFloat) { let α = Double(angle) let sine = CGFloat(sin(α)) let cosine = CGFloat(cos(α)) self.init(m11: cosine, m12: sine, m21: -sine, m22: cosine, tX: 0, tY: 0) } /** Creates an affine transformation matrix from a rotation value (angle in degrees). The matrix takes the following form: [ cos α sin α 0 ] [ -sin α cos α 0 ] [ 0 0 1 ] */ public init(rotationByDegrees angle: CGFloat) { let α = Double(angle) * M_PI / 180.0 self.init(rotationByRadians: CGFloat(α)) } /** An identity affine transformation matrix [ 1 0 0 ] [ 0 1 0 ] [ 0 0 1 ] */ public static let identity = AffineTransform(m11: 1, m12: 0, m21: 0, m22: 1, tX: 0, tY: 0) // Translating public mutating func translate(x: CGFloat, y: CGFloat) { tX += m11 * x + m21 * y tY += m12 * x + m22 * y } /** Mutates an affine transformation matrix from a rotation value (angle α in degrees). The matrix takes the following form: [ cos α sin α 0 ] [ -sin α cos α 0 ] [ 0 0 1 ] */ public mutating func rotate(byDegrees angle: CGFloat) { let α = Double(angle) * M_PI / 180.0 return rotate(byRadians: CGFloat(α)) } /** Mutates an affine transformation matrix from a rotation value (angle α in radians). The matrix takes the following form: [ cos α sin α 0 ] [ -sin α cos α 0 ] [ 0 0 1 ] */ public mutating func rotate(byRadians angle: CGFloat) { let α = Double(angle) let sine = CGFloat(sin(α)) let cosine = CGFloat(cos(α)) m11 = cosine m12 = sine m21 = -sine m22 = cosine } /** Creates an affine transformation matrix by combining the receiver with `transformStruct`. That is, it computes `T * M` and returns the result, where `T` is the receiver's and `M` is the `transformStruct`'s affine transformation matrix. The resulting matrix takes the following form: [ m11_T m12_T 0 ] [ m11_M m12_M 0 ] T * M = [ m21_T m22_T 0 ] [ m21_M m22_M 0 ] [ tX_T tY_T 1 ] [ tX_M tY_M 1 ] [ (m11_T*m11_M + m12_T*m21_M) (m11_T*m12_M + m12_T*m22_M) 0 ] = [ (m21_T*m11_M + m22_T*m21_M) (m21_T*m12_M + m22_T*m22_M) 0 ] [ (tX_T*m11_M + tY_T*m21_M + tX_M) (tX_T*m12_M + tY_T*m22_M + tY_M) 1 ] */ private func concatenated(_ other: AffineTransform) -> AffineTransform { let (t, m) = (self, other) // this could be optimized with a vector version return AffineTransform( m11: (t.m11 * m.m11) + (t.m12 * m.m21), m12: (t.m11 * m.m12) + (t.m12 * m.m22), m21: (t.m21 * m.m11) + (t.m22 * m.m21), m22: (t.m21 * m.m12) + (t.m22 * m.m22), tX: (t.tX * m.m11) + (t.tY * m.m21) + m.tX, tY: (t.tX * m.m12) + (t.tY * m.m22) + m.tY ) } // Scaling public mutating func scale(_ scale: CGFloat) { self.scale(x: scale, y: scale) } public mutating func scale(x: CGFloat, y: CGFloat) { m11 *= x m12 *= x m21 *= y m22 *= y } /** Inverts the transformation matrix if possible. Matrices with a determinant that is less than the smallest valid representation of a double value greater than zero are considered to be invalid for representing as an inverse. If the input AffineTransform can potentially fall into this case then the inverted() method is suggested to be used instead since that will return an optional value that will be nil in the case that the matrix cannot be inverted. D = (m11 * m22) - (m12 * m21) D < ε the inverse is undefined and will be nil */ public mutating func invert() { guard let inverse = inverted() else { fatalError("Transform has no inverse") } self = inverse } public func inverted() -> AffineTransform? { let determinant = (m11 * m22) - (m12 * m21) if fabs(determinant) <= ε { return nil } var inverse = AffineTransform() inverse.m11 = m22 / determinant inverse.m12 = -m12 / determinant inverse.m21 = -m21 / determinant inverse.m22 = m11 / determinant inverse.tX = (m21 * tY - m22 * tX) / determinant inverse.tY = (m12 * tX - m11 * tY) / determinant return inverse } // Transforming with transform public mutating func append(_ transform: AffineTransform) { self = concatenated(transform) } public mutating func prepend(_ transform: AffineTransform) { self = transform.concatenated(self) } // Transforming points and sizes public func transform(_ point: NSPoint) -> NSPoint { var newPoint = NSPoint() newPoint.x = (m11 * point.x) + (m21 * point.y) + tX newPoint.y = (m12 * point.x) + (m22 * point.y) + tY return newPoint } public func transform(_ size: NSSize) -> NSSize { var newSize = NSSize() newSize.width = (m11 * size.width) + (m21 * size.height) newSize.height = (m12 * size.width) + (m22 * size.height) return newSize } public var hashValue : Int { return Int(m11 + m12 + m21 + m22 + tX + tY) } public var description: String { return "{m11:\(m11), m12:\(m12), m21:\(m21), m22:\(m22), tX:\(tX), tY:\(tY)}" } public var debugDescription: String { return description } public static func ==(lhs: AffineTransform, rhs: AffineTransform) -> Bool { return lhs.m11 == rhs.m11 && lhs.m12 == rhs.m12 && lhs.m21 == rhs.m21 && lhs.m22 == rhs.m22 && lhs.tX == rhs.tX && lhs.tY == rhs.tY } } extension AffineTransform : _ObjectiveCBridgeable { public static func _getObjectiveCType() -> Any.Type { return NSAffineTransform.self } @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSAffineTransform { return self.reference } public static func _forceBridgeFromObjectiveC(_ x: NSAffineTransform, result: inout AffineTransform?) { if !_conditionallyBridgeFromObjectiveC(x, result: &result) { fatalError("Unable to bridge type") } } public static func _conditionallyBridgeFromObjectiveC(_ x: NSAffineTransform, result: inout AffineTransform?) -> Bool { result = AffineTransform(reference: x) return true // Can't fail } public static func _unconditionallyBridgeFromObjectiveC(_ x: NSAffineTransform?) -> AffineTransform { var result: AffineTransform? _forceBridgeFromObjectiveC(x!, result: &result) return result! } } extension NSAffineTransform : _HasCustomAnyHashableRepresentation { // Must be @nonobjc to avoid infinite recursion during bridging. @nonobjc public func _toCustomAnyHashable() -> AnyHashable? { return AnyHashable(self as AffineTransform) } } #endif
48e3bfefeacaa98b9e28c185220f2b2a
31.664653
123
0.552627
false
false
false
false
loisie123/Cuisine-Project
refs/heads/master
Cuisine/WeekTableViewController.swift
mit
1
// // WeekTableViewController.swift // Cuisine // // Created by Lois van Vliet on 15-01-17. // Copyright © 2017 Lois van Vliet. All rights reserved. // import UIKit import Firebase class WeekTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableViewImage: UITableView! var ref:FIRDatabaseReference? var databaseHandle: FIRDatabaseHandle? var days = [String]() var selectedDay = String() var array = [String]() override func viewDidLoad() { getweek() super.viewDidLoad() if days.isEmpty{ days = ["No information available"] } ref = FIRDatabase.database().reference() self.tableViewImage.reloadData() } //MARK:- Get the available dates. func getweek(){ let ref = FIRDatabase.database().reference() ref.child("cormet").child("different days").observeSingleEvent(of: .value, with: { (snapshot) in self.days = self.getWeekDays(snapshot: snapshot) self.tableViewImage.reloadData() }) } //MARK:- Make tableview func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "weekCell", for: indexPath) as! WeekTableViewCell cell.weekLabel.text = days[indexPath.row] return cell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return days.count } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { selectedDay = days[indexPath.row] self.performSegue(withIdentifier: "mealsVC", sender: nil) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "mealsVC"{ let controller = segue.destination as! TodayMealsViewController controller.day = selectedDay } } }
8249d37a500e1ca891379930126801ed
24.823529
114
0.599089
false
false
false
false
sebk/BeaconMonitor
refs/heads/master
BeaconMonitor/BeaconSender.swift
mit
1
// // BeaconSender.swift // BeaconMonitor // // Created by Sebastian Kruschwitz on 16.09.15. // Copyright © 2015 seb. All rights reserved. // import Foundation import CoreLocation import CoreBluetooth public class BeaconSender: NSObject { public static let sharedInstance = BeaconSender() fileprivate var _region: CLBeaconRegion? fileprivate var _peripheralManager: CBPeripheralManager! fileprivate var _uuid = "" fileprivate var _identifier = "" public func startSending(uuid: String, majorID: CLBeaconMajorValue, minorID: CLBeaconMinorValue, identifier: String) { _uuid = uuid _identifier = identifier stopSending() //stop sending when it's active // create the region that will be used to send _region = CLBeaconRegion( proximityUUID: UUID(uuidString: uuid)!, major: majorID, minor: minorID, identifier: identifier) _peripheralManager = CBPeripheralManager(delegate: self, queue: nil) } open func stopSending() { _peripheralManager?.stopAdvertising() } } //MARK: - CBPeripheralManagerDelegate extension BeaconSender: CBPeripheralManagerDelegate { public func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) { if peripheral.state == .poweredOn { let data = ((_region?.peripheralData(withMeasuredPower: nil))! as NSDictionary) as! Dictionary<String, Any> peripheral.startAdvertising(data) print("Powered On -> start advertising") } else if peripheral.state == .poweredOff { peripheral.stopAdvertising() print("Powered Off -> stop advertising") } } public func peripheralManagerDidStartAdvertising(_ peripheral: CBPeripheralManager, error: Error?) { if let error = error { print("Error starting advertising: \(error)") } else { print("Did start advertising") } } }
595edbe2526b753ca3f55b4e63d72f1c
26.641026
122
0.608998
false
false
false
false
wangyuxianglove/TestKitchen1607
refs/heads/master
Testkitchen1607/Testkitchen1607/classes/ingredient(食材)/main(主要模块)/view/IngreRecommendView.swift
mit
1
// // IngreRecommendView.swift // Testkitchen1607 // // Created by qianfeng on 16/10/25. // Copyright © 2016年 zhb. All rights reserved. // import UIKit public enum IngreWidgetType:Int{ case GuessYouLike = 1//猜你喜欢 case RedPacket = 2//红包入口 case TodayNew=5//今日新品 case Scene=3//早餐 case SceneList=9//全部场景 } class IngreRecommendView: UIView { //数据 var jumpClosure:IngreJumpClourse? var model:IngreRcommend?{ didSet{ //set方法调用之后会调用这里方法 tableView?.reloadData() } } //表格 private var tableView:UITableView? //重新实现初始化方法 override init(frame: CGRect) { super.init(frame: frame) //创建表格视图 tableView=UITableView(frame: CGRectZero, style: .Plain) tableView?.dataSource=self tableView?.delegate=self addSubview(tableView!) //约束 tableView?.snp_makeConstraints(closure: { (make) in make.edges.equalToSuperview() }) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } //MARK:UITableView代理方法 extension IngreRecommendView:UITableViewDelegate,UITableViewDataSource{ func numberOfSectionsInTableView(tableView: UITableView) -> Int { //banner广告部分显示一个分组 var section=1 if model?.data?.widgetList?.count>0{ section+=(model?.data?.widgetList?.count)! } return section } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { //banner广告Section显示一行 var row=0 if section==0{ //广告 row=1 }else{ //获取list对象 let listModel = model?.data?.widgetList![section-1] if (listModel?.widget_type?.integerValue)! == IngreWidgetType.GuessYouLike.rawValue||(listModel?.widget_type?.integerValue)! == IngreWidgetType.RedPacket.rawValue||(listModel?.widget_type?.integerValue)! == IngreWidgetType.TodayNew.rawValue||(listModel?.widget_type?.integerValue)! == IngreWidgetType.Scene.rawValue||(listModel?.widget_type?.integerValue)! == IngreWidgetType.SceneList.rawValue{ //猜你喜欢 //红包入口 //今日新品 //早餐日记 //全部场景 row=1 } } return row } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { var height:CGFloat=0 if indexPath.section==0{ height=140 }else{ let listModel=model?.data?.widgetList![indexPath.section-1] if listModel?.widget_type?.integerValue==IngreWidgetType.GuessYouLike.rawValue{ //猜你喜欢 height=70 }else if listModel?.widget_type?.integerValue==IngreWidgetType.RedPacket.rawValue{ //红包入口 height=75 }else if listModel?.widget_type?.integerValue==IngreWidgetType.TodayNew.rawValue{ //今日新品 height=280 }else if listModel?.widget_type?.integerValue==IngreWidgetType.Scene.rawValue{ //早餐日记 height=200 }else if listModel?.widget_type?.integerValue==IngreWidgetType.SceneList.rawValue{ //全部场景 height=70 } } return height } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.section==0{ let cell=IngreBannerCell.creatBannerCellFor(tableView, atIndexPath: indexPath, bannerArray: model?.data?.bannerArray) //点击事件 cell.jumpClosure=jumpClosure return cell }else{ let listModel=model?.data?.widgetList![indexPath.section-1] if listModel?.widget_type?.integerValue==IngreWidgetType.GuessYouLike.rawValue{ //猜你喜欢 let cell = IngreLikeCell.creatLikeCellFor(tableView, atIndexPath: indexPath, listModel: listModel) //点击事件 cell.jumpClosure=jumpClosure return cell }else if listModel?.widget_type?.integerValue==IngreWidgetType.RedPacket.rawValue{ //红包入口 let cell = IngreRedPacketCell.creatRedPackCellFor(tableView, atIndexPath: indexPath, listModel: listModel!) //点击事件 cell.jumpClosure=jumpClosure return cell }else if listModel?.widget_type?.integerValue==IngreWidgetType.TodayNew.rawValue{ //今日新品 let cell = IngreTodayCell.creatRedTodayCellFor(tableView, atIndexPath: indexPath, listModel: listModel) //点击事件 cell.jumpClosure=jumpClosure return cell }else if listModel?.widget_type?.integerValue==IngreWidgetType.Scene.rawValue{ //早餐 let cell = IngrescenCell.creatSceneCellFor(tableView, atIndexPath: indexPath, listModel: listModel) //点击事件 cell.jumpClosure=jumpClosure return cell }else if listModel?.widget_type?.integerValue==IngreWidgetType.SceneList.rawValue{ //全部 let cell = IngreSceneListCell.creatSceneListCellFor(tableView, atIndexPath: indexPath, listModel: listModel) //点击事件 cell.jumpClosure=jumpClosure return cell } } return UITableViewCell() } func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if section>0{ let listModel=model?.data?.widgetList![section-1] if listModel?.widget_type?.integerValue==IngreWidgetType.GuessYouLike.rawValue{ //猜你喜欢分组的header let likeHeaderView=IngreLikeHeaderView(frame: CGRect(x: 0, y: 0, width: bounds.size.width, height: 44)) return likeHeaderView }else if listModel?.widget_type?.integerValue==IngreWidgetType.TodayNew.rawValue||listModel?.widget_type?.integerValue==IngreWidgetType.Scene.rawValue{ //今日新品 let headerView=IngreHeaderView(frame: CGRect(x: 0, y: 0, width:kScreenWidth , height: 54)) //headerView.configText((listModel?.title)!) headerView.jumpClosure=jumpClosure headerView.listModel=listModel return headerView } } return nil } //设置header的高度 func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { var height:CGFloat=0 if section > 0{ let listModel=model?.data?.widgetList![section-1] if listModel?.widget_type?.integerValue==IngreWidgetType.GuessYouLike.rawValue{ height=44 }else if listModel?.widget_type?.integerValue==IngreWidgetType.TodayNew.rawValue||listModel?.widget_type?.integerValue==IngreWidgetType.Scene.rawValue{ // height=54 } } return height } }
f1c2a23aa22aaec988a65e50f67f9526
34.209524
412
0.585204
false
false
false
false
Foild/SwiftForms
refs/heads/master
SwiftForms/descriptors/FormRowDescriptor.swift
mit
5
// // FormRowDescriptor.swift // SwiftForms // // Created by Miguel Angel Ortuno on 20/08/14. // Copyright (c) 2014 Miguel Angel Ortuño. All rights reserved. // import UIKit public enum FormRowType { case Unknown case Text case URL case Number case NumbersAndPunctuation case Decimal case Name case Phone case NamePhone case Email case Twitter case ASCIICapable case Password case Button case BooleanSwitch case BooleanCheck case SegmentedControl case Picker case Date case Time case DateAndTime case Stepper case Slider case MultipleSelector case MultilineText } public typealias DidSelectClosure = (Void) -> Void public typealias UpdateClosure = (FormRowDescriptor) -> Void public typealias TitleFormatterClosure = (NSObject) -> String! public typealias VisualConstraintsClosure = (FormBaseCell) -> NSArray public class FormRowDescriptor: NSObject { /// MARK: Types public struct Configuration { public static let Required = "FormRowDescriptorConfigurationRequired" public static let CellClass = "FormRowDescriptorConfigurationCellClass" public static let CheckmarkAccessoryView = "FormRowDescriptorConfigurationCheckmarkAccessoryView" public static let CellConfiguration = "FormRowDescriptorConfigurationCellConfiguration" public static let Placeholder = "FormRowDescriptorConfigurationPlaceholder" public static let WillUpdateClosure = "FormRowDescriptorConfigurationWillUpdateClosure" public static let DidUpdateClosure = "FormRowDescriptorConfigurationDidUpdateClosure" public static let MaximumValue = "FormRowDescriptorConfigurationMaximumValue" public static let MinimumValue = "FormRowDescriptorConfigurationMinimumValue" public static let Steps = "FormRowDescriptorConfigurationSteps" public static let Continuous = "FormRowDescriptorConfigurationContinuous" public static let DidSelectClosure = "FormRowDescriptorConfigurationDidSelectClosure" public static let VisualConstraintsClosure = "FormRowDescriptorConfigurationVisualConstraintsClosure" public static let Options = "FormRowDescriptorConfigurationOptions" public static let TitleFormatterClosure = "FormRowDescriptorConfigurationTitleFormatterClosure" public static let SelectorControllerClass = "FormRowDescriptorConfigurationSelectorControllerClass" public static let AllowsMultipleSelection = "FormRowDescriptorConfigurationAllowsMultipleSelection" public static let ShowsInputToolbar = "FormRowDescriptorConfigurationShowsInputToolbar" public static let DateFormatter = "FormRowDescriptorConfigurationDateFormatter" } /// MARK: Properties public var title: String! public var rowType: FormRowType = .Unknown public var tag: String! public var value: NSObject! { willSet { if let willUpdateBlock = self.configuration[Configuration.WillUpdateClosure] as? UpdateClosure { willUpdateBlock(self) } } didSet { if let didUpdateBlock = self.configuration[Configuration.DidUpdateClosure] as? UpdateClosure { didUpdateBlock(self) } } } public var configuration: [NSObject : Any] = [:] /// MARK: Init public override init() { super.init() configuration[Configuration.Required] = true configuration[Configuration.AllowsMultipleSelection] = false configuration[Configuration.ShowsInputToolbar] = false } public convenience init(tag: String, rowType: FormRowType, title: String, placeholder: String! = nil) { self.init() self.tag = tag self.rowType = rowType self.title = title if placeholder != nil { configuration[FormRowDescriptor.Configuration.Placeholder] = placeholder } } /// MARK: Public interface public func titleForOptionAtIndex(index: Int) -> String! { if let options = configuration[FormRowDescriptor.Configuration.Options] as? NSArray { return titleForOptionValue(options[index] as! NSObject) } return nil } public func titleForOptionValue(optionValue: NSObject) -> String! { if let titleFormatter = configuration[FormRowDescriptor.Configuration.TitleFormatterClosure] as? TitleFormatterClosure { return titleFormatter(optionValue) } else if optionValue is String { return optionValue as! String } return "\(optionValue)" } }
0109412ac8e06230dcb600dd1fe48729
32.84507
128
0.6933
false
true
false
false
le-lerot/altim
refs/heads/master
Altim/CameraViewController.swift
gpl-3.0
1
// // CameraViewController.swift // Altim // // Created by Martin Delille on 23/12/2016. // Copyright © 2016 Phonations. All rights reserved. // import UIKit import AVFoundation import CoreMotion class CameraViewController: UIViewController { var cameraPreviewLayer: AVCaptureVideoPreviewLayer? var hudLayer = CAShapeLayer() var motionManager = CMMotionManager() @IBOutlet weak var cameraView: UIImageView! override func viewDidLoad() { super.viewDidLoad() let session = AVCaptureSession() session.sessionPreset = AVCaptureSessionPresetHigh let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) do { let input = try AVCaptureDeviceInput(device: device) session.addInput(input) // Create video preview layer and add it to the UI if let newCaptureVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: session) { let viewLayer = self.cameraView.layer let size = self.cameraView.bounds newCaptureVideoPreviewLayer.frame = size; viewLayer.addSublayer(newCaptureVideoPreviewLayer) self.cameraPreviewLayer = newCaptureVideoPreviewLayer; session.startRunning() let textLayer = CATextLayer() textLayer.string = "coucou" textLayer.frame = CGRect(x: 0, y: 20, width: size.width, height: 40) viewLayer.addSublayer(textLayer) hudLayer.backgroundColor = UIColor.red.cgColor hudLayer.frame = CGRect(x: size.width / 2 - 20, y: 0, width: 40, height: size.height) viewLayer.addSublayer(hudLayer) } } catch { print(error) } motionManager.deviceMotionUpdateInterval = 0.1 motionManager.startDeviceMotionUpdates(to: OperationQueue.main) { (deviceMotion, error) in if let yaw = deviceMotion?.attitude.yaw { let size = self.cameraView.bounds let x = CGFloat(yaw) * size.width self.hudLayer.frame = CGRect(x: x, y: 0, width: 10, height: size.height) } } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
12a03623b30528831346da16e54061e3
31.55
107
0.63172
false
false
false
false
kumabook/StickyNotesiOS
refs/heads/master
StickyNotes/DateFormatter.swift
mit
1
// // DateFormatter.swift // StickyNotes // // Created by Hiroki Kumamoto on 8/14/16. // Copyright © 2016 kumabook. All rights reserved. // import Foundation import Breit class DateFormatter { private static var __once: () = { dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" let posix = Locale(identifier: "en_US_POSIX") dateFormatter.locale = posix }() fileprivate static var dateFormatter = Foundation.DateFormatter() fileprivate static var onceToken : Int = 0 static var shared: Foundation.DateFormatter { _ = DateFormatter.__once return dateFormatter } } extension Date { var passedTime: String { return "\(elapsedTime.value) \(elapsedTime.unit.rawValue.localize())" } }
67d812470faa25a73675da32876b5f56
25.2
77
0.647583
false
false
false
false
khoren93/SwiftHub
refs/heads/master
SwiftHub/Modules/Search/TrendingUserCellViewModel.swift
mit
1
// // TrendingUserCellViewModel.swift // SwiftHub // // Created by Sygnoos9 on 12/18/18. // Copyright © 2018 Khoren Markosyan. All rights reserved. // import Foundation import RxSwift import RxCocoa class TrendingUserCellViewModel: DefaultTableViewCellViewModel { let user: TrendingUser init(with user: TrendingUser) { self.user = user super.init() title.accept("\(user.username ?? "") (\(user.name ?? ""))") detail.accept(user.repo?.fullname) imageUrl.accept(user.avatar) badge.accept(R.image.icon_cell_badge_user()?.template) badgeColor.accept(UIColor.Material.green900) } } extension TrendingUserCellViewModel { static func == (lhs: TrendingUserCellViewModel, rhs: TrendingUserCellViewModel) -> Bool { return lhs.user == rhs.user } }
9806513ba57a0642e6f61b04db8da738
24.9375
93
0.675904
false
false
false
false
apple/swift
refs/heads/main
test/Concurrency/Runtime/executor_deinit2.swift
apache-2.0
1
// RUN: %target-run-simple-swift(-parse-as-library -Xfrontend -disable-availability-checking) | %FileCheck %s // REQUIRES: executable_test // REQUIRES: concurrency // UNSUPPORTED: freestanding // rdar://76038845 // REQUIRES: concurrency_runtime // UNSUPPORTED: back_deployment_runtime // this needs to match with the check count below. let NUM_TASKS : Int = 100 @available(SwiftStdlib 5.1, *) final class Capture : Sendable { func doSomething() { } deinit { // CHECK-COUNT-100: deinit was called! print("deinit was called!") } } @available(SwiftStdlib 5.1, *) @main struct App { static func main() async { var n = 0 for _ in 1...NUM_TASKS { let c = Capture() let r = detach { c.doSomething() } await r.get() n += 1 } print("test complete") } }
5468675a9aabdc096f5c9f8764cac9ad
22.526316
110
0.583893
false
true
false
false
HabitRPG/habitrpg-ios
refs/heads/develop
HabitRPG/Views/SetupCustomizationItemView.swift
gpl-3.0
1
// // SetupCustomizationItemView.swift // Habitica // // Created by Phillip on 07.08.17. // Copyright © 2017 HabitRPG Inc. All rights reserved. // import UIKit class SetupCustomizationItemView: UIView { @IBOutlet weak var iconView: UIImageView! @IBOutlet weak var labelView: UILabel! @IBOutlet weak var borderView: UIView! var isActive = false { didSet { updateViewsForActivity() } } override init(frame: CGRect) { super.init(frame: frame) xibSetup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) xibSetup() } func xibSetup() { if let view = loadViewFromNib() { view.frame = bounds view.autoresizingMask = [UIView.AutoresizingMask.flexibleWidth, UIView.AutoresizingMask.flexibleHeight] addSubview(view) borderView.layer.borderColor = UIColor.purple400.cgColor } } func loadViewFromNib() -> UIView? { let bundle = Bundle(for: type(of: self)) let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle) let view = nib.instantiate(withOwner: self, options: nil)[0] as? UIView return view } func setItem(_ item: SetupCustomization) { if let icon = item.icon { iconView.image = icon } if let color = item.color { iconView.backgroundColor = color } if let text = item.text { labelView.text = text } else { labelView.isHidden = true } } private func updateViewsForActivity() { if isActive { borderView.layer.borderWidth = 4 labelView.textColor = .white } else { borderView.layer.borderWidth = 0 labelView.textColor = UIColor.white.withAlphaComponent(0.5) } } }
66c4bf6b98e4dec39d60a14e0b68a0c3
25.739726
115
0.577869
false
false
false
false
jay18001/brickkit-ios
refs/heads/master
Source/Layout/BrickLayoutSection.swift
apache-2.0
1
// // BrickLayoutSection.swift // BrickKit // // Created by Ruben Cagnie on 9/1/16. // Copyright © 2016 Wayfair LLC. All rights reserved. // import UIKit private let PrecisionAccuracy: CGFloat = 0.0000001 protocol BrickLayoutSectionDelegate: class { func brickLayoutSection(_ section: BrickLayoutSection, didCreateAttributes attributes: BrickLayoutAttributes) } protocol BrickLayoutSectionDataSource: class { /// Scroll Direction of the layout var scrollDirection: UICollectionViewScrollDirection { get } /// The current frame of interest that we want to calculate attributes in var frameOfInterest: CGRect { get } /// The edge insets for this section func edgeInsets(in section: BrickLayoutSection) -> UIEdgeInsets /// The inset for this section func inset(in section: BrickLayoutSection) -> CGFloat /// Flag that indicates if row heights need to be aligned func isAlignRowHeights(in section: BrickLayoutSection) -> Bool /// func aligment(in section: BrickLayoutSection) -> BrickAlignment /// Function called right before the height is asked. This can be used to do some other pre-calcuations func prepareForSizeCalculation(for attributes: BrickLayoutAttributes, containedIn width: CGFloat, origin: CGPoint, invalidate: Bool, in section: BrickLayoutSection, updatedAttributes: OnAttributesUpdatedHandler?) /// Returns the width of attributes at a given index /// /// - Parameters: /// - totalWidth: width minus the edgeinsets /// - Returns: width for attributes at a given index func width(for index: Int, totalWidth: CGFloat, startingAt origin: CGFloat, in section: BrickLayoutSection) -> CGFloat /// Returns the size for attributes at a given index func size(for attributes: BrickLayoutAttributes, containedIn width: CGFloat, in section: BrickLayoutSection) -> CGSize /// Returns the identifier for attributes at a given index func identifier(for index: Int, in section: BrickLayoutSection) -> String /// Returns if attributes are estimated at a given index func isEstimate(for attributes: BrickLayoutAttributes, in section: BrickLayoutSection) -> Bool /// Returns the downstream indexpaths for this section func downStreamIndexPaths(in section: BrickLayoutSection) -> [IndexPath] } /// BrickLayoutSection manages all the attributes that are in one specific section internal class BrickLayoutSection { /// The BrickLayoutAttributes that represent this section on a level higher /// - Optional because the root section will not have this set internal var sectionAttributes: BrickLayoutAttributes? /// Index of the section internal let sectionIndex: Int /// Number of Items in this section internal fileprivate(set) var numberOfItems: Int /// Calculated attributes for this section /// This is a dictionary, because the attributes might get calculated in a different order and could get removed if we need to free up memory internal fileprivate(set) var attributes: [Int: BrickLayoutAttributes] = [:] /// IndexPaths of attributes that are touched by behaviors (originalFrame and frame are different) internal fileprivate(set) var behaviorAttributesIndexPaths: Set<IndexPath> = [] /// Frame that contains this whole section internal fileprivate(set) var frame: CGRect = .zero /// Width of the section. Can be set by `setSectionWidth` /// This is not a calculated property of the frame because in case of horizontal scrolling, the values will be different internal fileprivate(set) var sectionWidth: CGFloat /// Origin of the frame. Can be set by `setOrigin` internal var origin: CGPoint { return frame.origin } /// DataSource that is used to calculate the section internal weak var dataSource: BrickLayoutSectionDataSource? /// Unwrapped dataSource that is used to avoid unwrapping all the time var _dataSource: BrickLayoutSectionDataSource { guard let unwrappedDataSource = self.dataSource else { fatalError("`dataSource` should be set when calling a function to the layoutSection") } return unwrappedDataSource } /// Delegate that is used get informed by certain events internal weak var delegate: BrickLayoutSectionDelegate? /// Default constructor /// /// - parameter sectionIndex: Index of the section /// - parameter sectionAttributes: Attributes on a higher level that contain this section /// - parameter numberOfItems: Initial number of items in this section /// - parameter origin: Origin of the section /// - parameter sectionWidth: Width of the section /// - parameter dataSource: DataSource /// /// - returns: instance of the BrickLayoutSection init(sectionIndex: Int, sectionAttributes: BrickLayoutAttributes?, numberOfItems: Int, origin: CGPoint, sectionWidth: CGFloat, dataSource: BrickLayoutSectionDataSource, delegate: BrickLayoutSectionDelegate? = nil) { self.dataSource = dataSource self.delegate = delegate self.sectionIndex = sectionIndex self.numberOfItems = numberOfItems self.sectionAttributes = sectionAttributes self.sectionWidth = sectionWidth initializeFrameWithOrigin(origin, sectionWidth: sectionWidth) } /// Initialize the frame with the default origin and width /// /// - parameter sectionOrigin: origin /// - parameter sectionWidth: width /// fileprivate func initializeFrameWithOrigin(_ origin: CGPoint, sectionWidth: CGFloat) { frame.origin = origin frame.size.width = sectionWidth } /// Set the number of items for this BrickLayoutSection /// /// - Parameters: /// - addedAttributes: callback for the added attributes /// - removedAttributes: callback for the removed attributes func setNumberOfItems(_ numberOfItems: Int, addedAttributes: OnAttributesUpdatedHandler?, removedAttributes: OnAttributesUpdatedHandler?) { guard numberOfItems != self.numberOfItems else { return } let difference = numberOfItems - self.numberOfItems if difference > 0 { self.numberOfItems = numberOfItems var startIndex = attributes.count updateAttributeIdentifiers(targetStartIndex: &startIndex) createOrUpdateCells(from: startIndex, invalidate: true, updatedAttributes: addedAttributes) } else { self.numberOfItems = numberOfItems while attributes.count > numberOfItems { let lastIndex = attributes.keys.max()! // Max Element will always be available based on this logic (difference is smaller than 0, so there are values available) let last = attributes[lastIndex]! removedAttributes?(last, last.frame) attributes.removeValue(forKey: lastIndex) } var startIndex = attributes.count updateAttributeIdentifiers(targetStartIndex: &startIndex) createOrUpdateCells(from: startIndex, invalidate: true, updatedAttributes: nil) } } /// Update the identifiers for the attributes /// /// - Parameter targetStartIndex: The index that should start invalidating bricks func updateAttributeIdentifiers(targetStartIndex: inout Int) { for (index, attribute) in attributes { let identifier = _dataSource.identifier(for: index, in: self) if attribute.identifier != identifier { targetStartIndex = min(index, targetStartIndex) attribute.identifier = identifier invalidateAttributes(attribute) } } } func appendItem(_ updatedAttributes: OnAttributesUpdatedHandler?) { numberOfItems += 1 createOrUpdateCells(from: attributes.count, invalidate: true, updatedAttributes: updatedAttributes) } func deleteLastItem(_ updatedAttributes: OnAttributesUpdatedHandler?) { guard let lastIndex = attributes.keys.max(), let last = attributes[lastIndex] else { return } numberOfItems -= 1 attributes.removeValue(forKey: lastIndex) createOrUpdateCells(from: attributes.count, invalidate: true, updatedAttributes: updatedAttributes) updatedAttributes?(last, last.frame) } func setOrigin(_ origin: CGPoint, fromBehaviors: Bool, updatedAttributes: OnAttributesUpdatedHandler?) { guard self.origin != origin else { return } self.frame.origin = origin _ = continueCalculatingCells() createOrUpdateCells(from: 0, invalidate: false, updatedAttributes: updatedAttributes) } func setSectionWidth(_ sectionWidth: CGFloat, updatedAttributes: OnAttributesUpdatedHandler?) { if self.sectionWidth != sectionWidth { self.sectionWidth = sectionWidth invalidateAttributes(updatedAttributes) } } func invalidateAttributes(_ updatedAttributes: OnAttributesUpdatedHandler?) { createOrUpdateCells(from: 0, invalidate: true, updatedAttributes: updatedAttributes) } fileprivate func invalidateAttributes(_ attributes: BrickLayoutAttributes) { attributes.isEstimateSize = true attributes.originalFrame.size.width = 0 attributes.frame.size.width = 0 } func update(height: CGFloat, at index: Int, updatedAttributes: OnAttributesUpdatedHandler?) { guard let brickAttributes = attributes[index] else { return } brickAttributes.isEstimateSize = false guard brickAttributes.originalFrame.height != height else { return } brickAttributes.originalFrame.size.height = height createOrUpdateCells(from: index, invalidate: false, updatedAttributes: updatedAttributes) } func invalidate(at index: Int, updatedAttributes: OnAttributesUpdatedHandler?) { guard let brickAttributes = attributes[index] else { return // Attributes not yet calculated } invalidateAttributes(brickAttributes) let width = widthAtIndex(index, startingAt: brickAttributes.originalFrame.minX - _dataSource.edgeInsets(in: self).left, dataSource: _dataSource) let size = _dataSource.size(for: brickAttributes, containedIn: width, in: self) brickAttributes.originalFrame.size = size brickAttributes.frame.size = size createOrUpdateCells(from: index, invalidate: false, updatedAttributes: updatedAttributes) } func changeVisibility(_ visibility: Bool, at index: Int, updatedAttributes: OnAttributesUpdatedHandler?) { guard let brickAttributes = attributes[index] else { return } brickAttributes.isHidden = visibility createOrUpdateCells(from: index, invalidate: false, updatedAttributes: updatedAttributes) } fileprivate func widthAtIndex(_ index: Int, startingAt origin: CGFloat, dataSource: BrickLayoutSectionDataSource) -> CGFloat { let edgeInsets = dataSource.edgeInsets(in: self) let totalWidth = sectionWidth - edgeInsets.left - edgeInsets.right return dataSource.width(for: index, totalWidth: totalWidth, startingAt: origin, in: self) } /// Continue the calculation of attributes if needed /// /// - Parameter updatedAttributes: callback for when attributes were actually calculated /// - Returns: flag that indicates if more cells were calculated func continueCalculatingCells(_ updatedAttributes: OnAttributesUpdatedHandler? = nil) -> Bool { guard attributes.count != numberOfItems else { return false } let downStreamIndexPathsCount = dataSource?.downStreamIndexPaths(in: self).count ?? 0 let nextIndex = max(0, attributes.count - downStreamIndexPathsCount) createOrUpdateCells(from: nextIndex, invalidate: false, updatedAttributes: updatedAttributes) return true } /// Main function to recalculate cells /// /// - Parameters: /// - firstIndex: The index the calculation needs to start from (the main reason is to just calculate the next cells /// - invalidate: Identifies if the attributes need to be invalidated (reset height etc) /// - updatedAttributes: Callback for the attributes that have been updated fileprivate func createOrUpdateCells(from firstIndex: Int, invalidate: Bool, updatedAttributes: OnAttributesUpdatedHandler?) { guard let dataSource = dataSource else { return } let edgeInsets = _dataSource.edgeInsets(in: self) let inset = dataSource.inset(in: self) let startAndMaxY = findStartOriginAndMaxY(for: firstIndex, edgeInsets: edgeInsets, inset: inset, invalidate: invalidate) var maxY: CGFloat = startAndMaxY.1 var x: CGFloat = startAndMaxY.0.x var y: CGFloat = startAndMaxY.0.y let frameOfInterest = dataSource.frameOfInterest let numberOfItems = self.numberOfItems for index in firstIndex..<numberOfItems { // Create or Update an attribute at an index. If returned true, continue calculating. If not, break if !createOrUpdateAttribute(at: index, with: dataSource, x: &x, y: &y, maxY: &maxY, force: false, invalidate: invalidate, frameOfInterest: frameOfInterest, updatedAttributes: updatedAttributes) { break } } // If rows need to be aligned, make sure the previous lines are checked handleRow(for: attributes.count - 1, maxHeight: maxY - y, updatedAttributes: updatedAttributes) // Downstream IndexPaths. Just add these attributes at the end of the stack. // The idea is to have them available for behaviors, but not visible let downStreamIndexPaths = dataSource.downStreamIndexPaths(in: self) for indexPath in downStreamIndexPaths { guard indexPath.section == sectionIndex else { continue } if let downstreamAttributes = self.attributes[indexPath.item] { // If the attribute already exists, but not in the current frameset, push it off screen if indexPath.item >= attributes.count { downstreamAttributes.frame.origin.y = maxY downstreamAttributes.originalFrame.origin.y = maxY } } else { // create the attribute, so it's available for the behaviors to pick it up _ = createOrUpdateAttribute(at: indexPath.item, with: dataSource, x: &x, y: &y, maxY: &maxY, force: true, invalidate: invalidate, frameOfInterest: frameOfInterest, updatedAttributes: updatedAttributes) } } // Frame Height var frameHeight: CGFloat = 0 if let first = attributes[0] { let percentageDone = CGFloat(attributes.count) / CGFloat(numberOfItems) switch dataSource.scrollDirection { case .horizontal: frameHeight = maxY + edgeInsets.bottom if percentageDone < 1 { let width = (x - first.originalFrame.origin.x) x = (width / percentageDone) } case .vertical: // If not all attributes are calculated, we need to estimate how big the section will be let height = (maxY - first.originalFrame.origin.y) + inset let frameHeightA = (height / percentageDone) - inset + edgeInsets.bottom + edgeInsets.top let frameHeightB = (maxY - first.originalFrame.origin.y) + edgeInsets.bottom + edgeInsets.top if percentageDone < 1 { frameHeight = frameHeightA } else { frameHeight = frameHeightB } } //If the height is less than the edgeinsets, clearly nothing is calculated. Set it to 0 if frameHeight <= edgeInsets.bottom + edgeInsets.top { frameHeight = 0 } } else if numberOfItems > 0 { // there are no attributes calculated, but there will (because numberOfItems is larger than zero) // set a dummy height of 1 to not be set invisible frameHeight = 1 + edgeInsets.bottom + edgeInsets.top } frame.size.height = frameHeight switch dataSource.scrollDirection { case .vertical: frame.size.width = sectionWidth case .horizontal: x -= inset // Take off the inset as this is added to the end frame.size.width = x + edgeInsets.right } if brickDebug { printAttributes() } } /// To continue calculating, it needs to start from a certain origin. To make sure that the rows are /// /// - Parameters: /// - index: start index /// - edgeInsets /// - inset /// - Returns: a tuple of the start origin and maxY fileprivate func findStartOriginAndMaxY(for index: Int, edgeInsets: UIEdgeInsets, inset: CGFloat, invalidate: Bool) -> (CGPoint, CGFloat) { let create = attributes.isEmpty let startFrame = sectionAttributes?.originalFrame ?? frame var startOrigin = CGPoint(x: startFrame.origin.x + edgeInsets.left, y: startFrame.origin.y + edgeInsets.top) var maxY = startFrame.origin.y if !create { if index > 0 { var originY: CGFloat? if let currentAttribute = attributes[index] { originY = currentAttribute.originalFrame.minY } var startOriginFound = false for index in stride(from: (index-1), to: -1, by: -1) { if let nextAttribute = attributes[index] , !nextAttribute.isHidden { if originY == nil { originY = nextAttribute.originalFrame.minY } if !startOriginFound { startOrigin = CGPoint(x: nextAttribute.originalFrame.maxX + inset, y: nextAttribute.originalFrame.origin.y) startOriginFound = true } maxY = max(maxY, nextAttribute.originalFrame.maxY) if startOrigin.y != nextAttribute.originalFrame.minY { break } } } } else if !invalidate { // Check the first visible attribute for index in 0..<index { if let first = attributes[index] , !first.isHidden { maxY = first.originalFrame.maxY startOrigin = first.originalFrame.origin } } } } return (startOrigin, maxY) } func handleRow(for index: Int, maxHeight: CGFloat, updatedAttributes: OnAttributesUpdatedHandler?) { if _dataSource.scrollDirection == .vertical { updateHeightAndAlignForRowWithStartingIndex(index, maxHeight: maxHeight, updatedAttributes: updatedAttributes) } } /// Update the height for a row starting at a given index func updateHeightAndAlignForRowWithStartingIndex(_ index: Int, maxHeight: CGFloat, updatedAttributes: OnAttributesUpdatedHandler?) { var rowWidthWithoutInsets: CGFloat = 0 // Keep track of all the widths, so we can calculate the correct inset for `Justified`-alignment let rowAttributes: [BrickLayoutAttributes] = calculateRowAttributes(startingAt: index, rowWidthWithoutInsets: &rowWidthWithoutInsets) // Keep track of all attributes in this row guard rowAttributes.count > 0 else { return } let edgeInsets = _dataSource.edgeInsets(in: self) let totalSectionWidth = (sectionWidth - edgeInsets.right - edgeInsets.left) // Total width of the section minus the insets let totalRowWidth = rowAttributes.last!.originalFrame.maxX - rowAttributes.first!.originalFrame.minX // Total width of the bricks (with insets, as supposed to rowWidths) let inset: CGFloat let numberOfInsets: CGFloat = CGFloat(rowAttributes.count-1) let alignment = _dataSource.aligment(in: self) switch alignment.horizontal { case .justified: // Distribute insets evenly inset = (totalSectionWidth - rowWidthWithoutInsets) / numberOfInsets default: // Distribute the insets the way they were inset = (totalRowWidth - rowWidthWithoutInsets) / numberOfInsets } // Get the x value of the first brick let startX: CGFloat switch alignment.horizontal { case .center: startX = (totalSectionWidth - totalRowWidth) / 2 // Start from the middle minus the middle of the bricks total width case .right: startX = totalSectionWidth - totalRowWidth // Start at the end of the section minus the total of the bricks total width default: startX = 0 // Start at zero } updateRow(for: rowAttributes, with: maxHeight, startingAt: startX, edgeInsets: edgeInsets, inset: inset, updatedAttributes: updatedAttributes) } /// Update the attributes within the row fileprivate func updateRow(for rowAttributes: [BrickLayoutAttributes], with maxHeight: CGFloat, startingAt startX: CGFloat, edgeInsets: UIEdgeInsets, inset: CGFloat, updatedAttributes: OnAttributesUpdatedHandler?) { // Check if the height need to be aligned let alignRowHeights = _dataSource.isAlignRowHeights(in: self) // start at the startX + insets + origin var x: CGFloat = edgeInsets.left + origin.x + startX // Iterate over the attributes (starting from the first one) and update each frame for brickAttributes in rowAttributes { let oldFrame = brickAttributes.frame var newFrame = oldFrame if alignRowHeights { newFrame.size.height = maxHeight } newFrame.origin.x = x let offsetY: CGFloat switch _dataSource.aligment(in: self).vertical { case .top: offsetY = 0 case .center: offsetY = (maxHeight / 2) - (newFrame.height / 2) case .bottom: offsetY = maxHeight - newFrame.height } newFrame.origin.y += offsetY if newFrame != oldFrame { brickAttributes.frame = newFrame updatedAttributes?(brickAttributes, oldFrame) _dataSource.prepareForSizeCalculation(for: brickAttributes, containedIn: brickAttributes.frame.width, origin: brickAttributes.frame.origin, invalidate: false, in: self, updatedAttributes: updatedAttributes) } x += oldFrame.width + inset } } /// Calculate the row attributes /// /// - Parameters: /// - startingIndex: index of the attributes within the row /// - rowWidthWithoutInsets: variable to indicate what the row width is without insets /// - Returns: array of all attributes within the row fileprivate func calculateRowAttributes(startingAt startingIndex: Int, rowWidthWithoutInsets: inout CGFloat) -> [BrickLayoutAttributes] { guard let brickAttributes = self.attributes[startingIndex] else { return [] } var currentIndex = startingIndex let y = brickAttributes.originalFrame.origin.y var rowAttributes: [BrickLayoutAttributes] = [] // Keep track of all attributes in this row // Count down until attributes are found with a lower Y-origin while currentIndex >= 0 { guard let brickAttributes = attributes[currentIndex] , !brickAttributes.isHidden else { currentIndex -= 1 continue } if brickAttributes.originalFrame.origin.y != y { break // Done, no more attributes on this row } rowAttributes.insert(brickAttributes, at: 0) // insert at the front, so the attributes are sorted by lowest first rowWidthWithoutInsets += brickAttributes.originalFrame.width currentIndex -= 1 } return rowAttributes } func printAttributes() { guard attributes.count < 100 else { // Prevent that the "Huge" test aren't taking forever to complete return } BrickUtils.print("\n") BrickUtils.print("Attributes for section \(sectionIndex) in \(String(describing: dataSource))") BrickUtils.print("Number of attributes: \(attributes.count) in \(_dataSource.frameOfInterest)") BrickUtils.print("Frame: \(self.frame)") let keys = attributes.keys.sorted(by: <) for key in keys { BrickUtils.print("\(key): \(attributes[key]!)") } } /// Create or update 1 cell /// - Returns: flag if the cell was created func createOrUpdateAttribute(at index: Int, with dataSource: BrickLayoutSectionDataSource, x: inout CGFloat, y: inout CGFloat, maxY: inout CGFloat, force: Bool, invalidate: Bool, frameOfInterest: CGRect, updatedAttributes: OnAttributesUpdatedHandler?) -> Bool { let edgeInsets = dataSource.edgeInsets(in: self) let inset = dataSource.inset(in: self) let indexPath = IndexPath(item: index, section: sectionIndex) var brickAttributes: BrickLayoutAttributes! = attributes[index] let existingAttribute: Bool = brickAttributes != nil var width = widthAtIndex(index, startingAt: x - edgeInsets.left - origin.x, dataSource: dataSource) let shouldBeOnNextRow: Bool switch dataSource.scrollDirection { case .horizontal: shouldBeOnNextRow = false case .vertical: let leftOverSpace = (sectionWidth - edgeInsets.right) - (x + width - origin.x) shouldBeOnNextRow = leftOverSpace < 0 && fabs(leftOverSpace) > PrecisionAccuracy } var nextY: CGFloat = y var nextX: CGFloat = x if shouldBeOnNextRow { handleRow(for: index - 1, maxHeight: maxY - nextY, updatedAttributes: updatedAttributes) if maxY > nextY { nextY = maxY + inset } nextX = origin.x + edgeInsets.left } let offsetX: CGFloat let offsetY: CGFloat if let sectionAttributes = sectionAttributes , sectionAttributes.originalFrame != nil { offsetX = sectionAttributes.frame.origin.x - sectionAttributes.originalFrame.origin.x offsetY = sectionAttributes.frame.origin.y - sectionAttributes.originalFrame.origin.y } else { offsetX = 0 offsetY = 0 } nextX += offsetX nextY += offsetY let nextOrigin = CGPoint(x: nextX, y: nextY) let restrictedScrollDirection: Bool // For now, only restrict if scrolling vertically (will update later for Horizontal) switch dataSource.scrollDirection { case .vertical: restrictedScrollDirection = true case .horizontal: restrictedScrollDirection = false } if !existingAttribute && !frameOfInterest.contains(nextOrigin) && !force && restrictedScrollDirection { return false } nextX -= offsetX nextY -= offsetY x = nextX y = nextY let cellOrigin = nextOrigin let oldFrame:CGRect? let oldOriginalFrame: CGRect? if existingAttribute { brickAttributes = attributes[index] oldFrame = brickAttributes.frame oldOriginalFrame = brickAttributes.originalFrame if invalidate { invalidateAttributes(brickAttributes) brickAttributes.isEstimateSize = dataSource.isEstimate(for: brickAttributes, in: self) } } else { brickAttributes = createAttribute(at: indexPath, with: dataSource) oldFrame = nil oldOriginalFrame = nil } brickAttributes.identifier = dataSource.identifier(for: indexPath.item, in: self) let height: CGFloat // Prepare the datasource that size calculation will happen brickAttributes.frame.origin = cellOrigin brickAttributes.originalFrame = brickAttributes.frame dataSource.prepareForSizeCalculation(for: brickAttributes, containedIn: width, origin: cellOrigin, invalidate: invalidate, in: self, updatedAttributes: updatedAttributes) if let brickFrame = oldOriginalFrame , !invalidate { height = brickFrame.height width = brickFrame.width } else { let size = dataSource.size(for: brickAttributes, containedIn: width, in: self) height = size.height width = size.width } var brickFrame = CGRect(origin: cellOrigin, size: CGSize(width: width, height: height)) brickAttributes.frame = brickFrame brickFrame.origin.x -= offsetX brickFrame.origin.y -= offsetY brickAttributes.originalFrame = brickFrame if !existingAttribute { delegate?.brickLayoutSection(self, didCreateAttributes: brickAttributes) } updatedAttributes?(brickAttributes, oldFrame) let sectionIsHidden = sectionAttributes?.isHidden ?? false let brickIsHiddenOrHasNoHeight = height <= 0 || brickAttributes.isHidden if sectionIsHidden || !brickIsHiddenOrHasNoHeight { x = brickFrame.maxX + inset maxY = max(brickAttributes.originalFrame.maxY, maxY) } brickAttributes.alpha = brickAttributes.isHidden ? 0 : 1 return true } func createAttribute(at indexPath: IndexPath, with dataSource: BrickLayoutSectionDataSource) -> BrickLayoutAttributes { let brickAttributes = BrickLayoutAttributes(forCellWith: indexPath) attributes[indexPath.item] = brickAttributes brickAttributes.isEstimateSize = dataSource.isEstimate(for: brickAttributes, in: self) return brickAttributes } } // MARK: - Binary search for elements extension BrickLayoutSection { func registerUpdatedAttributes(_ attributes: BrickLayoutAttributes) { if attributes.frame != attributes.originalFrame { behaviorAttributesIndexPaths.insert(attributes.indexPath) } else { behaviorAttributesIndexPaths.remove(attributes.indexPath) } } func layoutAttributesForElementsInRect(_ rect: CGRect, with zIndexer: BrickZIndexer) -> [UICollectionViewLayoutAttributes] { var attributes = [UICollectionViewLayoutAttributes]() if self.attributes.isEmpty { return attributes } // Find an index that is pretty close to the top of the rect let closestIndex: Int switch _dataSource.scrollDirection { case .vertical: closestIndex = findEstimatedClosestIndexVertical(in: rect) case .horizontal: closestIndex = findEstimatedClosestIndexHorizontal(in: rect) } // Closure that checks if an attribute is within the rect and adds it to the attributes to return // Returns true if the frame is within the rect let frameCheck: (_ index: Int) -> Bool = { index in guard let brickAttributes = self.attributes[index] else { return false } if rect.intersects(brickAttributes.frame) { let hasZeroHeight = brickAttributes.frame.height == 0 || brickAttributes.frame.width == 0 if !brickAttributes.isHidden && !hasZeroHeight && !attributes.contains(brickAttributes) { brickAttributes.setAutoZIndex(zIndexer.zIndex(for: brickAttributes.indexPath)) attributes.append(brickAttributes) } return true } else { // if the frame is not the same as the originalFrame, continue checking because the attribute could be offscreen return brickAttributes.frame != brickAttributes.originalFrame } } // Go back to see if previous attributes are not closer for index in stride(from: (closestIndex - 1), to: -1, by: -1) { if !frameCheck(index) { // Check if the next attribute is on the same row. If so, continue checking let nextAttributeIsOnSameRow = index != 0 && self.attributes[index]!.frame.minY == self.attributes[index - 1]!.frame.minY if !nextAttributeIsOnSameRow { break } } } // Go forward until an attribute is outside or the rect for index in closestIndex..<self.attributes.count { if !frameCheck(index) { break } } // Verify the behaviors attributes and check if they are in the frame as well for indexPath in behaviorAttributesIndexPaths { _ = frameCheck(indexPath.item) } return attributes } func findEstimatedClosestIndexVertical(in rect: CGRect) -> Int { return findEstimatedClosestIndex(in: rect, referencePoint: { (frame) -> CGFloat in return frame.minY }) } func findEstimatedClosestIndexHorizontal(in rect: CGRect) -> Int { return findEstimatedClosestIndex(in: rect, referencePoint: { (frame) -> CGFloat in return frame.minX }) } func findEstimatedClosestIndex(in rect: CGRect, referencePoint: (_ forFrame: CGRect) -> CGFloat) -> Int { let min = referencePoint(rect) var complexity = 0 var lowerBound = 0 var upperBound = attributes.count while lowerBound < upperBound { complexity += 1 let midIndex = lowerBound + (upperBound - lowerBound) / 2 guard let frame = attributes[midIndex]?.frame else { break } if referencePoint(frame) < min { lowerBound = midIndex + 1 } else { upperBound = midIndex } } return lowerBound } }
671c81cb4e02d5dad209216543d50933
41.235294
265
0.649315
false
false
false
false
jmgc/swift
refs/heads/master
test/Reflection/typeref_decoding_imported.swift
apache-2.0
1
// XFAIL: OS=windows-msvc // SR-12893 // XFAIL: openbsd // UNSUPPORTED: CPU=arm64e // RUN: %empty-directory(%t) // RUN: %target-build-swift %S/Inputs/ImportedTypes.swift %S/Inputs/ImportedTypesOther.swift -parse-as-library -emit-module -emit-library -module-name TypesToReflect -o %t/%target-library-name(TypesToReflect) -I %S/Inputs // RUN: %target-swift-reflection-dump -binary-filename %t/%target-library-name(TypesToReflect) | %FileCheck %s --check-prefix=CHECK-%target-ptrsize --check-prefix=CHECK-%target-cpu // ... now, test single-frontend mode with multi-threaded LLVM emission: // RUN: %empty-directory(%t) // RUN: %target-build-swift %S/Inputs/ImportedTypes.swift %S/Inputs/ImportedTypesOther.swift -parse-as-library -emit-module -emit-library -module-name TypesToReflect -o %t/%target-library-name(TypesToReflect) -I %S/Inputs -whole-module-optimization -num-threads 2 // RUN: %target-swift-reflection-dump -binary-filename %t/%target-library-name(TypesToReflect) | %FileCheck %s --check-prefix=CHECK-%target-ptrsize --check-prefix=CHECK-%target-cpu // CHECK-32: FIELDS: // CHECK-32: ======= // CHECK-32: TypesToReflect.HasCTypes // CHECK-32: ------------------------ // CHECK-32: mcs: __C.MyCStruct // CHECK-32: (struct __C.MyCStruct) // CHECK-32: mce: __C.MyCEnum // CHECK-32: (struct __C.MyCEnum) // CHECK-32: __C.MyCStruct // CHECK-32: ------------- // CHECK-32: i: Swift.Int32 // CHECK-32: (struct Swift.Int32) // CHECK-32: ip: Swift.Optional<Swift.UnsafeMutablePointer<Swift.Int32>> // CHECK-32: (bound_generic_enum Swift.Optional // CHECK-32: (bound_generic_struct Swift.UnsafeMutablePointer // CHECK-32: (struct Swift.Int32))) // CHECK-32: c: Swift.Int8 // CHECK-32: (struct Swift.Int8) // CHECK-32: TypesToReflect.AlsoHasCTypes // CHECK-32: ---------------------------- // CHECK-32: mcu: __C.MyCUnion // CHECK-32: (struct __C.MyCUnion) // CHECK-32: mcsbf: __C.MyCStructWithBitfields // CHECK-32: (struct __C.MyCStructWithBitfields) // CHECK-32: ASSOCIATED TYPES: // CHECK-32: ================= // CHECK-32: BUILTIN TYPES: // CHECK-32: ============== // CHECK-32-LABEL: - __C.MyCStruct: // CHECK-32: Size: 12 // CHECK-32: Alignment: 4 // CHECK-32: Stride: 12 // CHECK-32: NumExtraInhabitants: 0 // CHECK-32: BitwiseTakable: 1 // CHECK-32-LABEL: - __C.MyCEnum: // CHECK-32: Size: 4 // CHECK-32: Alignment: 4 // CHECK-32: Stride: 4 // CHECK-32: NumExtraInhabitants: 0 // CHECK-32: BitwiseTakable: 1 // CHECK-32-LABEL: - __C.MyCUnion: // CHECK-32: Size: 4 // CHECK-32: Alignment: 4 // CHECK-32: Stride: 4 // CHECK-32: NumExtraInhabitants: 0 // CHECK-32: BitwiseTakable: 1 // CHECK-i386-LABEL: - __C.MyCStructWithBitfields: // CHECK-i386: Size: 4 // CHECK-i386: Alignment: 4 // CHECK-i386: Stride: 4 // CHECK-i386: NumExtraInhabitants: 0 // CHECK-i386: BitwiseTakable: 1 // CHECK-arm-LABEL: - __C.MyCStructWithBitfields: // CHECK-arm: Size: 2 // CHECK-arm: Alignment: 1 // CHECK-arm: Stride: 2 // CHECK-arm: NumExtraInhabitants: 0 // CHECK-arm: BitwiseTakable: 1 // CHECK-32: CAPTURE DESCRIPTORS: // CHECK-32: ==================== // CHECK-64: FIELDS: // CHECK-64: ======= // CHECK-64: TypesToReflect.HasCTypes // CHECK-64: ------------------------ // CHECK-64: mcs: __C.MyCStruct // CHECK-64: (struct __C.MyCStruct) // CHECK-64: mce: __C.MyCEnum // CHECK-64: (struct __C.MyCEnum) // CHECK-64: mcu: __C.MyCUnion // CHECK-64: (struct __C.MyCUnion) // CHECK-64: __C.MyCStruct // CHECK-64: ------------- // CHECK-64: i: Swift.Int32 // CHECK-64: (struct Swift.Int32) // CHECK-64: ip: Swift.Optional<Swift.UnsafeMutablePointer<Swift.Int32>> // CHECK-64: (bound_generic_enum Swift.Optional // CHECK-64: (bound_generic_struct Swift.UnsafeMutablePointer // CHECK-64: (struct Swift.Int32))) // CHECK-64: c: Swift.Int8 // CHECK-64: (struct Swift.Int8) // CHECK-64: TypesToReflect.AlsoHasCTypes // CHECK-64: ---------------------------- // CHECK-64: mcu: __C.MyCUnion // CHECK-64: (struct __C.MyCUnion) // CHECK-64: mcsbf: __C.MyCStructWithBitfields // CHECK-64: (struct __C.MyCStructWithBitfields) // CHECK-64: ASSOCIATED TYPES: // CHECK-64: ================= // CHECK-64: BUILTIN TYPES: // CHECK-64: ============== // CHECK-64-LABEL: - __C.MyCStruct: // CHECK-64: Size: 24 // CHECK-64: Alignment: 8 // CHECK-64: Stride: 24 // CHECK-64: NumExtraInhabitants: 0 // CHECK-64: BitwiseTakable: 1 // CHECK-64-LABEL: - __C.MyCEnum: // CHECK-64: Size: 4 // CHECK-64: Alignment: 4 // CHECK-64: Stride: 4 // CHECK-64: NumExtraInhabitants: 0 // CHECK-64: BitwiseTakable: 1 // CHECK-64-LABEL: - __C.MyCUnion: // CHECK-64: Size: 8 // CHECK-64: Alignment: 8 // CHECK-64: Stride: 8 // CHECK-64: NumExtraInhabitants: 0 // CHECK-64: BitwiseTakable: 1 // CHECK-64-LABEL: - __C.MyCStructWithBitfields: // CHECK-64: Size: 4 // CHECK-64: Alignment: 4 // CHECK-64: Stride: 4 // CHECK-64: NumExtraInhabitants: 0 // CHECK-64: BitwiseTakable: 1 // CHECK-64: CAPTURE DESCRIPTORS: // CHECK-64: ====================
1b34f24a346ba1fc33c6b5b6b25f3b48
28.446429
263
0.65191
false
false
false
false
darina/omim
refs/heads/master
iphone/Maps/UI/Welcome/WhatsNew/WhatsNewBuilder.swift
apache-2.0
4
class WhatsNewBuilder { static var configs:[WhatsNewPresenter.WhatsNewConfig] { return [ WhatsNewPresenter.WhatsNewConfig(image: UIImage(named: "img_whatsnew_lp"), title: "whatsnew_lp_title", text: "whatsnew_lp_message", buttonNextTitle: "whatsnew_trial_cta", isCloseButtonHidden: false, action: { let subscribeViewController = SubscriptionViewBuilder.buildLonelyPlanet(parentViewController: MapViewController.shared(), source: kStatWhatsNew, successDialog: .goToCatalog, completion: nil) MapViewController.shared().present(subscribeViewController, animated: true) }), WhatsNewPresenter.WhatsNewConfig(image: UIImage(named: "img_whatsnew_lp"), title: "whatsnew_lp_title", text: "whatsnew_lp_message", buttonNextTitle: "done") ] } static func build(delegate: WelcomeViewDelegate) -> [UIViewController] { return WhatsNewBuilder.configs.map { (config) -> UIViewController in let sb = UIStoryboard.instance(.welcome) let vc = sb.instantiateViewController(ofType: WelcomeViewController.self); let router = WelcomeRouter(viewController: vc, delegate: delegate) let presenter = WhatsNewPresenter(view: vc, router: router, config: config) vc.presenter = presenter return vc } } }
7dce2a7cdf490262310eac95204a45bb
54.675676
161
0.454369
false
true
false
false