repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
polydice/ICInputAccessory
Source/TokenField/InsetLabel.swift
1
2423
// // InsetLabel.swift // iCook // // Created by Ben on 10/07/2015. // Copyright (c) 2015 Polydice, Inc. // // 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 internal class InsetLabel: UILabel { enum CornerRadius { case dynamic case constant(CGFloat) } var contentEdgeInsets = UIEdgeInsets.zero var cornerRadius = CornerRadius.constant(0) convenience init(contentEdgeInsets: UIEdgeInsets, cornerRadius: CornerRadius = .constant(0)) { self.init(frame: CGRect.zero) self.contentEdgeInsets = contentEdgeInsets self.cornerRadius = cornerRadius switch cornerRadius { case let .constant(radius) where radius > 0: layer.cornerRadius = radius fallthrough // swiftlint:disable:this fallthrough case .dynamic: layer.masksToBounds = true layer.shouldRasterize = true layer.rasterizationScale = UIScreen.main.scale default: break } } // MARK: - UIView override var intrinsicContentSize: CGSize { let size = super.intrinsicContentSize return CGSize( width: contentEdgeInsets.left + size.width + contentEdgeInsets.right, height: contentEdgeInsets.top + size.height + contentEdgeInsets.bottom ) } override func layoutSubviews() { super.layoutSubviews() if case .dynamic = cornerRadius { layer.cornerRadius = frame.height / 2 } } }
mit
085c8652180584339cbb3f8552e7f727
31.743243
96
0.721832
4.528972
false
false
false
false
andrebocchini/SwiftChattyOSX
Pods/SwiftChatty/SwiftChatty/Responses/Client Data/GetCategoryFiltersResponse.swift
1
845
// // GetCategoryFiltersResponse.swift // SwiftChatty // // Created by Andre Bocchini on 1/27/16. // Copyright © 2016 Andre Bocchini. All rights reserved. // import Genome /// SeeAlso: http://winchatty.com/v2/readme#_Toc421451697 public struct GetCategoryFiltersResponse { public var nws: Bool = false public var stupid: Bool = false public var political: Bool = false public var tangent: Bool = false public var informative: Bool = false public init() {} } extension GetCategoryFiltersResponse: MappableResponse { public mutating func sequence(map: Map) throws { try nws <~ map["filters.nws"] try stupid <~ map["filters.stupid"] try political <~ map["filters.political"] try tangent <~ map["filters.tangent"] try informative <~ map["filters.informative"] } }
mit
ed85f494c958e9e53c94d990e000e09f
23.823529
57
0.674171
4.137255
false
false
false
false
dche/FlatCG
Sources/Point.swift
1
4348
// // FlatCG - Point.swift // // Copyright (c) 2016 The FlatCG authors. // Licensed under MIT License. import simd import GLMath // FIXME: Currently `Point` is choosed as the main type parameter of all // geometry related types for carrying dimension and precision // information. This is not ideal. // Current design is hindered greatly by the generic type of SWIFT. // Re-design is needed. /// A point in Euclidean space. public protocol Point: Equatable, ApproxEquatable, Interpolatable { /// `VectorType` determines the dimension and precision of a `Point`. associatedtype VectorType: FloatVector typealias Component = VectorType.Component // SWIFT EVOLUTION: Constraints between `VectorType` and `TransformMatrixType` // can not be defined. /// Type of affine transformation matrix. associatedtype TransformMatrixType: GenericSquareMatrix /// Vector representation of a `Point`. var vector: VectorType { get set } static func + (lhs: Self, rhs: VectorType) -> Self static func - (lhs: Self, rhs: Self) -> VectorType /// Constructs a point from a vector. init (_ vector: VectorType) /// The _origin_ point. static var origin: Self { get } } extension Point { public static var origin: Self { return self.init(VectorType.zero) } /// Returns the distance from `self` to another point. public func distance(to: Self) -> Component { return self.vector.distance(to: to.vector) } public static func == (lhs: Self, rhs: Self) -> Bool { return lhs.vector == rhs.vector } public static func + (lhs: Self, rhs: Self.VectorType) -> Self { return Self(lhs.vector + rhs) } public static func - (lhs: Self, rhs: Self) -> Self.VectorType { return lhs.vector - rhs.vector } } extension Point where VectorType: Vector2 { public var x: VectorType.Component { get { return vector.x } set { vector.x = newValue } } public var y: VectorType.Component { get { return vector.y } set { vector.y = newValue } } } extension Point where VectorType: Vector3 { public var x: VectorType.Component { get { return vector.x } set { vector.x = newValue } } public var y: VectorType.Component { get { return vector.y } set { vector.y = newValue } } public var z: VectorType.Component { get { return vector.z } set { vector.z = newValue } } } /// Point in 2D Euclidean space. public struct Point2D: Point { public typealias VectorType = vec2 public typealias TransformMatrixType = mat3 public var vector: vec2 public init (_ vector: VectorType) { self.vector = vector } public init (_ x: VectorType.Component, _ y: VectorType.Component) { self.vector = VectorType(x, y) } } // FIXME: Should just extend `Point`. extension Point2D { public typealias NumberType = Float public func isClose(to other: Point2D, tolerance: Float) -> Bool { return self.vector.isClose(to: other.vector, tolerance: tolerance) } public func interpolate(between y: Point2D, t: Float) -> Point2D { return Point2D(self.vector.interpolate(between: y.vector, t: t)) } } extension Point2D: CustomStringConvertible { public var description: String { return "Point(x: \(self.x), y: \(self.y))" } } /// Point in 3D Euclidean space. public struct Point3D: Point { public typealias VectorType = vec3 public typealias TransformMatrixType = mat4 public var vector: vec3 public init (_ vector: vec3) { self.vector = vector } public init (_ x: Float, _ y: Float, _ z: Float) { vector = vec3(x, y, z) } } extension Point3D { public typealias NumberType = Float public func isClose(to other: Point3D, tolerance: Float) -> Bool { return self.vector.isClose(to: other.vector, tolerance: tolerance) } public func interpolate(between y: Point3D, t: Float) -> Point3D { return Point3D(self.vector.interpolate(between: y.vector, t: t)) } } extension Point3D: CustomStringConvertible { public var description: String { return "Point(x: \(self.x), y: \(self.y), z: \(self.z))" } }
mit
caf4f124d0d4cedbced86d7980d48bd7
24.27907
82
0.638454
4.033395
false
false
false
false
gnachman/iTerm2
sources/AsyncFilter.swift
2
8641
// // AsyncFilter.swift // iTerm2SharedARC // // Created by George Nachman on 8/30/21. // import Foundation class FilteringUpdater { var accept: ((Int32, Bool) -> (Void))? = nil private let lineBuffer: LineBuffer private let count: Int32 private var context: FindContext private var stopAt: LineBufferPosition private let width: Int32 private let mode: iTermFindMode private let query: String private var lastY = Int32(-1) private var lastPosition: LineBufferPosition? = nil init(query: String, lineBuffer: LineBuffer, count: Int32, width: Int32, mode: iTermFindMode) { self.lineBuffer = lineBuffer self.count = count self.width = Int32(width) self.mode = mode self.query = query context = FindContext() stopAt = lineBuffer.lastPosition() begin(at: lineBuffer.firstPosition()) } private func begin(at startPosition: LineBufferPosition) { context = FindContext() stopAt = lineBuffer.lastPosition() lineBuffer.prepareToSearch(for: query, startingAt: startPosition, options: [.multipleResults, .oneResultPerRawLine, .optEmptyQueryMatches], mode: mode, with: context) } var progress: Double { return min(1.0, Double(max(0, lastY)) / Double(count)) } func update() -> Bool { if let lastPosition = lastPosition { DLog("Reset search at last position, set lastPosition to nil") begin(at: lastPosition) self.lastPosition = nil } guard context.status == .Searching || context.status == .Matched else { DLog("FilteringUpdater: finished, return false. Set lastPosition to end of buffer") self.lastPosition = lineBuffer.lastPosition() return false } DLog("FilteringUpdater: perform search") var needsToBackUp = false lineBuffer.findSubstring(context, stopAt: stopAt) switch context.status { case .Matched: DLog("FilteringUpdater: Matched") let positions = lineBuffer.convertPositions(context.results as! [ResultRange], withWidth: width) ?? [] for range in positions { let temporary = range === positions.last && context.includesPartialLastLine accept?(range.yStart, temporary) if temporary { needsToBackUp = true } lastY = range.yEnd } context.results.removeAllObjects() case .Searching, .NotFound: DLog("FilteringUpdater: no results") break @unknown default: fatalError() } if needsToBackUp { // We know we searched the last line so prepare to search again from the beginning // of the last line next time. lastPosition = lineBuffer.positionForStartOfLastLine() DLog("Back up to start of last line") return false } DLog("status is \(context.status.rawValue)") switch context.status { case .NotFound: DLog("Set last position to end of buffer") lastPosition = lineBuffer.lastPosition() return false case .Matched, .Searching: return true @unknown default: fatalError() } } } @objc(iTermFilterDestination) protocol FilterDestination { @objc(filterDestinationAppendCharacters:count:externalAttributeIndex:continuation:) func append(_ characters: UnsafePointer<screen_char_t>, count: Int32, externalAttributeIndex: iTermExternalAttributeIndexReading?, continuation: screen_char_t) @objc(filterDestinationRemoveLastLine) func removeLastLine() } @objc(iTermAsyncFilter) class AsyncFilter: NSObject { private var timer: Timer? = nil private let progress: ((Double) -> (Void))? private let cadence: TimeInterval private let query: String private var updater: FilteringUpdater private var started = false private let lineBufferCopy: LineBuffer private let width: Int32 private let destination: FilterDestination private var lastLineIsTemporary: Bool @objc(initWithQuery:lineBuffer:grid:mode:destination:cadence:refining:progress:) init(query: String, lineBuffer: LineBuffer, grid: VT100Grid, mode: iTermFindMode, destination: FilterDestination, cadence: TimeInterval, refining: AsyncFilter?, progress: ((Double) -> (Void))?) { lineBufferCopy = lineBuffer.copy() lineBufferCopy.setMaxLines(-1) grid.appendLines(grid.numberOfLinesUsed(), to: lineBufferCopy) let numberOfLines = lineBufferCopy.numLines(withWidth: grid.size.width) let width = grid.size.width self.width = width self.cadence = cadence self.progress = progress self.query = query self.destination = destination updater = FilteringUpdater(query: query, lineBuffer: lineBufferCopy, count: numberOfLines, width: width, mode: mode) lastLineIsTemporary = refining?.lastLineIsTemporary ?? false super.init() updater.accept = { [weak self] (lineNumber: Int32, temporary: Bool) in self?.addFilterResult(lineNumber, temporary: temporary) } } private func addFilterResult(_ lineNumber: Int32, temporary: Bool) { DLog("AsyncFilter: append line \(lineNumber)") if lastLineIsTemporary { destination.removeLastLine() } lastLineIsTemporary = temporary let chars = lineBufferCopy.rawLine(atWrappedLine: lineNumber, width: width) let metadata = lineBufferCopy.metadataForRawLine(withWrappedLineNumber: lineNumber, width: width) destination.append(chars.line, count: chars.length, externalAttributeIndex: iTermImmutableMetadataGetExternalAttributesIndex(metadata), continuation: chars.continuation) } @objc func start() { precondition(!started) started = true progress?(0) DLog("AsyncFilter\(self): Init") timer = Timer.scheduledTimer(withTimeInterval: cadence, repeats: true, block: { [weak self] timer in self?.update() }) update() } @objc func cancel() { DLog("AsyncFilter\(self): Cancel") timer?.invalidate() timer = nil } @objc(canRefineWithQuery:) func canRefine(query: String) -> Bool { if timer != nil { return false } if !started { return false } return query.contains(self.query) } /// `block` returns whether to keep going. Return true to continue or false to break. /// Returns true if it ran out of time, false if block returned false private func loopForDuration(_ duration: TimeInterval, block: () -> Bool) -> Bool { let startTime = NSDate.it_timeSinceBoot() while NSDate.it_timeSinceBoot() - startTime < duration { if !block() { return false } } return true } private func update() { DLog("AsyncFilter\(self): Timer fired") let needsUpdate = loopForDuration(0.01) { DLog("AsyncFilter: Update") return updater.update() } if !needsUpdate { progress?(1) timer?.invalidate() DLog("don't need an update") timer = nil } else { progress?(updater.progress) } } } extension AsyncFilter: ContentSubscriber { func deliver(_ array: ScreenCharArray, metadata: iTermImmutableMetadata) { lineBufferCopy.appendLine(array.line, length: array.length, partial: array.eol != EOL_HARD, width: width, metadata: metadata, continuation: array.continuation) if timer != nil { return } while updater.update() { } } }
gpl-2.0
36859ce1442ebc11e6658dc3ebd378ff
33.564
114
0.577595
5.18979
false
false
false
false
CatchChat/Yep
Yep/Views/PullToRefresh/PullToRefreshView.swift
1
4982
// // PullToRefreshView.swift // Yep // // Created by NIX on 15/4/14. // Copyright (c) 2015年 Catch Inc. All rights reserved. // import UIKit protocol PullToRefreshViewDelegate: class { func pulllToRefreshViewDidRefresh(pulllToRefreshView: PullToRefreshView) func scrollView() -> UIScrollView } private let sceneHeight: CGFloat = 80 final class PullToRefreshView: UIView { var refreshView: YepRefreshView! var progressPercentage: CGFloat = 0 weak var delegate: PullToRefreshViewDelegate? var refreshItems = [RefreshItem]() var isRefreshing = false { didSet { if !isRefreshing { refreshTimeoutTimer?.invalidate() } } } var refreshTimeoutTimer: NSTimer? var refreshTimeoutAction: (() -> Void)? { didSet { refreshTimeoutTimer?.invalidate() refreshTimeoutTimer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: #selector(PullToRefreshView.refreshTimeout(_:)), userInfo: nil, repeats: false) } } override func didMoveToSuperview() { super.didMoveToSuperview() self.clipsToBounds = true setupRefreshItems() updateColors() } func setupRefreshItems() { refreshView = YepRefreshView(frame: CGRectMake(0, 0, 50, 50)) refreshItems = [ RefreshItem( view: refreshView, centerEnd: CGPoint( x: CGRectGetMidX(UIScreen.mainScreen().bounds), y: 200 - sceneHeight * 0.5 ), parallaxRatio: 0, sceneHeight: sceneHeight ), ] for refreshItem in refreshItems { addSubview(refreshItem.view) } } func updateColors() { refreshView.updateShapePositionWithProgressPercentage(progressPercentage) } func updateRefreshItemPositions() { for refreshItem in refreshItems { refreshItem.updateViewPositionForPercentage(progressPercentage) } } // MARK: Actions func beginRefreshing() { isRefreshing = true UIView.animateWithDuration(0.25, delay: 0, options: .CurveEaseInOut, animations: { [weak self] in self?.delegate?.scrollView().contentInset.top += sceneHeight }, completion: { (_) -> Void in }) } func endRefreshingAndDoFurtherAction(furtherAction: () -> Void) { guard isRefreshing else { return } isRefreshing = false UIView.animateWithDuration(0.25, delay: 0, options: .CurveEaseInOut, animations: { [weak self] in self?.delegate?.scrollView().contentInset.top -= sceneHeight }, completion: { (_) -> Void in furtherAction() self.refreshView.stopFlashing() self.refreshView.updateRamdonShapePositions() }) } func refreshTimeout(timer: NSTimer) { println("PullToRefreshView refreshTimeout") refreshTimeoutAction?() } } extension PullToRefreshView: UIScrollViewDelegate { func scrollViewDidScroll(scrollView: UIScrollView) { if isRefreshing { return } let refreshViewVisibleHeight = max(0, -(scrollView.contentOffset.y + scrollView.contentInset.top)) progressPercentage = min(1, refreshViewVisibleHeight / sceneHeight) updateRefreshItemPositions() updateColors() } func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { if !isRefreshing && progressPercentage == 1 { beginRefreshing() targetContentOffset.memory.y = -scrollView.contentInset.top delegate?.pulllToRefreshViewDidRefresh(self) } } func scrollViewDidEndScrollingAnimation(scrollView: UIScrollView) { if !isRefreshing && progressPercentage == 1 { beginRefreshing() scrollView.contentOffset.y = -scrollView.contentInset.top delegate?.pulllToRefreshViewDidRefresh(self) } } } final class RefreshItem { unowned var view: UIView private var centerStart: CGPoint private var centerEnd: CGPoint init(view: UIView, centerEnd: CGPoint, parallaxRatio: CGFloat, sceneHeight: CGFloat) { self.view = view self.centerEnd = centerEnd centerStart = CGPoint(x: centerEnd.x, y: centerEnd.y + (parallaxRatio * sceneHeight)) self.view.center = centerStart } func updateViewPositionForPercentage(percentage: CGFloat) { view.center = CGPoint( x: centerStart.x + (centerEnd.x - centerStart.x) * percentage, y: centerStart.y + (centerEnd.y - centerStart.y) * percentage ) } func updateViewTintColor(tintColor: UIColor) { view.tintColor = tintColor } }
mit
15f9f4983bcd9fd3b2ec411cb21ad771
25.215789
181
0.627108
5.275424
false
false
false
false
ktmswzw/FeelClient
FeelingClient/common/utils/MapHelper.swift
1
2828
// // MapHelper.swift // FeelingClient // // Created by Vincent on 16/3/25. // Copyright © 2016年 xecoder. All rights reserved. // import Foundation import MapKit let a = 6378245.0 let ee = 0.00669342162296594323 // World Geodetic System ==> Mars Geodetic System func outOfChina(coordinate: CLLocationCoordinate2D) -> Bool { if coordinate.longitude < 72.004 || coordinate.longitude > 137.8347 { return true } if coordinate.latitude < 0.8293 || coordinate.latitude > 55.8271 { return true } return false } func transformLat(x: Double, y: Double) -> Double { var ret = -100.0 + 2.0 * x + 3.0 * y ret += 0.2 * y * y + 0.1 * x * y ret += 0.2 * sqrt(abs(x)) ret += (20.0 * sin(6.0 * x * M_PI) + 20.0 * sin(2.0 * x * M_PI)) * 2.0 / 3.0 ret += (20.0 * sin(y * M_PI) + 40.0 * sin(y / 3.0 * M_PI)) * 2.0 / 3.0 ret += (160.0 * sin(y / 12.0 * M_PI) + 320 * sin(y * M_PI / 30.0)) * 2.0 / 3.0 return ret; } func transformLon(x: Double, y: Double) -> Double { var ret = 300.0 + x + 2.0 * y ret += 0.1 * x * x + 0.1 * x * y ret += 0.1 * sqrt(abs(x)) ret += (20.0 * sin(6.0 * x * M_PI) + 20.0 * sin(2.0 * x * M_PI)) * 2.0 / 3.0 ret += (20.0 * sin(x * M_PI) + 40.0 * sin(x / 3.0 * M_PI)) * 2.0 / 3.0 ret += (150.0 * sin(x / 12.0 * M_PI) + 300.0 * sin(x / 30.0 * M_PI)) * 2.0 / 3.0 return ret; } // 地球坐标系 (WGS-84) -> 火星坐标系 (GCJ-02) func wgs2gcj(coordinate: CLLocationCoordinate2D) -> CLLocationCoordinate2D { if outOfChina(coordinate) == true { return coordinate } let wgLat = coordinate.latitude let wgLon = coordinate.longitude var dLat = transformLat(wgLon - 105.0, y: wgLat - 35.0) var dLon = transformLon(wgLon - 105.0, y: wgLat - 35.0) let radLat = wgLat / 180.0 * M_PI var magic = sin(radLat) magic = 1 - ee * magic * magic let sqrtMagic = sqrt(magic) dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * M_PI) dLon = (dLon * 180.0) / (a / sqrtMagic * cos(radLat) * M_PI) return CLLocationCoordinate2DMake(wgLat + dLat, wgLon + dLon) } // 地球坐标系 (WGS-84) <- 火星坐标系 (GCJ-02) func gcj2wgs(coordinate: CLLocationCoordinate2D) -> CLLocationCoordinate2D { if outOfChina(coordinate) == true { return coordinate } let c2 = wgs2gcj(coordinate) return CLLocationCoordinate2DMake(2 * coordinate.latitude - c2.latitude, 2 * coordinate.longitude - c2.longitude) } // 计算两点距离 func getDistinct(currentLocation:CLLocation,targetLocation:CLLocation) -> Double { let distance:CLLocationDistance = currentLocation.distanceFromLocation(targetLocation) return distance } extension CLLocationCoordinate2D { func toMars() -> CLLocationCoordinate2D { return wgs2gcj(self) } }
mit
1f4bc455f62a9495f066418d6585ad7f
30.873563
117
0.601154
2.876556
false
false
false
false
oskarpearson/rileylink_ios
MinimedKit/PumpModel.swift
1
2177
// // PumpModel.swift // RileyLink // // Created by Pete Schwamb on 3/7/16. // Copyright © 2016 Pete Schwamb. All rights reserved. // /// Represents a pump model and its defining characteristics. /// This class implements the `RawRepresentable` protocol public enum PumpModel: String { case Model508 = "508" case Model511 = "511" case Model711 = "711" case Model512 = "512" case Model712 = "712" case Model515 = "515" case Model715 = "715" case Model522 = "522" case Model722 = "722" case Model523 = "523" case Model723 = "723" case Model530 = "530" case Model730 = "730" case Model540 = "540" case Model740 = "740" case Model551 = "551" case Model751 = "751" case Model554 = "554" case Model754 = "754" private var size: Int { return Int(rawValue)! / 100 } private var generation: Int { return Int(rawValue)! % 100 } /// Identifies pumps that support a major-generation shift in record format, starting with the x23. /// Mirrors the "larger" flag as defined by decoding-carelink public var larger: Bool { return generation >= 23 } // On newer pumps, square wave boluses are added to history on start of delivery, and updated in place // when delivery is finished public var appendsSquareWaveToHistoryOnStartOfDelivery: Bool { return generation >= 23 } public var hasMySentry: Bool { return generation >= 23 } var hasLowSuspend: Bool { return generation >= 51 } /// The number of turns of the stepper motor required to deliver 1 U of U-100 insulin. /// This is a measure of motor precision. public var strokesPerUnit: Int { return (generation >= 23) ? 40 : 10 } public var reservoirCapacity: Int { switch size { case 5: return 176 case 7: return 300 default: fatalError("Unknown reservoir capacity for PumpModel.\(self)") } } } extension PumpModel: CustomStringConvertible { public var description: String { return rawValue } }
mit
bb0f9d0566a58e92af44e93ace95695f
24.904762
106
0.616728
4.291913
false
false
false
false
LetItPlay/iOSClient
blockchainapp/NewFeedTableViewCell.swift
1
8787
import UIKit import SnapKit class NewFeedTableViewCell: UITableViewCell { public static let cellID: String = "NewFeedCellID" public var onPlay: ((Int) -> Void)? public var onLike: ((Int) -> Void)? weak var track: Track? = nil { didSet { if let iconUrl = track?.findChannelImage() { iconImageView.sd_setImage(with: iconUrl) } else { iconImageView.image = nil } if let iconUrl = track?.image.buildImageURL() { mainPictureImageView.sd_setImage(with: iconUrl) } else { mainPictureImageView.image = nil } let maxTime = track?.audiofile?.lengthSeconds ?? 0 trackTitleLabel.attributedText = type(of: self).title(text: track?.name ?? "") // trackTitleLabel.text = track?.name ?? "" channelLabel.text = track?.findStationName() timeAgoLabel.text = track?.publishedAt.formatString() dataLabels[.likes]?.setData(data: Int64(track?.likeCount ?? 0)) dataLabels[.listens]?.setData(data: Int64(track?.listenCount ?? 0)) dataLabels[.time]?.setData(data: maxTime) likeButton.isSelected = LikeManager.shared.hasObject(id: track?.id ?? 0) // playButton.isSelected = audioManager.isPlaying && audioManager.currentItemId == track?.uniqString() } } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) viewInitialize() // self.playButton.addTarget(self, action: #selector(playPressed(_:)), for: .touchUpInside) self.likeButton.addTarget(self, action: #selector(likePressed(_:)), for: .touchUpInside) } @objc func playPressed(_: UIButton){ // if let id = track?.id { onPlay?(0) // } } @objc func likePressed(_: UIButton) { likeButton.isSelected = !likeButton.isSelected // if let id = track?.id { onLike?(0) // } } func set(isPlaying: Bool) { self.dataLabels[.playingIndicator]?.isHidden = !isPlaying self.dataLabels[.listens]?.isHidden = isPlaying } static func title(text: String, calc: Bool = false) -> NSAttributedString { let para = NSMutableParagraphStyle() para.lineBreakMode = .byWordWrapping para.minimumLineHeight = 22 para.maximumLineHeight = 22 return NSAttributedString.init(string: text , attributes: [.font: UIFont.systemFont(ofSize: 16, weight: .semibold), .foregroundColor: AppColor.Title.dark, .paragraphStyle: para]) } static func height(text: String, width: CGFloat) -> CGFloat { let picHeight = ceil((width - 32)*9.0/16.0) let textHeight = title(text: text, calc: true) .boundingRect(with: CGSize.init(width: width - 20 - 32, height: 999), options: .usesLineFragmentOrigin, context: nil) .height return min(66, ceil(textHeight)) + picHeight + 32 + 4 + 32 + 24 + 2 } // MARK: - AudioManager events // @objc func audioManagerStartPlaying(_ notification: Notification) { // playButton.isSelected = audioManager.currentItemId == track?.uniqString() // } // // @objc func audioManagerPaused(_ notification: Notification) { // playButton.isSelected = false // } deinit { NotificationCenter.default.removeObserver(self) } let iconImageView: UIImageView = { let imageView: UIImageView = UIImageView() imageView.layer.masksToBounds = true imageView.layer.cornerRadius = 10 imageView.snp.makeConstraints({ (maker) in maker.width.equalTo(20) maker.height.equalTo(20) }) return imageView }() let channelLabel: UILabel = { let label = UILabel() label.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium) label.textColor = UIColor.init(white: 2/255.0, alpha: 1) label.textAlignment = .left label.lineBreakMode = .byTruncatingTail label.numberOfLines = 1 label.text = "123 123 123" return label }() let timeAgoLabel: UILabel = { let label = UILabel() label.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular) label.textColor = UIColor.init(white: 74/255.0, alpha: 1) label.textAlignment = .right label.text = "9 days ago" return label }() let mainPictureImageView: UIImageView = { let imageView = UIImageView() imageView.image = UIImage.init(named: "channelPrevievImg") imageView.layer.masksToBounds = true imageView.contentMode = .scaleAspectFill return imageView }() let titleLabel: UILabel = { let label = UILabel() label.numberOfLines = 3 label.lineBreakMode = .byWordWrapping label.font = UIFont.systemFont(ofSize: 16, weight: .semibold) label.textColor = AppColor.Title.dark return label }() var dataLabels: [IconLabelType: IconedLabel] = [:] let likeButton: UIButton = { let button = UIButton() button.setImage(UIImage.init(named: "likeActiveFeed") , for: .selected) button.setImage(UIImage.init(named: "likeInactiveFeed"), for: .normal) return button }() let trackTitleLabel: UILabel = { let label = UILabel() label.numberOfLines = 3 return label }() func viewInitialize() { self.selectionStyle = .none let cellContentView = UIView() cellContentView.layer.masksToBounds = true cellContentView.layer.cornerRadius = 9.0 cellContentView.layer.borderWidth = 1.0 cellContentView.layer.borderColor = UIColor.init(white: 151.0/255, alpha: 0.06).cgColor cellContentView.backgroundColor = UIColor.init(white: 240.0/255, alpha: 1) self.contentView.addSubview(cellContentView) cellContentView.snp.makeConstraints { (make) in make.left.equalToSuperview().inset(16) make.right.equalToSuperview().inset(16) make.top.equalToSuperview().inset(24) make.bottom.equalToSuperview() } cellContentView.addSubview(mainPictureImageView) mainPictureImageView.snp.makeConstraints { (make) in make.left.equalToSuperview() make.right.equalToSuperview() make.top.equalToSuperview().inset(32) make.width.equalTo(mainPictureImageView.snp.height).multipliedBy(16.0/9) } cellContentView.addSubview(iconImageView) iconImageView.snp.makeConstraints { (make) in make.left.equalToSuperview().inset(10) make.top.equalToSuperview().inset(6) } cellContentView.addSubview(channelLabel) channelLabel.snp.makeConstraints { (make) in make.left.equalTo(iconImageView.snp.right).inset(-6) make.centerY.equalTo(iconImageView) } cellContentView.addSubview(timeAgoLabel) timeAgoLabel.snp.makeConstraints { (make) in make.right.equalToSuperview().inset(10) make.centerY.equalTo(iconImageView) make.width.equalTo(88) make.left.equalTo(channelLabel.snp.right).inset(-8) } let time = IconedLabel.init(type: .time) cellContentView.addSubview(time) time.snp.makeConstraints { (make) in make.left.equalToSuperview().inset(8) make.bottom.equalToSuperview().inset(8) } let likes = IconedLabel.init(type: .likes) cellContentView.addSubview(likes) likes.snp.makeConstraints { (make) in make.left.equalTo(time.snp.right).inset(-4) make.centerY.equalTo(time) } let listens = IconedLabel.init(type: .listens) cellContentView.addSubview(listens) listens.snp.makeConstraints { (make) in make.left.equalTo(likes.snp.right).inset(-4) make.centerY.equalTo(time) } let playingIndicator = IconedLabel.init(type: .playingIndicator) cellContentView.addSubview(playingIndicator) playingIndicator.snp.makeConstraints { (make) in make.left.equalTo(likes.snp.right).inset(-4) make.centerY.equalTo(time) } playingIndicator.isHidden = true self.dataLabels = [.time: time, .likes: likes, .listens: listens, .playingIndicator: playingIndicator] cellContentView.addSubview(trackTitleLabel) trackTitleLabel.snp.makeConstraints { (make) in make.left.equalToSuperview().inset(10) make.top.equalTo(mainPictureImageView.snp.bottom).inset(-4) make.bottom.equalToSuperview().inset(32) make.right.equalToSuperview().inset(10) } let likeBlurView = UIVisualEffectView(effect: UIBlurEffect.init(style: .extraLight)) likeBlurView.contentView.addSubview(self.likeButton) self.likeButton.snp.makeConstraints { (make) in make.edges.equalToSuperview() } cellContentView.addSubview(likeBlurView) likeBlurView.snp.makeConstraints { (make) in make.bottom.equalTo(mainPictureImageView).inset(10) make.right.equalTo(mainPictureImageView).inset(10) make.width.equalTo(36) make.height.equalTo(36) } likeBlurView.layer.masksToBounds = true likeBlurView.layer.cornerRadius = 18 } required init?(coder aDecoder: NSCoder) { return nil } // override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { // let likePoint = self.convert(point, to: likeButton) //// let playPoint = self.convert(point, to: playButton) // if likeButton.frame.contains(likePoint) { // return likeButton // } //// if playButton.frame.contains(playPoint) { //// return playButton //// } // return super.hitTest(point, with: event) // } }
mit
bbcb65cd6362295b45db12826268f306
30.270463
180
0.720155
3.637003
false
false
false
false
Zewo/HTTPParser
Tests/HTTPParser/RequestParserTests.swift
1
39137
import XCTest @testable import HTTPParser class RequestParserTests: XCTestCase { func testInvalidMethod() { let parser = RequestParser() do { let data = ("INVALID / HTTP/1.1\r\n" + "\r\n") try parser.parse(data) } catch { XCTAssert(true) } } func testShortDELETERequest() { let parser = RequestParser() do { let data = ("DELETE / HTTP/1.1\r\n" + "\r\n") if let request = try parser.parse(data) { XCTAssert(request.method == .delete) XCTAssert(request.uri.path == "/") XCTAssert(request.version.major == 1) XCTAssert(request.version.minor == 1) XCTAssert(request.headers.count == 0) } else { XCTAssert(false) } } catch { XCTAssert(false) } } func testShortGETRequest() { let parser = RequestParser() do { let data = ("GET / HTTP/1.1\r\n" + "\r\n") if let request = try parser.parse(data) { XCTAssert(request.method == .get) XCTAssert(request.uri.path == "/") XCTAssert(request.version.major == 1) XCTAssert(request.version.minor == 1) XCTAssert(request.headers.count == 0) } else { XCTAssert(false) } } catch { XCTAssert(false) } } func testShortHEADRequest() { let parser = RequestParser() do { let data = ("HEAD / HTTP/1.1\r\n" + "\r\n") if let request = try parser.parse(data) { XCTAssert(request.method == .head) XCTAssert(request.uri.path == "/") XCTAssert(request.version.major == 1) XCTAssert(request.version.minor == 1) XCTAssert(request.headers.count == 0) } else { XCTAssert(false) } } catch { XCTAssert(false) } } func testShortPOSTRequest() { let parser = RequestParser() do { let data = ("POST / HTTP/1.1\r\n" + "\r\n") if let request = try parser.parse(data) { XCTAssert(request.method == .post) XCTAssert(request.uri.path == "/") XCTAssert(request.version.major == 1) XCTAssert(request.version.minor == 1) XCTAssert(request.headers.count == 0) } else { XCTAssert(false) } } catch { XCTAssert(false) } } func testShortPUTRequest() { let parser = RequestParser() do { let data = ("PUT / HTTP/1.1\r\n" + "\r\n") if let request = try parser.parse(data) { XCTAssert(request.method == .put) XCTAssert(request.uri.path == "/") XCTAssert(request.version.major == 1) XCTAssert(request.version.minor == 1) XCTAssert(request.headers.count == 0) } else { XCTAssert(false) } } catch { XCTAssert(false) } } func testShortCONNECTRequest() { let parser = RequestParser() do { let data = ("CONNECT / HTTP/1.1\r\n" + "\r\n") if let request = try parser.parse(data) { XCTAssert(request.method == .connect) XCTAssert(request.uri.path == "/") XCTAssert(request.version.major == 1) XCTAssert(request.version.minor == 1) XCTAssert(request.headers.count == 0) } else { XCTAssert(false) } } catch { XCTAssert(false) } } func testShortOPTIONSRequest() { let parser = RequestParser() do { let data = ("OPTIONS / HTTP/1.1\r\n" + "\r\n") if let request = try parser.parse(data) { XCTAssert(request.method == .options) XCTAssert(request.uri.path == "/") XCTAssert(request.version.major == 1) XCTAssert(request.version.minor == 1) XCTAssert(request.headers.count == 0) } else { XCTAssert(false) } } catch { XCTAssert(false) } } func testShortTRACERequest() { let parser = RequestParser() do { let data = ("TRACE / HTTP/1.1\r\n" + "\r\n") if let request = try parser.parse(data) { XCTAssert(request.method == .trace) XCTAssert(request.uri.path == "/") XCTAssert(request.version.major == 1) XCTAssert(request.version.minor == 1) XCTAssert(request.headers.count == 0) } else { XCTAssert(false) } } catch { XCTAssert(false) } } func testShortCOPYRequest() { let parser = RequestParser() do { let data = ("COPY / HTTP/1.1\r\n" + "\r\n") if let request = try parser.parse(data) { XCTAssert(request.method == .other(method: "COPY")) XCTAssert(request.uri.path == "/") XCTAssert(request.version.major == 1) XCTAssert(request.version.minor == 1) XCTAssert(request.headers.count == 0) } else { XCTAssert(false) } } catch { XCTAssert(false) } } func testShortLOCKRequest() { let parser = RequestParser() do { let data = ("LOCK / HTTP/1.1\r\n" + "\r\n") if let request = try parser.parse(data) { XCTAssert(request.method == .other(method: "LOCK")) XCTAssert(request.uri.path == "/") XCTAssert(request.version.major == 1) XCTAssert(request.version.minor == 1) XCTAssert(request.headers.count == 0) } else { XCTAssert(false) } } catch { XCTAssert(false) } } func testShortMKCOLRequest() { let parser = RequestParser() do { let data = ("MKCOL / HTTP/1.1\r\n" + "\r\n") if let request = try parser.parse(data) { XCTAssert(request.method == .other(method: "MKCOL")) XCTAssert(request.uri.path == "/") XCTAssert(request.version.major == 1) XCTAssert(request.version.minor == 1) XCTAssert(request.headers.count == 0) } else { XCTAssert(false) } } catch { XCTAssert(false) } } func testShortMOVERequest() { let parser = RequestParser() do { let data = ("MOVE / HTTP/1.1\r\n" + "\r\n") if let request = try parser.parse(data) { XCTAssert(request.method == .other(method: "MOVE")) XCTAssert(request.uri.path == "/") XCTAssert(request.version.major == 1) XCTAssert(request.version.minor == 1) XCTAssert(request.headers.count == 0) } else { XCTAssert(false) } } catch { XCTAssert(false) } } func testShortPROPFINDRequest() { let parser = RequestParser() do { let data = ("PROPFIND / HTTP/1.1\r\n" + "\r\n") if let request = try parser.parse(data) { XCTAssert(request.method == .other(method: "PROPFIND")) XCTAssert(request.uri.path == "/") XCTAssert(request.version.major == 1) XCTAssert(request.version.minor == 1) XCTAssert(request.headers.count == 0) } else { XCTAssert(false) } } catch { XCTAssert(false) } } func testShortPROPPATCHRequest() { let parser = RequestParser() do { let data = ("PROPPATCH / HTTP/1.1\r\n" + "\r\n") if let request = try parser.parse(data) { XCTAssert(request.method == .other(method: "PROPPATCH")) XCTAssert(request.uri.path == "/") XCTAssert(request.version.major == 1) XCTAssert(request.version.minor == 1) XCTAssert(request.headers.count == 0) } else { XCTAssert(false) } } catch { XCTAssert(false) } } func testShortSEARCHRequest() { let parser = RequestParser() do { let data = ("SEARCH / HTTP/1.1\r\n" + "\r\n") if let request = try parser.parse(data) { XCTAssert(request.method == .other(method: "SEARCH")) XCTAssert(request.uri.path == "/") XCTAssert(request.version.major == 1) XCTAssert(request.version.minor == 1) XCTAssert(request.headers.count == 0) } else { XCTAssert(false) } } catch { XCTAssert(false) } } func testShortUNLOCKRequest() { let parser = RequestParser() do { let data = ("UNLOCK / HTTP/1.1\r\n" + "\r\n") if let request = try parser.parse(data) { XCTAssert(request.method == .other(method: "UNLOCK")) XCTAssert(request.uri.path == "/") XCTAssert(request.version.major == 1) XCTAssert(request.version.minor == 1) XCTAssert(request.headers.count == 0) } else { XCTAssert(false) } } catch { XCTAssert(false) } } func testShortBINDRequest() { let parser = RequestParser() do { let data = ("BIND / HTTP/1.1\r\n" + "\r\n") if let request = try parser.parse(data) { XCTAssert(request.method == .other(method: "BIND")) XCTAssert(request.uri.path == "/") XCTAssert(request.version.major == 1) XCTAssert(request.version.minor == 1) XCTAssert(request.headers.count == 0) } else { XCTAssert(false) } } catch { XCTAssert(false) } } func testShortREBINDRequest() { let parser = RequestParser() do { let data = ("REBIND / HTTP/1.1\r\n" + "\r\n") if let request = try parser.parse(data) { XCTAssert(request.method == .other(method: "REBIND")) XCTAssert(request.uri.path == "/") XCTAssert(request.version.major == 1) XCTAssert(request.version.minor == 1) XCTAssert(request.headers.count == 0) } else { XCTAssert(false) } } catch { XCTAssert(false) } } func testShortUNBINDRequest() { let parser = RequestParser() do { let data = ("UNBIND / HTTP/1.1\r\n" + "\r\n") if let request = try parser.parse(data) { XCTAssert(request.method == .other(method: "UNBIND")) XCTAssert(request.uri.path == "/") XCTAssert(request.version.major == 1) XCTAssert(request.version.minor == 1) XCTAssert(request.headers.count == 0) } else { XCTAssert(false) } } catch { XCTAssert(false) } } func testShortACLRequest() { let parser = RequestParser() do { let data = ("ACL / HTTP/1.1\r\n" + "\r\n") if let request = try parser.parse(data) { XCTAssert(request.method == .other(method: "ACL")) XCTAssert(request.uri.path == "/") XCTAssert(request.version.major == 1) XCTAssert(request.version.minor == 1) XCTAssert(request.headers.count == 0) } else { XCTAssert(false) } } catch { XCTAssert(false) } } func testShortREPORTRequest() { let parser = RequestParser() do { let data = ("REPORT / HTTP/1.1\r\n" + "\r\n") if let request = try parser.parse(data) { XCTAssert(request.method == .other(method: "REPORT")) XCTAssert(request.uri.path == "/") XCTAssert(request.version.major == 1) XCTAssert(request.version.minor == 1) XCTAssert(request.headers.count == 0) } else { XCTAssert(false) } } catch { XCTAssert(false) } } func testShortMKACTIVITYRequest() { let parser = RequestParser() do { let data = ("MKACTIVITY / HTTP/1.1\r\n" + "\r\n") if let request = try parser.parse(data) { XCTAssert(request.method == .other(method: "MKACTIVITY")) XCTAssert(request.uri.path == "/") XCTAssert(request.version.major == 1) XCTAssert(request.version.minor == 1) XCTAssert(request.headers.count == 0) } else { XCTAssert(false) } } catch { XCTAssert(false) } } func testShortCHECKOUTRequest() { let parser = RequestParser() do { let data = ("CHECKOUT / HTTP/1.1\r\n" + "\r\n") if let request = try parser.parse(data) { XCTAssert(request.method == .other(method: "CHECKOUT")) XCTAssert(request.uri.path == "/") XCTAssert(request.version.major == 1) XCTAssert(request.version.minor == 1) XCTAssert(request.headers.count == 0) } else { XCTAssert(false) } } catch { XCTAssert(false) } } func testShortMERGERequest() { let parser = RequestParser() do { let data = ("MERGE / HTTP/1.1\r\n" + "\r\n") if let request = try parser.parse(data) { XCTAssert(request.method == .other(method: "MERGE")) XCTAssert(request.uri.path == "/") XCTAssert(request.version.major == 1) XCTAssert(request.version.minor == 1) XCTAssert(request.headers.count == 0) } else { XCTAssert(false) } } catch { XCTAssert(false) } } func testShortNOTIFYRequest() { let parser = RequestParser() do { let data = ("NOTIFY / HTTP/1.1\r\n" + "\r\n") if let request = try parser.parse(data) { XCTAssert(request.method == .other(method: "NOTIFY")) XCTAssert(request.uri.path == "/") XCTAssert(request.version.major == 1) XCTAssert(request.version.minor == 1) XCTAssert(request.headers.count == 0) } else { XCTAssert(false) } } catch { XCTAssert(false) } } func testShortSUBSCRIBERequest() { let parser = RequestParser() do { let data = ("SUBSCRIBE / HTTP/1.1\r\n" + "\r\n") if let request = try parser.parse(data) { XCTAssert(request.method == .other(method: "SUBSCRIBE")) XCTAssert(request.uri.path == "/") XCTAssert(request.version.major == 1) XCTAssert(request.version.minor == 1) XCTAssert(request.headers.count == 0) } else { XCTAssert(false) } } catch { XCTAssert(false) } } func testShortUNSUBSCRIBERequest() { let parser = RequestParser() do { let data = ("UNSUBSCRIBE / HTTP/1.1\r\n" + "\r\n") if let request = try parser.parse(data) { XCTAssert(request.method == .other(method: "UNSUBSCRIBE")) XCTAssert(request.uri.path == "/") XCTAssert(request.version.major == 1) XCTAssert(request.version.minor == 1) XCTAssert(request.headers.count == 0) } else { XCTAssert(false) } } catch { XCTAssert(false) } } func testShortPATCHRequest() { let parser = RequestParser() do { let data = ("PATCH / HTTP/1.1\r\n" + "\r\n") if let request = try parser.parse(data) { XCTAssert(request.method == .patch) XCTAssert(request.uri.path == "/") XCTAssert(request.version.major == 1) XCTAssert(request.version.minor == 1) XCTAssert(request.headers.count == 0) } else { XCTAssert(false) } } catch { XCTAssert(false) } } func testShortPURGERequest() { let parser = RequestParser() do { let data = ("PURGE / HTTP/1.1\r\n" + "\r\n") if let request = try parser.parse(data) { XCTAssert(request.method == .other(method: "PURGE")) XCTAssert(request.uri.path == "/") XCTAssert(request.version.major == 1) XCTAssert(request.version.minor == 1) XCTAssert(request.headers.count == 0) } else { XCTAssert(false) } } catch { XCTAssert(false) } } func testShortMKCALENDARRequest() { let parser = RequestParser() do { let data = ("MKCALENDAR / HTTP/1.1\r\n" + "\r\n") if let request = try parser.parse(data) { XCTAssert(request.method == .other(method: "MKCALENDAR")) XCTAssert(request.uri.path == "/") XCTAssert(request.version.major == 1) XCTAssert(request.version.minor == 1) XCTAssert(request.headers.count == 0) } else { XCTAssert(false) } } catch { XCTAssert(false) } } func testDiscontinuousShortRequest() { let parser = RequestParser() do { let data1 = "GET / HT" let data2 = "TP/1." let data3 = "1\r\n" let data4 = "\r\n" var request = try parser.parse(data1) XCTAssert(request == nil) request = try parser.parse(data2) XCTAssert(request == nil) request = try parser.parse(data3) XCTAssert(request == nil) if let request = try parser.parse(data4) { XCTAssert(request.method == .get) XCTAssert(request.uri.path == "/") XCTAssert(request.version.major == 1) XCTAssert(request.version.minor == 1) XCTAssert(request.headers.count == 0) } else { XCTAssert(false) } } catch { XCTAssert(false) } } func testMediumRequest() { let parser = RequestParser() do { let data = ("GET / HTTP/1.1\r\n" + "Host: zewo.co\r\n" + "\r\n") if let request = try parser.parse(data) { XCTAssert(request.method == .get) XCTAssert(request.uri.path == "/") XCTAssert(request.version.major == 1) XCTAssert(request.version.minor == 1) XCTAssert(request.headers["Host"] == "zewo.co") } else { XCTAssert(false) } } catch { XCTAssert(false) } } func testDiscontinuousMediumRequest() { let parser = RequestParser() do { let data1 = "GET / HTT" let data2 = "P/1.1\r\n" let data3 = "Hos" let data4 = "t: zewo.c" let data5 = "o\r\n" let data6 = "Conten" let data7 = "t-Type: appl" let data8 = "ication/json\r\n" let data9 = "\r" let data10 = "\n" var request = try parser.parse(data1) XCTAssert(request == nil) request = try parser.parse(data2) XCTAssert(request == nil) request = try parser.parse(data3) XCTAssert(request == nil) request = try parser.parse(data4) XCTAssert(request == nil) request = try parser.parse(data5) XCTAssert(request == nil) request = try parser.parse(data6) XCTAssert(request == nil) request = try parser.parse(data7) XCTAssert(request == nil) request = try parser.parse(data8) XCTAssert(request == nil) request = try parser.parse(data9) XCTAssert(request == nil) if let request = try parser.parse(data10) { XCTAssert(request.method == .get) XCTAssert(request.uri.path == "/") XCTAssert(request.version.major == 1) XCTAssert(request.version.minor == 1) XCTAssert(request.headers["Host"] == "zewo.co") XCTAssert(request.headers["Content-Type"] == "application/json") } else { XCTAssert(false) } } catch { XCTAssert(false) } } func testDiscontinuousMediumRequestMultipleCookie() { let parser = RequestParser() do { let data1 = "GET / HTT" let data2 = "P/1.1\r\n" let data3 = "Hos" let data4 = "t: zewo.c" let data5 = "o\r\n" let data6 = "C" let data7 = "ookie: serv" let data8 = "er=zewo\r\n" let data9 = "C" let data10 = "ookie: lan" let data11 = "g=swift\r\n" let data12 = "\r" let data13 = "\n" var request = try parser.parse(data1) XCTAssert(request == nil) request = try parser.parse(data2) XCTAssert(request == nil) request = try parser.parse(data3) XCTAssert(request == nil) request = try parser.parse(data4) XCTAssert(request == nil) request = try parser.parse(data5) XCTAssert(request == nil) request = try parser.parse(data6) XCTAssert(request == nil) request = try parser.parse(data7) XCTAssert(request == nil) request = try parser.parse(data8) XCTAssert(request == nil) request = try parser.parse(data9) XCTAssert(request == nil) request = try parser.parse(data10) XCTAssert(request == nil) request = try parser.parse(data11) XCTAssert(request == nil) request = try parser.parse(data12) XCTAssert(request == nil) if let request = try parser.parse(data13) { XCTAssert(request.method == .get) XCTAssert(request.uri.path == "/") XCTAssert(request.version.major == 1) XCTAssert(request.version.minor == 1) XCTAssert(request.headers["Host"] == "zewo.co") XCTAssert(request.headers["Cookie"] == "server=zewo, lang=swift") } else { XCTAssert(false) } } catch { XCTAssert(false) } } func testCompleteRequest() { let parser = RequestParser() do { let data = ("POST / HTTP/1.1\r\n" + "Content-Length: 4\r\n" + "\r\n" + "Zewo") if let request = try parser.parse(data) { XCTAssert(request.method == .post) XCTAssert(request.uri.path == "/") XCTAssert(request.version.major == 1) XCTAssert(request.version.minor == 1) XCTAssert(request.headers["Content-Length"] == "4") } else { XCTAssert(false) } } catch { XCTAssert(false) } } func testDiscontinuousCompleteRequest() { let parser = RequestParser() do { let data1 = "PO" let data2 = "ST /pro" let data3 = "file HTT" let data4 = "P/1.1\r\n" let data5 = "Cont" let data6 = "ent-Length: 4" let data7 = "\r\n" let data8 = "\r" let data9 = "\n" let data10 = "Ze" let data11 = "wo" var request = try parser.parse(data1) XCTAssert(request == nil) request = try parser.parse(data2) XCTAssert(request == nil) request = try parser.parse(data3) XCTAssert(request == nil) request = try parser.parse(data4) XCTAssert(request == nil) request = try parser.parse(data5) XCTAssert(request == nil) request = try parser.parse(data6) XCTAssert(request == nil) request = try parser.parse(data7) XCTAssert(request == nil) request = try parser.parse(data8) XCTAssert(request == nil) request = try parser.parse(data9) XCTAssert(request == nil) request = try parser.parse(data10) XCTAssert(request == nil) if let request = try parser.parse(data11) { XCTAssert(request.method == .post) XCTAssert(request.uri.path == "/profile") XCTAssert(request.version.major == 1) XCTAssert(request.version.minor == 1) XCTAssert(request.headers["Content-Length"] == "4") } else { XCTAssert(false) } } catch { XCTAssert(false) } } func testMultipleShortRequestsInTheSameStream() { let parser = RequestParser() do { let data1 = "GET / HT" let data2 = "TP/1." let data3 = "1\r\n" let data4 = "\r\n" var request = try parser.parse(data1) XCTAssert(request == nil) request = try parser.parse(data2) XCTAssert(request == nil) request = try parser.parse(data3) XCTAssert(request == nil) if let request = try parser.parse(data4) { XCTAssert(request.method == .get) XCTAssert(request.uri.path == "/") XCTAssert(request.version.major == 1) XCTAssert(request.version.minor == 1) XCTAssert(request.headers.count == 0) } else { XCTAssert(false) } let data5 = "HEAD /profile HT" let data6 = "TP/1." let data7 = "1\r\n" let data8 = "\r\n" request = try parser.parse(data5) XCTAssert(request == nil) request = try parser.parse(data6) XCTAssert(request == nil) request = try parser.parse(data7) XCTAssert(request == nil) if let request = try parser.parse(data8) { XCTAssert(request.method == .head) XCTAssert(request.uri.path == "/profile") XCTAssert(request.version.major == 1) XCTAssert(request.version.minor == 1) XCTAssert(request.headers.count == 0) } else { XCTAssert(false) } } catch { XCTAssert(false) } } func testManyRequests() { #if os(OSX) let data = ("POST / HTTP/1.1\r\n" + "Content-Length: 4\r\n" + "\r\n" + "Zewo") self.measure { for _ in 0 ..< 10000 { let parser = RequestParser() do { if let request = try parser.parse(data) { XCTAssert(request.method == .post) } else { XCTAssert(false) } } catch { XCTAssert(false) } } } #endif } // // func testUpgradeRequests() { // let parser = HTTPRequestParser { _ in // XCTAssert(true) // } // // do { // let data = ("GET / HTTP/1.1\r\n" + // "Upgrade: WebSocket\r\n" + // "Connection: Upgrade\r\n" + // "\r\n") // try parser.parse(data) // } catch { // XCTAssert(true) // } // } // // func testChunkedEncoding() { // let parser = HTTPRequestParser { request in // XCTAssert(request.method == .GET) // XCTAssert(request.uri.path == "/") // XCTAssert(request.majorVersion == 1) // XCTAssert(request.minorVersion == 1) // XCTAssert(request.headers["Transfer-Encoding"] == "chunked") // XCTAssert(request.body == "Zewo".bytes) // } // // do { // let data = ("GET / HTTP/1.1\r\n" + // "Transfer-Encoding: chunked\r\n" + // "\r\n" + // "4\r\n" + // "Zewo\r\n") // try parser.parse(data) // } catch { // XCTAssert(false) // } // } // // func testIncorrectContentLength() { // let parser = HTTPRequestParser { _ in // XCTAssert(false) // } // // do { // let data = ("POST / HTTP/1.1\r\n" + // "Content-Length: 5\r\n" + // "\r\n" + // "Zewo") // try parser.parse(data) // } catch { // XCTAssert(true) // } // } // // func testIncorrectChunkSize() { // let parser = HTTPRequestParser { _ in // XCTAssert(false) // } // // do { // let data = ("GET / HTTP/1.1\r\n" + // "Transfer-Encoding: chunked\r\n" + // "\r\n" + // "5\r\n" + // "Zewo\r\n") // try parser.parse(data) // } catch { // XCTAssert(true) // } // } // // func testInvalidChunkSize() { // let parser = HTTPRequestParser { _ in // XCTAssert(false) // } // // do { // let data = ("GET / HTTP/1.1\r\n" + // "Transfer-Encoding: chunked\r\n" + // "\r\n" + // "x\r\n" + // "Zewo\r\n") // try parser.parse(data) // } catch { // XCTAssert(true) // } // } // // func testConnectionKeepAlive() { // let parser = HTTPRequestParser { request in // XCTAssert(request.method == .GET) // XCTAssert(request.uri.path == "/") // XCTAssert(request.majorVersion == 1) // XCTAssert(request.minorVersion == 1) // XCTAssert(request.headers["Connection"] == "keep-alive") // } // // do { // let data = ("GET / HTTP/1.1\r\n" + // "Connection: keep-alive\r\n" + // "\r\n") // try parser.parse(data) // } catch { // XCTAssert(false) // } // } // // func testConnectionClose() { // let parser = HTTPRequestParser { request in // XCTAssert(request.method == .GET) // XCTAssert(request.uri.path == "/") // XCTAssert(request.majorVersion == 1) // XCTAssert(request.minorVersion == 1) // XCTAssert(request.headers["Connection"] == "close") // } // // do { // let data = ("GET / HTTP/1.1\r\n" + // "Connection: close\r\n" + // "\r\n") // try parser.parse(data) // } catch { // XCTAssert(false) // } // } // // func testRequestHTTP1_0() { // let parser = HTTPRequestParser { request in // XCTAssert(request.method == .GET) // XCTAssert(request.uri.path == "/") // XCTAssert(request.majorVersion == 1) // XCTAssert(request.minorVersion == 0) // } // // do { // let data = ("GET / HTTP/1.0\r\n" + // "\r\n") // try parser.parse(data) // } catch { // XCTAssert(false) // } // } // // func testURI() { // let URIString = "http://username:[email protected]:777/foo/bar?foo=bar&for=baz#yeah" // let uri = URI(string: URIString) // XCTAssert(uri.scheme == "http") // XCTAssert(uri.userInfo?.username == "username") // XCTAssert(uri.userInfo?.password == "password") // XCTAssert(uri.host == "www.google.com") // XCTAssert(uri.port == 777) // XCTAssert(uri.path == "/foo/bar") // XCTAssert(uri.query["foo"] == "bar") // XCTAssert(uri.query["for"] == "baz") // XCTAssert(uri.fragment == "yeah") // } // // func testURIIPv6() { // let URIString = "http://username:password@[2001:db8:1f70::999:de8:7648:6e8]:100/foo/bar?foo=bar&for=baz#yeah" // let uri = URI(string: URIString) // XCTAssert(uri.scheme == "http") // XCTAssert(uri.userInfo?.username == "username") // XCTAssert(uri.userInfo?.password == "password") // XCTAssert(uri.host == "2001:db8:1f70::999:de8:7648:6e8") // XCTAssert(uri.port == 100) // XCTAssert(uri.path == "/foo/bar") // XCTAssert(uri.query["foo"] == "bar") // XCTAssert(uri.query["for"] == "baz") // XCTAssert(uri.fragment == "yeah") // } // // func testURIIPv6WithZone() { // let URIString = "http://username:password@[2001:db8:a0b:12f0::1%eth0]:100/foo/bar?foo=bar&for=baz#yeah" // let uri = URI(string: URIString) // XCTAssert(uri.scheme == "http") // XCTAssert(uri.userInfo?.username == "username") // XCTAssert(uri.userInfo?.password == "password") // XCTAssert(uri.host == "2001:db8:a0b:12f0::1%eth0") // XCTAssert(uri.port == 100) // XCTAssert(uri.path == "/foo/bar") // XCTAssert(uri.query["foo"] == "bar") // XCTAssert(uri.query["for"] == "baz") // XCTAssert(uri.fragment == "yeah") // } // // func testQueryElementWitoutValue() { // let URIString = "http://username:password@[2001:db8:a0b:12f0::1%eth0]:100/foo/bar?foo=&for#yeah" // let uri = URI(string: URIString) // XCTAssert(uri.scheme == "http") // XCTAssert(uri.userInfo?.username == "username") // XCTAssert(uri.userInfo?.password == "password") // XCTAssert(uri.host == "2001:db8:a0b:12f0::1%eth0") // XCTAssert(uri.port == 100) // XCTAssert(uri.path == "/foo/bar") // XCTAssert(uri.query["foo"] == "") // XCTAssert(uri.query["for"] == "") // XCTAssert(uri.fragment == "yeah") // } } extension RequestParserTests { static var allTests: [(String, (RequestParserTests) -> () throws -> Void)] { return [ ("testInvalidMethod", testInvalidMethod), ("testShortDELETERequest", testShortDELETERequest), ("testShortGETRequest", testShortGETRequest), ("testShortHEADRequest", testShortHEADRequest), ("testShortPOSTRequest", testShortPOSTRequest), ("testShortPUTRequest", testShortPUTRequest), ("testShortCONNECTRequest", testShortCONNECTRequest), ("testShortOPTIONSRequest", testShortOPTIONSRequest), ("testShortTRACERequest", testShortTRACERequest), ("testShortCOPYRequest", testShortCOPYRequest), ("testShortLOCKRequest", testShortLOCKRequest), ("testShortMKCOLRequest", testShortMKCOLRequest), ("testShortMOVERequest", testShortMOVERequest), ("testShortPROPFINDRequest", testShortPROPFINDRequest), ("testShortPROPPATCHRequest", testShortPROPPATCHRequest), ("testShortSEARCHRequest", testShortSEARCHRequest), ("testShortUNLOCKRequest", testShortUNLOCKRequest), ("testShortBINDRequest", testShortBINDRequest), ("testShortREBINDRequest", testShortREBINDRequest), ("testShortUNBINDRequest", testShortUNBINDRequest), ("testShortACLRequest", testShortACLRequest), ("testShortREPORTRequest", testShortREPORTRequest), ("testShortMKACTIVITYRequest", testShortMKACTIVITYRequest), ("testShortCHECKOUTRequest", testShortCHECKOUTRequest), ("testShortMERGERequest", testShortMERGERequest), ("testShortNOTIFYRequest", testShortNOTIFYRequest), ("testShortSUBSCRIBERequest", testShortSUBSCRIBERequest), ("testShortUNSUBSCRIBERequest", testShortUNSUBSCRIBERequest), ("testShortPATCHRequest", testShortPATCHRequest), ("testShortPURGERequest", testShortPURGERequest), ("testShortMKCALENDARRequest", testShortMKCALENDARRequest), ("testDiscontinuousShortRequest", testDiscontinuousShortRequest), ("testMediumRequest", testMediumRequest), ("testDiscontinuousMediumRequest", testDiscontinuousMediumRequest), ("testDiscontinuousMediumRequestMultipleCookie", testDiscontinuousMediumRequestMultipleCookie), ("testCompleteRequest", testCompleteRequest), ("testDiscontinuousCompleteRequest", testDiscontinuousCompleteRequest), ("testMultipleShortRequestsInTheSameStream", testMultipleShortRequestsInTheSameStream), ("testManyRequests", testManyRequests), ] } }
mit
5041199cae39cec411baca4a0104780b
33.695922
119
0.476276
4.440322
false
true
false
false
full-of-fire/YJWeibo
YJWeibo/YJWeibo/Classes/Message/Controllers/YJMessageViewController.swift
1
1348
// // YJMessageViewController.swift // YJWeibo // // Created by pan on 16/8/18. // Copyright © 2016年 yj. All rights reserved. // import UIKit class YJMessageViewController: YJBaseTableViewController { var account:YJUserAccount? = YJUserAccount.loadAccount() override func viewDidLoad() { super.viewDidLoad() if let res = account { if res.loginSuccess { super.loadView() } else{ visitorView.frame = view.bounds view = visitorView } }else{ visitorView.frame = view.bounds view = visitorView } } //MARK:懒加载 lazy var visitorView:YJMessageVisitorView = { let messageVisitorView = YJMessageVisitorView.messageVisitorView() messageVisitorView.hidden = false messageVisitorView.loginClickBlock = { print("登录跳转啊") let loginVC = YJLoginViewController() self.navigationController!.pushViewController(loginVC, animated: true) } return messageVisitorView }() }
mit
d9e0e962ee17039fc3b629d440c22e0d
18.26087
78
0.499624
5.933036
false
false
false
false
zisko/swift
test/SILGen/boxed_existentials.swift
1
10806
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -enable-sil-ownership -emit-silgen %s | %FileCheck %s // RUN: %target-swift-frontend -Xllvm -sil-full-demangle -enable-sil-ownership -emit-silgen %s | %FileCheck %s --check-prefix=GUARANTEED func test_type_lowering(_ x: Error) { } // CHECK-LABEL: sil hidden @$S18boxed_existentials18test_type_loweringyys5Error_pF : $@convention(thin) (@owned Error) -> () { // CHECK: destroy_value %0 : $Error class Document {} enum ClericalError: Error { case MisplacedDocument(Document) var _domain: String { return "" } var _code: Int { return 0 } } func test_concrete_erasure(_ x: ClericalError) -> Error { return x } // CHECK-LABEL: sil hidden @$S18boxed_existentials21test_concrete_erasureys5Error_pAA08ClericalF0OF // CHECK: bb0([[ARG:%.*]] : @owned $ClericalError): // CHECK: [[EXISTENTIAL:%.*]] = alloc_existential_box $Error, $ClericalError // CHECK: [[ADDR:%.*]] = project_existential_box $ClericalError in [[EXISTENTIAL]] : $Error // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: store [[ARG_COPY]] to [init] [[ADDR]] : $*ClericalError // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] // CHECK: return [[EXISTENTIAL]] : $Error protocol HairType {} func test_composition_erasure(_ x: HairType & Error) -> Error { return x } // CHECK-LABEL: sil hidden @$S18boxed_existentials24test_composition_erasureys5Error_psAC_AA8HairTypepF // CHECK: [[VALUE_ADDR:%.*]] = open_existential_addr immutable_access [[OLD_EXISTENTIAL:%.*]] : $*Error & HairType to $*[[VALUE_TYPE:@opened\(.*\) Error & HairType]] // CHECK: [[NEW_EXISTENTIAL:%.*]] = alloc_existential_box $Error, $[[VALUE_TYPE]] // CHECK: [[ADDR:%.*]] = project_existential_box $[[VALUE_TYPE]] in [[NEW_EXISTENTIAL]] : $Error // CHECK: copy_addr [[VALUE_ADDR]] to [initialization] [[ADDR]] // CHECK: destroy_addr [[OLD_EXISTENTIAL]] // CHECK: return [[NEW_EXISTENTIAL]] protocol HairClass: class {} func test_class_composition_erasure(_ x: HairClass & Error) -> Error { return x } // CHECK-LABEL: sil hidden @$S18boxed_existentials30test_class_composition_erasureys5Error_psAC_AA9HairClasspF // CHECK: [[VALUE:%.*]] = open_existential_ref [[OLD_EXISTENTIAL:%.*]] : $Error & HairClass to $[[VALUE_TYPE:@opened\(.*\) Error & HairClass]] // CHECK: [[NEW_EXISTENTIAL:%.*]] = alloc_existential_box $Error, $[[VALUE_TYPE]] // CHECK: [[ADDR:%.*]] = project_existential_box $[[VALUE_TYPE]] in [[NEW_EXISTENTIAL]] : $Error // CHECK: [[COPIED_VALUE:%.*]] = copy_value [[VALUE]] // CHECK: store [[COPIED_VALUE]] to [init] [[ADDR]] // CHECK: return [[NEW_EXISTENTIAL]] func test_property(_ x: Error) -> String { return x._domain } // CHECK-LABEL: sil hidden @$S18boxed_existentials13test_propertyySSs5Error_pF // CHECK: bb0([[ARG:%.*]] : @owned $Error): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[VALUE:%.*]] = open_existential_box [[BORROWED_ARG]] : $Error to $*[[VALUE_TYPE:@opened\(.*\) Error]] // FIXME: Extraneous copy here // CHECK-NEXT: [[COPY:%[0-9]+]] = alloc_stack $[[VALUE_TYPE]] // CHECK-NEXT: copy_addr [[VALUE]] to [initialization] [[COPY]] : $*[[VALUE_TYPE]] // CHECK: [[METHOD:%.*]] = witness_method $[[VALUE_TYPE]], #Error._domain!getter.1 // -- self parameter of witness is @in_guaranteed; no need to copy since // value in box is immutable and box is guaranteed // CHECK: [[RESULT:%.*]] = apply [[METHOD]]<[[VALUE_TYPE]]>([[COPY]]) // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] // CHECK: return [[RESULT]] func test_property_of_lvalue(_ x: Error) -> String { var x = x return x._domain } // CHECK-LABEL: sil hidden @$S18boxed_existentials23test_property_of_lvalueySSs5Error_pF : // CHECK: bb0([[ARG:%.*]] : @owned $Error): // CHECK: [[VAR:%.*]] = alloc_box ${ var Error } // CHECK: [[PVAR:%.*]] = project_box [[VAR]] // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] : $Error // CHECK: store [[ARG_COPY]] to [init] [[PVAR]] // CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[PVAR]] : $*Error // CHECK: [[VALUE_BOX:%.*]] = load [copy] [[ACCESS]] // CHECK: [[VALUE:%.*]] = open_existential_box [[VALUE_BOX]] : $Error to $*[[VALUE_TYPE:@opened\(.*\) Error]] // CHECK: [[COPY:%.*]] = alloc_stack $[[VALUE_TYPE]] // CHECK: copy_addr [[VALUE]] to [initialization] [[COPY]] // CHECK: [[METHOD:%.*]] = witness_method $[[VALUE_TYPE]], #Error._domain!getter.1 // CHECK: [[RESULT:%.*]] = apply [[METHOD]]<[[VALUE_TYPE]]>([[COPY]]) // CHECK: destroy_addr [[COPY]] // CHECK: dealloc_stack [[COPY]] // CHECK: destroy_value [[VALUE_BOX]] // CHECK: destroy_value [[VAR]] // CHECK: destroy_value [[ARG]] // CHECK: return [[RESULT]] // CHECK: } // end sil function '$S18boxed_existentials23test_property_of_lvalueySSs5Error_pF' extension Error { func extensionMethod() { } } // CHECK-LABEL: sil hidden @$S18boxed_existentials21test_extension_methodyys5Error_pF func test_extension_method(_ error: Error) { // CHECK: bb0([[ARG:%.*]] : @owned $Error): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[VALUE:%.*]] = open_existential_box [[BORROWED_ARG]] // CHECK: [[METHOD:%.*]] = function_ref // CHECK-NOT: copy_addr // CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]]) // CHECK-NOT: destroy_addr [[COPY]] // CHECK-NOT: destroy_addr [[VALUE]] // CHECK-NOT: destroy_addr [[VALUE]] // -- destroy_value the owned argument // CHECK: destroy_value %0 error.extensionMethod() } func plusOneError() -> Error { } // CHECK-LABEL: sil hidden @$S18boxed_existentials31test_open_existential_semanticsyys5Error_p_sAC_ptF // GUARANTEED-LABEL: sil hidden @$S18boxed_existentials31test_open_existential_semanticsyys5Error_p_sAC_ptF // CHECK: bb0([[ARG0:%.*]]: @owned $Error, // GUARANTEED: bb0([[ARG0:%.*]]: @owned $Error, func test_open_existential_semantics(_ guaranteed: Error, _ immediate: Error) { var immediate = immediate // CHECK: [[IMMEDIATE_BOX:%.*]] = alloc_box ${ var Error } // CHECK: [[PB:%.*]] = project_box [[IMMEDIATE_BOX]] // GUARANTEED: [[IMMEDIATE_BOX:%.*]] = alloc_box ${ var Error } // GUARANTEED: [[PB:%.*]] = project_box [[IMMEDIATE_BOX]] // CHECK-NOT: copy_value [[ARG0]] // CHECK: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]] // CHECK: [[VALUE:%.*]] = open_existential_box [[BORROWED_ARG0]] // CHECK: [[METHOD:%.*]] = function_ref // CHECK-NOT: copy_addr // CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]]) // CHECK: end_borrow [[BORROWED_ARG0]] from [[ARG0]] // CHECK-NOT: destroy_value [[ARG0]] // GUARANTEED-NOT: copy_value [[ARG0]] // GUARANTEED: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]] // GUARANTEED: [[VALUE:%.*]] = open_existential_box [[BORROWED_ARG0]] // GUARANTEED: [[METHOD:%.*]] = function_ref // GUARANTEED: apply [[METHOD]]<{{.*}}>([[VALUE]]) // GUARANTEED: end_borrow [[BORROWED_ARG0]] from [[ARG0]] // GUARANTEED-NOT: destroy_addr [[VALUE]] // GUARANTEED-NOT: destroy_value [[ARG0]] guaranteed.extensionMethod() // CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[PB]] : $*Error // CHECK: [[IMMEDIATE:%.*]] = load [copy] [[ACCESS]] // -- need a copy_value to guarantee // CHECK: [[VALUE:%.*]] = open_existential_box [[IMMEDIATE]] // CHECK: [[METHOD:%.*]] = function_ref // CHECK-NOT: copy_addr // CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]]) // -- end the guarantee // -- TODO: could in theory do this sooner, after the value's been copied // out. // CHECK: destroy_value [[IMMEDIATE]] // GUARANTEED: [[ACCESS:%.*]] = begin_access [read] [unknown] [[PB]] : $*Error // GUARANTEED: [[IMMEDIATE:%.*]] = load [copy] [[ACCESS]] // -- need a copy_value to guarantee // GUARANTEED: [[VALUE:%.*]] = open_existential_box [[IMMEDIATE]] // GUARANTEED: [[METHOD:%.*]] = function_ref // GUARANTEED: apply [[METHOD]]<{{.*}}>([[VALUE]]) // GUARANTEED-NOT: destroy_addr [[VALUE]] // -- end the guarantee // GUARANTEED: destroy_value [[IMMEDIATE]] immediate.extensionMethod() // CHECK: [[F:%.*]] = function_ref {{.*}}plusOneError // CHECK: [[PLUS_ONE:%.*]] = apply [[F]]() // CHECK: [[VALUE:%.*]] = open_existential_box [[PLUS_ONE]] // CHECK: [[METHOD:%.*]] = function_ref // CHECK-NOT: copy_addr // CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]]) // CHECK: destroy_value [[PLUS_ONE]] // GUARANTEED: [[F:%.*]] = function_ref {{.*}}plusOneError // GUARANTEED: [[PLUS_ONE:%.*]] = apply [[F]]() // GUARANTEED: [[VALUE:%.*]] = open_existential_box [[PLUS_ONE]] // GUARANTEED: [[METHOD:%.*]] = function_ref // GUARANTEED: apply [[METHOD]]<{{.*}}>([[VALUE]]) // GUARANTEED-NOT: destroy_addr [[VALUE]] // GUARANTEED: destroy_value [[PLUS_ONE]] plusOneError().extensionMethod() } // CHECK-LABEL: sil hidden @$S18boxed_existentials14erasure_to_anyyyps5Error_p_sAC_ptF // CHECK: bb0([[OUT:%.*]] : @trivial $*Any, [[GUAR:%.*]] : @owned $Error, func erasure_to_any(_ guaranteed: Error, _ immediate: Error) -> Any { var immediate = immediate // CHECK: [[IMMEDIATE_BOX:%.*]] = alloc_box ${ var Error } // CHECK: [[PB:%.*]] = project_box [[IMMEDIATE_BOX]] if true { // CHECK-NOT: copy_value [[GUAR]] // CHECK: [[FROM_VALUE:%.*]] = open_existential_box [[GUAR:%.*]] // CHECK: [[TO_VALUE:%.*]] = init_existential_addr [[OUT]] // CHECK: copy_addr [[FROM_VALUE]] to [initialization] [[TO_VALUE]] // CHECK-NOT: destroy_value [[GUAR]] return guaranteed } else if true { // CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[PB]] // CHECK: [[IMMEDIATE:%.*]] = load [copy] [[ACCESS]] // CHECK: [[FROM_VALUE:%.*]] = open_existential_box [[IMMEDIATE]] // CHECK: [[TO_VALUE:%.*]] = init_existential_addr [[OUT]] // CHECK: copy_addr [[FROM_VALUE]] to [initialization] [[TO_VALUE]] // CHECK: destroy_value [[IMMEDIATE]] return immediate } else if true { // CHECK: function_ref boxed_existentials.plusOneError // CHECK: [[PLUS_ONE:%.*]] = apply // CHECK: [[FROM_VALUE:%.*]] = open_existential_box [[PLUS_ONE]] // CHECK: [[TO_VALUE:%.*]] = init_existential_addr [[OUT]] // CHECK: copy_addr [[FROM_VALUE]] to [initialization] [[TO_VALUE]] // CHECK: destroy_value [[PLUS_ONE]] return plusOneError() } }
apache-2.0
9f3f8fb07d0da1637c13e054c30f6cf7
46.814159
173
0.592541
3.651909
false
true
false
false
borglab/SwiftFusion
Sources/SwiftFusion/Inference/AppearanceTrackingFactor.swift
1
9552
import _Differentiation import PenguinParallel import PenguinStructures import TensorFlow /// A factor over a target's pose and appearance in an image. public struct AppearanceTrackingFactor<LatentCode: FixedSizeVector>: LinearizableFactor2 { /// The first adjacent variable, the pose of the target in the image. /// /// This explicitly specifies `LinearizableFactor2`'s `associatedtype V0`. public typealias V0 = Pose2 /// The second adjacent variable, the latent code for the appearance of the target. /// /// This explicitly specifies `LinearizableFactor2`'s `associatedtype V1`. public typealias V1 = LatentCode /// A region cropped from the image. public typealias Patch = TensorVector /// The IDs of the variables adjacent to this factor. public let edges: Variables.Indices /// The image containing the target. public let measurement: ArrayImage /// Weighting of the error public var weight: Double /// A generative model that produces an appearance from a latent code. /// /// - Parameters: /// - latentCode: the input to the generative model, which is a tensor with shape /// `[LatentCode.dimension]`. /// - Returns: /// - appearance: the output of the generative model, which is a tensor with shape /// `Patch.shape`. public typealias GenerativeModel = (_ latentCode: Tensor<Double>) -> Tensor<Double> /// The generative model that produces an appearance from a latent code. public var appearanceModel: GenerativeModel /// The Jacobian of a `GenerativeModel`. /// /// - Parameters: /// - latentCode: the input to the generative model, which is a tensor with shape /// `[LatentCode.dimension]`. /// - Returns: /// - jacobian: the Jacobian of the generative model at the given `latentCode`, which is a /// tensor with shape `Patch.shape + [LatentCode.dimension]`. public typealias GenerativeModelJacobian = (_ latentCode: Tensor<Double>) -> Tensor<Double> /// The Jacobian of `appearanceModel`. public var appearanceModelJacobian: GenerativeModelJacobian /// The size, in `(height, width)` pixels of the target in `measurement`. public var targetSize: (Int, Int) /// Creates an instance. /// /// - Parameters: /// - poseId: the id of the adjacent pose variable. /// - latentId: the id of the adjacent latent code variable. /// - measurement: the image containing the target. /// - appearanceModel: the generative model that produces an appearance from a latent code. /// - targetSize: the size, in `(height, width)` pixels of the target in `measurement`. If this /// is not specified, then the target size is assumed to be the same size a the /// patches generated by `appearanceModel`. public init( _ poseId: TypedID<Pose2>, _ latentId: TypedID<LatentCode>, measurement: Tensor<Float>, appearanceModel: @escaping GenerativeModel, appearanceModelJacobian: @escaping GenerativeModelJacobian, weight: Double = 1.0, targetSize: (Int, Int)? = nil ) { self.edges = Tuple2(poseId, latentId) self.measurement = ArrayImage(measurement) self.appearanceModel = appearanceModel self.appearanceModelJacobian = appearanceModelJacobian self.weight = weight if let targetSize = targetSize { self.targetSize = targetSize } else { let appearance = appearanceModel(LatentCode.zero.flatTensor) self.targetSize = (appearance.shape[0], appearance.shape[1]) } } /// Returns the difference between the PPCA generated `Patch` and the `Patch` cropped from /// `measurement`. @differentiable public func errorVector(_ pose: Pose2, _ latent: LatentCode) -> Patch.TangentVector { let appearance = appearanceModel(latent.flatTensor) let region = OrientedBoundingBox( center: pose, rows: targetSize.0, cols: targetSize.1) let patch = measurement.patch(at: region, outputSize: (appearance.shape[0], appearance.shape[1])) return Patch(weight * (appearance - Tensor<Double>(patch.tensor))) } @derivative(of: errorVector) @usableFromInline func vjpErrorVector(_ pose: Pose2, _ latent: LatentCode) -> (value: Patch.TangentVector, pullback: (Patch.TangentVector) -> (Pose2.TangentVector, LatentCode)) { let lin = self.linearized(at: Tuple2(pose, latent)) return ( lin.error, { v in let r = lin.errorVector_linearComponent_adjoint(v) return (r.head, r.tail.head) } ) } /// Returns a linear approximation to `self` at `x`. public func linearized(at x: Variables) -> LinearizedAppearanceTrackingFactor<LatentCode> { let pose = x.head let latent = x.tail.head let generatedAppearance = appearanceModel(latent.flatTensor) let generatedAppearance_H_latent = appearanceModelJacobian(latent.flatTensor) let region = OrientedBoundingBox( center: pose, rows: targetSize.0, cols: targetSize.1) let (actualAppearance, actualAppearance_H_pose) = measurement.patchWithJacobian( at: region, outputSize: (generatedAppearance.shape[0], generatedAppearance.shape[1])) assert(generatedAppearance_H_latent.shape == generatedAppearance.shape + [LatentCode.dimension]) let actualAppearance_H_pose_tensor = Tensor<Double>(Tensor(stacking: [ actualAppearance_H_pose.dtheta.tensor, actualAppearance_H_pose.du.tensor, actualAppearance_H_pose.dv.tensor, ], alongAxis: -1)) return LinearizedAppearanceTrackingFactor<LatentCode>( error: Patch(weight * (Tensor<Double>(actualAppearance.tensor) - generatedAppearance)), errorVector_H_pose: -weight * actualAppearance_H_pose_tensor, errorVector_H_latent: weight * generatedAppearance_H_latent, edges: Variables.linearized(edges)) } /// Returns the linearizations of `factors` at `x`. /// /// Note: This causes factor graph linearization to use our custom linearization, /// `LinearizedPPCATrackingFactor` instead of the default AD-generated linearization. public static func linearized<C: Collection>(_ factors: C, at x: VariableAssignments) -> AnyGaussianFactorArrayBuffer where C.Element == Self { Variables.withBufferBaseAddresses(x) { varsBufs in .init(ArrayBuffer<LinearizedAppearanceTrackingFactor<LatentCode>>( count: factors.count, minimumCapacity: factors.count) { b in ComputeThreadPools.local.parallelFor(n: factors.count) { (i, _) in let f = factors[factors.index(factors.startIndex, offsetBy: i)] (b + i).initialize(to: f.linearized(at: Variables(at: f.edges, in: varsBufs))) } }) } } } /// A linear approximation to `AppearanceTrackingFactor`, at a certain linearization point. public struct LinearizedAppearanceTrackingFactor<LatentCode: FixedSizeVector>: GaussianFactor { /// The tangent vectors of the `AppearanceTrackingFactor`'s "pose" and "latent" variables. public typealias Variables = Tuple2<Pose2.TangentVector, LatentCode> /// A region cropped from the image. public typealias Patch = TensorVector /// The error vector at the linearization point. public let error: Patch /// The Jacobian with respect to the `AppearanceTrackingFactor`'s "pose" variable. public let errorVector_H_pose: Tensor<Double> /// The Jacobian with respect to the `AppearanceTrackingFactor`'s "latent" variable. public let errorVector_H_latent: Tensor<Double> /// The IDs of the variables adjacent to this factor. public let edges: Variables.Indices /// Creates an instance with the given arguments. public init( error: Patch, errorVector_H_pose: Tensor<Double>, errorVector_H_latent: Tensor<Double>, edges: Variables.Indices ) { precondition( errorVector_H_pose.shape == error.shape + [Pose2.TangentVector.dimension], "\(errorVector_H_pose.shape) \(error.shape) \(Pose2.TangentVector.dimension)") precondition( errorVector_H_latent.shape == error.shape + [LatentCode.dimension], "\(errorVector_H_latent.shape) \(error.shape) \(LatentCode.dimension)") self.error = error self.errorVector_H_pose = errorVector_H_pose self.errorVector_H_latent = errorVector_H_latent self.edges = edges } public func error(at x: Variables) -> Double { return 0.5 * errorVector(at: x).squaredNorm } @differentiable public func errorVector(at x: Variables) -> Patch { errorVector_linearComponent(x) - error } public func errorVector_linearComponent(_ x: Variables) -> Patch { startTimer("linearized appearance") defer { stopTimer("linearized appearance") } incrementCounter("linearized appearance") let pose = x.head let latent = x.tail.head return Patch( matmul(errorVector_H_pose, pose.flatTensor.expandingShape(at: 1)).squeezingShape(at: 3) + matmul(errorVector_H_latent, latent.flatTensor.expandingShape(at: 1)).squeezingShape(at: 3)) } public func errorVector_linearComponent_adjoint(_ y: Patch) -> Variables { startTimer("linearized appearance transpose") defer { stopTimer("linearized appearance transpose") } incrementCounter("linearized appearance transpose") let t = y.tensor.reshaped(to: [error.dimension, 1]) let pose = matmul( errorVector_H_pose.reshaped(to: [error.dimension, 3]), transposed: true, t) let latent = matmul( errorVector_H_latent.reshaped(to: [error.dimension, LatentCode.dimension]), transposed: true, t) return Tuple2(Vector3(flatTensor: pose), LatentCode(flatTensor: latent)) } }
apache-2.0
a55071747ce62920f366ef73013e8cb0
39.820513
162
0.706763
4.407937
false
false
false
false
coinbase/coinbase-ios-sdk
Tests/Integration/TransactionPartySpec.swift
1
7070
// // TransactionPartySpec.swift // CoinbaseTests // // Copyright © 2018 Coinbase, Inc. All rights reserved. // @testable import CoinbaseSDK import Quick import Nimble class TransactionPartySpec: QuickSpec, IntegrationSpecProtocol { override func spec() { super.spec() let accountID = StubConstants.accountID let transactionID = StubConstants.transactionID let user = User(id: "user_id", resourcePath: "user/user_id") let cryptoAddress = CryptoAddress(resource: "bitcoin_address", addressInfo: AddressInfo(address: "address")) let email = EmailModel(email: "[email protected]") let account = Account(id: StubConstants.accountID, resourcePath: "account_path") describe("TransactionParty") { let transactionResource = specVar { Coinbase(accessToken: StubConstants.accessToken).transactionResource } describe("transactionToUser") { itBehavesLikeResource(with: "transaction_to_user.json", requestedBy: { completion in transactionResource().transaction(accountID: accountID, transactionID: transactionID, completion: completion) }, expectationsForRequest: { _ in }, expectationsForResult: successfulResult(ofType: Transaction.self) && to(party: .user(user))) } describe("transactionFromUser") { itBehavesLikeResource(with: "transaction_from_user.json", requestedBy: { completion in transactionResource().transaction(accountID: accountID, transactionID: transactionID, completion: completion) }, expectationsForRequest: { _ in }, expectationsForResult: successfulResult(ofType: Transaction.self) && from(party: .user(user))) } describe("transactionToBTCAddress") { itBehavesLikeResource(with: "transaction_to_btc_address.json", requestedBy: { completion in transactionResource().transaction(accountID: accountID, transactionID: transactionID, completion: completion) }, expectationsForRequest: { _ in }, expectationsForResult: successfulResult(ofType: Transaction.self) && to(party: .cryptoAddress(cryptoAddress))) } describe("transactionFromBTCAddress") { itBehavesLikeResource(with: "transaction_from_btc_address.json", requestedBy: { completion in transactionResource().transaction(accountID: accountID, transactionID: transactionID, completion: completion) }, expectationsForRequest: { _ in }, expectationsForResult: successfulResult(ofType: Transaction.self) && from(party: .cryptoAddress(cryptoAddress))) } describe("transactionToEmail") { itBehavesLikeResource(with: "transaction_to_email.json", requestedBy: { completion in transactionResource().transaction(accountID: accountID, transactionID: transactionID, completion: completion) }, expectationsForRequest: { _ in }, expectationsForResult: successfulResult(ofType: Transaction.self) && to(party: .email(email))) } describe("transactionFromEmail") { itBehavesLikeResource(with: "transaction_from_email.json", requestedBy: { completion in transactionResource().transaction(accountID: accountID, transactionID: transactionID, completion: completion) }, expectationsForRequest: { _ in }, expectationsForResult: successfulResult(ofType: Transaction.self) && from(party: .email(email))) } describe("transactionToAccount") { itBehavesLikeResource(with: "transaction_to_account.json", requestedBy: { completion in transactionResource().transaction(accountID: accountID, transactionID: transactionID, completion: completion) }, expectationsForRequest: { _ in }, expectationsForResult: successfulResult(ofType: Transaction.self) && to(party: .account(account))) } describe("transactionFromAccount") { itBehavesLikeResource(with: "transaction_from_account.json", requestedBy: { completion in transactionResource().transaction(accountID: accountID, transactionID: transactionID, completion: completion) }, expectationsForRequest: { _ in }, expectationsForResult: successfulResult(ofType: Transaction.self) && from(party: .account(account))) } describe("transactionToUnsupportedParty") { itBehavesLikeResource(with: "transaction_to_unsupported_party.json", requestedBy: { completion in transactionResource().transaction(accountID: accountID, transactionID: transactionID, completion: completion) }, expectationsForRequest: { _ in }, expectationsForResult: invalid(result:)) } describe("transactionFromUnsupportedParty") { itBehavesLikeResource(with: "transaction_from_unsupported_party.json", requestedBy: { completion in transactionResource().transaction(accountID: accountID, transactionID: transactionID, completion: completion) }, expectationsForRequest: { _ in }, expectationsForResult: invalid(result:)) } } } func invalid(result: Result<Transaction>) { expect(result).notTo(beSuccessful()) } func to(party: TransactionParty) -> ResultExpectation<Transaction> { return { result in self.check(lhParty: party, rhParty: result.value!.to!) } } func from(party: TransactionParty) -> ResultExpectation<Transaction> { return { result in self.check(lhParty: party, rhParty: result.value!.from!) } } func check(lhParty: TransactionParty, rhParty: TransactionParty) { expect({ switch (lhParty, rhParty) { case (.account, .account), (.user, .user), (.email, .email), (.cryptoAddress, .cryptoAddress): return .succeeded default: return .failed(reason: "Unexpected TransactionParty") } }).to(succeed()) } }
apache-2.0
94972916f0adb6853dea629d19971c72
58.403361
179
0.576178
6.272405
false
false
false
false
zmeyc/GRDB.swift
Tests/GRDBTests/DatabasePoolConcurrencyTests.swift
1
34855
import XCTest #if USING_SQLCIPHER import GRDBCipher #elseif USING_CUSTOMSQLITE import GRDBCustomSQLite #else import GRDB #endif class DatabasePoolConcurrencyTests: GRDBTestCase { func testDatabasePoolFundamental1() throws { // Constraint: the sum of values, the balance, must remain zero. // // This test shows (if needed) that writes that are not wrapped in a // transaction can not provide our guarantee, and that deferred // transaction provide the immutable view of the database needed by // dbPool.read(). // // Reader Writer // BEGIN DEFERRED TRANSACTION let s1 = DispatchSemaphore(value: 0) // INSERT INTO moves VALUES (1) let s2 = DispatchSemaphore(value: 0) // SELECT SUM(value) AS balance FROM moves let s3 = DispatchSemaphore(value: 0) // INSERT INTO moves VALUES (-1) let s4 = DispatchSemaphore(value: 0) // SELECT SUM(value) AS balance FROM moves // END do { let dbQueue = try makeDatabaseQueue(filename: "test.sqlite") try dbQueue.inDatabase { db in let journalMode = try String.fetchOne(db, "PRAGMA journal_mode = wal") XCTAssertEqual(journalMode, "wal") try db.create(table: "moves") { $0.column("value", .integer) } try db.execute("INSERT INTO moves VALUES (0)") } } let s0 = DispatchSemaphore(value: 0) let block1 = { () in let dbQueue = try! self.makeDatabaseQueue(filename: "test.sqlite") s0.signal() // Avoid "database is locked" error: don't open the two databases at the same time try! dbQueue.inDatabase { db in try db.execute("BEGIN DEFERRED TRANSACTION") s1.signal() _ = s2.wait(timeout: .distantFuture) XCTAssertEqual(try Int.fetchOne(db, "SELECT SUM(value) AS balance FROM moves"), 1) // Non-zero balance s3.signal() _ = s4.wait(timeout: .distantFuture) XCTAssertEqual(try Int.fetchOne(db, "SELECT SUM(value) AS balance FROM moves"), 1) // Non-zero balance try db.execute("END") } } let block2 = { () in _ = s0.wait(timeout: .distantFuture) // Avoid "database is locked" error: don't open the two databases at the same time let dbQueue = try! self.makeDatabaseQueue(filename: "test.sqlite") try! dbQueue.inDatabase { db in _ = s1.wait(timeout: .distantFuture) try db.execute("INSERT INTO moves VALUES (1)") s2.signal() _ = s3.wait(timeout: .distantFuture) try db.execute("INSERT INTO moves VALUES (-1)") s4.signal() } } let blocks = [block1, block2] DispatchQueue.concurrentPerform(iterations: blocks.count) { index in blocks[index]() } } func testDatabasePoolFundamental2() throws { // Constraint: the sum of values, the balance, must remain zero. // // This test shows that deferred transactions play well with concurrent // immediate transactions. // // Reader Writer // BEGIN IMMEDIATE TRANSACTION let s1 = DispatchSemaphore(value: 0) // BEGIN DEFERRED TRANSACTION let s2 = DispatchSemaphore(value: 0) // INSERT INTO moves VALUES (1) let s3 = DispatchSemaphore(value: 0) // SELECT SUM(value) AS balance FROM moves let s4 = DispatchSemaphore(value: 0) // INSERT INTO moves VALUES (-1) let s5 = DispatchSemaphore(value: 0) // SELECT SUM(value) AS balance FROM moves // END END do { let dbQueue = try makeDatabaseQueue(filename: "test.sqlite") try dbQueue.inDatabase { db in let journalMode = try String.fetchOne(db, "PRAGMA journal_mode = wal") XCTAssertEqual(journalMode, "wal") try db.create(table: "moves") { $0.column("value", .integer) } try db.execute("INSERT INTO moves VALUES (0)") } } let s0 = DispatchSemaphore(value: 0) let block1 = { () in let dbQueue = try! self.makeDatabaseQueue(filename: "test.sqlite") s0.signal() // Avoid "database is locked" error: don't open the two databases at the same time try! dbQueue.inDatabase { db in _ = s1.wait(timeout: .distantFuture) try db.execute("BEGIN DEFERRED TRANSACTION") s2.signal() _ = s3.wait(timeout: .distantFuture) XCTAssertEqual(try Int.fetchOne(db, "SELECT SUM(value) AS balance FROM moves"), 0) // Zero balance s4.signal() _ = s5.wait(timeout: .distantFuture) XCTAssertEqual(try Int.fetchOne(db, "SELECT SUM(value) AS balance FROM moves"), 0) // Zero balance try db.execute("END") } } let block2 = { () in _ = s0.wait(timeout: .distantFuture) // Avoid "database is locked" error: don't open the two databases at the same time let dbQueue = try! self.makeDatabaseQueue(filename: "test.sqlite") try! dbQueue.inDatabase { db in try db.execute("BEGIN DEFERRED TRANSACTION") s1.signal() _ = s2.wait(timeout: .distantFuture) try db.execute("INSERT INTO moves VALUES (1)") s3.signal() _ = s4.wait(timeout: .distantFuture) try db.execute("INSERT INTO moves VALUES (-1)") s5.signal() try db.execute("END") } } let blocks = [block1, block2] DispatchQueue.concurrentPerform(iterations: blocks.count) { index in blocks[index]() } } func testDatabasePoolFundamental3() throws { // Constraint: the sum of values, the balance, must remain zero. // // This test shows that deferred transactions play well with concurrent // immediate transactions. // // Reader Writer // BEGIN DEFERRED TRANSACTION let s1 = DispatchSemaphore(value: 0) // BEGIN IMMEDIATE TRANSACTION // INSERT INTO moves VALUES (1) let s2 = DispatchSemaphore(value: 0) // SELECT SUM(value) AS balance FROM moves let s3 = DispatchSemaphore(value: 0) // INSERT INTO moves VALUES (-1) let s4 = DispatchSemaphore(value: 0) // SELECT SUM(value) AS balance FROM moves END // END do { let dbQueue = try makeDatabaseQueue(filename: "test.sqlite") try dbQueue.inDatabase { db in let journalMode = try String.fetchOne(db, "PRAGMA journal_mode = wal") XCTAssertEqual(journalMode, "wal") try db.create(table: "moves") { $0.column("value", .integer) } try db.execute("INSERT INTO moves VALUES (0)") } } let s0 = DispatchSemaphore(value: 0) let block1 = { () in let dbQueue = try! self.makeDatabaseQueue(filename: "test.sqlite") s0.signal() // Avoid "database is locked" error: don't open the two databases at the same time try! dbQueue.inDatabase { db in try db.execute("BEGIN DEFERRED TRANSACTION") s1.signal() _ = s2.wait(timeout: .distantFuture) XCTAssertEqual(try Int.fetchOne(db, "SELECT SUM(value) AS balance FROM moves"), 0) // Zero balance s3.signal() _ = s4.wait(timeout: .distantFuture) XCTAssertEqual(try Int.fetchOne(db, "SELECT SUM(value) AS balance FROM moves"), 0) // Zero balance try db.execute("END") } } let block2 = { () in _ = s0.wait(timeout: .distantFuture) // Avoid "database is locked" error: don't open the two databases at the same time let dbQueue = try! self.makeDatabaseQueue(filename: "test.sqlite") try! dbQueue.inDatabase { db in _ = s1.wait(timeout: .distantFuture) try db.execute("BEGIN DEFERRED TRANSACTION") try db.execute("INSERT INTO moves VALUES (1)") s2.signal() _ = s3.wait(timeout: .distantFuture) try db.execute("INSERT INTO moves VALUES (-1)") s4.signal() try db.execute("END") } } let blocks = [block1, block2] DispatchQueue.concurrentPerform(iterations: blocks.count) { index in blocks[index]() } } func testWrappedReadWrite() throws { let dbPool = try makeDatabasePool() try dbPool.write { db in try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") try db.execute("INSERT INTO items (id) VALUES (NULL)") } let id = try dbPool.read { db in try Int.fetchOne(db, "SELECT id FROM items")! } XCTAssertEqual(id, 1) } func testReadFromPreviousNonWALDatabase() throws { do { let dbQueue = try makeDatabaseQueue(filename: "test.sqlite") try dbQueue.inDatabase { db in try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") try db.execute("INSERT INTO items (id) VALUES (NULL)") } } do { let dbPool = try makeDatabasePool(filename: "test.sqlite") let id = try dbPool.read { db in try Int.fetchOne(db, "SELECT id FROM items")! } XCTAssertEqual(id, 1) } } func testReadOpensATransaction() throws { let dbPool = try makeDatabasePool() try dbPool.read { db in XCTAssertTrue(db.isInsideTransaction) do { try db.execute("BEGIN DEFERRED TRANSACTION") XCTFail("Expected error") } catch let error as DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_ERROR) XCTAssertEqual(error.message!, "cannot start a transaction within a transaction") XCTAssertEqual(error.sql!, "BEGIN DEFERRED TRANSACTION") XCTAssertEqual(error.description, "SQLite error 1 with statement `BEGIN DEFERRED TRANSACTION`: cannot start a transaction within a transaction") } } } func testReadError() throws { let dbPool = try makeDatabasePool() // Block 1 Block 2 // PRAGMA locking_mode=EXCLUSIVE // CREATE TABLE // > let s1 = DispatchSemaphore(value: 0) // dbPool.read // throws let block1 = { () in try! dbPool.write { db in try db.execute("PRAGMA locking_mode=EXCLUSIVE") try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") s1.signal() } } let block2 = { () in _ = s1.wait(timeout: .distantFuture) do { try dbPool.read { _ in } XCTFail("Expected error") } catch let error as DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_BUSY) XCTAssertEqual(error.message!, "database is locked") XCTAssertTrue(error.sql == nil) XCTAssertEqual(error.description, "SQLite error 5: database is locked") } catch { XCTFail("Expected DatabaseError") } } let blocks = [block1, block2] DispatchQueue.concurrentPerform(iterations: blocks.count) { index in blocks[index]() } } func testConcurrentRead() throws { let dbPool = try makeDatabasePool() try dbPool.write { db in try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") for _ in 0..<3 { try db.execute("INSERT INTO items (id) VALUES (NULL)") } } // Block 1 Block 2 // dbPool.read { dbPool.read { // SELECT * FROM items SELECT * FROM items // step step // > let s1 = DispatchSemaphore(value: 0) // step // < let s2 = DispatchSemaphore(value: 0) // step step // step end // end } // } let block1 = { () in try! dbPool.read { db in let cursor = try Row.fetchCursor(db, "SELECT * FROM items") XCTAssertTrue(try cursor.next() != nil) s1.signal() _ = s2.wait(timeout: .distantFuture) XCTAssertTrue(try cursor.next() != nil) XCTAssertTrue(try cursor.next() != nil) XCTAssertTrue(try cursor.next() == nil) } } let block2 = { () in try! dbPool.read { db in let cursor = try Row.fetchCursor(db, "SELECT * FROM items") XCTAssertTrue(try cursor.next() != nil) _ = s1.wait(timeout: .distantFuture) XCTAssertTrue(try cursor.next() != nil) s2.signal() XCTAssertTrue(try cursor.next() != nil) XCTAssertTrue(try cursor.next() == nil) } } let blocks = [block1, block2] DispatchQueue.concurrentPerform(iterations: blocks.count) { index in blocks[index]() } } func testReadMethodIsolationOfStatement() throws { let dbPool = try makeDatabasePool() try dbPool.write { db in try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") for _ in 0..<2 { try db.execute("INSERT INTO items (id) VALUES (NULL)") } } // Block 1 Block 2 // dbPool.read { // SELECT * FROM items // step // > let s1 = DispatchSemaphore(value: 0) // DELETE * FROM items // < let s2 = DispatchSemaphore(value: 0) // step // end // } let block1 = { () in try! dbPool.read { db in let cursor = try Row.fetchCursor(db, "SELECT * FROM items") XCTAssertTrue(try cursor.next() != nil) s1.signal() _ = s2.wait(timeout: .distantFuture) XCTAssertTrue(try cursor.next() != nil) XCTAssertTrue(try cursor.next() == nil) } } let block2 = { () in do { _ = s1.wait(timeout: .distantFuture) defer { s2.signal() } try dbPool.write { db in try db.execute("DELETE FROM items") } } catch { XCTFail("error: \(error)") } } let blocks = [block1, block2] DispatchQueue.concurrentPerform(iterations: blocks.count) { index in blocks[index]() } } func testReadMethodIsolationOfStatementWithCheckpoint() throws { let dbPool = try makeDatabasePool() try dbPool.write { db in try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") for _ in 0..<2 { try db.execute("INSERT INTO items (id) VALUES (NULL)") } } // Block 1 Block 2 // dbPool.read { // SELECT * FROM items // step // > let s1 = DispatchSemaphore(value: 0) // DELETE * FROM items // Checkpoint // < let s2 = DispatchSemaphore(value: 0) // step // end // } let block1 = { () in try! dbPool.read { db in let cursor = try Row.fetchCursor(db, "SELECT * FROM items") XCTAssertTrue(try cursor.next() != nil) s1.signal() _ = s2.wait(timeout: .distantFuture) XCTAssertTrue(try cursor.next() != nil) XCTAssertTrue(try cursor.next() == nil) } } let block2 = { () in do { _ = s1.wait(timeout: .distantFuture) defer { s2.signal() } try dbPool.write { db in try db.execute("DELETE FROM items") } try dbPool.checkpoint() } catch { XCTFail("error: \(error)") } } let blocks = [block1, block2] DispatchQueue.concurrentPerform(iterations: blocks.count) { index in blocks[index]() } } func testReadBlockIsolationStartingWithRead() throws { let dbPool = try makeDatabasePool() try dbPool.write { db in try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") } // Block 1 Block 2 // dbPool.read { // > let s1 = DispatchSemaphore(value: 0) // INSERT INTO items (id) VALUES (NULL) // < let s2 = DispatchSemaphore(value: 0) // SELECT COUNT(*) FROM items -> 0 // > let s3 = DispatchSemaphore(value: 0) // INSERT INTO items (id) VALUES (NULL) // < let s4 = DispatchSemaphore(value: 0) // SELECT COUNT(*) FROM items -> 0 // } let block1 = { () in try! dbPool.read { db in s1.signal() _ = s2.wait(timeout: .distantFuture) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 1) // Not a bug. The writer did not start a transaction. s3.signal() _ = s4.wait(timeout: .distantFuture) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 1) } } let block2 = { () in do { _ = s1.wait(timeout: .distantFuture) try dbPool.write { db in try db.execute("INSERT INTO items (id) VALUES (NULL)") s2.signal() _ = s3.wait(timeout: .distantFuture) try db.execute("INSERT INTO items (id) VALUES (NULL)") s4.signal() } } catch { XCTFail("error: \(error)") } } let blocks = [block1, block2] DispatchQueue.concurrentPerform(iterations: blocks.count) { index in blocks[index]() } } func testReadBlockIsolationStartingWithSelect() throws { let dbPool = try makeDatabasePool() try dbPool.write { db in try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") } // Block 1 Block 2 // dbPool.read { // SELECT COUNT(*) FROM items -> 0 // > let s1 = DispatchSemaphore(value: 0) // INSERT INTO items (id) VALUES (NULL) // Checkpoint // < let s2 = DispatchSemaphore(value: 0) // SELECT COUNT(*) FROM items -> 0 // } let block1 = { () in try! dbPool.read { db in XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 0) s1.signal() _ = s2.wait(timeout: .distantFuture) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 0) } } let block2 = { () in do { _ = s1.wait(timeout: .distantFuture) defer { s2.signal() } try dbPool.write { db in try db.execute("INSERT INTO items (id) VALUES (NULL)") } try dbPool.checkpoint() } catch { XCTFail("error: \(error)") } } let blocks = [block1, block2] DispatchQueue.concurrentPerform(iterations: blocks.count) { index in blocks[index]() } } func testReadBlockIsolationStartingWithWrite() throws { let dbPool = try makeDatabasePool() try dbPool.write { db in try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") } // Block 1 Block 2 // INSERT INTO items (id) VALUES (NULL) // > let s1 = DispatchSemaphore(value: 0) // dbPool.read { // SELECT COUNT(*) FROM items -> 1 // < let s2 = DispatchSemaphore(value: 0) // INSERT INTO items (id) VALUES (NULL) // > let s3 = DispatchSemaphore(value: 0) // SELECT COUNT(*) FROM items -> 1 // < let s4 = DispatchSemaphore(value: 0) // > let s5 = DispatchSemaphore(value: 0) // SELECT COUNT(*) FROM items -> 1 // } let block1 = { () in do { try dbPool.write { db in try db.execute("INSERT INTO items (id) VALUES (NULL)") s1.signal() _ = s2.wait(timeout: .distantFuture) try db.execute("INSERT INTO items (id) VALUES (NULL)") s3.signal() _ = s4.wait(timeout: .distantFuture) } s5.signal() } catch { XCTFail("error: \(error)") } } let block2 = { () in try! dbPool.read { db in _ = s1.wait(timeout: .distantFuture) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 1) s2.signal() _ = s3.wait(timeout: .distantFuture) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 1) s4.signal() _ = s5.wait(timeout: .distantFuture) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 1) } } let blocks = [block1, block2] DispatchQueue.concurrentPerform(iterations: blocks.count) { index in blocks[index]() } } func testReadBlockIsolationStartingWithWriteTransaction() throws { let dbPool = try makeDatabasePool() try dbPool.write { db in try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") } // Block 1 Block 2 // BEGIN IMMEDIATE TRANSACTION // INSERT INTO items (id) VALUES (NULL) // > let s1 = DispatchSemaphore(value: 0) // dbPool.read { // SELECT COUNT(*) FROM items -> 0 // < let s2 = DispatchSemaphore(value: 0) // INSERT INTO items (id) VALUES (NULL) // > let s3 = DispatchSemaphore(value: 0) // SELECT COUNT(*) FROM items -> 0 // < let s4 = DispatchSemaphore(value: 0) // COMMIT // > let s5 = DispatchSemaphore(value: 0) // SELECT COUNT(*) FROM items -> 0 // } let block1 = { () in do { try dbPool.writeInTransaction(.immediate) { db in try db.execute("INSERT INTO items (id) VALUES (NULL)") s1.signal() _ = s2.wait(timeout: .distantFuture) try db.execute("INSERT INTO items (id) VALUES (NULL)") s3.signal() _ = s4.wait(timeout: .distantFuture) return .commit } s5.signal() } catch { XCTFail("error: \(error)") } } let block2 = { () in try! dbPool.read { db in _ = s1.wait(timeout: .distantFuture) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 0) s2.signal() _ = s3.wait(timeout: .distantFuture) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 0) s4.signal() _ = s5.wait(timeout: .distantFuture) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 0) } } let blocks = [block1, block2] DispatchQueue.concurrentPerform(iterations: blocks.count) { index in blocks[index]() } } func testUnsafeReadMethodIsolationOfStatement() throws { let dbPool = try makeDatabasePool() try dbPool.write { db in try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") for _ in 0..<2 { try db.execute("INSERT INTO items (id) VALUES (NULL)") } } // Block 1 Block 2 // dbPool.unsafeRead { // SELECT * FROM items // step // > let s1 = DispatchSemaphore(value: 0) // DELETE * FROM items // < let s2 = DispatchSemaphore(value: 0) // step // end // SELECT COUNT(*) FROM items -> 0 // } let block1 = { () in try! dbPool.unsafeRead { db in let cursor = try Row.fetchCursor(db, "SELECT * FROM items") XCTAssertTrue(try cursor.next() != nil) s1.signal() _ = s2.wait(timeout: .distantFuture) XCTAssertTrue(try cursor.next() != nil) XCTAssertTrue(try cursor.next() == nil) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 0) } } let block2 = { () in do { _ = s1.wait(timeout: .distantFuture) defer { s2.signal() } try dbPool.write { db in try db.execute("DELETE FROM items") } } catch { XCTFail("error: \(error)") } } let blocks = [block1, block2] DispatchQueue.concurrentPerform(iterations: blocks.count) { index in blocks[index]() } } func testUnsafeReadMethodIsolationOfStatementWithCheckpoint() throws { let dbPool = try makeDatabasePool() try dbPool.write { db in try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") for _ in 0..<2 { try db.execute("INSERT INTO items (id) VALUES (NULL)") } } // Block 1 Block 2 // dbPool.unsafeRead { // SELECT * FROM items // step // > let s1 = DispatchSemaphore(value: 0) // DELETE * FROM items // Checkpoint // < let s2 = DispatchSemaphore(value: 0) // step // end // } let block1 = { () in try! dbPool.unsafeRead { db in let cursor = try Row.fetchCursor(db, "SELECT * FROM items") XCTAssertTrue(try cursor.next() != nil) s1.signal() _ = s2.wait(timeout: .distantFuture) XCTAssertTrue(try cursor.next() != nil) XCTAssertTrue(try cursor.next() == nil) } } let block2 = { () in do { _ = s1.wait(timeout: .distantFuture) defer { s2.signal() } try dbPool.write { db in try db.execute("DELETE FROM items") } try dbPool.checkpoint() } catch { XCTFail("error: \(error)") } } let blocks = [block1, block2] DispatchQueue.concurrentPerform(iterations: blocks.count) { index in blocks[index]() } } func testUnsafeReadMethodIsolationOfBlock() throws { let dbPool = try makeDatabasePool() try dbPool.write { db in try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") } // Block 1 Block 2 // dbPool.unsafeRead { // SELECT COUNT(*) FROM items -> 0 // > let s1 = DispatchSemaphore(value: 0) // INSERT INTO items (id) VALUES (NULL) // Checkpoint // < let s2 = DispatchSemaphore(value: 0) // SELECT COUNT(*) FROM items -> 1 // } let block1 = { () in try! dbPool.unsafeRead { db in XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 0) s1.signal() _ = s2.wait(timeout: .distantFuture) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 1) } } let block2 = { () in do { _ = s1.wait(timeout: .distantFuture) defer { s2.signal() } try dbPool.write { db in try db.execute("INSERT INTO items (id) VALUES (NULL)") } try dbPool.checkpoint() } catch { XCTFail("error: \(error)") } } let blocks = [block1, block2] DispatchQueue.concurrentPerform(iterations: blocks.count) { index in blocks[index]() } } func testReadFromCurrentStateOpensATransaction() throws { let dbPool = try makeDatabasePool() let s = DispatchSemaphore(value: 0) try dbPool.write { db in try dbPool.readFromCurrentState { db in XCTAssertTrue(db.isInsideTransaction) do { try db.execute("BEGIN DEFERRED TRANSACTION") XCTFail("Expected error") } catch { } s.signal() } } _ = s.wait(timeout: .distantFuture) } func testReadFromCurrentStateOutsideOfTransaction() throws { let dbPool = try makeDatabasePool() try dbPool.write { db in try db.create(table: "persons") { t in t.column("id", .integer).primaryKey() } } // Writer Reader // dbPool.write { // > // dbPool.readFromCurrentState { // < // INSERT INTO items (id) VALUES (NULL) // > let s1 = DispatchSemaphore(value: 0) // } SELECT COUNT(*) FROM persons -> 0 // < let s2 = DispatchSemaphore(value: 0) // } var i: Int! = nil try dbPool.write { db in try dbPool.readFromCurrentState { db in _ = s1.wait(timeout: .distantFuture) i = try! Int.fetchOne(db, "SELECT COUNT(*) FROM persons")! s2.signal() } try db.execute("INSERT INTO persons DEFAULT VALUES") s1.signal() } _ = s2.wait(timeout: .distantFuture) XCTAssertEqual(i, 0) } func testReadFromCurrentStateError() throws { dbConfiguration.trace = { print($0) } let dbPool = try makeDatabasePool() try dbPool.write { db in try db.execute("PRAGMA locking_mode=EXCLUSIVE") try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") do { try dbPool.readFromCurrentState { db in fatalError("Should not run") } XCTFail("Expected error") } catch let error as DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_BUSY) XCTAssertEqual(error.message!, "database is locked") XCTAssertTrue(error.sql == nil) XCTAssertEqual(error.description, "SQLite error 5: database is locked") } } } func testIssue80() throws { // See https://github.com/groue/GRDB.swift/issues/80 // // Here we test that `SELECT * FROM search`, which is announced by // SQLite has a statement that modifies the sqlite_master table, is // still allowed as a regular select statement. // // This test uses a database pool, a connection for creating the // search virtual table, and another connection for reading. // // This is the tested setup: don't change it. let dbPool = try makeDatabasePool() try dbPool.write { db in try db.execute("CREATE VIRTUAL TABLE search USING fts3(title)") } try dbPool.read { db in _ = try Row.fetchAll(db, "SELECT * FROM search") } } }
mit
2e4e744e771cce166172be3337a20887
38.206974
160
0.477865
5.020887
false
false
false
false
Nyx0uf/SwiftyImages
src/extensions/UIImage+Resizing.swift
1
8408
// UIImage+Resizing.swift // Copyright (c) 2016 Nyx0uf // // 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 public extension UIImage { // MARK: - Cropping public func cropped(toSize: CGSize) -> UIImage? { return self.cropped(toSize: toSize, mode: .topLeft) } public func cropped(toSize: CGSize, mode: NYXCropMode) -> UIImage? { guard let cgImage = self.cgImage else { return nil } let size = self.size var x: CGFloat = 0.0, y: CGFloat = 0.0 switch (mode) { case .topLeft: x = 0.0 y = 0.0 case .topCenter: x = (size.width - toSize.width) * 0.5 y = 0.0 case .topRight: x = size.width - toSize.width y = 0.0 case .bottomLeft: x = 0.0 y = size.height - toSize.height case .bottomCenter: x = (size.width - toSize.width) * 0.5 y = size.height - toSize.height case .bottomRight: x = size.width - toSize.width y = size.height - toSize.height case .leftCenter: x = 0.0 y = (size.height - toSize.height) * 0.5 case .rightCenter: x = size.width - toSize.width y = (size.height - toSize.height) * 0.5 case .center: x = (size.width - toSize.width) * 0.5 y = (size.height - toSize.height) * 0.5 } var newSize = toSize if self.imageOrientation == .left || self.imageOrientation == .leftMirrored || self.imageOrientation == .right || self.imageOrientation == .rightMirrored { var temp = x x = y y = temp temp = newSize.width newSize.width = newSize.height newSize.height = temp } // Create the cropped image let cropRect = CGRect(x * self.scale, y * self.scale, newSize.width * self.scale, newSize.height * self.scale) guard let croppedImageRef = cgImage.cropping(to: cropRect) else { return nil } return UIImage(cgImage: croppedImageRef, scale: self.scale, orientation: self.imageOrientation) } func smartCropped(toSize: CGSize) -> UIImage? { guard let cgImage = self.cgImage else { return nil } let sourceWidth = self.size.width * self.scale let sourceHeight = self.size.height * self.scale let targetWidth = toSize.width let targetHeight = toSize.height // Calculate aspect ratios let sourceRatio = sourceWidth / sourceHeight let targetRatio = targetWidth / targetHeight // Determine what side of the source image to use for proportional scaling let scaleWidth = (sourceRatio <= targetRatio) // Proportionally scale source image var scalingFactor: CGFloat, scaledWidth: CGFloat, scaledHeight: CGFloat if (scaleWidth) { scalingFactor = 1.0 / sourceRatio scaledWidth = targetWidth scaledHeight = CGFloat(round(targetWidth * scalingFactor)) } else { scalingFactor = sourceRatio scaledWidth = CGFloat(round(targetHeight * scalingFactor)) scaledHeight = targetHeight } let scaleFactor = scaledHeight / sourceHeight let destRect = CGRect(CGPoint.zero, toSize).integral // Crop center let destX = CGFloat(round((scaledWidth - targetWidth) * 0.5)) let destY = CGFloat(round((scaledHeight - targetHeight) * 0.5)) let sourceRect = CGRect(ceil(destX / scaleFactor), destY / scaleFactor, targetWidth / scaleFactor, targetHeight / scaleFactor).integral // Create scale-cropped image if #available(iOS 10, *) { let renderer = UIGraphicsImageRenderer(size: destRect.size) return renderer.image() { rendererContext in guard let sourceImg = cgImage.cropping(to: sourceRect) else // cropping happens here { return } let image = UIImage(cgImage: sourceImg, scale: 0.0, orientation: self.imageOrientation) image.draw(in: destRect) // the actual scaling happens here, and orientation is taken care of automatically } } else { UIGraphicsBeginImageContextWithOptions(destRect.size, false, 0.0) // 0.0 = scale for device's main screen guard let sourceImg = cgImage.cropping(to: sourceRect) else // cropping happens here { return nil } let image = UIImage(cgImage: sourceImg, scale: 0.0, orientation: self.imageOrientation) image.draw(in: destRect) // the actual scaling happens here, and orientation is taken care of automatically let final = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return final } } // MARK: - Scaling public func scaled(factor: CGFloat) -> UIImage? { let scaledSize = CGSize(self.size.width * factor, self.size.height * factor) return self.scaleToFillSize(scaledSize) } public func scaled(toSize: CGSize) -> UIImage? { return self.scaleToFillSize(toSize) } public func scaled(toSize: CGSize, mode: NYXScaleMode) -> UIImage? { switch (mode) { case .aspectFit: return self.scaleToFitSize(toSize) case .aspectFill: return self.scaleToCoverSize(toSize) default: return self.scaleToFillSize(toSize) } } private func scaleToFillSize(_ scaleSize: CGSize) -> UIImage? { guard let cgImage = self.cgImage else { return nil } var destWidth = Int(scaleSize.width * self.scale) var destHeight = Int(scaleSize.height * self.scale) if self.imageOrientation == .left || self.imageOrientation == .leftMirrored || self.imageOrientation == .right || self.imageOrientation == .rightMirrored { let temp = destWidth destWidth = destHeight destHeight = temp } // Create an ARGB bitmap context guard let bmContext = CGContext.ARGBBitmapContext(width: destWidth, height: destHeight, withAlpha: cgImage.hasAlpha()) else { return nil } // Image quality bmContext.setShouldAntialias(true) bmContext.setAllowsAntialiasing(true) bmContext.interpolationQuality = .high // Draw the image in the bitmap context UIGraphicsPushContext(bmContext) bmContext.draw(cgImage, in: CGRect(0, 0, destWidth, destHeight)) UIGraphicsPopContext() // Create an image object from the context guard let scaledImageRef = bmContext.makeImage() else { return nil } return UIImage(cgImage: scaledImageRef, scale: self.scale, orientation: self.imageOrientation) } private func scaleToFitSize(_ scaleSize: CGSize) -> UIImage? { // Keep aspect ratio var destWidth = 0, destHeight = 0 if self.size.width > self.size.height { destWidth = Int(scaleSize.width) destHeight = Int(self.size.height * scaleSize.width / self.size.width) } else { destHeight = Int(scaleSize.height) destWidth = Int(self.size.width * scaleSize.height / self.size.height) } if destWidth > Int(scaleSize.width) { destWidth = Int(scaleSize.width) destHeight = Int(self.size.height * scaleSize.width / self.size.width) } if destHeight > Int(scaleSize.height) { destHeight = Int(scaleSize.height) destWidth = Int(self.size.width * scaleSize.height / self.size.height) } return self.scaleToFillSize(CGSize(destWidth, destHeight)) } private func scaleToCoverSize(_ scaleSize: CGSize) -> UIImage? { var destWidth = 0, destHeight = 0 let widthRatio = scaleSize.width / self.size.width let heightRatio = scaleSize.height / self.size.height // Keep aspect ratio if heightRatio > widthRatio { destHeight = Int(scaleSize.height) destWidth = Int(self.size.width * scaleSize.height / self.size.height) } else { destWidth = Int(scaleSize.width) destHeight = Int(self.size.height * scaleSize.width / self.size.width) } return self.scaleToFillSize(CGSize(destWidth, destHeight)) } }
mit
a208dcb322a3ed4196406d77b0c7863b
28.501754
137
0.706827
3.662021
false
false
false
false
chetca/Android_to_iOs
memuDemo/LecturesSC/LecturesTableViewController.swift
1
2866
// // LecturesTableViewController.swift // memuDemo // // Created by Dugar Badagarov on 29/08/2017. // Copyright © 2017 Parth Changela. All rights reserved. // import UIKit class LecturesTableViewController: UITableViewController { @IBOutlet var btnMenuButton: UIBarButtonItem! var paramDict:[String:[String]] = Dictionary() override func viewDidLoad() { super.viewDidLoad() if revealViewController() != nil { btnMenuButton.target = revealViewController() btnMenuButton.action = #selector(SWRevealViewController.revealToggle(_:)) paramDict = JSONTaker.shared.loadData(API: "lectures", paramNames: ["title", "date", "short", "image", "text"]) //loadAstrologicalData(baseURL: "file:///Users/dugar/Downloads/feed.json") //print (paramDict) } tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 140 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (paramDict["title"]?.count)! } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print("You selected name : "+(self.paramDict["date"]?[indexPath.row])!) StringLblText = (self.paramDict["title"]?[indexPath.row])! StringText = (self.paramDict["text"]?[indexPath.row])! StringDataField = (self.paramDict["date"]?[indexPath.row])! StringUrlImg = (self.paramDict["image"]?[indexPath.row])! performSegue(withIdentifier: "segue", sender: self) } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: LectureTableViewCell = tableView.dequeueReusableCell(withIdentifier: "LectureTableViewCell", for: indexPath) as! LectureTableViewCell cell.dateLbl.text = JSONTaker.shared.convertDate(date: (self.paramDict["date"]?[indexPath.row])!) //cell.dateLbl.text = JSONTaker.shared.convertDate(date: (self.paramDict["date"]?[indexPath.row])!) cell.titleLbl.text = self.paramDict["title"]?[indexPath.row] cell.shortTextLbl.setHTML(html: (self.paramDict["short"]?[indexPath.row])!) JSONTaker.shared.loadImg(imgURL: (self.paramDict["image"]?[indexPath.row])!, img: [cell.img], spinner: cell.spinner) return cell } }
mit
7d2f19c24c983ff1723ae9a345ac9066
38.791667
151
0.612216
5.152878
false
false
false
false
wookay/Look
Look/lib/UIViewControllerLook.swift
1
511
// // UIViewControllerLook.swift // Look // // Created by wookyoung on 11/27/15. // Copyright © 2015 factorcat. All rights reserved. // import UIKit extension Look { public convenience init(UIViewController vc: UIViewController?) { self.init() if let vc = vc { self.object = vc if CGRectZero == vc.view.frame { vc.view.frame = def.frame } self.preview = .View(vc.view) self.canvas = vc.view } } }
mit
99eaec01f099f62bc7b76ff2e58761f7
21.217391
69
0.55098
3.923077
false
false
false
false
blinksh/blink
BlinkTests/SSHCommandTests.swift
1
4072
////////////////////////////////////////////////////////////////////////////////// // // B L I N K // // Copyright (C) 2016-2019 Blink Mobile Shell Project // // This file is part of Blink. // // Blink is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Blink is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Blink. If not, see <http://www.gnu.org/licenses/>. // // In addition, Blink is also subject to certain additional terms under // GNU GPL version 3 section 7. // // You should have received a copy of these additional terms immediately // following the terms and conditions of the GNU General Public License // which accompanied the Blink Source Code. If not, see // <http://www.github.com/blinksh/blink>. // //////////////////////////////////////////////////////////////////////////////// import Foundation import XCTest import ArgumentParser class SSHCommandTests: XCTestCase { override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testSshCommandParameters() throws { let commandString = "-vv -L 8080:localhost:80 -i id_rsa -p 2023 [email protected] -- echo 'hello'" do { var components = commandString.components(separatedBy: " ") let command = try SSHCommand.parse(components) XCTAssertTrue(command.localPortForward?.localPort == 8080) XCTAssertTrue(command.localPortForward?.remotePort == 80) XCTAssertTrue(command.localPortForward?.bindAddress == "localhost") XCTAssertTrue(command.verbose == 2) XCTAssertTrue(command.port == 2023) XCTAssertTrue(command.identityFile == "id_rsa") XCTAssertTrue(command.host == "17.0.0.1") XCTAssertTrue(command.user == "username") XCTAssertTrue(command.command == ["echo", "'hello'"]) } catch { let msg = SSHCommand.message(for: error) XCTFail("Couldn't parse command: \(msg)") } } func testMoshCommandParameters() throws { var commandString = "localhost tmux -vv --attach" do { let components = commandString.components(separatedBy: " ") let command = try SSHCommand.parse(components) XCTAssertTrue(command.command == ["tmux", "--attach"]) } catch { let msg = SSHCommand.message(for: error) XCTFail("Couldn't parse command: \(msg)") } commandString = "localhost -- tmux -vv --attach" do { let components = commandString.components(separatedBy: " ") let command = try SSHCommand.parse(components) XCTAssertTrue(command.command == ["tmux", "-vv", "--attach"]) } catch { let msg = SSHCommand.message(for: error) XCTFail("Couldn't parse command: \(msg)") } } func testSshCommandOptionals() throws { let args = ["-o", "ProxyCommand=ssh", "localhost", "-o", "Compression=yes", "-o", "CompressionLevel=4"] do { let command = try SSHCommand.parse(args) let options = try command.connectionOptions.get() XCTAssertTrue(options.proxyCommand == "ssh") XCTAssertTrue(options.compression == true) XCTAssert(options.compressionLevel == 4) } catch { let msg = SSHCommand.message(for: error) XCTFail("Couldn't parse SSH command: \(msg)") } } func testUnknownOptional() throws { let args = ["-o", "ProxyCommand=ssh", "localhost", "-o", "Compresion=yes"] do { let command = try SSHCommand.parse(args) XCTFail("Parsing should have failed") } catch { } } }
gpl-3.0
d8c3c79303f4b04e25ac7fe14e6ebf9a
33.803419
107
0.649558
4.359743
false
true
false
false
Diego5529/tcc-swift3
tcc-swift3/src/controllers/EventFormViewController.swift
1
17671
// // EventFormViewController.swift // tcc-swift3 // // Created by Diego Oliveira on 24/05/17. // Copyright © 2017 DO. All rights reserved. // import Former import CoreData class EventFormViewController : FormViewController { var delegate: AppDelegate! var context: NSManagedObjectContext! var companyEvent: CompanyBean! var eventClass: EventBean! var invitations: NSMutableDictionary = [:] override func viewDidLoad() { super.viewDidLoad() delegate = UIApplication.shared.delegate as! AppDelegate context = self.delegate.managedObjectContext if eventClass == nil { eventClass = EventBean.init() eventClass.company_id = companyEvent.company_id } configureCompanyRows() addSaveButton() } func addSaveButton(){ let addButton = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(insertNewObject(_:))) self.navigationItem.rightBarButtonItem = addButton } func insertNewObject(_ sender: Any) { if self.eventClass?.created_at == nil { eventClass?.created_at = NSDate.init() } let message = eventClass?.validateCreateEvent(title: eventClass.title!, shortDescription: eventClass.short_description!, longDescription: eventClass.long_description!, minUsers: (eventClass?.min_users)!, maxUsers: (eventClass?.max_users)!, createdAt: eventClass!.created_at) if (message?.isEmpty)! { self.navigationItem.rightBarButtonItem?.isEnabled = false self.eventClass.event_id = EventBean().getMaxEvent(context: self.context) let eventObj: NSManagedObject = NSEntityDescription.insertNewObject(forEntityName: "Event", into: self.context) eventObj.setValue(self.eventClass.event_id, forKey: "event_id") eventObj.setValue(eventClass.title, forKey: "title") eventObj.setValue(eventClass.short_description, forKey: "short_description") eventObj.setValue(eventClass.long_description, forKey: "long_description") eventObj.setValue(eventClass.min_users, forKey: "min_users") eventObj.setValue(eventClass.max_users, forKey: "max_users") eventObj.setValue(eventClass.created_at, forKey: "created_at") eventObj.setValue(eventClass.initial_date, forKey: "initial_date") eventObj.setValue(eventClass.end_date, forKey: "end_date") eventObj.setValue(eventClass.initial_hour, forKey: "initial_hour") eventObj.setValue(eventClass.end_hour, forKey: "end_hour") eventObj.setValue(eventClass.city_id, forKey: "city_id") eventObj.setValue(eventClass.company_id, forKey: "company_id") eventObj.setValue(eventClass.archive, forKey: "archive") eventObj.setValue(eventClass.status, forKey: "status") do { try self.context.save() print("save success!") self.former.reload() }catch{ print("Salvou") } }else{ showMessage(message: message!, title: "Error", cancel: "") } } override func viewDidAppear(_ animated: Bool) { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func configureCompanyRows (){ // Create RowFormers // CompanyRows let inputAccessoryView = FormerInputAccessoryView(former: former) // Create RowFormers let createMenu: ((String, (() -> Void)?) -> RowFormer) = { text, onSelected in return LabelRowFormer<FormLabelCell>() { $0.titleLabel.textColor = .formerColor() $0.titleLabel.font = .boldSystemFont(ofSize: 16) $0.accessoryType = .disclosureIndicator }.configure { $0.text = text }.onSelected { _ in onSelected?() } } // Create Headers and Footers let createHeader: ((String) -> ViewFormer) = { text in return LabelViewFormer<FormLabelHeaderView>() .configure { $0.text = text $0.viewHeight = 44 } } //Create Rows //Title let textFieldTitleEvent = TextFieldRowFormer<FormTextFieldCell>() { $0.titleLabel.text = "Title" $0.textField.keyboardType = .alphabet }.configure { $0.placeholder = "" }.onTextChanged { print($0) self.navigationItem.rightBarButtonItem?.isEnabled = true self.eventClass?.title = $0 }.onUpdate{ $0.text = self.eventClass.title } //Description let textFieldDescription = TextFieldRowFormer<FormTextFieldCell>() { $0.titleLabel.text = "Short Description" $0.textField.keyboardType = .alphabet }.configure { $0.placeholder = "" }.onTextChanged { print($0) self.navigationItem.rightBarButtonItem?.isEnabled = true self.eventClass?.short_description = $0 }.onUpdate { $0.text = self.eventClass.short_description } //Long Description let textViewLongDescriptionRow = TextViewRowFormer<FormTextViewCell> { $0.titleLabel.text = "Long Description" }.configure { $0.placeholder = "" }.onTextChanged { print($0) self.navigationItem.rightBarButtonItem?.isEnabled = true self.eventClass?.long_description = $0 }.onUpdate { $0.text = self.eventClass.long_description } // Create SectionFormers let arrayInvitesRow = NSMutableArray() if self.eventClass.event_id > 0 { //Invitations let myInvitationsRow = createMenu("My Invitations") { [weak self] in let inviteFormVC = InvitationListViewController() inviteFormVC.companyEvent = self?.companyEvent inviteFormVC.eventClass = self?.eventClass self?.navigationController?.pushViewController(inviteFormVC, animated: true) } arrayInvitesRow.add(myInvitationsRow) // let newInviteRow = createMenu("New Invite") { [weak self] in let inviteFormVC = InviteFormViewController() inviteFormVC.eventClass = self?.eventClass self?.navigationController?.pushViewController(inviteFormVC, animated: true) } arrayInvitesRow.add(newInviteRow) } let invitationsSection = SectionFormer(rowFormers: arrayInvitesRow as! [RowFormer]) .set(headerViewFormer: createHeader("Invitations")) //City let selectorCityPickerRow = SelectorPickerRowFormer<FormSelectorPickerCell, Any>() { $0.titleLabel.text = "City" }.configure { $0.pickerItems = [SelectorPickerItem( title: "", displayTitle: NSAttributedString(string: "Not Set"), value: nil)] + (1...20).map { SelectorPickerItem(title: "City \($0)") } }.onValueChanged { print($0) // print($0.displayTitle!,$0.value! , $0.title) } //Initial Date let initialDateRow = InlineDatePickerRowFormer<FormInlineDatePickerCell>() { $0.titleLabel.text = "Initial Date" }.inlineCellSetup { $0.datePicker.datePickerMode = .date }.configure { $0.displayEditingColor = .formerHighlightedSubColor() }.displayTextFromDate(String.fullDate).onDateChanged { print($0) self.eventClass.initial_date = $0 as NSDate }.onUpdate { $0.date = self.eventClass.initial_date as Date } //End Date let endDateRow = InlineDatePickerRowFormer<FormInlineDatePickerCell>() { $0.titleLabel.text = "End Date" }.inlineCellSetup { $0.datePicker.datePickerMode = .date }.configure { $0.displayEditingColor = .formerHighlightedSubColor() }.displayTextFromDate(String.fullDate).onDateChanged { print($0) self.eventClass.end_date = $0 as NSDate }.onUpdate { $0.date = self.eventClass.end_date as Date } //Initial Hour let initialHourRow = InlineDatePickerRowFormer<FormInlineDatePickerCell>() { $0.titleLabel.text = "Initial Hour" }.inlineCellSetup { $0.datePicker.datePickerMode = .time }.configure { $0.displayEditingColor = .formerHighlightedSubColor() }.displayTextFromDate(String.fullTime).onDateChanged { print($0) self.eventClass.initial_hour = $0 as NSDate }.onUpdate { $0.date = self.eventClass.initial_hour as Date } //End Hour let endHourRow = InlineDatePickerRowFormer<FormInlineDatePickerCell>() { $0.titleLabel.text = "End Hour" }.inlineCellSetup { $0.datePicker.datePickerMode = .time }.configure { $0.displayEditingColor = .formerHighlightedSubColor() }.displayTextFromDate(String.fullTime).onDateChanged { print($0) self.eventClass.end_hour = $0 as NSDate }.onUpdate { $0.date = self.eventClass.end_hour as Date } //Min User let stepperRowMinUser = StepperRowFormer<FormStepperCell>(){ $0.titleLabel.text = "Min User" }.displayTextFromValue { "\(Int($0))" }.onValueChanged { self.navigationItem.rightBarButtonItem?.isEnabled = true print($0) }.onUpdate{ $0.value = Double(self.eventClass.min_users) } //Max User let stepperRowMaxUser = StepperRowFormer<FormStepperCell>(){ $0.titleLabel.text = "Max User" $0.stepper.value = Double(self.eventClass.max_users) }.displayTextFromValue { "\(Int($0))" }.onValueChanged { self.navigationItem.rightBarButtonItem?.isEnabled = true print($0) self.eventClass?.max_users = Int16($0) if stepperRowMinUser.value >= $0 { stepperRowMinUser.value = $0 stepperRowMinUser.update() } }.onUpdate{ $0.value = Double(self.eventClass.max_users) } //Min User Value Changed stepperRowMinUser.onValueChanged { self.navigationItem.rightBarButtonItem?.isEnabled = true print($0) self.eventClass?.min_users = Int16($0) stepperRowMaxUser.value = $0 stepperRowMaxUser.update() } //Archive let archiveEventCheckRow = CheckRowFormer<FormCheckCell>() { $0.titleLabel.text = "Archive Event" $0.titleLabel.textColor = .formerColor() $0.titleLabel.font = .boldSystemFont(ofSize: 16) }.configure { $0.checked = false }.onCheckChanged{ self.eventClass.archive = $0 }.onUpdate { $0.checked = self.eventClass.archive } // Create SectionFormers let section0 = SectionFormer(rowFormer: textFieldTitleEvent, textFieldDescription, textViewLongDescriptionRow) .set(headerViewFormer: createHeader("Event")) let section1 = SectionFormer(rowFormer: initialDateRow, endDateRow, initialHourRow, endHourRow) .set(headerViewFormer: createHeader("Date")) let section2 = SectionFormer(rowFormer: selectorCityPickerRow) .set(headerViewFormer: createHeader("Address")) let section3 = SectionFormer(rowFormer: archiveEventCheckRow) .set(headerViewFormer: createHeader("Others")) former.append(sectionFormer: section0, section1, invitationsSection, section2, section3 ).onCellSelected { _ in inputAccessoryView.update() } } private enum InsertPosition: Int { case Below, Above } private var insertRowAnimation = UITableViewRowAnimation.left private var insertSectionAnimation = UITableViewRowAnimation.fade private var insertRowPosition: InsertPosition = .Below private var insertSectionPosition: InsertPosition = .Below private lazy var subRowFormers: [RowFormer] = { return (1...2).map { index -> RowFormer in return CheckRowFormer<FormCheckCell>() { $0.titleLabel.text = "Check\(index)" $0.titleLabel.textColor = .formerColor() $0.titleLabel.font = .boldSystemFont(ofSize: 16) $0.tintColor = .formerSubColor() } } }() private lazy var subSectionFormer: SectionFormer = { return SectionFormer(rowFormers: [ CheckRowFormer<FormCheckCell>() { $0.titleLabel.text = "Check3" $0.titleLabel.textColor = .formerColor() $0.titleLabel.font = .boldSystemFont(ofSize: 16) $0.tintColor = .formerSubColor() } ]) }() private func insertRows(sectionTop: RowFormer, sectionBottom: RowFormer) -> (Bool) -> Void { return { [weak self] insert in guard let `self` = self else { return } if insert { if self.insertRowPosition == .Below { self.former.insertUpdate(rowFormers: self.subRowFormers, below: sectionBottom, rowAnimation: self.insertRowAnimation) } else if self.insertRowPosition == .Above { self.former.insertUpdate(rowFormers: self.subRowFormers, above: sectionTop, rowAnimation: self.insertRowAnimation) } } else { self.former.removeUpdate(rowFormers: self.subRowFormers, rowAnimation: self.insertRowAnimation) } } } private func insertSection(relate: SectionFormer) -> (Bool) -> Void { return { [weak self] insert in guard let `self` = self else { return } if insert { if self.insertSectionPosition == .Below { self.former.insertUpdate(sectionFormers: [self.subSectionFormer], below: relate, rowAnimation: self.insertSectionAnimation) } else if self.insertSectionPosition == .Above { self.former.insertUpdate(sectionFormers: [self.subSectionFormer], above: relate, rowAnimation: self.insertSectionAnimation) } } else { self.former.removeUpdate(sectionFormers: [self.subSectionFormer], rowAnimation: self.insertSectionAnimation) } } } private func sheetSelectorRowSelected(options: [String]) -> (RowFormer) -> Void { return { [weak self] rowFormer in if let rowFormer = rowFormer as? LabelRowFormer<FormLabelCell> { let sheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) options.forEach { title in sheet.addAction(UIAlertAction(title: title, style: .default, handler: { [weak rowFormer] _ in rowFormer?.subText = title rowFormer?.update() }) ) } sheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) self?.present(sheet, animated: true, completion: nil) self?.former.deselect(animated: true) } } } //AlertView func showMessage(message: String, title: String, cancel: String){ let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert) if cancel.characters.count > 0 { let DestructiveAction = UIAlertAction(title: cancel, style: UIAlertActionStyle.destructive) { (result : UIAlertAction) -> Void in print("Destructive") } alertController.addAction(DestructiveAction) } let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in } alertController.addAction(okAction) OperationQueue.main.addOperation { self.present(alertController, animated: false, completion: nil) } } }
mit
8d6366f5fb08f0333adfb6b28dbe404b
39.068027
282
0.563894
5.405323
false
false
false
false
sjf0213/DingShan
DingshanSwift/DingshanSwift/SNSShareView.swift
1
1232
// // SNSShareView.swift // DingshanSwift // // Created by song jufeng on 15/11/24. // Copyright © 2015年 song jufeng. All rights reserved. // import Foundation class SNSShareView:UIView{ var cancelHandler: (() -> Void)? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame aRect: CGRect) { super.init(frame: aRect); self.backgroundColor = UIColor.whiteColor() let cancelBtn = UIButton(frame: CGRect(x: 10, y: frame.size.height - 50, width: frame.size.width - 20, height: 40)) cancelBtn.backgroundColor = UIColor.lightGrayColor() self.addSubview(cancelBtn) let titleArr = ["微信好友", "朋友圈", "QQ", "微博"] let iconArr = ["sns_weixin", "sns_moments", "sns_qq", "sns_weibo"] let w:CGFloat = 72.0 let gap = (frame.size.width - 20.0 - 4*w)/5.0 for (var i = 0; i < 4; i++){ let btn = SNSShareBtn(frame: CGRect(x: 10.0+gap+CGFloat(i)*(w+gap), y: 0, width: w, height: 120)) btn.setImage(UIImage(named: iconArr[i]), forState:UIControlState.Normal) btn.title = titleArr[i] self.addSubview(btn); } } }
mit
76a6d1c6591f23aa16694edfab68354b
34.647059
123
0.591247
3.58284
false
false
false
false
amirdew/MyTasks
MyTasks/ViewControllers/AddEditTaskViewController.swift
1
7036
// // AddEditTaskViewController.swift // MyTasks // // Created by amir on 6/27/17. // Copyright © 2017 Amir Khorsandi. All rights reserved. // import UIKit class AddEditTaskViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var pageTitleLabel: UILabel! var editTask:Task! @IBOutlet weak var whiteView: UIView! @IBOutlet weak var whiteViewBottomConstraint: NSLayoutConstraint! @IBOutlet weak var cancelButtonCenterConstraint: NSLayoutConstraint! @IBOutlet weak var confirmButtonCenterConstraint: NSLayoutConstraint! @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var dateTextField: UITextField! @IBOutlet weak var descriptionTextField: UITextField! var datePicker:UIDatePicker! override func viewDidLoad() { super.viewDidLoad() setupViews() setupData() //add notification to watch keyboard frame NotificationCenter.default.addObserver(self, selector: #selector(keyboarFrameChange(notification:)), name: .UIKeyboardWillChangeFrame, object: nil) if (editTask) != nil{ pageTitleLabel.text = "Edit Task" } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) nameTextField.becomeFirstResponder() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: - Buttons action @IBAction func cancelButtonAction(_ sender: Any) { (sender as! UIButton).superview?.bringSubview(toFront: sender as! UIButton) dismiss() } @IBAction func confirmButtonAction(_ sender: Any) { //Validation: check name not empty if (nameTextField.text?.lengthOfBytes(using: .utf8))! < 1 { let alert = UIAlertController(title: "", message: "Write some text in name", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) return } //edit if let editTask = editTask{ editTask.name = nameTextField.text! editTask.date = datePicker.date editTask.desc = descriptionTextField.text! TaskRepository.edit(task: editTask) } //create new task else{ TaskRepository.new(name: nameTextField.text!, date: datePicker.date, author: UtilityHelper.getUserName(), desc: descriptionTextField.text!) } (sender as! UIButton).superview?.bringSubview(toFront: sender as! UIButton) dismiss() } //MARK: - func dismiss(){ //hide keyboard if isInEditing(){ self.view.endEditing(true) } //animation buttons confirmButtonCenterConstraint.constant = 0 cancelButtonCenterConstraint.constant = 0 UIView.animate(withDuration: 0.30) { self.view.layoutIfNeeded() } //animate and dismiss vc let when = DispatchTime.now() + 0.36 DispatchQueue.main.asyncAfter(deadline: when) { self.dismiss(animated: true, completion: nil) } } func isInEditing() -> Bool{ return nameTextField.isEditing || descriptionTextField.isEditing || dateTextField.isEditing } //MARK: - UITextFieldDelegate func textFieldShouldReturn(_ textField: UITextField) -> Bool { self.view.endEditing(true) return true } //MARK: - date picker func datePickerValueChanged(sender:Any) { dateTextField.text = UtilityHelper.getHumanDateString(date: datePicker.date) } func datePickerTextFieldValueChanged(sender:Any){ dateTextField.text = UtilityHelper.getHumanDateString(date: datePicker.date) } //MARK: - keyboard func keyboarFrameChange(notification:NSNotification){ let userInfo = notification.userInfo as! [String:AnyObject] let topOfKetboard = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue .origin.y var animationDuration:TimeInterval = 0.25 var animationCurve:UIViewAnimationCurve = .easeOut if let animDuration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber { animationDuration = animDuration.doubleValue } if let animCurve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber { animationCurve = UIViewAnimationCurve.init(rawValue: animCurve.intValue)! } let superHeight = (self.view.frame.size.height) var bottomInset = superHeight - topOfKetboard + 50 if bottomInset < 40 { bottomInset = 40 } whiteViewBottomConstraint.constant = bottomInset UIView.beginAnimations(nil, context: nil) UIView.setAnimationDuration(animationDuration) UIView.setAnimationCurve(animationCurve) self.view.layoutIfNeeded() UIView.commitAnimations() } //MARK: - setup func setupData(){ if let editTask = editTask{ datePicker.date = editTask.date! nameTextField.text = editTask.name descriptionTextField.text = editTask.desc } else{ datePicker.date = Date().addingTimeInterval(24*60*60) } dateTextField.text = UtilityHelper.getHumanDateString(date: datePicker.date) } func setupViews(){ //setup white view whiteView.layer.cornerRadius = 4 whiteView.layer.shadowColor = UIColor.black.cgColor whiteView.layer.shadowOffset = CGSize(width: 0, height: 0) whiteView.layer.shadowRadius = 10 whiteView.layer.shadowOpacity = 0.06 datePicker = UIDatePicker() datePicker.datePickerMode = .dateAndTime datePicker.addTarget(self, action: #selector(datePickerValueChanged), for: .valueChanged) dateTextField.inputView = datePicker dateTextField.tintColor = .clear dateTextField.addTarget(self, action: #selector(datePickerTextFieldValueChanged), for: .editingChanged) } }
mit
501cde9f627ca789acdd1d0be4113ff1
25.447368
155
0.580952
5.89196
false
false
false
false
nicolaschriste/MoreFoundation
MoreFoundation/Observable/EventStore.swift
1
2453
/// Copyright (c) 2018 Nicolas Christe /// /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to deal /// in the Software without restriction, including without limitation the rights /// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell /// copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included in all /// copies or substantial portions of the Software. /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE /// SOFTWARE. import Foundation public class EventStore<T> { enum Error: Swift.Error { case empty case wrongEventType } public private(set) var latestEvents = [Event<T>]() private let disposeBag = DisposeBag() public init(source: Observable<T>) { source.subscribe { self.latestEvents.append($0) }.disposed(by: disposeBag) } public func clear() { latestEvents = [] } public func pop() throws -> Event<T> { guard !latestEvents.isEmpty else { throw Error.empty } return latestEvents.removeFirst() } public func popValue() throws -> T { guard !latestEvents.isEmpty else { throw Error.empty } guard case let .next(value) = latestEvents.removeFirst() else { throw Error.wrongEventType } return value } public func popTerminated() throws { guard !latestEvents.isEmpty else { throw Error.empty } guard case .terminated = latestEvents.removeFirst() else { throw Error.wrongEventType } } public func peek() -> Event<T>? { return latestEvents.first } } public extension Observable { func subscribeStore() -> EventStore<T> { return EventStore(source: self) } }
mit
4738e5b508eea90d79d4d56583bceb20
31.276316
82
0.664492
4.699234
false
true
false
false
knorrium/OnTheMap
OnTheMap/ViewController.swift
1
6017
// // ViewController.swift // OnTheMap // // Created by Felipe Kuhn on 12/19/15. // Copyright © 2015 Knorrium. All rights reserved. // import UIKit import FBSDKCoreKit import FBSDKLoginKit class ViewController: UIViewController, FBSDKLoginButtonDelegate { var udacityLogin: UdacityLogin? var fbLoginManager : FBSDKLoginManager = FBSDKLoginManager() let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate @IBOutlet weak var txtLogin: UITextField! @IBOutlet weak var txtPassword: UITextField! @IBOutlet weak var loginButton: UIButton! @IBAction func loginButtonAction(sender: UIButton) { if ((txtLogin.text!.isEmpty || txtPassword.text!.isEmpty)) { let alertController = UIAlertController(title: "On The Map", message: "Please fill both the username and password fields.", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) return } else { UdacityLogin.sharedInstance.login(txtLogin.text!, password: txtPassword.text!) { (success, errorMessage) in if success { self.showMapViewController() } else { let alertController = UIAlertController(title: "On The Map", message: "\(errorMessage!)", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil)) dispatch_async(dispatch_get_main_queue(), { self.presentViewController(alertController, animated: true, completion: nil) }) } } } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "mainView" { if let destinationVC = segue.destinationViewController as? MainTabViewController{ } } } @IBOutlet weak var signupLink: UIButton! @IBAction func signupLinkAction(sender: UIButton) { let url : NSURL url = NSURL(string: "https://www.udacity.com/account/auth#!/signin")! UIApplication.sharedApplication().openURL(url) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. addGradient() udacityLogin = UdacityLogin.sharedInstance let loginButton = FBSDKLoginButton() loginButton.readPermissions = ["public_profile", "email", "user_friends",] loginButton.delegate = self loginButton.center = self.view.center; loginButton.frame.origin.y = signupLink.frame.origin.y + signupLink.frame.height + 20; self.view.addSubview(loginButton); fbLoginManager.loginBehavior = FBSDKLoginBehavior.SystemAccount let loginManager = FBSDKLoginManager() loginManager.logOut() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func addGradient(){ // Source: http://stackoverflow.com/questions/24380535/how-to-apply-gradient-to-background-view-of-ios-swift-app let gradient:CAGradientLayer = CAGradientLayer() gradient.frame.size = self.view.frame.size gradient.colors = [UIColor.orangeColor().colorWithAlphaComponent(0.5).CGColor,UIColor.orangeColor().CGColor] //Or any colors self.view.layer.insertSublayer(gradient, atIndex: 0) } // Facebook delegate methods func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) { if ((error) != nil) { print(error.description); } else if result.isCancelled { } else { if result.grantedPermissions.contains("email") { getFBUserData() UdacityLogin.sharedInstance.loginWithFacebook(FBSDKAccessToken.currentAccessToken().tokenString) { (success, errorMessage) in if (success) { self.showMapViewController() } else { let alertController = UIAlertController(title: "On The Map", message: "\(errorMessage!)", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil)) dispatch_async(dispatch_get_main_queue(), { self.presentViewController(alertController, animated: true, completion: nil) }) } } } } } func loginButtonDidLogOut(loginButton: FBSDKLoginButton!) { } func showMapViewController() { dispatch_async(dispatch_get_main_queue(), { () -> Void in let viewController:UIViewController = self.storyboard?.instantiateViewControllerWithIdentifier("MainTabView") as! MainTabViewController self.presentViewController(viewController, animated: true, completion: nil) }) } func getFBUserData() { let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: nil) graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in if ((error) != nil) { } else { let userName : NSString = result.valueForKey("name") as! NSString } }) } }
mit
36de6247a35315fcfba735cc2134aaca
37.564103
147
0.615858
5.534499
false
false
false
false
Jubilant-Appstudio/Scuba
Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/Categories/IQUIView+Hierarchy.swift
3
11511
// // IQUIView+Hierarchy.swift // https://github.com/hackiftekhar/IQKeyboardManager // Copyright (c) 2013-16 Iftekhar Qurashi. // // 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 /** UIView hierarchy category. */ public extension UIView { ///---------------------- /// MARK: viewControllers ///---------------------- /** Returns the UIViewController object that manages the receiver. */ public func viewController()->UIViewController? { var nextResponder: UIResponder? = self repeat { nextResponder = nextResponder?.next if let viewController = nextResponder as? UIViewController { return viewController } } while nextResponder != nil return nil } /** Returns the topMost UIViewController object in hierarchy. */ public func topMostController()->UIViewController? { var controllersHierarchy = [UIViewController]() if var topController = window?.rootViewController { controllersHierarchy.append(topController) while topController.presentedViewController != nil { topController = topController.presentedViewController! controllersHierarchy.append(topController) } var matchController :UIResponder? = viewController() while matchController != nil && controllersHierarchy.contains(matchController as! UIViewController) == false { repeat { matchController = matchController?.next } while matchController != nil && matchController is UIViewController == false } return matchController as? UIViewController } else { return viewController() } } ///----------------------------------- /// MARK: Superviews/Subviews/Siglings ///----------------------------------- /** Returns the superView of provided class type. */ public func superviewOfClassType(_ classType:UIView.Type)->UIView? { var superView = superview while let unwrappedSuperView = superView { if unwrappedSuperView.isKind(of: classType) { //If it's UIScrollView, then validating for special cases if unwrappedSuperView.isKind(of: UIScrollView.self) { let classNameString = NSStringFromClass(type(of:unwrappedSuperView.self)) // If it's not UITableViewWrapperView class, this is internal class which is actually manage in UITableview. The speciality of this class is that it's superview is UITableView. // If it's not UITableViewCellScrollView class, this is internal class which is actually manage in UITableviewCell. The speciality of this class is that it's superview is UITableViewCell. //If it's not _UIQueuingScrollView class, actually we validate for _ prefix which usually used by Apple internal classes if unwrappedSuperView.superview?.isKind(of: UITableView.self) == false && unwrappedSuperView.superview?.isKind(of: UITableViewCell.self) == false && classNameString.hasPrefix("_") == false { return superView } } else { return superView } } superView = unwrappedSuperView.superview } return nil } /** Returns all siblings of the receiver which canBecomeFirstResponder. */ public func responderSiblings()->[UIView] { //Array of (UITextField/UITextView's). var tempTextFields = [UIView]() // Getting all siblings if let siblings = superview?.subviews { for textField in siblings { if (textField == self || textField.ignoreSwitchingByNextPrevious == false) && textField._IQcanBecomeFirstResponder() == true { tempTextFields.append(textField) } } } return tempTextFields } /** Returns all deep subViews of the receiver which canBecomeFirstResponder. */ public func deepResponderViews()->[UIView] { //Array of (UITextField/UITextView's). var textfields = [UIView]() for textField in subviews { if (textField == self || textField.ignoreSwitchingByNextPrevious == false) && textField._IQcanBecomeFirstResponder() == true { textfields.append(textField) } //Sometimes there are hidden or disabled views and textField inside them still recorded, so we added some more validations here (Bug ID: #458) //Uncommented else (Bug ID: #625) if textField.subviews.count != 0 && isUserInteractionEnabled == true && isHidden == false && alpha != 0.0 { for deepView in textField.deepResponderViews() { textfields.append(deepView) } } } //subviews are returning in opposite order. Sorting according the frames 'y'. return textfields.sorted(by: { (view1 : UIView, view2 : UIView) -> Bool in let frame1 = view1.convert(view1.bounds, to: self) let frame2 = view2.convert(view2.bounds, to: self) let x1 = frame1.minX let y1 = frame1.minY let x2 = frame2.minX let y2 = frame2.minY if y1 != y2 { return y1 < y2 } else { return x1 < x2 } }) } fileprivate func _IQcanBecomeFirstResponder() -> Bool { var _IQcanBecomeFirstResponder = false // Setting toolbar to keyboard. if let textField = self as? UITextField { _IQcanBecomeFirstResponder = textField.isEnabled } else if let textView = self as? UITextView { _IQcanBecomeFirstResponder = textView.isEditable } if _IQcanBecomeFirstResponder == true { _IQcanBecomeFirstResponder = (isUserInteractionEnabled == true && isHidden == false && alpha != 0.0 && isAlertViewTextField() == false && isSearchBarTextField() == false) as Bool } return _IQcanBecomeFirstResponder } ///------------------------- /// MARK: Special TextFields ///------------------------- /** Returns YES if the receiver object is UISearchBarTextField, otherwise return NO. */ public func isSearchBarTextField()-> Bool { var searchBar : UIResponder? = self.next var isSearchBarTextField = false while searchBar != nil && isSearchBarTextField == false { if searchBar!.isKind(of: UISearchBar.self) { isSearchBarTextField = true break } else if searchBar is UIViewController { break } searchBar = searchBar?.next } return isSearchBarTextField } /** Returns YES if the receiver object is UIAlertSheetTextField, otherwise return NO. */ public func isAlertViewTextField()->Bool { var alertViewController : UIResponder? = self.viewController() var isAlertViewTextField = false while alertViewController != nil && isAlertViewTextField == false { if alertViewController!.isKind(of: UIAlertController.self) { isAlertViewTextField = true break } alertViewController = alertViewController?.next } return isAlertViewTextField } ///---------------- /// MARK: Transform ///---------------- /** Returns current view transform with respect to the 'toView'. */ public func convertTransformToView(_ toView:UIView?)->CGAffineTransform { var newView = toView if newView == nil { newView = window } //My Transform var myTransform = CGAffineTransform.identity if let superView = superview { myTransform = transform.concatenating(superView.convertTransformToView(nil)) } else { myTransform = transform } var viewTransform = CGAffineTransform.identity //view Transform if let unwrappedToView = newView { if let unwrappedSuperView = unwrappedToView.superview { viewTransform = unwrappedToView.transform.concatenating(unwrappedSuperView.convertTransformToView(nil)) } else { viewTransform = unwrappedToView.transform } } //Concating MyTransform and ViewTransform return myTransform.concatenating(viewTransform.inverted()) } ///----------------- /// TODO: Hierarchy ///----------------- // /** // Returns a string that represent the information about it's subview's hierarchy. You can use this method to debug the subview's positions. // */ // func subHierarchy()->NSString { // // } // // /** // Returns an string that represent the information about it's upper hierarchy. You can use this method to debug the superview's positions. // */ // func superHierarchy()->NSString { // // } // // /** // Returns an string that represent the information about it's frame positions. You can use this method to debug self positions. // */ // func debugHierarchy()->NSString { // // } fileprivate func depth()->Int { var depth : Int = 0 if let superView = superview { depth = superView.depth()+1 } return depth } } extension NSObject { public func _IQDescription() -> String { return "<\(self) \(Unmanaged.passUnretained(self).toOpaque())>" } }
mit
0610595a908e95f59226133c1d5aed8d
31.888571
208
0.569282
5.933505
false
false
false
false
vmanot/swift-package-manager
Sources/SourceControl/Repository.swift
1
8615
/* 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 http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import Basic /// Specifies a repository address. public struct RepositorySpecifier { /// The URL of the repository. public let url: String /// Create a specifier. public init(url: String) { self.url = url } /// A unique identifier for this specifier. /// /// This identifier is suitable for use in a file system path, and /// unique for each repository. public var fileSystemIdentifier: String { // FIXME: Need to do something better here. In particular, we should use // a stable hash function since this interacts with the RepositoryManager // persistence. let basename = url.components(separatedBy: "/").last! return basename + "-" + String(url.hashValue) } } extension RepositorySpecifier: Hashable { public var hashValue: Int { return url.hashValue } public static func == (lhs: RepositorySpecifier, rhs: RepositorySpecifier) -> Bool { return lhs.url == rhs.url } } extension RepositorySpecifier: CustomStringConvertible { public var description: String { return url } } extension RepositorySpecifier: JSONMappable, JSONSerializable { public init(json: JSON) throws { guard case .string(let url) = json else { throw JSON.MapError.custom(key: nil, message: "expected string, got \(json)") } self.url = url } public func toJSON() -> JSON { return .string(url) } } /// A repository provider. /// /// This protocol defines the lower level interface used to to access /// repositories. High-level clients should access repositories via a /// `RepositoryManager`. public protocol RepositoryProvider { /// Fetch the complete repository at the given location to `path`. /// /// - Throws: If there is an error fetching the repository. func fetch(repository: RepositorySpecifier, to path: AbsolutePath) throws /// Open the given repository. /// /// - Parameters: /// - repository: The specifier for the repository. /// - path: The location of the repository on disk, at which the /// repository has previously been created via `fetch`. /// - Throws: If the repository is unable to be opened. func open(repository: RepositorySpecifier, at path: AbsolutePath) throws -> Repository /// Clone a managed repository into a working copy at on the local file system. /// /// Once complete, the repository can be opened using `openCheckout`. /// /// - Parameters: /// - sourcePath: The location of the repository on disk, at which the /// repository has previously been created via `fetch`. /// - destinationPath: The path at which to create the working copy; it is /// expected to be non-existent when called. /// - editable: The checkout is expected to be edited by users. func cloneCheckout( repository: RepositorySpecifier, at sourcePath: AbsolutePath, to destinationPath: AbsolutePath, editable: Bool) throws /// Open a working repository copy. /// /// - Parameters: /// - path: The location of the repository on disk, at which the /// repository has previously been created via `cloneCheckout`. func openCheckout(at path: AbsolutePath) throws -> WorkingCheckout } /// Abstract repository operations. /// /// This interface provides access to an abstracted representation of a /// repository which is ultimately owned by a `RepositoryManager`. This interface /// is designed in such a way as to provide the minimal facilities required by /// the package manager to gather basic information about a repository, but it /// does not aim to provide all of the interfaces one might want for working /// with an editable checkout of a repository on disk. /// /// The goal of this design is to allow the `RepositoryManager` a large degree of /// flexibility in the storage and maintenance of its underlying repositories. /// /// This protocol is designed under the assumption that the repository can only /// be mutated via the functions provided here; thus, e.g., `tags` is expected /// to be unchanged through the lifetime of an instance except as otherwise /// documented. The behavior when this assumption is violated is undefined, /// although the expectation is that implementations should throw or crash when /// an inconsistency can be detected. public protocol Repository { /// Get the list of tags in the repository. var tags: [String] { get } /// Resolve the revision for a specific tag. /// /// - Precondition: The `tag` should be a member of `tags`. /// - Throws: If a error occurs accessing the named tag. func resolveRevision(tag: String) throws -> Revision /// Resolve the revision for an identifier. /// /// The identifier can be a branch name or a revision identifier. /// /// - Throws: If the identifier can not be resolved. func resolveRevision(identifier: String) throws -> Revision /// Fetch and update the repository from its remote. /// /// - Throws: If an error occurs while performing the fetch operation. func fetch() throws /// Returns true if the given revision exists. func exists(revision: Revision) -> Bool /// Open an immutable file system view for a particular revision. /// /// This view exposes the contents of the repository at the given revision /// as a file system rooted inside the repository. The repository must /// support opening multiple views concurrently, but the expectation is that /// clients should be prepared for this to be inefficient when performing /// interleaved accesses across separate views (i.e., the repository may /// back the view by an actual file system representation of the /// repository). /// /// It is expected behavior that attempts to mutate the given FileSystem /// will fail or crash. /// /// - Throws: If a error occurs accessing the revision. func openFileView(revision: Revision) throws -> FileSystem } /// An editable checkout of a repository (i.e. a working copy) on the local file /// system. public protocol WorkingCheckout { /// Get the list of tags in the repository. var tags: [String] { get } /// Get the current revision. func getCurrentRevision() throws -> Revision /// Fetch and update the repository from its remote. /// /// - Throws: If an error occurs while performing the fetch operation. func fetch() throws /// Query whether the checkout has any commits which are not pushed to its remote. func hasUnpushedCommits() throws -> Bool /// This check for any modified state of the repository and returns true /// if there are uncommited changes. func hasUncommitedChanges() -> Bool /// Check out the given tag. func checkout(tag: String) throws /// Check out the given revision. func checkout(revision: Revision) throws /// Returns true if the given revision exists. func exists(revision: Revision) -> Bool /// Create a new branch and checkout HEAD to it. /// /// Note: It is an error to provide a branch name which already exists. func checkout(newBranch: String) throws } /// A single repository revision. public struct Revision: Hashable { /// A precise identifier for a single repository revision, in a repository-specified manner. /// /// This string is intended to be opaque to the client, but understandable /// by a user. For example, a Git repository might supply the SHA1 of a /// commit, or an SVN repository might supply a string such as 'r123'. public let identifier: String public init(identifier: String) { self.identifier = identifier } public var hashValue: Int { return identifier.hashValue } public static func == (lhs: Revision, rhs: Revision) -> Bool { return lhs.identifier == rhs.identifier } } extension Revision: JSONMappable { public init(json: JSON) throws { guard case .string(let identifier) = json else { throw JSON.MapError.custom(key: nil, message: "expected string, got \(json)") } self.init(identifier: identifier) } }
apache-2.0
03888a473030f6a84545a0e583837fdf
35.816239
96
0.682879
4.802118
false
false
false
false
zvonler/PasswordElephant
external/github.com/apple/swift-protobuf/Sources/protoc-gen-swift/FileIo.swift
7
2184
// Sources/protoc-gen-swift/FileIo.swift - File I/O utilities // // Copyright (c) 2014 - 2016 Apple Inc. and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information: // https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt // // ----------------------------------------------------------------------------- /// /// Some basic utilities to handle writing to Stderr, Stdout, and reading/writing /// blocks of data from/to a file on disk. /// // ----------------------------------------------------------------------------- import Foundation #if os(Linux) import Glibc #else import Darwin.C #endif // Alias clib's write() so Stdout.write(bytes:) can call it. private let _write = write private func printToFd(_ s: String, fd: Int32, appendNewLine: Bool = true) { // Write UTF-8 bytes let bytes: [UInt8] = [UInt8](s.utf8) bytes.withUnsafeBufferPointer { (bp: UnsafeBufferPointer<UInt8>) -> () in write(fd, bp.baseAddress, bp.count) } if appendNewLine { // Write trailing newline [UInt8(10)].withUnsafeBufferPointer { (bp: UnsafeBufferPointer<UInt8>) -> () in write(fd, bp.baseAddress, bp.count) } } } class Stderr { static func print(_ s: String) { let out = "\(CommandLine.programName): " + s printToFd(out, fd: 2) } } class Stdout { static func print(_ s: String) { printToFd(s, fd: 1) } static func write(bytes: Data) { bytes.withUnsafeBytes { (p: UnsafePointer<UInt8>) -> () in _ = _write(1, p, bytes.count) } } } class Stdin { static func readall() -> Data? { let fd: Int32 = 0 let buffSize = 1024 var buff = [UInt8]() var fragment = [UInt8](repeating: 0, count: buffSize) while true { let count = read(fd, &fragment, buffSize) if count < 0 { return nil } if count < buffSize { if count > 0 { buff += fragment[0..<count] } return Data(bytes: buff) } buff += fragment } } } func readFileData(filename: String) throws -> Data { let url = URL(fileURLWithPath: filename) return try Data(contentsOf: url) }
gpl-3.0
05d63f10e91b2abb3ac10e816a641bb3
25.634146
83
0.586996
3.765517
false
false
false
false
peferron/algo
EPI/Searching/Find the kth largest element/swift/main.swift
1
1311
// swiftlint:disable variable_name import Darwin public func largestInPlace<T: Comparable>(array: inout [T], k: Int) -> T { var low = 0 var high = array.count - 1 while true { let pivotIndex = random(from: low, through: high) let newPivotIndex = partition(&array, low: low, high: high, pivotIndex: pivotIndex) if newPivotIndex < k { low = newPivotIndex + 1 } else if newPivotIndex > k { high = newPivotIndex - 1 } else { return array[newPivotIndex] } } } func random(from: Int, through: Int) -> Int { return from + Int(arc4random_uniform(UInt32(through - from) + 1)) } func partition<T: Comparable>(_ array: inout [T], low: Int, high: Int, pivotIndex: Int) -> Int { let pivot = array[pivotIndex] swap(&array, pivotIndex, low) var newPivotIndex = low for i in low...high { // Move array[i] to the correct side of the pivot (left if larger, right if smaller). if array[i] > pivot { swap(&array, newPivotIndex + 1, i) swap(&array, newPivotIndex, newPivotIndex + 1) newPivotIndex += 1 } } return newPivotIndex } func swap<T>(_ array: inout [T], _ i: Int, _ j: Int) { (array[i], array[j]) = (array[j], array[i]) }
mit
2bfcff058e3e7992bbe499da1478895c
26.893617
96
0.582761
3.745714
false
false
false
false
ilyahal/VKMusic
VkPlaylist/FriendsTableViewController.swift
1
28517
// // FriendsTableViewController.swift // VkPlaylist // // MIT License // // Copyright (c) 2016 Ilya Khalyapin // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit /// Контроллер содержит таблицу со списком друзей class FriendsTableViewController: UITableViewController { /// Выполняется ли обновление var isRefreshing: Bool { if let refreshControl = refreshControl where refreshControl.refreshing { return true } else { return false } } /// Статус выполнения запроса к серверу var requestManagerStatus: RequestManagerObject.State { return RequestManager.sharedInstance.getFriends.state } /// Ошибки при выполнении запроса к серверу var requestManagerError: RequestManagerObject.ErrorRequest { return RequestManager.sharedInstance.getFriends.error } /// Кэш аватарок друзей private var imageCache = NSCache() /// Словарь с именами [Первая буква фамилии : Массив друзей, у которых фамилия начинается на ту же букву] private var names = [String: [Friend]]() /// Массив содержащий заголовки секций таблицы (первые буквы фамилий) private var nameSectionTitles = [String]() /// Массив друзей, загруженных с сервера private var friends = [Friend]() /// Массив друзей, полученный в результате поиска private var filteredFriends = [Friend]() /// Массив друзей, отображаемый на экране var activeArray: [Friend] { if isSearched { return filteredFriends } else { return friends } } /// Поисковый контроллер let searchController = UISearchController(searchResultsController: nil) /// Выполняется ли сейчас поиск var isSearched: Bool { return searchController.active && !searchController.searchBar.text!.isEmpty } override func viewDidLoad() { super.viewDidLoad() if VKAPIManager.isAuthorized { getFriends() } // Настройка Pull-To-Refresh pullToRefreshEnable(VKAPIManager.isAuthorized) // Настройка поисковой панели searchController.searchResultsUpdater = self searchController.searchBar.delegate = self searchController.dimsBackgroundDuringPresentation = false searchController.hidesNavigationBarDuringPresentation = false searchController.searchBar.searchBarStyle = .Prominent searchController.searchBar.placeholder = "Поиск" definesPresentationContext = true searchEnable(VKAPIManager.isAuthorized) // Кастомизация tableView tableView.tableFooterView = UIView() // Чистим пустое пространство под таблицей // Регистрация ячеек var cellNib = UINib(nibName: TableViewCellIdentifiers.noAuthorizedCell, bundle: nil) // Ячейка "Необходимо авторизоваться" tableView.registerNib(cellNib, forCellReuseIdentifier: TableViewCellIdentifiers.noAuthorizedCell) cellNib = UINib(nibName: TableViewCellIdentifiers.networkErrorCell, bundle: nil) // Ячейка "Ошибка при подключении к интернету" tableView.registerNib(cellNib, forCellReuseIdentifier: TableViewCellIdentifiers.networkErrorCell) cellNib = UINib(nibName: TableViewCellIdentifiers.nothingFoundCell, bundle: nil) // Ячейка "Ничего не найдено" tableView.registerNib(cellNib, forCellReuseIdentifier: TableViewCellIdentifiers.nothingFoundCell) cellNib = UINib(nibName: TableViewCellIdentifiers.loadingCell, bundle: nil) // Ячейка "Загрузка" tableView.registerNib(cellNib, forCellReuseIdentifier: TableViewCellIdentifiers.loadingCell) cellNib = UINib(nibName: TableViewCellIdentifiers.numberOfRowsCell, bundle: nil) // Ячейка с количеством друзей tableView.registerNib(cellNib, forCellReuseIdentifier: TableViewCellIdentifiers.numberOfRowsCell) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if let _ = tableView.tableHeaderView { if tableView.contentOffset.y == 0 { tableView.hideSearchBar() } } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == SegueIdentifiers.showFriendAudioViewControllerSegue { let ownerMusicViewController = segue.destinationViewController as! OwnerMusicViewController let friend = sender as! Friend ownerMusicViewController.id = friend.id ownerMusicViewController.name = friend.getFullName() } } deinit { if let superView = searchController.view.superview { superView.removeFromSuperview() } } /// Заново отрисовать таблицу func reloadTableView() { dispatch_async(dispatch_get_main_queue()) { self.tableView.reloadData() } } // MARK: Pull-to-Refresh /// Управление доступностью Pull-to-Refresh func pullToRefreshEnable(enable: Bool) { if enable { if refreshControl == nil { refreshControl = UIRefreshControl() //refreshControl!.attributedTitle = NSAttributedString(string: "Потяните, чтобы обновить...") // Все крашится :с refreshControl!.addTarget(self, action: #selector(getFriends), forControlEvents: .ValueChanged) // Добавляем обработчик контроллера обновления } } else { if let refreshControl = refreshControl { if refreshControl.refreshing { refreshControl.endRefreshing() } refreshControl.removeTarget(self, action: #selector(getFriends), forControlEvents: .ValueChanged) // Удаляем обработчик контроллера обновления } refreshControl = nil } } // MARK: Работа с клавиатурой /// Распознаватель тапов по экрану lazy var tapRecognizer: UITapGestureRecognizer = { var recognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard)) return recognizer }() /// Спрятать клавиатуру у поисковой строки func dismissKeyboard() { searchController.searchBar.resignFirstResponder() if searchController.active && searchController.searchBar.text!.isEmpty { searchController.active = false } } // MARK: Выполнение запроса на получение списка друзей /// Запрос на получение списка друзей с сервера func getFriends() { RequestManager.sharedInstance.getFriends.performRequest() { success in self.friends = DataManager.sharedInstance.friends.array self.names = [:] self.nameSectionTitles = [] // Распределяем по секциям if self.requestManagerStatus == .Results { for friend in self.friends { // Устанавливаем по какому значению будем сортировать let name = friend.last_name var firstCharacter = String(name.characters.first!) let characterSet = NSCharacterSet(charactersInString: "абвгдеёжзийклмнопрстуфхцчшщъыьэюя" + "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ" + "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ") if (NSString(string: firstCharacter).rangeOfCharacterFromSet(characterSet.invertedSet).location != NSNotFound){ firstCharacter = "#" } if self.names[String(firstCharacter)] == nil { self.names[String(firstCharacter)] = [] } self.names[String(firstCharacter)]!.append(friend) } self.nameSectionTitles = self.names.keys.sort { (left: String, right: String) -> Bool in return left.localizedStandardCompare(right) == .OrderedAscending // Сортировка по возрастанию } if self.nameSectionTitles.first == "#" { self.nameSectionTitles.removeFirst() self.nameSectionTitles.append("#") } // Сортируем имена в каждой секции for (key, section) in self.names { self.names[key] = section.sort { (left: Friend, right: Friend) -> Bool in let leftFullName = left.last_name + " " + left.first_name let rightFullName = right.last_name + " " + right.first_name return leftFullName.localizedStandardCompare(rightFullName) == .OrderedAscending // Сортировка по возрастанию } } } self.reloadTableView() if self.isRefreshing { // Если данные обновляются self.refreshControl!.endRefreshing() // Говорим что обновление завершено } if !success { switch self.requestManagerError { case .UnknownError: let alertController = UIAlertController(title: "Ошибка", message: "Произошла какая-то ошибка, попробуйте еще раз...", preferredStyle: .Alert) let okAction = UIAlertAction(title: "ОК", style: .Default, handler: nil) alertController.addAction(okAction) dispatch_async(dispatch_get_main_queue()) { self.presentViewController(alertController, animated: false, completion: nil) } default: break } } } } // MARK: Поиск /// Управление доступностью поиска func searchEnable(enable: Bool) { if enable { if tableView.tableHeaderView == nil { searchController.searchBar.alpha = 1 tableView.tableHeaderView = searchController.searchBar tableView.hideSearchBar() } } else { if let _ = tableView.tableHeaderView { searchController.searchBar.alpha = 0 searchController.active = false tableView.tableHeaderView = nil tableView.contentOffset = CGPointZero } } } /// Выполнение поискового запроса func filterContentForSearchText(searchText: String) { filteredFriends = friends.filter { friend in return friend.first_name.lowercaseString.containsString(searchText.lowercaseString) || friend.last_name.lowercaseString.containsString(searchText.lowercaseString) } } // MARK: Получение ячеек для строк таблицы helpers /// Текст для ячейки с сообщением о том, что сервер вернул пустой массив var noResultsLabelText: String { return "Список друзей пуст" } /// Текст для ячейки с сообщением о том, что при поиске ничего не найдено var nothingFoundLabelText: String { return "Измените поисковый запрос" } // Получение количества друзей в списке для ячейки с количеством друзей func numberOfFriendsForIndexPath(indexPath: NSIndexPath) -> Int? { let sectionTitle = nameSectionTitles[indexPath.section] let sectionNames = names[sectionTitle] let count: Int? if isSearched && filteredFriends.count == indexPath.row { count = filteredFriends.count } else if !isSearched && sectionNames!.count == indexPath.row { count = friends.count } else { count = nil } return count } /// Текст для ячейки с сообщением о необходимости авторизоваться var noAuthorizedLabelText: String { return "Необходимо авторизоваться" } // MARK: Получение ячеек для строк таблицы // Ячейка для строки когда поиск еще не выполнялся и была получена ошибка при подключении к интернету func getCellForNotSearchedYetRowWithInternetErrorForIndexPath(indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(TableViewCellIdentifiers.networkErrorCell, forIndexPath: indexPath) as! NetworkErrorCell return cell } // Ячейка для строки когда поиск еще не выполнялся func getCellForNotSearchedYetRowForIndexPath(indexPath: NSIndexPath) -> UITableViewCell { return UITableViewCell() } // Ячейка для строки с сообщением что сервер вернул пустой массив func getCellForNoResultsRowForIndexPath(indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(TableViewCellIdentifiers.nothingFoundCell, forIndexPath: indexPath) as! NothingFoundCell cell.messageLabel.text = noResultsLabelText return cell } // Ячейка для строки с сообщением, что при поиске ничего не было найдено func getCellForNothingFoundRowForIndexPath(indexPath: NSIndexPath) -> UITableViewCell { let nothingFoundCell = tableView.dequeueReusableCellWithIdentifier(TableViewCellIdentifiers.nothingFoundCell, forIndexPath: indexPath) as! NothingFoundCell nothingFoundCell.messageLabel.text = nothingFoundLabelText return nothingFoundCell } // Ячейка для строки с сообщением о загрузке func getCellForLoadingRowForIndexPath(indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(TableViewCellIdentifiers.loadingCell, forIndexPath: indexPath) as! LoadingCell cell.activityIndicator.startAnimating() return cell } // Пытаемся получить ячейку для строки с количеством друзей func getCellForNumberOfFriendsRowForIndexPath(indexPath: NSIndexPath) -> UITableViewCell? { let count = numberOfFriendsForIndexPath(indexPath) if let count = count { let numberOfRowsCell = tableView.dequeueReusableCellWithIdentifier(TableViewCellIdentifiers.numberOfRowsCell) as! NumberOfRowsCell numberOfRowsCell.configureForType(.Friend, withCount: count) return numberOfRowsCell } return nil } // Ячейка для строки с другом func getCellForRowWithGroupForIndexPath(indexPath: NSIndexPath) -> UITableViewCell { let sectionTitle = nameSectionTitles[indexPath.section] let sectionNames = names[sectionTitle] let friend = isSearched ? filteredFriends[indexPath.row] : sectionNames![indexPath.row] let cell = tableView.dequeueReusableCellWithIdentifier(TableViewCellIdentifiers.friendCell, forIndexPath: indexPath) as! FriendCell cell.configureForFriend(friend, withImageCacheStorage: imageCache) return cell } // Ячейка для строки с сообщением о необходимости авторизоваться func getCellForNoAuthorizedRowForIndexPath(indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(TableViewCellIdentifiers.noAuthorizedCell, forIndexPath: indexPath) as! NoAuthorizedCell cell.messageLabel.text = noAuthorizedLabelText return cell } } // MARK: UITableViewDataSource private typealias _FriendsTableViewControllerDataSource = FriendsTableViewController extension _FriendsTableViewControllerDataSource { // Получение количество секций override func numberOfSectionsInTableView(tableView: UITableView) -> Int { if VKAPIManager.isAuthorized { switch requestManagerStatus { case .Loading where isRefreshing: return nameSectionTitles.count case .Results: return isSearched ? 1 : nameSectionTitles.count default: return 1 } } return 1 } // Получение заголовков секций override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if VKAPIManager.isAuthorized { switch requestManagerStatus { case .Loading where isRefreshing: return nameSectionTitles[section] case .Results: return isSearched ? nil : nameSectionTitles[section] default: return nil } } return nil } // Получение количества строк таблицы в указанной секции override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if VKAPIManager.isAuthorized { switch requestManagerStatus { case .NotSearchedYet where requestManagerError == .NetworkError: return 1 // Ячейка с сообщением об отсутствии интернет соединения case .Loading where isRefreshing: let sectionTitle = nameSectionTitles[section] let sectionNames = names[sectionTitle] var count = sectionNames!.count if nameSectionTitles.count - 1 == section { count += 1 // Для ячейки с количеством друзей в последней секции } return count case .Loading: return 1 // Ячейка с индикатором загрузки case .NoResults: return 1 // Ячейки с сообщением об отсутствии друзей case .Results: if isSearched { return filteredFriends.count == 0 ? 1 : filteredFriends.count + 1 // Если массив пустой - ячейка с сообщением об отсутствии результатов поиска, иначе - количество найденных друзей } else { let sectionTitle = nameSectionTitles[section] let sectionNames = names[sectionTitle] var count = sectionNames!.count if nameSectionTitles.count - 1 == section { count += 1 // Для ячейки с количеством друзей в последней секции } return count } default: return 0 } } return 1 // Ячейка с сообщением о необходимости авторизоваться } // Получение ячейки для строки таблицы override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if VKAPIManager.isAuthorized { switch requestManagerStatus { case .NotSearchedYet where requestManagerError == .NetworkError: return getCellForNotSearchedYetRowWithInternetErrorForIndexPath(indexPath) case .NotSearchedYet: return getCellForNotSearchedYetRowForIndexPath(indexPath) case .NoResults: return getCellForNoResultsRowForIndexPath(indexPath) case .Loading where isRefreshing: if let numberOfRowsCell = getCellForNumberOfFriendsRowForIndexPath(indexPath) { return numberOfRowsCell } return getCellForRowWithGroupForIndexPath(indexPath) case .Loading: return getCellForLoadingRowForIndexPath(indexPath) case .Results: if searchController.active && searchController.searchBar.text != "" && filteredFriends.count == 0 { return getCellForNothingFoundRowForIndexPath(indexPath) } if let numberOfRowsCell = getCellForNumberOfFriendsRowForIndexPath(indexPath) { return numberOfRowsCell } return getCellForRowWithGroupForIndexPath(indexPath) } } return getCellForNoAuthorizedRowForIndexPath(indexPath) } // Получение массива индексов секций таблицы override func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? { if VKAPIManager.isAuthorized { switch requestManagerStatus { case .Loading where isRefreshing: return nameSectionTitles case .Results: return isSearched ? nil : nameSectionTitles default: return nil } } return nil } } // MARK: UITableViewDelegate private typealias _FriendsTableViewControllerDelegate = FriendsTableViewController extension _FriendsTableViewControllerDelegate { // Высота каждой строки override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if VKAPIManager.isAuthorized { if requestManagerStatus == .Results || requestManagerStatus == .Loading && isRefreshing { let sectionTitle = nameSectionTitles[indexPath.section] let sectionNames = names[sectionTitle] let count: Int? if searchController.active && searchController.searchBar.text != "" && filteredFriends.count == indexPath.row && filteredFriends.count != 0 { count = filteredFriends.count } else if sectionNames!.count == indexPath.row { count = sectionNames!.count } else { count = nil } if let _ = count { return 44 } } } return 62 } // Вызывается при тапе по строке таблицы override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) if tableView.cellForRowAtIndexPath(indexPath) is FriendCell { var friend: Friend if isSearched { friend = filteredFriends[indexPath.row] } else { let sectionTitle = nameSectionTitles[indexPath.section] let sectionNames = names[sectionTitle] friend = sectionNames![indexPath.row] } performSegueWithIdentifier(SegueIdentifiers.showFriendAudioViewControllerSegue, sender: friend) } } } // MARK: UISearchBarDelegate extension FriendsTableViewController: UISearchBarDelegate { // Пользователь хочет начать поиск func searchBarShouldBeginEditing(searchBar: UISearchBar) -> Bool { if VKAPIManager.isAuthorized { switch requestManagerStatus { case .Results: if let refreshControl = refreshControl { return !refreshControl.refreshing } return friends.count != 0 default: return false } } else { return false } } // Пользователь начал редактирование поискового текста func searchBarTextDidBeginEditing(searchBar: UISearchBar) { view.addGestureRecognizer(tapRecognizer) pullToRefreshEnable(false) } // Пользователь закончил редактирование поискового текста func searchBarTextDidEndEditing(searchBar: UISearchBar) { view.removeGestureRecognizer(tapRecognizer) pullToRefreshEnable(true) } // В поисковой панели была нажата кнопка "Отмена" func searchBarCancelButtonClicked(searchBar: UISearchBar) { filteredFriends.removeAll() } } // MARK: UISearchResultsUpdating extension FriendsTableViewController: UISearchResultsUpdating { // Поле поиска получило фокус или значение поискового запроса изменилось func updateSearchResultsForSearchController(searchController: UISearchController) { filterContentForSearchText(searchController.searchBar.text!) reloadTableView() } }
mit
dc259c3f60769b3b8f310f163a1efe36
38.092846
210
0.623214
5.679567
false
false
false
false
mozilla-mobile/firefox-ios
Client/Frontend/Widgets/PhotonActionSheet/PhotonActionSheetProtocol.swift
2
4956
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0 import Foundation import Shared import Storage import UIKit protocol PhotonActionSheetProtocol { var tabManager: TabManager { get } var profile: Profile { get } } extension PhotonActionSheetProtocol { typealias PresentableVC = UIViewController & UIPopoverPresentationControllerDelegate typealias MenuActionsDelegate = QRCodeViewControllerDelegate & SettingsDelegate & PresentingModalViewControllerDelegate & UIViewController func presentSheetWith(viewModel: PhotonActionSheetViewModel, on viewController: PresentableVC, from view: UIView) { let sheet = PhotonActionSheet(viewModel: viewModel) sheet.modalPresentationStyle = viewModel.modalStyle sheet.photonTransitionDelegate = PhotonActionSheetAnimator() if let popoverVC = sheet.popoverPresentationController, sheet.modalPresentationStyle == .popover { popoverVC.delegate = viewController popoverVC.sourceView = view popoverVC.sourceRect = view.bounds let trait = viewController.traitCollection if viewModel.isMainMenu { let margins = viewModel.getMainMenuPopOverMargins(trait: trait, view: view, presentedOn: viewController) popoverVC.popoverLayoutMargins = margins } popoverVC.permittedArrowDirections = viewModel.getPossibleArrowDirections(trait: trait) } viewController.present(sheet, animated: true, completion: nil) } func getLongPressLocationBarActions(with urlBar: URLBarView, webViewContainer: UIView) -> [PhotonRowActions] { let pasteGoAction = SingleActionViewModel(title: .PasteAndGoTitle, iconString: ImageIdentifiers.pasteAndGo) { _ in if let pasteboardContents = UIPasteboard.general.string { urlBar.delegate?.urlBar(urlBar, didSubmitText: pasteboardContents) } }.items let pasteAction = SingleActionViewModel(title: .PasteTitle, iconString: ImageIdentifiers.paste) { _ in if let pasteboardContents = UIPasteboard.general.string { urlBar.enterOverlayMode(pasteboardContents, pasted: true, search: true) } }.items let copyAddressAction = SingleActionViewModel(title: .CopyAddressTitle, iconString: ImageIdentifiers.copyLink) { _ in if let url = tabManager.selectedTab?.canonicalURL?.displayURL ?? urlBar.currentURL { UIPasteboard.general.url = url SimpleToast().showAlertWithText(.AppMenu.AppMenuCopyURLConfirmMessage, bottomContainer: webViewContainer) } }.items if UIPasteboard.general.string != nil { return [pasteGoAction, pasteAction, copyAddressAction] } else { return [copyAddressAction] } } func getRefreshLongPressMenu(for tab: Tab) -> [PhotonRowActions] { guard tab.webView?.url != nil && (tab.getContentScript(name: ReaderMode.name()) as? ReaderMode)?.state != .active else { return [] } let defaultUAisDesktop = UserAgent.isDesktop(ua: UserAgent.getUserAgent()) let toggleActionTitle: String if defaultUAisDesktop { toggleActionTitle = tab.changedUserAgent ? .AppMenu.AppMenuViewDesktopSiteTitleString : .AppMenu.AppMenuViewMobileSiteTitleString } else { toggleActionTitle = tab.changedUserAgent ? .AppMenu.AppMenuViewMobileSiteTitleString : .AppMenu.AppMenuViewDesktopSiteTitleString } let toggleDesktopSite = SingleActionViewModel(title: toggleActionTitle, iconString: ImageIdentifiers.requestDesktopSite) { _ in if let url = tab.url { tab.toggleChangeUserAgent() Tab.ChangeUserAgent.updateDomainList(forUrl: url, isChangedUA: tab.changedUserAgent, isPrivate: tab.isPrivate) } }.items if let url = tab.webView?.url, let helper = tab.contentBlocker, helper.isEnabled, helper.blockingStrengthPref == .strict { let isSafelisted = helper.status == .safelisted let title: String = !isSafelisted ? .TrackingProtectionReloadWithout : .TrackingProtectionReloadWith let imageName = helper.isEnabled ? "menu-TrackingProtection-Off" : "menu-TrackingProtection" let toggleTP = SingleActionViewModel(title: title, iconString: imageName) { _ in ContentBlocker.shared.safelist(enable: !isSafelisted, url: url) { tab.reload() } }.items return [toggleDesktopSite, toggleTP] } else { return [toggleDesktopSite] } } }
mpl-2.0
d9c7cdeadfd5f5aa507dad27b18dfe86
45.754717
142
0.670299
5.690011
false
false
false
false
swc1098/TIRO
TIRO/TIRO/SKTUtils/SKTEffects.swift
2
4230
/* * Copyright (c) 2013-2014 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import SpriteKit /** * Allows you to perform actions with custom timing functions. * * Unfortunately, SKAction does not have a concept of a timing function, so * we need to replicate the actions using SKTEffect subclasses. */ public class SKTEffect { unowned var node: SKNode var duration: TimeInterval public var timingFunction: ((CGFloat) -> CGFloat)? public init(node: SKNode, duration: TimeInterval) { self.node = node self.duration = duration timingFunction = SKTTimingFunctionLinear } public func update(_ t: CGFloat) { // subclasses implement this } } /** * Moves a node from its current position to a new position. */ public class SKTMoveEffect: SKTEffect { var startPosition: CGPoint var delta: CGPoint var previousPosition: CGPoint public init(node: SKNode, duration: TimeInterval, startPosition: CGPoint, endPosition: CGPoint) { previousPosition = node.position self.startPosition = startPosition delta = endPosition - startPosition super.init(node: node, duration: duration) } public override func update(_ t: CGFloat) { // This allows multiple SKTMoveEffect objects to modify the same node // at the same time. let newPosition = startPosition + delta*t let diff = newPosition - previousPosition previousPosition = newPosition node.position += diff } } /** * Scales a node to a certain scale factor. */ public class SKTScaleEffect: SKTEffect { var startScale: CGPoint var delta: CGPoint var previousScale: CGPoint public init(node: SKNode, duration: TimeInterval, startScale: CGPoint, endScale: CGPoint) { previousScale = CGPoint(x: node.xScale, y: node.yScale) self.startScale = startScale delta = endScale - startScale super.init(node: node, duration: duration) } public override func update(_ t: CGFloat) { let newScale = startScale + delta*t let diff = newScale / previousScale previousScale = newScale node.xScale *= diff.x node.yScale *= diff.y } } /** * Rotates a node to a certain angle. */ public class SKTRotateEffect: SKTEffect { var startAngle: CGFloat var delta: CGFloat var previousAngle: CGFloat public init(node: SKNode, duration: TimeInterval, startAngle: CGFloat, endAngle: CGFloat) { previousAngle = node.zRotation self.startAngle = startAngle delta = endAngle - startAngle super.init(node: node, duration: duration) } public override func update(_ t: CGFloat) { let newAngle = startAngle + delta*t let diff = newAngle - previousAngle previousAngle = newAngle node.zRotation += diff } } /** * Wrapper that allows you to use SKTEffect objects as regular SKActions. */ public extension SKAction { public class func actionWithEffect(_ effect: SKTEffect) -> SKAction { return SKAction.customAction(withDuration: effect.duration) { node, elapsedTime in var t = elapsedTime / CGFloat(effect.duration) if let timingFunction = effect.timingFunction { t = timingFunction(t) // the magic happens here } effect.update(t) } } }
mit
e7e2b0e6ec548b66212ef8d822dc29c8
30.567164
99
0.720095
4.485684
false
false
false
false
polymr/polymyr-api
Sources/App/Utility/Node+Convenience.swift
1
5947
// // Node+Convenience.swift // polymr-api // // Created by Hakon Hanesand on 3/3/17. // // import Node import JSON import Fluent import FluentProvider import Vapor import Foundation extension NodeError { func appendPath(_ path: [PathIndexer]) -> NodeError { switch self { case .unableToConvert( input: let input, expectation: let expectation, path: let existing ) where existing.isEmpty: return .unableToConvert(input: input, expectation: expectation, path: path) default: return self } } } extension StructuredDataWrapper { public func extract<T : NodeInitializable>(_ indexers: PathIndexer...) throws -> T { return try extract(indexers) } public func extract<T : NodeInitializable>(_ indexers: [PathIndexer]) throws -> T { if let value = self[indexers], value != .null { return try T(node: value) } throw try NodeError.unableToConvert(input: self.makeNode(in: nil), expectation: "\(T.self)", path: indexers) } public func extract<T, InputType: NodeInitializable>(_ indexers: PathIndexer..., transform: (InputType) throws -> T) throws -> T { return try get(path: indexers, transform: transform) } public func extract<T, InputType: NodeInitializable>(path indexers: [PathIndexer], transform: (InputType) throws -> T) throws -> T { if let value = self[indexers], value != .null { let input = try InputType(node: value, in: context) return try transform(input) } throw try NodeError.unableToConvert(input: self.makeNode(in: nil), expectation: "\(Node.self)", path: indexers) } } extension Node { mutating func merge(with json: JSON) throws -> Node { guard let update = json.node.object else { throw Abort.custom(status: .badRequest, message: "Expected [String : Object] node but got \(json.node)") } for (key, object) in update { self[key] = object } return self } func add(name: String, node: Node?) throws -> Node { if let node = node { return try add(name: name, node: node) } return self } func add(name: String, node: Node) throws -> Node { guard var object = self.object else { throw NodeError.unableToConvert(input: self, expectation: "[String: Node].self", path: [name]) } object[name] = node return try Node(node: object) } func add(objects: [String : NodeConvertible?]) throws -> Node { guard var previous = self.object else { throw NodeError.invalidContainer(container: "object", element: "self") } for (name, object) in objects { previous[name] = try object.makeNode(in: emptyContext) } return try Node(node: previous) } } public extension RawRepresentable where Self: NodeConvertible, RawValue == String { public init(node: Node) throws { guard let string = node.string else { throw NodeError.unableToConvert(input: node, expectation: "\(String.self)", path: ["self"]) } guard let value = Self.init(rawValue: string) else { throw Abort.custom(status: .badRequest, message: "Invalid node for \(Self.self)") } self = value } public func makeNode(in context: Context?) throws -> Node { return Node.string(self.rawValue) } public init?(from string: String) throws { guard let value = Self.init(rawValue: string) else { throw Abort.custom(status: .badRequest, message: "\(string) is not a valid value for for \(Self.self)") } self = value } } public extension Node { // TODO : rename to extract stripe list func extractList<T: NodeInitializable>(_ path: PathIndexer...) throws -> [T] { guard let node = self[path] else { throw NodeError.unableToConvert(input: self, expectation: "stripe list", path: path) } guard try node.extract("object") as String == "list" else { throw NodeError.unableToConvert(input: node, expectation: "list", path: ["object"]) } guard let data = node["data"]?.array else { throw NodeError.unableToConvert(input: node, expectation: "\(Array<Node>.self)", path: ["object"]) } return try [T](node: data) } func parseList(at key: String, with separator: String) throws -> [String] { guard let object = self[key] else { throw Abort.custom(status: .badRequest, message: "Missing list or string at \(key)") } switch object.wrapped { case let .array(strings): return strings.map { $0.string }.flatMap { $0 } case let .string(string): return string.components(separatedBy: separator) default: throw Abort.custom(status: .badRequest, message: "Unknown format for \(key)... got \(object.wrapped.type)") } } } extension StructuredData { var type: String { switch self { case .array(_): return "array" case .null: return "null" case .bool(_): return "bool" case .bytes(_): return "bytes" case let .number(number): switch number { case .int(_): return "number.int" case .double(_): return "number.double" case .uint(_): return "number.uint" } case .object(_): return "object" case .string(_): return "string" case .date(_): return "date" } } }
mit
72cc9a68519ebd7f236a0f0f3685643d
29.654639
142
0.565495
4.553599
false
false
false
false
nunosans/currency
Currency/UI Classes/CurrencyButton.swift
1
1338
// // CurrencyButton.swift // Currency // // Created by Nuno Coelho Santos on 19/05/2016. // Copyright © 2016 Nuno Coelho Santos. All rights reserved. // import Foundation import UIKit class CurrencyButton: UIButton { required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! } override var isHighlighted: Bool { get { return super.isHighlighted } set { if newValue { let fadeOut = CABasicAnimation(keyPath: "opacity") fadeOut.fromValue = 1 fadeOut.toValue = 0.3 fadeOut.duration = 0.03 fadeOut.autoreverses = false fadeOut.repeatCount = 1 self.layer.add(fadeOut, forKey: "fadeOut") self.layer.opacity = 0.3 } else { let fadeIn = CABasicAnimation(keyPath: "opacity") fadeIn.fromValue = 0.3 fadeIn.toValue = 1 fadeIn.duration = 0.12 fadeIn.autoreverses = false fadeIn.repeatCount = 1 self.layer.add(fadeIn, forKey: "fadeIn") self.layer.opacity = 1 } super.isHighlighted = newValue } } }
mit
b8408c28a067df50e2fbfa76d401de0a
26.285714
66
0.503366
5.026316
false
false
false
false
RTWeiss/pretto
Pretto/AddEventDateCell.swift
1
1106
// // AddEventDateCell.swift // Pretto // // Created by Francisco de la Pena on 6/14/15. // Copyright (c) 2015 Pretto. All rights reserved. // import UIKit class AddEventDateCell: UITableViewCell { @IBOutlet var startOrEndLabel: UILabel! @IBOutlet var dateLabel: UILabel! var isStartDate: Bool! { didSet { startOrEndLabel.text = isStartDate! ? "Starts on" : "Ends on" } } var date: NSDate! { didSet { dateFormatter.dateFormat = "MMM, d yyyy - hh:mm a" dateLabel.text = dateFormatter.stringFromDate(date) } } override func awakeFromNib() { super.awakeFromNib() self.selectionStyle = UITableViewCellSelectionStyle.None self.dateLabel.textColor = UIColor.prettoOrange() self.startOrEndLabel.textColor = UIColor.lightGrayColor() self.tintColor = UIColor.whiteColor() } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
89071a6d03199c8979bcc1c2271a439b
25.333333
73
0.637432
4.477733
false
false
false
false
neilpa/Equality
Equality/Equality.swift
1
2383
// Copyright (c) 2015 Neil Pankey. All rights reserved. /// An equality function over two sequences. Returns true iff both contain the same number of values in the same order. /// /// Unlike the Swift stdlib version of `equal` this doesn't require elements of both sequences to be the same. public func equal<S0: SequenceType, S1: SequenceType>(lhs: S0, rhs: S1, @noescape compare: (S0.Generator.Element, S1.Generator.Element) -> Bool) -> Bool { var leftGenerator = lhs.generate() var rightGenerator = rhs.generate() var leftElement = leftGenerator.next() var rightElement = rightGenerator.next() while let leftValue = leftElement, let rightValue = rightElement where compare(leftValue, rightValue) { leftElement = leftGenerator.next() rightElement = rightGenerator.next() } return leftElement == nil && rightElement == nil; } /// An equality function over two sequence. Returns true iff both contain the same number of values in the same order. /// /// Unlike the Swift stdlib version of `equal` this doesn't require elements of both sequences to be the same. /// /// This overload supports currying the comparator for easier creation of binary equality functions. public func equal<S0: SequenceType, S1: SequenceType>(@noescape compare: (S0.Generator.Element, S1.Generator.Element) -> Bool)(_ lhs: S0, _ rhs: S1) -> Bool { return Equality.equal(lhs, rhs, compare) } /// Defines an equality operator for arbitrary sequences of equatable elements. /// /// In practice this is most useful in tests for asserting equality of custom sequences against some reference collection: /// /// assert(CustomCollection(1, 2, 3) == [1, 2, 3]) public func == <S0: SequenceType, S1: SequenceType where S0.Generator.Element == S1.Generator.Element, S0.Generator.Element: Equatable> (lhs: S0, rhs: S1) -> Bool { return Equality.equal(lhs, rhs) { $0 == $1 } } /// Defines an inequality operator for arbitrary sequences of equatable elements /// /// In practice this is most useful in tests for asserting inequality of custom sequences against some reference collection: /// /// assert(CustomCollection(1, 2, 3) != [1, 2, 3]) public func != <S0: SequenceType, S1: SequenceType where S0.Generator.Element == S1.Generator.Element, S0.Generator.Element: Equatable> (lhs: S0, rhs: S1) -> Bool { return !(lhs == rhs) }
mit
d39190ad89bda01e9bb71bd29d68eb01
49.702128
164
0.714226
3.978297
false
false
false
false
JeffESchmitz/OnTheMap
OnTheMap/OnTheMap/InformationPostingViewController.swift
1
5239
// // InformationPostingViewController.swift // OnTheMap // // Created by Jeff Schmitz on 4/30/16. // Copyright © 2016 Jeff Schmitz. All rights reserved. // import UIKit import MapKit class InformationPostingViewController: UIViewController { @IBOutlet weak var locationTextField: UITextField! { didSet { locationTextField.delegate = self } } @IBOutlet weak var urlTextField: UITextField! { didSet { urlTextField.delegate = self } } @IBOutlet weak var findOnMapButton: UIButton! @IBOutlet weak var mapView: MKMapView! @IBOutlet weak var whereStudyingLabel: UILabel! @IBOutlet weak var submitButton: UIButton! private var coordinate: CLLocationCoordinate2D? @IBAction func findButtonTouched(sender: AnyObject) { findFunctionVersion() } func findFunctionVersion() { guard let whereabouts = locationTextField.text where !whereabouts.isEmpty else { self.showAlert("Please enter a location") return } LoadingOverlay.shared.showOverlay(self.view, message: "Locating...") CLGeocoder().geocodeAddressString(whereabouts) { (placemarks, error) in LoadingOverlay.shared.hideOverlayView() guard error == nil else { self.showAlert("Geocoding the map failed") return } guard let placemarks = placemarks else { LoadingOverlay.shared.hideOverlayView() self.showAlert("Dude, no map placements were returned...") return } let placemark = placemarks.first self.coordinate = placemark?.location?.coordinate if let placemark = placemark { self.mapView.addAnnotation(MKPlacemark(placemark: placemark)) } // center the map guard let unwrappedCoordinate = self.coordinate else { LoadingOverlay.shared.hideOverlayView() self.showAlert("Failed to retrieve coordinates") return } // set the zoom focus let latitudeDelta = CLLocationDegrees(floatLiteral: 0.001) let longitudDelta = CLLocationDegrees(floatLiteral: 0.001) let coordinateSpan = MKCoordinateSpanMake(latitudeDelta, longitudDelta) let region = MKCoordinateRegionMake(unwrappedCoordinate, coordinateSpan) self.mapView.setRegion(region, animated: true) // Hide/Show UI elements self.whereStudyingLabel.text = "Add a URL to your post" self.locationTextField.hidden = true self.findOnMapButton.enabled = false self.findOnMapButton.hidden = true self.urlTextField.hidden = false self.urlTextField.enabled = true self.submitButton.hidden = false self.submitButton.enabled = true } } @IBAction func submitButtonTouched(sender: AnyObject) { print("submitButtonTouched") LoadingOverlay.shared.showOverlay(view, message: "Posting...") let studentInfoDictionary = [ Constants.ParseAPI.ObjectId: "", Constants.ParseAPI.UniqueKey: Client.sharedInstance.userLogin.accountKey!, Constants.ParseAPI.FirstName: Client.sharedInstance.userLogin.userFirstName!, Constants.ParseAPI.LastName: Client.sharedInstance.userLogin.userLastName!, Constants.ParseAPI.MapString: locationTextField.text!, Constants.ParseAPI.MediaURL: urlTextField.text!, Constants.ParseAPI.CreatedAt: "", Constants.ParseAPI.UpdatedAt: "", Constants.ParseAPI.Latitude: coordinate!.latitude, Constants.ParseAPI.Longitude: self.coordinate!.longitude ] print("studentInfoDictionary: \(studentInfoDictionary)") let studentInformation = StudentInformation(dictionary: studentInfoDictionary as! [String:AnyObject]) print("studentInformation: \(studentInformation)") Client.sharedInstance.postStudentInformation(studentInformation) { (result, error) in if error != nil { dispatch_async(dispatch_get_main_queue(), { LoadingOverlay.shared.hideOverlayView() self.showAlert(error!) }) } else { dispatch_async(dispatch_get_main_queue(), { self.dismissViewControllerAnimated(true, completion: nil) }) } } } @IBAction func cancel(sender: AnyObject) { dismissViewControllerAnimated(true, completion: nil) } } extension InformationPostingViewController: UITextFieldDelegate { func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { view.endEditing(true) } }
mit
d4c9f8edb96a83110d419a17bb9148df
35.131034
109
0.609202
5.762376
false
false
false
false
biohazardlover/ByTrain
ByTrain/CitiesViewController.swift
1
1922
import UIKit class CitiesViewController: TableViewController { @IBOutlet weak var doneButtonItem: UIBarButtonItem! var cities: [City]? var selectedCities = [City]() private var networkController = NetworkController() deinit { networkController.invalidate() } override func refresh() { networkController.retrieveCities(station_name: nil) { [weak self] (_, cities, error) -> Void in self?.refreshControl?.endRefreshing() if error == nil { self?.cities = cities as? [City] self?.tableView.reloadData() } } } // MARK: - Table View Data Source override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return cities?.count ?? 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "CityTableCell", for: indexPath) let city = cities![indexPath.row] cell.textLabel?.text = city.chineseName cell.accessoryType = selectedCities.contains(city) ? .checkmark : .none return cell } // MARK: - Table View Delegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let city = cities![indexPath.row] let cell = tableView.cellForRow(at: indexPath)! if let index = selectedCities.index(of: city) { selectedCities.remove(at: index) cell.accessoryType = .none } else { selectedCities.append(city) cell.accessoryType = .checkmark } doneButtonItem.isEnabled = (selectedCities.count == 2) } }
mit
c8fb23c6b99ed64cdef4b5b634683796
30
109
0.605099
5.265753
false
false
false
false
SwiftFS/Swift-FS-China
Sources/SwiftFSChina/server/CommentServer.swift
1
3986
// // comment.swift // PerfectChina // // Created by mubin on 2017/7/28. // // import PerfectLib import MySQL struct CommentServer { public static func delete(user_id:Int,comment_id:Int)throws -> Bool{ return try pool.execute{ try $0.query("delete from comment where id=? and user_id=?",[comment_id,user_id]) }.affectedRows > 0 } public static func get_total_count_of_user(user_id:Int) throws -> Int{ let row:[Count] = try pool.execute{ try $0.query("select count(c.id) as count from comment c " + "right join topic t on c.topic_id=t.id " + " where c.user_id=? " ,[user_id]) } return row.count > 0 ? row[0].count : 0 } public static func get_all_of_user(user_id:Int,page_no:Int,page_size:Int) throws -> [ReplyCommentEntity]{ var page_no = page_no if page_no < 1 { page_no = 1 } return try pool.execute{ try $0.query("select t.id as topic_id, t.title as topic_title, c.content as comment_content,c.id as comment_id, c.create_time as comment_time from comment c" + " right join topic t on c.topic_id=t.id" + " where c.user_id=? order by c.id desc limit ?,?",[user_id,(page_no - 1)*page_size,page_size]) } } public static func query(comment_id:Int) throws -> CommentEntity? { let row:[CommentEntity] = try pool.execute{ try $0.query("select c.*, u.avatar as avatar, u.username as user_name from comment c " + "left join user u on c.user_id=u.id " + "where c.id=? " ,[comment_id]) } return row.count > 0 ? row[0] : nil } public static func get_last_reply_of_topic(topic_id:Int)throws ->NACommentEntity?{ let row:[NACommentEntity] = try pool.execute{ try $0.query("select c.*, u.username as user_name, u.id as user_id from comment c " + "left join user u on c.user_id=u.id " + "where c.topic_id=? order by c.id desc limit 1" ,[topic_id]) } return row.count > 0 ? row[0] : nil } public static func reset_topic_comment_num(topic_id:Int)throws -> Bool{ return try pool.execute{ try $0.query("update topic set reply_num=(select count(id) from comment where topic_id=?) where id=?", [topic_id,topic_id]) }.insertedID > 0 } public static func new(topic_id:Int,user_id:Int,content:String)throws -> UInt64?{ let status = try pool.execute{ try $0.query("insert into comment(topic_id,user_id, content) values(?,?,?)",[topic_id,user_id,content]) } return status.insertedID > 0 ? status.insertedID : nil } public static func get_total_count() throws -> [Count] { return try pool.execute{ try $0.query("select count(c.id) as comment_count from comment c ") } } public static func get_total_count_of_topic(topic_id:Int?) throws -> Int { guard let t_id = topic_id,t_id != 0 else{ return 0 } let row:[Count] = try pool.execute{ try $0.query("select count(id) as count from comment where topic_id=?",[topic_id]) } return row.count > 0 ? row[0].count : 0 } public static func get_all_of_topic(topic_id:Int,page_no:Int,page_size:Int) throws -> [CommentEntity]{ var page_no = page_no guard topic_id != 0 else { return [] } if page_no < 1 { page_no = 1 } return try pool.execute{ try $0.query("select c.*, u.avatar as avatar, u.username as user_name from comment c " + "left join user u on c.user_id=u.id " + "where c.topic_id=? order by c.id asc limit ?,?",[topic_id,(page_no - 1) * page_size,page_size]) } } }
mit
53d0b57fc748fc36bf1c65458336c16f
33.068376
171
0.552935
3.546263
false
false
false
false
taylorguo/douyuZB
douyuzb/douyuzb/Classes/Home/HomeViewController.swift
1
3499
// // HomeViewController.swift // douyuzb // // Created by mac on 2017/10/23. // Copyright © 2017年 mac. All rights reserved. // import UIKit private let kTitleViewHeight : CGFloat = 40 class HomeViewController: UIViewController { // MARK:- 懒加载属性 private lazy var pageTitleView: PageTitleView = { [weak self] in let titleFrame = CGRect(x: 0, y: kStatusBarHeight + kNavigationBarHeight, width: kScreenWidth, height: kTitleViewHeight) let titles = ["推荐", "游戏", "娱乐", "趣玩"] let titleView = PageTitleView(frame: titleFrame, titles: titles) titleView.delegate = self return titleView }() private lazy var pageContentView : PageContentView = {[weak self] in // 1. 确定内容 Frame let contentHight = kScreenHeight - kStatusBarHeight - kNavigationBarHeight - kTitleViewHeight - kTabbarHeight let contentFrame = CGRect(x: 0, y: kStatusBarHeight + kNavigationBarHeight + kTitleViewHeight, width: kScreenWidth, height: contentHight) // 2. 确定所有自控制器 var childVcs = [UIViewController]() childVcs.append(RecommendViewController()) for _ in 0..<3 { let vc = UIViewController() vc.view.backgroundColor = UIColor(r: CGFloat(arc4random_uniform(255)), g: CGFloat(arc4random_uniform(255)), b: CGFloat(arc4random_uniform(255))) childVcs.append(vc) } let contentView = PageContentView(frame: contentFrame, childVcs: childVcs, parentViewController: self!) contentView.delegate = self return contentView }() override func viewDidLoad() { super.viewDidLoad() setupUI() } } // MARK: - 设置UI界面 extension HomeViewController{ private func setupUI(){ // 设置导航栏 setupNavigationBar() //添加 TitleView view.addSubview(pageTitleView) // 添加 contentView view.addSubview(pageContentView) pageContentView.backgroundColor = UIColor.cyan } private func setupNavigationBar(){ // 1. 设置左侧的item let btn = UIButton() btn.setImage(UIImage(named: "douban_logo"), for: .normal) btn.sizeToFit() navigationItem.leftBarButtonItem = UIBarButtonItem(customView: btn) // 2. 设置右侧的item let size = CGSize(width: 40, height: 40) let historyItem = UIBarButtonItem(imageName: "ic_applied_icon", highImageName: "douban_logo", size: size) let searchItem = UIBarButtonItem(imageName: "ic_check_blue", highImageName: "ic_applied_icon", size: size) let qrcodeItem = UIBarButtonItem(imageName: "douban_logo", highImageName: "ic_check_blue", size: size) navigationItem.rightBarButtonItems = [historyItem, searchItem, qrcodeItem] } } // MARK:- 遵守PageTitleViewDelegate协议 extension HomeViewController : PageTitleViewDelegate{ func pageTitleView(titleView: PageTitleView, selectedIndex index: Int) { print(index) } } // MARK:- 遵守PageContentViewDelegate协议 extension HomeViewController : PageContentViewDelegate{ func pageContentView(contentView: PageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) { pageTitleView.setTitleWithProgress(progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex) } }
mit
9b2b1bac9d638a892485b6674863e44a
32.176471
156
0.656028
5.043219
false
false
false
false
hnney/SwiftReeder
SwiftReeder/UI/FeedListViewController.swift
2
3512
// // FeedList.swift // SwiftReeder // // Created by Thilong on 14/6/4. // Copyright (c) 2014年 thilong. All rights reserved. // import Foundation import UIKit class FeedListViewController : UIViewController , UITableViewDataSource, UITableViewDelegate { var tableView : UITableView? ; override func viewDidLoad(){ self.title="网易Rss" var addButton : UIButton = UIButton() addButton.frame = CGRect(x: 0,y: 0,width: 50,height: 40); addButton.setTitle("添加",forState: UIControlState.Normal) addButton.titleLabel.font = UIFont.systemFontOfSize(12); addButton.setTitleColor( UIColor.blackColor(),forState: UIControlState.Normal); addButton.addTarget(self,action: "addButtonTapped:",forControlEvents: UIControlEvents.TouchUpInside) var addButtonItem = UIBarButtonItem(customView : addButton); super.navigationItem.rightBarButtonItem = addButtonItem; var aboutButton : UIButton = UIButton() aboutButton.frame = CGRect(x: 0,y: 0,width: 50,height: 40); aboutButton.setTitle("关于",forState: UIControlState.Normal) aboutButton.titleLabel.font = UIFont.systemFontOfSize(12); aboutButton.setTitleColor( UIColor.blackColor(),forState: UIControlState.Normal); aboutButton.addTarget(self,action: "aboutButtonTapped:",forControlEvents: UIControlEvents.TouchUpInside) var aboutButtonItem = UIBarButtonItem(customView : aboutButton); super.navigationItem.leftBarButtonItem = aboutButtonItem; var tableFrame : CGRect = self.view.bounds; self.tableView = UITableView(frame:tableFrame); self.tableView!.dataSource = self; self.tableView!.delegate = self; self.view.addSubview(tableView); } override func viewWillAppear(animated: Bool){ self.tableView!.reloadData(); } func aboutButtonTapped(sender : AnyObject){ OCBridge.messageBox("关于",msg: "Swift语言Demo程序,请不要用于商业用途. By thilong.") } func addButtonTapped( sender : AnyObject){ var defaultFeedList : DefaultFeedListViewController = DefaultFeedListViewController() self.navigationController.pushViewController(defaultFeedList,animated: true); } func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int{ return FeedManager.sharedManager().feedsCount(); } func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!{ var data : Feed = FeedManager.sharedManager().feedAtIndex(indexPath.row); let cellReuseId = "cell_FeedListCell" ; var cell : UITableViewCell! = tableView.dequeueReusableCellWithIdentifier(cellReuseId) as? UITableViewCell; if !cell{ cell = UITableViewCell(style: UITableViewCellStyle.Default,reuseIdentifier: cellReuseId); cell.selectionStyle = UITableViewCellSelectionStyle.None; } cell.textLabel.text = data.name?; return cell; } func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!){ var data : Feed = FeedManager.sharedManager().feedAtIndex(indexPath.row); var vc : FeedRssListViewController = FeedRssListViewController(data); self.navigationController.pushViewController(vc,animated:true); } }
apache-2.0
cab4c1cf28ae8a3099430437e893e202
38.420455
115
0.685986
5.160714
false
false
false
false
SoneeJohn/WWDC
WWDC/BookmarkViewController.swift
1
3814
// // BookmarkViewController.swift // WWDC // // Created by Guilherme Rambo on 28/05/17. // Copyright © 2017 Guilherme Rambo. All rights reserved. // import Cocoa import ConfCore import PlayerUI import RxSwift import RxCocoa extension Notification.Name { fileprivate static let WWDCTextViewTextChanged = Notification.Name("WWDCTextViewTextChanged") } private final class WWDCTextView: NSTextView { lazy var rxText: Observable<String> = { return Observable<String>.create { [weak self] observer -> Disposable in let token = NotificationCenter.default.addObserver(forName: .WWDCTextViewTextChanged, object: self, queue: OperationQueue.main) { _ in observer.onNext(self?.string ?? "") } return Disposables.create { NotificationCenter.default.removeObserver(token) } } }() override func didChangeText() { super.didChangeText() NotificationCenter.default.post(name: .WWDCTextViewTextChanged, object: self) } } final class BookmarkViewController: NSViewController { let bookmark: Bookmark let storage: Storage init(bookmark: Bookmark, storage: Storage) { self.storage = storage self.bookmark = bookmark super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } fileprivate lazy var imageView: WWDCImageView = { let v = WWDCImageView() v.widthAnchor.constraint(equalToConstant: 85).isActive = true v.heightAnchor.constraint(equalToConstant: 48).isActive = true v.backgroundColor = .black return v }() private lazy var textView: WWDCTextView = { let v = WWDCTextView() v.drawsBackground = false v.backgroundColor = .clear v.font = .systemFont(ofSize: 12) v.textColor = .secondaryText v.autoresizingMask = [NSView.AutoresizingMask.width, NSView.AutoresizingMask.height] return v }() private lazy var scrollView: NSScrollView = { let v = NSScrollView() v.drawsBackground = false v.backgroundColor = .clear v.borderType = .noBorder v.documentView = self.textView return v }() private lazy var stackView: NSStackView = { let v = NSStackView(views: [self.imageView, self.scrollView]) v.orientation = .horizontal v.spacing = 8 v.alignment = .centerY v.translatesAutoresizingMaskIntoConstraints = false v.edgeInsets = NSEdgeInsets(top: 4, left: 4, bottom: 4, right: 4) return v }() override func loadView() { view = NSView() view.wantsLayer = true view.appearance = WWDCAppearance.appearance() scrollView.hasVerticalScroller = true scrollView.hasHorizontalScroller = false view.addSubview(stackView) stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true stackView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true stackView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true stackView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true } private let disposeBag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() imageView.image = NSImage(data: bookmark.snapshot) textView.string = bookmark.body textView.rxText.throttle(1, scheduler: MainScheduler.instance).subscribe(onNext: { [weak self] text in guard let bookmark = self?.bookmark else { return } self?.storage.modify(bookmark) { $0.body = text } }).disposed(by: disposeBag) } }
bsd-2-clause
f0012bc7e51ee112a22234cd0c91138d
28.10687
146
0.652767
4.888462
false
false
false
false
clappr/clappr-ios
Sources/Clappr/Classes/Base/Core.swift
1
10833
public typealias SharedData = [String: Any] open class Core: UIObject, UIGestureRecognizerDelegate { private var layerComposer: LayerComposer @objc public let environment = Environment() @objc open var sharedData = SharedData() @objc open var options: Options { didSet { containers.forEach { $0.options = options } updateChromelessMode() trigger(Event.didUpdateOptions) } } @objc private(set) open var containers: [Container] = [] private(set) open var plugins: [Plugin] = [] @objc open weak var parentController: UIViewController? @objc open var parentView: UIView? @objc open var overlayView = PassthroughView() #if os(iOS) @objc private (set) var fullscreenController: FullscreenController? = FullscreenController(nibName: nil, bundle: nil) lazy var fullscreenHandler: FullscreenStateHandler? = { return self.optionsUnboxer.fullscreenControledByApp ? FullscreenByApp(core: self) : FullscreenByPlayer(core: self) as FullscreenStateHandler }() private var orientationObserver: OrientationObserver? #endif lazy var optionsUnboxer: OptionsUnboxer = OptionsUnboxer(options: self.options) @objc open weak var activeContainer: Container? { willSet { activeContainer?.stopListening() trigger(.willChangeActiveContainer) } didSet { activeContainer?.on(Event.willChangePlayback.rawValue) { [weak self] info in self?.trigger(.willChangeActivePlayback, userInfo: info) } activeContainer?.on(Event.didChangePlayback.rawValue) { [weak self] info in self?.trigger(.didChangeActivePlayback, userInfo: info) } trigger(.didChangeActiveContainer) } } @objc open var activePlayback: Playback? { return activeContainer?.playback } @objc open var isFullscreen: Bool = false public var chromelessMode: Bool = false { didSet { updateLayersVisibility() updateGestureRecognizersState() } } public required init(options: Options = [:], layerComposer: LayerComposer) { Logger.logDebug("loading with \(options)", scope: "\(type(of: self))") self.options = options self.layerComposer = layerComposer super.init() updateChromelessMode() bindEventListeners() Loader.shared.corePlugins.forEach { addPlugin($0.init(context: self)) } } func load() { guard let source = options[kSourceUrl] as? String else { return } trigger(.willLoadSource) activeContainer?.load(source, mimeType: options[kMimeType] as? String) } public func gestureRecognizer(_: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { return touch.view!.accessibilityIdentifier == "Container" } public func add(container: Container) { containers.append(container) } public func setActive(container: Container) { if activeContainer != container { activeContainer = container } } private func updateLayersVisibility() { #if os(iOS) chromelessMode ? layerComposer.hideUI() : layerComposer.showUI() #endif } private func updateGestureRecognizersState() { #if os(iOS) view.gestureRecognizers?.forEach { $0.isEnabled = !chromelessMode } #endif } private func updateChromelessMode() { if let chromelessMode = options[kChromeless] as? Bool { self.chromelessMode = chromelessMode } } private func bindEventListeners() { #if os(iOS) listenTo(self, eventName: InternalEvent.userRequestEnterInFullscreen.rawValue) { [weak self] _ in self?.fullscreenHandler?.enterInFullscreen() } listenTo(self, eventName: InternalEvent.userRequestExitFullscreen.rawValue) { [weak self] _ in self?.onUserRequestExitFullscreen() } orientationObserver = OrientationObserver(core: self) #endif } open func attach(to parentView: UIView, controller: UIViewController) { guard let containerView = activeContainer?.view else { Logger.logError("Active container should not be nil when attaching to parent view", scope: "Core") return } parentView.addSubviewMatchingConstraints(view) layerComposer.attachContainer(containerView) layerComposer.attachOverlay(overlayView) layerComposer.compose(inside: view) self.parentController = controller self.parentView = parentView trigger(.didAttachView) } open override func render() { addTapGestures() containers.forEach(renderContainer) addToContainer() updateGestureRecognizersState() } private func addToContainer() { #if os(iOS) if shouldEnterInFullScreen { renderCorePlugins() renderMediaControlElements() fullscreenHandler?.enterInFullscreen() } else { renderInContainerView() renderCorePlugins() renderMediaControlElements() } renderOverlayPlugins() #else renderInContainerView() renderPlugins() #endif } private func renderInContainerView() { isFullscreen = false parentView?.addSubviewMatchingConstraints(view) } private func renderContainer(_ container: Container) { #if os(tvOS) view.addSubviewMatchingConstraints(container.view) #endif container.render() } #if os(tvOS) private func renderPlugins() { plugins.forEach(render) } #endif #if os(iOS) private func renderCorePlugins() { attachMediaControlLayer() plugins .filter { $0.isNotMediaControlElement } .filter { $0.isNotOverlayPlugin } .filter { $0.isNotMediaControl } .compactMap { $0 as? UICorePlugin } .forEach { plugin in layerComposer.attachUICorePlugin(plugin) plugin.safeRender() } } private func attachMediaControlLayer() { guard let mediaControl = plugins.first(where: { $0 is MediaControl }) as? MediaControl else { return } layerComposer.attachMediaControl(mediaControl.view) mediaControl.safeRender() } private func renderMediaControlElements() { let mediaControl = plugins.first { $0 is MediaControl } as? MediaControl let elements = plugins.compactMap { $0 as? MediaControl.Element } mediaControl?.render(elements) } private func renderOverlayPlugins() { plugins .compactMap { $0 as? OverlayPlugin } .forEach(render) } #endif private func viewThatRenders(_ plugin: Plugin) -> UIView { return plugin is OverlayPlugin ? overlayView : view } private func add(_ plugin: UICorePlugin, to view: UIView) { if plugin.shouldFitParentView { view.addSubviewMatchingConstraints(plugin.view) } else { view.addSubview(plugin.view) } } private func render(_ plugin: Plugin) { guard let plugin = plugin as? UICorePlugin else { return } add(plugin, to: viewThatRenders(plugin)) plugin.safeRender() } private var shouldEnterInFullScreen: Bool { return optionsUnboxer.fullscreen && !optionsUnboxer.fullscreenControledByApp } private var isFullscreenButtonDisable: Bool { optionsUnboxer.fullscreenDisabled } private var isFullscreenControlledByPlayer: Bool { !optionsUnboxer.fullscreenControledByApp } private var shouldDestroyPlayer: Bool { isFullscreenButtonDisable && isFullscreenControlledByPlayer } open func addPlugin(_ plugin: Plugin) { let containsPluginWithPlaceholder = plugins.contains(where: { $0.hasPlaceholder }) if !plugin.hasPlaceholder || !containsPluginWithPlaceholder { plugins.append(plugin) } } @objc open func setFullscreen(_ fullscreen: Bool) { #if os(iOS) fullscreenHandler?.set(fullscreen: fullscreen) #endif } private func onUserRequestExitFullscreen() { #if os(iOS) if shouldDestroyPlayer { trigger(InternalEvent.requestDestroyPlayer.rawValue) } else { fullscreenHandler?.exitFullscreen() } #endif } @objc open func destroy() { Logger.logDebug("destroying", scope: "Core") trigger(.willDestroy) Logger.logDebug("destroying listeners", scope: "Core") stopListening() Logger.logDebug("destroying containers", scope: "Core") containers.forEach { $0.destroy() } containers.removeAll() Logger.logDebug("destroying plugins", scope: "Core") plugins.forEach { $0.safeDestroy() } plugins.removeAll() Logger.logDebug("destroyed", scope: "Core") #if os(iOS) fullscreenHandler?.destroy() fullscreenHandler = nil fullscreenController = nil orientationObserver = nil #endif view.removeFromSuperview() trigger(.didDestroy) } } fileprivate extension Plugin { func logRenderCrash(for error: Error) { Logger.logError("\(pluginName) crashed during render (\(error.localizedDescription))", scope: "Core") } func logDestroyCrash(for error: Error) { Logger.logError("\(pluginName) crashed during destroy (\(error.localizedDescription))", scope: "Core") } var shouldFitParentView: Bool { return (self as? OverlayPlugin)?.isModal == true } var hasPlaceholder: Bool { #if os(iOS) guard let drawer = self as? DrawerPlugin else { return false } return drawer.placeholder > .zero #else return false #endif } #if os(iOS) var isNotMediaControl: Bool { return !(self is MediaControl) } var isNotMediaControlElement: Bool { return !(self is MediaControl.Element) } var isNotOverlayPlugin: Bool { return !(self is OverlayPlugin) } #endif func safeDestroy() { do { try ObjC.catchException { self.destroy() } } catch { logDestroyCrash(for: error) } } } fileprivate extension UICorePlugin { func safeRender() { do { try ObjC.catchException { self.render() } } catch { logRenderCrash(for: error) } } }
bsd-3-clause
f5b268fc68ca9fdae2323b15ecf5bccb
29.259777
152
0.624112
5.029248
false
false
false
false
tokyovigilante/CesiumKit
CesiumKit/Core/EllipsoidTerrainProvider.swift
1
5355
// // EllipsoidTerrainProvider.swift // CesiumKit // // Created by Ryan Walklin on 13/06/14. // Copyright (c) 2014 Test Toast. All rights reserved. // import Foundation /** * A very simple {@link TerrainProvider} that produces geometry by tessellating an ellipsoidal * surface. * * @alias EllipsoidTerrainProvider * @constructor * * @param {Object} [options] Object with the following properties: * @param {TilingScheme} [options.tilingScheme] The tiling scheme specifying how the ellipsoidal * surface is broken into tiles. If this parameter is not provided, a {@link GeographicTilingScheme} * is used. * @param {Ellipsoid} [options.ellipsoid] The ellipsoid. If the tilingScheme is specified, * this parameter is ignored and the tiling scheme's ellipsoid is used instead. If neither * parameter is specified, the WGS84 ellipsoid is used. * * @see TerrainProvider */ class EllipsoidTerrainProvider: TerrainProvider { /** * Gets an event that is raised when the terrain provider encounters an asynchronous error. By subscribing * to the event, you will be notified of the error and can potentially recover from it. Event listeners * are passed an instance of {@link TileProviderError}. * @memberof EllipsoidTerrainProvider.prototype * @type {Event} */ var errorEvent: Event /** * Gets the tiling scheme used by the provider. This function should * not be called before {@link TerrainProvider#ready} returns true. * @memberof TerrainProvider.prototype * @type {TilingScheme} */ let tilingScheme: TilingScheme let ellipsoid: Ellipsoid /** * Gets the credit to display when this terrain provider is active. Typically this is used to credit * the source of the terrain. This function should * not be called before {@link TerrainProvider#ready} returns true. * @memberof TerrainProvider.prototype * @type {Credit} */ var credit: Credit? = nil /** * Gets a value indicating whether or not the provider is ready for use. * @memberof TerrainProvider.prototype * @type {Boolean} */ fileprivate (set) var ready = true fileprivate var _levelZeroMaximumGeometricError: Double = 0.0 var heightmapTerrainQuality = 0.25 required init(tilingScheme: TilingScheme = GeographicTilingScheme(), ellipsoid: Ellipsoid = Ellipsoid.wgs84) { self.tilingScheme = tilingScheme self.ellipsoid = ellipsoid credit = nil errorEvent = Event() // Note: the 64 below does NOT need to match the actual vertex dimensions, because // the ellipsoid is significantly smoother than actual terrain. _levelZeroMaximumGeometricError = EllipsoidTerrainProvider.estimatedLevelZeroGeometricErrorForAHeightmap(ellipsoid: ellipsoid, tileImageWidth: 64,numberOfTilesAtLevelZero: tilingScheme.numberOfXTilesAt(level: 0)) } /** * Requests the geometry for a given tile. This function should not be called before * {@link TerrainProvider#ready} returns true. The result includes terrain * data and indicates that all child tiles are available. * * @param {Number} x The X coordinate of the tile for which to request geometry. * @param {Number} y The Y coordinate of the tile for which to request geometry. * @param {Number} level The level of the tile for which to request geometry. * @param {Boolean} [throttleRequests=true] True if the number of simultaneous requests should be limited, * or false if the request should be initiated regardless of the number of requests * already in progress. * @returns {Promise|TerrainData} A promise for the requested geometry. If this method * returns undefined instead of a promise, it is an indication that too many requests are already * pending and the request will be retried later. */ func requestTileGeometry(x: Int, y: Int, level: Int, throttleRequests: Bool, completionBlock: @escaping (TerrainData?) -> ()) -> NetworkOperation? { logPrint(.debug, "Requested terrain for L\(level)X\(x)Y\(y)") let terrainData = HeightmapTerrainData( buffer: [UInt16](repeating: 0, count: 16 * 16), width : 16, height : 16) completionBlock(terrainData) return nil } /** * Gets the maximum geometric error allowed in a tile at a given level. * * @param {Number} level The tile level for which to get the maximum geometric error. * @returns {Number} The maximum geometric error. */ func levelMaximumGeometricError(_ level: Int) -> Double { return _levelZeroMaximumGeometricError / Double(1 << level) } /** * Gets a value indicating whether or not the provider includes a water mask. The water mask * indicates which areas of the globe are water rather than land, so they can be rendered * as a reflective surface with animated waves. * * @returns {Boolean} True if the provider has a water mask; otherwise, false. */ var hasWaterMask: Bool { return false } var hasVertexNormals: Bool { return false } }
apache-2.0
f0474b47ad954aede2e57c56d6a95839
39.263158
220
0.67451
4.718062
false
false
false
false
thiagotmb/BEPiD-Challenges-2016
2016-03-11-Menu/ChallengeBookStore/ChallengeBookStore WatchKit Extension/CheckoutInterfaceController.swift
2
2611
// // CheckoutInterfaceController.swift // ChallengeBookStore // // Created by Thiago-Bernardes on 3/11/16. // Copyright © 2016 TB. All rights reserved. // import WatchKit import Foundation class CheckoutInterfaceController: WKInterfaceController { @IBOutlet var table: WKInterfaceTable! var boughtBooks = ((NSUserDefaults.standardUserDefaults().arrayForKey("boughtBooks") as? [Int]) != nil) ? NSUserDefaults.standardUserDefaults().arrayForKey("boughtBooks") as! [Int] : [Int]() override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) configureTable() // Configure interface objects here. } //Configure table attributtes private func configureTable() { table.setNumberOfRows(Books.books.count, withRowType: "BookRow") for (index, value) in Books.books.enumerate() { let rowController = table.rowControllerAtIndex(index) as? RowController rowController?.loadRow(value.1, bookPrice: value.2) rowController?.authorNameLabel.setText(value.0) if boughtBooks.contains(index) { rowController?.isBoughtImage.setAlpha(1) } } } override func table(table: WKInterfaceTable, didSelectRowAtIndex rowIndex: Int) { let rowController = table.rowControllerAtIndex(rowIndex) as! RowController let alertTitle = String(format: rowController.bookName! + ": " + rowController.bookPrice!) let confirmAction = WKAlertAction(title: "Yes", style: WKAlertActionStyle.Default) { () -> Void in self.boughtBooks.append(rowIndex) NSUserDefaults.standardUserDefaults().setObject(self.boughtBooks, forKey: "boughtBooks") self.configureTable() } let cancelAction = WKAlertAction(title: "No", style: WKAlertActionStyle.Cancel) { () -> Void in } presentAlertControllerWithTitle(alertTitle, message:"Confirm purchase ?" , preferredStyle: WKAlertControllerStyle.Alert, actions: [confirmAction,cancelAction]) } @IBAction func comprarTudo() { for (index, _) in Books.books.enumerate() { self.boughtBooks.append(index) } NSUserDefaults.standardUserDefaults().setObject(boughtBooks, forKey: "boughtBooks") self.configureTable() } }
mit
2a5261dbdbbde2dc9bcb3571803a2df8
30.445783
194
0.610728
5.471698
false
true
false
false
ryanipete/AmericanChronicle
AmericanChronicle/Code/AppWide/Views/TitleValueButton.swift
1
3124
import UIKit final class TitleValueButton: UIControl { // MARK: Properties var value: String? { get { valueLabel.text } set { valueLabel.text = newValue } } private let titleLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.textColor = AMCColor.darkGray label.highlightedTextColor = .white label.textAlignment = .center label.font = AMCFont.verySmallRegular return label }() private let valueLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.textColor = AMCColor.brightBlue label.highlightedTextColor = .white label.font = AMCFont.mediumRegular label.textAlignment = .center return label }() private let button: UIButton = { let btn = UIButton() btn.setBackgroundImage(.imageWithFillColor(.white, cornerRadius: 1.0), for: .normal) btn.setBackgroundImage(.imageWithFillColor(AMCColor.brightBlue, cornerRadius: 1.0), for: .highlighted) return btn }() private var observingToken: NSKeyValueObservation? // MARK: Init methods init(title: String, initialValue: String = "--") { super.init(frame: .zero) layer.shadowColor = AMCColor.darkGray.cgColor layer.shadowOffset = .zero layer.shadowRadius = 0.5 layer.shadowOpacity = 0.4 titleLabel.text = title valueLabel.text = initialValue button.addTarget(self, action: #selector(didTapButton), for: .touchUpInside) observingToken = button.observe(\UIButton.isHighlighted) { [weak self] _, _ in self?.isHighlighted = (self?.button.isHighlighted ?? false) } addSubview(button) button.fillSuperview(insets: .zero) let labelStackView = UIStackView(arrangedSubviews: [titleLabel, valueLabel]) labelStackView.translatesAutoresizingMaskIntoConstraints = false labelStackView.isUserInteractionEnabled = false labelStackView.axis = .vertical addSubview(labelStackView) labelStackView.fillSuperview(horizontalInsets: 8.0, verticalInsets: 5.0) } @available(*, unavailable) override init(frame: CGRect) { fatalError("init(frame:) has not been implemented") } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } @available(*, unavailable) init() { fatalError("init() has not been implemented") } // MARK: Internal methods @objc func didTapButton() { sendActions(for: .touchUpInside) } // MARK: UIControl overrides override var isHighlighted: Bool { didSet { titleLabel.isHighlighted = isHighlighted valueLabel.isHighlighted = isHighlighted } } // MARK: UIView overrides override var intrinsicContentSize: CGSize { CGSize(width: UIView.noIntrinsicMetric, height: Dimension.buttonHeight) } }
mit
230e12a00355153f9a02028e8eb6c2a5
29.627451
110
0.650768
5.138158
false
false
false
false
NghiaTranUIT/Unofficial-Uber-macOS
UberGoCore/UberGoCore/ReachabilityService.swift
1
2485
// // ReachabilityService.swift // RxExample // // Created by Vodovozov Gleb on 10/22/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if !RX_NO_MODULE import RxSwift #endif import Foundation public enum ReachabilityStatus { case reachable(viaWiFi: Bool) case unreachable } extension ReachabilityStatus { var reachable: Bool { switch self { case .reachable: return true case .unreachable: return false } } } protocol ReachabilityService { var reachability: Observable<ReachabilityStatus> { get } } enum ReachabilityServiceError: Error { case failedToCreate } class DefaultReachabilityService : ReachabilityService { private let _reachabilitySubject: BehaviorSubject<ReachabilityStatus> var reachability: Observable<ReachabilityStatus> { return _reachabilitySubject.asObservable() } let _reachability: Reachability init() throws { guard let reachabilityRef = Reachability() else { throw ReachabilityServiceError.failedToCreate } let reachabilitySubject = BehaviorSubject<ReachabilityStatus>(value: .unreachable) // so main thread isn't blocked when reachability via WiFi is checked let backgroundQueue = DispatchQueue(label: "reachability.wificheck") reachabilityRef.whenReachable = { reachability in backgroundQueue.async { reachabilitySubject.on(.next(.reachable(viaWiFi: reachabilityRef.isReachableViaWiFi))) } } reachabilityRef.whenUnreachable = { reachability in backgroundQueue.async { reachabilitySubject.on(.next(.unreachable)) } } try reachabilityRef.startNotifier() _reachability = reachabilityRef _reachabilitySubject = reachabilitySubject } deinit { _reachability.stopNotifier() } } extension ObservableConvertibleType { func retryOnBecomesReachable(_ valueOnFailure:E, reachabilityService: ReachabilityService) -> Observable<E> { return self.asObservable() .catchError { (e) -> Observable<E> in reachabilityService.reachability .skip(1) .filter { $0.reachable } .flatMap { _ in Observable.error(e) } .startWith(valueOnFailure) } .retry() } }
mit
4092a5e2fbe39e3e537b0d8ee9927400
25.709677
113
0.635266
5.507761
false
false
false
false
idapgroup/IDPDesign
Tests/iOS/iOSTests/Specs/Lens+UITableViewSpec.swift
1
16910
// // Lens+UITableViewSpec.swift // iOSTests // // Created by Oleksa 'trimm' Korin on 9/2/17. // Copyright © 2017 Oleksa 'trimm' Korin. All rights reserved. // import Quick import Nimble import UIKit @testable import IDPDesign extension UITableView: UITableViewProtocol { } class LensUITableViewSpec: QuickSpec { override func spec() { describe("Lens+UITableViewSpec") { context("dataSource") { it("should get and set") { class DataSource: NSObject, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return UITableViewCell() } } let lens: Lens<UITableView, UITableViewDataSource?> = dataSource() let object = UITableView() let value: UITableViewDataSource = DataSource() let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(beIdenticalTo(value)) expect(resultObject.dataSource).to(beIdenticalTo(value)) } } context("delegate") { it("should get and set") { class Delegate: NSObject, UITableViewDelegate { } let lens: Lens<UITableView, UITableViewDelegate?> = delegate() let object = UITableView() let value: UITableViewDelegate = Delegate() let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(beIdenticalTo(value)) expect(resultObject.delegate).to(beIdenticalTo(value)) } } context("prefetchDataSource") { it("should get and set") { class DataSource: NSObject, UITableViewDataSourcePrefetching { func tableView(_ tableView: UITableView, prefetchRowsAt indexPaths: [IndexPath]) { } } let lens: Lens<UITableView, UITableViewDataSourcePrefetching?> = prefetchDataSource() let object = UITableView() let value: UITableViewDataSourcePrefetching = DataSource() let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(beIdenticalTo(value)) expect(resultObject.prefetchDataSource).to(beIdenticalTo(value)) } } context("rowHeight") { it("should get and set") { let lens: Lens<UITableView, CGFloat> = rowHeight() let object = UITableView() let value: CGFloat = 0.5 let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.rowHeight).to(equal(value)) } } context("sectionHeaderHeight") { it("should get and set") { let lens: Lens<UITableView, CGFloat> = sectionHeaderHeight() let object = UITableView() let value: CGFloat = 0.5 let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.sectionHeaderHeight).to(equal(value)) } } context("sectionFooterHeight") { it("should get and set") { let lens: Lens<UITableView, CGFloat> = sectionFooterHeight() let object = UITableView() let value: CGFloat = 0.5 let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.sectionFooterHeight).to(equal(value)) } } context("estimatedRowHeight") { it("should get and set") { let lens: Lens<UITableView, CGFloat> = estimatedRowHeight() let object = UITableView() let value: CGFloat = 20.0 let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.estimatedRowHeight).to(equal(value)) } } context("estimatedSectionHeaderHeight") { it("should get and set") { let lens: Lens<UITableView, CGFloat> = estimatedSectionHeaderHeight() let object = UITableView() let value: CGFloat = 20.0 let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.estimatedSectionHeaderHeight).to(equal(value)) } } context("estimatedSectionFooterHeight") { it("should get and set") { let lens: Lens<UITableView, CGFloat> = estimatedSectionFooterHeight() let object = UITableView() let value: CGFloat = 20.0 let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.estimatedSectionFooterHeight).to(equal(value)) } } context("separatorInset") { it("should get and set") { let lens: Lens<UITableView, UIEdgeInsets> = separatorInset() let object = UITableView() let value: UIEdgeInsets = UIEdgeInsets(top: 1, left: 1, bottom: 1, right: 1) let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.separatorInset).to(equal(value)) } } context("backgroundView") { it("should get and set") { let lens: Lens<UITableView, UIView?> = backgroundView() let object = UITableView() let value: UIView = UIView() let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.backgroundView).to(equal(value)) } } context("isEditing") { it("should get and set") { let lens: Lens<UITableView, Bool> = isEditing() let object = UITableView() let value: Bool = !object.isEditing let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.isEditing).to(equal(value)) } } context("allowsSelection") { it("should get and set") { let lens: Lens<UITableView, Bool> = allowsSelection() let object = UITableView() let value: Bool = !object.allowsSelection let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.allowsSelection).to(equal(value)) } } context("allowsSelectionDuringEditing") { it("should get and set") { let lens: Lens<UITableView, Bool> = allowsSelectionDuringEditing() let object = UITableView() let value: Bool = !object.allowsSelectionDuringEditing let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.allowsSelectionDuringEditing).to(equal(value)) } } context("allowsMultipleSelection") { it("should get and set") { let lens: Lens<UITableView, Bool> = allowsMultipleSelection() let object = UITableView() let value: Bool = !object.allowsMultipleSelection let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.allowsMultipleSelection).to(equal(value)) } } context("allowsMultipleSelectionDuringEditing") { it("should get and set") { let lens: Lens<UITableView, Bool> = allowsMultipleSelectionDuringEditing() let object = UITableView() let value: Bool = !object.allowsMultipleSelectionDuringEditing let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.allowsMultipleSelectionDuringEditing).to(equal(value)) } } context("sectionIndexMinimumDisplayRowCount") { it("should get and set") { let lens: Lens<UITableView, Int> = sectionIndexMinimumDisplayRowCount() let object = UITableView() let value: Int = 2 let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.sectionIndexMinimumDisplayRowCount).to(equal(value)) } } context("sectionIndexColor") { it("should get and set") { let lens: Lens<UITableView, UIColor?> = sectionIndexColor() let object = UITableView() let value: UIColor = UIColor.red let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.sectionIndexColor).to(equal(value)) } } context("sectionIndexBackgroundColor") { it("should get and set") { let lens: Lens<UITableView, UIColor?> = sectionIndexBackgroundColor() let object = UITableView() let value: UIColor = UIColor.red let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.sectionIndexBackgroundColor).to(equal(value)) } } context("sectionIndexTrackingBackgroundColor") { it("should get and set") { let lens: Lens<UITableView, UIColor?> = sectionIndexTrackingBackgroundColor() let object = UITableView() let value: UIColor = UIColor.red let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.sectionIndexTrackingBackgroundColor).to(equal(value)) } } context("separatorStyle") { it("should get and set") { let lens: Lens<UITableView, UITableViewCell.SeparatorStyle> = separatorStyle() let object = UITableView() let value: UITableViewCell.SeparatorStyle = .none let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.separatorStyle).to(equal(value)) } } context("separatorColor") { it("should get and set") { let lens: Lens<UITableView, UIColor?> = separatorColor() let object = UITableView() let value: UIColor = UIColor.red let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.separatorColor).to(equal(value)) } } context("separatorEffect") { it("should get and set") { let lens: Lens<UITableView, UIVisualEffect?> = separatorEffect() let object = UITableView() let value: UIVisualEffect = UIVisualEffect() let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.separatorEffect).to(equal(value)) } } context("cellLayoutMarginsFollowReadableWidth") { it("should get and set") { let lens: Lens<UITableView, Bool> = cellLayoutMarginsFollowReadableWidth() let object = UITableView() let value: Bool = !object.cellLayoutMarginsFollowReadableWidth let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.cellLayoutMarginsFollowReadableWidth).to(equal(value)) } } context("tableHeaderView") { it("should get and set") { let lens: Lens<UITableView, UIView?> = tableHeaderView() let object = UITableView() let value: UIView = UIView() let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.tableHeaderView).to(equal(value)) } } context("tableFooterView") { it("should get and set") { let lens: Lens<UITableView, UIView?> = tableFooterView() let object = UITableView() let value: UIView = UIView() let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.tableFooterView).to(equal(value)) } } context("remembersLastFocusedIndexPath") { it("should get and set") { let lens: Lens<UITableView, Bool> = remembersLastFocusedIndexPath() let object = UITableView() let value: Bool = !object.remembersLastFocusedIndexPath let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.remembersLastFocusedIndexPath).to(equal(value)) } } } } }
bsd-3-clause
384b430d9d7f20db5c96a1bb22a55478
36.912556
120
0.507718
6.159927
false
false
false
false
haskellswift/swift-package-manager
Sources/POSIX/stat.swift
2
1553
/* This source file is part of the Swift.org open source project Copyright 2015 - 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 Swift project authors */ import libc /// Extensions to the libc `stat` structure to interpret the contents in more readable ways. extension libc.stat { /// File system entity kind. public enum Kind { case file, directory, symlink, fifo, blockdev, chardev, socket, unknown fileprivate init(mode: mode_t) { switch mode { case S_IFREG: self = .file case S_IFDIR: self = .directory case S_IFLNK: self = .symlink case S_IFBLK: self = .blockdev case S_IFCHR: self = .chardev case S_IFSOCK: self = .socket default: self = .unknown } } } /// Kind of file system entity. public var kind: Kind { return Kind(mode: st_mode & S_IFMT) } } public func stat(_ path: String) throws -> libc.stat { var sbuf = libc.stat() let rv = stat(path, &sbuf) guard rv == 0 else { throw SystemError.stat(errno, path) } return sbuf } public func lstat(_ path: String) throws -> libc.stat { var sbuf = libc.stat() let rv = lstat(path, &sbuf) guard rv == 0 else { throw SystemError.stat(errno, path) } return sbuf }
apache-2.0
07d1bb91a3d4daea2189b8d62a1ffdce
28.865385
92
0.598197
3.992288
false
false
false
false
AaronMT/firefox-ios
Client/Frontend/Widgets/SearchInputView.swift
8
6888
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import SnapKit private struct SearchInputViewUX { static let horizontalSpacing: CGFloat = 16 static let titleFont = UIFont.systemFont(ofSize: 16) static let borderLineWidth: CGFloat = 0.5 static let closeButtonSize: CGFloat = 36 } @objc protocol SearchInputViewDelegate: AnyObject { func searchInputView(_ searchView: SearchInputView, didChangeTextTo text: String) func searchInputViewBeganEditing(_ searchView: SearchInputView) func searchInputViewFinishedEditing(_ searchView: SearchInputView) } class SearchInputView: UIView, Themeable { weak var delegate: SearchInputViewDelegate? var showBottomBorder: Bool = true { didSet { bottomBorder.isHidden = !showBottomBorder } } lazy var inputField: UITextField = { let textField = UITextField() textField.delegate = self textField.addTarget(self, action: #selector(inputTextDidChange), for: .editingChanged) textField.accessibilityLabel = NSLocalizedString("Search Input Field", tableName: "LoginManager", comment: "Accessibility label for the search input field in the Logins list") textField.autocorrectionType = .no textField.autocapitalizationType = .none return textField }() lazy var titleLabel: UILabel = { let label = UILabel() label.text = NSLocalizedString("Search", tableName: "LoginManager", comment: "Title for the search field at the top of the Logins list screen") label.font = SearchInputViewUX.titleFont return label }() lazy var searchIcon: UIImageView = { return UIImageView(image: UIImage(named: "quickSearch")) }() fileprivate lazy var closeButton: UIButton = { let button = UIButton() button.addTarget(self, action: #selector(tappedClose), for: .touchUpInside) button.setImage(UIImage(named: "clear"), for: []) button.accessibilityLabel = NSLocalizedString("Clear Search", tableName: "LoginManager", comment: "Accessibility message e.g. spoken by VoiceOver after the user taps the close button in the search field to clear the search and exit search mode") return button }() fileprivate var centerContainer = UIView() fileprivate lazy var bottomBorder: UIView = { let border = UIView() return border }() fileprivate lazy var overlay: UIView = { let view = UIView() view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tappedSearch))) view.isAccessibilityElement = true view.accessibilityLabel = NSLocalizedString("Enter Search Mode", tableName: "LoginManager", comment: "Accessibility label for entering search mode for logins") return view }() fileprivate(set) var isEditing = false { didSet { if isEditing { overlay.isHidden = true inputField.isHidden = false inputField.accessibilityElementsHidden = false closeButton.isHidden = false closeButton.accessibilityElementsHidden = false } else { overlay.isHidden = false inputField.isHidden = true inputField.accessibilityElementsHidden = true closeButton.isHidden = true closeButton.accessibilityElementsHidden = true } } } override init(frame: CGRect) { super.init(frame: frame) isUserInteractionEnabled = true addSubview(inputField) addSubview(closeButton) centerContainer.addSubview(searchIcon) centerContainer.addSubview(titleLabel) overlay.addSubview(centerContainer) addSubview(overlay) addSubview(bottomBorder) setupConstraints() setEditing(false) applyTheme() } fileprivate func setupConstraints() { centerContainer.snp.makeConstraints { make in make.center.equalTo(overlay) } overlay.snp.makeConstraints { make in make.edges.equalTo(self) } searchIcon.snp.makeConstraints { make in make.right.equalTo(titleLabel.snp.left).offset(-SearchInputViewUX.horizontalSpacing) make.centerY.equalTo(centerContainer) } titleLabel.snp.makeConstraints { make in make.center.equalTo(centerContainer) } inputField.snp.makeConstraints { make in make.left.equalTo(self).offset(SearchInputViewUX.horizontalSpacing) make.centerY.equalTo(self) make.right.equalTo(closeButton.snp.left).offset(-SearchInputViewUX.horizontalSpacing) } closeButton.snp.makeConstraints { make in make.right.equalTo(self).offset(-SearchInputViewUX.horizontalSpacing) make.centerY.equalTo(self) make.size.equalTo(SearchInputViewUX.closeButtonSize) } bottomBorder.snp.makeConstraints { make in make.left.right.bottom.equalTo(self) make.height.equalTo(SearchInputViewUX.borderLineWidth) } } // didSet callbacks don't trigger when a property is being set in the init() call // but calling a method that does works fine. fileprivate func setEditing(_ editing: Bool) { isEditing = editing } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func applyTheme() { backgroundColor = UIColor.theme.tableView.rowBackground overlay.backgroundColor = backgroundColor titleLabel.textColor = UIColor.theme.tableView.rowText inputField.textColor = titleLabel.textColor } } // MARK: - Selectors extension SearchInputView { @objc func tappedSearch() { isEditing = true inputField.becomeFirstResponder() delegate?.searchInputViewBeganEditing(self) } @objc func tappedClose() { isEditing = false delegate?.searchInputViewFinishedEditing(self) inputField.text = nil inputField.resignFirstResponder() } @objc func inputTextDidChange(_ textField: UITextField) { delegate?.searchInputView(self, didChangeTextTo: textField.text ?? "") } } // MARK: - UITextFieldDelegate extension SearchInputView: UITextFieldDelegate { func textFieldDidEndEditing(_ textField: UITextField) { // If there is no text, go back to showing the title view if textField.text?.isEmpty ?? true { isEditing = false delegate?.searchInputViewFinishedEditing(self) } } }
mpl-2.0
86bf5f86152fda932a6009a46044a14a
32.6
183
0.663328
5.479714
false
false
false
false
shadanan/mado
Mado/AppWindow.swift
1
8305
// // AccessibilityElement.swift // MadoSize // // Created by Shad Sharma on 7/3/16. // Copyright © 2016 Shad Sharma. All rights reserved. // import Cocoa import Foundation class ResizeSpec: NSObject { var xExpr: String var yExpr: String var wExpr: String var hExpr: String init(xExpr: String, yExpr: String, wExpr: String, hExpr: String) { self.xExpr = xExpr self.yExpr = yExpr self.wExpr = wExpr self.hExpr = hExpr } } class AppWindow: CustomStringConvertible { let app: NSRunningApplication let appElement: AXUIElement let windowElement: AXUIElement static func frontmost() -> AppWindow? { guard let frontmostApplication = NSWorkspace.shared().frontmostApplication else { return nil } let appElement = AXUIElementCreateApplication(frontmostApplication.processIdentifier) var result: AnyObject? guard AXUIElementCopyAttributeValue(appElement, kAXFocusedWindowAttribute as CFString, &result) == .success else { return nil } let windowElement = result as! AXUIElement return AppWindow(app: frontmostApplication, appElement: appElement, windowElement: windowElement) } var primaryScreenHeight: CGFloat { get { if let screens = NSScreen.screens() { return screens[0].frame.maxY } else { return 0 } } } init(app: NSRunningApplication, appElement: AXUIElement, windowElement: AXUIElement) { self.app = app self.appElement = appElement self.windowElement = windowElement } fileprivate func value(_ attribute: String, type: AXValueType) -> AXValue? { guard CFGetTypeID(windowElement) == AXUIElementGetTypeID() else { return nil } var result: AnyObject? guard AXUIElementCopyAttributeValue(windowElement, attribute as CFString, &result) == .success else { return nil } let value = result as! AXValue guard AXValueGetType(value) == type else { return nil } return value } fileprivate func setValue(_ value: AXValue, attribute: String) { let status = AXUIElementSetAttributeValue(windowElement, attribute as CFString, value) if status != .success { print("Failed to set \(attribute)=\(value)") } } fileprivate var appOrigin: CGPoint? { get { guard let positionValue = value(kAXPositionAttribute, type: .cgPoint) else { return nil } var position = CGPoint() AXValueGetValue(positionValue, .cgPoint, &position) return position } set { var origin = newValue guard let positionRef = AXValueCreate(.cgPoint, &origin) else { print("Failed to create positionRef") return } setValue(positionRef, attribute: kAXPositionAttribute) } } var origin: CGPoint? { get { guard let appOrigin = appOrigin, let size = size else { return nil } return CGPoint(x: appOrigin.x, y: primaryScreenHeight - size.height - appOrigin.y) } set { if let newOrigin = newValue, let size = size { appOrigin = CGPoint(x: newOrigin.x, y: primaryScreenHeight - size.height - newOrigin.y) } } } var size: CGSize? { get { guard let sizeValue = value(kAXSizeAttribute, type: .cgSize) else { return nil } var size = CGSize() AXValueGetValue(sizeValue, .cgSize, &size) return size } set { var size = newValue guard let sizeRef = AXValueCreate(.cgSize, &size) else { print("Failed to create sizeRef") return } setValue(sizeRef, attribute: kAXSizeAttribute) } } var globalFrame: CGRect? { get { guard let origin = appOrigin, let size = size else { return nil } return CGRect(origin: CGPoint(x: origin.x, y: primaryScreenHeight - size.height - origin.y), size: size) } set { if let frame = newValue { appOrigin = CGPoint(x: frame.origin.x, y: primaryScreenHeight - frame.size.height - frame.origin.y) size = frame.size } } } var frame: CGRect? { get { guard let screen = screen(), let globalFrame = globalFrame else { return nil } return CGRect(origin: globalFrame.origin - screen.frame.origin, size: globalFrame.size) } set { if let screen = screen(), let localFrame = newValue { globalFrame = CGRect(origin: localFrame.origin + screen.frame.origin, size: localFrame.size) } } } func resize(spec: ResizeSpec) { if let visibleFrame = screen()?.visibleFrame, let origin = origin, let size = size { let W = Double(visibleFrame.width) let H = Double(visibleFrame.height) let X = Double(visibleFrame.origin.x) let Y = Double(visibleFrame.origin.y) let x = Double(origin.x) let y = Double(origin.y) let w = Double(size.width) let h = Double(size.height) if let nx = Expr.evaluate(exprStr: spec.xExpr, W: W, H: H, x: x, y: y, w: w, h: h), let ny = Expr.evaluate(exprStr: spec.yExpr, W: W, H: H, x: x, y: y, w: w, h: h), let nw = Expr.evaluate(exprStr: spec.wExpr, W: W, H: H, x: x, y: y, w: w, h: h), let nh = Expr.evaluate(exprStr: spec.hExpr, W: W, H: H, x: x, y: y, w: w, h: h) { globalFrame = CGRect(x: nx + X, y: ny + Y, width: nw, height: nh) } } } func activateWithOptions(_ options: NSApplicationActivationOptions) { app.activate(options: options) } func screen() -> NSScreen? { guard let screens = NSScreen.screens(), let screenFrame = globalFrame else { return nil } var result: NSScreen? = nil var area: CGFloat = 0 for screen in screens { let overlap = screen.frame.intersection(screenFrame) if overlap.width * overlap.height > area { area = overlap.width * overlap.height result = screen } } return result } var appTitle: String? { get { guard CFGetTypeID(appElement) == AXUIElementGetTypeID() else { return nil } var result: AnyObject? guard AXUIElementCopyAttributeValue(appElement, kAXTitleAttribute as CFString, &result) == .success else { return nil } return result as? String } } var windowTitle: String? { get { guard CFGetTypeID(windowElement) == AXUIElementGetTypeID() else { return nil } var result: AnyObject? guard AXUIElementCopyAttributeValue(windowElement, kAXTitleAttribute as CFString, &result) == .success else { return nil } return result as? String } } var description: String { get { return "\(String(describing: appTitle)): \(String(describing: windowTitle)) - Frame: \(String(describing: frame))" } } } func +(left: CGPoint, right: CGPoint) -> CGPoint { return CGPoint(x: left.x + right.x, y: left.y + right.y) } func -(left: CGPoint, right: CGPoint) -> CGPoint { return CGPoint(x: left.x - right.x, y: left.y - right.y) }
mit
c572f1ca6de4281c1b38a087688f9cdb
29.755556
126
0.533719
4.873239
false
false
false
false
ainopara/Stage1st-Reader
Stage1st/Manager/DiscuzClient/DiscuzClient.swift
1
2058
// // DiscuzClient.swift // Stage1st // // Created by Zheng Li on 5/8/16. // Copyright © 2016 Renaissance. All rights reserved. // import Alamofire public final class DiscuzClient: NSObject { public let baseURL: String let session: Session public init(baseURL: String, configuration: URLSessionConfiguration) { self.baseURL = baseURL self.session = Session( configuration: configuration, redirectHandler: Redirector(behavior: Redirector.Behavior.modify({ (task, request, response) -> URLRequest? in if task.originalRequest?.url?.absoluteString == request.url?.absoluteString { S1LogWarn("Redirect to self detected! request \(String(describing: task.originalRequest?.url?.absoluteString)) will redirect to \(String(describing: request.url?.absoluteString))") AppEnvironment.current.eventTracker.recordError(NSError( domain: "S1RedirectIssue", code: 0, userInfo: [ "originalRequest": task.originalRequest?.url?.absoluteString ?? "", "currentRequest": task.currentRequest?.url?.absoluteString ?? "", "redirectedTo": request.url?.absoluteString ?? "" ] )) return request } else { S1LogDebug("request \(String(describing: task.originalRequest?.url?.absoluteString)) will redirect to \(String(describing: request.url?.absoluteString))") return request } })) ) super.init() } } extension DiscuzClient { static let loginStatusDidChangeNotification = Notification.Name.init(rawValue: "DiscuzLoginStatusDidChangeNotification") } struct FailureURL: URLConvertible { let message: String init(_ message: String) { self.message = message } func asURL() throws -> URL { throw message } }
bsd-3-clause
a4ac3cb586a03de0ae2fd11ca264569e
35.087719
200
0.590666
5.315245
false
true
false
false
Eonil/ArchiveWatch
modules/ArchiveWatch/ArchiveWatch/ImageWatchUI.swift
1
2012
// // ImageWatchUI.swift // ArchiveWatch // // Created by Hoon H. on 2015/09/30. // Copyright © 2015 Eonil. All rights reserved. // import Foundation import AppKit class ImageWatchUI { init() { } deinit { } /// weak var model: WatchModel? { willSet { if let model = model { model.channel.deregister(ObjectIdentifier(self)) } } didSet { if let model = model { _processSelection() model.channel.register(ObjectIdentifier(self)) { [weak self] in self?._processSignal($0) } } } } /// var viewController: NSViewController { get { return _vc } } /// private let _vc = _VC() private func _processSelection() { do { if let idx = model?.selectionIndex { let name = model!.fileNames[idx] let data = try model!.dataForName(name) _vc.nameLabel.stringValue = name _vc.imageView.image = NSImage(data: data) } else { _vc.nameLabel.stringValue = "" _vc.imageView.image = nil } } catch let error as NSError { _vc.presentError(error) _vc.nameLabel.stringValue = "" _vc.imageView.image = nil } _vc.view.needsLayout = true } private func _processSignal(s: WatchModel.Signal) { switch s { case .SelectionWillChange: break case .SelectionDidChange: _processSelection() } } } private class _VC: NSViewController { let imageView = NSImageView() let nameLabel = NSTextField() private override func loadView() { let v = NSView(frame: NSRect(x: 0, y: 0, width: 800, height: 450)) v.wantsLayer = true view = v } private override func viewDidLoad() { super.viewDidLoad() nameLabel.bordered = false nameLabel.editable = false imageView.imageScaling = NSImageScaling.ScaleProportionallyUpOrDown view.addSubview(imageView) // view.addSubview(nameLabel) } private override func viewDidLayout() { super.viewDidLayout() imageView.frame = view.bounds nameLabel.sizeToFit() nameLabel.center = view.bounds.midPoint.pixelGridFittingPointForView(view) } }
mit
048976ae7e1327da016df59a93b2813b
16.79646
94
0.666832
3.014993
false
false
false
false
ipmobiletech/firefox-ios
Client/Frontend/Settings/Clearables.swift
1
7064
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import WebKit // A base protocol for something that can be cleared. protocol Clearable { func clear() -> Success var label: String { get } } class ClearableError: MaybeErrorType { private let msg: String init(msg: String) { self.msg = msg } var description: String { return msg } } // Clears our browsing history, including favicons and thumbnails. class HistoryClearable: Clearable { let profile: Profile init(profile: Profile) { self.profile = profile } var label: String { return NSLocalizedString("Browsing History", comment: "Settings item for clearing browsing history") } func clear() -> Success { return profile.history.clearHistory().bind { success in SDImageCache.sharedImageCache().clearDisk() SDImageCache.sharedImageCache().clearMemory() NSNotificationCenter.defaultCenter().postNotificationName(NotificationPrivateDataClearedHistory, object: nil) return Deferred(value: success) } } } // Clear all stored passwords. This will clear both Firefox's SQLite storage and the system shared // Credential storage. class PasswordsClearable: Clearable { let profile: Profile init(profile: Profile) { self.profile = profile } var label: String { return NSLocalizedString("Saved Logins", comment: "Settings item for clearing passwords and login data") } func clear() -> Success { // Clear our storage return profile.logins.removeAll() >>== { res in let storage = NSURLCredentialStorage.sharedCredentialStorage() let credentials = storage.allCredentials for (space, credentials) in credentials { for (_, credential) in credentials { storage.removeCredential(credential, forProtectionSpace: space) } } return succeed() } } } struct ClearableErrorType: MaybeErrorType { let err: ErrorType init(err: ErrorType) { self.err = err } var description: String { return "Couldn't clear: \(err)." } } // Clear the web cache. Note, this has to close all open tabs in order to ensure the data // cached in them isn't flushed to disk. class CacheClearable: Clearable { let tabManager: TabManager init(tabManager: TabManager) { self.tabManager = tabManager } var label: String { return NSLocalizedString("Cache", comment: "Settings item for clearing the cache") } func clear() -> Success { if #available(iOS 9.0, *) { let dataTypes = Set([WKWebsiteDataTypeDiskCache, WKWebsiteDataTypeMemoryCache]) WKWebsiteDataStore.defaultDataStore().removeDataOfTypes(dataTypes, modifiedSince: NSDate.distantPast(), completionHandler: {}) } else { // First ensure we close all open tabs first. tabManager.removeAll() // Reset the process pool to ensure no cached data is written back tabManager.resetProcessPool() // Remove the basic cache. NSURLCache.sharedURLCache().removeAllCachedResponses() // Now let's finish up by destroying our Cache directory. do { try deleteLibraryFolderContents("Caches") } catch { return deferMaybe(ClearableErrorType(err: error)) } } return succeed() } } private func deleteLibraryFolderContents(folder: String) throws { let manager = NSFileManager.defaultManager() let library = manager.URLsForDirectory(NSSearchPathDirectory.LibraryDirectory, inDomains: .UserDomainMask)[0] let dir = library.URLByAppendingPathComponent(folder) let contents = try manager.contentsOfDirectoryAtPath(dir.path!) for content in contents { try manager.removeItemAtURL(dir.URLByAppendingPathComponent(content)) } } private func deleteLibraryFolder(folder: String) throws { let manager = NSFileManager.defaultManager() let library = manager.URLsForDirectory(NSSearchPathDirectory.LibraryDirectory, inDomains: .UserDomainMask)[0] let dir = library.URLByAppendingPathComponent(folder) try manager.removeItemAtURL(dir) } // Removes all app cache storage. class SiteDataClearable: Clearable { let tabManager: TabManager init(tabManager: TabManager) { self.tabManager = tabManager } var label: String { return NSLocalizedString("Offline Website Data", comment: "Settings item for clearing website data") } func clear() -> Success { if #available(iOS 9.0, *) { let dataTypes = Set([WKWebsiteDataTypeOfflineWebApplicationCache]) WKWebsiteDataStore.defaultDataStore().removeDataOfTypes(dataTypes, modifiedSince: NSDate.distantPast(), completionHandler: {}) } else { // First, close all tabs to make sure they don't hold anything in memory. tabManager.removeAll() // Then we just wipe the WebKit directory from our Library. do { try deleteLibraryFolder("WebKit") } catch { return deferMaybe(ClearableErrorType(err: error)) } } return succeed() } } // Remove all cookies stored by the site. This includes localStorage, sessionStorage, and WebSQL/IndexedDB. class CookiesClearable: Clearable { let tabManager: TabManager init(tabManager: TabManager) { self.tabManager = tabManager } var label: String { return NSLocalizedString("Cookies", comment: "Settings item for clearing cookies") } func clear() -> Success { if #available(iOS 9.0, *) { let dataTypes = Set([WKWebsiteDataTypeCookies, WKWebsiteDataTypeLocalStorage, WKWebsiteDataTypeSessionStorage, WKWebsiteDataTypeWebSQLDatabases, WKWebsiteDataTypeIndexedDBDatabases]) WKWebsiteDataStore.defaultDataStore().removeDataOfTypes(dataTypes, modifiedSince: NSDate.distantPast(), completionHandler: {}) } else { // First close all tabs to make sure they aren't holding anything in memory. tabManager.removeAll() // Now we wipe the system cookie store (for our app). let storage = NSHTTPCookieStorage.sharedHTTPCookieStorage() if let cookies = storage.cookies { for cookie in cookies { storage.deleteCookie(cookie) } } // And just to be safe, we also wipe the Cookies directory. do { try deleteLibraryFolderContents("Cookies") } catch { return deferMaybe(ClearableErrorType(err: error)) } } return succeed() } }
mpl-2.0
cc6c6ece9b3d2f77d0f61ce018ab98b5
33.130435
194
0.650764
5.392366
false
false
false
false
ReactiveCocoa/EditableProperty
EditableProperty/Committed.swift
1
1840
import Box import ReactiveCocoa /// Represents a committed change to the value of an EditableProperty. public enum Committed<Value, ValidationError: ErrorType> { /// The change is an automatic update to a new default value. case DefaultValue(Box<Value>) /// The change is a new value that has been explicitly set _without_ an /// editor. /// /// This might occur from setting `value` directly, or by explicitly binding /// signals, producers, or other properties to the EditableProperty. case ExplicitUpdate(Box<Value>) /// The value was validated and committed by the given editor. case ValidatedEdit(Box<Value>, Editor<Value, ValidationError>) /// The value that was committed. public var value: Value { switch self { case let .DefaultValue(value): return value.value case let .ExplicitUpdate(value): return value.value case let .ValidatedEdit(value, _): return value.value } } /// Whether this change represents a user-initiated edit. public var isEdit: Bool { switch self { case .ValidatedEdit: return true case .DefaultValue, .ExplicitUpdate: return false } } } public func == <Value: Equatable, ValidationError> (lhs: Committed<Value, ValidationError>, rhs: Committed<Value, ValidationError>) -> Bool { switch (lhs, rhs) { case (.DefaultValue, .DefaultValue), (.ExplicitUpdate, .ExplicitUpdate): return lhs.value == rhs.value case let (.ValidatedEdit(_, left), .ValidatedEdit(_, right)): return left === right && lhs.value == rhs.value default: return false } } extension Committed: Printable { public var description: String { let value = self.value switch self { case .DefaultValue: return "DefaultValue(\(value))" case .ExplicitUpdate: return "ExplicitUpdate(\(value))" case .ValidatedEdit: return "ValidatedEdit(\(value))" } } }
mit
a3f11b63bc5bb6d5985d3021d312043c
24.205479
141
0.71087
3.873684
false
false
false
false
KrishMunot/swift
test/ClangModules/ctypes_parse_union.swift
10
1762
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -parse -verify %s import ctypes func useStructWithUnion(_ vec: GLKVector4) -> GLKVector4 { var vec = vec _ = vec.v.0 _ = vec.v.1 _ = vec.v.2 _ = vec.v.3 vec.v = (0, 0, 0, 0) } func useUnionIndirectFields(_ vec: GLKVector4) -> GLKVector4 { // TODO: Make indirect fields from anonymous structs in unions // accessible. // Anonymous indirect fields let x: CFloat = vec.x // expected-error{{}} let y: CFloat = vec.y // expected-error{{}} let z: CFloat = vec.z // expected-error{{}} let w: CFloat = vec.w // expected-error{{}} let r: CFloat = vec.r // expected-error{{}} let g: CFloat = vec.g // expected-error{{}} let b: CFloat = vec.b // expected-error{{}} let a: CFloat = vec.a // expected-error{{}} let s: CFloat = vec.s // expected-error{{}} let t: CFloat = vec.t // expected-error{{}} let p: CFloat = vec.p // expected-error{{}} let q: CFloat = vec.q // expected-error{{}} // Named indirect fields let v0: CFloat = vec.v.0 let v1: CFloat = vec.v.1 let v2: CFloat = vec.v.2 let v3: CFloat = vec.v.3 return vec } func useStructWithNamedUnion(_ u: NamedUnion) -> NamedUnion { var u1 = NamedUnion() u1.a = u.a u1.b = u.b u1.intfloat = u.intfloat return u1 } func useStructWithAnonymousUnion(_ u: AnonUnion) -> AnonUnion { // TODO: Make union indirect fields from anonymous structs in unions // accessible. let a: CFloat = u.a // expected-error{{}} let b: CFloat = u.b // expected-error{{}} let c: CFloat = u.c // expected-error{{}} let d: CFloat = u.d // expected-error{{}} let x: CInt = u.x return u } func useStructWithUnnamedUnion(_ u: UnnamedUnion) -> UnnamedUnion { var u = u u.u.i = 100 u.u.f = 1.0 }
apache-2.0
42a8ee55f6bde757486ac083d88627fc
26.107692
79
0.624858
3.096661
false
false
false
false
klesh/cnodejs-swift
CNode/Topic/TopicDetailReplyCell.swift
1
2628
// // TopicDetailReplyCell.swift // CNode // // Created by Klesh Wong on 1/5/16. // Copyright © 2016 Klesh Wong. All rights reserved. // import UIKit import SwiftyJSON protocol DetailCellButtonsDelegate: class { func thumbUpTapped(id: String, cell: TopicDetailReplyCell) func replyToTapped(id: String, cell: TopicDetailReplyCell) } class TopicDetailReplyCell: UITableViewCell { weak var delegate: DetailCellButtonsDelegate? @IBOutlet weak var avatar: UIButton! @IBOutlet weak var author: UILabel! @IBOutlet weak var create_before: UILabel! @IBOutlet weak var ups_count: UILabel! @IBOutlet weak var content: CNWebView! @IBOutlet weak var up: UIButton! @IBOutlet weak var reply: UIButton! var id: String! override func awakeFromNib() { super.awakeFromNib() // Initialization code // 设定 顶 和 回复 font icon,可以自由设定颜色和大小,多科学。 // 这里用了 FontAwesome ,官网有 cheatsheet 可以查到 code 的值。也比较方便,不然管理一大把的 icon 也是个麻烦事 // 引入方式:把 fontawesome-webfont.ttf 拖放到工程中,在 Info.plist 加一行 Fonts provided by application (Array型) // 再 Item N 中加一个 fontawesome-webfont.ttf 就可以了。那编辑器真是难用!很容易点错。其实整个 xcdoe 真是难用得一逼。 Utils.fontAwesome(up, code: 0xf164, size: 20) Utils.fontAwesome(reply, code: 0xf112, size: 20) } func bind(reply: JSON, row: Int) { id = reply["id"].stringValue Utils.circleUp(avatar) avatar.kf_setImageWithURL(Utils.toURL(reply["author"]["avatar_url"].stringValue), forState: .Normal) author.text = "\(row + 1)楼 " + reply["author"]["loginname"].stringValue create_before.text = Utils.relativeTillNow(reply["create_at"].stringValue.toDateFromISO8601()) ups_count.text = String(reply["ups"].arrayValue.count) content.loadHTMLAsPageOnce(reply["content"].stringValue, baseURL: ApiClient.BASE_URL) } @IBAction func avatarTapped(sender: AnyObject) { AppDelegate.app.drawer.presentViewController(UserViewController.create(author.text!), animated: true, completion: nil) } @IBAction func upTapped(sender: AnyObject) { if let d = delegate { d.thumbUpTapped(id, cell: self) } } @IBAction func replyTapped(sender: AnyObject) { if let d = delegate { d.replyToTapped(id, cell: self) } } }
apache-2.0
8a56f3f2bac0011f975092eee445db5e
32.277778
126
0.65762
3.771654
false
false
false
false
STShenZhaoliang/STWeiBo
STWeiBo/STWeiBo/Classes/Newfeature/WelcomeViewController.swift
1
2979
// // WelcomeViewController.swift // STWeiBo // // Created by ST on 15/11/16. // Copyright © 2015年 ST. All rights reserved. // import UIKit import SDWebImage class WelcomeViewController: UIViewController { /// 记录底部约束 var bottomCons: NSLayoutConstraint? override func viewDidLoad() { super.viewDidLoad() // 1.添加子控件 view.addSubview(bgIV) view.addSubview(iconView) view.addSubview(messageLabel) // 2.布局子控件 bgIV.ST_Fill(view) let cons = iconView.ST_AlignInner(type: ST_AlignType.BottomCenter, referView: view, size: CGSize(width: 100, height: 100), offset: CGPoint(x: 0, y: -150)) // 拿到头像的底部约束 bottomCons = iconView.ST_Constraint(cons, attribute: NSLayoutAttribute.Bottom) messageLabel.ST_AlignVertical(type: ST_AlignType.BottomCenter, referView: iconView, size: nil, offset: CGPoint(x: 0, y: 20)) // 3.设置用户头像 if let iconUrl = UserAccount.loadAccount()?.avatar_large { let url = NSURL(string: iconUrl)! iconView.sd_setImageWithURL(url) } } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) bottomCons?.constant = -UIScreen.mainScreen().bounds.height - bottomCons!.constant print(-UIScreen.mainScreen().bounds.height) print(bottomCons!.constant) // -736.0 + 586.0 = -150.0 print(-UIScreen.mainScreen().bounds.height - bottomCons!.constant) // 3.执行动画 UIView.animateWithDuration(2, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 1, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in // 头像动画 self.iconView.layoutIfNeeded() }) { (_) -> Void in // 文本动画 UIView.animateWithDuration( 2.0, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 1, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in self.messageLabel.alpha = 1.0 }, completion: { (_) -> Void in NSNotificationCenter.defaultCenter().postNotificationName(STSwitchRootViewControllerKey, object: true) }) } } // MARK: -懒加载 private lazy var bgIV: UIImageView = UIImageView(image: UIImage(named: "ad_background")) private lazy var iconView: UIImageView = { let iv = UIImageView(image: UIImage(named: "avatar_default_big")) iv.layer.cornerRadius = 50 iv.clipsToBounds = true return iv }() private lazy var messageLabel: UILabel = { let label = UILabel() label.text = "欢迎回来" label.sizeToFit() label.alpha = 0.0 return label }() }
mit
02490888a7ba4faa6c71cac477effe40
33.650602
189
0.59388
4.646204
false
false
false
false
AlexIzh/Griddle
CollectionPresenter/UI/CustomView/ItemsView/ItemsViewPresenter.swift
1
3100
// // ItemsViewPresenter.swift // CollectionPresenter // // Created by Alex on 22/03/16. // Copyright © 2016 Moqod. All rights reserved. // import Foundation import Griddle import UIKit class ItemsViewPresenter<DataSourceModel: DataSource>: Presenter<DataSourceModel> { let view: ItemsView init(_ view: ItemsView, source: DataSourceModel, map: Map) { self.view = view super.init(source: source, map: map) view.delegate = self view.dataSource = self } open override func dataSourceDidRefresh(_: DataSourceModel) { view.reloadData() } open override func dataSource(_ dataSource: DataSourceModel, didMoveItemFrom from: Griddle.IndexPath, to: Griddle.IndexPath) { switch (from, to) { case (.item(_, let item), .item(_, let toItem)): view.moveItem(from: item, to: toItem) default: break } } open override func dataSource(_ dataSource: DataSourceModel, didDeleteItemAt indexPath: Griddle.IndexPath) { if case .item(_, let index) = indexPath { view.deleteItem(at: index) } } open override func dataSource(_ dataSource: DataSourceModel, didInsertItemAt indexPath: Griddle.IndexPath) { if case .item(_, let index) = indexPath { view.insertItem(at: index) } } open override func dataSource(_ dataSource: DataSourceModel, didUpdateItemAt indexPath: Griddle.IndexPath) { if case .item(_, let index) = indexPath { view.reloadItem(at: index) } } } extension ItemsViewPresenter: ItemsViewDelegate, ItemsViewDataSource { func sizeForItem(at index: Int) -> CGSize { guard let row = dataSource.item(at: 0, index: index) else { return .zero } let info = map.viewInfo(for: row, indexPath: .item(section: 0, item: index)) return info?.size(row, view) ?? .zero } func numberOfItems(in view: ItemsView) -> Int { return dataSource.itemsCount(for: 0) } func viewForItem(at index: Int) -> ItemView { guard let row = dataSource.item(at: 0, index: index), let info = map.viewInfo(for: row, indexPath: .item(section: 0, item: index)) else { fatalError("DataSource doesn't contains item for index = \(index) or map doesn't contain information for this item.") } /* You can add logic with registration of class and identifier like in UITableView or UICollectionView. For simple example I just create hardcoded view. */ let view = ItemView() info.setModel(view, row) delegate.didUpdateCell(view, row, (0, index)) return view } func coordinatesForItem(at index: Int) -> CGPoint { guard let row = dataSource.item(at: 0, index: index) as? ItemsViewSourceFactory.Model else { fatalError("dataSource doesn't contain item for \(index) or this item with incorrect type.") } return row.position } func view(_ view: ItemsView, didSelectItemAt index: Int) { guard let row = dataSource.item(at: 0, index: index) else { return } delegate.didSelectCell(view.view(for: index), row, (0, index)) } }
mit
5e6689237600f45da20206fe6267525d
31.28125
136
0.664408
4.239398
false
false
false
false
noxytrux/KnightWhoSaidSwift
KnightWhoSaidSwift/KWSPlayer.swift
1
14429
// // KWSPlayer.swift // KnightWhoSaidSwift // // Created by Marcin Pędzimąż on 20.09.2014. // Copyright (c) 2014 Marcin Pedzimaz. All rights reserved. // import SpriteKit var kKWSSharedAssetsOnceToken: dispatch_once_t = 0 var KWSSharedIdleAnimationFrames = [SKTexture]() var KWSSharedWalkAnimationFrames = [SKTexture]() var KWSSharedAttackAnimationFrames = [SKTexture]() var KWSSharedJumpAnimationFrames = [SKTexture]() var KWSSharedDeathAnimationFrames = [SKTexture]() var KWSSharedDefenseAnimationFrames = [SKTexture]() let kKWSPlayerScale : CGFloat! = 4 let kKWSMaxPlayerMovement : CGFloat = 200 //MARK: player animation keys let kKWSMoveActionKey : String! = "moving_key" let kKWSJumpActionKey : String! = "jump_key" let kKWSWalkKey : String! = "anim_walk" let kKWSAttackKey : String! = "anim_attack" let kKWSDeadKey : String! = "anim_death" let kKWSIdleKey : String! = "anim_idle" let kKWSJumpKey : String! = "anim_jump" let kKWSDefenseKey : String! = "anim_defense" var KWSSharedSmokeEmitter = SKEmitterNode() var KWSSharedBloodEmitter = SKEmitterNode() var KWSSharedSparcleEmitter = SKEmitterNode() protocol KWSPlayerDelegate: class { func playerDidDied() } class KWSPlayer: SKSpriteNode { weak var delegate : KWSPlayerDelegate? private var healtBar : KWSHealtBar! private var animationSpeed: CGFloat = 0.1 private var animated = true private var attacking = false private var dying = false private var requestedAnimation = KWSActionType.IdleAction private var mirrorDirection : SKAction = SKAction.scaleXTo(-kKWSPlayerScale, y: kKWSPlayerScale, duration: 0.0) private var resetDirection : SKAction = SKAction.scaleXTo(kKWSPlayerScale, y: kKWSPlayerScale, duration: 0.0) private var movingSound : Bool = false internal var touchesGround : Bool = false internal var moveButtonActive : Bool = false internal var defenseButtonActive : Bool = false internal var movingLeft : Bool = false internal var externalControl : Bool = false internal var healt : Int8 = 100 //MARK: init init(atPosition position: CGPoint, redPlayer: Bool) { let atlas = SKTextureAtlas(named: "walk") let texture = atlas.textureNamed("walk_prefix_1.png") let size = CGSize(width: 32, height: 32) super.init(texture: texture, color: SKColor.whiteColor(), size: size) self.position = position configurePhysicsBody() xScale = kKWSPlayerScale yScale = kKWSPlayerScale zRotation = CGFloat(0) zPosition = -0.25 name = "Player" //if it is red player add Shader that will color it if redPlayer { applyRedShader() } self.healtBar = KWSHealtBar() self.healtBar.updateProgress(progress: 1.0) self.addChild(self.healtBar) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } //MARK: helper method var playerScene: KWSGameScene { return self.scene as! KWSGameScene } func resetPlayer() { healt = 100 dying = false animated = true requestedAnimation = .IdleAction self.healtBar.updateProgress(progress: 1.0) } //MARK: shader assets loading class func loadSharedAssets() { dispatch_once(&kKWSSharedAssetsOnceToken) { KWSSharedIdleAnimationFrames = loadFramesFromAtlasWithName("walk", baseFileName: "walk", numberOfFrames: 1) KWSSharedWalkAnimationFrames = loadFramesFromAtlasWithName("walk", baseFileName: "walk", numberOfFrames: 3) KWSSharedAttackAnimationFrames = loadFramesFromAtlasWithName("attack", baseFileName: "attack", numberOfFrames: 4) KWSSharedJumpAnimationFrames = loadFramesFromAtlasWithName("jump", baseFileName: "jump", numberOfFrames: 3) KWSSharedDeathAnimationFrames = loadFramesFromAtlasWithName("die", baseFileName: "dead", numberOfFrames: 5) KWSSharedDefenseAnimationFrames = loadFramesFromAtlasWithName("defense", baseFileName: "defense", numberOfFrames: 1) KWSSharedSmokeEmitter = .sharedSmokeEmitter() KWSSharedBloodEmitter = .sharedBloodEmitter() KWSSharedSparcleEmitter = .sharedSparkleEmitter() } } func applyRedShader() { let playerShader = SKShader(fileNamed: "Shader.fsh") self.shader = playerShader } //MARK: game logic func configurePhysicsBody() { physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(20, 20), center: CGPointMake(0, -6)) if let physicsBody = physicsBody { physicsBody.categoryBitMask = ColliderType.Player.rawValue physicsBody.collisionBitMask = ColliderType.Wall.rawValue | ColliderType.Ground.rawValue physicsBody.contactTestBitMask = ColliderType.Wall.rawValue | ColliderType.Ground.rawValue | ColliderType.Player.rawValue physicsBody.allowsRotation = false physicsBody.dynamic = true } } func applyDamage(damage: Int) { if !animated { return } if damage != 0 { KWSGameAudioManager.sharedInstance.playSound(soundNumber: KWSActionType.HitAction.rawValue ) let emitter = KWSSharedBloodEmitter.copy() as! SKEmitterNode emitter.position = self.position playerScene.addNode(emitter, atWorldLayer: .foliage) runOneShotEmitter(emitter, withDuration: 0.15) } healt -= damage self.healtBar.updateProgress(progress: CGFloat(Float(healt)/100.0) ) if healt <= 0 { healt = 0 KWSGameAudioManager.sharedInstance.playSound(soundNumber: KWSActionType.DieAction.rawValue ) dying = true } } func collidedWith(enemy: KWSPlayer) { let ownFrame = CGRectInset(self.frame, -20, 0) let enemyFrame = CGRectInset(enemy.frame, -20, 0) let distance = self.position.x - enemy.position.x var canDefense = false if distance == 0 { canDefense = true } else if distance < 0 { canDefense = !self.movingLeft && enemy.movingLeft } else if distance > 0 { canDefense = self.movingLeft && !enemy.movingLeft } if CGRectIntersectsRect(ownFrame, enemyFrame) { if enemy.defenseButtonActive && canDefense { let emitter = KWSSharedSparcleEmitter.copy() as! SKEmitterNode emitter.position = CGPointMake(enemy.position.x, enemy.position.y - enemy.size.height * 0.3) emitter.xAcceleration = movingLeft ? 1000 : -1000 playerScene.addNode(emitter, atWorldLayer: .foliage) runOneShotEmitter(emitter, withDuration: 0.15) KWSGameAudioManager.sharedInstance.playSound(soundNumber: KWSActionType.DefenseAction.rawValue ) return } if !dying && attacking { enemy.applyDamage(20) } } } //MARK: Update func updateWithTimeSinceLastUpdate(interval: NSTimeInterval) { if !dying && !animated { return } resolveRequestedAnimation() } //MARK: Animations func resolveRequestedAnimation() { let (frames, key) = animationFramesAndKeyForState(requestedAnimation) fireAnimationForState(requestedAnimation, usingTextures: frames, withKey: key) } func animationFramesAndKeyForState(state: KWSActionType) -> ([SKTexture], String) { switch state { case .WalkAction: return (KWSSharedWalkAnimationFrames, kKWSWalkKey) case .AttackAction: return (KWSSharedAttackAnimationFrames, kKWSAttackKey) case .DieAction: return (KWSSharedDeathAnimationFrames, kKWSDeadKey) case .IdleAction: return (KWSSharedIdleAnimationFrames, kKWSIdleKey) case .JumpAction: return (KWSSharedJumpAnimationFrames, kKWSJumpKey) case .DefenseAction: return (KWSSharedDefenseAnimationFrames, kKWSDefenseKey) default: return ([SKTexture](),"unknown") } } func fireAnimationForState(animationState: KWSActionType, usingTextures frames: [SKTexture], withKey key: String) { let animAction = actionForKey(key) if animAction != nil || frames.count < 1 { return } let animationAction = SKAction.animateWithTextures(frames, timePerFrame: NSTimeInterval(animationSpeed), resize: true, restore: false) let blockAction = SKAction.runBlock { self.animationHasCompleted(animationState) } let animateWithDirection : SKAction = movingLeft ? SKAction.group([mirrorDirection, animationAction]) : SKAction.group([resetDirection, animationAction]) runAction(SKAction.sequence([animateWithDirection, blockAction]), withKey: key) } func animationHasCompleted(animationState: KWSActionType) { if dying && animated { requestedAnimation = .DieAction animated = false } animationDidComplete(animationState) if !animated { return } if attacking && (animationState == KWSActionType.AttackAction) { attacking = false } if self.defenseButtonActive { requestedAnimation = .DefenseAction return } let actionMove = actionForKey(kKWSMoveActionKey) var endJumping = self.touchesGround if self.touchesGround == false && (animationState == KWSActionType.JumpAction) { endJumping = true } if !attacking && actionMove == nil && endJumping { requestedAnimation = .IdleAction } } func animationDidComplete(animation: KWSActionType) { switch animation { case .DieAction: let action = SKAction.runBlock{ self.dying = false self.notifyPlayerDied() } runAction(action) default: () } } func notifyPlayerDied() { self.delegate?.playerDidDied() } //MARK: player actions func lockedWalkSound() { if externalControl { return } if movingSound { return } movingSound = true KWSGameAudioManager.sharedInstance.playSound(soundNumber: KWSActionType.WalkAction.rawValue ) let runAfter : dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(1.0 * Double(NSEC_PER_SEC))) dispatch_after(runAfter, dispatch_get_main_queue()) { () -> Void in self.movingSound = false } } func playerMoveLeft() { if !animated { return } lockedWalkSound() movingLeft = true self.physicsBody?.velocity.dx = -kKWSMaxPlayerMovement let action: SKAction = SKAction.waitForDuration(0.1) requestedAnimation = .WalkAction let moveFinishAction = SKAction.runBlock { if self.moveButtonActive { self.playerMoveLeft() } else { self.physicsBody?.velocity.dy = 0 } } runAction(SKAction.sequence([action, moveFinishAction]), withKey: kKWSMoveActionKey) } func playerMoveRight() { if !animated { return } lockedWalkSound() movingLeft = false self.physicsBody?.velocity.dx = kKWSMaxPlayerMovement let action: SKAction = SKAction.waitForDuration(0.1) requestedAnimation = .WalkAction let moveFinishAction = SKAction.runBlock { if self.moveButtonActive { self.playerMoveRight() } else { self.physicsBody?.velocity.dy = 0 } } runAction(SKAction.sequence([action, moveFinishAction]), withKey: kKWSMoveActionKey) } func playerJump() { if !animated { return } if self.touchesGround { if !externalControl { KWSGameAudioManager.sharedInstance.playSound(soundNumber: KWSActionType.JumpAction.rawValue) } self.touchesGround = false let impulseY : CGFloat = 15.0 self.physicsBody!.applyImpulse(CGVectorMake(0, impulseY), atPoint: self.position) requestedAnimation = .JumpAction } } func playerAttack() { if !animated { return } if attacking { return } if !externalControl { KWSGameAudioManager.sharedInstance.playSound(soundNumber: KWSActionType.AttackAction.rawValue ) } attacking = true requestedAnimation = .AttackAction } func playerDefense() { if !animated { return } requestedAnimation = .DefenseAction } }
mit
c67873dce479d1b40d5e9f7e7198269d
27.397638
161
0.573409
5.508209
false
false
false
false
SoCM/iOS-FastTrack-2014-2015
04-App Architecture/Swift 4/Breadcrumbs/Breadcrumbs-4/Breadcrumbs/BCOptionsTableViewController.swift
3
2896
// // BCOptionsTableViewController.swift // Breadcrumbs // // Created by Nicholas Outram on 22/01/2016. // Copyright © 2016 Plymouth University. All rights reserved. // import UIKit class BCOptionsTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
44c27ec10b692e8bb555e896898f30b0
32.662791
157
0.689465
5.610465
false
false
false
false
andrewcar/pictures
Project/pictures/pictures/PageViewController.swift
1
2426
// // PageViewController.swift // pictures // // Created by Andrew Carvajal on 12/2/16. // Copyright © 2016 YugeTech. All rights reserved. // import UIKit class PageViewController: UIPageViewController { private(set) lazy var orderedViewControllers: [UIViewController] = { return [self.newViewController(name: "camera"), self.newViewController(name: "feed")] }() private func newViewController(name: String) -> UIViewController { return UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "\(name)ViewController") } override func viewDidLoad() { super.viewDidLoad() dataSource = self if let firstViewController = orderedViewControllers.first { setViewControllers([firstViewController], direction: .forward, animated: true, completion: nil) } } } // MARK: UINavigationControllerDelegate extension PageViewController: UINavigationControllerDelegate {} // MARK: UIPageViewControllerDataSource extension PageViewController: UIPageViewControllerDataSource { func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { guard let viewControllerIndex = orderedViewControllers.index(of: viewController) else { return nil } let previousIndex = viewControllerIndex - 1 guard previousIndex >= 0 else { return nil } guard orderedViewControllers.count > previousIndex else { return nil } return orderedViewControllers[previousIndex] } func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { guard let viewControllerIndex = orderedViewControllers.index(of: viewController) else { return nil } let nextIndex = viewControllerIndex + 1 let orderedViewControllersCount = orderedViewControllers.count guard orderedViewControllersCount != nextIndex else { return nil } guard orderedViewControllersCount > nextIndex else { return nil } return orderedViewControllers[nextIndex] } }
mit
d2f22400e6b419cbd422e8049576a816
29.3125
149
0.660619
6.625683
false
false
false
false
LeoNatan/LNPopupController
LNPopupControllerExample/LNPopupControllerExample/DemoAlbumTableViewController.swift
1
4871
// // DemoAlbumTableViewController.swift // LNPopupControllerExample // // Created by Leo Natan on 8/7/15. // Copyright © 2015 Leo Natan. All rights reserved. // import UIKit #if LNPOPUP import LNPopupController #endif import LoremIpsum class DemoAlbumTableViewController: UITableViewController { @IBOutlet var demoAlbumImageView: UIImageView! var images: [UIImage] var titles: [String] var subtitles: [String] required init?(coder aDecoder: NSCoder) { images = [] titles = [] subtitles = [] super.init(coder:aDecoder) } override func viewDidLoad() { tabBarController?.view.tintColor = view.tintColor super.viewDidLoad() let backgroundImageView = UIImageView(image: UIImage(named: "demoAlbum")) backgroundImageView.autoresizingMask = [.flexibleWidth, .flexibleHeight] backgroundImageView.contentMode = .scaleAspectFill let backgroundEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .systemThinMaterial)) backgroundEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] let container = UIView(frame: tableView.bounds) container.autoresizingMask = [.flexibleWidth, .flexibleHeight] backgroundImageView.frame = container.bounds backgroundEffectView.frame = container.bounds container.addSubview(backgroundImageView) container.addSubview(backgroundEffectView) tableView.backgroundView = container tableView.separatorEffect = UIVibrancyEffect(blurEffect: UIBlurEffect(style: .systemThinMaterial)) #if LNPOPUP tabBarController?.popupBar.barStyle = LNPopupBarStyle(rawValue: UserDefaults.standard.object(forKey: PopupSettingsBarStyle) as? Int ?? 0)! #endif let appearance = UINavigationBarAppearance() appearance.configureWithTransparentBackground() #if compiler(>=5.5) if #available(iOS 15.0, *) { navigationItem.compactScrollEdgeAppearance = appearance } #endif navigationItem.scrollEdgeAppearance = appearance let appearance2 = UINavigationBarAppearance() appearance2.configureWithDefaultBackground() navigationItem.compactAppearance = appearance2 navigationItem.standardAppearance = appearance2 demoAlbumImageView.layer.cornerCurve = .continuous demoAlbumImageView.layer.cornerRadius = 8 demoAlbumImageView.layer.masksToBounds = true for idx in 1...self.tableView(tableView, numberOfRowsInSection: 0) { images += [UIImage(named: "genre\(idx)")!] titles += [LoremIpsum.title] subtitles += [LoremIpsum.sentence] } } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 30 } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 2 } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let separator = UIView(frame: CGRect(x: view.layoutMargins.left, y: 0, width: tableView.bounds.size.width - view.layoutMargins.left, height: 1 / UIScreen.main.scale)) separator.backgroundColor = .separator separator.autoresizingMask = .flexibleWidth let view = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: 2)) view.addSubview(separator) return view } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "MusicCell", for: indexPath) cell.imageView?.image = images[(indexPath as NSIndexPath).row] cell.textLabel?.text = titles[(indexPath as NSIndexPath).row] cell.detailTextLabel?.text = subtitles[(indexPath as NSIndexPath).row] return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { #if LNPOPUP let popupContentController = DemoMusicPlayerController() popupContentController.songTitle = titles[(indexPath as NSIndexPath).row] popupContentController.albumTitle = subtitles[(indexPath as NSIndexPath).row] popupContentController.albumArt = images[(indexPath as NSIndexPath).row] popupContentController.popupItem.accessibilityHint = NSLocalizedString("Double Tap to Expand the Mini Player", comment: "") tabBarController?.popupContentView.popupCloseButton.accessibilityLabel = NSLocalizedString("Dismiss Now Playing Screen", comment: "") // tabBarController?.popupBar.customBarViewController = ManualLayoutCustomBarViewController() tabBarController?.presentPopupBar(withContentViewController: popupContentController, animated: true, completion: nil) tabBarController?.popupBar.imageView.layer.cornerRadius = 3 tabBarController?.popupBar.tintColor = UIColor.label tabBarController?.popupBar.progressViewStyle = .top #endif tableView.deselectRow(at: indexPath, animated: true) } }
mit
59b4a2d7fe3709a62b183d96a15cec8e
35.893939
168
0.768172
4.559925
false
false
false
false
jmieville/ToTheMoonAndBack-PitchPerfect
PitchPerfect/RecordSoundsViewController.swift
1
2858
// // RecordSoundsViewController.swift // PitchPerfect // // Created by Jean-Marc Kampol Mieville on 5/23/2559 BE. // Copyright © 2559 Jean-Marc Kampol Mieville. All rights reserved. // import UIKit import AVFoundation class RecordSoundsViewController: UIViewController, AVAudioRecorderDelegate { //Outlets @IBOutlet weak var recordingLabel: UILabel! @IBOutlet weak var recordButton: UIButton! @IBOutlet weak var stopRecordingButton: UIButton! var audioRecorder: AVAudioRecorder! @IBAction func RecordAudio(sender: AnyObject) { print("record the button") configureRecordingButtons(isRecording: true) let dirPath = NSSearchPathForDirectoriesInDomains(.documentDirectory,.userDomainMask, true)[0] as String let recordingName = "recordedVoice.wav" let pathArray = [dirPath, recordingName] let filePath = NSURL.fileURL(withPathComponents: pathArray) print(filePath!) let session = AVAudioSession.sharedInstance() try! session.setCategory(AVAudioSessionCategoryPlayAndRecord) try! audioRecorder = AVAudioRecorder(url: filePath!, settings: [:]) audioRecorder.delegate = self audioRecorder.isMeteringEnabled = true audioRecorder.prepareToRecord() audioRecorder.record() } @IBAction func StopRecordAudio(sender: AnyObject) { print("stop recording the audio") configureRecordingButtons(isRecording: false) audioRecorder.stop() let audioSession = AVAudioSession.sharedInstance() try! audioSession.setActive(false) } func configureRecordingButtons(isRecording: Bool){ recordingLabel.text = isRecording ? "Recording in progress" : "Tap to record" recordButton.isEnabled = isRecording ? false : true recordingLabel.textColor = isRecording ? UIColor.blue : UIColor.gray stopRecordingButton.isEnabled = isRecording ? true : false } override func viewWillAppear(_ animated: Bool) { print("viewWillAppear called") stopRecordingButton.isEnabled = false } func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) { print("AVAudioRecorder finished saving recording") if (flag) { performSegue(withIdentifier: "stopRecording", sender: audioRecorder.url) } else { print("Saving of recording failed") } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if (segue.identifier == "stopRecording") { let playSoundsVC = segue.destination as! PlaySoundsViewController let recordedAudioURL = sender as! NSURL playSoundsVC.recordedAudioURL = recordedAudioURL } } }
mit
0630743bd58359af88bb04e6e565e596
33.841463
112
0.675184
5.580078
false
false
false
false
hawkfalcon/SpaceEvaders
SpaceEvaders/Utility.swift
1
3404
import SpriteKit struct Utility { static func socialMedia(social: String, score: String) { NotificationCenter.default.post(name: Notification.Name(rawValue: "social"), object: nil, userInfo: ["score": score, "type": "com.apple.social.\(social)"]) } static func skyFullofStars(width: CGFloat, height: CGFloat) -> SKNode { let sky = SKNode() for _ in 1 ... 500 { let rand = Int(arc4random()) % 6 let star = SKSpriteNode(color: UIColor.white, size: CGSize(width: rand, height: rand)) star.position = CGPoint(x: Int(arc4random()) % Int(width), y: Int(arc4random()) % Int(height)) sky.addChild(star) } return sky } static func checkPremium() -> Bool { return Options.option.get(option: "premium") } static func pressButton(main: SKScene, touched: SKNode, score: String) { let size = main.size if let name = touched.name { if name.starts(with: "option") { toggle(option: name, sprite: touched as! SKSpriteNode, main: main) } switch name { case "purchase": NotificationCenter.default.post(name: Notification.Name(rawValue: "premium"), object: nil) case "restore": NotificationCenter.default.post(name: Notification.Name(rawValue: "restore"), object: nil) case "info": Info(size: size).addTo(parent: main) case "twitter": socialMedia(social: "twitter", score: score) case "facebook": socialMedia(social: "facebook", score: score) case "back": let parent = touched.parent if parent?.name == "back" { let superp = parent?.parent superp?.removeFromParent() } else { touched.removeFromParent() parent?.removeFromParent() } case "credits": let parent = touched.parent touched.removeFromParent() parent?.removeFromParent() let howto = Sprite(named: "howto", x: size.width / 2, y: size.height / 2, size: CGSize(width: size.width, height: size.height)) howto.zPosition = 20 howto.addTo(parent: main) case "howto": touched.removeFromParent() case "settings": let parent = touched.parent! as SKNode touched.removeFromParent() let _ = OptionsMenu(menu: parent, size: size) default: break } } } static func toggle(option: String, sprite: SKSpriteNode, main: SKScene) { let opt = option.replacingOccurrences(of: "option_", with: "") if opt == "indicators" || opt == "follow" { if !Options.option.get(option: "premium") { Iapp(size: main.size).addTo(parentNode: main) return } } var next = "on" if Options.option.get(option: opt) { next = "off" } let text = FadeText(x: 0, y: -70, label: "\(opt) \(next)") text.addTo(parent: sprite) sprite.texture = SKTexture(imageNamed: "\(opt)\(next)") Options.option.toggle(option: opt) } }
mit
bba5d3539f4263bc62454d061c7fda5d
38.581395
163
0.530846
4.502646
false
false
false
false
GabrielGhe/SwiftProjects
App3/App3/ViewController.swift
1
2624
// // ViewController.swift // App3 // // Created by Gabriel on 2014-06-19. // Copyright (c) 2014 Gabriel. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { //Variables let tableViewRect = CGRectMake(20, 64, 280, UIScreen.mainScreen().bounds.size.height - 84) let tableView: UITableView = { let tableView = UITableView() return tableView }() let buttonRect = CGRectMake(UIScreen.mainScreen().bounds.size.width - 84, 10, 44, 44) let button: UIButton = { let button = UIButton() return button }() var dataSource = [["one", "two"], ["three"]]; //Funcs override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell") //tableView tableView.frame = tableViewRect tableView.backgroundColor = UIColor.brownColor() self.view.addSubview(tableView) //button button.frame = buttonRect button.backgroundColor = UIColor.blueColor() button.setTitle("+", forState: UIControlState.Normal) self.view.addSubview(button) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfSectionsInTableView(tableView: UITableView!) -> Int { return dataSource.count } func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int { return dataSource[section].count } func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { let cell = tableView!.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath!) as UITableViewCell if let path = indexPath { let currentString = dataSource[path.section][path.row] cell.text = currentString } return cell } func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) { println(indexPath) } func tableView(tableView: UITableView!, titleForHeaderInSection section: Int) -> String! { var toReturn = "" switch(section) { case 0: toReturn = "Not Completed" case 1: toReturn = "Completed" default: toReturn = "" } return toReturn } }
mit
0c2064d4d5867b96eac66f1f33c7ed4b
28.818182
116
0.626524
5.366053
false
false
false
false
multinerd/Mia
Mia/Testing/UINavigationController/NavigationStacks/CollectionView/CollectionViewStackFlowLayout.swift
1
4511
import UIKit class CollectionViewStackFlowLayout: UICollectionViewFlowLayout { // MARK: Init/Deinit init(itemsCount: Int, overlay: Float, scaleRatio: Float, scale: Float) { self.itemsCount = itemsCount self.overlay = overlay self.scaleRatio = scaleRatio self.maxScale = scale super.init() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Variables let itemsCount: Int let overlay: Float // from 0 to 1 let maxScale: Float let scaleRatio: Float var additionScale = 1.0 var openAnimating = false var dxOffset: Float = 0 // MARK: Private Methods override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { let items = NSArray(array: super.layoutAttributesForElements(in: rect)!, copyItems: true) var headerAttributes: UICollectionViewLayoutAttributes? items.enumerateObjects({ (object, idex, stop) -> Void in let attributes = object as! UICollectionViewLayoutAttributes if attributes.representedElementKind == UICollectionElementKindSectionHeader { headerAttributes = attributes } else { self.updateCellAttributes(attributes, headerAttributes: headerAttributes) } }) return items as? [UICollectionViewLayoutAttributes] } override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { return true } // MARK: Helpers func updateCellAttributes(_ attributes: UICollectionViewLayoutAttributes, headerAttributes: UICollectionViewLayoutAttributes?) { guard let collectionView = self.collectionView else { return; } let itemWidth = collectionView.bounds.size.width - collectionView.bounds.size.width * CGFloat(overlay) let allWidth = itemWidth * CGFloat(itemsCount - 1) // set contentOffset range let contentOffsetX = min(max(0, collectionView.contentOffset.x), allWidth) let scale = transformScale(attributes, allWidth: allWidth, offset: contentOffsetX) let move = transformMove(attributes, itemWidth: itemWidth, offset: contentOffsetX) attributes.transform = scale.concatenating(move) attributes.alpha = calculateAlpha(attributes, itemWidth: itemWidth, offset: contentOffsetX) if additionScale > 0 && openAnimating { additionScale -= 0.02 additionScale = additionScale < 0 ? 0 : additionScale } attributes.zIndex = (attributes.indexPath as NSIndexPath).row } fileprivate func transformScale(_ attributes: UICollectionViewLayoutAttributes, allWidth: CGFloat, offset: CGFloat) -> CGAffineTransform { var maximum = CGFloat(maxScale) - CGFloat(itemsCount - (attributes.indexPath as NSIndexPath).row) / CGFloat(scaleRatio) maximum += CGFloat(1.0 - maximum) * CGFloat(additionScale) var minimum = CGFloat(maxScale - 0.1) - CGFloat(itemsCount - (attributes.indexPath as NSIndexPath).row) / CGFloat(scaleRatio) minimum += CGFloat(1.0 - minimum) * CGFloat(additionScale) var currentScale = (maximum + minimum) - (minimum + offset / (allWidth / (maximum - minimum))) currentScale = max(min(maximum, currentScale), minimum) return CGAffineTransform(scaleX: currentScale, y: currentScale) } fileprivate func transformMove(_ attributes: UICollectionViewLayoutAttributes, itemWidth: CGFloat, offset: CGFloat) -> CGAffineTransform { var currentContentOffsetX = offset - itemWidth * CGFloat((attributes.indexPath as NSIndexPath).row) currentContentOffsetX = min(max(currentContentOffsetX, 0), itemWidth) var dx = (currentContentOffsetX / itemWidth) if let collectionView = self.collectionView { dx *= collectionView.bounds.size.width / 8.0 } dx = currentContentOffsetX - dx return CGAffineTransform(translationX: dx, y: 0) } fileprivate func calculateAlpha(_ attributes: UICollectionViewLayoutAttributes, itemWidth: CGFloat, offset: CGFloat) -> CGFloat { var currentContentOffsetX = offset - itemWidth * CGFloat((attributes.indexPath as NSIndexPath).row) currentContentOffsetX = min(max(currentContentOffsetX, 0), itemWidth) let dx = (currentContentOffsetX / itemWidth) return 1.0 - dx } }
mit
d057e5369617ec796b1dc023d885379d
33.174242
142
0.684771
5.603727
false
false
false
false
byvapps/ByvManager-iOS
ByvManager/Classes/OAuthHandler.swift
1
5810
// // OAuth2Handler.swift // Pods // // Created by Adrian Apodaca on 25/10/16. // // import Foundation import Alamofire public class OAuthHandler: RequestAdapter, RequestRetrier { private typealias RefreshCompletion = (_ succeeded: Bool, _ accessToken: String?, _ refreshToken: String?) -> Void private let sessionManager: SessionManager = { let configuration = URLSessionConfiguration.default configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders return SessionManager(configuration: configuration) }() private let lock = NSLock() private var clientID: String private var clientSecret: String private var baseURLString: String private var accessToken: String? private var refreshToken: String? private var isRefreshing = false private var requestsToRetry: [RequestRetryCompletion] = [] // MARK: - Initialization public init() { self.clientID = Configuration.auth("byv_client_id") as! String self.clientSecret = Configuration.auth("byv_client_secret") as! String self.baseURLString = Environment.baseUrl() self.reloadCredentials() NotificationCenter.default.addObserver(self, selector: #selector(self.reloadCredentials), name: ByvNotifications.credUpdated, object: nil) } @objc private func reloadCredentials() { if let cred = Credentials.current() { self.accessToken = cred.access_token self.refreshToken = cred.refresh_token } } // MARK: - RequestAdapter public func adapt(_ urlRequest: URLRequest) throws -> URLRequest { if let token = self.accessToken, let url = urlRequest.url, url.absoluteString.hasPrefix(baseURLString) { var urlRequest = urlRequest urlRequest.setValue("Bearer " + token, forHTTPHeaderField: "Authorization") return urlRequest } return urlRequest } // MARK: - RequestRetrier public func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) { lock.lock() ; defer { lock.unlock() } if let response = request.task?.response as? HTTPURLResponse, response.statusCode == 401 { if ByvManager.debugMode { print("CADUCADO!!!!!") } requestsToRetry.append(completion) if !isRefreshing { refreshTokens { [weak self] succeeded, accessToken, refreshToken in guard let strongSelf = self else { return } if let accessToken = accessToken, let refreshToken = refreshToken { strongSelf.accessToken = accessToken strongSelf.refreshToken = refreshToken } strongSelf.requestsToRetry.forEach { $0(succeeded, 0.0) } strongSelf.requestsToRetry.removeAll() } } } else { completion(false, 0.0) } } // MARK: - Private - Refresh Tokens private func refreshTokens(completion: @escaping RefreshCompletion) { guard !isRefreshing else { if ByvManager.debugMode {print("intento de refresh")}; return } if let refreshToken: String = refreshToken, let accessToken: String = accessToken { isRefreshing = true let urlString = "\(Environment.baseUrl())/\(url_token())/refresh" let parameters: [String: Any] = [ "refreshToken": refreshToken, "client_id": clientID, "client_secret": clientSecret, "accessToken": accessToken, "grant_type": "refresh" ] if ByvManager.debugMode { print(parameters) } var headers: HTTPHeaders? = nil if let dId = Device().deviceId { headers = ["DeviceId": "\(dId)"] } sessionManager.request(urlString, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers) .validate(statusCode: 200..<300) .responseData { response in switch response.result { case .success: if let cred = Credentials.store(response.data) { completion(true, cred.access_token, cred.refresh_token) } else { completion(false, nil, nil) } case .failure(let error): print(error) if ByvManager.debugMode { print("REQUEST REFERSH:\nParams:") dump(parameters) debugPrint(response) print("Data: \(String(describing: String(data: response.data!, encoding: .utf8)))") } if response.response?.statusCode == 401 { //Refresh token invalid ByvAuth.logout() completion(false, nil, nil) } } self.isRefreshing = false } } else { ByvAuth.logout() completion(false, nil, nil) } } }
mit
d00e74a81ebdb31c59bce5ef973c6427
36.727273
140
0.52358
5.862765
false
false
false
false
anfema/Tarpit
src/tarfile.swift
1
6842
// // tarfile.swift // tarpit // // Created by Johannes Schriewer on 26/11/15. // Copyright © 2015 anfema. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the conditions of the 3-clause // BSD license (see LICENSE.txt for full license text) import Foundation open class TarFile { public enum Errors: Error { /// Invalid header encountered case headerParseError /// End of file marker found case endOfFile /// Programming error (called extractFile on streaming mode or consumeData on file mode) case programmingError } fileprivate struct TarFileHeader { var isFile: Bool var filepath: String var filesize: size_t var mtime: Date } fileprivate let streamingMode: Bool // MARK: - File based unpack fileprivate var data: Data! = nil fileprivate var offset: size_t = 0 /// Initialize for unpacking with data /// /// - parameter data: tar file data public init(data: Data) { self.streamingMode = false self.data = data } /// Initialize for unpacking with file name /// /// - parameter fileName: file name to open /// /// - throws: NSData contentsOfURL errors public convenience init(fileName: String) throws { self.init(data: try Data(contentsOf: URL(fileURLWithPath: fileName), options: .mappedIfSafe)) } /// Extract file from disk /// /// - throws: TarFile.Errors /// /// - returns: tuple with filename and data open func extractFile() throws -> (filename: String, mtime: Date, data: Data)? { if streamingMode { throw Errors.programmingError } var fileData : Data? var fileHeader : TarFileHeader? try self.data.withUnsafeBytes { rawBufferPointer -> Void in let dataPtr = rawBufferPointer.bindMemory(to: CChar.self).baseAddress! while true { guard self.offset + 512 < self.data.count else { throw Errors.endOfFile } // parse header info let header = try self.parse(header: dataPtr.advanced(by: self.offset)) var data: Data? = nil if header.filesize > 0 { // copy over data data = Data(bytes: dataPtr.advanced(by: self.offset + 512), count: header.filesize) } // advance offset (512 byte blocks) var size = 0 if header.filesize > 0 { if header.filesize % 512 == 0 { size = header.filesize } else { size = (header.filesize + (512 - header.filesize % 512)) } } self.offset += 512 + size if let data = data, header.isFile { // return file data fileData = data fileHeader = header break } } } guard let _fileData = fileData, let _fileHeader = fileHeader else { return nil } return (filename: _fileHeader.filepath, mtime: _fileHeader.mtime, data: _fileData) } // MARK: - Stream based unpack fileprivate var buffer = [CChar]() /// Initialize for unpacking from streaming data /// /// - parameter streamingData: initial data or nil public init(streamingData: [CChar]?) { self.streamingMode = true if let data = streamingData { self.buffer.append(contentsOf: data) } } /// Consume bytes from stream, return unpacked file /// /// - parameter data: data to consume /// /// - throws: TarFile.Errors /// /// - returns: tuple with filename and data on completion of a single file open func consume(data: [CChar]) throws -> (filename: String, data: Data)? { if !self.streamingMode { throw Errors.programmingError } self.buffer.append(contentsOf: data) let dataPtr = UnsafePointer<CChar>(self.buffer) if self.buffer.count > 512 { let header = try self.parse(header: dataPtr) let endOffset = 512 + (header.filesize + (512 - header.filesize % 512)) if self.buffer.count > endOffset { let data = Data(bytes: dataPtr.advanced(by: 512), count: header.filesize) self.buffer.removeFirst(endOffset) if header.isFile { return (filename: header.filepath, data:data) } } } return nil } // MARK: - Private fileprivate func parse(header: UnsafePointer<CChar>) throws -> TarFileHeader { var result = TarFileHeader(isFile: false, filepath: "", filesize: 0, mtime: Date(timeIntervalSince1970: 0)) let buffer = UnsafeBufferPointer<CChar>(start:header, count:512) // verify magic 257-262 guard buffer[257] == 117 && // u header[258] == 115 && // s header[259] == 116 && // t header[260] == 97 && // a header[261] == 114 && // r header[262] == 0 else { if header[0] == 0 { throw Errors.endOfFile } throw Errors.headerParseError } // verify checksum var checksum:UInt32 = 0 for index in 0..<512 { if index >= 148 && index < 148+8 { checksum += 32 } else { checksum += UInt32(header[index]) } } let headerChecksum:UInt32 = UInt32(strtol(header.advanced(by: 148), nil, 8)) if headerChecksum != checksum { throw Errors.headerParseError } // verify we're handling a file if header[156] == 0 || header[156] == 48 { result.isFile = true } // extract filename -> 0-99 guard let filename = String(cString: header, encoding: String.Encoding.utf8) else { return result } result.filepath = filename // extract file size let fileSize = strtol(header.advanced(by: 124), nil, 8) result.filesize = fileSize // extract modification time let mTime = strtol(header.advanced(by: 136), nil, 8) result.mtime = Date(timeIntervalSince1970: TimeInterval(mTime)) return result } }
bsd-3-clause
83bd9aba80e81996f6e3829e797d760e
30.095455
115
0.529601
4.935786
false
false
false
false
anthony0926/HChart
HCharts/Data/Implementations/Standard/ChartData.swift
2
24698
// // ChartData.swift // Charts // // Created by Daniel Cohen Gindi on 23/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import UIKit public class ChartData: NSObject { internal var _yMax = Double(0.0) internal var _yMin = Double(0.0) internal var _leftAxisMax = Double(0.0) internal var _leftAxisMin = Double(0.0) internal var _rightAxisMax = Double(0.0) internal var _rightAxisMin = Double(0.0) private var _yValCount = Int(0) /// the last start value used for calcMinMax internal var _lastStart: Int = 0 /// the last end value used for calcMinMax internal var _lastEnd: Int = 0 /// the average length (in characters) across all x-value strings private var _xValAverageLength = Double(0.0) internal var _xVals: [String?]! internal var _dataSets: [IChartDataSet]! public override init() { super.init() _xVals = [String?]() _dataSets = [IChartDataSet]() } public init(xVals: [String?]?, dataSets: [IChartDataSet]?) { super.init() _xVals = xVals == nil ? [String?]() : xVals _dataSets = dataSets == nil ? [IChartDataSet]() : dataSets self.initialize(_dataSets) } public init(xVals: [NSObject]?, dataSets: [IChartDataSet]?) { super.init() _xVals = xVals == nil ? [String?]() : ChartUtils.bridgedObjCGetStringArray(objc: xVals!) _dataSets = dataSets == nil ? [IChartDataSet]() : dataSets self.initialize(_dataSets) } public convenience init(xVals: [String?]?) { self.init(xVals: xVals, dataSets: [IChartDataSet]()) } public convenience init(xVals: [NSObject]?) { self.init(xVals: xVals, dataSets: [IChartDataSet]()) } public convenience init(xVals: [String?]?, dataSet: IChartDataSet?) { self.init(xVals: xVals, dataSets: dataSet === nil ? nil : [dataSet!]) } public convenience init(xVals: [NSObject]?, dataSet: IChartDataSet?) { self.init(xVals: xVals, dataSets: dataSet === nil ? nil : [dataSet!]) } internal func initialize(dataSets: [IChartDataSet]) { checkIsLegal(dataSets) calcMinMax(start: _lastStart, end: _lastEnd) calcYValueCount() calcXValAverageLength() } // calculates the average length (in characters) across all x-value strings internal func calcXValAverageLength() { if (_xVals.count == 0) { _xValAverageLength = 1 return } var sum = 1 for (var i = 0; i < _xVals.count; i++) { sum += _xVals[i] == nil ? 0 : (_xVals[i]!).characters.count } _xValAverageLength = Double(sum) / Double(_xVals.count) } // Checks if the combination of x-values array and DataSet array is legal or not. // :param: dataSets internal func checkIsLegal(dataSets: [IChartDataSet]!) { if (dataSets == nil) { return } if self is ScatterChartData { // In scatter chart it makes sense to have more than one y-value value for an x-index return } for (var i = 0; i < dataSets.count; i++) { if (dataSets[i].entryCount > _xVals.count) { print("One or more of the DataSet Entry arrays are longer than the x-values array of this Data object.", terminator: "\n") return } } } public func notifyDataChanged() { initialize(_dataSets) } /// calc minimum and maximum y value over all datasets internal func calcMinMax(start start: Int, end: Int) { if (_dataSets == nil || _dataSets.count < 1) { _yMax = 0.0 _yMin = 0.0 } else { _lastStart = start _lastEnd = end _yMin = DBL_MAX _yMax = -DBL_MAX for (var i = 0; i < _dataSets.count; i++) { _dataSets[i].calcMinMax(start: start, end: end) if (_dataSets[i].yMin < _yMin) { _yMin = _dataSets[i].yMin } if (_dataSets[i].yMax > _yMax) { _yMax = _dataSets[i].yMax } } if (_yMin == DBL_MAX) { _yMin = 0.0 _yMax = 0.0 } // left axis let firstLeft = getFirstLeft() if (firstLeft !== nil) { _leftAxisMax = firstLeft!.yMax _leftAxisMin = firstLeft!.yMin for dataSet in _dataSets { if (dataSet.axisDependency == .Left) { if (dataSet.yMin < _leftAxisMin) { _leftAxisMin = dataSet.yMin } if (dataSet.yMax > _leftAxisMax) { _leftAxisMax = dataSet.yMax } } } } // right axis let firstRight = getFirstRight() if (firstRight !== nil) { _rightAxisMax = firstRight!.yMax _rightAxisMin = firstRight!.yMin for dataSet in _dataSets { if (dataSet.axisDependency == .Right) { if (dataSet.yMin < _rightAxisMin) { _rightAxisMin = dataSet.yMin } if (dataSet.yMax > _rightAxisMax) { _rightAxisMax = dataSet.yMax } } } } // in case there is only one axis, adjust the second axis handleEmptyAxis(firstLeft, firstRight: firstRight) } } /// Calculates the total number of y-values across all ChartDataSets the ChartData represents. internal func calcYValueCount() { _yValCount = 0 if (_dataSets == nil) { return } var count = 0 for (var i = 0; i < _dataSets.count; i++) { count += _dataSets[i].entryCount } _yValCount = count } /// - returns: the number of LineDataSets this object contains public var dataSetCount: Int { if (_dataSets == nil) { return 0 } return _dataSets.count } /// - returns: the smallest y-value the data object contains. public var yMin: Double { return _yMin } public func getYMin() -> Double { return _yMin } public func getYMin(axis: ChartYAxis.AxisDependency) -> Double { if (axis == .Left) { return _leftAxisMin } else { return _rightAxisMin } } /// - returns: the greatest y-value the data object contains. public var yMax: Double { return _yMax } public func getYMax() -> Double { return _yMax } public func getYMax(axis: ChartYAxis.AxisDependency) -> Double { if (axis == .Left) { return _leftAxisMax } else { return _rightAxisMax } } /// - returns: the average length (in characters) across all values in the x-vals array public var xValAverageLength: Double { return _xValAverageLength } /// - returns: the total number of y-values across all DataSet objects the this object represents. public var yValCount: Int { return _yValCount } /// - returns: the x-values the chart represents public var xVals: [String?] { return _xVals } ///Adds a new x-value to the chart data. public func addXValue(xVal: String?) { _xVals.append(xVal) } /// Removes the x-value at the specified index. public func removeXValue(index: Int) { _xVals.removeAtIndex(index) } /// - returns: the array of ChartDataSets this object holds. public var dataSets: [IChartDataSet] { get { return _dataSets } set { _dataSets = newValue initialize(_dataSets) } } /// Retrieve the index of a ChartDataSet with a specific label from the ChartData. Search can be case sensitive or not. /// /// **IMPORTANT: This method does calculations at runtime, do not over-use in performance critical situations.** /// /// - parameter dataSets: the DataSet array to search /// - parameter type: /// - parameter ignorecase: if true, the search is not case-sensitive /// - returns: the index of the DataSet Object with the given label. Sensitive or not. internal func getDataSetIndexByLabel(label: String, ignorecase: Bool) -> Int { if (ignorecase) { for (var i = 0; i < dataSets.count; i++) { if (dataSets[i].label == nil) { continue } if (label.caseInsensitiveCompare(dataSets[i].label!) == NSComparisonResult.OrderedSame) { return i } } } else { for (var i = 0; i < dataSets.count; i++) { if (label == dataSets[i].label) { return i } } } return -1 } /// - returns: the total number of x-values this ChartData object represents (the size of the x-values array) public var xValCount: Int { return _xVals.count } /// - returns: the labels of all DataSets as a string array. internal func dataSetLabels() -> [String] { var types = [String]() for (var i = 0; i < _dataSets.count; i++) { if (dataSets[i].label == nil) { continue } types[i] = _dataSets[i].label! } return types } /// Get the Entry for a corresponding highlight object /// /// - parameter highlight: /// - returns: the entry that is highlighted public func getEntryForHighlight(highlight: ChartHighlight) -> ChartDataEntry? { if highlight.dataSetIndex >= dataSets.count { return nil } else { return _dataSets[highlight.dataSetIndex].entryForXIndex(highlight.xIndex) } } /// **IMPORTANT: This method does calculations at runtime. Use with care in performance critical situations.** /// /// - parameter label: /// - parameter ignorecase: /// - returns: the DataSet Object with the given label. Sensitive or not. public func getDataSetByLabel(label: String, ignorecase: Bool) -> IChartDataSet? { let index = getDataSetIndexByLabel(label, ignorecase: ignorecase) if (index < 0 || index >= _dataSets.count) { return nil } else { return _dataSets[index] } } public func getDataSetByIndex(index: Int) -> IChartDataSet! { if (_dataSets == nil || index < 0 || index >= _dataSets.count) { return nil } return _dataSets[index] } public func addDataSet(d: IChartDataSet!) { if (_dataSets == nil) { return } _yValCount += d.entryCount if (_dataSets.count == 0) { _yMax = d.yMax _yMin = d.yMin if (d.axisDependency == .Left) { _leftAxisMax = d.yMax _leftAxisMin = d.yMin } else { _rightAxisMax = d.yMax _rightAxisMin = d.yMin } } else { if (_yMax < d.yMax) { _yMax = d.yMax } if (_yMin > d.yMin) { _yMin = d.yMin } if (d.axisDependency == .Left) { if (_leftAxisMax < d.yMax) { _leftAxisMax = d.yMax } if (_leftAxisMin > d.yMin) { _leftAxisMin = d.yMin } } else { if (_rightAxisMax < d.yMax) { _rightAxisMax = d.yMax } if (_rightAxisMin > d.yMin) { _rightAxisMin = d.yMin } } } _dataSets.append(d) handleEmptyAxis(getFirstLeft(), firstRight: getFirstRight()) } public func handleEmptyAxis(firstLeft: IChartDataSet?, firstRight: IChartDataSet?) { // in case there is only one axis, adjust the second axis if (firstLeft === nil) { _leftAxisMax = _rightAxisMax _leftAxisMin = _rightAxisMin } else if (firstRight === nil) { _rightAxisMax = _leftAxisMax _rightAxisMin = _leftAxisMin } } /// Removes the given DataSet from this data object. /// Also recalculates all minimum and maximum values. /// /// - returns: true if a DataSet was removed, false if no DataSet could be removed. public func removeDataSet(dataSet: IChartDataSet!) -> Bool { if (_dataSets == nil || dataSet === nil) { return false } for (var i = 0; i < _dataSets.count; i++) { if (_dataSets[i] === dataSet) { return removeDataSetByIndex(i) } } return false } /// Removes the DataSet at the given index in the DataSet array from the data object. /// Also recalculates all minimum and maximum values. /// /// - returns: true if a DataSet was removed, false if no DataSet could be removed. public func removeDataSetByIndex(index: Int) -> Bool { if (_dataSets == nil || index >= _dataSets.count || index < 0) { return false } let d = _dataSets.removeAtIndex(index) _yValCount -= d.entryCount calcMinMax(start: _lastStart, end: _lastEnd) return true } /// Adds an Entry to the DataSet at the specified index. Entries are added to the end of the list. public func addEntry(e: ChartDataEntry, dataSetIndex: Int) { if _dataSets != nil && _dataSets.count > dataSetIndex && dataSetIndex >= 0 { let val = e.value let set = _dataSets[dataSetIndex] if !set.addEntry(e) { return } if (_yValCount == 0) { _yMin = val _yMax = val if (set.axisDependency == .Left) { _leftAxisMax = e.value _leftAxisMin = e.value } else { _rightAxisMax = e.value _rightAxisMin = e.value } } else { if (_yMax < val) { _yMax = val } if (_yMin > val) { _yMin = val } if (set.axisDependency == .Left) { if (_leftAxisMax < e.value) { _leftAxisMax = e.value } if (_leftAxisMin > e.value) { _leftAxisMin = e.value } } else { if (_rightAxisMax < e.value) { _rightAxisMax = e.value } if (_rightAxisMin > e.value) { _rightAxisMin = e.value } } } _yValCount += 1 handleEmptyAxis(getFirstLeft(), firstRight: getFirstRight()) } else { print("ChartData.addEntry() - dataSetIndex our of range.", terminator: "\n") } } /// Removes the given Entry object from the DataSet at the specified index. public func removeEntry(entry: ChartDataEntry!, dataSetIndex: Int) -> Bool { // entry null, outofbounds if (entry === nil || dataSetIndex >= _dataSets.count) { return false } // remove the entry from the dataset let removed = _dataSets[dataSetIndex].removeEntry(entry) if (removed) { _yValCount -= 1 calcMinMax(start: _lastStart, end: _lastEnd) } return removed } /// Removes the Entry object at the given xIndex from the ChartDataSet at the /// specified index. /// - returns: true if an entry was removed, false if no Entry was found that meets the specified requirements. public func removeEntryByXIndex(xIndex: Int, dataSetIndex: Int) -> Bool { if (dataSetIndex >= _dataSets.count) { return false } let entry = _dataSets[dataSetIndex].entryForXIndex(xIndex) if (entry?.xIndex != xIndex) { return false } return removeEntry(entry, dataSetIndex: dataSetIndex) } /// - returns: the DataSet that contains the provided Entry, or null, if no DataSet contains this entry. public func getDataSetForEntry(e: ChartDataEntry!) -> IChartDataSet? { if (e == nil) { return nil } for (var i = 0; i < _dataSets.count; i++) { let set = _dataSets[i] if (e === set.entryForXIndex(e.xIndex)) { return set } } return nil } /// - returns: the index of the provided DataSet inside the DataSets array of this data object. -1 if the DataSet was not found. public func indexOfDataSet(dataSet: IChartDataSet) -> Int { for (var i = 0; i < _dataSets.count; i++) { if (_dataSets[i] === dataSet) { return i } } return -1 } /// - returns: the first DataSet from the datasets-array that has it's dependency on the left axis. Returns null if no DataSet with left dependency could be found. public func getFirstLeft() -> IChartDataSet? { for dataSet in _dataSets { if (dataSet.axisDependency == .Left) { return dataSet } } return nil } /// - returns: the first DataSet from the datasets-array that has it's dependency on the right axis. Returns null if no DataSet with right dependency could be found. public func getFirstRight() -> IChartDataSet? { for dataSet in _dataSets { if (dataSet.axisDependency == .Right) { return dataSet } } return nil } /// - returns: all colors used across all DataSet objects this object represents. public func getColors() -> [UIColor]? { if (_dataSets == nil) { return nil } var clrcnt = 0 for (var i = 0; i < _dataSets.count; i++) { clrcnt += _dataSets[i].colors.count } var colors = [UIColor]() for (var i = 0; i < _dataSets.count; i++) { let clrs = _dataSets[i].colors for clr in clrs { colors.append(clr) } } return colors } /// Generates an x-values array filled with numbers in range specified by the parameters. Can be used for convenience. public func generateXVals(from: Int, to: Int) -> [String] { var xvals = [String]() for (var i = from; i < to; i++) { xvals.append(String(i)) } return xvals } /// Sets a custom ValueFormatter for all DataSets this data object contains. public func setValueFormatter(formatter: NSNumberFormatter!) { for set in dataSets { set.valueFormatter = formatter } } /// Sets the color of the value-text (color in which the value-labels are drawn) for all DataSets this data object contains. public func setValueTextColor(color: UIColor!) { for set in dataSets { set.valueTextColor = color ?? set.valueTextColor } } /// Sets the font for all value-labels for all DataSets this data object contains. public func setValueFont(font: UIFont!) { for set in dataSets { set.valueFont = font ?? set.valueFont } } /// Enables / disables drawing values (value-text) for all DataSets this data object contains. public func setDrawValues(enabled: Bool) { for set in dataSets { set.drawValuesEnabled = enabled } } /// Enables / disables highlighting values for all DataSets this data object contains. /// If set to true, this means that values can be highlighted programmatically or by touch gesture. public var highlightEnabled: Bool { get { for set in dataSets { if (!set.highlightEnabled) { return false } } return true } set { for set in dataSets { set.highlightEnabled = newValue } } } /// if true, value highlightning is enabled public var isHighlightEnabled: Bool { return highlightEnabled } /// Clears this data object from all DataSets and removes all Entries. /// Don't forget to invalidate the chart after this. public func clearValues() { dataSets.removeAll(keepCapacity: false) notifyDataChanged() } /// Checks if this data object contains the specified Entry. /// - returns: true if so, false if not. public func contains(entry entry: ChartDataEntry) -> Bool { for set in dataSets { if set.contains(entry) { return true } } return false } /// Checks if this data object contains the specified DataSet. /// - returns: true if so, false if not. public func contains(dataSet dataSet: IChartDataSet) -> Bool { for set in dataSets { if set === dataSet { return true } } return false } /// MARK: - ObjC compatibility /// - returns: the average length (in characters) across all values in the x-vals array public var xValsObjc: [NSObject] { return ChartUtils.bridgedObjCGetStringArray(swift: _xVals); } }
mit
6bf323412f28fd7367ad5f42f3c51dbc
26.082237
169
0.479108
5.218255
false
false
false
false
TCA-Team/iOS
TUM Campus App/StudyRoomGroup.swift
1
1901
// // StudyRoomGroup.swift // TUM Campus App // // This file is part of the TUM Campus App distribution https://github.com/TCA-Team/iOS // Copyright (c) 2018 TCA // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, version 3. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // import Sweeft class StudyRoomGroup: DataElement { let sortId: Int let name: String let detail: String let rooms: [StudyRoom] init(sortId: Int, name: String, detail: String, rooms: [StudyRoom]) { self.sortId = sortId self.name = name self.detail = detail self.rooms = rooms } convenience init?(from json: JSON, rooms: [StudyRoom]) { guard let sortId = json["sortierung"].int, let name = json["name"].string, let detail = json["detail"].string else { return nil } let numbers = json["raeume"].array ==> { $0.int } self.init(sortId: sortId, name: name, detail: detail, rooms: rooms.filter { numbers.contains($0.roomNumber) }) } var text: String { return name } func getCellIdentifier() -> String { return "studyRoomGroup" } } extension StudyRoomGroup: Equatable { static func == (lhs: StudyRoomGroup, rhs: StudyRoomGroup) -> Bool { return lhs.sortId == rhs.sortId } }
gpl-3.0
47b5dc4bc66d91d63e51574e03a7b8ab
28.246154
88
0.618622
4.061966
false
false
false
false
alvaromb/EventBlankApp
EventBlank/EventBlank/ViewControllers/Feed/TweetListViewController.swift
1
3687
// // TweetListViewController.swift // EventBlank // // Created by Marin Todorov on 7/10/15. // Copyright (c) 2015 Underplot ltd. All rights reserved. // import UIKit import SQLite let kRefreshViewHeight: CGFloat = 60.0 let kRefreshTimeout: Double = 5 * 60.0 class TweetListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, RefreshViewDelegate { @IBOutlet weak var tableView: UITableView! let twitter = TwitterController() var tweets = [Row]() var refreshView: RefreshView! var database: Database { return DatabaseProvider.databases[appDataFileName]! } var lastRefresh: NSTimeInterval = 0 //MARK: - view controller override func viewDidLoad() { super.viewDidLoad() //setup the UI setupUI() //show saved tweets loadTweets() //fetch new tweets fetchTweets() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if NSDate().timeIntervalSince1970 - lastRefresh > kRefreshTimeout { fetchTweets() } } func setupUI() { //setup the table view.backgroundColor = UIColor.whiteColor() self.tableView.estimatedRowHeight = 100.0 self.tableView.rowHeight = UITableViewAutomaticDimension //setup refresh view let refreshRect = CGRect(x: 0.0, y: -kRefreshViewHeight, width: view.frame.size.width, height: kRefreshViewHeight) refreshView = RefreshView(frame: refreshRect, scrollView: self.tableView) refreshView.delegate = self view.insertSubview(refreshView, aboveSubview: tableView) } //MARK: - table view methods func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tweets.count } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let tweet = tweets[indexPath.row] if let urlString = tweet[News.url], let url = NSURL(string: urlString) { let webVC = storyboard?.instantiateViewControllerWithIdentifier("WebViewController") as! WebViewController webVC.initialURL = url navigationController!.pushViewController(webVC, animated: true) } tableView.deselectRowAtIndexPath(indexPath, animated: true) } func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 100.0 } func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { fatalError() } // MARK: - fetching data func refreshViewDidRefresh(refreshView: RefreshView) { //fetch new tweets fetchTweets() } func loadTweets() { fatalError("Must override with a concrete implementation") } func fetchTweets() { fatalError("Must override with a concrete implementation") } // MARK: scroll view methods func scrollViewDidScroll(scrollView: UIScrollView) { refreshView.scrollViewDidScroll(scrollView) } func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { refreshView.scrollViewWillEndDragging(scrollView, withVelocity: velocity, targetContentOffset: targetContentOffset) } }
mit
4bd12d7d4e5e6ec0bf51744974393adf
30.245763
146
0.663683
5.470326
false
false
false
false
lkzhao/YetAnotherAnimationLibrary
Sources/YetAnotherAnimationLibrary/Animatables/SpringAnimatable.swift
1
2350
// The MIT License (MIT) // // Copyright (c) 2016 Luke Zhao <[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 public protocol SpringAnimatable: DecayAnimatable { var defaultStiffness: Double { get set } var target: AnimationProperty<Value> { get } } // convenience extension SpringAnimatable { public func setDefaultStiffness(_ stiffness: Double) { defaultStiffness = stiffness } public func animateTo(_ targetValue: Value, initialVelocity: Value? = nil, stiffness: Double? = nil, damping: Double? = nil, threshold: Double? = nil, completionHandler: ((Bool) -> Void)? = nil) { target.value = targetValue if let initialVelocity = initialVelocity { velocity.value = initialVelocity } var solver = SpringSolver<Value>(stiffness: stiffness ?? defaultStiffness, damping: damping ?? defaultDamping, threshold: threshold ?? defaultThreshold) solver.current = value solver.velocity = velocity solver.target = target self.solver = solver start(completionHandler) } }
mit
e43deb801805dd7e3bebd198a2c67a66
40.964286
82
0.658298
5.119826
false
false
false
false
Blackjacx/SwiftTrace
Sources/Image.swift
1
4144
// // Image.swift // SwiftTrace // // Created by Stefan Herold on 13/08/16. // // import Foundation enum FileIOError: Error { case writeError(String) } public class Image: CustomStringConvertible { private(set)var pixel: [Color] private(set) var width: UInt private(set) var height: UInt var size: UInt { return width * height } var backgroundColor: Color = Color(gray: 0) private let syncAccessQueue = DispatchQueue(label: "com.swiftTrace.imageSerialSynchAccessQueue") // Custom String Convertible public var description: String { return pixel.description } init(width: UInt, height: UInt) { self.width = width self.height = height self.pixel = Array(repeating: backgroundColor, count: Int(width*height)) } /// Normalized accessors for bumpmapping. Uses green component. Returns dx and dy. func derivativeAt(x: Double, y: Double) -> (Double, Double) { let ix = UInt(x * Double(width-1)) let iy = UInt(y * Double(height-1)) let dx = pixel[Int(windex(x: ix, y: iy+1))].green - pixel[Int(index(x: ix, y: iy))].green let dy = pixel[Int(windex(x: ix+1, y: iy))].green - pixel[Int(index(x: ix, y: iy))].green return (dx, dy) } /// Handy accessors: color = img[x, y]; img[x, y] = color subscript(x: UInt, y: UInt) -> Color { get { assert(indexIsValidFor(x: x, y: y), "Index out of range") var pixel: Color! syncAccessQueue.sync { pixel = self.pixel[Int(index(x: x, y: y))] } return pixel } set(newValue) { assert(indexIsValidFor(x: x, y: y), "Index out of range") syncAccessQueue.async { self.pixel[Int(self.index(x: x, y: y))] = newValue } } } /// Handy accessors: color = img[x, y]; img[x, y] = color subscript(x: Double, y: Double) -> Color { get { assert(indexIsValidFor(x: x, y: y), "Index out of range") var pixel: Color! syncAccessQueue.sync { pixel = self.pixel[Int(findex(x: x, y: y))] } return pixel } set(newValue) { assert(indexIsValidFor(x: x, y: y), "Index out of range") syncAccessQueue.async { self.pixel[Int(self.findex(x: x, y: y))] = newValue } } } // MARK: - Index /// Integer index private func index(x: UInt, y: UInt) -> UInt { return y * width + x } /// Wrapped index private func windex(x: UInt, y: UInt) -> UInt { return index(x: x % width, y: y % height) } /// Double index: x(0...1), y(0...1) private func findex(x: Double, y: Double) -> UInt { return index(x: UInt(x * Double(width-1)), y: UInt(y * Double(height-1))) } private func indexIsValidFor(x: UInt, y: UInt) -> Bool { return x < width && y < height && x <= UInt(Int.max) && y <= UInt(Int.max) } private func indexIsValidFor(x: Double, y: Double) -> Bool { return x >= 0 && x <= 1 && y >= 0 && y <= 1 } // MARK: - I/O func write(to filepath: String) throws { guard let out = OutputStream(toFileAtPath: filepath, append: false) else { throw FileIOError.writeError(filepath) } let writer = { (text: String, os: OutputStream)->() in guard let data = text.data(using: .utf8) else { return } _ = data.withUnsafeBytes { os.write($0, maxLength: data.count) } } out.open() let header = "P3 \(width) \(height) \(255)\n" writer(header, out) var row: UInt = 0 for index: Int in 0..<Int(size) { let c = pixel[index] * 255 var message = "\(Int(c.red)) \(Int(c.green)) \(Int(c.blue))" if row != 0 { message = ((row % 10) == 0 ? "\n" : " ") + message } row += 1 writer(message, out) } writer(header, out) out.close() } }
mit
3e2f1c89d34d0d65f6e82751ef9b0544
29.248175
100
0.527027
3.696699
false
false
false
false
Donkey-Tao/SinaWeibo
SinaWeibo/SinaWeibo/Classes/Home/UIPopover/TFPopPresentationController.swift
1
1490
// // TFPopPresentationController.swift // SinaWeibo // // Created by Donkey-Tao on 2017/1/29. // Copyright © 2017年 taofei.me. All rights reserved. // import UIKit class TFPopPresentationController: UIPresentationController { //MARK:- 懒加载属性 lazy var coverView : UIView = UIView() lazy var presentedFrame : CGRect = CGRect.zero //MARK:- 系统回调函数 override func containerViewWillLayoutSubviews() { super.containerViewWillLayoutSubviews() //1.设置弹出View的frame presentedView?.frame = presentedFrame//CGRect(x: 75, y: 55, width: 180 , height: 250) //2.添加HUD setupCoverView() } } //MARK:- 设置界面相关 extension TFPopPresentationController { ///设置蒙版 func setupCoverView(){ //1.添加HUD containerView?.insertSubview(coverView, at: 0) //2.设置HUD属性 coverView.backgroundColor = UIColor(white: 0.5 , alpha: 0.2) coverView.frame = containerView!.bounds //3.添加手势 let tapGes = UITapGestureRecognizer(target: self, action: #selector(TFPopPresentationController.tapCoverView)) coverView.addGestureRecognizer(tapGes) } } //MARK:- 事件监听 extension TFPopPresentationController{ ///点击手势 func tapCoverView(){ presentedViewController.dismiss(animated: true, completion: nil) print("tapCoverView--点击") } }
mit
64e8ac32f906f6ff6a71eaeeb58ec754
21.803279
118
0.649173
4.636667
false
false
false
false
february29/Learning
swift/ReactiveCocoaDemo/Pods/RxSwift/RxSwift/Observables/TakeWhile.swift
94
5130
// // TakeWhile.swift // RxSwift // // Created by Krunoslav Zaher on 6/7/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // extension ObservableType { /** Returns elements from an observable sequence as long as a specified condition is true. - seealso: [takeWhile operator on reactivex.io](http://reactivex.io/documentation/operators/takewhile.html) - parameter predicate: A function to test each element for a condition. - returns: An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. */ public func takeWhile(_ predicate: @escaping (E) throws -> Bool) -> Observable<E> { return TakeWhile(source: asObservable(), predicate: predicate) } /** Returns elements from an observable sequence as long as a specified condition is true. The element's index is used in the logic of the predicate function. - seealso: [takeWhile operator on reactivex.io](http://reactivex.io/documentation/operators/takewhile.html) - parameter predicate: A function to test each element for a condition; the second parameter of the function represents the index of the source element. - returns: An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. */ public func takeWhileWithIndex(_ predicate: @escaping (E, Int) throws -> Bool) -> Observable<E> { return TakeWhile(source: asObservable(), predicate: predicate) } } final fileprivate class TakeWhileSink<O: ObserverType> : Sink<O> , ObserverType { typealias Element = O.E typealias Parent = TakeWhile<Element> fileprivate let _parent: Parent fileprivate var _running = true init(parent: Parent, observer: O, cancel: Cancelable) { _parent = parent super.init(observer: observer, cancel: cancel) } func on(_ event: Event<Element>) { switch event { case .next(let value): if !_running { return } do { _running = try _parent._predicate(value) } catch let e { forwardOn(.error(e)) dispose() return } if _running { forwardOn(.next(value)) } else { forwardOn(.completed) dispose() } case .error, .completed: forwardOn(event) dispose() } } } final fileprivate class TakeWhileSinkWithIndex<O: ObserverType> : Sink<O> , ObserverType { typealias Element = O.E typealias Parent = TakeWhile<Element> fileprivate let _parent: Parent fileprivate var _running = true fileprivate var _index = 0 init(parent: Parent, observer: O, cancel: Cancelable) { _parent = parent super.init(observer: observer, cancel: cancel) } func on(_ event: Event<Element>) { switch event { case .next(let value): if !_running { return } do { _running = try _parent._predicateWithIndex(value, _index) let _ = try incrementChecked(&_index) } catch let e { forwardOn(.error(e)) dispose() return } if _running { forwardOn(.next(value)) } else { forwardOn(.completed) dispose() } case .error, .completed: forwardOn(event) dispose() } } } final fileprivate class TakeWhile<Element>: Producer<Element> { typealias Predicate = (Element) throws -> Bool typealias PredicateWithIndex = (Element, Int) throws -> Bool fileprivate let _source: Observable<Element> fileprivate let _predicate: Predicate! fileprivate let _predicateWithIndex: PredicateWithIndex! init(source: Observable<Element>, predicate: @escaping Predicate) { _source = source _predicate = predicate _predicateWithIndex = nil } init(source: Observable<Element>, predicate: @escaping PredicateWithIndex) { _source = source _predicate = nil _predicateWithIndex = predicate } override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { if let _ = _predicate { let sink = TakeWhileSink(parent: self, observer: observer, cancel: cancel) let subscription = _source.subscribe(sink) return (sink: sink, subscription: subscription) } else { let sink = TakeWhileSinkWithIndex(parent: self, observer: observer, cancel: cancel) let subscription = _source.subscribe(sink) return (sink: sink, subscription: subscription) } } }
mit
0a6d362f65cea277179e01729b95fa90
30.857143
157
0.593098
4.994158
false
false
false
false
8bytes/drift-sdk-ios
Drift/UI/Conversation View/Conversation Cells/ConversationMessageTableViewCell.swift
2
14654
// // ConversationMessageTableViewCell.swift // Drift // // Created by Brian McDonald on 01/08/2016. // Copyright © 2016 Drift. All rights reserved. // import UIKit import AlamofireImage class ConversationMessageTableViewCell: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { @IBOutlet weak var avatarView: AvatarView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var messageTextView: UITextView! @IBOutlet weak var attachmentsCollectionView: UICollectionView! @IBOutlet weak var loadingContainerView: UIView! @IBOutlet weak var loadingView: UIView! @IBOutlet weak var attachmentImageView: UIImageView! @IBOutlet weak var attachmentContainerView: UIView! @IBOutlet weak var singleAttachmentViewHeightConstraint: NSLayoutConstraint! @IBOutlet weak var multipleAttachmentViewHeightConstraint: NSLayoutConstraint! @IBOutlet weak var singleAttachmentView: UIView! @IBOutlet weak var multipleAttachmentView: UIView! @IBOutlet weak var headerTitleLabel: UILabel! @IBOutlet weak var headerHeightLayoutConstraint: NSLayoutConstraint! @IBOutlet weak var headerView: MessageTableHeaderView! @IBOutlet var scheduleMeetingHeightConstraint: NSLayoutConstraint! @IBOutlet var scheduleMeetingAvatarView: AvatarView! @IBOutlet var scheduleMeetingLabel: UILabel! @IBOutlet var scheduleMeetingButton: UIButton! @IBOutlet var scheduleMeetingBorderView: UIView! enum AttachmentStyle { case single case multiple case loading case none } lazy var dateFormatter: DriftDateFormatter = DriftDateFormatter() var indexPath: IndexPath? var message: Message? var configuration: Embed? weak var delegate: ConversationCellDelegate? override func awakeFromNib() { super.awakeFromNib() timeLabel.textColor = ColorPalette.titleTextColor nameLabel.isUserInteractionEnabled = true messageTextView.textContainer.lineFragmentPadding = 0 messageTextView.textContainerInset = UIEdgeInsets.zero selectionStyle = .none attachmentsCollectionView.register(UINib.init(nibName: "AttachmentCollectionViewCell", bundle: Bundle.drift_getResourcesBundle()), forCellWithReuseIdentifier: "AttachmentCollectionViewCell") attachmentsCollectionView.dataSource = self attachmentsCollectionView.delegate = self attachmentsCollectionView.backgroundColor = UIColor.clear scheduleMeetingBorderView.layer.borderWidth = 1 scheduleMeetingBorderView.layer.borderColor = ColorPalette.borderColor.cgColor scheduleMeetingBorderView.layer.cornerRadius = 3 scheduleMeetingButton.layer.cornerRadius = 3 scheduleMeetingButton.backgroundColor = DriftDataStore.sharedInstance.generateBackgroundColor() scheduleMeetingButton.setTitleColor(DriftDataStore.sharedInstance.generateForegroundColor(), for: .normal) loadingContainerView.backgroundColor = ColorPalette.borderColor loadingContainerView.layer.cornerRadius = 6 loadingContainerView.clipsToBounds = true loadingContainerView.alpha = 0 attachmentImageView.layer.masksToBounds = true attachmentImageView.contentMode = .scaleAspectFill attachmentImageView.layer.cornerRadius = 3 attachmentImageView.isUserInteractionEnabled = true let gestureRecognizer = UITapGestureRecognizer(target:self, action: #selector(ConversationMessageTableViewCell.imagePressed)) attachmentImageView.addGestureRecognizer(gestureRecognizer) } func setupForMessage(message: Message, showHeader: Bool, configuration: Embed?){ self.message = message self.configuration = configuration setupHeader(message: message, show: showHeader) setStyle() setupForAttachments(message: message) setupForOfferMeeting(message: message) } func setupHeader(message: Message, show: Bool){ if show { headerTitleLabel.text = dateFormatter.headerStringFromDate(message.createdAt) headerHeightLayoutConstraint.constant = 42 headerView.isHidden = false }else{ headerHeightLayoutConstraint.constant = 0 headerView.isHidden = true } } func setupForOfferMeeting(message: Message) { if let offerMeetingUser = message.presentSchedule { scheduleMeetingHeightConstraint.constant = 140 scheduleMeetingBorderView.isHidden = false scheduleMeetingAvatarView.imageView.image = UIImage(named: "placeholderAvatar", in: Bundle.drift_getResourcesBundle(), compatibleWith: nil) scheduleMeetingLabel.text = "Schedule Meeting" UserManager.sharedInstance.userMetaDataForUserId(offerMeetingUser, completion: { (user) in if let user = user { self.scheduleMeetingAvatarView.setupForUser(user: user) if let creatorName = user.name { self.scheduleMeetingLabel.text = "Schedule a meeting with \(creatorName)" } } }) } else { scheduleMeetingHeightConstraint.constant = 0 scheduleMeetingBorderView.isHidden = true } } func setStyle(){ avatarView.imageView.image = UIImage(named: "placeholderAvatar", in: Bundle.drift_getResourcesBundle(), compatibleWith: nil) if let message = message{ let textColor: UIColor switch message.sendStatus{ case .Sent: textColor = ColorPalette.titleTextColor avatarView.alpha = 1.0 nameLabel.textColor = ColorPalette.titleTextColor timeLabel.textColor = ColorPalette.subtitleTextColor timeLabel.text = dateFormatter.createdAtStringFromDate(message.createdAt) case .Pending: textColor = ColorPalette.subtitleTextColor timeLabel.text = "Sending..." timeLabel.textColor = ColorPalette.subtitleTextColor avatarView.alpha = 0.7 nameLabel.textColor = ColorPalette.subtitleTextColor case .Failed: nameLabel.textColor = ColorPalette.subtitleTextColor textColor = ColorPalette.subtitleTextColor timeLabel.text = "Failed to send" timeLabel.textColor = ColorPalette.subtitleTextColor avatarView.alpha = 0.7 nameLabel.textColor = ColorPalette.titleTextColor } messageTextView.textColor = textColor if let formattedString = message.formattedBody { let finalString = NSMutableAttributedString(attributedString: formattedString) finalString.addAttribute(NSAttributedString.Key.foregroundColor, value: textColor, range: NSMakeRange(0, finalString.length)) messageTextView.attributedText = finalString } else { messageTextView.text = message.body ?? " " } getUser(message.authorId) } } func getUser(_ userId: Int64) { if let authorType = message?.authorType , authorType == .User { UserManager.sharedInstance.userMetaDataForUserId(userId, completion: { (user) in if let user = user { self.avatarView.setupForUser(user: user) if let creatorName = user.name { self.nameLabel.text = creatorName } } }) }else { if let endUser = DriftDataStore.sharedInstance.auth?.endUser { avatarView.setupForUser(user: endUser) if let creatorName = endUser.name { self.nameLabel.text = creatorName }else if let email = endUser.email { self.nameLabel.text = email }else{ self.nameLabel.text = "You" } } } } func setupForAttachmentStyle(attachmentStyle: AttachmentStyle){ switch attachmentStyle{ case .multiple: singleAttachmentViewHeightConstraint.constant = 0 multipleAttachmentViewHeightConstraint.constant = 65 singleAttachmentView.isHidden = true multipleAttachmentView.isHidden = false case .single, .loading: singleAttachmentViewHeightConstraint.constant = 120 multipleAttachmentViewHeightConstraint.constant = 0 singleAttachmentView.isHidden = false multipleAttachmentView.isHidden = true case .none: singleAttachmentViewHeightConstraint.constant = 0 multipleAttachmentViewHeightConstraint.constant = 0 singleAttachmentView.isHidden = true multipleAttachmentView.isHidden = true } } func setupForAttachments(message: Message) { if message.attachmentIds.isEmpty == .some(true){ //Hide them all setupForAttachmentStyle(attachmentStyle: .none) }else{ if !message.attachments.isEmpty { //Attachments are loaded displayAttachments(attachments: message.attachments) } else { if message.attachmentIds.count == 1 { setupForAttachmentStyle(attachmentStyle: .loading) }else{ setupForAttachmentStyle(attachmentStyle: .multiple) } DriftAPIManager.getAttachmentsMetaData(message.attachmentIds, authToken: (DriftDataStore.sharedInstance.auth?.accessToken)!, completion: { [weak self] (result) in switch result{ case .success(let attachments): message.attachments.append(contentsOf: attachments) self?.displayAttachments(attachments: attachments) case .failure: LoggerManager.log("Failed to get attachment metadata for message: \(message.id ?? -1)") } }) } } } func displayAttachments(attachments: [Attachment]) { if attachments.count == 1 { //Single Attachments let attachment = attachments.first! if attachment.isImage(){ let placeholder = UIImage(named: "imagePlaceholder", in: Bundle.drift_getResourcesBundle(), compatibleWith: nil) self.setupForAttachmentStyle(attachmentStyle: .single) if let urlRequest = attachment.getAttachmentURL(accessToken: DriftDataStore.sharedInstance.auth?.accessToken) { self.attachmentImageView.af.setImage(withURLRequest: urlRequest, placeholderImage: placeholder) } else { self.attachmentImageView.image = placeholder } }else{ self.setupForAttachmentStyle(attachmentStyle: .multiple) } } else { //Multiple Attachments self.setupForAttachmentStyle(attachmentStyle: .multiple) } attachmentsCollectionView.reloadData() } @objc func imagePressed(){ if let attachment = message?.attachments.first{ delegate?.attachmentSelected(attachment, sender: self) } } func setTimeLabel(date: Date) { let formatter = DateFormatter() formatter.dateFormat = "hh:mm a" timeLabel.textColor = ColorPalette.subtitleTextColor timeLabel.text = formatter.string(from: date) } func setUser(name: String?, email: String?){ if name == nil && email == nil{ nameLabel.text = "Site Visitor" }else{ nameLabel.text = name == nil ? email : name } } @IBAction func schedulePressed() { if let scheduleUserId = message?.presentSchedule { delegate?.presentScheduleOfferingForUserId(userId: scheduleUserId) } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "AttachmentCollectionViewCell", for: indexPath) as! AttachmentCollectionViewCell cell.layer.cornerRadius = 3.0 if let attachment = message?.attachments[indexPath.row] { let fileName: NSString = attachment.fileName as NSString let fileExtension = fileName.pathExtension cell.fileNameLabel.text = "\(fileName)" cell.fileExtensionLabel.text = "\(fileExtension.uppercased())" let formatter = ByteCountFormatter() formatter.countStyle = .memory formatter.string(fromByteCount: Int64(attachment.size)) formatter.allowsNonnumericFormatting = false cell.sizeLabel.text = formatter.string(fromByteCount: Int64(attachment.size)) } return cell } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let count = message?.attachments.count ?? 0 if count == 1 { if message!.attachments[0].isImage(){ return 0 } } return count } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { delegate?.attachmentSelected(message!.attachments[indexPath.row], sender: self) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if let attachments = message?.attachments { if let attachment = attachments.first, attachments.count == 1, attachment.isImage(){ return CGSize(width: 0, height: 0) } return CGSize(width: 200, height: 55) } return CGSize(width: 0, height: 0) } }
mit
308986dbf3fc35eb6827dba95146e107
40.985673
198
0.630997
6.193153
false
false
false
false
MastodonKit/MastodonKit
Sources/MastodonKit/Requests/Statuses.swift
1
6024
// // Statuses.swift // MastodonKit // // Created by Ornithologist Coder on 4/9/17. // Copyright © 2017 MastodonKit. All rights reserved. // import Foundation /// `Statuses` requests. public enum Statuses { /// Fetches a status. /// /// - Parameter id: The status id. /// - Returns: Request for `Status`. public static func status(id: String) -> Request<Status> { return Request<Status>(path: "/api/v1/statuses/\(id)") } /// Gets a status context. /// /// - Parameter id: The status id. /// - Returns: Request for `Context`. public static func context(id: String) -> Request<Context> { return Request<Context>(path: "/api/v1/statuses/\(id)/context") } /// Gets a card associated with a status. /// /// - Parameter id: The status id. /// - Returns: Request for `Card`. public static func card(id: String) -> Request<Card> { return Request<Card>(path: "/api/v1/statuses/\(id)/card") } /// Gets who reblogged a status. /// /// - Parameters: /// - id: The status id. /// - range: The bounds used when requesting data from Mastodon. /// - Returns: Request for `[Account]`. public static func rebloggedBy(id: String, range: RequestRange = .default) -> Request<[Account]> { let parameters = range.parameters(limit: between(1, and: 80, default: 40)) let method = HTTPMethod.get(.parameters(parameters)) return Request<[Account]>(path: "/api/v1/statuses/\(id)/reblogged_by", method: method) } /// Gets who favourited a status. /// /// - Parameters: /// - id: The status id. /// - range: The bounds used when requesting data from Mastodon. /// - Returns: Request for `[Account]`. public static func favouritedBy(id: String, range: RequestRange = .default) -> Request<[Account]> { let parameters = range.parameters(limit: between(1, and: 80, default: 40)) let method = HTTPMethod.get(.parameters(parameters)) return Request<[Account]>(path: "/api/v1/statuses/\(id)/favourited_by", method: method) } /// Posts a new status. /// /// - Parameters: /// - status: The text of the status. /// - replyTo: The local ID of the status you want to reply to. /// - mediaIDs: The array of media IDs to attach to the status (maximum 4). /// - sensitive: Marks the status as NSFW. /// - spoilerText: the text to be shown as a warning before the actual content. /// - visibility: The status' visibility. /// - Returns: Request for `Status`. public static func create(status: String, replyToID: String? = nil, mediaIDs: [String] = [], sensitive: Bool? = nil, spoilerText: String? = nil, visibility: Visibility = .public) -> Request<Status> { let parameters = [ Parameter(name: "status", value: status), Parameter(name: "in_reply_to_id", value: replyToID), Parameter(name: "sensitive", value: sensitive.flatMap(trueOrNil)), Parameter(name: "spoiler_text", value: spoilerText), Parameter(name: "visibility", value: visibility.rawValue) ] + mediaIDs.map(toArrayOfParameters(withName: "media_ids")) let method = HTTPMethod.post(.parameters(parameters)) return Request<Status>(path: "/api/v1/statuses", method: method) } /// Deletes a status. /// /// - Parameter id: The status id. /// - Returns: Request for `Empty`. public static func delete(id: String) -> Request<Empty> { return Request<Empty>(path: "/api/v1/statuses/\(id)", method: .delete(.empty)) } /// Reblogs a status. /// /// - Parameter id: The status id. /// - Returns: Request for `Status`. public static func reblog(id: String) -> Request<Status> { return Request<Status>(path: "/api/v1/statuses/\(id)/reblog", method: .post(.empty)) } /// Unreblogs a status. /// /// - Parameter id: The status id. /// - Returns: Request for `Status`. public static func unreblog(id: String) -> Request<Status> { return Request<Status>(path: "/api/v1/statuses/\(id)/unreblog", method: .post(.empty)) } /// Favourites a status. /// /// - Parameter id: The status id. /// - Returns: Request for `Status`. public static func favourite(id: String) -> Request<Status> { return Request<Status>(path: "/api/v1/statuses/\(id)/favourite", method: .post(.empty)) } /// Unfavourites a status. /// /// - Parameter id: The status id. /// - Returns: Request for `Status`. public static func unfavourite(id: String) -> Request<Status> { return Request<Status>(path: "/api/v1/statuses/\(id)/unfavourite", method: .post(.empty)) } /// Pins a status. /// /// - Parameter id: The status id. /// - Returns: Request for `Status`. public static func pin(id: String) -> Request<Status> { return Request<Status>(path: "/api/v1/statuses/\(id)/pin", method: .post(.empty)) } /// Unpins a status. /// /// - Parameter id: The status id. /// - Returns: Request for `Status`. public static func unpin(id: String) -> Request<Status> { return Request<Status>(path: "/api/v1/statuses/\(id)/unpin", method: .post(.empty)) } /// Mutes a status. /// /// - Parameter id: The status id. /// - Returns: Request for `Status`. public static func mute(id: String) -> Request<Status> { return Request<Status>(path: "/api/v1/statuses/\(id)/mute", method: .post(.empty)) } /// Unmutes a status. /// /// - Parameter id: The status id. /// - Returns: Request for `Status`. public static func unmute(id: String) -> Request<Status> { return Request<Status>(path: "/api/v1/statuses/\(id)/unmute", method: .post(.empty)) } }
mit
705baffadf3a6cbaa5644eeec21a76d0
36.179012
103
0.586917
3.970336
false
false
false
false
benbahrenburg/KeyStorage
KeyStorage/Classes/KeyStoreUbiquitousProvider.swift
1
14924
// // KeyStorage - Simplifying securely saving key information // KeyStoreUbiquitousProvider.swift // // Created by Ben Bahrenburg on 3/23/16. // Copyright © 2019 bencoding.com. All rights reserved. // import Foundation /** Storage Provider that saves/reads keys from the NSUserDefaults */ public final class KeyStoreUbiquitousProvider: KeyStorage { private var store: NSUbiquitousKeyValueStore private var crypter: KeyStorageCrypter? private var usingEncryption: Bool = false public init(cryptoProvider: KeyStorageCrypter? = nil) { self.store = NSUbiquitousKeyValueStore() self.crypter = cryptoProvider self.usingEncryption = cryptoProvider != nil } /** Synchronize information to/from iCloud NSUbiquitousKeyValueStore. - Returns: Bool is returned true if the in-memory and on-disk keys and values were synchronized, or false if an error occurred. For example, this method returns false if an app was not built with the proper entitlement requests. */ @discardableResult public func synchronize() -> Bool { return store.synchronize() } @discardableResult public func setStruct<T: Codable>(forKey: String, value: T?) -> Bool { guard let data = try? JSONEncoder().encode(value) else { return removeKey(forKey: forKey) } return saveData(forKey: forKey, value: data) } public func getStruct<T>(forKey: String, forType: T.Type) -> T? where T : Decodable { if let data = load(forKey: forKey) { return try! JSONDecoder().decode(forType, from: data) } return nil } @discardableResult public func setStructArray<T: Codable>(forKey: String, value: [T]) -> Bool { let data = value.compactMap { try? JSONEncoder().encode($0) } if data.count == 0 { return removeKey(forKey: forKey) } return saveData(forKey: forKey, value: data) } public func getStructArray<T>(forKey: String, forType: T.Type) -> [T] where T : Decodable { if let data = loadArray(forKey: forKey) { return data.map { try! JSONDecoder().decode(forType, from: $0) } } return [] } /** Returns a Bool indicating if a stored value exists for the provided key. - Parameter forKey: The key to check if there is a stored value for. - Returns: Bool is returned true if a stored value exists or false if there is no stored value. */ public func exists(forKey: String) -> Bool { store.synchronize() return store.object(forKey: forKey) != nil } /** Removes the stored value for the provided key. - Parameter forKey: The key that should have it's stored value removed - Returns: Bool is returned with the status of the removal operation. True for success, false for error. */ @discardableResult public func removeKey(forKey: String) -> Bool { store.removeObject(forKey: forKey) return true } @discardableResult public func setString(forKey: String, value: String) -> Bool { if usingEncryption { if let data = value.data(using: .utf8) { return saveData(forKey: forKey, value: data) } } else { store.set(value, forKey: forKey) } return true } @discardableResult public func setInt(forKey: String, value: Int) -> Bool { if usingEncryption { return saveObject(forKey: forKey, value: NSNumber(value: value)) } else { store.set(value, forKey: forKey) } return true } @discardableResult public func setBool(forKey: String, value: Bool) -> Bool { if usingEncryption { return saveObject(forKey: forKey, value: NSNumber(value: value)) } else { store.set(value, forKey: forKey) } return true } @discardableResult public func setDouble(forKey: String, value: Double) -> Bool { if usingEncryption { return saveObject(forKey: forKey, value: NSNumber(value: value)) } else { store.set(value, forKey: forKey) } return true } @discardableResult public func setFloat(forKey: String, value: Float) -> Bool { if usingEncryption { return saveObject(forKey: forKey, value: NSNumber(value: value)) } else { store.set(value, forKey: forKey) } return true } @discardableResult public func setDate(forKey: String, value: Date) -> Bool { if usingEncryption { return saveObject(forKey: forKey, value: NSNumber(value: value.timeIntervalSince1970)) } else { store.set(value, forKey: forKey) } return true } @discardableResult public func setURL(forKey: String, value: URL) -> Bool { if usingEncryption { guard let data: Data = try? NSKeyedArchiver.archivedData(withRootObject: value, requiringSecureCoding: true) else { return false } return saveData(forKey: forKey, value: data) } else { store.set(value, forKey: forKey) } return true } @discardableResult public func setData(forKey: String, value: Data) -> Bool { return saveData(forKey: forKey, value: value) } /** Returns String? (optional) for a provided key. Nil is returned if no stored value is found. - Parameter forKey: The key used to return a stored value - Returns: The String? (optional) for the provided key */ public func getString(forKey: String) -> String? { if usingEncryption { if let data = load(forKey: forKey) { return String(data: data, encoding: String.Encoding.utf8) } return nil } return store.string(forKey: forKey) } /** Returns String for a provided key. If no stored value is available, defaultValue is returned. - Parameter forKey: The key used to return a stored value - Parameter defaultValue: The value to be returned if no stored value is available - Returns: The String for the provided key */ public func getString(forKey: String, defaultValue: String) -> String { guard exists(forKey: forKey) else { return defaultValue } if let results = getString(forKey: forKey) { return results } return defaultValue } public func getInt(forKey: String) -> Int { if usingEncryption { guard let result = getObject(forKey: forKey) as? NSNumber else { return 0 } return result.intValue } if let value = store.value(forKey: forKey) as? NSNumber { return value.intValue } return 0 } public func getInt(forKey: String, defaultValue: Int) -> Int { guard exists(forKey: forKey) else { return defaultValue } return getInt(forKey: forKey) } public func getDouble(forKey: String) -> Double { if usingEncryption { guard let result = getObject(forKey: forKey) as? NSNumber else { return 0 } return result.doubleValue } return store.double(forKey: forKey) } public func getDouble(forKey: String, defaultValue: Double) -> Double { guard exists(forKey: forKey) else { return defaultValue } return getDouble(forKey: forKey) } public func getFloat(forKey: String) -> Float { if usingEncryption { guard let result = getObject(forKey: forKey) as? NSNumber else { return 0 } return result.floatValue } if let value = store.value(forKey: forKey) as? NSNumber { return value.floatValue } return 0 } public func getFloat(forKey: String, defaultValue: Float) -> Float { guard exists(forKey: forKey) else { return defaultValue } return getFloat(forKey: forKey) } @discardableResult public func setObject(forKey: String, value: NSCoding) -> Bool { guard let data: Data = try? NSKeyedArchiver.archivedData(withRootObject: value, requiringSecureCoding: true) else { return false } return saveData(forKey: forKey, value: data) } public func getArray(forKey: String) -> NSArray? { guard exists(forKey: forKey) else { return nil } guard let data = getObject(forKey: forKey) else { return nil } if let obj = try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data as! Data) as? NSArray { return obj } return nil } /** Saves an NSArray to NSUserDefaults. - Parameter forKey: The key to be used when saving the provided value - Parameter value: The value to be saved - Returns: True if saved successfully, false if the provider was not able to save successfully */ @discardableResult public func setArray(forKey: String, value: NSArray) -> Bool { guard let data: Data = try? NSKeyedArchiver.archivedData(withRootObject: value, requiringSecureCoding: true) else { return false } return saveData(forKey: forKey, value: data) } public func getDictionary(forKey: String) -> NSDictionary? { guard exists(forKey: forKey) else { return nil } guard let data = getObject(forKey: forKey) else { return nil } if let obj = try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data as! Data) as? NSDictionary { return obj } return nil } /** Saves a NSDictionary to NSUserDefaults. - Parameter forKey: The key to be used when saving the provided value - Parameter value: The value to be saved - Returns: True if saved successfully, false if the provider was not able to save successfully */ @discardableResult public func setDictionary(forKey: String, value: NSDictionary) -> Bool { guard let data: Data = try? NSKeyedArchiver.archivedData(withRootObject: value, requiringSecureCoding: true) else { return false } return saveData(forKey: forKey, value: data) } public func getBool(forKey: String) -> Bool { guard exists(forKey: forKey) else { return false } if usingEncryption { guard let result = getObject(forKey: forKey) as? Bool else { return false } return result } return store.bool(forKey: forKey) } public func getBool(forKey: String, defaultValue: Bool) -> Bool { guard exists(forKey: forKey) else { return defaultValue } return getBool(forKey: forKey) } public func getDate(forKey: String) -> Date? { guard exists(forKey: forKey) else { return nil } if let stored = getObject(forKey: forKey) { return stored as? Date } return nil } public func getDate(forKey: String, defaultValue: Date) -> Date { guard exists(forKey: forKey) else { return defaultValue } if let stored = getObject(forKey: forKey) { return stored as! Date } return defaultValue } public func getURL(forKey: String) -> URL? { guard exists(forKey: forKey) else { return nil } if usingEncryption { guard let result = getObject(forKey: forKey) as? URL else { return nil } return result } if let urlString = store.string(forKey: forKey) { return URL(fileURLWithPath: urlString) } return nil } public func getURL(forKey: String, defaultValue: URL) -> URL { if let url = getURL(forKey: forKey) { return url } return defaultValue } /** Returns Data? (optional) for a provided key. Nil is returned if no stored value is found. - Parameter forKey: The key used to return a stored value - Returns: The Data? (optional) for the provided key */ public func getData(forKey: String) -> Data? { return load(forKey: forKey) } public func getData(forKey: String, defaultValue: Data) -> Data? { if let stored = getData(forKey: forKey) { return stored } return defaultValue } /** Removes all of the keys stored with the provider - Returns: Bool is returned with the status of the removal operation. True for success, false for error. */ @discardableResult public func removeAllKeys() -> Bool { for key in Array(store.dictionaryRepresentation.keys) { store.removeObject(forKey: key) } return true } private func getObject(forKey: String) -> NSCoding? { guard let data = load(forKey: forKey) else { return nil } if let obj = try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as? NSCoding { return obj } return nil } private func saveObject(forKey: String, value: NSCoding) -> Bool { guard let data: Data = try? NSKeyedArchiver.archivedData(withRootObject: value, requiringSecureCoding: true) else { return false } return saveData(forKey: forKey, value: data) } private func loadArray(forKey: String) -> [Data]? { let raw = store.array(forKey: forKey) guard let data = raw as? [Data] else { return nil } if let crypto = self.crypter { return crypto.decrypt(data: data, forKey: forKey) } return data } private func load(forKey: String) -> Data? { let data = store.data(forKey: forKey) guard data != nil else { return nil } if let crypto = self.crypter { return crypto.decrypt(data: data!, forKey: forKey) } return data } private func saveData(forKey: String, value: Data) -> Bool { if let crypto = self.crypter { store.set(crypto.encrypt(data: value, forKey: forKey), forKey: forKey) } else { store.set(value, forKey: forKey) } return true } private func saveData(forKey: String, value: [Data]) -> Bool { if let crypto = self.crypter { store.set(crypto.encrypt(data: value, forKey: forKey), forKey: forKey) } else { store.set(value, forKey: forKey) } return true } }
mit
f21b845ab290b4f2a646503c9b4c7a96
32.915909
233
0.59941
4.867254
false
false
false
false
kmalkic/LazyKit
LazyKit/Classes/Theming/Sets/Models/LazyMeasureUnit.swift
1
1926
// // LazyMeasure.swift // LazyKit // // Created by Kevin Malkic on 23/04/2015. // Copyright (c) 2015 Malkic Kevin. All rights reserved. // import UIKit internal enum MeasureUnit: String { case Default = "default" case Pixel = "px" case Point = "pt" case Percent = "%" case Auto = "auto" } internal class LazyMeasure { var value: LazyFloat? var unit: MeasureUnit? init() { } init(string: String?) { setup(string) } func setup(_ string: String?) { value = valueFromString(string) unit = unitFromString(string) } func unitFromString(_ string: String?) -> MeasureUnit? { guard let string = string else { return nil } if string.contains(MeasureUnit.Pixel.rawValue) { return .Pixel } else if string.contains(MeasureUnit.Point.rawValue) { return .Point } else if string.contains(MeasureUnit.Percent.rawValue) { return .Percent } else if string == MeasureUnit.Auto.rawValue { return .Auto } return .Default } func valueFromString(_ string: String?) -> LazyFloat? { guard let string = string else { return nil } let convertString = string.replacingOccurrences(of: " ", with:"") as NSString var range: NSRange let units = [MeasureUnit.Pixel,MeasureUnit.Point,MeasureUnit.Percent] for unit in units { range = convertString.range(of: unit.rawValue) if range.location != NSNotFound { let value = (convertString.substring(to: range.location) as NSString).floatValue return LazyFloat(value) } } return LazyFloat(convertString.floatValue) } }
mit
68ba8ccb17012daf1662ce15cb854a0c
19.273684
85
0.549844
4.663438
false
false
false
false
roecrew/AudioKit
AudioKit/macOS/AudioKit for macOS/User Interface/AKTelephoneView.swift
2
19371
// // AKTelephoneView.swift // AudioKit for macOS // // Created by Aurelius Prochazka on 7/31/16. // Copyright © 2016 AudioKit. All rights reserved. // /// This is primarily for the telephone page in the Synthesis playground public class AKTelephoneView: NSView { var key1Rect = CGRect.zero var key2Rect = CGRect.zero var key3Rect = CGRect.zero var key4Rect = CGRect.zero var key5Rect = CGRect.zero var key6Rect = CGRect.zero var key7Rect = CGRect.zero var key8Rect = CGRect.zero var key9Rect = CGRect.zero var key0Rect = CGRect.zero var keyStarRect = CGRect.zero var keyHashRect = CGRect.zero var callCirclePath = NSBezierPath() var busyCirclePath = NSBezierPath() var last10Presses = Array<String>(count: 10, repeatedValue: "") var currentKey = "" var callback: (String, String) -> () override public func mouseDown(theEvent: NSEvent) { let touchLocation = convertPoint(theEvent.locationInWindow, fromView: nil) if key1Rect.contains(touchLocation) { currentKey = "1" } if key2Rect.contains(touchLocation) { currentKey = "2" } if key3Rect.contains(touchLocation) { currentKey = "3" } if key4Rect.contains(touchLocation) { currentKey = "4" } if key5Rect.contains(touchLocation) { currentKey = "5" } if key6Rect.contains(touchLocation) { currentKey = "6" } if key7Rect.contains(touchLocation) { currentKey = "7" } if key8Rect.contains(touchLocation) { currentKey = "8" } if key9Rect.contains(touchLocation) { currentKey = "9" } if key0Rect.contains(touchLocation) { currentKey = "0" } if keyStarRect.contains(touchLocation) { currentKey = "*" } if keyHashRect.contains(touchLocation) { currentKey = "#" } if callCirclePath.containsPoint(touchLocation) { currentKey = "CALL" } if busyCirclePath.containsPoint(touchLocation) { currentKey = "BUSY" } if currentKey != "" { callback(currentKey, "down") if currentKey.characters.count == 1 { last10Presses.removeFirst() last10Presses.append(currentKey) } } needsDisplay = true } override public func mouseUp(theEvent: NSEvent) { if currentKey != "" { callback(currentKey, "up") currentKey = "" } needsDisplay = true } public init(frame: CGRect = CGRect(x: 0, y: 0, width: 440, height: 782), callback: (String, String) -> ()) { self.callback = callback super.init(frame: frame) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override public func drawRect(rect: CGRect) { //// General Declarations let context = NSGraphicsContext.currentContext()!.CGContext //// Color Declarations let color = NSColor(calibratedRed: 0.306, green: 0.851, blue: 0.392, alpha: 1) let color2 = NSColor(calibratedRed: 1, green: 0.151, blue: 0, alpha: 1) let unpressedKeyColor = NSColor(calibratedRed: 0.937, green: 0.941, blue: 0.949, alpha: 1) //// Background Drawing let backgroundPath = NSBezierPath(rect: NSMakeRect(1, 0, 440, 782)) unpressedKeyColor.setFill() backgroundPath.fill() //// key 1 Drawing key1Rect = NSMakeRect(70, 494, 82, 82) NSGraphicsContext.saveGraphicsState() NSRectClip(key1Rect) CGContextTranslateCTM(context, key1Rect.origin.x, key1Rect.origin.y) CGContextScaleCTM(context, key1Rect.size.width / 100, key1Rect.size.height / 100) AKTelephoneView.drawKey(text: "\n", numeral: "1", isPressed: currentKey == "1") NSGraphicsContext.restoreGraphicsState() //// key 2 Drawing key2Rect = NSMakeRect(179, 495, 82, 82) NSGraphicsContext.saveGraphicsState() NSRectClip(key2Rect) CGContextTranslateCTM(context, key2Rect.origin.x, key2Rect.origin.y) CGContextScaleCTM(context, key2Rect.size.width / 100, key2Rect.size.height / 100) AKTelephoneView.drawKey(text: "A B C", numeral: "2", isPressed: currentKey == "2") NSGraphicsContext.restoreGraphicsState() //// key 3 Drawing key3Rect = NSMakeRect(288, 495, 82, 82) NSGraphicsContext.saveGraphicsState() NSRectClip(key3Rect) CGContextTranslateCTM(context, key3Rect.origin.x, key3Rect.origin.y) CGContextScaleCTM(context, key3Rect.size.width / 100, key3Rect.size.height / 100) AKTelephoneView.drawKey(text: "D E F", numeral: "3", isPressed: currentKey == "3") NSGraphicsContext.restoreGraphicsState() //// key 4 Drawing key4Rect = NSMakeRect(70, 398, 82, 82) NSGraphicsContext.saveGraphicsState() NSRectClip(key4Rect) CGContextTranslateCTM(context, key4Rect.origin.x, key4Rect.origin.y) CGContextScaleCTM(context, key4Rect.size.width / 100, key4Rect.size.height / 100) AKTelephoneView.drawKey(text: "G H I", numeral: "4", isPressed: currentKey == "4") NSGraphicsContext.restoreGraphicsState() //// key 5 Drawing key5Rect = NSMakeRect(179, 398, 82, 82) NSGraphicsContext.saveGraphicsState() NSRectClip(key5Rect) CGContextTranslateCTM(context, key5Rect.origin.x, key5Rect.origin.y) CGContextScaleCTM(context, key5Rect.size.width / 100, key5Rect.size.height / 100) AKTelephoneView.drawKey(text: "J K L", numeral: "5", isPressed: currentKey == "5") NSGraphicsContext.restoreGraphicsState() //// key 6 Drawing key6Rect = NSMakeRect(288, 398, 82, 82) NSGraphicsContext.saveGraphicsState() NSRectClip(key6Rect) CGContextTranslateCTM(context, key6Rect.origin.x, key6Rect.origin.y) CGContextScaleCTM(context, key6Rect.size.width / 100, key6Rect.size.height / 100) AKTelephoneView.drawKey(text: "M N O", numeral: "6", isPressed: currentKey == "6") NSGraphicsContext.restoreGraphicsState() //// key 7 Drawing key7Rect = NSMakeRect(70, 303, 82, 82) NSGraphicsContext.saveGraphicsState() NSRectClip(key7Rect) CGContextTranslateCTM(context, key7Rect.origin.x, key7Rect.origin.y) CGContextScaleCTM(context, key7Rect.size.width / 100, key7Rect.size.height / 100) AKTelephoneView.drawKey(text: "P Q R S", numeral: "7", isPressed: currentKey == "7") NSGraphicsContext.restoreGraphicsState() //// key 8 Drawing key8Rect = NSMakeRect(179, 303, 82, 82) NSGraphicsContext.saveGraphicsState() NSRectClip(key8Rect) CGContextTranslateCTM(context, key8Rect.origin.x, key8Rect.origin.y) CGContextScaleCTM(context, key8Rect.size.width / 100, key8Rect.size.height / 100) AKTelephoneView.drawKey(text: "T U V", numeral: "8", isPressed: currentKey == "8") NSGraphicsContext.restoreGraphicsState() //// key 9 Drawing key9Rect = NSMakeRect(288, 303, 82, 82) NSGraphicsContext.saveGraphicsState() NSRectClip(key9Rect) CGContextTranslateCTM(context, key9Rect.origin.x, key9Rect.origin.y) CGContextScaleCTM(context, key9Rect.size.width / 100, key9Rect.size.height / 100) AKTelephoneView.drawKey(text: "W X Y Z", numeral: "9", isPressed: currentKey == "9") NSGraphicsContext.restoreGraphicsState() //// key 0 Drawing key0Rect = NSMakeRect(179, 206, 82, 82) NSGraphicsContext.saveGraphicsState() NSRectClip(key0Rect) CGContextTranslateCTM(context, key0Rect.origin.x, key0Rect.origin.y) CGContextScaleCTM(context, key0Rect.size.width / 100, key0Rect.size.height / 100) AKTelephoneView.drawKey(text: "+", numeral: "0", isPressed: currentKey == "0") NSGraphicsContext.restoreGraphicsState() //// keyStar Drawing keyStarRect = NSMakeRect(70, 206, 82, 82) NSGraphicsContext.saveGraphicsState() NSRectClip(keyStarRect) CGContextTranslateCTM(context, keyStarRect.origin.x, keyStarRect.origin.y) CGContextScaleCTM(context, keyStarRect.size.width / 100, keyStarRect.size.height / 100) AKTelephoneView.drawCenteredKey(numeral: "*", isPressed: currentKey == "*") NSGraphicsContext.restoreGraphicsState() //// keyHash Drawing keyHashRect = NSMakeRect(288, 206, 82, 82) NSGraphicsContext.saveGraphicsState() NSRectClip(keyHashRect) CGContextTranslateCTM(context, keyHashRect.origin.x, keyHashRect.origin.y) CGContextScaleCTM(context, keyHashRect.size.width / 100, keyHashRect.size.height / 100) AKTelephoneView.drawCenteredKey(numeral: "#", isPressed: currentKey == "#") NSGraphicsContext.restoreGraphicsState() //// CallButton //// callCircle Drawing callCirclePath = NSBezierPath(ovalInRect: NSMakeRect(181, 100, 79, 79)) color.setFill() callCirclePath.fill() //// telephoneSilhouette Drawing let telephoneSilhouettePath = NSBezierPath() telephoneSilhouettePath.moveToPoint(NSMakePoint(214.75, 131.6)) telephoneSilhouettePath.curveToPoint(NSMakePoint(228.04, 122.98), controlPoint1: NSMakePoint(220.59, 125.68), controlPoint2: NSMakePoint(228.04, 122.98)) telephoneSilhouettePath.curveToPoint(NSMakePoint(234.15, 122.98), controlPoint1: NSMakePoint(228.04, 122.98), controlPoint2: NSMakePoint(231.54, 121.9)) telephoneSilhouettePath.curveToPoint(NSMakePoint(237.74, 128.01), controlPoint1: NSMakePoint(236.75, 124.06), controlPoint2: NSMakePoint(237.74, 128.01)) telephoneSilhouettePath.lineToPoint(NSMakePoint(229.12, 134.11)) telephoneSilhouettePath.curveToPoint(NSMakePoint(222.65, 132.68), controlPoint1: NSMakePoint(229.12, 134.11), controlPoint2: NSMakePoint(225.17, 130.88)) telephoneSilhouettePath.curveToPoint(NSMakePoint(213.68, 141.3), controlPoint1: NSMakePoint(220.14, 134.47), controlPoint2: NSMakePoint(214.75, 139.14)) telephoneSilhouettePath.curveToPoint(NSMakePoint(215.83, 146.68), controlPoint1: NSMakePoint(212.6, 143.45), controlPoint2: NSMakePoint(215.83, 146.68)) telephoneSilhouettePath.lineToPoint(NSMakePoint(210.8, 155.66)) telephoneSilhouettePath.curveToPoint(NSMakePoint(207.57, 154.58), controlPoint1: NSMakePoint(210.8, 155.66), controlPoint2: NSMakePoint(209.1, 155.57)) telephoneSilhouettePath.curveToPoint(NSMakePoint(204.7, 151.71), controlPoint1: NSMakePoint(206.05, 153.59), controlPoint2: NSMakePoint(204.7, 151.71)) telephoneSilhouettePath.curveToPoint(NSMakePoint(205.78, 144.89), controlPoint1: NSMakePoint(204.7, 151.71), controlPoint2: NSMakePoint(204.34, 147.76)) telephoneSilhouettePath.curveToPoint(NSMakePoint(214.75, 131.6), controlPoint1: NSMakePoint(207.21, 142.01), controlPoint2: NSMakePoint(208.92, 137.53)) telephoneSilhouettePath.closePath() NSColor.whiteColor().setFill() telephoneSilhouettePath.fill() //// BusyButton //// busyCircle Drawing busyCirclePath = NSBezierPath(ovalInRect: NSMakeRect(73, 100, 79, 79)) color2.setFill() busyCirclePath.fill() //// busyText Drawing let busyTextRect = NSMakeRect(73, 100, 79, 79) let busyTextTextContent = NSString(string: "BUSY") let busyTextStyle = NSMutableParagraphStyle() busyTextStyle.alignment = .Center let busyTextFontAttributes = [NSFontAttributeName: NSFont(name: "HelveticaNeue", size: 17)!, NSForegroundColorAttributeName: NSColor.whiteColor(), NSParagraphStyleAttributeName: busyTextStyle] let busyTextTextHeight: CGFloat = busyTextTextContent.boundingRectWithSize(NSMakeSize(busyTextRect.width, CGFloat.infinity), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: busyTextFontAttributes).size.height let busyTextTextRect: NSRect = NSMakeRect(busyTextRect.minX, busyTextRect.minY + (busyTextRect.height - busyTextTextHeight) / 2, busyTextRect.width, busyTextTextHeight) NSGraphicsContext.saveGraphicsState() NSRectClip(busyTextRect) busyTextTextContent.drawInRect(NSOffsetRect(busyTextTextRect, 0, 5), withAttributes: busyTextFontAttributes) NSGraphicsContext.restoreGraphicsState() //// Readout Drawing let readoutRect = NSMakeRect(0, 658, 440, 72) let readoutTextContent = NSString(string: last10Presses.joinWithSeparator("")) let readoutStyle = NSMutableParagraphStyle() readoutStyle.alignment = .Center let readoutFontAttributes = [NSFontAttributeName: NSFont(name: "HelveticaNeue", size: 48)!, NSForegroundColorAttributeName: NSColor.blackColor(), NSParagraphStyleAttributeName: readoutStyle] let readoutTextHeight: CGFloat = readoutTextContent.boundingRectWithSize(NSMakeSize(readoutRect.width, CGFloat.infinity), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: readoutFontAttributes).size.height let readoutTextRect: NSRect = NSMakeRect(readoutRect.minX, readoutRect.minY + (readoutRect.height - readoutTextHeight) / 2, readoutRect.width, readoutTextHeight) NSGraphicsContext.saveGraphicsState() NSRectClip(readoutRect) readoutTextContent.drawInRect(NSOffsetRect(readoutTextRect, 0, 0), withAttributes: readoutFontAttributes) NSGraphicsContext.restoreGraphicsState() } public class func drawKey(text text: String = "A B C", numeral: String = "1", isPressed: Bool = true) { //// General Declarations let _ = NSGraphicsContext.currentContext()!.CGContext //// Color Declarations let pressedKeyColor = NSColor(calibratedRed: 0.655, green: 0.745, blue: 0.804, alpha: 1) let unpressedKeyColor = NSColor(calibratedRed: 0.937, green: 0.941, blue: 0.949, alpha: 1) let unpressedTextColor = NSColor(calibratedRed: 0, green: 0, blue: 0, alpha: 1) let pressedTextColor = NSColor(calibratedRed: 1, green: 0.992, blue: 0.988, alpha: 1) //// Variable Declarations let keyColor: NSColor = isPressed ? pressedKeyColor : unpressedKeyColor let textColor: NSColor = isPressed ? pressedTextColor : unpressedTextColor //// Oval Drawing let ovalPath = NSBezierPath(ovalInRect: NSMakeRect(2, 2, 96, 96)) keyColor.setFill() ovalPath.fill() NSColor.lightGrayColor().setStroke() ovalPath.lineWidth = 2.5 ovalPath.stroke() //// Letters Drawing let lettersRect = NSMakeRect(0, 17, 100, 23) let lettersStyle = NSMutableParagraphStyle() lettersStyle.alignment = .Center let lettersFontAttributes = [NSFontAttributeName: NSFont(name: "HelveticaNeue", size: 11)!, NSForegroundColorAttributeName: textColor, NSParagraphStyleAttributeName: lettersStyle] let lettersTextHeight: CGFloat = NSString(string: text).boundingRectWithSize(NSMakeSize(lettersRect.width, CGFloat.infinity), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: lettersFontAttributes).size.height let lettersTextRect: NSRect = NSMakeRect(lettersRect.minX, lettersRect.minY + (lettersRect.height - lettersTextHeight) / 2, lettersRect.width, lettersTextHeight) NSGraphicsContext.saveGraphicsState() NSRectClip(lettersRect) NSString(string: text).drawInRect(NSOffsetRect(lettersTextRect, 0, 2), withAttributes: lettersFontAttributes) NSGraphicsContext.restoreGraphicsState() //// Number Drawing let numberRect = NSMakeRect(27, 36, 45, 46) let numberStyle = NSMutableParagraphStyle() numberStyle.alignment = .Center let numberFontAttributes = [NSFontAttributeName: NSFont(name: "HelveticaNeue", size: 48)!, NSForegroundColorAttributeName: textColor, NSParagraphStyleAttributeName: numberStyle] let numberTextHeight: CGFloat = NSString(string: numeral).boundingRectWithSize(NSMakeSize(numberRect.width, CGFloat.infinity), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: numberFontAttributes).size.height let numberTextRect: NSRect = NSMakeRect(numberRect.minX, numberRect.minY + (numberRect.height - numberTextHeight) / 2, numberRect.width, numberTextHeight) NSGraphicsContext.saveGraphicsState() NSRectClip(numberRect) NSString(string: numeral).drawInRect(NSOffsetRect(numberTextRect, 0, 0), withAttributes: numberFontAttributes) NSGraphicsContext.restoreGraphicsState() } public class func drawCenteredKey(numeral numeral: String = "1", isPressed: Bool = true) { //// General Declarations let _ = NSGraphicsContext.currentContext()!.CGContext //// Color Declarations let pressedKeyColor = NSColor(calibratedRed: 0.655, green: 0.745, blue: 0.804, alpha: 1) let unpressedKeyColor = NSColor(calibratedRed: 0.937, green: 0.941, blue: 0.949, alpha: 1) let unpressedTextColor = NSColor(calibratedRed: 0, green: 0, blue: 0, alpha: 1) let pressedTextColor = NSColor(calibratedRed: 1, green: 0.992, blue: 0.988, alpha: 1) //// Variable Declarations let keyColor: NSColor = isPressed ? pressedKeyColor : unpressedKeyColor let textColor: NSColor = isPressed ? pressedTextColor : unpressedTextColor //// Oval Drawing let ovalPath = NSBezierPath(ovalInRect: NSMakeRect(2, 2, 96, 96)) keyColor.setFill() ovalPath.fill() NSColor.lightGrayColor().setStroke() ovalPath.lineWidth = 2.5 ovalPath.stroke() //// Number Drawing let numberRect = NSMakeRect(27, 27, 45, 46) let numberStyle = NSMutableParagraphStyle() numberStyle.alignment = .Center let numberFontAttributes = [NSFontAttributeName: NSFont(name: "HelveticaNeue", size: 48)!, NSForegroundColorAttributeName: textColor, NSParagraphStyleAttributeName: numberStyle] let numberTextHeight: CGFloat = NSString(string: numeral).boundingRectWithSize(NSMakeSize(numberRect.width, CGFloat.infinity), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: numberFontAttributes).size.height let numberTextRect: NSRect = NSMakeRect(numberRect.minX, numberRect.minY + (numberRect.height - numberTextHeight) / 2, numberRect.width, numberTextHeight) NSGraphicsContext.saveGraphicsState() NSRectClip(numberRect) NSString(string: numeral).drawInRect(NSOffsetRect(numberTextRect, 0, 0), withAttributes: numberFontAttributes) NSGraphicsContext.restoreGraphicsState() } }
mit
c7e26ffb92d10ab43349c1e0ee244d2d
49.311688
236
0.67238
4.906282
false
false
false
false
mumbler/PReVo-iOS
PoshReVo/Subaj Paghoj/Informoj/InformojPaghoViewController.swift
1
3353
// // InformojPaghoViewController.swift // PoshReVo // // Created by Robin Hill on 3/12/16. // Copyright © 2016 Robin Hill. All rights reserved. // import Foundation import UIKit import TTTAttributedLabel /* Informoj pri la programo, kaj ligoj al samtemaj retpaghoj */ class InformojPaghoViewController: UIViewController, Stilplena { @IBOutlet var rulumilo: UIScrollView? @IBOutlet var fonoView: UIView? @IBOutlet var linioView: UIView? @IBOutlet var etikedo: TTTAttributedLabel? var titolo: String? var teksto: String? init(titolo: String, teksto: String) { self.titolo = titolo self.teksto = teksto super.init(nibName: "InformojPaghoViewController", bundle: nil) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { guard let teksto = teksto else { return } title = titolo etikedo?.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body) etikedo?.text = teksto etikedo?.delegate = self efektivigiStilon() let markoj = Iloj.troviMarkojn(teksto: teksto) etikedo?.setText(Iloj.pretigiTekston(teksto, kunMarkoj: markoj)) for ligMarko in markoj[markoLigoKlavo]! { etikedo?.addLink( to: URL(string: ligMarko.2), with: NSMakeRange(ligMarko.0, ligMarko.1 - ligMarko.0) ) } NotificationCenter.default.addObserver(self, selector: #selector(preferredContentSizeDidChange(forChildContentContainer:)), name: UIContentSizeCategory.didChangeNotification, object: nil) } // MARK: - UI agordoj func aranghiNavigaciilo() { guard let titolo = titolo else { return } parent?.title = NSLocalizedString(titolo, comment: "") parent?.navigationItem.rightBarButtonItem = nil } // MARK: - Stilplena func efektivigiStilon() { view.backgroundColor = UzantDatumaro.stilo.fonKoloro rulumilo?.indicatorStyle = UzantDatumaro.stilo.scrollKoloro fonoView?.backgroundColor = UzantDatumaro.stilo.bazKoloro linioView?.layer.borderWidth = 1 linioView?.layer.borderColor = UzantDatumaro.stilo.fonKoloro.cgColor linioView?.backgroundColor = UzantDatumaro.stilo.bazKoloro etikedo?.textColor = UzantDatumaro.stilo.tekstKoloro etikedo?.linkAttributes = [kCTForegroundColorAttributeName : UzantDatumaro.stilo.tintKoloro, kCTUnderlineStyleAttributeName : NSNumber(value: NSUnderlineStyle.single.rawValue)] //etikedo?.activeLinkAttributes = [NSAttributedString.Key.foregroundColor : UzantDatumaro.stilo.tintKoloro, .underlineStyle : NSNumber(value: .single.rawValue)] } } // MARK: - TTTAttributedLabelDelegate extension InformojPaghoViewController : TTTAttributedLabelDelegate { func attributedLabel(_ label: TTTAttributedLabel!, didSelectLinkWith url: URL?) { if let url = url { UIApplication.shared.openURL(url) } } } // MARK: - Helpiloj extension InformojPaghoViewController { func didChangePreferredContentSize(notification: NSNotification) -> Void { etikedo?.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body) } }
mit
d990ed0f080818552b9dc21bdcda9226
31.862745
195
0.679296
4.52973
false
false
false
false
Journey321/xiaorizi
xiaorizi/Classes/SmallDay/SmallDayViewController.swift
1
3265
// // SmallDayViewController.swift // xiaorizi // // Created by JohnSon on 16/7/8. // Copyright © 2016年 zhike. All rights reserved. // import UIKit class SmallDayViewController: UIViewController { var cityBtn: TextImageButton! override func viewDidLoad() { super.viewDidLoad() self.title = "小日子" self.view.backgroundColor = UIColor.blueColor() let button = UIButton(type: UIButtonType.Custom) button.frame = CGRectMake(100, 100, 100, 30) button.backgroundColor = UIColor.redColor() button.addTarget(self, action: #selector(SmallDayViewController.btnClick(_:)), forControlEvents: UIControlEvents.TouchUpInside) self.view.addSubview(button) } func btnClick(button:UIButton){ // 1 创建分享参数 let shareParemes = NSMutableDictionary() shareParemes.SSDKSetupShareParamsByText("分享内容", images:UIImage(named:"collect.png"), url: NSURL(string:"http://mob.com"), title: "分享标题", type: SSDKContentType.Image) ShareSDK.showShareActionSheet(view, items:nil, shareParams: shareParemes) { (state : SSDKResponseState, type:SSDKPlatformType, userData : [NSObject : AnyObject]!, contentEntity :SSDKContentEntity!, error : NSError!, end:Bool) in switch state{ case SSDKResponseState.Success: print("分享成功") case SSDKResponseState.Fail: print("分享失败,错误描述:\(error)") case SSDKResponseState.Cancel: print("分享取消") default: break } } } // MARK: 初始化导航栏 func setupNav(){ cityBtn = TextImageButton(frame: CGRectMake(0, 20, 80, 44)) cityBtn.setTitle("上海", forState: UIControlState.Normal) cityBtn.titleLabel!.font = theme.navItemFont cityBtn.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal) cityBtn.setImage(UIImage(named: "city_1"), forState: UIControlState.Normal) cityBtn.addTarget(self, action: #selector(SmallDayViewController.selectedCityBtnClick), forControlEvents: .TouchUpInside) self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: cityBtn) self.navigationItem.rightBarButtonItem = UIBarButtonItem.barButtonItemWithRightIcon("camera5", highlightedIcon: "", target: self, action: #selector(SmallDayViewController.shareBtnClick)) } // MARK: 导航栏按钮点击事件 func shareBtnClick() { } func selectedCityBtnClick() { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
5e66bb094299ad0777e74f6e945e37b4
35.344828
236
0.64358
4.948357
false
false
false
false
lsn-sokna/TextFieldEffects
TextFieldEffects/TextFieldEffects/IsaoTextField.swift
1
5310
// // IsaoTextField.swift // TextFieldEffects // // Created by Raúl Riera on 29/01/2015. // Copyright (c) 2015 Raul Riera. All rights reserved. // import UIKit @IBDesignable public class IsaoTextField: TextFieldEffects { @IBInspectable public var inactiveColor: UIColor? { didSet { updateBorder() } } @IBInspectable public var activeColor: UIColor? { didSet { updateBorder() } } override public var placeholder: String? { didSet { updatePlaceholder() } } override public var bounds: CGRect { didSet { updateBorder() updatePlaceholder() } } private let borderThickness: (active: CGFloat, inactive: CGFloat) = (4, 2) private let placeholderInsets = CGPoint(x: 6, y: 6) private let textFieldInsets = CGPoint(x: 6, y: 6) private let borderLayer = CALayer() // MARK: - TextFieldsEffectsProtocol override public func drawViewsForRect(rect: CGRect) { let frame = CGRect(origin: CGPointZero, size: CGSize(width: rect.size.width, height: rect.size.height)) placeholderLabel.frame = CGRectInset(frame, placeholderInsets.x, placeholderInsets.y) placeholderLabel.font = placeholderFontFromFont(font!) updateBorder() updatePlaceholder() layer.addSublayer(borderLayer) addSubview(placeholderLabel) } private func updateBorder() { borderLayer.frame = rectForBorder(frame) borderLayer.backgroundColor = isFirstResponder() ? activeColor?.CGColor : inactiveColor?.CGColor } private func updatePlaceholder() { placeholderLabel.text = placeholder placeholderLabel.textColor = inactiveColor placeholderLabel.sizeToFit() layoutPlaceholderInTextRect() if isFirstResponder() { animateViewsForTextEntry() } } private func placeholderFontFromFont(font: UIFont) -> UIFont! { let smallerFont = UIFont(name: font.fontName, size: font.pointSize * 0.7) return smallerFont } private func rectForBorder(bounds: CGRect) -> CGRect { var newRect:CGRect if isFirstResponder() { newRect = CGRect(x: 0, y: bounds.size.height - font!.lineHeight + textFieldInsets.y - borderThickness.active, width: bounds.size.width, height: borderThickness.active) } else { newRect = CGRect(x: 0, y: bounds.size.height - font!.lineHeight + textFieldInsets.y - borderThickness.inactive, width: bounds.size.width, height: borderThickness.inactive) } return newRect } private func layoutPlaceholderInTextRect() { if text!.isNotEmpty { return } let textRect = textRectForBounds(bounds) var originX = textRect.origin.x switch textAlignment { case .Center: originX += textRect.size.width/2 - placeholderLabel.bounds.width/2 case .Right: originX += textRect.size.width - placeholderLabel.bounds.width default: break } placeholderLabel.frame = CGRect(x: originX, y: bounds.height - placeholderLabel.frame.height, width: placeholderLabel.frame.size.width, height: placeholderLabel.frame.size.height) } override public func animateViewsForTextEntry() { updateBorder() if let activeColor = activeColor { performPlacerholderAnimationWithColor(activeColor) } } override public func animateViewsForTextDisplay() { updateBorder() if let inactiveColor = inactiveColor { performPlacerholderAnimationWithColor(inactiveColor) } } private func performPlacerholderAnimationWithColor(color: UIColor) { let yOffset: CGFloat = 4 UIView.animateWithDuration(0.15, animations: { self.placeholderLabel.transform = CGAffineTransformMakeTranslation(0, -yOffset) self.placeholderLabel.alpha = 0 }) { (completed) in self.placeholderLabel.transform = CGAffineTransformIdentity self.placeholderLabel.transform = CGAffineTransformMakeTranslation(0, yOffset) UIView.animateWithDuration(0.15, animations: { self.placeholderLabel.textColor = color self.placeholderLabel.transform = CGAffineTransformIdentity self.placeholderLabel.alpha = 1 }) } } // MARK: - Overrides override public func editingRectForBounds(bounds: CGRect) -> CGRect { let newBounds = CGRect(x: 0, y: 0, width: bounds.size.width, height: bounds.size.height - font!.lineHeight + textFieldInsets.y) return CGRectInset(newBounds, textFieldInsets.x, 0) } override public func textRectForBounds(bounds: CGRect) -> CGRect { let newBounds = CGRect(x: 0, y: 0, width: bounds.size.width, height: bounds.size.height - font!.lineHeight + textFieldInsets.y) return CGRectInset(newBounds, textFieldInsets.x, 0) } }
mit
406ac1cd13afb13384cc0533f6d86bd8
33.032051
183
0.621774
5.395325
false
false
false
false
bluquar/emoji_keyboard
DecisiveEmojiKeyboard/DEKeyboard/EmojiSelectionController.swift
1
5597
// // EmojiSelectionController.swift // DecisiveEmojiKeyboard // // Created by Chris Barker on 11/25/14. // Copyright (c) 2014 Chris Barker. All rights reserved. // import UIKit // Implements the core logic of the EmojiSelectKB Keyboard class EmojiSelectionController: NSObject { var imageOptions: [ImageSelectionOption] let maxSelections: Int = 3 // How many choices to make before inserting a character var numSelections: Int var imageOptionsSelected: [ImageSelectionOption: Bool] var imageOptionsRemaining: [ImageSelectionOption: Bool] var accumulator: EmojiScore var buttonManager: ButtonLayoutManager var keyboardVC: KeyboardViewController! init(buttonManager: ButtonLayoutManager) { self.numSelections = 0 self.buttonManager = buttonManager self.accumulator = EmojiScore() self.imageOptions = [] self.imageOptionsSelected = [:] self.imageOptionsRemaining = [:] super.init() self.initParse() } func initParse() -> () { Parse.setApplicationId("J3RRC4EBBpTJhzKEJ6SWSfWZ3bPUo6mFvAoPkK0C", clientKey: "RIkvgQJiE8IIt6fd4muh68KitSQhajdEMpYKlxkl") } func getImagePath(name: String) -> String { return name } func parseImageOptions(text: String) -> [ImageSelectionOption] { var options: [ImageSelectionOption] = [] let lines = text.componentsSeparatedByString("\n") var i: Int = 0 while i+2 < lines.count { options.append(ImageSelectionOption(controller: self, path: self.getImagePath(lines[i]), score: EmojiScore(emojis: lines[i+1]))) i += 3 } return options } func loadImageOptions() -> [ImageSelectionOption] { let bundle = NSBundle.mainBundle() let resources: [AnyObject] = bundle.pathsForResourcesOfType("txt", inDirectory: nil) let path: String = resources[0].stringByResolvingSymlinksInPath let text: String = String(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil) let options: [ImageSelectionOption] = self.parseImageOptions(text) let loader = BackgroundImageLoader(options: options) loader.start() return options } func viewDidLoad(keyboardVC: KeyboardViewController) -> Void { self.keyboardVC = keyboardVC self.imageOptions = self.loadImageOptions() self.resetState() } func allOptions() -> [ImageSelectionOption: Bool] { var options: [ImageSelectionOption: Bool] = [:] for option: ImageSelectionOption in self.imageOptions { options[option] = true } return options } func resetState() { self.numSelections = 0 self.accumulator = EmojiScore() self.imageOptionsSelected = [:] self.imageOptionsRemaining = self.allOptions() self.refreshButtons() } func refreshButtons() -> () { self.buttonManager.updateButtons(self.getOptions(self.buttonManager.optionsPerGrid())) } func getOptions(count: Int) -> [SelectionOption] { var options: [SelectionOption] = [] for _ in 0..<count { options.append(self.takeBest()) } return options } func readyForEmojiOptions() -> Bool { if self.imageOptionsRemaining.count == 0 { return true } else if self.numSelections >= self.maxSelections { return true } return false } func finalSelect(selection: EmojiSelectionOption) -> () { let emoji = selection.emoji self.updatePreferences(emoji) self.keyboardVC.insertText(emoji) self.resetState() } func updatePreferences(emoji: String) -> () { for (imageSelection: ImageSelectionOption, _) in self.imageOptionsSelected { imageSelection.score.add(EmojiScore(mapping: [emoji: 1])) var emojiObject : PFObject = PFObject(className: "Emoji", dictionary: ["UnicodeValue": emoji]) var imageObject: PFObject = PFObject(className: "Image", dictionary: ["ImageFile": imageSelection.path, "ImageName": imageSelection.path]) var ratingObject: PFObject = PFObject(className: "Rating", dictionary: ["Emoji": emojiObject, "Rating": imageSelection.score.score(emoji)]) var emojiScoreObject: PFObject = PFObject(className: "ImageScore", dictionary: ["Image": imageObject, "Score": ratingObject, "User": PFUser.currentUser()]) } } func incrementalSelect(selection: ImageSelectionOption) -> Void { self.numSelections++ self.accumulator.add(selection.score) self.imageOptionsSelected[selection] = true self.refreshButtons() } func takeBest() -> SelectionOption { if self.readyForEmojiOptions() { return EmojiSelectionOption(controller: self, emoji: self.accumulator.removeBest()) } else { var bestOption: ImageSelectionOption? = nil var bestRating: Int = -1 for (option, _) in self.imageOptionsRemaining { let rating: Int = option.score.dot(self.accumulator) if bestOption == nil || bestRating <= rating { bestRating = rating bestOption = option } } let idx = imageOptionsRemaining.indexForKey(bestOption!) self.imageOptionsRemaining.removeAtIndex(idx!) return bestOption! } } }
gpl-2.0
e9f279b005618ac03a5ccfbd712003a8
35.581699
167
0.63266
4.771526
false
false
false
false
peteratseneca/dps923winter2015
Week_10/Where Am I/Classes/ExampleList.swift
3
2908
// // ExampleList.swift // Classes // // Created by Peter McIntyre on 2015-02-01. // Copyright (c) 2015 School of ICT, Seneca College. All rights reserved. // import UIKit import CoreData // Notice the protocol conformance class ExampleList: UITableViewController, NSFetchedResultsControllerDelegate { // MARK: - Private properties var frc: NSFetchedResultsController! // MARK: - Properties // Passed in by the app delegate during app initialization var model: Model! // MARK: - View lifecycle override func viewDidLoad() { super.viewDidLoad() // Configure and load the fetched results controller (frc) frc = model.frc_example // This controller will be the frc delegate frc.delegate = self; // No predicate (which means the results will NOT be filtered) frc.fetchRequest.predicate = nil; // Create an error object var error: NSError? = nil // Perform fetch, and if there's an error, log it if !frc.performFetch(&error) { println(error?.description) } } // MARK: - Table view methods override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return self.frc.sections?.count ?? 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let sectionInfo = self.frc.sections![section] as NSFetchedResultsSectionInfo return sectionInfo.numberOfObjects } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell self.configureCell(cell, atIndexPath: indexPath) return cell } func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) { let item: AnyObject = frc.objectAtIndexPath(indexPath) cell.textLabel!.text = item.valueForKey("attribute1")! as? String } // MARK: - Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "toExampleDetail" { // Get a reference to the destination view controller let vc = segue.destinationViewController as ExampleDetail // From the data source (the fetched results controller)... // Get a reference to the object for the tapped/selected table view row let item = frc.objectAtIndexPath(self.tableView.indexPathForSelectedRow()!) as Sport // Pass on the object vc.detailItem = item // Configure the view if you wish vc.title = item.valueForKey("attribute1") as? String } } }
mit
f8b1297a9e9d15786e74e193aaab0fd3
30.268817
118
0.644085
5.395176
false
false
false
false
tedvb/Looking-Glass
Looking Glass/Looking Glass/AppDelegate.swift
1
3895
// // AppDelegate.swift // Looking Glass // // Created by Ted von Bevern on 6/26/14. // Copyright (c) 2014 Ted von Bevern. All rights reserved. // import Cocoa class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet var window: NSWindow! @IBOutlet var plot: SPPlotController! func applicationDidFinishLaunching(aNotification: NSNotification?) { // Insert code here to initialize your application var data = LGSeries() var y = 0.0 let noiseAmplitude = 0.07 for x in 0..<2048 { y += (Double(arc4random_uniform(1000)) / 1000.0 - 0.5) * noiseAmplitude data.append((Double(x)/2048*5, y)) } var filter = LGModifiedHaarFilter(inputSeries: data) filter.compute() let lastCoefficient = filter.deviationCoefficients.count filter.deviationCoefficients[0] = 0.0 filter.deviationCoefficients[1] = 0.0 filter.deviationCoefficients[2] = 0.0 filter.deviationCoefficients[3] = 0.0 filter.deviationCoefficients[4] = 0.0 filter.deviationCoefficients[5] = 1.0 filter.deviationCoefficients[6] = 1.0 filter.deviationCoefficients[7] = 1.0 filter.deviationCoefficients[8] = 1.0 filter.deviationCoefficients[9] = 1.0 filter.synthesize() var dataArrayNS = dataArrayToNSMutableArray(data) var fourthTrendNS = dataArrayToNSMutableArray(filter.trendArrays[4]) var firstDeviationNS = dataArrayToNSMutableArray(filter.deviationArrays[0]) var secondDeviationNS = dataArrayToNSMutableArray(filter.deviationArrays[1]) var thirdDeviationNS = dataArrayToNSMutableArray(filter.deviationArrays[2]) var outputNS = dataArrayToNSMutableArray(filter.outputData) var dataSeries = SPDataSeries(name: "Original", data: dataArrayNS, color: SPColor.red().takeUnretainedValue()) var fourthTrendSeries = SPDataSeries(name: "256", data: fourthTrendNS, color: SPColor.yellow().takeUnretainedValue()) var firstDeviationSeries = SPDataSeries(name: "1024d", data: firstDeviationNS, color: SPColor.blue().takeUnretainedValue()) var secondDeviationSeries = SPDataSeries(name: "512d", data: secondDeviationNS, color: SPColor.yellow().takeUnretainedValue()) var thirdDeviationSeries = SPDataSeries(name: "256d", data: thirdDeviationNS, color: SPColor.red().takeUnretainedValue()) var outputSeries = SPDataSeries(name: "output", data: outputNS, color: SPColor.white().takeUnretainedValue()) plot.addDataSeries(dataSeries) plot.addDataSeries(fourthTrendSeries) //plot.addDataSeries(firstDeviationSeries) //plot.addDataSeries(secondDeviationSeries) //plot.addDataSeries(thirdDeviationSeries) plot.addDataSeries(outputSeries) plot.xMin = -0.5 plot.xMax = 5.0 plot.yMin = -1.5 plot.yMax = 1.5 plot.numXTicks = 6 plot.numYTicks = 5 plot.axisLineWeight = 0.5 plot.seriesLineWeight = 0.5 plot.axisColor = SPColor.green().takeUnretainedValue() plot.reDraw() filter.synthesize() /*var sum = 0.0 for var i = 0; i < data.count; ++i { sum += abs(data[i].y - filter.outputData[i].y) //println("\(data[i].y), \(filter.outputData[i].y)") } println(sum)*/ } func dataArrayToNSMutableArray(data: LGSeries) -> NSMutableArray { var out = NSMutableArray() for i in data { out.addObject(SPPoint.pointWithX(i.x, andY: i.y)) } return out } func applicationWillTerminate(aNotification: NSNotification?) { // Insert code here to tear down your application } }
mit
de5cf619aeb33926853a7f609c5b5310
36.095238
134
0.636457
4.631391
false
false
false
false
Miguel-Herrero/Swift
Landmarks/Landmarks/PageControl.swift
1
1116
// // PageControl.swift // Landmarks // // Created by Miguel Herrero Baena on 20/06/2019. // Copyright © 2019 Miguel Herrero Baena. All rights reserved. // import SwiftUI import UIKit struct PageControl: UIViewRepresentable { var numberOfPages: Int @Binding var currentPage: Int func makeCoordinator() -> Coordinator { Coordinator(self) } func makeUIView(context: Context) -> UIPageControl { let control = UIPageControl() control.numberOfPages = numberOfPages control.addTarget( context.coordinator, action: #selector(Coordinator.updateCurrentPage(sender:)), for: .valueChanged) return control } func updateUIView(_ uiView: UIPageControl, context: Context) { uiView.currentPage = currentPage } class Coordinator: NSObject { var control: PageControl init(_ control: PageControl) { self.control = control } @objc func updateCurrentPage(sender: UIPageControl) { control.currentPage = sender.currentPage } } }
gpl-3.0
5d0504c5e549ff83d58fd4d9f6e2e2a3
22.723404
70
0.633184
5.114679
false
false
false
false
ricardorauber/iOS-Swift
iOS-Swift.playground/Pages/Functional Programming.xcplaygroundpage/Contents.swift
1
891
//: ## Functional Programming //: ---- //: [Previous](@previous) import Foundation //: Filtering let evenAndOddNumbers = Array(0..<10) let onlyEvenNumbers = evenAndOddNumbers.filter { $0 % 2 == 0 } print(onlyEvenNumbers) //: Reducing let purchases = [0.35, 4.82, 8.34, 8.0, 2.4, 5.6, 9.9, 6.3, 4.6, 7.7] let total = purchases.reduce(0) { $0 + $1 } print(total) //: Mapping let numbers = Array(0..<10) let strings = numbers.map { "The number is " + String($0) } print(strings) //: FlatMap let nestedArrays = [[0, 1, 2], [3, 4, 5], [6, 7, 8]] let flatArray = nestedArrays.flatMap { $0 } print(flatArray) //: Combining uses let numbersArray = Array(0..<10) let stringResult = numbersArray.filter { $0 % 2 == 0 } .map { "[\($0)]" } .reduce("List of even numbers:") { $0 + " " + $1 } print(stringResult) //: [Next](@next)
mit
c72ced6449066e88712e64f1c252ccba
21.846154
81
0.573513
2.960133
false
false
false
false
powerfolder/Cuckoo
Generator/Source/CuckooGeneratorFramework/Tokens/MethodParameter.swift
1
1184
// // MethodParameter.swift // CuckooGenerator // // Created by Filip Dolnik on 30.05.16. // Copyright © 2016 Brightify. All rights reserved. // public struct MethodParameter: Token { public let label: String? public let name: String public let type: String public let range: CountableRange<Int> public let nameRange: CountableRange<Int> public var labelAndName: String { if let label = label { return label != name ? "\(label) \(name)" : name } else { return "_ \(name)" } } public var typeWithoutAttributes: String { return type.replacingOccurrences(of: "@escaping", with: "").replacingOccurrences(of: "@autoclosure", with: "").trimmed } public func isEqual(to other: Token) -> Bool { guard let other = other as? MethodParameter else { return false } return self.name == other.name } public func serialize() -> [String : Any] { return [ "label": label, "name": name, "type": type, "labelAndName": labelAndName, "typeWithoutAttributes": typeWithoutAttributes ] } }
mit
bd632dd49f1c4ad908134eb105d10872
27.166667
126
0.590025
4.55
false
false
false
false
gradyzhuo/Acclaim
Sources/Procedure/Intents.swift
1
3139
// // Intents.swift // Procedure // // Created by Grady Zhuo on 2017/9/2. // Copyright © 2017年 Grady Zhuo. All rights reserved. // import Foundation import Logger public struct Intents { public typealias IntentType = Intent internal var storage: [String: IntentType] = [:] public var commands: [String] { return storage.keys.map{ $0 } } public var count:Int{ return storage.count } public mutating func add(intent: IntentType?){ guard let intent = intent else{ Logger.debug("An intent to add into intents(\(withUnsafePointer(to: &self, { $0 }))) is nil.") return } storage[intent.command] = intent } public mutating func add(intents: [IntentType]){ for intent in intents { self.add(intent: intent) } } public mutating func add(intents: Intents){ for (_, intent) in intents.storage{ self.add(intent: intent) } } public mutating func remove(for name: String)->IntentType!{ return storage.removeValue(forKey: name) } public mutating func remove(intent: IntentType){ storage.removeValue(forKey: intent.command) } public func contains(command: String)->Bool { return commands.contains(command) } public func contains(intent: SimpleIntent)->Bool { return commands.contains(intent.command) } public func intent(for name: String)-> IntentType! { return storage[name] } //MARK: - init public static var empty: Intents { return [] } public init(array intents: [IntentType]){ self.add(intents: intents) } public init(intents: Intents){ self.add(intents: intents) } //MARK: - subscript public subscript(name: String)->IntentType!{ set{ guard let intent = newValue else { return } self.add(intent: intent) } get{ return intent(for: name) } } } extension Intents : ExpressibleByArrayLiteral{ public typealias Element = IntentType public init(arrayLiteral elements: Element...) { self = Intents(array: elements) } } extension Intents : ExpressibleByDictionaryLiteral{ public typealias Key = String public typealias Value = Any public init(dictionaryLiteral elements: (Key, Value)...) { for (key, value) in elements { let intent = SimpleIntent(command: key, value: value) self.add(intent: intent) } } } public func +(lhs: Intents, rhs: Intents)->Intents{ var gifts = lhs gifts.add(intents: rhs) return gifts } public func +(lhs: Intents, rhs: Intents.IntentType)->Intents{ var intents = lhs intents.add(intent: rhs) return intents } public func +(lhs: Intents, rhs: String)->Intents{ var intents = lhs intents.add(intent: SimpleIntent(command: rhs)) return intents }
mit
242b6bb794fc87a81596cc6f0a9e69a0
21.890511
106
0.581952
4.551524
false
false
false
false
BBRick/wp
wp/Scenes/Share/RechageVC/SelectBankVC.swift
1
3741
// // BankCardVC.swift // wp // // Created by sum on 2017/1/11. // Copyright © 2017年 com.yundian. All rights reserved. // class SelectBankVC: BaseListTableViewController { //定义选择的行数 var selectNumber = Int() var dataArry : [BankListModel] = [] var finishBtn = UIButton() override func viewDidLoad() { //默认开始选择的是第一行 selectNumber = 100000 self.title = "我的银行卡" super.viewDidLoad() initUI() } func initUI(){ // 设置 提现记录按钮 finishBtn = UIButton.init(frame: CGRect.init(x: 30, y: 0, width: 40, height: 30)) finishBtn.titleLabel?.font = UIFont.systemFont(ofSize: 15) finishBtn.setTitle("完成", for: UIControlState.normal) finishBtn.addTarget(self, action: #selector(finish), for: UIControlEvents.touchUpInside) finishBtn.isHidden = true let barItem :UIBarButtonItem = UIBarButtonItem.init(customView: finishBtn as UIView) self.navigationItem.rightBarButtonItem = barItem } //MARK: 点击完成按钮 func finish(){ //做数组保护 不等于1000的时候来进行充值 if selectNumber != 100000 { let Model : BankListModel = self.dataArry[selectNumber] ShareModel.share().selectBank = Model _ = self.navigationController?.popViewController(animated: true) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // self.didRequest() } //MARK: --网络请求 override func didRequest() { AppAPIHelper.user().bankcardList(complete: { [weak self](result) -> ()? in if let object = result { let Model : BankModel = object as! BankModel self?.didRequestComplete(Model.cardlist as AnyObject) self?.dataArry = Model.cardlist! self?.tableView.reloadData() }else { self?.didRequestComplete(nil) } return nil }, error: errorBlockFunc()) } //MARK: --tableView的代理和数据源的设置 override func numberOfSections(in tableView: UITableView) -> Int { return dataArry.count } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat{ return 15 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ return 1 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell : BindingBankVCCell = tableView.dequeueReusableCell(withIdentifier: "BankCardVCCell") as! BindingBankVCCell let Model : BankListModel = self.dataArry[indexPath.section] cell.update(Model.self) cell.contentView.alpha = 0.7 if indexPath.section == selectNumber { cell.contentView.alpha = 1 // cell.accessoryType = UITableViewCellAccessoryType .checkmark } return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){ selectNumber = indexPath.section tableView.reloadData() finishBtn.isHidden = false } //MARK: -- 添加银行卡点击事件 @IBAction func addbank(_ sender: Any) { } }
apache-2.0
e40f30704ed058351f186df688c5dd61
28.85
124
0.570073
5.117143
false
false
false
false
deirinberg/MDCalendarSelector
MDCalendarSelector/MDCalendarSelector.swift
1
25922
// // MDCalendarSelector.swift // MDCalendarSelector // // Created by Dylan Eirinberg on 10/26/15. // Copyright © 2015 Dylan Eirinberg. All rights reserved. // import Foundation import UIKit import PureLayout public protocol MDCalendarSelectorDelegate { func calendarSelector(calendarSelector: MDCalendarSelector, startDateChanged startDate: NSDate) func calendarSelector(calendarSelector: MDCalendarSelector, endDateChanged endDate: NSDate) } public class MDCalendarSelector: UIView { public var delegate: MDCalendarSelectorDelegate? // public variables // changes color behind the main section of the calendar public var backgroundViewColor: UIColor = UIColor.blackColor() // background color of header and of selected days public var highlightedColor: UIColor = UIColor.themeRedColor() // text color of days that can be selected public var dateTextColor: UIColor = UIColor.whiteColor() // text color of days that are in a different month public var nextDateTextColor: UIColor = UIColor(white: 1.0, alpha: 0.5) // text color of days that are disabled public var disabledTextColor: UIColor = UIColor(white: 1.0, alpha: 0.3) // text color of selected days and header month public var highlightedTextColor: UIColor = UIColor.whiteColor() // max amount of days that can be selected (default is 21 days), max is 28 public var maxRange: UInt = 21 // font name for all regular text public var regularFontName: String? // font name for all bold text public var boldFontName: String? // font size for the headerLabel text public var headerFontSize: CGFloat = 15.0 // font size for dates public var dateFontSize: CGFloat = 13.0 // public readonly variables public var startDate: NSDate? { get { if let date = prevMonthStartDate { return date } if startIndex == -1 { return nil } return dateFromDateLabelsIndex(startIndex) } } public var endDate: NSDate? { get { if let date = nextMonthEndDate { return date } if endIndex == -1 { return nil } return dateFromDateLabelsIndex(endIndex) } } public var selectedLength: Int { get { let calendar = NSCalendar.currentCalendar() let unit: NSCalendarUnit = .Day if let date = prevMonthStartDate { let components = calendar.components(unit, fromDate: date, toDate: endDate!, options: []) return components.day + 1 } if let date = nextMonthEndDate { let components = calendar.components(unit, fromDate: startDate!, toDate: date, options: []) return components.day + 1 } return endIndex - startIndex + 1 } } // private variables (UI) private var headerView: UIView! private var headerLabel: UILabel! private var calendarView: UIView! private var weekdayLabelsContainerView: UIView! private var monthButtonsContainerView: UIView! private var boxViews: [MDBoxView] = [] private var weekdayLabels: [UILabel] = [] private var dateLabels: [UILabel] = [] // private variables (data) private var startIndex: Int = -1 { didSet { if startIndex > 0 { prevMonthStartDate = nil } delegate?.calendarSelector(self, startDateChanged: startDate!) } } private var endIndex: Int = -1 { didSet { if endIndex < numDaysPerWeek*numRows - 1 { nextMonthEndDate = nil } delegate?.calendarSelector(self, endDateChanged: endDate!) } } private var lastSelectedIndex: Int = -1 private var todayIndex: Int = -1 private var todayDate: NSDate = NSDate() private var currentDate: NSDate = NSDate() private var currentYear: Int = -1 private var prevMonthStartDate: NSDate? private var nextMonthEndDate: NSDate? private let numDaysPerWeek: Int = 7 private let numRows: Int = 6 private let numMonths: Int = 12 private let maxMonthDays: Int = 31 private let minMonthDays: Int = 28 private var didSetupConstraints: Bool = false init(){ super.init(frame: CGRectMake(0, 0, 300, 300)) commonInit() } override init(frame: CGRect) { super.init(frame: frame) commonInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } func commonInit() { self.layer.cornerRadius = 8.0 self.layer.masksToBounds = true headerView = UIView.newAutoLayoutView() headerView.backgroundColor = highlightedColor addSubview(headerView) headerLabel = UILabel.newAutoLayoutView() headerLabel.textColor = highlightedTextColor headerView.addSubview(headerLabel) calendarView = UIView.newAutoLayoutView() calendarView.backgroundColor = backgroundViewColor addSubview(calendarView) weekdayLabelsContainerView = UIView.newAutoLayoutView() calendarView.addSubview(weekdayLabelsContainerView) for i in 0...numDaysPerWeek { let dayOfWeekLabel = UILabel.newAutoLayoutView() switch(i) { case 0: dayOfWeekLabel.text = "Sun" break case 1: dayOfWeekLabel.text = "Mon" break case 2: dayOfWeekLabel.text = "Tue" break case 3: dayOfWeekLabel.text = "Wed" break case 4: dayOfWeekLabel.text = "Thu" break case 5: dayOfWeekLabel.text = "Fri" break case 6: dayOfWeekLabel.text = "Sat" break default: break } dayOfWeekLabel.textColor = highlightedTextColor dayOfWeekLabel.font = regularFontOfSize(dateFontSize) dayOfWeekLabel.textAlignment = .Center weekdayLabels.append(dayOfWeekLabel) weekdayLabelsContainerView .addSubview(dayOfWeekLabel) } monthButtonsContainerView = UIView.newAutoLayoutView() calendarView.addSubview(monthButtonsContainerView) for _ in 0..<numRows { let boxView = MDBoxView.newAutoLayoutView() boxView.backgroundColor = highlightedColor boxViews.append(boxView) monthButtonsContainerView.addSubview(boxView) } for _ in 0..<numDaysPerWeek*numRows { let label = UILabel.newAutoLayoutView() label.textAlignment = .Center label.layer.masksToBounds = true dateLabels.append(label) monthButtonsContainerView.addSubview(label) } currentYear = todayDate.year populateMonth(todayDate) updateConstraints() } override public func updateConstraints() { if !didSetupConstraints { headerView .autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsZero, excludingEdge: .Bottom) headerLabel.autoPinEdgeToSuperviewEdge(.Top, withInset: 8.0) headerLabel.autoPinEdgeToSuperviewEdge(.Bottom, withInset: 7.0) headerLabel .autoAlignAxisToSuperviewAxis(.Vertical) calendarView.autoPinEdge(.Top, toEdge: .Bottom, ofView: headerView) calendarView.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsZero, excludingEdge: .Top) weekdayLabelsContainerView.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsZero, excludingEdge: .Bottom) monthButtonsContainerView.autoPinEdge(.Top, toEdge: .Bottom, ofView: weekdayLabelsContainerView) monthButtonsContainerView.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsZero, excludingEdge: .Top) for i in 0..<boxViews.count { let boxView: MDBoxView = boxViews[i] let startLabel: UILabel = dateLabels[i*numDaysPerWeek] boxView.autoPinEdge(.Top, toEdge: .Top, ofView: startLabel) boxView.autoPinEdge(.Bottom, toEdge: .Bottom, ofView: startLabel) } for i in 0..<weekdayLabels.count { let label: UILabel = weekdayLabels[i] label.autoPinEdgeToSuperviewEdge(.Top, withInset: 5.0) label.autoPinEdgeToSuperviewEdge(.Bottom) if i % numDaysPerWeek == 0 { label .autoPinEdgeToSuperviewEdge(.Leading, withInset: 5) } else { let prevLabel: UILabel = weekdayLabels[i - 1] label.autoPinEdge(.Leading, toEdge: .Trailing, ofView: prevLabel, withOffset: 5) label.autoMatchDimension(.Width, toDimension: .Width, ofView: prevLabel) } if i % numDaysPerWeek == numDaysPerWeek - 1 { label .autoPinEdgeToSuperviewEdge(.Trailing, withInset: 5) } } for i in 0..<dateLabels.count { let label: UILabel = dateLabels[i] if i % numDaysPerWeek == 0 { label.autoPinEdgeToSuperviewEdge(.Leading, withInset: 5) } else { let prevLabel: UILabel = dateLabels[i-1] label.autoPinEdge(.Leading, toEdge: .Trailing, ofView: prevLabel, withOffset: 5) label.autoMatchDimension(.Width, toDimension: .Width, ofView: prevLabel) } if i % numDaysPerWeek == numDaysPerWeek - 1 { label.autoPinEdgeToSuperviewEdge(.Trailing, withInset: 5) } if i <= numRows { label.autoPinEdgeToSuperviewEdge(.Top, withInset: 5) } else { let aboveLabel: UILabel = dateLabels[i - numDaysPerWeek] label.autoPinEdge(.Top, toEdge: .Bottom, ofView: aboveLabel) } if i > dateLabels.count - numDaysPerWeek { label.autoPinEdgeToSuperviewEdge(.Bottom, withInset: 5) } label.autoMatchDimension(.Height, toDimension: .Width, ofView: label) } didSetupConstraints = true } super.updateConstraints() } override public func layoutSubviews() { super.layoutSubviews() for i in 0..<42 { let label: UILabel = dateLabels[i] label.layer.cornerRadius = 15 } } private func populateMonth(date: NSDate) { currentDate = date currentYear = date.year let attributedDate: NSMutableAttributedString = NSMutableAttributedString(string: "\(date.monthString) \(date.year)", attributes: [NSFontAttributeName: boldFontOfSize(headerFontSize)]) attributedDate.addAttribute(NSFontAttributeName, value: regularFontOfSize(headerFontSize), range: NSMakeRange(date.monthString.utf16.count, "\(date.year)".utf16.count + 1)) headerLabel.attributedText = attributedDate let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)! let components: NSDateComponents = calendar.components(NSCalendarUnit.Day, fromDate: date) let offsetComponents = NSDateComponents() offsetComponents.day = 1-components.day let calendarDate: NSDate = calendar.dateByAddingComponents(offsetComponents, toDate: date, options: NSCalendarOptions(rawValue: 0))! let additionalDays: Int = (calendarDate.dayOfWeekNum == 1) ? 7 : (calendarDate.dayOfWeekNum - 1) let daysBefore = (date.day - 1) + additionalDays let isCurrentMonth: Bool = date.dateString == NSDate().dateString if isCurrentMonth { todayIndex = daysBefore } for i in 0..<numDaysPerWeek*numRows { let dateLabel: UILabel = dateLabels[i] dateLabel.textColor = dateTextColor dateLabel.font = isCurrentMonth && i == todayIndex ? boldFontOfSize(dateFontSize) : regularFontOfSize(dateFontSize) if i < daysBefore { offsetComponents.day = -(daysBefore - i) let newDate = calendar.dateByAddingComponents(offsetComponents, toDate: date, options: .MatchFirst)! let newComponents: NSDateComponents = calendar.components(NSCalendarUnit.Day, fromDate: newDate) dateLabel.text = "\(newComponents.day)" } else if i > daysBefore { offsetComponents.day = i - daysBefore let newDate = calendar.dateByAddingComponents(offsetComponents, toDate: date, options: .MatchFirst)! let newComponents: NSDateComponents = calendar.components(NSCalendarUnit.Day, fromDate: newDate) dateLabel.text = "\(newComponents.day)" } else { dateLabel.text = "\(date.day)" dateLabel.textColor = dateTextColor } if currentDate.month == todayDate.month && currentDate.year == todayDate.year { if i < daysBefore { dateLabel.textColor = disabledTextColor } else if dateNextMonth(i) { dateLabel.textColor = nextDateTextColor } } else if datePrevMonth(i) || dateNextMonth(i) { dateLabel.textColor = nextDateTextColor } } } private func buttonSelected(index: Int) { if startIndex == -1 || index < startIndex { startIndex = index } else if endIndex == -1 || index > endIndex { endIndex = index } if endIndex == -1 { endIndex = startIndex } if index > startIndex && index < endIndex { endIndex = index } let range: Int = Int(maxRange) if selectedLength > range && index >= endIndex { incrementPrevMonthStartDate(selectedLength - range) if prevMonthStartDate == nil { startIndex = endIndex - range + 1 } else { delegate?.calendarSelector(self, startDateChanged: startDate!) } } if selectedLength > range && index <= startIndex { decrementNextMonthEndDate(selectedLength - range) if nextMonthEndDate == nil { endIndex = startIndex + range - 1 } else { delegate?.calendarSelector(self, endDateChanged: endDate!) } } if todayDate.month == currentDate.month && todayDate.year == currentDate.year { startIndex = max(startIndex, todayIndex) endIndex = max(endIndex, todayIndex) } if index != lastSelectedIndex { lastSelectedIndex = -1 } let startRow: Int = startIndex/numDaysPerWeek let endRow: Int = endIndex/numDaysPerWeek for i in 0..<boxViews.count { let boxView: MDBoxView = boxViews[i] boxView.leadingConstraint?.autoRemove() boxView.trailingConstaint?.autoRemove() if selectedLength > 1 { if i == startRow { let startLabel: UILabel = dateLabels[startIndex] boxView.leadingConstraint = boxView.autoPinEdge(.Leading, toEdge: .Leading, ofView: startLabel, withOffset: startLabel.bounds.size.width/2) } else if i > startRow && i <= endRow { let firstColumnLabel: UILabel = dateLabels[i*numDaysPerWeek] boxView.leadingConstraint = boxView.autoPinEdge(.Leading, toEdge: .Leading, ofView: firstColumnLabel, withOffset: firstColumnLabel.bounds.size.width/2) } if i == endRow { let endLabel: UILabel = dateLabels[endIndex] boxView.trailingConstaint?.autoRemove() boxView.trailingConstaint = boxView.autoPinEdge(.Trailing, toEdge: .Trailing, ofView: endLabel, withOffset: -endLabel.bounds.size.width/2) } else if i < endRow && i >= startRow { let lastColumnLabel: UILabel = dateLabels[i*numDaysPerWeek + numDaysPerWeek-1] boxView.trailingConstaint = boxView.autoPinEdge(.Trailing, toEdge: .Trailing, ofView: lastColumnLabel, withOffset: -lastColumnLabel.bounds.size.width/2) } } if i >= startRow && i <= endRow { boxView.backgroundColor = highlightedColor } else { boxView.backgroundColor = UIColor.clearColor() } } for i in 0..<dateLabels.count { let button = dateLabels[i] if i >= startIndex && i <= endIndex { button.backgroundColor = highlightedColor } else { button.backgroundColor = UIColor.clearColor() } } layoutIfNeeded() } private func datePrevMonth(index: Int) -> Bool { let dateLabel: UILabel = dateLabels[index] if let text = dateLabel.text { let day = Int(text)! let prevMonthMinCount: Int = minMonthDays - (numDaysPerWeek*numRows-maxMonthDays) let minIndex: Int = numDaysPerWeek*2 - 1 if index <= minIndex && day >= prevMonthMinCount { return true } } return false } private func dateNextMonth(index: Int) -> Bool { let dateLabel: UILabel = dateLabels[index] if let text = dateLabel.text { let day = Int(text)! let nextMonthMaxCount: Int = numDaysPerWeek*numRows-minMonthDays let maxIndex: Int = numDaysPerWeek*numRows - nextMonthMaxCount if index >= maxIndex && day <= nextMonthMaxCount { return true } } return false } private func incrementPrevMonthStartDate(change: Int) { if let date = prevMonthStartDate { prevMonthStartDate = NSCalendar.currentCalendar().dateByAddingUnit(.Day, value: abs(change), toDate: date, options: NSCalendarOptions(rawValue: 0)) let firstMonthDate: NSDate = dateFromDateLabelsIndex(0) if prevMonthStartDate!.compare(firstMonthDate) != .OrderedAscending { prevMonthStartDate = nil } } } private func decrementNextMonthEndDate(change: Int) { if let date = nextMonthEndDate { nextMonthEndDate = NSCalendar.currentCalendar().dateByAddingUnit(.Day, value: -abs(change), toDate: date, options: NSCalendarOptions(rawValue: 0)) let endMonthDate: NSDate = dateFromDateLabelsIndex(dateLabels.count - 1) if nextMonthEndDate!.compare(endMonthDate) != .OrderedDescending { nextMonthEndDate = nil } } } private func dateFromDateLabelsIndex(index: Int) -> NSDate { let dateLabel: UILabel = dateLabels[index] var month: Int = currentDate.month var year: Int = currentDate.year if dateNextMonth(index) { if month == numMonths { month = 1 year++ } else { month++ } } else if datePrevMonth(index) { if month == 1 { month = numMonths year-- } else { month-- } } let dateString: String = "\(year)-\(month)-\(dateLabel.text!)" let dateFormatter: NSDateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" return dateFormatter.dateFromString(dateString)! } public func goToToday() { populateMonth(todayDate) startIndex = todayIndex endIndex = todayIndex buttonSelected(endIndex) } private func regularFontOfSize(size: CGFloat) -> UIFont { if let fontName = regularFontName, let font = UIFont(name: fontName, size: size) { return font } return UIFont.systemFontOfSize(size) } private func boldFontOfSize(size: CGFloat) -> UIFont { if let fontName = boldFontName, let font = UIFont(name: fontName, size: size) { return font } return UIFont.boldSystemFontOfSize(size) } // touch handling override public func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { touchesMoved(touches, withEvent: event) } override public func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { if let location = touches.first?.locationInView(monthButtonsContainerView) { if CGRectContainsPoint(monthButtonsContainerView.frame, location) { for i in 0..<dateLabels.count { let label: UILabel = dateLabels[i] if CGRectContainsPoint(label.frame, location) { buttonSelected(i) return } } } } } override public func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { if let location = touches.first?.locationInView(monthButtonsContainerView) { let minDateLabel: UILabel = dateLabels[0] let maxDateLabel: UILabel = dateLabels[dateLabels.count - 1] let relativeLocationX: CGFloat = min(max(location.x, minDateLabel.center.x), maxDateLabel.center.x) let relativeLocationY: CGFloat = min(max(location.y, minDateLabel.center.y), maxDateLabel.center.y) let relativeLocation: CGPoint = CGPointMake(relativeLocationX, relativeLocationY) for i in 0..<dateLabels.count { let label: UILabel = dateLabels[i] if CGRectContainsPoint(label.frame, relativeLocation) { if i < todayIndex && currentDate.month == todayDate.month && currentDate.year == todayDate.year { return } let firstDate: NSDate = dateFromDateLabelsIndex(numDaysPerWeek) let lastDate: NSDate = dateFromDateLabelsIndex(numDaysPerWeek*numRows - 1) let date: NSDate = dateFromDateLabelsIndex(i) if date.month != currentDate.month || date.year != currentDate.year { let length = endIndex - startIndex prevMonthStartDate = startDate nextMonthEndDate = endDate if date.compare(currentDate) == .OrderedDescending { endIndex = (lastDate.day >= 7 && i >= numDaysPerWeek*(numRows - 1)) ? date.dayOfWeekNum - 1 + numDaysPerWeek : date.dayOfWeekNum - 1 startIndex = max(endIndex - length, 0) } else { let start = numDaysPerWeek*numRows - (numDaysPerWeek - date.dayOfWeekNum) - 1 startIndex = (firstDate.day == 1) ? start - numDaysPerWeek : start endIndex = min(startIndex + length, numDaysPerWeek*numRows - 1) } let populateDate: NSDate = date.month == todayDate.month && date.year == todayDate.year ? todayDate : date populateMonth(populateDate) buttonSelected(endIndex) delegate?.calendarSelector(self, startDateChanged: startDate!) delegate?.calendarSelector(self, endDateChanged: endDate!) return } if i == lastSelectedIndex { startIndex = i endIndex = i buttonSelected(i) lastSelectedIndex = -1 } lastSelectedIndex = i return } } } } }
mit
3967e56cde1aff5069fab720a1ef179b
36.137536
192
0.551638
5.968455
false
false
false
false
idomizrachi/Regen
regen/ArgumentsParser.swift
1
2347
// // ArgumentsParser.swift // Regen // // Created by Ido Mizrachi on 7/15/16. // import Foundation protocol CanBeInitializedWithString { init?(_ description: String) } extension Int: CanBeInitializedWithString {} extension String: CanBeInitializedWithString {} class ArgumentsParser { let arguments : [String] let operationType: OperationType init(arguments : [String]) { self.arguments = arguments self.operationType = ArgumentsParser.parseOperationType(arguments: arguments) } private static func parseOperationType(arguments: [String]) -> OperationType { let operationTypeKey = parseOperationTypeKey(arguments) switch operationTypeKey { case .localization: guard let parameters = parseLocalizationParameters(arguments) else { return .usage } return .localization(parameters: parameters) case .images: guard let parameters = parseImagesParameters(arguments) else { return .usage } return .images(parameters: parameters) case .version: return .version case .usage: return .usage } } private static func parseOperationTypeKey(_ arguments: [String]) -> OperationType.Keys { guard let firstArgument = arguments.first else { return .usage } return OperationType.Keys(rawValue: firstArgument) ?? .usage } private static func parseLocalizationParameters(_ arguments: [String]) -> Localization.Parameters? { let parser = LocalizationParametersParser(arguments: arguments) return parser.parse() } private static func parseImagesParameters(_ arguments: [String]) -> Images.Parameters? { let parser = ImagesParametersParser(arguments: arguments) return parser.parse() } // private static func parseAssetsFile(arguments: [String]) -> String? { // let assetsFile: String? = tryParse("--assets-file", from: arguments) // return assetsFile // } private static func isVersionOperation(_ arguments: [String]) -> Bool { guard let firstArgument = arguments.first else { return false } return firstArgument.lowercased() == OperationType.Keys.version.rawValue } }
mit
13ab93d588782f10604db2425fd6f53f
29.881579
104
0.649766
5.091106
false
false
false
false
Esri/arcgis-runtime-samples-ios
arcgis-ios-sdk-samples/Content Display Logic/Controllers/Progress View Controller/ProgressViewController.swift
1
5619
// Copyright 2021 Esri // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit extension UIViewController: GlobalProgressDisplayable { var window: UIWindow? { view.window } } extension UIApplication: GlobalProgressDisplayable { var window: UIWindow? { windows.first } } protocol GlobalProgressDisplayable { var window: UIWindow? { get } } extension GlobalProgressDisplayable { func showProgressHUD(message: String, duration: TimeInterval? = nil) { GlobalProgress.shared.showProgress(message: message, duration: duration, window: window, animated: true) } func showErrorHUD(error: Error, duration: TimeInterval = 2.0) { GlobalProgress.shared.showProgress(message: error.localizedDescription, duration: duration, window: window, animated: false) } func hideProgressHUD() { GlobalProgress.shared.hideProgress() } } private class GlobalProgress { static let shared = GlobalProgress() private init() { } private var alertWindow: UIWindow? private var timer: Timer? func showProgress(message: String, duration: TimeInterval?, window: UIWindow?, animated: Bool) { // Invalidate old timer, if one exists. if let timer = timer { timer.invalidate() self.timer = nil } // Update existing progress if already presented. if let alertWindow = alertWindow { (alertWindow.rootViewController as! PhantomViewController).progressViewController.label.text = message } else { let progressWindow = UIWindow(frame: window?.frame ?? UIScreen.main.bounds) let progressViewController = ProgressViewController() progressViewController.loadViewIfNeeded() progressViewController.label.text = message let phantom = PhantomViewController(progressViewController: progressViewController) progressWindow.rootViewController = phantom progressWindow.windowLevel = .alert + 1 progressWindow.makeKeyAndVisible() alertWindow = progressWindow } // Create a timer to dismiss if a duration is set. if let duration = duration { timer = Timer.scheduledTimer(withTimeInterval: duration, repeats: false) { [unowned self] _ in self.timer = nil self.hideProgress() } } } func hideProgress() { guard let window = alertWindow, let phantom = window.rootViewController as? PhantomViewController else { return } phantom.progressViewController.dismiss(animated: true) { guard let alertWindow = self.alertWindow else { return } alertWindow.resignKey() self.alertWindow = nil } } } private class ProgressViewController: UIViewController { @IBOutlet var label: UILabel! @IBOutlet var activityView: UIActivityIndicatorView! init() { super.init(nibName: "ProgressViewController", bundle: Bundle.main) view.backgroundColor = backgroundColor(for: traitCollection.userInterfaceStyle) } @available(*, unavailable) override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { fatalError("init(nibName:bundle:) has not been implemented") } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) view.backgroundColor = backgroundColor(for: traitCollection.userInterfaceStyle) } func backgroundColor(for userInterfaceStyle: UIUserInterfaceStyle) -> UIColor { let backgroundColor: UIColor switch userInterfaceStyle { case .dark: backgroundColor = UIColor.black.withAlphaComponent(0.48) default: backgroundColor = UIColor.black.withAlphaComponent(0.2) } return backgroundColor } } private class PhantomViewController: UIViewController { let progressViewController: ProgressViewController // MARK: - Init init(progressViewController: ProgressViewController) { self.progressViewController = progressViewController super.init(nibName: nil, bundle: nil) } @available(*, unavailable) override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { fatalError("init(nibName:bundle:) has not been implemented") } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Lifecycle override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) progressViewController.modalTransitionStyle = .crossDissolve progressViewController.modalPresentationStyle = .overFullScreen present(progressViewController, animated: true) } }
apache-2.0
26738dd3930370a746f51e9ac7c33990
35.019231
132
0.678235
5.481951
false
false
false
false
yangchenghu/actor-platform
actor-apps/app-ios/ActorApp/Controllers/Contacts/Cells/ContactCell.swift
4
1985
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import Foundation import UIKit class ContactCell : BasicCell { let avatarView = AvatarView(frameSize: 40, type: .Rounded); let shortNameView = UILabel(); let titleView = UILabel(); init(reuseIdentifier:String) { super.init(reuseIdentifier: reuseIdentifier, separatorPadding: 80) titleView.font = UIFont.systemFontOfSize(18) titleView.textColor = MainAppTheme.list.contactsTitle shortNameView.font = UIFont.boldSystemFontOfSize(18) shortNameView.textAlignment = NSTextAlignment.Center shortNameView.textColor = MainAppTheme.list.contactsShortTitle self.contentView.addSubview(avatarView); self.contentView.addSubview(shortNameView); self.contentView.addSubview(titleView); backgroundColor = MainAppTheme.list.bgColor let selectedView = UIView() selectedView.backgroundColor = MainAppTheme.list.bgSelectedColor selectedBackgroundView = selectedView } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func bindContact(contact: ACContact, shortValue: String?, isLast: Bool) { avatarView.bind(contact.getName(), id: contact.getUid(), avatar: contact.getAvatar()); titleView.text = contact.getName(); if (shortValue == nil){ shortNameView.hidden = true; } else { shortNameView.text = shortValue!; shortNameView.hidden = false; } hideSeparator(isLast) } override func layoutSubviews() { super.layoutSubviews() let width = self.contentView.frame.width; shortNameView.frame = CGRectMake(0, 8, 30, 40); avatarView.frame = CGRectMake(30, 8, 40, 40); titleView.frame = CGRectMake(80, 8, width - 80 - 14, 40); } }
mit
c956b6eed2b78c68e78d74417813d87c
31.557377
94
0.636776
5.089744
false
false
false
false
zero2launch/z2l-ios-social-network
InstagramClone/HeaderProfileCollectionReusableView.swift
1
4389
// // HeaderProfileCollectionReusableView.swift // InstagramClone // // Created by The Zero2Launch Team on 1/15/17. // Copyright © 2017 The Zero2Launch Team. All rights reserved. // import UIKit protocol HeaderProfileCollectionReusableViewDelegate { func updateFollowButton(forUser user: User) } protocol HeaderProfileCollectionReusableViewDelegateSwitchSettingVC { func goToSettingVC() } class HeaderProfileCollectionReusableView: UICollectionReusableView { @IBOutlet weak var profileImage: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var myPostsCountLabel: UILabel! @IBOutlet weak var followingCountLabel: UILabel! @IBOutlet weak var followersCountLabel: UILabel! @IBOutlet weak var followButton: UIButton! var delegate: HeaderProfileCollectionReusableViewDelegate? var delegate2: HeaderProfileCollectionReusableViewDelegateSwitchSettingVC? var user: User? { didSet { updateView() } } override func awakeFromNib() { super.awakeFromNib() clear() } func updateView() { self.nameLabel.text = user!.username if let photoUrlString = user!.profileImageUrl { let photoUrl = URL(string: photoUrlString) self.profileImage.sd_setImage(with: photoUrl) } Api.MyPosts.fetchCountMyPosts(userId: user!.id!) { (count) in self.myPostsCountLabel.text = "\(count)" } Api.Follow.fetchCountFollowing(userId: user!.id!) { (count) in self.followingCountLabel.text = "\(count)" } Api.Follow.fetchCountFollowers(userId: user!.id!) { (count) in self.followersCountLabel.text = "\(count)" } if user?.id == Api.User.CURRENT_USER?.uid { followButton.setTitle("Edit Profile", for: UIControlState.normal) followButton.addTarget(self, action: #selector(self.goToSettingVC), for: UIControlEvents.touchUpInside) } else { updateStateFollowButton() } } func clear() { self.nameLabel.text = "" self.myPostsCountLabel.text = "" self.followersCountLabel.text = "" self.followingCountLabel.text = "" } func goToSettingVC() { delegate2?.goToSettingVC() } func updateStateFollowButton() { if user!.isFollowing! { configureUnFollowButton() } else { configureFollowButton() } } func configureFollowButton() { followButton.layer.borderWidth = 1 followButton.layer.borderColor = UIColor(red: 226/255, green: 228/255, blue: 232.255, alpha: 1).cgColor followButton.layer.cornerRadius = 5 followButton.clipsToBounds = true followButton.setTitleColor(UIColor.white, for: UIControlState.normal) followButton.backgroundColor = UIColor(red: 69/255, green: 142/255, blue: 255/255, alpha: 1) followButton.setTitle("Follow", for: UIControlState.normal) followButton.addTarget(self, action: #selector(self.followAction), for: UIControlEvents.touchUpInside) } func configureUnFollowButton() { followButton.layer.borderWidth = 1 followButton.layer.borderColor = UIColor(red: 226/255, green: 228/255, blue: 232.255, alpha: 1).cgColor followButton.layer.cornerRadius = 5 followButton.clipsToBounds = true followButton.setTitleColor(UIColor.black, for: UIControlState.normal) followButton.backgroundColor = UIColor.clear followButton.setTitle("Following", for: UIControlState.normal) followButton.addTarget(self, action: #selector(self.unFollowAction), for: UIControlEvents.touchUpInside) } func followAction() { if user!.isFollowing! == false { Api.Follow.followAction(withUser: user!.id!) configureUnFollowButton() user!.isFollowing! = true delegate?.updateFollowButton(forUser: user!) } } func unFollowAction() { if user!.isFollowing! == true { Api.Follow.unFollowAction(withUser: user!.id!) configureFollowButton() user!.isFollowing! = false delegate?.updateFollowButton(forUser: user!) } } }
mit
8bb1dc831572aef91c95988117e82608
32.753846
115
0.641978
4.963801
false
false
false
false
melling/ios_topics
CountDownTimer/CountDownTimer/ViewController.swift
1
1685
// // ViewController.swift // CountDownTimer // // Created by Michael Mellinger on 10/9/16. // import UIKit class ViewController: UIViewController { let timerLabel = UILabel() var secondsRemaining = 5 var isTimerRunning = true var timer:Timer! func startTimer() { timer = Timer() timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true) } @objc func updateTimer() { secondsRemaining -= 1 if secondsRemaining == 0 { isTimerRunning = false timer.invalidate() timerLabel.text = "Done" } else { timerLabel.text = "\(secondsRemaining)" } } func buildView() { timerLabel.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(timerLabel) NSLayoutConstraint.activate([ timerLabel.centerXAnchor.constraint(equalTo: self.view.centerXAnchor), timerLabel.centerYAnchor.constraint(equalTo: self.view.centerYAnchor), ]) timerLabel.font = UIFont.systemFont(ofSize: 36) timerLabel.text = "\(secondsRemaining)" } override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor(red: 90/255.0, green: 200.0/255.0, blue: 250.0/255, alpha: 1.0) // Apple Videos buildView() startTimer() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
cc0-1.0
604f2e3a2658bc6871cfcea7f7c87db3
24.149254
131
0.593472
5.029851
false
false
false
false
NUKisZ/MyTools
MyTools/MyTools/Base/BaseViewController.swift
1
3020
// // BaseViewController.swift // MyTools // // Created by zhangk on 17/3/23. // Copyright © 2017年 zhangk. All rights reserved. // import UIKit open class BaseViewController: UIViewController { override open func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. view.backgroundColor = UIColor.white navigationItem.title = "\(type(of: self))" } public func initNavTitle(titleString:String){ navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.colorWithHexStringAndAlpha(hex: "FFFFFF", alpha: 1.0)]; navigationItem.title = titleString } public func initNavBack(){ let backBtn = UIButton(type: .custom) backBtn.setImage(UIImage(named: ""), for: .normal) backBtn.addTarget(self, action: #selector(bafseBackAction), for: .touchUpInside) backBtn.frame = CGRect(x: 0, y: 0, width: 40, height: 40) navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backBtn) } public func bafseBackAction(){ if((presentingViewController) != nil){ let views = navigationController?.viewControllers if((views?.count)!>1){ if((views?[(views?.count)!-1])!==self){ navigationController?.popViewController(animated: true) } } dismiss(animated: true, completion: nil) }else{ navigationController?.popViewController(animated: true) } } public func changeNavBackGroundColor(leftColor:String,rightColor:String){ navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default) navigationController?.navigationBar.shadowImage = UIImage() let navBGView = UIView(frame: CGRect(x: 0, y: 0, w: kScreenWidth, h: 64)) view.addSubview(navBGView) let gradientLayer = CAGradientLayer() gradientLayer.frame = navBGView.bounds navBGView.layer.addSublayer(gradientLayer) gradientLayer.startPoint = CGPoint(x: 0, y: 0) gradientLayer.endPoint = CGPoint(x: 1, y: 0) gradientLayer.colors = [UIColor.colorWithHexStringAndAlpha(hex: leftColor, alpha: 1.0).cgColor,UIColor.colorWithHexStringAndAlpha(hex: rightColor, alpha: 1.0).cgColor] gradientLayer.locations = [0.5,1.0] } deinit { print("\(type(of: self))被释放了") } override open func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
858e1e0f2fe26addaabf798bb27e0f4c
36.148148
175
0.655035
4.77619
false
false
false
false
nicholas-richardson/swift3-treehouse
swift3-Basics/swift3-Basics.playground/Pages/Types.xcplaygroundpage/Contents.swift
1
1128
// String Literals let country = "United States of America" let state = "Indiana" let city = "Indianapolis" let street = "West Street" let buildingNumber = 222 // String Concatenation let address = country + ", " + state + ", " + city //let streetAddress = buildingNumber + street | Does not compile due to string value and number value // String Interpolation let interpolatedAddress = "\(country), \(state), \(city)" let interpolatedStreetAddress = "\(buildingNumber) \(street)" /* ----------------------- Integers ----------------------- */ let favoriteProgrammingLanguage = "Swift" let year = 2014 // Int /* ----------------------- Floating Point Numbers ----------------------- */ var version = 3.0 // Double /* ----------------------- Boolean ----------------------- */ let isAwesome = true // Boolean /* ----------------------- Type Safety ----------------------- */ var someString = "" //someString = 12.0 | Can not assign type double to type string let bestPlayer: String = "Michael Jordan" let averagePointsPerGame: Double = 30.1 let yearOfRetirement: Int = 2003 let hallOfFame: Bool = true
mit
8560a0cbdcea82e93ea1d82ee8271c8b
20.283019
101
0.579787
4.256604
false
false
false
false
ashfurrow/pragma-2015-rx-workshop
Session 4/Signup Demo/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxScrollViewDelegateProxy.swift
12
2137
// // RxScrollViewDelegateProxy.swift // RxCocoa // // Created by Krunoslav Zaher on 6/19/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) import Foundation #if !RX_NO_MODULE import RxSwift #endif import UIKit // Please take a look at `DelegateProxyType.swift` class RxScrollViewDelegateProxy : DelegateProxy , UIScrollViewDelegate , DelegateProxyType { private var _contentOffsetSubject: ReplaySubject<CGPoint>? unowned let scrollView: UIScrollView var contentOffsetSubject: Observable<CGPoint> { if _contentOffsetSubject == nil { _contentOffsetSubject = ReplaySubject.create(bufferSize: 1) _contentOffsetSubject!.on(.Next(self.scrollView.contentOffset)) } return _contentOffsetSubject! } required init(parentObject: AnyObject) { self.scrollView = parentObject as! UIScrollView super.init(parentObject: parentObject) } // delegate methods func scrollViewDidScroll(scrollView: UIScrollView) { if let contentOffset = _contentOffsetSubject { contentOffset.on(.Next(self.scrollView.contentOffset)) } self._forwardToDelegate?.scrollViewDidScroll?(scrollView) } // delegate proxy override class func createProxyForObject(object: AnyObject) -> AnyObject { let scrollView = object as! UIScrollView return castOrFatalError(scrollView.rx_createDelegateProxy()) } class func setCurrentDelegate(delegate: AnyObject?, toObject object: AnyObject) { let collectionView: UIScrollView = castOrFatalError(object) collectionView.delegate = castOptionalOrFatalError(delegate) } class func currentDelegateFor(object: AnyObject) -> AnyObject? { let collectionView: UIScrollView = castOrFatalError(object) return collectionView.delegate } deinit { if let contentOffset = _contentOffsetSubject { contentOffset.on(.Completed) } } } #endif
mit
9ca715a62a8fb46cd9757aff8a6af58e
28.273973
85
0.660739
5.623684
false
false
false
false
Aioria1314/WeiBo
WeiBo/WeiBo/Classes/Views/ZXCComposeButton.swift
1
1040
// // ZXCComposeButton.swift // WeiBo // // Created by Aioria on 2017/4/2. // Copyright © 2017年 Aioria. All rights reserved. // import UIKit class ZXCComposeButton: UIButton { override init(frame: CGRect) { super.init(frame: frame) imageView?.contentMode = .center titleLabel?.textAlignment = .center } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() imageView?.frame.origin.y = 0 imageView?.frame.origin.x = 0 imageView?.frame.size.width = bounds.size.width imageView?.frame.size.height = bounds.size.width titleLabel?.frame.origin.y = bounds.size.width titleLabel?.frame.origin.x = 0 titleLabel?.frame.size.width = bounds.size.width titleLabel?.frame.size.height = bounds.size.height - bounds.size.width } }
mit
d5d97538acca92ee120572bdd9edb353
22.568182
78
0.594021
4.412766
false
false
false
false