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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
hsylife/SwiftyPickerPopover
|
SwiftyPickerPopover/DatePickerPopoverViewController.swift
|
1
|
3236
|
//
// DatePickerPopoverViewController.swift
// SwiftyPickerPopover
//
// Created by Yuta Hoshino on 2016/09/14.
// Copyright © 2016 Yuta Hoshino. All rights reserved.
//
public class DatePickerPopoverViewController: AbstractPickerPopoverViewController {
typealias PopoverType = DatePickerPopover
fileprivate var popover: PopoverType! { return anyPopover as? PopoverType }
@IBOutlet weak private var picker: UIDatePicker!
@IBOutlet weak private var cancelButton: UIBarButtonItem!
@IBOutlet weak private var doneButton: UIBarButtonItem!
@IBOutlet weak private var clearButton: UIButton!
override func refrectPopoverProperties(){
super.refrectPopoverProperties()
if #available(iOS 11.0, *) { }
else {
navigationItem.leftBarButtonItem = nil
navigationItem.rightBarButtonItem = nil
}
cancelButton.title = popover.cancelButton.title
if let font = popover.cancelButton.font {
cancelButton.setTitleTextAttributes([NSAttributedString.Key.font: font], for: .normal)
}
cancelButton.tintColor = popover.cancelButton.color ?? popover.tintColor
navigationItem.setLeftBarButton(cancelButton, animated: false)
doneButton.title = popover.doneButton.title
if let font = popover.doneButton.font {
doneButton.setTitleTextAttributes([NSAttributedString.Key.font: font], for: .normal)
}
doneButton.tintColor = popover.doneButton.color ?? popover.tintColor
navigationItem.setRightBarButton(doneButton, animated: false)
clearButton.setTitle(popover.clearButton.title, for: .normal)
if let font = popover.clearButton.font {
clearButton.titleLabel?.font = font
}
clearButton.tintColor = popover.clearButton.color ?? popover.tintColor
clearButton.isHidden = popover.clearButton.action == nil
picker.date = popover.selectedDate
picker.minimumDate = popover.minimumDate
picker.maximumDate = popover.maximumDate
picker.datePickerMode = popover.dateMode_
picker.locale = popover.locale
if picker.datePickerMode != .date {
picker.minuteInterval = popover.minuteInterval
}
}
@IBAction func tappedDone(_ sender: UIButton? = nil) {
tapped(button: popover.doneButton)
}
@IBAction func tappedCancel(_ sender: AnyObject? = nil) {
tapped(button: popover.cancelButton)
}
@IBAction func tappedClear(_ sender: UIButton? = nil) {
popover.clearButton.action?(popover, picker.date)
popover.redoDisappearAutomatically()
}
private func tapped(button: DatePickerPopover.ButtonParameterType?) {
button?.action?(popover, picker.date)
popover.removeDimmedView()
dismiss(animated: false)
}
@IBAction func pickerValueChanged(_ sender: UIDatePicker) {
popover.valueChangeAction?(popover, picker.date)
popover.redoDisappearAutomatically()
}
func popoverPresentationControllerDidDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) {
tappedCancel()
}
}
|
mit
|
2b251343f5b58481fa02ce742814c3d6
| 37.058824 | 123 | 0.684389 | 5.320724 | false | false | false | false |
chenl326/stwitter
|
stwitter/stwitter/Classes/Tools/Network/Model/CLUserAccount.swift
|
1
|
2250
|
//
// CLUserAccount.swift
// stwitter
//
// Created by sun on 2017/5/27.
// Copyright © 2017年 sun. All rights reserved.
//
import UIKit
private let accountFile: NSString = "userAccount.json"
class CLUserAccount: NSObject {
/// 访问令牌
var access_token: String?
/// 用户代号
var uid: String?
//用户昵称
var screen_name: String?
//用户头像地址(大图),180×180像素
var avatar_large: String?
/// access_token 的生命周期 开发者5年 使用者3天
var expires_in:TimeInterval = 0{
didSet{
expiresDate = Date.init(timeIntervalSinceNow: expires_in)
}
}
//过期日期
var expiresDate: Date?
override var description: String{
return yy_modelDescription()
}
override init() {
super.init()
//从磁盘加载保存文件
guard let path = accountFile.yw_appendDocumentDir(),
let data = NSData(contentsOfFile: path),
let dic = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [String: AnyObject]
else {
return
}
//使用字典设置属性值
yy_modelSet(with: dic ?? [:])
print("从沙盒加载用户信息\(self)")
//测试日期
// expiresDate = Date(timeIntervalSinceNow: -3600 * 24)
//判断 token 是否过期
if expiresDate?.compare(Date()) == .orderedAscending {
//账户过期 清空 token uid
access_token = nil
uid = nil
//删除账户文件
_ = try?FileManager.default.removeItem(atPath: path)
}
}
func saveAccount() {
var dict = (self.yy_modelToJSONObject() as? [String:Any]) ?? [:]
dict.removeValue(forKey: "expires_in")
guard let data = try? JSONSerialization.data(withJSONObject: dict, options: []),
let filePath = accountFile.yw_appendDocumentDir() else{
return
}
(data as NSData).write(toFile: filePath, atomically: true)
print("账户保存成功\(filePath)")
}
}
|
apache-2.0
|
c072e1558e357d6347472d0d5d0e2078
| 23.141176 | 112 | 0.540936 | 4.239669 | false | false | false | false |
AzAli71/AZGradientView
|
AZGradientViewSample/AZGradientViewSample/classes/AZHorizontalGradientView.swift
|
1
|
731
|
//
// AZHorizontalGradientView.swift
// AZGradientViewSample
//
// Created by Ali on 8/28/17.
// Copyright © 2017 Ali Azadeh. All rights reserved.
//
import Foundation
import UIKit
@IBDesignable final class AZHorizontalGradientView: AZGradientView {
@IBInspectable var leftColor: UIColor = UIColor.clear
@IBInspectable var rightColor: UIColor = UIColor.clear
override func draw(_ rect: CGRect) {
let gradient = CAGradientLayer()
gradient.frame = self.bounds
gradient.colors = [leftColor.cgColor, rightColor.cgColor]
gradient.startPoint = CGPoint(x: 0, y: 0)
gradient.endPoint = CGPoint(x: 1, y: 0)
self.layer.addSublayer(gradient)
}
}
|
mit
|
1b024a97d97e64b8a9f5cdff47b2c97e
| 25.071429 | 68 | 0.669863 | 4.219653 | false | false | false | false |
gottesmm/swift
|
stdlib/public/core/EmptyCollection.swift
|
9
|
4917
|
//===--- EmptyCollection.swift - A collection with no elements ------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Sometimes an operation is best expressed in terms of some other,
// larger operation where one of the parameters is an empty
// collection. For example, we can erase elements from an Array by
// replacing a subrange with the empty collection.
//
//===----------------------------------------------------------------------===//
/// An iterator that never produces an element.
///
/// - SeeAlso: `EmptyCollection<Element>`.
public struct EmptyIterator<Element> : IteratorProtocol, Sequence {
/// Creates an instance.
public init() {}
/// Returns `nil`, indicating that there are no more elements.
public mutating func next() -> Element? {
return nil
}
}
/// A collection whose element type is `Element` but that is always empty.
public struct EmptyCollection<Element> :
RandomAccessCollection, MutableCollection
{
/// A type that represents a valid position in the collection.
///
/// Valid indices consist of the position of every element and a
/// "past the end" position that's not valid for use as a subscript.
public typealias Index = Int
public typealias IndexDistance = Int
public typealias SubSequence = EmptyCollection<Element>
/// Creates an instance.
public init() {}
/// Always zero, just like `endIndex`.
public var startIndex: Index {
return 0
}
/// Always zero, just like `startIndex`.
public var endIndex: Index {
return 0
}
/// Always traps.
///
/// `EmptyCollection` does not have any element indices, so it is not
/// possible to advance indices.
public func index(after i: Index) -> Index {
_preconditionFailure("EmptyCollection can't advance indices")
}
/// Always traps.
///
/// `EmptyCollection` does not have any element indices, so it is not
/// possible to advance indices.
public func index(before i: Index) -> Index {
_preconditionFailure("EmptyCollection can't advance indices")
}
/// Returns an empty iterator.
public func makeIterator() -> EmptyIterator<Element> {
return EmptyIterator()
}
/// Accesses the element at the given position.
///
/// Must never be called, since this collection is always empty.
public subscript(position: Index) -> Element {
get {
_preconditionFailure("Index out of range")
}
set {
_preconditionFailure("Index out of range")
}
}
public subscript(bounds: Range<Index>) -> EmptyCollection<Element> {
get {
_precondition(bounds.lowerBound == 0 && bounds.upperBound == 0,
"Index out of range")
return self
}
set {
_precondition(bounds.lowerBound == 0 && bounds.upperBound == 0,
"Index out of range")
}
}
/// The number of elements (always zero).
public var count: Int {
return 0
}
public func index(_ i: Index, offsetBy n: IndexDistance) -> Index {
_precondition(i == startIndex && n == 0, "Index out of range")
return i
}
public func index(
_ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index
) -> Index? {
_precondition(i == startIndex && limit == startIndex,
"Index out of range")
return n == 0 ? i : nil
}
/// The distance between two indexes (always zero).
public func distance(from start: Index, to end: Index) -> IndexDistance {
_precondition(start == 0, "From must be startIndex (or endIndex)")
_precondition(end == 0, "To must be endIndex (or startIndex)")
return 0
}
public func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>) {
_precondition(index == 0, "out of bounds")
_precondition(bounds == Range(indices),
"invalid bounds for an empty collection")
}
public func _failEarlyRangeCheck(
_ range: Range<Index>, bounds: Range<Index>
) {
_precondition(range == Range(indices),
"invalid range for an empty collection")
_precondition(bounds == Range(indices),
"invalid bounds for an empty collection")
}
public typealias Indices = CountableRange<Int>
}
extension EmptyCollection : Equatable {
public static func == (
lhs: EmptyCollection<Element>, rhs: EmptyCollection<Element>
) -> Bool {
return true
}
}
@available(*, unavailable, renamed: "EmptyIterator")
public struct EmptyGenerator<Element> {}
extension EmptyIterator {
@available(*, unavailable, renamed: "makeIterator()")
public func generate() -> EmptyIterator<Element> {
Builtin.unreachable()
}
}
|
apache-2.0
|
755765ad6791aa93ef617381ed3cf4fe
| 29.351852 | 80 | 0.652227 | 4.552778 | false | false | false | false |
jwfriese/FrequentFlyer
|
FrequentFlyerTests/Pipelines/PipelinesServiceSpec.swift
|
1
|
7302
|
import XCTest
import Quick
import Nimble
import RxSwift
@testable import FrequentFlyer
import Result
class PipelinesServiceSpec: QuickSpec {
override func spec() {
class MockHTTPClient: HTTPClient {
var capturedRequest: URLRequest?
var callCount = 0
var responseSubject = PublishSubject<HTTPResponse>()
override func perform(request: URLRequest) -> Observable<HTTPResponse> {
capturedRequest = request
callCount += 1
return responseSubject
}
}
class MockPipelineDataDeserializer: PipelineDataDeserializer {
var capturedPipelineData: Data?
var toReturnPipelines: [Pipeline]?
var toReturnError: Error?
override func deserialize(_ data: Data) -> Observable<[Pipeline]> {
capturedPipelineData = data
if let error = toReturnError {
return Observable.error(error)
} else {
return Observable.from(optional: toReturnPipelines)
}
}
}
describe("PipelinesService") {
var subject: PipelinesService!
var mockHTTPClient: MockHTTPClient!
var mockPipelineDataDeserializer: MockPipelineDataDeserializer!
beforeEach {
subject = PipelinesService()
mockHTTPClient = MockHTTPClient()
subject.httpClient = mockHTTPClient
mockPipelineDataDeserializer = MockPipelineDataDeserializer()
subject.pipelineDataDeserializer = mockPipelineDataDeserializer
}
describe("Getting the pipelines for a team") {
var pipeline$: Observable<[Pipeline]>!
var pipeline$Result: StreamResult<[Pipeline]>!
beforeEach {
let target = Target(name: "turtle target name",
api: "https://api.com",
teamName: "turtle_team_name",
token: Token(value: "Bearer turtle auth token")
)
pipeline$ = subject.getPipelines(forTarget: target)
pipeline$Result = StreamResult(pipeline$)
}
it("passes the necessary request to the HTTPClient") {
guard let request = mockHTTPClient.capturedRequest else {
fail("Failed to make request with HTTPClient")
return
}
expect(request.url?.absoluteString).to(equal("https://api.com/api/v1/teams/turtle_team_name/pipelines"))
expect(request.allHTTPHeaderFields?["Content-Type"]).to(equal("application/json"))
expect(request.allHTTPHeaderFields?["Authorization"]).to(equal("Bearer turtle auth token"))
expect(request.httpMethod).to(equal("GET"))
}
describe("When the request resolves with a success response and valid pipeline data") {
beforeEach {
mockPipelineDataDeserializer.toReturnPipelines = [
Pipeline(name: "turtle super pipeline", isPublic: false, teamName: "")
]
let validPipelineData = "valid pipeline data".data(using: String.Encoding.utf8)
mockHTTPClient.responseSubject.onNext(HTTPResponseImpl(body: validPipelineData, statusCode: 200))
}
it("passes the data along to the deserializer") {
guard let data = mockPipelineDataDeserializer.capturedPipelineData else {
fail("Failed to pass any data to the PipelineDataDeserializer")
return
}
let expectedData = "valid pipeline data".data(using: String.Encoding.utf8)
expect(data).to(equal(expectedData!))
}
it("emits the deserialized data") {
expect(pipeline$Result.elements.first?.first).to(equal(Pipeline(name: "turtle super pipeline", isPublic: false, teamName: "")))
}
it("emits no error") {
expect(pipeline$Result.error).to(beNil())
}
}
describe("When the request resolves with a success response and deserialization fails with an error") {
var error: TestError!
beforeEach {
error = TestError()
mockPipelineDataDeserializer.toReturnError = error
let invalidData = "invalid data".data(using: String.Encoding.utf8)
mockHTTPClient.responseSubject.onNext(HTTPResponseImpl(body: invalidData, statusCode: 200))
}
it("emits no pipelines") {
expect(pipeline$Result.elements).to(beEmpty())
}
it("emits the error that came from the deserializer") {
expect(pipeline$Result.error as? TestError).to(equal(error))
}
}
describe("When the request resolves with no body") {
beforeEach {
mockHTTPClient.responseSubject.onNext(HTTPResponseImpl(body: nil, statusCode: 500))
}
it("emits nil for the pipeline data") {
expect(pipeline$Result.elements.first).to(beNil())
}
it("emits an \(UnexpectedError.self)") {
expect(pipeline$Result.error as? UnexpectedError).toNot(beNil())
}
}
describe("When the request resolves with a 401 response") {
beforeEach {
let unauthorizedData = "not authorized".data(using: String.Encoding.utf8)
mockHTTPClient.responseSubject.onNext(HTTPResponseImpl(body: unauthorizedData, statusCode: 401))
}
it("emits no pipelines") {
expect(pipeline$Result.elements).to(beEmpty())
}
it("emits an \(AuthorizationError.self)") {
expect(pipeline$Result.error as? AuthorizationError).toNot(beNil())
}
}
describe("When the request resolves with an error") {
var error: TestError!
beforeEach {
error = TestError()
mockHTTPClient.responseSubject.onError(error)
}
it("emits no pipelines") {
expect(pipeline$Result.elements).to(beEmpty())
}
it("emits the error that came from the request") {
expect(pipeline$Result.error as? TestError).to(equal(error))
}
}
}
}
}
}
|
apache-2.0
|
89bafd53f0a2ca74cd7e89f6b65fba34
| 40.022472 | 151 | 0.513969 | 6.219761 | false | true | false | false |
twostraws/SwiftGD
|
Sources/SwiftGD/Geometry/Size.swift
|
1
|
1991
|
/// A structure that represents a two-dimensional size.
public struct Size {
/// The width value of the size.
public var width: Int
/// The height value of the size.
public var height: Int
/// Creates a size with specified dimensions.
///
/// - Parameters:
/// - width: The width value of the size
/// - height: The height value of the size
public init(width: Int, height: Int) {
self.width = width
self.height = height
}
}
extension Size {
/// Size whose width and height are both zero.
public static let zero = Size(width: 0, height: 0)
/// Creates a size with specified dimensions.
///
/// - Parameters:
/// - width: The width value of the size
/// - height: The height value of the size
public init(width: Int32, height: Int32) {
self.init(width: Int(width), height: Int(height))
}
}
extension Size: Comparable {
/// Returns a Boolean value indicating whether the value of the first
/// argument is less than that of the second argument.
///
/// This function is the only requirement of the `Comparable` protocol. The
/// remainder of the relational operator functions are implemented by the
/// standard library for any type that conforms to `Comparable`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func < (lhs: Size, rhs: Size) -> Bool {
return lhs.width < rhs.width && lhs.height < rhs.height
}
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (lhs: Size, rhs: Size) -> Bool {
return lhs.width == rhs.width && lhs.height == rhs.height
}
}
|
mit
|
5799416afb8ba56dec5f6869f7040ee7
| 32.183333 | 79 | 0.608237 | 4.122153 | false | false | false | false |
amitburst/HackerNews
|
HackerNews/MainViewController.swift
|
1
|
6068
|
//
// MainViewController.swift
// HackerNews
//
// Copyright (c) 2015 Amit Burstein. All rights reserved.
// See LICENSE for licensing information.
//
import UIKit
import SafariServices
class MainViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, SFSafariViewControllerDelegate {
// MARK: Properties
let PostCellIdentifier = "PostCell"
let ShowBrowserIdentifier = "ShowBrowser"
let PullToRefreshString = "Pull to Refresh"
let FetchErrorMessage = "Could Not Fetch Posts"
let ErrorMessageLabelTextColor = UIColor.gray
let ErrorMessageFontSize: CGFloat = 16
let FirebaseRef = "https://hacker-news.firebaseio.com/v0/"
let ItemChildRef = "item"
let StoryTypeChildRefMap = [StoryType.top: "topstories", .new: "newstories", .show: "showstories"]
let StoryLimit: UInt = 30
let DefaultStoryType = StoryType.top
var firebase: Firebase!
var stories: [Story]! = []
var storyType: StoryType!
var retrievingStories: Bool!
var refreshControl: UIRefreshControl!
var errorMessageLabel: UILabel!
@IBOutlet weak var tableView: UITableView!
// MARK: Enums
enum StoryType {
case top, new, show
}
// MARK: Structs
struct Story {
let title: String
let url: String?
let by: String
let score: Int
}
// MARK: Initialization
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
firebase = Firebase(url: FirebaseRef)
stories = []
storyType = DefaultStoryType
retrievingStories = false
refreshControl = UIRefreshControl()
}
// MARK: UIViewController
override func viewDidLoad() {
super.viewDidLoad()
configureUI()
retrieveStories()
}
// MARK: Functions
func configureUI() {
refreshControl.addTarget(self, action: #selector(MainViewController.retrieveStories), for: .valueChanged)
refreshControl.attributedTitle = NSAttributedString(string: PullToRefreshString)
tableView.insertSubview(refreshControl, at: 0)
// Have to initialize this UILabel here because the view does not exist in init() yet.
errorMessageLabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: self.view.bounds.size.height))
errorMessageLabel.textColor = ErrorMessageLabelTextColor
errorMessageLabel.textAlignment = .center
errorMessageLabel.font = UIFont.systemFont(ofSize: ErrorMessageFontSize)
}
@objc func retrieveStories() {
if retrievingStories! {
return
}
UIApplication.shared.isNetworkActivityIndicatorVisible = true
retrievingStories = true
var storiesMap = [Int:Story]()
let query = firebase.child(byAppendingPath: StoryTypeChildRefMap[storyType]).queryLimited(toFirst: StoryLimit)
query?.observeSingleEvent(of: .value, with: { snapshot in
let storyIds = snapshot?.value as! [Int]
for storyId in storyIds {
let query = self.firebase.child(byAppendingPath: self.ItemChildRef).child(byAppendingPath: String(storyId))
query?.observeSingleEvent(of: .value, with: { snapshot in
storiesMap[storyId] = self.extractStory(snapshot!)
if storiesMap.count == Int(self.StoryLimit) {
var sortedStories = [Story]()
for storyId in storyIds {
sortedStories.append(storiesMap[storyId]!)
}
self.stories = sortedStories
self.tableView.reloadData()
self.refreshControl.endRefreshing()
self.retrievingStories = false
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
}, withCancel: self.loadingFailed)
}
}, withCancel: self.loadingFailed)
}
func extractStory(_ snapshot: FDataSnapshot) -> Story {
let data = snapshot.value as! Dictionary<String, Any>
let title = data["title"] as! String
let url = data["url"] as? String
let by = data["by"] as! String
let score = data["score"] as! Int
return Story(title: title, url: url, by: by, score: score)
}
func loadingFailed(_ error: Error?) -> Void {
self.retrievingStories = false
self.stories.removeAll()
self.tableView.reloadData()
self.showErrorMessage(self.FetchErrorMessage)
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
func showErrorMessage(_ message: String) {
errorMessageLabel.text = message
self.tableView.backgroundView = errorMessageLabel
self.tableView.separatorStyle = .none
}
// MARK: UITableViewDataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return stories.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let story = stories[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: PostCellIdentifier) as UITableViewCell!
cell?.textLabel?.text = story.title
cell?.detailTextLabel?.text = "\(story.score) points by \(story.by)"
return cell!
}
// MARK: UITableViewDelegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let story = stories[indexPath.row]
if let url = story.url {
let webViewController = SFSafariViewController(url: URL(string: url)!)
webViewController.delegate = self
present(webViewController, animated: true, completion: nil)
}
}
// MARK: SFSafariViewControllerDelegate
func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
controller.dismiss(animated: true, completion: nil)
}
// MARK: IBActions
@IBAction func changeStoryType(_ sender: UISegmentedControl) {
if sender.selectedSegmentIndex == 0 {
storyType = .top
} else if sender.selectedSegmentIndex == 1 {
storyType = .new
} else if sender.selectedSegmentIndex == 2 {
storyType = .show
} else {
print("Bad segment index!")
}
retrieveStories()
}
}
|
mit
|
e6689b803f962339aa015518f5b37a59
| 30.769634 | 132 | 0.691826 | 4.72954 | false | false | false | false |
306244907/Weibo
|
JLSina/JLSina/Classes/View(视图和控制器)/Home/JLHomeViewController.swift
|
1
|
4567
|
//
// JLHomeViewController.swift
// JLSina
//
// Created by 盘赢 on 2017/9/29.
// Copyright © 2017年 JinLong. All rights reserved.
//
import UIKit
//定义全局常量,尽量使用private修饰
//原创微博可重用cellid
private let originalCellId = "originalCellId"
//被转发微博的可重用cellid
private let retweetedCellId = "retweetedCellId"
class JLHomeViewController: JLBaseViewController {
//列表视图模型
private lazy var listViewModel: JLStatusListViewModel = JLStatusListViewModel()
//加载数据
//模拟“延时”加载数据
override func loadData() {
refreshControl?.beginRefreshing()
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) {
self.listViewModel.loadStatus (pullup: self.isPullup) { (isSuccess , shouldRefresh) in
//结束刷新控件
self.refreshControl?.endRefreshing()
//恢复上拉刷新标记
self.isPullup = false
//刷新表格
if shouldRefresh {
self.tableView?.reloadData()
}
}
}
}
//显示好友
@objc private func showFriends() {
print(#function)
let vc = JLDemoViewController()
//push的动作是NAV做的
navigationController?.pushViewController(vc, animated: true)
}
}
//MARK: - 表格数据源方法,具体的数据源方法实现,不需要super
extension JLHomeViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return listViewModel.statusList.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//0,取出视图模型,根据视图模型,判断可重用cell
let vm = listViewModel.statusList[indexPath.row]
let cellId = vm.status.retweeted_status != nil ? retweetedCellId : originalCellId
//FIXME: 修改id
//1,取cell - 本身会调用代理方法(如果有)
//如果没有,找到cell,按照自动布局的规则,从上向下计算,找到向下的约束,从而动态计算行高
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! JLStatusCell
//2,设置cell
cell.viewModel = vm
//设置代理,只是传递了一个指针
cell.delegate = self
//3,返回cell
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
//1.根据indexpath获取视图模型
let vm = listViewModel.statusList[indexPath.row]
//返回行高
return vm.rowHeight
}
}
// MARK: - JLStatusCellDelegate
extension JLHomeViewController: JLStatusCellDelegate {
func statusCellDidSelectedURLString(cell: JLStatusCell, urlString: String) {
print(urlString)
let vc = JLWebViewController()
vc.urlString = urlString
navigationController?.pushViewController(vc, animated: true)
}
}
//MARK: - 设置界面
extension JLHomeViewController {
//重写父类方法
override func setupTableView() {
super.setupTableView()
//设置导航栏按钮
navItem.leftBarButtonItem = UIBarButtonItem(title: "好友", target: self, action: #selector(showFriends))
//注册原型cell
tableView?.register(UINib(nibName: "JLStatusNormalCell", bundle: nil), forCellReuseIdentifier: originalCellId)
tableView?.register(UINib(nibName: "JLStatusRetweetedCell", bundle: nil), forCellReuseIdentifier: retweetedCellId)
//设置行高
// tableView?.rowHeight = UITableViewAutomaticDimension
tableView?.estimatedRowHeight = 300
//取消分割线
tableView?.separatorStyle = .none
setNavTitle()
}
//设置导航栏标题
private func setNavTitle() {
let title = JLNetworkManager.shared.userAccount.screen_name
let button = JLTitleButton(title: title)
navItem.titleView = button
button.addTarget(self, action: #selector(clickTitleButton), for: .touchUpInside)
}
@objc func clickTitleButton(btn: UIButton) {
//设置选中状态
btn.isSelected = !btn.isSelected
}
}
|
mit
|
3837c94e07cf1248119551668991aa36
| 27.041379 | 122 | 0.619528 | 4.738928 | false | false | false | false |
strivingboy/CocoaChinaPlus
|
Code/CocoaChinaPlus/CCRemoteNotificationHandler.swift
|
1
|
1643
|
//
// CCRemoteNotificationHandler.swift
// CocoaChinaPlus
//
// Created by chenyl on 15/9/24.
// Copyright © 2015年 zixun. All rights reserved.
//
import UIKit
class CCRemoteNotificationHandler: NSObject,UIAlertViewDelegate {
static let sharedHandler : CCRemoteNotificationHandler = {
return CCRemoteNotificationHandler()
}()
private var identity : String?
func handle(userInfo:NSDictionary) {
guard userInfo.count > 1 else {
return;
}
let state = UIApplication.sharedApplication().applicationState
if let aps = userInfo["aps"] as? NSDictionary {
let alert = aps["alert"] as! String
if let cocoachina_url = userInfo["cocoachina"] {
self.identity = CCURLHelper.generateIdentity(cocoachina_url as! String)
if state == UIApplicationState.Active {
UIAlertView(title: "新消息",
message: alert,
delegate: self,
cancelButtonTitle: "下次吧",
otherButtonTitles: "学习一下").show()
}else {
ZXOpenURL("go/ccp/article?identity=\(self.identity! )")
}
}
}
}
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
if buttonIndex == 1 && self.identity != nil {
ZXOpenURL("go/ccp/article?identity=\(self.identity!)")
}
}
}
|
mit
|
7cc59c900db1bbfc730dff97381f11c8
| 28.454545 | 88 | 0.52284 | 5.25974 | false | false | false | false |
tripleCC/GanHuoCode
|
GanHuoShareExtension/TPCShareItemTypePickView.swift
|
1
|
2080
|
//
// TPCShareItemTypePickView.swift
// TPCShareextension
//
// Created by tripleCC on 16/4/12.
// Copyright © 2016年 tripleCC. All rights reserved.
//
import UIKit
public class TPCShareItemTypePickView: UIView {
var typesTitle: [String]! {
didSet {
pickView.reloadAllComponents()
pickView.layoutIfNeeded()
}
}
var selectedTitle: String {
return typesTitle[pickView.selectedRowInComponent(0)]
}
private var pickView: UIPickerView!
override init(frame: CGRect) {
super.init(frame: frame)
setupSubviews()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupSubviews()
}
private func setupSubviews() {
pickView = UIPickerView()
pickView.delegate = self
pickView.dataSource = self
addSubview(pickView)
}
override public func layoutSubviews() {
super.layoutSubviews()
pickView.frame = bounds
}
}
extension TPCShareItemTypePickView: UIPickerViewDelegate {
public func pickerView(pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
return 40
}
public func pickerView(pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
let attributes = [NSFontAttributeName : UIFont.systemFontOfSize(16),
NSForegroundColorAttributeName : UIColor.blackColor()]
let string = NSAttributedString(string: typesTitle[row], attributes: attributes)
return string
}
public func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
}
}
extension TPCShareItemTypePickView: UIPickerViewDataSource {
public func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
public func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return typesTitle.count
}
}
|
mit
|
b5eff46275d87875ea7302269bd95904
| 27.861111 | 138 | 0.665383 | 5.325641 | false | false | false | false |
KeithPiTsui/Pavers
|
Pavers/Pavers.playground/Sources/style-guide.swift
|
2
|
1417
|
import Foundation
import UIKit
/**
Returns a UIView consisting of many rectangles of colors with their labels printed on them.
- parameter colors: An array of colors to put in the UIView.
- parameter size: The size of the UIView
- parameter columnsCount: Number of columns to use in the palette.
*/
public func colorPalette(colors: [(color: UIColor, name: String)],
size: CGSize = CGSize(width: 800.0, height: 400.0),
columnsCount: Int = 6)
-> UIView {
let palette = UIView(frame: CGRect(origin: .zero, size: size))
palette.backgroundColor = .clear
let rowsCount = Int(ceil(Float(colors.count) / Float(columnsCount)))
let columnWidth = palette.frame.width / CGFloat(columnsCount)
let rowHeight = palette.frame.height / CGFloat(rowsCount)
let tiles = colors.enumerated().map { idx, data -> UIView in
let row = Int(idx / columnsCount)
let column = idx % columnsCount
let view = UIView(frame: CGRect(
x: CGFloat(column) * columnWidth,
y: CGFloat(row) * rowHeight,
width: columnWidth,
height: rowHeight
)
)
view.backgroundColor = data.color
let label = UILabel(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 20.0))
label.text = data.name
label.textColor = data.color._white < 0.5 ? .white : .black
view.addSubview(label)
return view
}
tiles.forEach(palette.addSubview)
return palette
}
|
mit
|
eff7915ab467bf1c5bb7bb922f956e4e
| 29.148936 | 92 | 0.680311 | 3.871585 | false | false | false | false |
Harley-xk/Chrysan
|
Chrysan/Sources/Responders/HUDLayout.swift
|
1
|
897
|
//
// HUDLayout.swift
// Chrysan
//
// Created by Harley-xk on 2020/6/3.
// Copyright © 2020 Harley. All rights reserved.
//
import Foundation
import UIKit
// 布局参数
public struct HUDLayout {
/// 位置,决定状态视图的锚点
public enum Position {
/// 居中, 此时锚点为中心点
case center
/// 顶部固定,此时锚点为顶部中心
case top
/// 底部固定,此时锚点为底部中心
case bottom
}
/// 状态视图的位置
public var position: Position = .center
/// 距离锚点的偏移
/// - Note: 当 position == .bottom 时,offset 在 y 轴的偏移方向为**自下向上**
public var offset = CGPoint.zero
/// 状态视图距离遮罩层边缘的最小距离
public var padding = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
}
|
mit
|
3dd0821acdcb67453af0fe0767e3e3f5
| 18.942857 | 79 | 0.581662 | 3.158371 | false | false | false | false |
rodrigoff/hackingwithswift
|
project1/Project1/ViewController.swift
|
1
|
1536
|
//
// ViewController.swift
// Project1
//
// Created by Rodrigo F. Fernandes on 7/20/17.
// Copyright © 2017 Rodrigo F. Fernandes. All rights reserved.
//
import UIKit
class ViewController: UITableViewController {
var pictures = [String]()
override func viewDidLoad() {
super.viewDidLoad()
title = "Storm Viewer"
let fm = FileManager.default
let path = Bundle.main.resourcePath!
let items = try! fm.contentsOfDirectory(atPath: path)
for item in items {
if item.hasPrefix("nssl") {
pictures.append(item)
}
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return pictures.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Picture", for: indexPath)
cell.textLabel?.text = pictures[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let vc = storyboard?.instantiateViewController(withIdentifier: "Detail") as? DetailViewController {
vc.selectedImage = pictures[indexPath.row]
navigationController?.pushViewController(vc, animated: true)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
|
mit
|
ce31f94ef4a9969aaba1e55c87cdf952
| 27.425926 | 110 | 0.636482 | 5.185811 | false | false | false | false |
PiXeL16/PasswordTextField
|
PasswordTextFieldTests/PasswordTextFieldSpecs.swift
|
1
|
2355
|
//
// PasswordTextFieldSpecs.swift
// PasswordTextField
//
// Created by Chris Jimenez on 2/11/16.
// Copyright © 2016 Chris Jimenez. All rights reserved.
//
import Foundation
import Nimble
import Quick
import PasswordTextField
//Specs for the delayer class
class PasswordTextFieldSpecs: QuickSpec {
override func spec() {
let passwordTextField = PasswordTextField()
it("initial values are correct"){
let passwordString = "1234Abcd8988!"
passwordTextField.text = passwordString
passwordTextField.imageTintColor = UIColor.red
passwordTextField.setSecureMode(false)
expect(passwordTextField.isValid()).to(beTrue())
expect(passwordTextField.errorMessage()).toNot(beNil())
expect(passwordTextField.showButtonWhile).to(equal(PasswordTextField.ShowButtonWhile.Editing))
expect(passwordTextField.imageTintColor).to(equal(UIColor.red))
expect(passwordTextField.secureTextButton.tintColor).to(equal(UIColor.red))
expect(passwordTextField.isSecureTextEntry).to(beFalse())
}
it("values are correct after button pressed"){
let passwordString = "love"
passwordTextField.text = passwordString
passwordTextField.secureTextButton.buttonTouch()
expect(passwordTextField.isValid()).to(beFalse())
expect(passwordTextField.errorMessage()).toNot(beNil())
expect(passwordTextField.secureTextButton.isSecure).to(beFalse())
expect(passwordTextField.isSecureTextEntry).to(beFalse())
}
it("validates with custom validator"){
let passwordString = "LOVE"
passwordTextField.text = passwordString
let validationRule = RegexRule(regex:"^[A-Z ]+$", errorMessage: "test")
passwordTextField.validationRule = validationRule
expect(passwordTextField.isValid()).to(beTrue())
expect(passwordTextField.errorMessage()).to(equal("test"))
}
}
}
|
mit
|
f07268ec86315f00a4f626908f6a39d0
| 29.571429 | 106 | 0.584962 | 6.130208 | false | false | false | false |
Stosyk/stosyk-service
|
Tests/AppLogicTests/AdminCollection/TeamControllerTests.swift
|
1
|
4396
|
import Foundation
import XCTest
import HTTP
import URI
@testable import AppLogic
@testable import Vapor
class TeamControllerTests: XCTestCase, DropletDatabaseTests {
/// This is a requirement for XCTest on Linux to function properly.
/// See ./Tests/LinuxMain.swift for examples
static let allTests = [
("testPostTeamResponse", testPostTeamResponse),
("testGetTeamsResponse", testGetTeamsResponse),
("testGetTeamIdResponse", testGetTeamIdResponse),
("testPatchTeamIdResponse", testPatchTeamIdResponse),
("testDeleteTeamIdResponse", testDeleteTeamIdResponse),
]
var drop: Droplet!
override func setUp() {
super.setUp()
drop = type(of: self).createDroplet()
drop.collection(V1AdminCollection())
}
func testPostTeamResponse() throws {
// arrange
let post = try JSON(node: ["name": "name", "description": "desc"])
// act
let response = try dropResponse(method: .post, uri: "/admin/v1/teams", body: post.makeBody())
let node = try Node(response: response)
let teams = node?["teams"]?.nodeArray
// assert
XCTAssertEqual(response.status, .created)
XCTAssertTrue(teams?.count == 1)
let item = teams?.first
XCTAssertTrue(item?["name"] == "name")
XCTAssertTrue(item?["description"] == "desc")
XCTAssertNotNil(item?["id"])
}
func testGetTeamsResponse() throws {
// arrange
try drop.database?.driver.raw("INSERT INTO `teams`(`id`,`name`,`description`) VALUES (1,'name','desc');")
try drop.database?.driver.raw("INSERT INTO `teams`(`id`,`name`,`description`) VALUES (2,'name2','desc2');")
// act
let response = try dropResponse(method: .get, uri: "/admin/v1/teams")
let node = try Node(response: response)
let teams = node?["teams"]?.nodeArray
// assert
XCTAssertEqual(response.status, .ok)
XCTAssertTrue(teams?.count == 2)
let first = teams?[0]
XCTAssertTrue(first?["id"] == 1)
XCTAssertTrue(first?["name"] == "name")
XCTAssertTrue(first?["description"] == "desc")
let second = teams?[1]
XCTAssertTrue(second?["id"] == 2)
XCTAssertTrue(second?["name"] == "name2")
XCTAssertTrue(second?["description"] == "desc2")
}
func testGetTeamIdResponse() throws {
// arrange
try drop.database?.driver.raw("INSERT INTO `teams`(`id`,`name`,`description`) VALUES (123,'name','desc');")
// act
let response = try dropResponse(method: .get, uri: "/admin/v1/teams/123")
let node = try Node(response: response)
let teams = node?["teams"]?.nodeArray
// assert
XCTAssertEqual(response.status, .ok)
XCTAssertTrue(teams?.count == 1)
let item = teams?.first
XCTAssertTrue(item?["id"] == 123)
XCTAssertTrue(item?["name"] == "name")
XCTAssertTrue(item?["description"] == "desc")
}
func testPatchTeamIdResponse() throws {
// arrange
let post = try JSON(node: ["name": "newName", "description": "newDesc"])
try drop.database?.driver.raw("INSERT INTO `teams`(`id`,`name`,`description`) VALUES (123,'oldName','oldDesc');")
// act
let response = try dropResponse(method: .patch, uri: "/admin/v1/teams/123", body: post.makeBody())
let node = try Node(response: response)
let teams = node?["teams"]?.nodeArray
// assert
XCTAssertEqual(response.status, .ok)
let item = teams?.first
XCTAssertTrue(item?["id"] == 123)
XCTAssertTrue(item?["name"] == "newName")
XCTAssertTrue(item?["description"] == "newDesc")
}
func testDeleteTeamIdResponse() throws {
// arrange
try drop.database?.driver.raw("INSERT INTO `teams`(`id`,`name`) VALUES (123,'name');")
// act
let response = try dropResponse(method: .delete, uri: "/admin/v1/teams/123")
// assert
XCTAssertEqual(response.status, .noContent)
XCTAssertNotNil(response.body.bytes)
if let bytes = response.body.bytes {
XCTAssertTrue(bytes.isEmpty)
}
}
}
|
mit
|
96b34bc42c33153433bb2bfa1a0f0598
| 33.888889 | 121 | 0.583485 | 4.46748 | false | true | false | false |
GenerallyHelpfulSoftware/ATSCgh
|
Classes/Core Data Categories/ContentAdvisory+TV.swift
|
1
|
4634
|
//
// ContentAdvisory+TV.swift
// Signal GH
//
// Created by Glenn Howes on 4/7/17.
// Copyright © 2017 Generally Helpful Software. All rights reserved.
//
import Foundation
import CoreData
public extension ContentAdvisory
{
public static func extractAdvisories(fromDescriptors advisoryDescriptor: ContentAdvisoryDescriptor, intoShow show: ScheduledShow)
{
guard let context = show.managedObjectContext else
{
return
}
context.performAndWait
{
let contentAdvisoryEntity = NSEntityDescription.entity(forEntityName: "ContentAdvisory", in: context)!
let ratingDescriptionEntity = NSEntityDescription.entity(forEntityName: "RatingDescription", in: context)!
let eventRatingEntity = NSEntityDescription.entity(forEntityName: "EventRating", in: context)!
let advisories = advisoryDescriptor.rating_regions.map{ aRegion -> ContentAdvisory in
let anAdvisory = ContentAdvisory(entity: contentAdvisoryEntity, insertInto: context)
anAdvisory.rating_region = NSNumber(value: aRegion.rating_region)
var index = 0
let eventRatings = aRegion.eventRatingDimensions.map
{(aDimension) ->EventRating in
let anEventRating = EventRating(entity: eventRatingEntity, insertInto: context)
anEventRating.ratingIndex = NSNumber(value: index)
index += 1
let ratingValue = aDimension.rating_value
anEventRating.ratingValue = NSNumber(value: ratingValue)
anEventRating.advisory = anAdvisory
return anEventRating
}
anAdvisory.addToEventRatings(NSSet(array: eventRatings))
let descriptions = aRegion.rating_descriptions.map { (aLanguageString) -> RatingDescription in
let aDescription = RatingDescription(entity: ratingDescriptionEntity, insertInto: context)
aDescription.locale = aLanguageString.languageCode
aDescription.text = aLanguageString.string
aDescription.advisory = anAdvisory
return aDescription
}
anAdvisory.addToRatingDescriptions(NSSet(array: descriptions))
anAdvisory.show = show
return anAdvisory
}
show.addToContentAdvisories(NSSet(array: advisories))
}
}
public static func retrieveBestMatch(fromAdvisories advisories: Set<ContentAdvisory>) -> ContentAdvisory?
{
return advisories.first // TODO, be more selective
}
public func advisoryString(givenRatings ratings : Set<Rating>) -> String?
{
var result : String? = nil
self.managedObjectContext?.performAndWait {
if (self.ratingDescriptions?.count)! > 0
{
result = LocalizedString.bestMatch(fromSet: self.ratingDescriptions as! Set<LocalizedString>)
}
guard let eventRatings = self.eventRatings as? Set<EventRating> else
{
return
}
let sortedRatings = ratings.sorted(by: { (rating1, rating2) -> Bool in
guard let index1 = rating1.index?.intValue, let index2 = rating2.index?.intValue else
{
return rating1.index != rating2.index && rating1.index != nil
}
return index1 < index2
})
for anEventRating in eventRatings
{
let whichDimension = anEventRating.ratingIndex?.intValue
if whichDimension ?? 0 < sortedRatings.count
{
let theRating = sortedRatings[whichDimension ?? 0]
if let theTitle = LocalizedString.bestMatch(fromSet: theRating.titles as! Set<LocalizedString>)
{
result = (result != nil) ? "\(result!) \(theTitle)" : theTitle
}
if theRating.isGraduated?.boolValue ?? false && anEventRating.ratingValue != nil
{
let ratingValue = anEventRating.ratingValue!.stringValue
result = (result != nil) ? "\(result!) ratingValue" : ratingValue
}
}
}
}
return result
}
}
|
mit
|
96a3fb19e7288c9187b90db1b25115a5
| 41.898148 | 133 | 0.56853 | 5.406068 | false | false | false | false |
gobetti/Swift
|
NSFileManager/NSFileManager/SecondViewController.swift
|
1
|
2625
|
//
// SecondViewController.swift
// NSFileManager
//
// Created by Carlos Butron on 06/12/14.
// Copyright (c) 2014 Carlos Butron.
//
import UIKit
class SecondViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var name: UITextField!
@IBOutlet weak var text: UITextView!
@IBOutlet weak var nameDirectory: UITextField!
@IBAction func createFile(sender: UIButton) {
let content = text.text.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
if(fileManager.createFileAtPath(documentsPath.stringByAppendingPathComponent("\(name.text).txt"), contents: content, attributes: nil)){
print("created")
}
}
@IBAction func createDirectory(sender: UIButton) {
let newDirectory:NSString = documentsPath.stringByAppendingPathComponent(nameDirectory.text!)
let fileManager = NSFileManager.defaultManager()
_ = try? fileManager.createDirectoryAtPath( newDirectory as String,
withIntermediateDirectories: true,
attributes: nil )
// if(fileManager.createDirectoryAtPath(newDirectory as String, withIntermediateDirectories: true, attributes: nil)){
// print("created")
// }
}
var fileManager = NSFileManager.defaultManager()
var documentsPath = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).first! as NSString)
override func viewDidLoad() {
super.viewDidLoad()
name.delegate = self
nameDirectory.delegate = self
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldShouldReturn(textField: UITextField) -> Bool // called when 'return' key pressed. return NO to ignore.
{
textField.resignFirstResponder()
return true;
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(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
|
c9190986d8209a5eda1ac1bee3cc1fcc
| 31.012195 | 166 | 0.668952 | 5.585106 | false | false | false | false |
tuannme/Up
|
Up+/Up+/Controller/NearbyViewController.swift
|
1
|
4380
|
//
// NearbyViewController.swift
// Up+
//
// Created by Dreamup on 3/6/17.
// Copyright © 2017 Dreamup. All rights reserved.
//
import UIKit
import CoreLocation
import FirebaseDatabase
import SendBirdSDK
class NearbyViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
var nearbyUsers:[User] = []
@IBOutlet weak var tbView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
searchNearBy()
}
func searchNearBy() {
nearbyUsers.removeAll()
let ref = FIRDatabase.database().reference()
ref .child("account").observeSingleEvent(of: .value, with: {
snapshot -> Void in
if let value = snapshot.value as? NSDictionary{
let arrUser:NSArray = value.allValues as NSArray
for userDic in arrUser{
if let userDic = userDic as? NSDictionary{
let user = User()
user.userId = userDic.object(forKey: "userId") as! String!
user.photoURL = userDic.object(forKey: "photoURL") as! String!
user.username = userDic.object(forKey: "username") as! String!
user.lat = userDic.object(forKey: "lat") as! String!
user.lgn = userDic.object(forKey: "lgn") as! String!
user.updateAt = userDic.object(forKey: "updateAt") as! String!
let mLat = LocationManager.shareInstace.getLatitude()
let mLgn = LocationManager.shareInstace.getLongitude()
let coordinate1 = CLLocation(latitude: mLat, longitude: mLgn)
let coordinate2 = CLLocation(latitude: Double(user.lat!)!, longitude:Double(user.lgn!)!)
let distance = Int(coordinate1.distance(from: coordinate2))
if distance < 1000 {
user.distance = ("\(String(distance)) m")
}else{
user.distance = ("\(String(distance/1000)) km")
}
self.nearbyUsers.append(user)
}
}
}
DispatchQueue.main.async(execute: {
self.tbView.reloadData()
})
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func backAction(_ sender: Any) {
self.navigationController!.popViewController(animated: true)
}
// tableView Delegate
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return nearbyUsers.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let user = nearbyUsers[indexPath.row]
let cell = tbView.dequeueReusableCell(withIdentifier: "Cell")
let avatar = cell?.contentView.viewWithTag(111) as! UIImageView
avatar.layer.cornerRadius = 20
avatar.clipsToBounds = true
ImageCache.shareInstance.getImageURL(url: user.photoURL!, completion: {
image -> Void in
DispatchQueue.main.async(execute: {
avatar.image = image
})
})
let username = cell?.contentView.viewWithTag(222) as! UILabel
username.text = user.username
let distance = cell?.contentView.viewWithTag(333) as! UILabel
distance.text = user.distance
return cell!
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let index = tbView.indexPathForSelectedRow
if let index = index{
let user = nearbyUsers[index.row]
let messageVC = segue.destination as! MessageBaseViewController
object_setClass(messageVC, MessageFriendViewController.self)
messageVC.memberId = user.userId
}
}
}
|
mit
|
9633e3d975db511a969085d6f1b0e301
| 32.945736 | 112 | 0.537794 | 5.439752 | false | false | false | false |
inaka/EventSource
|
EventSourceSample/ViewController.swift
|
1
|
2840
|
//
// ViewController.swift
// EventSource
//
// Created by Andres on 2/13/15.
// Copyright (c) 2015 Inaka. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet fileprivate weak var status: UILabel!
@IBOutlet fileprivate weak var dataLabel: UILabel!
@IBOutlet fileprivate weak var nameLabel: UILabel!
@IBOutlet fileprivate weak var idLabel: UILabel!
@IBOutlet fileprivate weak var squareConstraint: NSLayoutConstraint!
var eventSource: EventSource?
override func viewDidLoad() {
super.viewDidLoad()
let serverURL = URL(string: "http://127.0.0.1:8080/sse")!
eventSource = EventSource(url: serverURL, headers: ["Authorization": "Bearer basic-auth-token"])
eventSource?.onOpen { [weak self] in
self?.status.backgroundColor = UIColor(red: 166/255, green: 226/255, blue: 46/255, alpha: 1)
self?.status.text = "CONNECTED"
}
eventSource?.onComplete { [weak self] statusCode, reconnect, error in
self?.status.backgroundColor = UIColor(red: 249/255, green: 38/255, blue: 114/255, alpha: 1)
self?.status.text = "DISCONNECTED"
guard reconnect ?? false else { return }
let retryTime = self?.eventSource?.retryTime ?? 3000
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(retryTime)) { [weak self] in
self?.eventSource?.connect()
}
}
eventSource?.onMessage { [weak self] id, event, data in
self?.updateLabels(id, event: event, data: data)
}
eventSource?.addEventListener("user-connected") { [weak self] id, event, data in
self?.updateLabels(id, event: event, data: data)
}
}
func updateLabels(_ id: String?, event: String?, data: String?) {
idLabel.text = id
nameLabel.text = event
dataLabel.text = data
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let finalPosition = view.frame.size.width - 50
squareConstraint.constant = 0
view.layoutIfNeeded()
let animationOptions: UIView.KeyframeAnimationOptions = [
UIView.KeyframeAnimationOptions.repeat, UIView.KeyframeAnimationOptions.autoreverse
]
UIView.animateKeyframes(withDuration: 2,
delay: 0,
options: animationOptions,
animations: { () in
self.squareConstraint.constant = finalPosition
self.view.layoutIfNeeded()
}, completion: nil)
}
@IBAction func disconnect(_ sender: Any) {
eventSource?.disconnect()
}
@IBAction func connect(_ sender: Any) {
eventSource?.connect()
}
}
|
apache-2.0
|
dd0f4f39f9cdea21089f56ec1a224528
| 32.411765 | 104 | 0.613732 | 4.678748 | false | false | false | false |
auth0/Lock.iOS-OSX
|
LockTests/Presenters/AuthPresenterSpec.swift
|
1
|
4686
|
// AuthPresenterSpec.swift
//
// Copyright (c) 2016 Auth0 (http://auth0.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Quick
import Nimble
@testable import Lock
class AuthPresenterSpec: QuickSpec {
override func spec() {
var presenter: AuthPresenter!
var interactor: MockOAuth2!
var messagePresenter: MockMessagePresenter!
beforeEach {
var connections = OfflineConnections()
connections.social(name: "social0", style: AuthStyle(name: "custom"))
interactor = MockOAuth2()
messagePresenter = MockMessagePresenter()
presenter = AuthPresenter(connections: connections.oauth2, interactor: interactor, customStyle: [:])
presenter.messagePresenter = messagePresenter
}
describe("view") {
it("should return view") {
expect(presenter.view as? AuthCollectionView).toNot(beNil())
}
it("should return view in Expanded mode") {
expect((presenter.view as? AuthCollectionView)?.mode).to(beExpandedMode())
}
}
describe("embedded view") {
it("should return view") {
expect(presenter.newViewToEmbed(withInsets: UIEdgeInsets.zero)).toNot(beNil())
}
it("should return view with expanded mode for single connection") {
let connections = OfflineConnections(databases: [], oauth2: mockConnections(count: 1), enterprise: [], passwordless: [])
presenter = AuthPresenter(connections: connections.oauth2, interactor: interactor, customStyle: [:])
expect(presenter.newViewToEmbed(withInsets: UIEdgeInsets.zero).mode).to(beExpandedMode())
}
it("should return view with expanded mode and signup flag") {
let connections = OfflineConnections(databases: [], oauth2: mockConnections(count: 1), enterprise: [], passwordless: [])
presenter = AuthPresenter(connections: connections.oauth2, interactor: interactor, customStyle: [:])
expect(presenter.newViewToEmbed(withInsets: UIEdgeInsets.zero, isLogin: false).mode).to(beExpandedMode(isLogin: false))
}
it("should return view with expanded mode for two connections") {
let connections = OfflineConnections(databases: [], oauth2: mockConnections(count: 2), enterprise: [], passwordless: [])
presenter = AuthPresenter(connections: connections.oauth2, interactor: interactor, customStyle: [:])
expect(presenter.newViewToEmbed(withInsets: UIEdgeInsets.zero).mode).to(beExpandedMode())
}
}
describe("action") {
context("oauth2") {
var view: AuthCollectionView!
beforeEach {
view = presenter.view as? AuthCollectionView
}
it("should login with connection") {
view.onAction("social0")
expect(interactor.connection) == "social0"
}
it("should hide current message on start") {
view.onAction("social0")
expect(messagePresenter.message).toEventually(beNil())
}
it("should show error") {
interactor.onStart = { return .couldNotAuthenticate }
view.onAction("social0")
expect(messagePresenter.error).toEventually(beError(error: OAuth2AuthenticatableError.couldNotAuthenticate))
}
}
}
}
}
|
mit
|
001cd54f6242e3a985b60134bf5f49dc
| 40.469027 | 136 | 0.632522 | 5.177901 | false | false | false | false |
swift-gtk/SwiftGTK
|
Sources/UIKit/Application.swift
|
1
|
6386
|
public typealias ApplicationActivateCallback = (Application) -> Void
public typealias ApplicationWindowAddedCallback = (Application, Window?) -> Void
public typealias ApplicationWindowRemovedCallback = (Application, Window?) -> Void
open class Application: Object, Signals {
typealias T = Application
fileprivate (set) var applicationWindow: ApplicationWindow?
fileprivate var windowCallback: ((_ window: ApplicationWindow) -> Void)?
public init(applicationId: String) {
super.init()
object = gtk_application_new(applicationId, G_APPLICATION_FLAGS_NONE).asGObject()
}
open func run(_ windowCallback: @escaping (_ window: ApplicationWindow) -> Void) -> Int {
self.windowCallback = windowCallback
let handler: @convention(c) (UnsafeMutableRawPointer, UnsafeMutableRawPointer) -> Void = { sender, data in
let app = unsafeBitCast(data, to: Application.self)
app.activate()
}
connectSignal("activate", data: Unmanaged.passUnretained(self).toOpaque(), handler: unsafeBitCast(handler, to: GCallback.self))
let status = g_application_run(object.asGObject(), 0, nil)
g_object_unref(object)
return Int(status)
}
fileprivate func activate() {
let window = ApplicationWindow(application: self)
windowCallback?(window)
window.showAll()
self.applicationWindow = window
}
// TODO: in future
// func windowWithId(id: Int) -> Window? {
// }
//internal var n_App: UnsafeMutablePointer<GtkApplication>
internal var _windows = [Window]()
var windows: [Window] {
return _windows
}
internal func _getWindowForNativeWindow(_ n_Window: UnsafeMutablePointer<GtkWindow>) -> Window! {
for window in _windows {
if window.object.asGObject() == n_Window {
return window
}
}
return nil
}
internal func _addWindowToApplicationStack(_ window: Window) {
_windows.append(window)
}
public func addWindow(_ window: Window) {
_windows.append(window)
gtk_application_add_window(object.asGObject(), window.object.asGObject())
}
public func removeWindow(_ window: Window) {
if let index = _windows.index(of: window) {
_windows.remove(at: index)
}
gtk_application_remove_window(object.asGObject(), window.object.asGObject())
}
public var activeWindow: Window! {
let n_object: UnsafeMutablePointer<GtkWindow> = gtk_application_get_active_window(object.asGObject()).asGObject()
return _getWindowForNativeWindow(n_object.asGObject())
}
// public init?(applicationId: String, flags: [ApplicationFlag]) {
// let totalFlag = flags.reduce(0) { $0 | $1.rawValue }
//
// n_App = gtk_application_new(applicationId, GApplicationFlags(totalFlag))
// super.init(n_Object: unsafeBitCast(n_App, to: UnsafeMutablePointer<GObject>.self))
// }
deinit {
g_object_unref (object.asGObject())
}
// MARK: - GApplication
public func run(_ arguments: [String]) -> Int {
return Int(g_application_run (UnsafeMutablePointer<GApplication> (object.asGObject()), Int32(arguments.count), arguments.withUnsafeBufferPointer {
let buffer = UnsafeMutablePointer<UnsafeMutablePointer<CChar>?>.allocate(capacity: $0.count + 1)
buffer.initialize(from: $0.map { $0.withCString(strdup) })
buffer[$0.count] = nil
return buffer
}))
}
public typealias ApplicationActivateNative = @convention(c)(UnsafeMutablePointer<GtkApplication>, gpointer) -> Void
public lazy var activateSignal: Signal<ApplicationActivateCallback, Application, ApplicationActivateNative>
= Signal(obj: self, signal: "activate", c_handler: {
(_, user_data) in
let data = unsafeBitCast(user_data, to: SignalData<Application, ApplicationActivateCallback>.self)
let application = data.obj
let action = data.function
action(application)
})
public typealias ApplicationWindowAddedNative = @convention(c)(UnsafeMutablePointer<GtkApplication>,
UnsafeMutablePointer<GtkWindow>, gpointer) -> Void
/// Emitted when a Window is added to application through Application.addWindow(_:).
public lazy var windowAddedSignal: Signal<ApplicationWindowAddedCallback, Application, ApplicationWindowAddedNative>
= Signal(obj: self, signal: "window-added", c_handler: {
(_, n_Window, user_data) in
let data = unsafeBitCast(user_data, to: SignalData<Application, ApplicationWindowAddedCallback>.self)
let application = data.obj
let window = application._getWindowForNativeWindow(n_Window.asGObject())
let action = data.function
action(application, window)
})
public typealias ApplicationWindowRemovedNative = @convention(c)(UnsafeMutablePointer<GtkApplication>,
UnsafeMutablePointer<GtkWindow>, gpointer) -> Void
public lazy var windowRemovedSignal: Signal<ApplicationWindowRemovedCallback, Application, ApplicationWindowRemovedNative>
= Signal(obj: self, signal: "window-removed", c_handler: {
(_, n_Window, user_data) in
let data = unsafeBitCast(user_data, to: SignalData<Application, ApplicationWindowRemovedCallback>.self)
let application = data.obj
let window = application._getWindowForNativeWindow(n_Window.asGObject())
let action = data.function
action(application, window)
})
}
public enum ApplicationFlag: UInt32 {
case none = 0b00000001
case isService = 0b00000010
case isLauncher = 0b00000100
case handlesOpen = 0b00001000
case handlesCommandLine = 0b00010000
case sendEnvironent = 0000100000
case nonUnique = 0b01000000
}
extension Application: Equatable { }
public func ==(lhs: Application, rhs: Application) -> Bool {
return lhs.object == rhs.object
}
|
gpl-2.0
|
4518a9ed66d08e6a4d3dfddacbec1ff1
| 33.518919 | 154 | 0.637958 | 4.664719 | false | false | false | false |
marcbbb/Spline
|
Spline/Classes/BezierExtension.swift
|
1
|
6416
|
//
// BezierExtension.swift
// Spline
//
// Created by balas on 22/10/2015.
// Copyright © 2015 com.balas. All rights reserved.
//
// Based on Objective C code from: https://github.com/jnfisher/ios-curve-interpolation/blob/master/Curve%20Interpolation/UIBezierPath%2BInterpolation.m
// From this article: http://spin.atomicobject.com/2014/05/28/ios-interpolating-points/
import Foundation
import UIKit
private var _contractionFactor: CGFloat = 0.7
extension UIBezierPath {
/// The curve‘s bend level. The good value is about 0.6 ~ 0.8. The default and recommended value is 0.7.
var contractionFactor: CGFloat {
get {
return _contractionFactor
}
set {
_contractionFactor = max(0, newValue)
}
}
/**
@param: points Points your bezier wants to through. You must give at least 1 point (different from current point) for drawing curve.
*/
func interpolatePointsWithCatMull(points points: [CGPoint]) {
assert(points.count > 0, "You must give at least 1 point for drawing the bezier.");
if points.count < 3 {
switch points.count {
case 1:
addLineToPoint(points[0])
case 2:
addLineToPoint(points[1])
default:
break
}
return
}
var previousPoint = CGPointZero
var previousCenterPoint = CGPointZero
var centerPoint = CGPointZero
var centerPointDistance = CGFloat()
var obliqueAngle = CGFloat()
var previousControlPoint1 = CGPointZero
var previousControlPoint2 = CGPointZero
var controlPoint1 = CGPointZero
for var i = 0; i < points.count; i++ {
let pointI = points[i]
if i > 0 {
previousCenterPoint = CenterPointOf(currentPoint, point2: previousPoint)
centerPoint = CenterPointOf(previousPoint, point2: pointI)
centerPointDistance = DistanceBetween(previousCenterPoint, point2: centerPoint)
obliqueAngle = ObliqueAngleOfStraightThrough(point1:centerPoint, point2:previousCenterPoint)
previousControlPoint2 = CGPoint(x: previousPoint.x - 0.5 * contractionFactor * centerPointDistance * cos(obliqueAngle), y: previousPoint.y - 0.5 * contractionFactor * centerPointDistance * sin(obliqueAngle))
controlPoint1 = CGPoint(x: previousPoint.x + 0.5 * contractionFactor * centerPointDistance * cos(obliqueAngle), y: previousPoint.y + 0.5 * contractionFactor * centerPointDistance * sin(obliqueAngle))
}
switch i {
case 1 :
addQuadCurveToPoint(previousPoint, controlPoint: previousControlPoint2)
case 2 ..< points.count - 1 :
addCurveToPoint(previousPoint, controlPoint1: previousControlPoint1, controlPoint2: previousControlPoint2)
case points.count - 1 :
addCurveToPoint(previousPoint, controlPoint1: previousControlPoint1, controlPoint2: previousControlPoint2)
addQuadCurveToPoint(pointI, controlPoint: controlPoint1)
default:
break
}
previousControlPoint1 = controlPoint1
previousPoint = pointI
}
}
}
extension UIBezierPath
{
func interpolatePointsWithHermite(interpolationPoints : [CGPoint])
{
let n = interpolationPoints.count - 1
for var ii = 0; ii < n; ++ii
{
var currentPoint = interpolationPoints[ii]
if ii == 0
{
self.moveToPoint(interpolationPoints[0])
}
var nextii = (ii + 1) % interpolationPoints.count
var previi = (ii - 1 < 0 ? interpolationPoints.count - 1 : ii-1);
var previousPoint = interpolationPoints[previi]
var nextPoint = interpolationPoints[nextii]
let endPoint = nextPoint;
var mx : Double = 0.0
var my : Double = 0.0
if ii > 0
{
mx = Double(nextPoint.x - currentPoint.x) * 0.5 + Double(currentPoint.x - previousPoint.x) * 0.5;
my = Double(nextPoint.y - currentPoint.y) * 0.5 + Double(currentPoint.y - previousPoint.y) * 0.5;
}
else
{
mx = Double(nextPoint.x - currentPoint.x) * 0.5;
my = Double(nextPoint.y - currentPoint.y) * 0.5;
}
let controlPoint1 = CGPoint(x: Double(currentPoint.x) + mx / 3.0, y: Double(currentPoint.y) + my / 3.0)
currentPoint = interpolationPoints[nextii]
nextii = (nextii + 1) % interpolationPoints.count
previi = ii;
previousPoint = interpolationPoints[previi]
nextPoint = interpolationPoints[nextii]
if ii < n - 1
{
mx = Double(nextPoint.x - currentPoint.x) * 0.5 + Double(currentPoint.x - previousPoint.x) * 0.5;
my = Double(nextPoint.y - currentPoint.y) * 0.5 + Double(currentPoint.y - previousPoint.y) * 0.5;
}
else
{
mx = Double(currentPoint.x - previousPoint.x) * 0.5;
my = Double(currentPoint.y - previousPoint.y) * 0.5;
}
let controlPoint2 = CGPoint(x: Double(currentPoint.x) - mx / 3.0, y: Double(currentPoint.y) - my / 3.0)
self.addCurveToPoint(endPoint, controlPoint1: controlPoint1, controlPoint2: controlPoint2)
}
}
}
func ObliqueAngleOfStraightThrough(point1 point1: CGPoint, point2: CGPoint) -> CGFloat { // [-π/2, 3π/2)
var obliqueRatio: CGFloat = 0
var obliqueAngle: CGFloat = 0
if (point1.x > point2.x) {
obliqueRatio = (point2.y - point1.y) / (point2.x - point1.x)
obliqueAngle = atan(obliqueRatio)
}
else if (point1.x < point2.x) {
obliqueRatio = (point2.y - point1.y) / (point2.x - point1.x)
obliqueAngle = CGFloat(M_PI) + atan(obliqueRatio)
}
else if (point2.y - point1.y >= 0) {
obliqueAngle = CGFloat(M_PI)/2
}
else {
obliqueAngle = -CGFloat(M_PI)/2
}
return obliqueAngle
}
func ControlPointForTheBezierCanThrough(point1 point1: CGPoint, point2: CGPoint, point3: CGPoint) -> CGPoint {
return CGPoint(x: (2 * point2.x - (point1.x + point3.x) / 2), y: (2 * point2.y - (point1.y + point3.y) / 2));
}
func DistanceBetween(point1: CGPoint, point2: CGPoint) -> CGFloat {
return sqrt((point1.x - point2.x) * (point1.x - point2.x) + (point1.y - point2.y) * (point1.y - point2.y))
}
func CenterPointOf(point1: CGPoint, point2: CGPoint) -> CGPoint {
return CGPoint(x: (point1.x + point2.x) / 2, y: (point1.y + point2.y) / 2)
}
|
apache-2.0
|
3009a44cf61d84b66a9226ac7c4f03b8
| 30.431373 | 215 | 0.636718 | 3.852764 | false | false | false | false |
jquave/SwiftLSColors
|
lss.swift
|
1
|
1504
|
#!/usr/bin/env xcrun swift -i -sdk /Applications/Xcode6-Beta.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk
import Foundation
let C_RED = "\x1b[31m"
let C_GREEN = "\x1b[32m"
let C_YELLOW = "\x1b[33m"
let C_BLUE = "\x1b[34m"
let C_MAGENTA = "\x1b[35m"
let C_CYAN = "\x1b[36m"
let C_RESET = "\x1b[0m"
let fileManager = NSFileManager.defaultManager()
var showHiddenFiles = false
var argCount = C_ARGC as CInt
if argCount == CInt(2) {
var arg = C_ARGV[1] as CString
if arg == "-h" {
showHiddenFiles = true
}
}
let path = "./"
//let contents = fileManager.directoryContentsAtPath(path) as String[]
var err: NSError?
var pathURL = NSURL(string: path)
var options = NSDirectoryEnumerationOptions.SkipsHiddenFiles
if !showHiddenFiles {
options = nil
}
let contents = fileManager.contentsOfDirectoryAtURL(pathURL, includingPropertiesForKeys: nil, options: options, error: &err)
func setColor(color: String) {
print(color)
}
for item: AnyObject in contents {
let url: NSURL = item as NSURL
var isDirectoryOC: ObjCBool = false
let fullPath = "\(path)\(item)"
fileManager.fileExistsAtPath(url.absoluteString, isDirectory: &isDirectoryOC)
let isDirectory = isDirectoryOC as Bool
let isExecutable = fileManager.isExecutableFileAtPath(fullPath)
if isDirectory {
setColor(C_RED)
}
else if isExecutable {
setColor(C_BLUE)
}
else {
setColor(C_RESET)
}
print("\(url.lastPathComponent) ")
}
println("")
|
mit
|
e35ad526a674def59acdc88709c445da
| 21.447761 | 140 | 0.704787 | 3.410431 | false | false | false | false |
HackerEdu/TangZhifeng
|
day3/sorting.playground/section-1.swift
|
1
|
1007
|
var numberList = [9,12,45,32,6]
func insertionSort(){
var x, y, key :Int
for (x = 0; x < numberList.count; x++){
key = numberList[x]
for (y = x; y > -1; y = y-1){
if (key < numberList[y]){
numberList.removeAtIndex(y + 1)
numberList.insert(key, atIndex: y)
}
}
}
}
insertionSort()
numberList
func bubblesort(){
}
func quickSort(var newArray: Array<Int>) -> Array<Int> {
var less:[Int] = []
var equal:[Int] = []
var more: [Int] = []
if newArray.count > 1 {
var pivot = newArray[0]
for x in newArray{
if x < pivot {
less.append(x)
}else if x > pivot{
more.append(x)
}else{
equal.append(x)
}
}
return (quickSort(less) + equal + quickSort(more))
}else{
return newArray
}
}
|
mit
|
e370139752aa2f76c00981f6aa3d06ca
| 16.982143 | 58 | 0.428004 | 3.918288 | false | false | false | false |
Shopify/mobile-buy-sdk-ios
|
Buy/Generated/Storefront/LocationEdge.swift
|
1
|
3692
|
//
// LocationEdge.swift
// Buy
//
// Created by Shopify.
// Copyright (c) 2017 Shopify Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
extension Storefront {
/// An auto-generated type which holds one Location and a cursor during
/// pagination.
open class LocationEdgeQuery: GraphQL.AbstractQuery, GraphQLQuery {
public typealias Response = LocationEdge
/// A cursor for use in pagination.
@discardableResult
open func cursor(alias: String? = nil) -> LocationEdgeQuery {
addField(field: "cursor", aliasSuffix: alias)
return self
}
/// The item at the end of LocationEdge.
@discardableResult
open func node(alias: String? = nil, _ subfields: (LocationQuery) -> Void) -> LocationEdgeQuery {
let subquery = LocationQuery()
subfields(subquery)
addField(field: "node", aliasSuffix: alias, subfields: subquery)
return self
}
}
/// An auto-generated type which holds one Location and a cursor during
/// pagination.
open class LocationEdge: GraphQL.AbstractResponse, GraphQLObject {
public typealias Query = LocationEdgeQuery
internal override func deserializeValue(fieldName: String, value: Any) throws -> Any? {
let fieldValue = value
switch fieldName {
case "cursor":
guard let value = value as? String else {
throw SchemaViolationError(type: LocationEdge.self, field: fieldName, value: fieldValue)
}
return value
case "node":
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: LocationEdge.self, field: fieldName, value: fieldValue)
}
return try Location(fields: value)
default:
throw SchemaViolationError(type: LocationEdge.self, field: fieldName, value: fieldValue)
}
}
/// A cursor for use in pagination.
open var cursor: String {
return internalGetCursor()
}
func internalGetCursor(alias: String? = nil) -> String {
return field(field: "cursor", aliasSuffix: alias) as! String
}
/// The item at the end of LocationEdge.
open var node: Storefront.Location {
return internalGetNode()
}
func internalGetNode(alias: String? = nil) -> Storefront.Location {
return field(field: "node", aliasSuffix: alias) as! Storefront.Location
}
internal override func childResponseObjectMap() -> [GraphQL.AbstractResponse] {
var response: [GraphQL.AbstractResponse] = []
objectMap.keys.forEach {
switch($0) {
case "node":
response.append(internalGetNode())
response.append(contentsOf: internalGetNode().childResponseObjectMap())
default:
break
}
}
return response
}
}
}
|
mit
|
d19534ed05c99bc292f63cc86f31c98c
| 32.261261 | 99 | 0.716414 | 4.079558 | false | false | false | false |
ylovesy/CodeFun
|
wuzhentao/coinChange.swift
|
1
|
699
|
class Solution {
func coinChange(_ coins: [Int], _ amount: Int) -> Int {
var dp = Array(repeating: -1, count: amount + 1)
dp[0] = 0
for (index,_) in dp.enumerated() {
if dp[index] < 0 {
continue
}
for item2 in coins {
let amc = index + item2
if amc > amount {
continue
}
if dp[amc] > dp[index] + 1 || dp[amc] < 0 {
dp[amc] = dp[index] + 1
}
}
}
let result = dp[amount];
return result
}
}
|
apache-2.0
|
081182c3849dc03488bb4fd42be5b504
| 23.103448 | 59 | 0.337625 | 4.538961 | false | false | false | false |
nheagy/WordPress-iOS
|
WordPress/Classes/ViewRelated/Notifications/Views/NoteBlockTableViewCell.swift
|
1
|
1568
|
import Foundation
import WordPressShared
@objc public class NoteBlockTableViewCell : WPTableViewCell
{
// MARK: - Public Properties
public var isBadge: Bool = false {
didSet {
refreshSeparators()
}
}
public var isLastRow: Bool = false {
didSet {
refreshSeparators()
}
}
public var separatorsView = SeparatorsView()
// MARK: - Public Methods
public func refreshSeparators() {
// Exception: Badges require no separators
if isBadge {
separatorsView.bottomVisible = false
return;
}
// Last Rows requires full separators
separatorsView.bottomInsets = isLastRow ? fullSeparatorInsets : indentedSeparatorInsets
separatorsView.bottomVisible = true
}
public func isLayoutCell() -> Bool {
return self.dynamicType.layoutIdentifier() == reuseIdentifier
}
public class func reuseIdentifier() -> String {
return classNameWithoutNamespaces()
}
public class func layoutIdentifier() -> String {
return classNameWithoutNamespaces() + "-Layout"
}
// MARK: - View Methods
public override func awakeFromNib() {
super.awakeFromNib()
backgroundView = separatorsView
}
// MARK: - Private Constants
private let fullSeparatorInsets = UIEdgeInsetsZero
private let indentedSeparatorInsets = UIEdgeInsets(top: 0.0, left: 12.0, bottom: 0.0, right: 0.0)
}
|
gpl-2.0
|
12829819069f137b59fe7c6278392c5b
| 27.509091 | 101 | 0.609056 | 5.315254 | false | false | false | false |
wordpress-mobile/WordPress-iOS
|
WordPress/WordPressShareExtension/ExtensionPresentationAnimator.swift
|
2
|
2231
|
import UIKit
final class ExtensionPresentationAnimator: NSObject {
// MARK: - Properties
let direction: Direction
let isPresentation: Bool
// MARK: - Initializers
init(direction: Direction, isPresentation: Bool) {
self.direction = direction
self.isPresentation = isPresentation
super.init()
}
}
// MARK: - UIViewControllerAnimatedTransitioning Conformance
extension ExtensionPresentationAnimator: UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return Constants.animationDuration
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let key = isPresentation ? UITransitionContextViewControllerKey.to : UITransitionContextViewControllerKey.from
let controller = transitionContext.viewController(forKey: key)!
if isPresentation {
transitionContext.containerView.addSubview(controller.view)
}
let presentedFrame = transitionContext.finalFrame(for: controller)
var dismissedFrame = presentedFrame
switch direction {
case .left:
dismissedFrame.origin.x = -presentedFrame.width
case .right:
dismissedFrame.origin.x = transitionContext.containerView.frame.size.width
case .top:
dismissedFrame.origin.y = -presentedFrame.height
case .bottom:
dismissedFrame.origin.y = transitionContext.containerView.frame.size.height
}
let initialFrame = isPresentation ? dismissedFrame : presentedFrame
let finalFrame = isPresentation ? presentedFrame : dismissedFrame
let animationDuration = transitionDuration(using: transitionContext)
controller.view.frame = initialFrame
UIView.animate(withDuration: animationDuration, animations: {
controller.view.frame = finalFrame
}) { finished in
transitionContext.completeTransition(finished)
}
}
}
// MARK: - Constants
private extension ExtensionPresentationAnimator {
struct Constants {
static let animationDuration: Double = 0.33
}
}
|
gpl-2.0
|
36aafc342db730022d65a3be115ada3c
| 32.298507 | 118 | 0.707306 | 6.2493 | false | false | false | false |
mlgoogle/viossvc
|
viossvc/General/CommenClass/CommonWebVC.swift
|
1
|
1588
|
//
// CommonWebVC.swift
// HappyTravel
//
// Created by 司留梦 on 16/12/27.
// Copyright © 2016年 陈奕涛. All rights reserved.
//
import UIKit
import WebKit
import SnapKit
class CommonWebVC: UIViewController {
private var requestUrl:String? = nil
private var webTitle:String?
init(title: String?, url: String) {
super.init(nibName: nil, bundle: nil)
requestUrl = url
webTitle = title
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
title = webTitle ?? "网页"
self.view.backgroundColor = UIColor.redColor()
let webView = WKWebView()
view.addSubview(webView)
webView.snp_makeConstraints { (make) in
make.edges.equalTo(view)
}
let url = NSURL(string: requestUrl ?? "http://www.yundiantrip.com")
webView.loadRequest(NSURLRequest(URL: url!))
}
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.
}
*/
}
|
apache-2.0
|
1ab75da41d1899d20a936e0a6b7be3df
| 25.59322 | 107 | 0.626514 | 4.587719 | false | false | false | false |
TechnologySpeaks/smile-for-life
|
smile-for-life/CategoryCell.swift
|
1
|
3975
|
//
// CategoryCell.swift
// smile-for-life
//
// Created by Lisa Swanson on 4/29/16.
// Copyright © 2016 Technology Speaks. All rights reserved.
//
import UIKit
class CategoryCell: UICollectionViewCell, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
var photoCategory: DataSource? {
didSet {
if let name = photoCategory?.headerSectionName {
sectionLabel.text = name
}
}
}
fileprivate let cellId = "photoCellId"
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
let sectionLabel: UILabel = {
let label = UILabel()
label.text = "Healthy Teeth & Gums"
label.font = UIFont(name: "Gurmukhi MN", size: 23)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
let photosCollectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.clear
collectionView.translatesAutoresizingMaskIntoConstraints = false
return collectionView
}()
let dividerLineView: UIView = {
let view = UIView()
view.backgroundColor = UIColor(white: 0.4, alpha: 0.4)
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
func setupViews() {
backgroundColor = UIColor.clear
addSubview(photosCollectionView)
addSubview(sectionLabel)
addSubview(dividerLineView)
photosCollectionView.dataSource = self
photosCollectionView.delegate = self
photosCollectionView.register(PhotoCell.self, forCellWithReuseIdentifier: cellId)
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-10-[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": sectionLabel]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-5-[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": dividerLineView]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": photosCollectionView]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[nameLabel(30)][v0][v1(0.5)]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": photosCollectionView, "v1": dividerLineView, "nameLabel": sectionLabel]))
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if let count = photoCategory?.photoGroups?.count {
return count
}
return 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! PhotoCell
cell.photo = photoCategory?.photoGroups?[(indexPath as NSIndexPath).item]
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 130, height: frame.height - 32)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsetsMake(0, 5, 0, 5)
}
}
|
mit
|
54cf5373ed913800ee0e2a31a9053336
| 33.556522 | 243 | 0.656014 | 5.660969 | false | false | false | false |
circuit-project/identifiers
|
Tests/IdentifiersTests/RoomIdSpec.swift
|
1
|
5174
|
//
// RoomIdSpec.swift
// Identifiers
//
// Created by Gustavo Perdomo on 4/9/17.
// Copyright © 2017 Gustavo Perdomo. All rights reserved.
//
import Quick
import Nimble
@testable import Identifiers
// swiftlint:disable function_body_length
class RoomIdSpec: QuickSpec {
override func spec() {
var err: IdentifierError?
var roomId: RoomId?
describe("Room Id") {
beforeEach {
err = nil
roomId = nil
}
it("generate a valid room id") {
roomId = try? RoomId(from: "!29fhd83h92h0:example.com")
expect(roomId).toNot(beNil())
expect(roomId?.description).to(equal("!29fhd83h92h0:example.com"))
expect(roomId?.localpart).to(equal("29fhd83h92h0"))
//expect(roomId?.opaqueId).to(equal("29fhd83h92h0"))
expect(roomId?.hostname).to(equal("example.com"))
expect(roomId?.port).to(equal(443))
}
it("generate a random valid room id") {
roomId = try? RoomId(server: "example.com")
expect(roomId).toNot(beNil())
expect(roomId?.description.hasPrefix("!")).to(beTrue())
expect(roomId?.localpart.characters.count).to(equal(18))
//expect(roomId?.opaqueId.characters.count).to(equal(18))
expect(roomId?.hostname).to(equal("example.com"))
expect(roomId?.port).to(equal(443))
}
it("Throws error on invalid room id") {
do {
_ = try RoomId(server: "")
} catch {
err = error as? IdentifierError
}
expect(err).toNot(beNil())
expect(err).to(equal(IdentifierError.invalidHost))
}
it("generate valid room id with explicit standard port") {
roomId = try? RoomId(from: "!29fhd83h92h0:example.com")
expect(roomId).toNot(beNil())
expect(roomId?.description).to(equal("!29fhd83h92h0:example.com"))
expect(roomId?.localpart).to(equal("29fhd83h92h0"))
//expect(roomId?.opaqueId).to(equal("29fhd83h92h0"))
expect(roomId?.hostname).to(equal("example.com"))
expect(roomId?.port).to(equal(443))
}
it("generate valid room id with non standard port") {
roomId = try? RoomId(from: "!29fhd83h92h0:example.com:5000")
expect(roomId).toNot(beNil())
expect(roomId?.description).to(equal("!29fhd83h92h0:example.com:5000"))
expect(roomId?.localpart).to(equal("29fhd83h92h0"))
//expect(roomId?.opaqueId).to(equal("29fhd83h92h0"))
expect(roomId?.hostname).to(equal("example.com"))
expect(roomId?.port).to(equal(5000))
}
it("throws missing room id sigil") {
do {
_ = try RoomId(from: "29fhd83h92h0:example.com:5000")
} catch {
err = error as? IdentifierError
}
expect(err).toNot(beNil())
expect(err).to(equal(IdentifierError.missingSigil))
}
it("throws missing room id delimiter") {
do {
_ = try RoomId(from: "!29fhd83h92h0")
} catch {
err = error as? IdentifierError
}
expect(err).toNot(beNil())
expect(err).to(equal(IdentifierError.missingDelimiter))
}
it("throws invalid room id host") {
do {
let e = try RoomId(from: "!29fhd83h92h0:")
print(e)
} catch {
err = error as? IdentifierError
}
expect(err).toNot(beNil())
expect(err).to(equal(IdentifierError.invalidHost))
}
it("throws invalid room id port") {
do {
_ = try RoomId(from: "!29fhd83h92h0:example.com:notaport")
} catch {
err = error as? IdentifierError
}
expect(err).toNot(beNil())
expect(err).to(equal(IdentifierError.invalidHost))
}
it("throws invalid room id length") {
do {
_ = try RoomId(from: "!r:")
} catch {
err = error as? IdentifierError
}
expect(err).toNot(beNil())
expect(err).to(equal(IdentifierError.minimumLengthNotSatisfied))
do {
let string = "!\(String.random(ofLength: 250)):example.com"
_ = try RoomId(from: string)
} catch {
err = error as? IdentifierError
}
expect(err).toNot(beNil())
expect(err).to(equal(IdentifierError.maximumLengthExceeded))
}
}
}
}
|
mit
|
64db23f262842c1227b0d4c4ceadb8d7
| 34.190476 | 87 | 0.489078 | 4.36172 | false | false | false | false |
Chaosspeeder/YourGoals
|
YourGoals/Business/DataSource/HabitsDataSource.swift
|
1
|
3096
|
//
// HabitDataSource.swift
// YourGoals
//
// Created by André Claaßen on 10.11.17.
// Copyright © 2017 André Claaßen. All rights reserved.
//
import Foundation
/// a data source for retrieving ordered tasks from a goal
class HabitsDataSource: ActionableDataSource, ActionablePositioningProtocol, ActionableSwitchProtocol {
let habitOrderManager:HabitOrderManager
let habitCheckManager:HabitCheckManager
let goal:Goal?
init(manager: GoalsStorageManager, forGoal goal: Goal? = nil) {
self.habitOrderManager = HabitOrderManager(manager: manager)
self.habitCheckManager = HabitCheckManager(manager: manager)
self.goal = goal
}
// MARK: ActionableTableViewDataSource
func fetchSections(forDate date: Date, withBackburned backburnedGoals: Bool) throws -> [ActionableSection] {
return []
}
func fetchItems(forDate date: Date, withBackburned backburnedGoals: Bool, andSection: ActionableSection?) throws -> [ActionableItem] {
let actionables = try habitOrderManager.habitsByOrder(forGoal: self.goal, backburnedGoals: backburnedGoals)
return actionables.map { ActionableResult(actionable: $0) }
}
func positioningProtocol() -> ActionablePositioningProtocol? {
return self
}
func switchProtocol(forBehavior behavior: ActionableBehavior) -> ActionableSwitchProtocol? {
switch behavior {
case .state:
return self
case .progress:
return nil
case .commitment:
return nil
case .tomorrow:
return nil
}
}
// MARK: ActionablePositioningProtocol
func updatePosition(items: [ActionableItem], fromPosition: Int, toPosition: Int) throws {
let habits = items.map { $0.actionable as! Habit }
try self.habitOrderManager.updatePosition(habits: habits, fromPosition: fromPosition, toPosition: toPosition)
}
func moveIntoSection(item: ActionableItem, section: ActionableSection, toPosition: Int) throws {
assertionFailure("this method shouldn't be called")
}
// MARK: ActionableSwitchProtocol
func switchBehavior(forItem item: ActionableItem, atDate date: Date) throws {
guard let habit = item.actionable as? Habit else {
NSLog("couldn't get habit from actionable: \(item.actionable)")
return
}
let checked = habit.isChecked(forDate: date)
if checked {
try self.habitCheckManager.checkHabit(forHabit: habit, state: .notChecked, atDate: date)
} else {
try self.habitCheckManager.checkHabit(forHabit: habit, state: .checked, atDate: date)
}
}
func isBehaviorActive(forItem item: ActionableItem, atDate date: Date) -> Bool {
guard let habit = item.actionable as? Habit else {
NSLog("couldn't get habit from actionable: \(item.actionable)")
return false
}
return habit.isChecked(forDate: date)
}
}
|
lgpl-3.0
|
0b44895d30013d923d34e87050688fe7
| 32.597826 | 138 | 0.658687 | 4.740798 | false | false | false | false |
apple/swift-protobuf
|
Sources/SwiftProtobufCore/BinaryEncoder.swift
|
2
|
4811
|
// Sources/SwiftProtobuf/BinaryEncoder.swift - Binary encoding support
//
// 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/main/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Core support for protobuf binary encoding. Note that this is built
/// on the general traversal machinery.
///
// -----------------------------------------------------------------------------
import Foundation
/// Encoder for Binary Protocol Buffer format
internal struct BinaryEncoder {
internal var pointer: UnsafeMutableRawPointer
init(forWritingInto pointer: UnsafeMutableRawPointer) {
self.pointer = pointer
}
private mutating func append(_ byte: UInt8) {
pointer.storeBytes(of: byte, as: UInt8.self)
pointer = pointer.advanced(by: 1)
}
private mutating func append(contentsOf data: Data) {
data.withUnsafeBytes { dataPointer in
if let baseAddress = dataPointer.baseAddress, dataPointer.count > 0 {
pointer.copyMemory(from: baseAddress, byteCount: dataPointer.count)
pointer = pointer.advanced(by: dataPointer.count)
}
}
}
@discardableResult
private mutating func append(contentsOf bufferPointer: UnsafeRawBufferPointer) -> Int {
let count = bufferPointer.count
if let baseAddress = bufferPointer.baseAddress, count > 0 {
memcpy(pointer, baseAddress, count)
}
pointer = pointer.advanced(by: count)
return count
}
func distance(pointer: UnsafeMutableRawPointer) -> Int {
return pointer.distance(to: self.pointer)
}
mutating func appendUnknown(data: Data) {
append(contentsOf: data)
}
mutating func startField(fieldNumber: Int, wireFormat: WireFormat) {
startField(tag: FieldTag(fieldNumber: fieldNumber, wireFormat: wireFormat))
}
mutating func startField(tag: FieldTag) {
putVarInt(value: UInt64(tag.rawValue))
}
mutating func putVarInt(value: UInt64) {
var v = value
while v > 127 {
append(UInt8(v & 0x7f | 0x80))
v >>= 7
}
append(UInt8(v))
}
mutating func putVarInt(value: Int64) {
putVarInt(value: UInt64(bitPattern: value))
}
mutating func putVarInt(value: Int) {
putVarInt(value: Int64(value))
}
mutating func putZigZagVarInt(value: Int64) {
let coded = ZigZag.encoded(value)
putVarInt(value: coded)
}
mutating func putBoolValue(value: Bool) {
append(value ? 1 : 0)
}
mutating func putFixedUInt64(value: UInt64) {
var v = value.littleEndian
let n = MemoryLayout<UInt64>.size
memcpy(pointer, &v, n)
pointer = pointer.advanced(by: n)
}
mutating func putFixedUInt32(value: UInt32) {
var v = value.littleEndian
let n = MemoryLayout<UInt32>.size
memcpy(pointer, &v, n)
pointer = pointer.advanced(by: n)
}
mutating func putFloatValue(value: Float) {
let n = MemoryLayout<Float>.size
var v = value
var nativeBytes: UInt32 = 0
memcpy(&nativeBytes, &v, n)
var littleEndianBytes = nativeBytes.littleEndian
memcpy(pointer, &littleEndianBytes, n)
pointer = pointer.advanced(by: n)
}
mutating func putDoubleValue(value: Double) {
let n = MemoryLayout<Double>.size
var v = value
var nativeBytes: UInt64 = 0
memcpy(&nativeBytes, &v, n)
var littleEndianBytes = nativeBytes.littleEndian
memcpy(pointer, &littleEndianBytes, n)
pointer = pointer.advanced(by: n)
}
// Write a string field, including the leading index/tag value.
mutating func putStringValue(value: String) {
let utf8 = value.utf8
// If the String does not support an internal representation in a form
// of contiguous storage, body is not called and nil is returned.
let isAvailable = utf8.withContiguousStorageIfAvailable { (body: UnsafeBufferPointer<UInt8>) -> Int in
putVarInt(value: body.count)
return append(contentsOf: UnsafeRawBufferPointer(body))
}
if isAvailable == nil {
let count = utf8.count
putVarInt(value: count)
for b in utf8 {
pointer.storeBytes(of: b, as: UInt8.self)
pointer = pointer.advanced(by: 1)
}
}
}
mutating func putBytesValue(value: Data) {
putVarInt(value: value.count)
append(contentsOf: value)
}
}
|
apache-2.0
|
f40efe6a2e9ab849dd4bb46275db9fa2
| 31.288591 | 110 | 0.610892 | 4.56019 | false | false | false | false |
nessBautista/iOSBackup
|
iOSNotebook/Pods/AlamofireImage/Source/ImageCache.swift
|
1
|
13583
|
//
// ImageCache.swift
//
// Copyright (c) 2015-2018 Alamofire Software Foundation (http://alamofire.org/)
//
// 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 Alamofire
import Foundation
#if os(iOS) || os(tvOS) || os(watchOS)
import UIKit
#elseif os(macOS)
import Cocoa
#endif
// MARK: ImageCache
/// The `ImageCache` protocol defines a set of APIs for adding, removing and fetching images from a cache.
public protocol ImageCache {
/// Adds the image to the cache with the given identifier.
func add(_ image: Image, withIdentifier identifier: String)
/// Removes the image from the cache matching the given identifier.
func removeImage(withIdentifier identifier: String) -> Bool
/// Removes all images stored in the cache.
@discardableResult
func removeAllImages() -> Bool
/// Returns the image in the cache associated with the given identifier.
func image(withIdentifier identifier: String) -> Image?
}
/// The `ImageRequestCache` protocol extends the `ImageCache` protocol by adding methods for adding, removing and
/// fetching images from a cache given an `URLRequest` and additional identifier.
public protocol ImageRequestCache: ImageCache {
/// Adds the image to the cache using an identifier created from the request and identifier.
func add(_ image: Image, for request: URLRequest, withIdentifier identifier: String?)
/// Removes the image from the cache using an identifier created from the request and identifier.
func removeImage(for request: URLRequest, withIdentifier identifier: String?) -> Bool
/// Returns the image from the cache associated with an identifier created from the request and identifier.
func image(for request: URLRequest, withIdentifier identifier: String?) -> Image?
}
// MARK: -
/// The `AutoPurgingImageCache` in an in-memory image cache used to store images up to a given memory capacity. When
/// the memory capacity is reached, the image cache is sorted by last access date, then the oldest image is continuously
/// purged until the preferred memory usage after purge is met. Each time an image is accessed through the cache, the
/// internal access date of the image is updated.
open class AutoPurgingImageCache: ImageRequestCache {
class CachedImage {
let image: Image
let identifier: String
let totalBytes: UInt64
var lastAccessDate: Date
init(_ image: Image, identifier: String) {
self.image = image
self.identifier = identifier
self.lastAccessDate = Date()
self.totalBytes = {
#if os(iOS) || os(tvOS) || os(watchOS)
let size = CGSize(width: image.size.width * image.scale, height: image.size.height * image.scale)
#elseif os(macOS)
let size = CGSize(width: image.size.width, height: image.size.height)
#endif
let bytesPerPixel: CGFloat = 4.0
let bytesPerRow = size.width * bytesPerPixel
let totalBytes = UInt64(bytesPerRow) * UInt64(size.height)
return totalBytes
}()
}
func accessImage() -> Image {
lastAccessDate = Date()
return image
}
}
// MARK: Properties
/// The current total memory usage in bytes of all images stored within the cache.
open var memoryUsage: UInt64 {
var memoryUsage: UInt64 = 0
synchronizationQueue.sync { memoryUsage = self.currentMemoryUsage }
return memoryUsage
}
/// The total memory capacity of the cache in bytes.
open let memoryCapacity: UInt64
/// The preferred memory usage after purge in bytes. During a purge, images will be purged until the memory
/// capacity drops below this limit.
open let preferredMemoryUsageAfterPurge: UInt64
private let synchronizationQueue: DispatchQueue
private var cachedImages: [String: CachedImage]
private var currentMemoryUsage: UInt64
// MARK: Initialization
/// Initialies the `AutoPurgingImageCache` instance with the given memory capacity and preferred memory usage
/// after purge limit.
///
/// Please note, the memory capacity must always be greater than or equal to the preferred memory usage after purge.
///
/// - parameter memoryCapacity: The total memory capacity of the cache in bytes. `100 MB` by default.
/// - parameter preferredMemoryUsageAfterPurge: The preferred memory usage after purge in bytes. `60 MB` by default.
///
/// - returns: The new `AutoPurgingImageCache` instance.
public init(memoryCapacity: UInt64 = 100_000_000, preferredMemoryUsageAfterPurge: UInt64 = 60_000_000) {
self.memoryCapacity = memoryCapacity
self.preferredMemoryUsageAfterPurge = preferredMemoryUsageAfterPurge
precondition(
memoryCapacity >= preferredMemoryUsageAfterPurge,
"The `memoryCapacity` must be greater than or equal to `preferredMemoryUsageAfterPurge`"
)
self.cachedImages = [:]
self.currentMemoryUsage = 0
self.synchronizationQueue = {
let name = String(format: "org.alamofire.autopurgingimagecache-%08x%08x", arc4random(), arc4random())
return DispatchQueue(label: name, attributes: .concurrent)
}()
#if os(iOS) || os(tvOS)
NotificationCenter.default.addObserver(
self,
selector: #selector(AutoPurgingImageCache.removeAllImages),
name: Notification.Name.UIApplicationDidReceiveMemoryWarning,
object: nil
)
#endif
}
deinit {
NotificationCenter.default.removeObserver(self)
}
// MARK: Add Image to Cache
/// Adds the image to the cache using an identifier created from the request and optional identifier.
///
/// - parameter image: The image to add to the cache.
/// - parameter request: The request used to generate the image's unique identifier.
/// - parameter identifier: The additional identifier to append to the image's unique identifier.
open func add(_ image: Image, for request: URLRequest, withIdentifier identifier: String? = nil) {
let requestIdentifier = imageCacheKey(for: request, withIdentifier: identifier)
add(image, withIdentifier: requestIdentifier)
}
/// Adds the image to the cache with the given identifier.
///
/// - parameter image: The image to add to the cache.
/// - parameter identifier: The identifier to use to uniquely identify the image.
open func add(_ image: Image, withIdentifier identifier: String) {
synchronizationQueue.async(flags: [.barrier]) {
let cachedImage = CachedImage(image, identifier: identifier)
if let previousCachedImage = self.cachedImages[identifier] {
self.currentMemoryUsage -= previousCachedImage.totalBytes
}
self.cachedImages[identifier] = cachedImage
self.currentMemoryUsage += cachedImage.totalBytes
}
synchronizationQueue.async(flags: [.barrier]) {
if self.currentMemoryUsage > self.memoryCapacity {
let bytesToPurge = self.currentMemoryUsage - self.preferredMemoryUsageAfterPurge
var sortedImages = self.cachedImages.map { $1 }
sortedImages.sort {
let date1 = $0.lastAccessDate
let date2 = $1.lastAccessDate
return date1.timeIntervalSince(date2) < 0.0
}
var bytesPurged = UInt64(0)
for cachedImage in sortedImages {
self.cachedImages.removeValue(forKey: cachedImage.identifier)
bytesPurged += cachedImage.totalBytes
if bytesPurged >= bytesToPurge {
break
}
}
self.currentMemoryUsage -= bytesPurged
}
}
}
// MARK: Remove Image from Cache
/// Removes the image from the cache using an identifier created from the request and optional identifier.
///
/// - parameter request: The request used to generate the image's unique identifier.
/// - parameter identifier: The additional identifier to append to the image's unique identifier.
///
/// - returns: `true` if the image was removed, `false` otherwise.
@discardableResult
open func removeImage(for request: URLRequest, withIdentifier identifier: String?) -> Bool {
let requestIdentifier = imageCacheKey(for: request, withIdentifier: identifier)
return removeImage(withIdentifier: requestIdentifier)
}
/// Removes all images from the cache created from the request.
///
/// - parameter request: The request used to generate the image's unique identifier.
///
/// - returns: `true` if any images were removed, `false` otherwise.
@discardableResult
open func removeImages(matching request: URLRequest) -> Bool {
let requestIdentifier = imageCacheKey(for: request, withIdentifier: nil)
var removed = false
synchronizationQueue.sync {
for key in self.cachedImages.keys where key.hasPrefix(requestIdentifier) {
if let cachedImage = self.cachedImages.removeValue(forKey: key) {
self.currentMemoryUsage -= cachedImage.totalBytes
removed = true
}
}
}
return removed
}
/// Removes the image from the cache matching the given identifier.
///
/// - parameter identifier: The unique identifier for the image.
///
/// - returns: `true` if the image was removed, `false` otherwise.
@discardableResult
open func removeImage(withIdentifier identifier: String) -> Bool {
var removed = false
synchronizationQueue.sync {
if let cachedImage = self.cachedImages.removeValue(forKey: identifier) {
self.currentMemoryUsage -= cachedImage.totalBytes
removed = true
}
}
return removed
}
/// Removes all images stored in the cache.
///
/// - returns: `true` if images were removed from the cache, `false` otherwise.
@discardableResult @objc
open func removeAllImages() -> Bool {
var removed = false
synchronizationQueue.sync {
if !self.cachedImages.isEmpty {
self.cachedImages.removeAll()
self.currentMemoryUsage = 0
removed = true
}
}
return removed
}
// MARK: Fetch Image from Cache
/// Returns the image from the cache associated with an identifier created from the request and optional identifier.
///
/// - parameter request: The request used to generate the image's unique identifier.
/// - parameter identifier: The additional identifier to append to the image's unique identifier.
///
/// - returns: The image if it is stored in the cache, `nil` otherwise.
open func image(for request: URLRequest, withIdentifier identifier: String? = nil) -> Image? {
let requestIdentifier = imageCacheKey(for: request, withIdentifier: identifier)
return image(withIdentifier: requestIdentifier)
}
/// Returns the image in the cache associated with the given identifier.
///
/// - parameter identifier: The unique identifier for the image.
///
/// - returns: The image if it is stored in the cache, `nil` otherwise.
open func image(withIdentifier identifier: String) -> Image? {
var image: Image?
synchronizationQueue.sync {
if let cachedImage = self.cachedImages[identifier] {
image = cachedImage.accessImage()
}
}
return image
}
// MARK: Image Cache Keys
/// Returns the unique image cache key for the specified request and additional identifier.
///
/// - parameter request: The request.
/// - parameter identifier: The additional identifier.
///
/// - returns: The unique image cache key.
open func imageCacheKey(for request: URLRequest, withIdentifier identifier: String?) -> String {
var key = request.url?.absoluteString ?? ""
if let identifier = identifier {
key += "-\(identifier)"
}
return key
}
}
|
cc0-1.0
|
144b86365d265cb61ee3963756155e69
| 38.371014 | 121 | 0.65582 | 5.256579 | false | false | false | false |
iOS-Swift-Developers/Swift
|
实战项目一/JQLiveTV/JQLiveTV/Classes/Home/Other/WaterfallLayout.swift
|
1
|
3197
|
//
// WaterfallLayout.swift
// JQLiveTV
//
// Created by 韩俊强 on 2017/7/31.
// Copyright © 2017年 HaRi. All rights reserved.
// 欢迎加入iOS交流群: ①群:446310206 ②群:426087546
import UIKit
@objc protocol WaterfallLayoutDataSource : class {
func waterfallLayout(_ latout : WaterfallLayout, indexPath : IndexPath) -> CGFloat
@objc optional func numberOfColsInWaterfallLayout(_ layout : WaterfallLayout) -> Int
}
class WaterfallLayout: UICollectionViewFlowLayout {
// MARK: 对外提供属性
weak var dataSource : WaterfallLayoutDataSource?
// MARK: 私有属性
fileprivate lazy var attrsArray : [UICollectionViewLayoutAttributes] = [UICollectionViewLayoutAttributes]()
fileprivate var totalHeights : CGFloat = 0
fileprivate lazy var colHeights : [CGFloat] = {
let cols = self.dataSource?.numberOfColsInWaterfallLayout?(self) ?? 2
var colHeights = Array(repeating: self.sectionInset.top, count: cols)
return colHeights
}()
fileprivate var maxH : CGFloat = 0
fileprivate var startIndex = 0
}
extension WaterfallLayout {
override func prepare() {
super.prepare()
// 1.获取item个数
let itemCount = collectionView!.numberOfItems(inSection: 0)
// 2.获得列数
let cols = dataSource?.numberOfColsInWaterfallLayout?(self) ?? 2
// 3.计算Item的宽度
let itemW = (collectionView!.bounds.width - self.sectionInset.left - self.sectionInset.right - self.minimumInteritemSpacing) / CGFloat(cols)
// 4.计算所有的item属性
for i in startIndex..<itemCount {
// 4.1.设置每一个Item位置相关的属性
let indexPath = IndexPath(item: i, section: 0)
// 4.2.根据位置创建Attributes属性
let attrs = UICollectionViewLayoutAttributes(forCellWith: indexPath)
// 4.3.随机一个高度
guard let height = dataSource?.waterfallLayout(self, indexPath: indexPath) else {
fatalError("请设置数据源, 并实现对应的数据源方法")
}
// 4.4.取出最小列的位置
var minH = colHeights.min()!
let index = colHeights.index(of: minH)!
minH = minH + height + minimumLineSpacing
colHeights[index] = minH
// 4.5.设置item属性
attrs.frame = CGRect(x: self.sectionInset.left + (self.minimumInteritemSpacing + itemW) * CGFloat(index), y: minH - height - self.minimumLineSpacing, width: itemW, height: height)
attrsArray.append(attrs)
}
// 5.记录最大值
maxH = colHeights.max()!
// 6.给startIndex重新赋值
startIndex = itemCount
}
}
extension WaterfallLayout {
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
return attrsArray
}
override var collectionViewContentSize : CGSize {
return CGSize(width: 0, height: maxH + sectionInset.bottom - minimumLineSpacing)
}
}
|
mit
|
c534c6fc98c789267e8038e1a0a0fef5
| 33.206897 | 191 | 0.628696 | 4.65 | false | false | false | false |
steve-holmes/music-app-2
|
MusicApp/Modules/Singer/SingerDetailAction.swift
|
1
|
2729
|
//
// SingerDetailAction.swift
// MusicApp
//
// Created by Hưng Đỗ on 6/21/17.
// Copyright © 2017 HungDo. All rights reserved.
//
import RxSwift
import Action
protocol SingerDetailAction {
var store: SingerDetailStore { get }
var onLoad: Action<Void, SingerDetailInfo> { get }
func onSingerDetailStateChange() -> Action<SingerDetailState, Void>
var onSongDidSelect: Action<Song, Void> { get }
var onPlaylistDidSelect: Action<(Playlist, UIViewController), Void> { get }
var onVideoDidSelect: Action<(Video, UIViewController), Void> { get }
var onContextMenuOpen: Action<(Song, UIViewController), Void> { get }
}
class MASingerDetailAction: SingerDetailAction {
let store: SingerDetailStore
let service: SingerDetailService
init(store: SingerDetailStore, service: SingerDetailService) {
self.store = store
self.service = service
}
lazy var onLoad: Action<Void, SingerDetailInfo> = {
return Action { [weak self] _ in
guard let this = self else { return .empty() }
return this.service.getSinger(this.store.info.value)
.do(onNext: { detailInfo in
this.store.songs.value = detailInfo.songs
this.store.playlists.value = detailInfo.playlists
this.store.videos.value = detailInfo.videos
this.store.state.value = .song
})
}
}()
func onSingerDetailStateChange() -> Action<SingerDetailState, Void> {
return Action { [weak self] state in
self?.store.state.value = state
return Observable.empty()
}
}
lazy var onSongDidSelect: Action<Song, Void> = {
return Action { [weak self] song in
self?.service.play(song) ?? .empty()
}
}()
lazy var onPlaylistDidSelect: Action<(Playlist, UIViewController), Void> = {
return Action { [weak self] segueInfo in
let (playlist, controller) = segueInfo
return self?.service.presentPlaylist(playlist, in: controller) ?? .empty()
}
}()
lazy var onVideoDidSelect: Action<(Video, UIViewController), Void> = {
return Action { [weak self] info in
let (video, controller) = info
return self?.service.presentVideo(video, in: controller) ?? .empty()
}
}()
lazy var onContextMenuOpen: Action<(Song, UIViewController), Void> = {
return Action { [weak self] segueInfo in
let (song, controller) = segueInfo
return self?.service.openContextMenu(song, in: controller) ?? .empty()
}
}()
}
|
mit
|
7425f84e8cd455f6038223ac7e08397c
| 31.047059 | 86 | 0.603157 | 4.316957 | false | false | false | false |
SwiftyVK/SwiftyVK
|
Library/Tests/LongPollTests.swift
|
2
|
11656
|
import Foundation
import XCTest
@testable import SwiftyVK
final class LongPollTests: XCTestCase {
func test_callOnConnected_onConnected() {
// Given
let expectation = self.expectation(description: "")
let context = makeContext(
onConnected: { expectation.fulfill() },
onDisconnected: { XCTFail("Unexpected result") }
)
context.session.state = .authorized
context.connectionObserver.onSubscribe = { _, callbacks in
callbacks.onConnect()
}
// When
context.longPoll.start { _ in }
// Then
waitForExpectations(timeout: 5)
}
func test_callOnDisconnected_onDisconnected() {
// Given
let expectation = self.expectation(description: "")
let context = makeContext(
onDisconnected: { expectation.fulfill() }
)
context.session.state = .authorized
context.connectionObserver.onSubscribe = { _, callbacks in
callbacks.onConnect()
DispatchQueue.global().async {
callbacks.onDisconnect()
}
}
// When
context.longPoll.start { _ in }
// Then
waitForExpectations(timeout: 5)
}
//
func test_handleUpdates_whenStarted() {
// Given
guard let longPollServerData = JsonReader.read("longPoll.getServer.success") else { return }
guard let longPollServerResponseData = Response(longPollServerData).data else {
return XCTFail("response not parsed")
}
guard
let data = JsonReader.read("longPoll.updates"),
let json: [Any] = data.toJson()?.array("updates") else {
return XCTFail()
}
let updates = json.compactMap { JSON(value: $0) } .dropFirst().toArray()
let expectation = self.expectation(description: "")
let context = makeContext()
context.session.state = .authorized
context.connectionObserver.onSubscribe = { _, callbacks in
callbacks.onConnect()
}
context.operationMaker.onMake = { _, data in
let operation = LongPollTaskMock()
operation.onMain = {
data.onResponse(updates)
}
return operation
}
context.session.onSend = { method in
try? method.toRequest().callbacks.onSuccess?(longPollServerResponseData)
}
// When
context.longPoll.start { events in
if case .type114? = events.last {
expectation.fulfill()
}
else {
XCTFail("Unexpected events: \(events)")
}
}
// Then
waitForExpectations(timeout: 5)
}
func test_notHandleUpdates_whenStopped() {
// Given
guard let longPollServerData = JsonReader.read("longPoll.getServer.success") else { return }
guard let longPollServerResponseData = Response(longPollServerData).data else {
return XCTFail("response not parsed")
}
let expectation = self.expectation(description: "")
expectation.isInverted = true
let context = makeContext()
context.session.state = .authorized
context.connectionObserver.onSubscribe = { _, callbacks in
callbacks.onConnect()
}
context.operationMaker.onMake = { _, data in
let operation = LongPollTaskMock()
operation.onMain = {
data.onResponse([])
}
return operation
}
context.session.onSend = { method in
try? method.toRequest().callbacks.onSuccess?(longPollServerResponseData)
}
// When
context.longPoll.start { events in
if events.first?.data != nil {
XCTFail("Unexpected events: \(events)")
}
}
context.longPoll.stop()
// Then
waitForExpectations(timeout: 5)
}
func test_restartingUpdate_whenConnectionInfoLost() {
// Given
guard let longPollServerData = JsonReader.read("longPoll.getServer.success") else { return }
guard let longPollServerResponseData = Response(longPollServerData).data else {
return XCTFail("response not parsed")
}
let expectation = self.expectation(description: "")
let context = makeContext()
var getInfoCallCount = 0
context.session.state = .authorized
context.connectionObserver.onSubscribe = { _, callbacks in
callbacks.onConnect()
}
context.operationMaker.onMake = { _, data in
let operation = LongPollTaskMock()
operation.onMain = {
if getInfoCallCount == 1 {
data.onError(.connectionInfoLost)
} else {
data.onResponse([])
}
}
return operation
}
context.session.onSend = { method in
getInfoCallCount += 1
try? method.toRequest().callbacks.onSuccess?(longPollServerResponseData)
}
// When
context.longPoll.start { events in
if events.isEmpty {
expectation.fulfill()
}
else {
XCTFail("Unexpected events: \(events)")
}
}
// Then
waitForExpectations(timeout: 5)
XCTAssertEqual(getInfoCallCount, 2)
}
func test_restartingUpdate_whenHistoryMayBeLost() {
// Given
guard let longPollServerData = JsonReader.read("longPoll.getServer.success") else { return }
guard let longPollServerResponseData = Response(longPollServerData).data else {
return XCTFail("response not parsed")
}
let expectation = self.expectation(description: "")
let context = makeContext()
var taskCount = 0
context.session.state = .authorized
context.connectionObserver.onSubscribe = { _, callbacks in
callbacks.onConnect()
}
context.operationMaker.onMake = { _, data in
let operation = LongPollTaskMock()
operation.onMain = {
taskCount += 1
if taskCount == 1 {
data.onError(.historyMayBeLost)
operation.onMain?()
} else {
data.onResponse([])
}
}
return operation
}
context.session.onSend = { method in
try? method.toRequest().callbacks.onSuccess?(longPollServerResponseData)
}
// When
context.longPoll.start { events in
if taskCount == 1 {
guard case .historyMayBeLost? = events.first else {
return XCTFail("Unexpected event: \(String(describing: events.first))")
}
} else if events.isEmpty {
expectation.fulfill()
}
else {
XCTFail("Unexpected events: \(events)")
}
}
// Then
waitForExpectations(timeout: 5)
XCTAssertEqual(taskCount, 2)
}
func test_restartingUpdate_whenUnexpectedError() {
// Given
guard let longPollServerData = JsonReader.read("longPoll.getServer.success") else { return }
guard let longPollServerResponseData = Response(longPollServerData).data else {
return XCTFail("response not parsed")
}
let expectation = self.expectation(description: "")
let context = makeContext()
var taskCount = 0
context.session.state = .authorized
context.connectionObserver.onSubscribe = { _, callbacks in
callbacks.onConnect()
}
context.operationMaker.onMake = { _, data in
let operation = LongPollTaskMock()
operation.onMain = {
taskCount += 1
if taskCount == 1 {
data.onError(.unknown)
} else {
data.onResponse([])
}
}
return operation
}
context.session.onSend = { method in
try? method.toRequest().callbacks.onSuccess?(longPollServerResponseData)
}
// When
context.longPoll.start { events in
if taskCount == 1 {
guard case .forcedStop? = events.first else {
return XCTFail("Unexpected events: \(events)")
}
expectation.fulfill()
}
else {
XCTFail("Unexpected events: \(events)")
}
}
// Then
waitForExpectations(timeout: 5)
XCTAssertEqual(taskCount, 1)
}
func test_restartingUpdate_whenGetInfoFailing() {
// Given
guard let longPollServerData = JsonReader.read("longPoll.getServer.success") else { return }
guard let longPollServerResponseData = Response(longPollServerData).data else {
return XCTFail("response not parsed")
}
let expectation = self.expectation(description: "")
let context = makeContext()
var getInfoCallCount = 0
context.session.state = .authorized
context.connectionObserver.onSubscribe = { _, callbacks in
callbacks.onConnect()
}
context.operationMaker.onMake = { _, data in
let operation = LongPollTaskMock()
operation.onMain = {
data.onResponse([])
}
return operation
}
context.session.onSend = { method in
getInfoCallCount += 1
if getInfoCallCount == 1 {
method.toRequest().callbacks.onError?(.unexpectedResponse)
}
else {
try? method.toRequest().callbacks.onSuccess?(longPollServerResponseData)
}
}
// When
context.longPoll.start { events in
if events.isEmpty {
expectation.fulfill()
}
else {
XCTFail("Unexpected events: \(events)")
}
}
// Then
waitForExpectations(timeout: 5)
XCTAssertEqual(getInfoCallCount, 2)
}
}
private func makeContext(
onConnected: (() -> ())? = nil,
onDisconnected: (() -> ())? = nil
) -> (
session: SessionMock,
longPoll: LongPollImpl,
operationMaker: LongPollTaskMakerMock,
connectionObserver: ConnectionObserverMock
) {
let session = SessionMock()
let operationMaker = LongPollTaskMakerMock()
let connectionObserver = ConnectionObserverMock()
let longPoll = LongPollImpl(
session: session,
operationMaker: operationMaker,
connectionObserver: connectionObserver,
getInfoDelay: 0.1,
onConnected: onConnected,
onDisconnected: onDisconnected
)
return (session, longPoll, operationMaker, connectionObserver)
}
|
mit
|
62994ccba98149a461fb4f7b847852af
| 29.673684 | 100 | 0.532172 | 5.444185 | false | false | false | false |
ngageoint/mage-ios
|
Mage/FeatureSummaryView.swift
|
1
|
4332
|
//
// FeatureSummaryView.swift
// MAGE
//
// Created by Daniel Barela on 8/12/21.
// Copyright © 2021 National Geospatial Intelligence Agency. All rights reserved.
//
import Foundation
import PureLayout
import Kingfisher
class FeatureItem: NSObject {
init(annotation: StaticPointAnnotation) {
self.featureDetail = StaticLayer.featureDescription(feature: annotation.feature)
self.coordinate = annotation.coordinate
self.featureTitle = StaticLayer.featureName(feature: annotation.feature)
self.featureDate = StaticLayer.featureTimestamp(feature: annotation.feature)
self.layerName = annotation.layerName
if let iconUrl = annotation.iconUrl {
if iconUrl.hasPrefix("http") {
self.iconURL = URL(string: iconUrl)
} else {
self.iconURL = URL(fileURLWithPath: "\(FeatureItem.getDocumentsDirectory())/\(iconUrl)")
}
}
}
init(featureId: Int = 0, featureDetail: String? = nil, coordinate: CLLocationCoordinate2D = kCLLocationCoordinate2DInvalid, featureTitle: String? = nil, layerName: String? = nil, iconURL: URL? = nil, images: [UIImage]? = nil) {
self.featureId = featureId
self.featureDetail = featureDetail
self.coordinate = coordinate
self.featureTitle = featureTitle
self.iconURL = iconURL
self.images = images
self.layerName = layerName;
}
var featureId: Int = 0;
var featureDetail: String?;
var coordinate: CLLocationCoordinate2D = kCLLocationCoordinate2DInvalid;
var featureTitle: String?;
var iconURL: URL?;
var images: [UIImage]?;
var layerName: String?
var featureDate: Date?
static func getDocumentsDirectory() -> String {
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory = paths[0]
return documentsDirectory as String
}
}
class FeatureSummaryView : CommonSummaryView<FeatureItem, FeatureActionsDelegate> {
private var didSetUpConstraints = false;
private lazy var secondaryLabelIcon: UIImageView = {
let secondaryLabelIcon = UIImageView(image: UIImage(systemName: "square.stack.3d.up"));
secondaryLabelIcon.tintColor = secondaryField.textColor
secondaryLabelIcon.autoSetDimensions(to: CGSize(width: 14, height: 14));
return secondaryLabelIcon;
}();
required init(coder aDecoder: NSCoder) {
fatalError("This class does not support NSCoding")
}
override init(imageOverride: UIImage? = nil, hideImage: Bool = false) {
super.init(imageOverride: imageOverride, hideImage: hideImage);
isUserInteractionEnabled = false;
}
override func populate(item: FeatureItem, actionsDelegate: FeatureActionsDelegate? = nil) {
let processor = DownsamplingImageProcessor(size: CGSize(width: 40, height: 40))
itemImage.tintColor = UIColor(red: 0.6, green: 0.6, blue: 0.6, alpha: 1.0);
let image = UIImage(named: "observations");
let iconUrl = item.iconURL;
itemImage.kf.indicatorType = .activity
itemImage.kf.setImage(
with: iconUrl,
placeholder: image,
options: [
.requestModifier(ImageCacheProvider.shared.accessTokenModifier),
.processor(processor),
.scaleFactor(UIScreen.main.scale),
.transition(.fade(1)),
.cacheOriginalImage
])
{
result in
switch result {
case .success(_):
self.setNeedsLayout()
case .failure(let error):
print("Job failed: \(error.localizedDescription)")
}
}
primaryField.text = item.featureTitle ?? " ";
if let featureDate: NSDate = item.featureDate as NSDate? {
timestamp.text = featureDate.formattedDisplay().uppercased().replacingOccurrences(of: " ", with: "\u{00a0}")
}
secondaryField.text = item.layerName;
if (secondaryLabelIcon.superview == nil) {
secondaryContainer.insertArrangedSubview(secondaryLabelIcon, at: 0);
}
// secondaryField.text = item.featureDetail;
}
}
|
apache-2.0
|
b94b63a141f3d663d5507fbcfaae7020
| 37.669643 | 231 | 0.641653 | 4.916005 | false | false | false | false |
OneBusAway/onebusaway-iphone
|
Carthage/Checkouts/SwiftEntryKit/Source/Model/EntryAttributes/EKAttributes+Precedence.swift
|
3
|
5388
|
//
// EKAttributes+Precedence.swift
// SwiftEntryKit
//
// Created by Daniel Huri on 4/29/18.
//
import Foundation
fileprivate extension Int {
var isValidDisplayPriority: Bool {
return self >= EKAttributes.Precedence.Priority.minRawValue && self <= EKAttributes.Precedence.Priority.maxRawValue
}
}
public extension EKAttributes {
/**
Describes the manner on which the entry is pushed and displayed.
See the various values of more explanation.
*/
enum Precedence {
/**
The display priority of the entry - Determines whether is can be overriden by other entries.
Must be in range [0...1000]
*/
public struct Priority: Hashable, Equatable, RawRepresentable, Comparable {
public var rawValue: Int
public var hashValue: Int {
return rawValue
}
public init(_ rawValue: Int) {
assert(rawValue.isValidDisplayPriority, "Display Priority must be in range [\(Priority.minRawValue)...\(Priority.maxRawValue)]")
self.rawValue = rawValue
}
public init(rawValue: Int) {
assert(rawValue.isValidDisplayPriority, "Display Priority must be in range [\(Priority.minRawValue)...\(Priority.maxRawValue)]")
self.rawValue = rawValue
}
public static func == (lhs: Priority, rhs: Priority) -> Bool {
return lhs.rawValue == rhs.rawValue
}
public static func < (lhs: Priority, rhs: Priority) -> Bool {
return lhs.rawValue < rhs.rawValue
}
}
/**
Describes the queueing heoristic of entries.
*/
public enum QueueingHeuristic {
/** Determines the heuristic which the entry-queue is based on */
public static var value = QueueingHeuristic.priority
/** Chronological - FIFO */
case chronological
/** Ordered by priority */
case priority
/** Returns the caching heuristics mechanism that determines the priority in queue */
var heuristic: EntryCachingHeuristic {
switch self {
case .chronological:
return EKEntryChronologicalQueue()
case .priority:
return EKEntryPriorityQueue()
}
}
}
/**
Describes an *overriding* behavior for a new entry.
- In case no previous entry is currently presented, display the new entry.
- In case there is an entry that is currently presented - override it using the new entry. Also optionally drop all previously enqueued entries.
*/
case override(priority: Priority, dropEnqueuedEntries: Bool)
/**
Describes a FIFO behavior for an entry presentation.
- In case no previous entry is currently presented, display the new entry.
- In case there is an entry that is currently presented - enqueue the new entry, an present it just after the previous one is dismissed.
*/
case enqueue(priority: Priority)
var isEnqueue: Bool {
switch self {
case .enqueue:
return true
default:
return false
}
}
/** Setter / Getter for the display priority */
public var priority: Priority {
set {
switch self {
case .enqueue(priority: _):
self = .enqueue(priority: newValue)
case .override(priority: _, dropEnqueuedEntries: let dropEnqueuedEntries):
self = .override(priority: newValue, dropEnqueuedEntries: dropEnqueuedEntries)
}
}
get {
switch self {
case .enqueue(priority: let priority):
return priority
case .override(priority: let priority, dropEnqueuedEntries: _):
return priority
}
}
}
}
}
/** High priority entries can be overriden by other equal or higher priority entries only.
Entries are ignored as a higher priority entry is being displayed.
High priority entry overrides any other entry including another equal priority one.
You can you on of the values (.max, high, normal, low, min) and also set your own values. */
public extension EKAttributes.Precedence.Priority {
static let maxRawValue = 1000
static let highRawValue = 750
static let normalRawValue = 500
static let lowRawValue = 250
static let minRawValue = 0
/** Max - the highest possible priority of an entry. Can override only entries with *max* priority */
static let max = EKAttributes.Precedence.Priority(rawValue: maxRawValue)
static let high = EKAttributes.Precedence.Priority(rawValue: highRawValue)
static let normal = EKAttributes.Precedence.Priority(rawValue: normalRawValue)
static let low = EKAttributes.Precedence.Priority(rawValue: lowRawValue)
static let min = EKAttributes.Precedence.Priority(rawValue: minRawValue)
}
|
apache-2.0
|
4ea5f0455fd199c90883069823c44eb3
| 36.943662 | 153 | 0.587045 | 5.57764 | false | false | false | false |
strangeliu/firefox-ios
|
Client/Frontend/Browser/URLBarView.swift
|
4
|
31645
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import UIKit
import Shared
import SnapKit
private struct URLBarViewUX {
static let TextFieldBorderColor = UIColor(rgb: 0xBBBBBB)
static let TextFieldActiveBorderColor = UIColor(rgb: 0x4A90E2)
static let TextFieldContentInset = UIOffsetMake(9, 5)
static let LocationLeftPadding = 5
static let LocationHeight = 28
static let LocationContentOffset: CGFloat = 8
static let TextFieldCornerRadius: CGFloat = 3
static let TextFieldBorderWidth: CGFloat = 1
// offset from edge of tabs button
static let URLBarCurveOffset: CGFloat = 14
static let URLBarCurveOffsetLeft: CGFloat = -10
// buffer so we dont see edges when animation overshoots with spring
static let URLBarCurveBounceBuffer: CGFloat = 8
static let TabsButtonRotationOffset: CGFloat = 1.5
static let TabsButtonHeight: CGFloat = 18.0
static let ToolbarButtonInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
static func backgroundColorWithAlpha(alpha: CGFloat) -> UIColor {
return UIConstants.AppBackgroundColor.colorWithAlphaComponent(alpha)
}
}
protocol URLBarDelegate: class {
func urlBarDidPressTabs(urlBar: URLBarView)
func urlBarDidPressReaderMode(urlBar: URLBarView)
/// - returns: whether the long-press was handled by the delegate; i.e. return `false` when the conditions for even starting handling long-press were not satisfied
func urlBarDidLongPressReaderMode(urlBar: URLBarView) -> Bool
func urlBarDidPressStop(urlBar: URLBarView)
func urlBarDidPressReload(urlBar: URLBarView)
func urlBarDidEnterOverlayMode(urlBar: URLBarView)
func urlBarDidLeaveOverlayMode(urlBar: URLBarView)
func urlBarDidLongPressLocation(urlBar: URLBarView)
func urlBarLocationAccessibilityActions(urlBar: URLBarView) -> [UIAccessibilityCustomAction]?
func urlBarDidPressScrollToTop(urlBar: URLBarView)
func urlBar(urlBar: URLBarView, didEnterText text: String)
func urlBar(urlBar: URLBarView, didSubmitText text: String)
}
class URLBarView: UIView {
weak var delegate: URLBarDelegate?
weak var browserToolbarDelegate: BrowserToolbarDelegate?
var helper: BrowserToolbarHelper?
var isTransitioning: Bool = false {
didSet {
if isTransitioning {
// Cancel any pending/in-progress animations related to the progress bar
self.progressBar.setProgress(1, animated: false)
self.progressBar.alpha = 0.0
}
}
}
var toolbarIsShowing = false
/// Overlay mode is the state where the lock/reader icons are hidden, the home panels are shown,
/// and the Cancel button is visible (allowing the user to leave overlay mode). Overlay mode
/// is *not* tied to the location text field's editing state; for instance, when selecting
/// a panel, the first responder will be resigned, yet the overlay mode UI is still active.
var inOverlayMode = false
lazy var locationView: BrowserLocationView = {
let locationView = BrowserLocationView()
locationView.translatesAutoresizingMaskIntoConstraints = false
locationView.readerModeState = ReaderModeState.Unavailable
locationView.delegate = self
return locationView
}()
private lazy var locationTextField: ToolbarTextField = {
let locationTextField = ToolbarTextField()
locationTextField.translatesAutoresizingMaskIntoConstraints = false
locationTextField.autocompleteDelegate = self
locationTextField.keyboardType = UIKeyboardType.WebSearch
locationTextField.autocorrectionType = UITextAutocorrectionType.No
locationTextField.autocapitalizationType = UITextAutocapitalizationType.None
locationTextField.returnKeyType = UIReturnKeyType.Go
locationTextField.clearButtonMode = UITextFieldViewMode.WhileEditing
locationTextField.backgroundColor = UIColor.whiteColor()
locationTextField.font = UIConstants.DefaultMediumFont
locationTextField.accessibilityIdentifier = "address"
locationTextField.accessibilityLabel = NSLocalizedString("Address and Search", comment: "Accessibility label for address and search field, both words (Address, Search) are therefore nouns.")
locationTextField.attributedPlaceholder = self.locationView.placeholder
return locationTextField
}()
private lazy var locationContainer: UIView = {
let locationContainer = UIView()
locationContainer.translatesAutoresizingMaskIntoConstraints = false
// Enable clipping to apply the rounded edges to subviews.
locationContainer.clipsToBounds = true
locationContainer.layer.borderColor = URLBarViewUX.TextFieldBorderColor.CGColor
locationContainer.layer.cornerRadius = URLBarViewUX.TextFieldCornerRadius
locationContainer.layer.borderWidth = URLBarViewUX.TextFieldBorderWidth
return locationContainer
}()
private lazy var tabsButton: UIButton = {
let tabsButton = InsetButton()
tabsButton.translatesAutoresizingMaskIntoConstraints = false
tabsButton.setTitle("0", forState: UIControlState.Normal)
tabsButton.setTitleColor(URLBarViewUX.backgroundColorWithAlpha(1), forState: UIControlState.Normal)
tabsButton.titleLabel?.layer.backgroundColor = UIColor.whiteColor().CGColor
tabsButton.titleLabel?.layer.cornerRadius = 2
tabsButton.titleLabel?.font = UIConstants.DefaultSmallFontBold
tabsButton.titleLabel?.textAlignment = NSTextAlignment.Center
tabsButton.setContentHuggingPriority(1000, forAxis: UILayoutConstraintAxis.Horizontal)
tabsButton.setContentCompressionResistancePriority(1000, forAxis: UILayoutConstraintAxis.Horizontal)
tabsButton.addTarget(self, action: "SELdidClickAddTab", forControlEvents: UIControlEvents.TouchUpInside)
tabsButton.accessibilityLabel = NSLocalizedString("Show Tabs", comment: "Accessibility Label for the tabs button in the browser toolbar")
return tabsButton
}()
private lazy var progressBar: UIProgressView = {
let progressBar = UIProgressView()
progressBar.progressTintColor = UIColor(red:1, green:0.32, blue:0, alpha:1)
progressBar.alpha = 0
progressBar.hidden = true
return progressBar
}()
private lazy var cancelButton: UIButton = {
let cancelButton = InsetButton()
cancelButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
let cancelTitle = NSLocalizedString("Cancel", comment: "Button label to cancel entering a URL or search query")
cancelButton.setTitle(cancelTitle, forState: UIControlState.Normal)
cancelButton.titleLabel?.font = UIConstants.DefaultMediumFont
cancelButton.addTarget(self, action: "SELdidClickCancel", forControlEvents: UIControlEvents.TouchUpInside)
cancelButton.titleEdgeInsets = UIEdgeInsetsMake(10, 12, 10, 12)
cancelButton.setContentHuggingPriority(1000, forAxis: UILayoutConstraintAxis.Horizontal)
cancelButton.setContentCompressionResistancePriority(1000, forAxis: UILayoutConstraintAxis.Horizontal)
return cancelButton
}()
private lazy var curveShape: CurveView = { return CurveView() }()
private lazy var scrollToTopButton: UIButton = {
let button = UIButton()
button.addTarget(self, action: "SELtappedScrollToTopArea", forControlEvents: UIControlEvents.TouchUpInside)
return button
}()
lazy var shareButton: UIButton = { return UIButton() }()
lazy var bookmarkButton: UIButton = { return UIButton() }()
lazy var forwardButton: UIButton = { return UIButton() }()
lazy var backButton: UIButton = { return UIButton() }()
lazy var stopReloadButton: UIButton = { return UIButton() }()
lazy var actionButtons: [UIButton] = {
return [self.shareButton, self.bookmarkButton, self.forwardButton, self.backButton, self.stopReloadButton]
}()
// Used to temporarily store the cloned button so we can respond to layout changes during animation
private weak var clonedTabsButton: InsetButton?
private var rightBarConstraint: Constraint?
private let defaultRightOffset: CGFloat = URLBarViewUX.URLBarCurveOffset - URLBarViewUX.URLBarCurveBounceBuffer
var currentURL: NSURL? {
get {
return locationView.url
}
set(newURL) {
locationView.url = newURL
}
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
backgroundColor = URLBarViewUX.backgroundColorWithAlpha(0)
addSubview(curveShape)
addSubview(scrollToTopButton)
addSubview(progressBar)
addSubview(tabsButton)
addSubview(cancelButton)
addSubview(shareButton)
addSubview(bookmarkButton)
addSubview(forwardButton)
addSubview(backButton)
addSubview(stopReloadButton)
locationContainer.addSubview(locationView)
locationContainer.addSubview(locationTextField)
addSubview(locationContainer)
helper = BrowserToolbarHelper(toolbar: self)
setupConstraints()
// Make sure we hide any views that shouldn't be showing in non-overlay mode.
updateViewsForOverlayModeAndToolbarChanges()
self.locationTextField.hidden = !inOverlayMode
}
private func setupConstraints() {
scrollToTopButton.snp_makeConstraints { make in
make.top.equalTo(self)
make.left.right.equalTo(self.locationContainer)
}
progressBar.snp_makeConstraints { make in
make.top.equalTo(self.snp_bottom)
make.width.equalTo(self)
}
locationView.snp_makeConstraints { make in
make.edges.equalTo(self.locationContainer)
}
cancelButton.snp_makeConstraints { make in
make.centerY.equalTo(self.locationContainer)
make.trailing.equalTo(self)
}
tabsButton.titleLabel?.snp_makeConstraints { make in
make.size.equalTo(URLBarViewUX.TabsButtonHeight)
}
tabsButton.snp_makeConstraints { make in
make.centerY.equalTo(self.locationContainer)
make.trailing.equalTo(self)
make.width.height.equalTo(UIConstants.ToolbarHeight)
}
curveShape.snp_makeConstraints { make in
make.top.left.bottom.equalTo(self)
self.rightBarConstraint = make.right.equalTo(self).constraint
self.rightBarConstraint?.updateOffset(defaultRightOffset)
}
locationTextField.snp_makeConstraints { make in
make.edges.equalTo(self.locationView.urlTextField)
}
backButton.snp_makeConstraints { make in
make.left.centerY.equalTo(self)
make.size.equalTo(UIConstants.ToolbarHeight)
}
forwardButton.snp_makeConstraints { make in
make.left.equalTo(self.backButton.snp_right)
make.centerY.equalTo(self)
make.size.equalTo(backButton)
}
stopReloadButton.snp_makeConstraints { make in
make.left.equalTo(self.forwardButton.snp_right)
make.centerY.equalTo(self)
make.size.equalTo(backButton)
}
shareButton.snp_makeConstraints { make in
make.right.equalTo(self.bookmarkButton.snp_left)
make.centerY.equalTo(self)
make.size.equalTo(backButton)
}
bookmarkButton.snp_makeConstraints { make in
make.right.equalTo(self.tabsButton.snp_left).offset(URLBarViewUX.URLBarCurveOffsetLeft)
make.centerY.equalTo(self)
make.size.equalTo(backButton)
}
}
override func updateConstraints() {
super.updateConstraints()
if inOverlayMode {
// In overlay mode, we always show the location view full width
self.locationContainer.snp_remakeConstraints { make in
make.leading.equalTo(self).offset(URLBarViewUX.LocationLeftPadding)
make.trailing.equalTo(self.cancelButton.snp_leading)
make.height.equalTo(URLBarViewUX.LocationHeight)
make.centerY.equalTo(self)
}
} else {
self.locationContainer.snp_remakeConstraints { make in
if self.toolbarIsShowing {
// If we are showing a toolbar, show the text field next to the forward button
make.leading.equalTo(self.stopReloadButton.snp_trailing)
make.trailing.equalTo(self.shareButton.snp_leading)
} else {
// Otherwise, left align the location view
make.leading.equalTo(self).offset(URLBarViewUX.LocationLeftPadding)
make.trailing.equalTo(self.tabsButton.snp_leading).offset(-14)
}
make.height.equalTo(URLBarViewUX.LocationHeight)
make.centerY.equalTo(self)
}
}
}
// Ideally we'd split this implementation in two, one URLBarView with a toolbar and one without
// However, switching views dynamically at runtime is a difficult. For now, we just use one view
// that can show in either mode.
func setShowToolbar(shouldShow: Bool) {
toolbarIsShowing = shouldShow
setNeedsUpdateConstraints()
// when we transition from portrait to landscape, calling this here causes
// the constraints to be calculated too early and there are constraint errors
if !toolbarIsShowing {
updateConstraintsIfNeeded()
}
updateViewsForOverlayModeAndToolbarChanges()
}
func updateAlphaForSubviews(alpha: CGFloat) {
self.tabsButton.alpha = alpha
self.locationContainer.alpha = alpha
self.backgroundColor = URLBarViewUX.backgroundColorWithAlpha(1 - alpha)
}
func updateTabCount(count: Int) {
updateTabCount(count, animated: true)
}
func updateTabCount(count: Int, animated: Bool) {
if let _ = self.clonedTabsButton {
self.clonedTabsButton?.layer.removeAllAnimations()
self.clonedTabsButton?.removeFromSuperview()
self.tabsButton.layer.removeAllAnimations()
}
// make a 'clone' of the tabs button
let newTabsButton = InsetButton()
self.clonedTabsButton = newTabsButton
newTabsButton.addTarget(self, action: "SELdidClickAddTab", forControlEvents: UIControlEvents.TouchUpInside)
newTabsButton.setTitleColor(UIConstants.AppBackgroundColor, forState: UIControlState.Normal)
newTabsButton.titleLabel?.layer.backgroundColor = UIColor.whiteColor().CGColor
newTabsButton.titleLabel?.layer.cornerRadius = 2
newTabsButton.titleLabel?.font = UIConstants.DefaultSmallFontBold
newTabsButton.titleLabel?.textAlignment = NSTextAlignment.Center
newTabsButton.setTitle(count.description, forState: .Normal)
addSubview(newTabsButton)
newTabsButton.titleLabel?.snp_makeConstraints { make in
make.size.equalTo(URLBarViewUX.TabsButtonHeight)
}
newTabsButton.snp_makeConstraints { make in
make.centerY.equalTo(self.locationContainer)
make.trailing.equalTo(self)
make.size.equalTo(UIConstants.ToolbarHeight)
}
newTabsButton.frame = tabsButton.frame
// Instead of changing the anchorPoint of the CALayer, lets alter the rotation matrix math to be
// a rotation around a non-origin point
if let labelFrame = newTabsButton.titleLabel?.frame {
let halfTitleHeight = CGRectGetHeight(labelFrame) / 2
var newFlipTransform = CATransform3DIdentity
newFlipTransform = CATransform3DTranslate(newFlipTransform, 0, halfTitleHeight, 0)
newFlipTransform.m34 = -1.0 / 200.0 // add some perspective
newFlipTransform = CATransform3DRotate(newFlipTransform, CGFloat(-M_PI_2), 1.0, 0.0, 0.0)
newTabsButton.titleLabel?.layer.transform = newFlipTransform
var oldFlipTransform = CATransform3DIdentity
oldFlipTransform = CATransform3DTranslate(oldFlipTransform, 0, halfTitleHeight, 0)
oldFlipTransform.m34 = -1.0 / 200.0 // add some perspective
oldFlipTransform = CATransform3DRotate(oldFlipTransform, CGFloat(M_PI_2), 1.0, 0.0, 0.0)
let animate = {
newTabsButton.titleLabel?.layer.transform = CATransform3DIdentity
self.tabsButton.titleLabel?.layer.transform = oldFlipTransform
self.tabsButton.titleLabel?.layer.opacity = 0
}
let completion: (Bool) -> Void = { finished in
// remove the clone and setup the actual tab button
newTabsButton.removeFromSuperview()
self.tabsButton.titleLabel?.layer.opacity = 1
self.tabsButton.titleLabel?.layer.transform = CATransform3DIdentity
self.tabsButton.accessibilityLabel = NSLocalizedString("Show Tabs", comment: "Accessibility label for the tabs button in the (top) browser toolbar")
if finished {
self.tabsButton.setTitle(count.description, forState: UIControlState.Normal)
self.tabsButton.accessibilityValue = count.description
}
}
if animated {
UIView.animateWithDuration(1.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: animate, completion: completion)
} else {
completion(true)
}
}
}
func updateProgressBar(progress: Float) {
if progress == 1.0 {
self.progressBar.setProgress(progress, animated: !isTransitioning)
UIView.animateWithDuration(1.5, animations: {
self.progressBar.alpha = 0.0
}, completion: { finished in
if finished {
self.progressBar.setProgress(0.0, animated: false)
}
})
} else {
if self.progressBar.alpha < 1.0 {
self.progressBar.alpha = 1.0
}
self.progressBar.setProgress(progress, animated: (progress > progressBar.progress) && !isTransitioning)
}
}
func updateReaderModeState(state: ReaderModeState) {
locationView.readerModeState = state
}
func setAutocompleteSuggestion(suggestion: String?) {
locationTextField.setAutocompleteSuggestion(suggestion)
}
func enterOverlayMode(locationText: String?, pasted: Bool) {
// Show the overlay mode UI, which includes hiding the locationView and replacing it
// with the editable locationTextField.
animateToOverlayState(overlayMode: true)
delegate?.urlBarDidEnterOverlayMode(self)
// Bug 1193755 Workaround - Calling becomeFirstResponder before the animation happens
// won't take the initial frame of the label into consideration, which makes the label
// look squished at the start of the animation and expand to be correct. As a workaround,
// we becomeFirstResponder as the next event on UI thread, so the animation starts before we
// set a first responder.
if pasted {
// Clear any existing text, focus the field, then set the actual pasted text.
// This avoids highlighting all of the text.
self.locationTextField.text = ""
dispatch_async(dispatch_get_main_queue()) {
self.locationTextField.becomeFirstResponder()
self.locationTextField.text = locationText
}
} else {
// Copy the current URL to the editable text field, then activate it.
self.locationTextField.text = locationText
dispatch_async(dispatch_get_main_queue()) {
self.locationTextField.becomeFirstResponder()
}
}
}
func leaveOverlayMode(didCancel cancel: Bool = false) {
locationTextField.resignFirstResponder()
animateToOverlayState(overlayMode: false, didCancel: cancel)
delegate?.urlBarDidLeaveOverlayMode(self)
}
func prepareOverlayAnimation() {
// Make sure everything is showing during the transition (we'll hide it afterwards).
self.bringSubviewToFront(self.locationContainer)
self.cancelButton.hidden = false
self.progressBar.hidden = false
self.shareButton.hidden = !self.toolbarIsShowing
self.bookmarkButton.hidden = !self.toolbarIsShowing
self.forwardButton.hidden = !self.toolbarIsShowing
self.backButton.hidden = !self.toolbarIsShowing
self.stopReloadButton.hidden = !self.toolbarIsShowing
}
func transitionToOverlay(didCancel: Bool = false) {
self.cancelButton.alpha = inOverlayMode ? 1 : 0
self.progressBar.alpha = inOverlayMode || didCancel ? 0 : 1
self.shareButton.alpha = inOverlayMode ? 0 : 1
self.bookmarkButton.alpha = inOverlayMode ? 0 : 1
self.forwardButton.alpha = inOverlayMode ? 0 : 1
self.backButton.alpha = inOverlayMode ? 0 : 1
self.stopReloadButton.alpha = inOverlayMode ? 0 : 1
let borderColor = inOverlayMode ? URLBarViewUX.TextFieldActiveBorderColor : URLBarViewUX.TextFieldBorderColor
locationContainer.layer.borderColor = borderColor.CGColor
if inOverlayMode {
self.cancelButton.transform = CGAffineTransformIdentity
let tabsButtonTransform = CGAffineTransformMakeTranslation(self.tabsButton.frame.width + URLBarViewUX.URLBarCurveOffset, 0)
self.tabsButton.transform = tabsButtonTransform
self.clonedTabsButton?.transform = tabsButtonTransform
self.rightBarConstraint?.updateOffset(URLBarViewUX.URLBarCurveOffset + URLBarViewUX.URLBarCurveBounceBuffer + tabsButton.frame.width)
// Make the editable text field span the entire URL bar, covering the lock and reader icons.
self.locationTextField.snp_remakeConstraints { make in
make.leading.equalTo(self.locationContainer).offset(URLBarViewUX.LocationContentOffset)
make.top.bottom.trailing.equalTo(self.locationContainer)
}
} else {
self.tabsButton.transform = CGAffineTransformIdentity
self.clonedTabsButton?.transform = CGAffineTransformIdentity
self.cancelButton.transform = CGAffineTransformMakeTranslation(self.cancelButton.frame.width, 0)
self.rightBarConstraint?.updateOffset(defaultRightOffset)
// Shrink the editable text field back to the size of the location view before hiding it.
self.locationTextField.snp_remakeConstraints { make in
make.edges.equalTo(self.locationView.urlTextField)
}
}
}
func updateViewsForOverlayModeAndToolbarChanges() {
self.cancelButton.hidden = !inOverlayMode
self.progressBar.hidden = inOverlayMode
self.shareButton.hidden = !self.toolbarIsShowing || inOverlayMode
self.bookmarkButton.hidden = !self.toolbarIsShowing || inOverlayMode
self.forwardButton.hidden = !self.toolbarIsShowing || inOverlayMode
self.backButton.hidden = !self.toolbarIsShowing || inOverlayMode
self.stopReloadButton.hidden = !self.toolbarIsShowing || inOverlayMode
}
func animateToOverlayState(overlayMode overlay: Bool, didCancel cancel: Bool = false) {
prepareOverlayAnimation()
layoutIfNeeded()
inOverlayMode = overlay
locationView.urlTextField.hidden = inOverlayMode
locationTextField.hidden = !inOverlayMode
UIView.animateWithDuration(0.3, delay: 0.0, usingSpringWithDamping: 0.85, initialSpringVelocity: 0.0, options: [], animations: { _ in
self.transitionToOverlay(cancel)
self.setNeedsUpdateConstraints()
self.layoutIfNeeded()
}, completion: { _ in
self.updateViewsForOverlayModeAndToolbarChanges()
})
}
func SELdidClickAddTab() {
delegate?.urlBarDidPressTabs(self)
}
func SELdidClickCancel() {
leaveOverlayMode(didCancel: true)
}
func SELtappedScrollToTopArea() {
delegate?.urlBarDidPressScrollToTop(self)
}
}
extension URLBarView: BrowserToolbarProtocol {
func updateBackStatus(canGoBack: Bool) {
backButton.enabled = canGoBack
}
func updateForwardStatus(canGoForward: Bool) {
forwardButton.enabled = canGoForward
}
func updateBookmarkStatus(isBookmarked: Bool) {
bookmarkButton.selected = isBookmarked
}
func updateReloadStatus(isLoading: Bool) {
if isLoading {
stopReloadButton.setImage(helper?.ImageStop, forState: .Normal)
stopReloadButton.setImage(helper?.ImageStopPressed, forState: .Highlighted)
} else {
stopReloadButton.setImage(helper?.ImageReload, forState: .Normal)
stopReloadButton.setImage(helper?.ImageReloadPressed, forState: .Highlighted)
}
}
func updatePageStatus(isWebPage isWebPage: Bool) {
bookmarkButton.enabled = isWebPage
stopReloadButton.enabled = isWebPage
shareButton.enabled = isWebPage
}
override var accessibilityElements: [AnyObject]? {
get {
if inOverlayMode {
return [locationTextField, cancelButton]
} else {
if toolbarIsShowing {
return [backButton, forwardButton, stopReloadButton, locationView, shareButton, bookmarkButton, tabsButton, progressBar]
} else {
return [locationView, tabsButton, progressBar]
}
}
}
set {
super.accessibilityElements = newValue
}
}
}
extension URLBarView: BrowserLocationViewDelegate {
func browserLocationViewDidLongPressReaderMode(browserLocationView: BrowserLocationView) -> Bool {
return delegate?.urlBarDidLongPressReaderMode(self) ?? false
}
func browserLocationViewDidTapLocation(browserLocationView: BrowserLocationView) {
enterOverlayMode(locationView.url?.absoluteString, pasted: false)
}
func browserLocationViewDidLongPressLocation(browserLocationView: BrowserLocationView) {
delegate?.urlBarDidLongPressLocation(self)
}
func browserLocationViewDidTapReload(browserLocationView: BrowserLocationView) {
delegate?.urlBarDidPressReload(self)
}
func browserLocationViewDidTapStop(browserLocationView: BrowserLocationView) {
delegate?.urlBarDidPressStop(self)
}
func browserLocationViewDidTapReaderMode(browserLocationView: BrowserLocationView) {
delegate?.urlBarDidPressReaderMode(self)
}
func browserLocationViewLocationAccessibilityActions(browserLocationView: BrowserLocationView) -> [UIAccessibilityCustomAction]? {
return delegate?.urlBarLocationAccessibilityActions(self)
}
}
extension URLBarView: AutocompleteTextFieldDelegate {
func autocompleteTextFieldShouldReturn(autocompleteTextField: AutocompleteTextField) -> Bool {
guard let text = locationTextField.text else { return true }
delegate?.urlBar(self, didSubmitText: text)
return true
}
func autocompleteTextField(autocompleteTextField: AutocompleteTextField, didEnterText text: String) {
delegate?.urlBar(self, didEnterText: text)
}
func autocompleteTextFieldDidBeginEditing(autocompleteTextField: AutocompleteTextField) {
autocompleteTextField.highlightAll()
}
func autocompleteTextFieldShouldClear(autocompleteTextField: AutocompleteTextField) -> Bool {
delegate?.urlBar(self, didEnterText: "")
return true
}
}
/* Code for drawing the urlbar curve */
// Curve's aspect ratio
private let ASPECT_RATIO = 0.729
// Width multipliers
private let W_M1 = 0.343
private let W_M2 = 0.514
private let W_M3 = 0.49
private let W_M4 = 0.545
private let W_M5 = 0.723
// Height multipliers
private let H_M1 = 0.25
private let H_M2 = 0.5
private let H_M3 = 0.72
private let H_M4 = 0.961
/* Code for drawing the urlbar curve */
private class CurveView: UIView {
private lazy var leftCurvePath: UIBezierPath = {
var leftArc = UIBezierPath(arcCenter: CGPoint(x: 5, y: 5), radius: CGFloat(5), startAngle: CGFloat(-M_PI), endAngle: CGFloat(-M_PI_2), clockwise: true)
leftArc.addLineToPoint(CGPoint(x: 0, y: 0))
leftArc.addLineToPoint(CGPoint(x: 0, y: 5))
leftArc.closePath()
return leftArc
}()
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
self.opaque = false
self.contentMode = .Redraw
}
private func getWidthForHeight(height: Double) -> Double {
return height * ASPECT_RATIO
}
private func drawFromTop(path: UIBezierPath) {
let height: Double = Double(UIConstants.ToolbarHeight)
let width = getWidthForHeight(height)
let from = (Double(self.frame.width) - width * 2 - Double(URLBarViewUX.URLBarCurveOffset - URLBarViewUX.URLBarCurveBounceBuffer), Double(0))
path.moveToPoint(CGPoint(x: from.0, y: from.1))
path.addCurveToPoint(CGPoint(x: from.0 + width * W_M2, y: from.1 + height * H_M2),
controlPoint1: CGPoint(x: from.0 + width * W_M1, y: from.1),
controlPoint2: CGPoint(x: from.0 + width * W_M3, y: from.1 + height * H_M1))
path.addCurveToPoint(CGPoint(x: from.0 + width, y: from.1 + height),
controlPoint1: CGPoint(x: from.0 + width * W_M4, y: from.1 + height * H_M3),
controlPoint2: CGPoint(x: from.0 + width * W_M5, y: from.1 + height * H_M4))
}
private func getPath() -> UIBezierPath {
let path = UIBezierPath()
self.drawFromTop(path)
path.addLineToPoint(CGPoint(x: self.frame.width, y: UIConstants.ToolbarHeight))
path.addLineToPoint(CGPoint(x: self.frame.width, y: 0))
path.addLineToPoint(CGPoint(x: 0, y: 0))
path.closePath()
return path
}
override func drawRect(rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
CGContextSaveGState(context)
CGContextClearRect(context, rect)
CGContextSetFillColorWithColor(context, URLBarViewUX.backgroundColorWithAlpha(1).CGColor)
getPath().fill()
leftCurvePath.fill()
CGContextDrawPath(context, CGPathDrawingMode.Fill)
CGContextRestoreGState(context)
}
}
private class ToolbarTextField: AutocompleteTextField {
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mpl-2.0
|
4baa04daffa8971ba93534565c274d26
| 40.583443 | 207 | 0.682351 | 5.518835 | false | false | false | false |
imitationgame/pokemonpassport
|
pokepass/Model/Create/MCreateAnnotation.swift
|
1
|
601
|
import Foundation
import MapKit
class MCreateAnnotation:NSObject, MKAnnotation
{
var coordinate:CLLocationCoordinate2D
let reusableIdentifier:String
var title:String?
var index:Int
init(coordinate:CLLocationCoordinate2D)
{
reusableIdentifier = VCreateMapPin.reusableIdentifier
self.coordinate = coordinate
index = 0
title = " "
super.init()
}
//MARK: public
func view() -> MKAnnotationView
{
let view:MKAnnotationView = VCreateMapPin(annotation:self)
return view
}
}
|
mit
|
8b5923ba359993182c3cfaa90373ba25
| 19.724138 | 66 | 0.63228 | 5.136752 | false | false | false | false |
vtourraine/AcknowList
|
Tests/AcknowListTests/AcknowPodDecoderTests.swift
|
1
|
3596
|
//
// AcknowPodDecoderTests.swift
// AcknowExampleTests
//
// Created by Vincent Tourraine on 15/08/15.
// Copyright © 2015-2022 Vincent Tourraine. All rights reserved.
//
import XCTest
@testable import AcknowList
class AcknowPodDecoderTests: XCTestCase {
func testHeaderFooter() throws {
let bundle = resourcesBundle()
let url = try XCTUnwrap(bundle.url(forResource: "Pods-acknowledgements", withExtension: "plist"))
let data = try Data(contentsOf: url)
let acknowList = try AcknowPodDecoder().decode(from: data)
XCTAssertEqual(acknowList.headerText, "This application makes use of the following third party libraries:")
XCTAssertEqual(acknowList.footerText, "Generated by CocoaPods - https://cocoapods.org")
}
func testAcknowledgements() throws {
let bundle = resourcesBundle()
let url = try XCTUnwrap(bundle.url(forResource: "Pods-acknowledgements", withExtension: "plist"))
let data = try Data(contentsOf: url)
let acknowList = try AcknowPodDecoder().decode(from: data)
XCTAssertEqual(acknowList.acknowledgements.count, 3)
let acknow = try XCTUnwrap(acknowList.acknowledgements.first)
XCTAssertEqual(acknow.title, "AcknowList (1)")
let text = try XCTUnwrap(acknow.text)
XCTAssertTrue(text.hasPrefix("Copyright (c) 2015-2019 Vincent Tourraine (http://www.vtourraine.net)"))
}
// To test the somewhat complicated extraneous-newline-removing regex, I have:
//
// (1) Made a temporary project and installed the 5 most popular pods that
// had no dependencies (loosely based on https://trendingcocoapods.github.io -
// scroll down to the "Top CocoaPods" section). I skipped pods with duplicate
// licenses.
//
// Ultimately, I installed: TYPFontAwesome (SIL OFL 1.1), pop (BSD),
// Alamofire (MIT), Charts (Apache 2), and TPKeyboardAvoiding (zLib)
//
// (2) Copied the acknowledgements file over to Pods-acknowledgements-RegexTesting.plist
//
// (3) Created this test, which parses the plist and applies the regex, then
// verifies that the generated strings are correct verus a manually edited
// "ground truth" text file.
func testFilterOutPrematureLineBreaks() throws {
let bundle = resourcesBundle()
let url = try XCTUnwrap(bundle.url(forResource: "Pods-acknowledgements-RegexTesting", withExtension: "plist"))
let data = try Data(contentsOf: url)
let acknowList = try AcknowPodDecoder().decode(from: data)
XCTAssertEqual(acknowList.acknowledgements.count, 5)
// For each acknowledgement, load the ground truth and compare...
for acknowledgement in acknowList.acknowledgements {
let groundTruthPath = try XCTUnwrap(bundle.url(forResource: "RegexTesting-GroundTruth-\(acknowledgement.title)", withExtension: "txt"))
let groundTruth = try String(contentsOf: groundTruthPath, encoding: .utf8)
XCTAssertEqual(acknowledgement.text, groundTruth)
}
}
func testGeneralPerformance() throws {
let bundle = resourcesBundle()
let url = try XCTUnwrap(bundle.url(forResource: "Pods-acknowledgements", withExtension: "plist"))
let data = try Data(contentsOf: url)
self.measure() {
_ = try? AcknowPodDecoder().decode(from: data)
}
}
func testParseNonExistentFile() {
let data = Data()
XCTAssertThrowsError(try AcknowPodDecoder().decode(from: data))
}
}
|
mit
|
2fa0ece6ab5640d20cb5fe63a012a939
| 42.313253 | 147 | 0.678164 | 4.326113 | false | true | false | false |
aranasaurus/flingInvaders
|
flingInvaders/GameViewController.swift
|
1
|
1209
|
//
// GameViewController.swift
// flingInvaders
//
// Created by Ryan Arana on 7/12/14.
// Copyright (c) 2014 aranasaurus.com. All rights reserved.
//
import UIKit
import SpriteKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let skView = self.view as SKView
skView.showsFPS = true
skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
let scene = GameScene(size: skView.bounds.size)
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
override func shouldAutorotate() -> Bool {
return false
}
override func supportedInterfaceOrientations() -> Int {
return Int(UIInterfaceOrientationMask.Portrait.toRaw())
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
|
apache-2.0
|
f7026d3ae633047f7a9f010793e0990d
| 24.723404 | 90 | 0.64847 | 5.122881 | false | false | false | false |
jfosterdavis/Charles
|
Charles/InsightColorStickView.swift
|
1
|
9033
|
//
// InsightColorStickView.swift
// Charles
//
// Created by Jacob Foster Davis on 6/1/17.
// Copyright © 2017 Zero Mu, LLC. All rights reserved.
//
import Foundation
import UIKit
//@IBDesignable
class InsightColorStickView:UIView
{
@IBInspectable var redPercent: CGFloat = 1.0
{
didSet {}
}
@IBInspectable var greenPercent: CGFloat = 1.0
{
didSet {}
}
@IBInspectable var bluePercent: CGFloat = 1.0
{
didSet {}
}
@IBInspectable var stickWidth: CGFloat = 8.0
{
didSet {}
}
@IBInspectable var borderWidth: CGFloat = 3.0
{
didSet {}
}
@IBInspectable var margin: CGFloat = 10.0
{
didSet {}
}
@IBInspectable var showColors: Bool = true
{
didSet {}
}
@IBInspectable var showDeviation: Bool = false
{
didSet {}
}
@IBInspectable var deviation: CGFloat = 0.75
{
didSet {}
}
@IBOutlet var deviationLabel: UILabel!
@IBOutlet var deviationImageView: UIImageView!
override func draw(_ rect: CGRect)
{
deviationLabel.roundCorners()
drawSticks(redPercent: redPercent, greenPercent: greenPercent, bluePercent: bluePercent, stickWidth: stickWidth, showColors: showColors)
}
fileprivate func drawSticks(redPercent: CGFloat, greenPercent: CGFloat, bluePercent: CGFloat, stickWidth: CGFloat = 8, showColors: Bool = true) {
var redLength: CGFloat = redPercent
if redLength > 1 {
redLength = 1
} else if redLength < 0 {
redLength = 0
}
var greenLength: CGFloat = greenPercent
if greenLength > 1 {
greenLength = 1
} else if greenLength < 0 {
greenLength = 0
}
var blueLength: CGFloat = bluePercent
if blueLength > 1 {
blueLength = 1
} else if blueLength < 0 {
blueLength = 0
}
let stickWidth:CGFloat = stickWidth
let stickHeight: CGFloat = max(bounds.width, bounds.height) / 2 - (margin * 2)
let viewCenterX = bounds.width/2
let viewCenterY = bounds.height/2 + stickWidth - margin
let circleCompensator = stickWidth - 1
let longwaysBorderwidth = borderWidth - 1
//the paths
let redPath = UIBezierPath()
let greenPath = UIBezierPath()
let bluePath = UIBezierPath()
//line width
redLength = stickHeight * redLength
redPath.lineWidth = stickWidth
redPath.move(to: CGPoint(
x:viewCenterX,
y:viewCenterY))
redPath.addLine(to: CGPoint(
x:viewCenterX,
y:viewCenterY - redLength - circleCompensator))
//draw red stroke background
let redPathBackground = UIBezierPath()
redPathBackground.lineWidth = redPath.lineWidth + borderWidth
let redPathBackgroundLength = redLength + longwaysBorderwidth
redPathBackground.move(to: CGPoint(
x:viewCenterX ,
y:viewCenterY))
redPathBackground.addLine(to: CGPoint(
x:viewCenterX ,
y:viewCenterY - redPathBackgroundLength - circleCompensator))
UIColor(red: 56/255, green: 56/255, blue: 56/255, alpha: 1).setStroke() //darker gray color
redPathBackground.stroke()
//the color for the red stroke will either be red (if showing colors) or black if is 0 - or a gray if colors not showing
if showColors {
UIColor.red.setStroke()
} else {
UIColor(red: 245/255, green: 245/255, blue: 245/255, alpha: 1).setStroke() //almost white
}
if redLength == 0 {
UIColor.black.setStroke()
}
//lay the red stroke
redPath.stroke()
let greenCircleCompensationX = circleCompensator * CGFloat(sin(60 * Double.pi/180))
let greenCircleCompensationY = circleCompensator * CGFloat(cos(60 * Double.pi/180))
let greenXAddition = stickHeight * greenLength * CGFloat(sin(60 * Double.pi/180))
let greenYAddition = stickHeight * greenLength * CGFloat(cos(60 * Double.pi/180))
greenPath.lineWidth = stickWidth
greenPath.move(to: CGPoint(
x:viewCenterX,
y:viewCenterY))
greenPath.addLine(to: CGPoint(
x:viewCenterX + greenXAddition + greenCircleCompensationX,
y:viewCenterY + greenYAddition + greenCircleCompensationY))
//green background
let greenPathBackground = UIBezierPath()
greenPathBackground.lineWidth = greenPath.lineWidth + borderWidth
let greenPathBackgroundXAddition = greenXAddition + longwaysBorderwidth * CGFloat(sin(60 * Double.pi/180))
let greenPathBackgroundYAddition = greenYAddition + longwaysBorderwidth * CGFloat(cos(60 * Double.pi/180))
greenPathBackground.move(to: CGPoint(
x:viewCenterX,
y:viewCenterY))
greenPathBackground.addLine(to: CGPoint(
x:viewCenterX + greenPathBackgroundXAddition + greenCircleCompensationX,
y:viewCenterY + greenPathBackgroundYAddition + greenCircleCompensationY))
UIColor(red: 56/255, green: 56/255, blue: 56/255, alpha: 1).setStroke() //darker gray color
greenPathBackground.stroke()
if showColors {
UIColor.green.setStroke()
} else {
UIColor(red: 245/255, green: 245/255, blue: 245/255, alpha: 1).setStroke() //almost white
}
if greenLength == 0 {
UIColor.black.setStroke()
}
//lay the green stroke
greenPath.stroke()
let blueXAddition = stickHeight * blueLength * CGFloat(sin(60 * Double.pi/180)) * -1
let blueYAddition = stickHeight * blueLength * CGFloat(cos(60 * Double.pi/180))
bluePath.lineWidth = stickWidth
bluePath.move(to: CGPoint(
x:viewCenterX,
y:viewCenterY))
bluePath.addLine(to: CGPoint(
x:viewCenterX + blueXAddition - greenCircleCompensationX,
y:viewCenterY + blueYAddition + greenCircleCompensationY))
//blue background
let bluePathBackground = UIBezierPath()
bluePathBackground.lineWidth = bluePath.lineWidth + borderWidth
let bluePathBackgroundXAddition = blueXAddition - longwaysBorderwidth * CGFloat(sin(60 * Double.pi/180))
let bluePathBackgroundYAddition = blueYAddition + longwaysBorderwidth * CGFloat(cos(60 * Double.pi/180))
bluePathBackground.move(to: CGPoint(
x:viewCenterX,
y:viewCenterY))
bluePathBackground.addLine(to: CGPoint(
x:viewCenterX + bluePathBackgroundXAddition - greenCircleCompensationX,
y:viewCenterY + bluePathBackgroundYAddition + greenCircleCompensationY))
UIColor(red: 56/255, green: 56/255, blue: 56/255, alpha: 1).setStroke() //darker gray color
bluePathBackground.stroke()
if showColors {
UIColor.blue.setStroke()
} else {
UIColor(red: 245/255, green: 245/255, blue: 245/255, alpha: 1).setStroke() //almost white
}
if blueLength == 0 {
UIColor.black.setStroke()
}
//lay the blue stroke
bluePath.stroke()
//circle center
let circlePath = UIBezierPath(
arcCenter: CGPoint(x: viewCenterX, y: viewCenterY),
radius: circleCompensator - 1,
startAngle: CGFloat(0),
endAngle:CGFloat(2 * Double.pi),
clockwise: true)
if redPercent + bluePercent + greenPercent == 0 {
UIColor.black.setFill()
} else {
UIColor.gray.setFill()
}
circlePath.fill()
//show or don't the deviation
if showDeviation {
deviationLabel.isHidden = !showDeviation
deviationLabel.text = String(describing: "\(Int(deviation.rounded(toNearest: 0.01) * 100))")
} else {
deviationLabel.isHidden = !showDeviation
}
}
///draws the InsightColorStickView with the given percentages, each a CGFloat from 0 to 1
func drawSticks(redPercent: CGFloat, greenPercent: CGFloat, bluePercent: CGFloat, showColors: Bool = true, deviation: CGFloat? = nil) {
if let deviation = deviation {
self.deviation = deviation
self.showDeviation = true
} else {
self.showDeviation = false
}
self.redPercent = redPercent
self.greenPercent = greenPercent
self.bluePercent = bluePercent
self.showColors = showColors
self.setNeedsDisplay()
}
}
|
apache-2.0
|
a9d91f41101fb28df0312d5996b037b8
| 33.342205 | 149 | 0.593113 | 4.511489 | false | false | false | false |
modocache/swift
|
test/Generics/associated_type_typo.swift
|
2
|
2523
|
// RUN: %target-parse-verify-swift
// RUN: not %target-swift-frontend -parse -debug-generic-signatures %s > %t.dump 2>&1
// RUN: %FileCheck -check-prefix CHECK-GENERIC %s < %t.dump
protocol P1 {
associatedtype Assoc
}
protocol P2 {
associatedtype AssocP2 : P1
}
protocol P3 { }
protocol P4 { }
// expected-error@+1{{'T' does not have a member type named 'assoc'; did you mean 'Assoc'?}}{{30-35=Assoc}}
func typoAssoc1<T : P1>(x: T.assoc) { }
// expected-error@+2{{'T' does not have a member type named 'assoc'; did you mean 'Assoc'?}}{{43-48=Assoc}}
// expected-error@+1{{'U' does not have a member type named 'assoc'; did you mean 'Assoc'?}}{{54-59=Assoc}}
func typoAssoc2<T : P1, U : P1>() where T.assoc == U.assoc {}
// CHECK-GENERIC-LABEL: .typoAssoc2
// CHECK-GENERIC: Generic signature: <T, U where T : P1, U : P1, T.Assoc == U.Assoc>
// expected-error@+3{{'T.AssocP2' does not have a member type named 'assoc'; did you mean 'Assoc'?}}{{42-47=Assoc}}
// expected-error@+2{{'U.AssocP2' does not have a member type named 'assoc'; did you mean 'Assoc'?}}{{19-24=Assoc}}
func typoAssoc3<T : P2, U : P2>()
where U.AssocP2.assoc : P3, T.AssocP2.assoc : P4,
T.AssocP2 == U.AssocP2 {}
// expected-error@+2{{'T' does not have a member type named 'Assocp2'; did you mean 'AssocP2'?}}{{39-46=AssocP2}}
// expected-error@+1{{'T.AssocP2' does not have a member type named 'assoc'; did you mean 'Assoc'?}}{{47-52=Assoc}}
func typoAssoc4<T : P2>(_: T) where T.Assocp2.assoc : P3 {}
// CHECK-GENERIC-LABEL: .typoAssoc4@
// CHECK-GENERIC-NEXT: Requirements:
// CHECK-GENERIC-NEXT: T witness marker
// CHECK-GENERIC-NEXT: T : P2 [explicit
// CHECK-GENERIC-NEXT: T[.P2].AssocP2 witness marker
// CHECK-GENERIC-NEXT: T[.P2].AssocP2 : P1 [protocol
// CHECK-GENERIC-NEXT: T[.P2].AssocP2 == T.AssocP2 [redundant]
// CHECK-GENERIC-NEXT: T[.P2].AssocP2[.P1].Assoc witness marker
// CHECK-GENERIC-NEXT: T[.P2].AssocP2[.P1].Assoc : P3 [explicit
// CHECK-GENERIC-NEXT: T[.P2].AssocP2[.P1].Assoc == T[.P2].AssocP2.Assoc [redundant]
// CHECK-GENERIC-NEXT: Generic signature
// <rdar://problem/19620340>
func typoFunc1<T : P1>(x: TypoType) { // expected-error{{use of undeclared type 'TypoType'}}
let _: (T.Assoc) -> () = { let _ = $0 }
}
func typoFunc2<T : P1>(x: TypoType, y: T) { // expected-error{{use of undeclared type 'TypoType'}}
let _: (T.Assoc) -> () = { let _ = $0 }
}
func typoFunc3<T : P1>(x: TypoType, y: (T.Assoc) -> ()) { // expected-error{{use of undeclared type 'TypoType'}}
}
|
apache-2.0
|
44923b2d2f09069f3ee259f1c495c3b5
| 39.693548 | 115 | 0.649623 | 2.84763 | false | false | false | false |
modocache/swift
|
stdlib/private/SwiftPrivatePthreadExtras/SwiftPrivatePthreadExtras.swift
|
3
|
4496
|
//===--- SwiftPrivatePthreadExtras.swift ----------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file contains wrappers for pthread APIs that are less painful to use
// than the C APIs.
//
//===----------------------------------------------------------------------===//
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android)
import Glibc
#endif
/// An abstract base class to encapsulate the context necessary to invoke
/// a block from pthread_create.
internal class PthreadBlockContext {
/// Execute the block, and return an `UnsafeMutablePointer` to memory
/// allocated with `UnsafeMutablePointer.alloc` containing the result of the
/// block.
func run() -> UnsafeMutableRawPointer { fatalError("abstract") }
}
internal class PthreadBlockContextImpl<Argument, Result>: PthreadBlockContext {
let block: (Argument) -> Result
let arg: Argument
init(block: @escaping (Argument) -> Result, arg: Argument) {
self.block = block
self.arg = arg
super.init()
}
override func run() -> UnsafeMutableRawPointer {
let result = UnsafeMutablePointer<Result>.allocate(capacity: 1)
result.initialize(to: block(arg))
return UnsafeMutableRawPointer(result)
}
}
/// Entry point for `pthread_create` that invokes a block context.
internal func invokeBlockContext(
_ contextAsVoidPointer: UnsafeMutableRawPointer?
) -> UnsafeMutableRawPointer! {
// The context is passed in +1; we're responsible for releasing it.
let context = Unmanaged<PthreadBlockContext>
.fromOpaque(contextAsVoidPointer!)
.takeRetainedValue()
return context.run()
}
/// Block-based wrapper for `pthread_create`.
public func _stdlib_pthread_create_block<Argument, Result>(
_ attr: UnsafePointer<pthread_attr_t>?,
_ start_routine: @escaping (Argument) -> Result,
_ arg: Argument
) -> (CInt, pthread_t?) {
let context = PthreadBlockContextImpl(block: start_routine, arg: arg)
// We hand ownership off to `invokeBlockContext` through its void context
// argument.
let contextAsVoidPointer = Unmanaged.passRetained(context).toOpaque()
var threadID = _make_pthread_t()
let result = pthread_create(&threadID, attr,
{ invokeBlockContext($0) }, contextAsVoidPointer)
if result == 0 {
return (result, threadID)
} else {
return (result, nil)
}
}
#if os(Linux) || os(Android)
internal func _make_pthread_t() -> pthread_t {
return pthread_t()
}
#else
internal func _make_pthread_t() -> pthread_t? {
return nil
}
#endif
/// Block-based wrapper for `pthread_join`.
public func _stdlib_pthread_join<Result>(
_ thread: pthread_t,
_ resultType: Result.Type
) -> (CInt, Result?) {
var threadResultRawPtr: UnsafeMutableRawPointer?
let result = pthread_join(thread, &threadResultRawPtr)
if result == 0 {
let threadResultPtr = threadResultRawPtr!.assumingMemoryBound(
to: Result.self)
let threadResult = threadResultPtr.pointee
threadResultPtr.deinitialize()
threadResultPtr.deallocate(capacity: 1)
return (result, threadResult)
} else {
return (result, nil)
}
}
public class _stdlib_Barrier {
var _pthreadBarrier: _stdlib_pthread_barrier_t
var _pthreadBarrierPtr: UnsafeMutablePointer<_stdlib_pthread_barrier_t> {
return _getUnsafePointerToStoredProperties(self)
.assumingMemoryBound(to: _stdlib_pthread_barrier_t.self)
}
public init(threadCount: Int) {
self._pthreadBarrier = _stdlib_pthread_barrier_t()
let ret = _stdlib_pthread_barrier_init(
_pthreadBarrierPtr, nil, CUnsignedInt(threadCount))
if ret != 0 {
fatalError("_stdlib_pthread_barrier_init() failed")
}
}
deinit {
let ret = _stdlib_pthread_barrier_destroy(_pthreadBarrierPtr)
if ret != 0 {
fatalError("_stdlib_pthread_barrier_destroy() failed")
}
}
public func wait() {
let ret = _stdlib_pthread_barrier_wait(_pthreadBarrierPtr)
if !(ret == 0 || ret == _stdlib_PTHREAD_BARRIER_SERIAL_THREAD) {
fatalError("_stdlib_pthread_barrier_wait() failed")
}
}
}
|
apache-2.0
|
a8726d102e4d62d4549b7b5566841f3c
| 30.661972 | 80 | 0.674155 | 4.159112 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
Modules/Platform/Sources/PlatformKit/Coincore/Account/Crypto/CryptoInterestAccount.swift
|
1
|
7786
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Combine
import DIKit
import Localization
import MoneyKit
import RxSwift
import ToolKit
public final class CryptoInterestAccount: CryptoAccount, InterestAccount {
private enum CryptoInterestAccountError: LocalizedError {
case loadingFailed(asset: String, label: String, action: AssetAction, error: String)
var errorDescription: String? {
switch self {
case .loadingFailed(let asset, let label, let action, let error):
return "Failed to load: 'CryptoInterestAccount' asset '\(asset)' label '\(label)' action '\(action)' error '\(error)' ."
}
}
}
public private(set) lazy var identifier: AnyHashable = "CryptoInterestAccount." + asset.code
public let label: String
public let asset: CryptoCurrency
public let isDefault: Bool = false
public var accountType: AccountType = .trading
public var receiveAddress: AnyPublisher<ReceiveAddress, Error> {
receiveAddressRepository
.fetchInterestAccountReceiveAddressForCurrencyCode(asset.code)
.eraseError()
.flatMap { [cryptoReceiveAddressFactory, onTxCompleted, asset] addressString in
cryptoReceiveAddressFactory
.makeExternalAssetAddress(
address: addressString,
label: "\(asset.code) \(LocalizationConstants.rewardsAccount)",
onTxCompleted: onTxCompleted
)
.eraseError()
.publisher
.eraseToAnyPublisher()
}
.map { $0 as ReceiveAddress }
.eraseToAnyPublisher()
}
public var isFunded: AnyPublisher<Bool, Error> {
balances
.map { $0 != .absent }
.eraseError()
}
public var pendingBalance: AnyPublisher<MoneyValue, Error> {
balances
.map(\.balance?.pending)
.replaceNil(with: .zero(currency: currencyType))
.eraseError()
}
public var balance: AnyPublisher<MoneyValue, Error> {
balances
.map(\.balance?.available)
.replaceNil(with: .zero(currency: currencyType))
.eraseError()
}
public var disabledReason: AnyPublisher<InterestAccountIneligibilityReason, Error> {
interestEligibilityRepository
.fetchInterestAccountEligibilityForCurrencyCode(currencyType)
.map(\.ineligibilityReason)
.eraseError()
.eraseToAnyPublisher()
}
public var actionableBalance: AnyPublisher<MoneyValue, Error> {
// `withdrawable` is the accounts total balance
// minus the locked funds amount. Only these funds are
// available for withdraws (which is all you can do with
// your interest account funds)
balances
.map(\.balance)
.map(\.?.withdrawable)
.replaceNil(with: .zero(currency: currencyType))
.eraseError()
}
public var activity: AnyPublisher<[ActivityItemEvent], Error> {
interestActivityEventRepository
.fetchInterestActivityItemEventsForCryptoCurrency(asset)
.map { events in
events.map(ActivityItemEvent.interest)
}
.replaceError(with: [])
.eraseError()
.eraseToAnyPublisher()
}
private var isInterestWithdrawAndDepositEnabled: AnyPublisher<Bool, Never> {
featureFlagsService
.isEnabled(.interestWithdrawAndDeposit)
.replaceError(with: false)
.eraseToAnyPublisher()
}
private let featureFlagsService: FeatureFlagsServiceAPI
private let cryptoReceiveAddressFactory: ExternalAssetAddressFactory
private let errorRecorder: ErrorRecording
private let priceService: PriceServiceAPI
private let interestEligibilityRepository: InterestAccountEligibilityRepositoryAPI
private let receiveAddressRepository: InterestAccountReceiveAddressRepositoryAPI
private let interestActivityEventRepository: InterestActivityItemEventRepositoryAPI
private let balanceService: InterestAccountOverviewAPI
private var balances: AnyPublisher<CustodialAccountBalanceState, Never> {
balanceService.balance(for: asset)
}
public init(
asset: CryptoCurrency,
receiveAddressRepository: InterestAccountReceiveAddressRepositoryAPI = resolve(),
priceService: PriceServiceAPI = resolve(),
errorRecorder: ErrorRecording = resolve(),
balanceService: InterestAccountOverviewAPI = resolve(),
exchangeProviding: ExchangeProviding = resolve(),
interestEligibilityRepository: InterestAccountEligibilityRepositoryAPI = resolve(),
featureFlagService: FeatureFlagsServiceAPI = resolve(),
interestActivityEventRepository: InterestActivityItemEventRepositoryAPI = resolve(),
cryptoReceiveAddressFactory: ExternalAssetAddressFactory
) {
label = asset.defaultInterestWalletName
self.interestActivityEventRepository = interestActivityEventRepository
self.cryptoReceiveAddressFactory = cryptoReceiveAddressFactory
self.receiveAddressRepository = receiveAddressRepository
self.asset = asset
self.errorRecorder = errorRecorder
self.balanceService = balanceService
self.priceService = priceService
self.interestEligibilityRepository = interestEligibilityRepository
featureFlagsService = featureFlagService
}
public func can(perform action: AssetAction) -> AnyPublisher<Bool, Error> {
switch action {
case .interestWithdraw:
return canPerformInterestWithdraw()
.setFailureType(to: Error.self)
.eraseToAnyPublisher()
case .viewActivity:
return activity
.map { !$0.isEmpty }
.eraseError()
.eraseToAnyPublisher()
case .buy,
.deposit,
.interestTransfer,
.receive,
.sell,
.send,
.sign,
.swap,
.withdraw,
.linkToDebitCard:
return .just(false)
}
}
public func balancePair(
fiatCurrency: FiatCurrency,
at time: PriceTime
) -> AnyPublisher<MoneyValuePair, Error> {
balancePair(
priceService: priceService,
fiatCurrency: fiatCurrency,
at: time
)
}
private func canPerformInterestWithdraw() -> AnyPublisher<Bool, Never> {
isInterestWithdrawAndDepositEnabled.setFailureType(to: Error.self)
.zip(actionableBalance.map(\.isPositive))
.map { enabled, positiveBalance in
enabled && positiveBalance
}
.flatMap { [disabledReason] isAvailable -> AnyPublisher<Bool, Error> in
guard isAvailable else {
return .just(false)
}
return disabledReason.map(\.isEligible)
.eraseToAnyPublisher()
}
.mapError { [label, asset] error -> CryptoInterestAccountError in
.loadingFailed(
asset: asset.code,
label: label,
action: .interestWithdraw,
error: String(describing: error)
)
}
.recordErrors(on: errorRecorder)
.replaceError(with: false)
.eraseToAnyPublisher()
}
public func invalidateAccountBalance() {
balanceService
.invalidateInterestAccountBalances()
}
}
|
lgpl-3.0
|
c07e66ad977746a7a25a0a615d83d4ed
| 36.427885 | 136 | 0.627232 | 5.835832 | false | false | false | false |
jeffreybergier/Cartwheel
|
Cartwheel/Cartwheel/Source/DependencyDefinableListWindow/DependencyDefinableListTableViewRows/Controllers/CartfileUpdaterManager.swift
|
1
|
3136
|
//
// CartfileUpdaterController.swift
// Cartwheel
//
// Created by Jeffrey Bergier on 8/16/15.
//
// Copyright (c) 2015 Jeffrey Bergier
//
// 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 COwNTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import ReactiveCocoa
import ObserverSet
class CartfileUpdaterManager: CartfileUpdaterDelegate {
let changeNotifier = ObserverSet<Cartfile>()
private var updatesInProgress = [Cartfile : CartfileUpdater]()
func updateCartfile(cartfile: Cartfile, forceRestart force: Bool = false) {
switch self.statusForCartfile(cartfile) {
case .NonExistant:
let updater = CartfileUpdater(cartfile: cartfile, delegate: self)
updater.start()
self.updatesInProgress[cartfile] = updater
case .NotStarted:
self.updatesInProgress[cartfile]?.start()
case .InProgressIndeterminate, .InProgressDeterminate(let _), .FinishedSuccess:
if force == true {
self.cancelUpdateForCartfile(cartfile)
let updater = CartfileUpdater(cartfile: cartfile, delegate: self)
updater.start()
self.updatesInProgress[cartfile] = updater
}
case .FinishedInterrupted, .FinishedError(let _):
self.cancelUpdateForCartfile(cartfile)
let updater = CartfileUpdater(cartfile: cartfile, delegate: self)
updater.start()
self.updatesInProgress[cartfile] = updater
}
self.changeNotifier.notify(cartfile)
}
func cancelUpdateForCartfile(cartfile: Cartfile) -> Bool {
if let update = self.updatesInProgress[cartfile] {
update.cancel()
self.updatesInProgress.removeValueForKey(cartfile)
self.changeNotifier.notify(cartfile)
return true
}
self.changeNotifier.notify(cartfile)
return false
}
func statusForCartfile(cartfile: Cartfile) -> CartfileUpdater.Status {
if let update = self.updatesInProgress[cartfile] {
return update.status
}
return .NonExistant
}
}
|
mit
|
c009d909c011777ea98bd20aa4ed6cc9
| 40.276316 | 87 | 0.68176 | 4.722892 | false | false | false | false |
fengyu122/YUImageViewer
|
YUImageViewer/YUImageViewerViewController.swift
|
1
|
10719
|
//
// YUImageViewerViewController.swift
// YUImageViewer
//
// Created by yu on 2017/1/8.
// Copyright © 2017年 yu. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
@objc protocol YUImageViewerViewControllerDelegate:NSObjectProtocol {
@objc optional func imageViewerViewController(_ viewController:YUImageViewerViewController , onLongPressAt index:Int ,image:UIImage? ,model:YUImageViewerModel)
@objc optional func imageViewerViewController(_ viewController:YUImageViewerViewController, didShowAt index:Int ,model :YUImageViewerModel)
@objc optional func imageViewerViewController(_ viewController:YUImageViewerViewController, willShowAt index:Int ,model:YUImageViewerModel)
@objc optional func imageViewerViewController(_ viewController:YUImageViewerViewController, didDismissAt index:Int ,model:YUImageViewerModel)
@objc optional func imageViewerViewController(_ viewController:YUImageViewerViewController, willDismissAt index:Int ,model:YUImageViewerModel)
func imageViewerViewController(_ viewController:YUImageViewerViewController , downloadImageAt index:Int , imageView:UIImageView , model:YUImageViewerModel,complete:@escaping DownloadCompleteBlock)
}
typealias DownloadCompleteBlock = ((_ sucess:Bool)->())
public class YUImageViewerViewController: UIViewController,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UIViewControllerTransitioningDelegate,YUImageViewerCellProtocol {
private let cellWithReuseIdentifier="YUImageViewerCell"
private lazy var collectionView:UICollectionView={ [unowned self] in
let layout=UICollectionViewFlowLayout()
layout.scrollDirection=UICollectionViewScrollDirection.horizontal
let collectionView=UICollectionView.init(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.register(YUImageViewerCell.self, forCellWithReuseIdentifier: self.cellWithReuseIdentifier)
collectionView.isPagingEnabled=true
collectionView.dataSource=self
collectionView.delegate=self
collectionView.showsHorizontalScrollIndicator=false
collectionView.showsVerticalScrollIndicator=false
collectionView.translatesAutoresizingMaskIntoConstraints=false
return collectionView
}()
private lazy var pageControl:UIPageControl={ [unowned self] in
let pageControl=UIPageControl.init()
pageControl.pageIndicatorTintColor=UIColor.gray
pageControl.currentPageIndicatorTintColor=UIColor.white
pageControl.translatesAutoresizingMaskIntoConstraints=false
pageControl.hidesForSinglePage=true
pageControl.isEnabled=false
return pageControl
}()
private var hideNotCurrentCell=false
{
didSet
{
collectionView.reloadData()
}
}
private let transitonAnimation=YUTransitonAnimation.init()
private var canUpdateCurrentIndex=true
override public var shouldAutorotate: Bool
{
return true
}
override public var supportedInterfaceOrientations: UIInterfaceOrientationMask
{
return UIInterfaceOrientationMask.allButUpsideDown
}
var models=[YUImageViewerModel]()
{
didSet
{
pageControl.numberOfPages=models.count
}
}
override public func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor=UIColor.black
view.addSubview(collectionView)
view.addSubview(pageControl)
view.addConstraint(NSLayoutConstraint.init(item: pageControl, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint.init(item: pageControl, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: -10))
pageControl.numberOfPages=models.count
pageControl.currentPage=currentSelect
UIDevice.current.beginGeneratingDeviceOrientationNotifications()
collectionView.selectItem(at: IndexPath.init(row: currentSelect, section: 0), animated: false, scrollPosition: .left)
UIApplication.shared.setStatusBarHidden(true, with: .fade)
}
public override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.delegate?.imageViewerViewController?(self, willShowAt: currentSelect ,model:models[currentSelect])
}
public override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
self.delegate?.imageViewerViewController?(self, didDismissAt: self.currentSelect,model:models[currentSelect])
}
public override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.delegate?.imageViewerViewController?(self, willDismissAt: currentSelect,model:models[currentSelect])
}
public override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.delegate?.imageViewerViewController?(self, didShowAt: currentSelect,model:models[currentSelect])
}
public override var prefersStatusBarHidden: Bool
{
return true
}
deinit {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
}
public override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
canUpdateCurrentIndex=false
hideNotCurrentCell=true
coordinator.animate(alongsideTransition: { [unowned self] (ctx) in
self.collectionView.collectionViewLayout.invalidateLayout()
self.collectionView.frame=CGRect.init(origin: CGPoint.zero, size: size)
self.collectionView.selectItem(at: IndexPath.init(row: self.currentSelect, section: 0), animated: false, scrollPosition: .left)
}) { [unowned self] (ctx) in
self.canUpdateCurrentIndex=true
self.hideNotCurrentCell=false
}
}
private var currentSelect:Int=0
{
didSet
{
pageControl.currentPage=currentSelect
}
}
weak var delegate:YUImageViewerViewControllerDelegate?
convenience init(models:[YUImageViewerModel],currentSelect:Int,delegate:YUImageViewerViewControllerDelegate)
{
self.init()
self.models=models
self.delegate=delegate
self.currentSelect=currentSelect
transitioningDelegate=self
}
public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
transitonAnimation.actionType=YUTransitonActionType.present
transitonAnimation.model=models[currentSelect]
return transitonAnimation
}
public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
transitonAnimation.actionType=YUTransitonActionType.dismiss
transitonAnimation.model=models[currentSelect]
return transitonAnimation
}
override public func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
public func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return models.count
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell=collectionView.dequeueReusableCell(withReuseIdentifier: cellWithReuseIdentifier, for: indexPath) as! YUImageViewerCell
cell.delegate=self
cell.index=indexPath.item
cell.model=models[indexPath.row]
cell.isHidden=hideNotCurrentCell && currentSelect != indexPath.row
return cell
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return collectionView.bounds.size
}
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
if canUpdateCurrentIndex
{
let offsetX=scrollView.contentOffset.x
currentSelect=Int(offsetX/scrollView.bounds.width+0.5)
}
}
func imageViewerCell(singleTapActionAt index: Int) {
dismiss(animated: true) { [unowned self] in
for model in self.models
{
model.clearState()
}
}
}
func imageViewerCell(longPressActionAt index: Int, image: UIImage?) {
self.delegate?.imageViewerViewController?(self, onLongPressAt: index, image: image ,model:models[index])
}
func imageViewerCell(downloadImageAt index: Int, imageView: UIImageView, complete: @escaping DownloadCompleteBlock) {
self.delegate?.imageViewerViewController(self, downloadImageAt: index, imageView: imageView, model:models[index],complete: complete)
}
}
|
mit
|
4ff805442639af4e54e77f8c067395db
| 47.053812 | 211 | 0.732736 | 5.532266 | false | false | false | false |
alessiobrozzi/firefox-ios
|
Storage/SQL/SQLiteHistory.swift
|
1
|
51409
|
/* 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 XCGLogger
import Deferred
private let log = Logger.syncLogger
class NoSuchRecordError: MaybeErrorType {
let guid: GUID
init(guid: GUID) {
self.guid = guid
}
var description: String {
return "No such record: \(guid)."
}
}
func failOrSucceed<T>(_ err: NSError?, op: String, val: T) -> Deferred<Maybe<T>> {
if let err = err {
log.debug("\(op) failed: \(err.localizedDescription)")
return deferMaybe(DatabaseError(err: err))
}
return deferMaybe(val)
}
func failOrSucceed(_ err: NSError?, op: String) -> Success {
return failOrSucceed(err, op: op, val: ())
}
private var ignoredSchemes = ["about"]
public func isIgnoredURL(_ url: URL) -> Bool {
guard let scheme = url.scheme else { return false }
if let _ = ignoredSchemes.index(of: scheme) {
return true
}
if url.host == "localhost" {
return true
}
return false
}
public func isIgnoredURL(_ url: String) -> Bool {
if let url = URL(string: url) {
return isIgnoredURL(url)
}
return false
}
/*
// Here's the Swift equivalent of the below.
func simulatedFrecency(now: MicrosecondTimestamp, then: MicrosecondTimestamp, visitCount: Int) -> Double {
let ageMicroseconds = (now - then)
let ageDays = Double(ageMicroseconds) / 86400000000.0 // In SQL the .0 does the coercion.
let f = 100 * 225 / ((ageSeconds * ageSeconds) + 225)
return Double(visitCount) * max(1.0, f)
}
*/
// The constants in these functions were arrived at by utterly unscientific experimentation.
func getRemoteFrecencySQL() -> String {
let visitCountExpression = "remoteVisitCount"
let now = Date.nowMicroseconds()
let microsecondsPerDay = 86_400_000_000.0 // 1000 * 1000 * 60 * 60 * 24
let ageDays = "((\(now) - remoteVisitDate) / \(microsecondsPerDay))"
return "\(visitCountExpression) * max(1, 100 * 110 / (\(ageDays) * \(ageDays) + 110))"
}
func getLocalFrecencySQL() -> String {
let visitCountExpression = "((2 + localVisitCount) * (2 + localVisitCount))"
let now = Date.nowMicroseconds()
let microsecondsPerDay = 86_400_000_000.0 // 1000 * 1000 * 60 * 60 * 24
let ageDays = "((\(now) - localVisitDate) / \(microsecondsPerDay))"
return "\(visitCountExpression) * max(2, 100 * 225 / (\(ageDays) * \(ageDays) + 225))"
}
extension SDRow {
func getTimestamp(_ column: String) -> Timestamp? {
return (self[column] as? NSNumber)?.uint64Value
}
func getBoolean(_ column: String) -> Bool {
if let val = self[column] as? Int {
return val != 0
}
return false
}
}
/**
* The sqlite-backed implementation of the history protocol.
*/
open class SQLiteHistory {
let db: BrowserDB
let favicons: FaviconsTable<Favicon>
let prefs: Prefs
required public init(db: BrowserDB, prefs: Prefs) {
self.db = db
self.favicons = FaviconsTable<Favicon>()
self.prefs = prefs
// BrowserTable exists only to perform create/update etc. operations -- it's not
// a queryable thing that needs to stick around.
switch db.createOrUpdate(BrowserTable()) {
case .failure:
log.error("Failed to create/update DB schema!")
fatalError()
case .closed:
log.info("Database not created as the SQLiteConnection is closed.")
case .success:
log.debug("Database succesfully created/updated")
}
}
}
private let topSitesQuery = "SELECT \(TableCachedTopSites).*, \(TablePageMetadata).provider_name FROM \(TableCachedTopSites) LEFT OUTER JOIN \(TablePageMetadata) ON \(TableCachedTopSites).url = \(TablePageMetadata).site_url ORDER BY frecencies DESC LIMIT (?)"
extension SQLiteHistory: BrowserHistory {
public func removeSiteFromTopSites(_ site: Site) -> Success {
if let host = (site.url as String).asURL?.normalizedHost {
return self.removeHostFromTopSites(host)
}
return deferMaybe(DatabaseError(description: "Invalid url for site \(site.url)"))
}
public func removeHostFromTopSites(_ host: String) -> Success {
return db.run([("UPDATE \(TableDomains) set showOnTopSites = 0 WHERE domain = ?", [host])])
>>> { return self.refreshTopSitesCache() }
}
public func removeHistoryForURL(_ url: String) -> Success {
let visitArgs: Args = [url]
let deleteVisits = "DELETE FROM \(TableVisits) WHERE siteID = (SELECT id FROM \(TableHistory) WHERE url = ?)"
let markArgs: Args = [Date.nowNumber(), url]
let markDeleted = "UPDATE \(TableHistory) SET url = NULL, is_deleted = 1, should_upload = 1, local_modified = ? WHERE url = ?"
//return db.run([(sql: String, args: Args?)])
let command = [(sql: deleteVisits, args: visitArgs), (sql: markDeleted, args: markArgs), favicons.getCleanupCommands()] as [(sql: String, args: Args?)]
return db.run(command)
}
// Note: clearing history isn't really a sane concept in the presence of Sync.
// This method should be split to do something else.
// Bug 1162778.
public func clearHistory() -> Success {
return self.db.run([
("DELETE FROM \(TableVisits)", nil),
("DELETE FROM \(TableHistory)", nil),
("DELETE FROM \(TableDomains)", nil),
self.favicons.getCleanupCommands(),
])
// We've probably deleted a lot of stuff. Vacuum now to recover the space.
>>> effect(self.db.vacuum)
}
func recordVisitedSite(_ site: Site) -> Success {
var error: NSError? = nil
// Don't store visits to sites with about: protocols
if isIgnoredURL(site.url as String) {
return deferMaybe(IgnoredSiteError())
}
let _ = db.withConnection(&error) { (conn, _) -> Int in
let now = Date.now()
let i = self.updateSite(site, atTime: now, withConnection: conn)
if i > 0 {
return i
}
// Insert instead.
return self.insertSite(site, atTime: now, withConnection: conn)
}
return failOrSucceed(error, op: "Record site")
}
func updateSite(_ site: Site, atTime time: Timestamp, withConnection conn: SQLiteDBConnection) -> Int {
// We know we're adding a new visit, so we'll need to upload this record.
// If we ever switch to per-visit change flags, this should turn into a CASE statement like
// CASE WHEN title IS ? THEN max(should_upload, 1) ELSE should_upload END
// so that we don't flag this as changed unless the title changed.
//
// Note that we will never match against a deleted item, because deleted items have no URL,
// so we don't need to unset is_deleted here.
if let host = (site.url as String).asURL?.normalizedHost {
let update = "UPDATE \(TableHistory) SET title = ?, local_modified = ?, should_upload = 1, domain_id = (SELECT id FROM \(TableDomains) where domain = ?) WHERE url = ?"
let updateArgs: Args? = [site.title, time, host, site.url]
if Logger.logPII {
log.debug("Setting title to \(site.title) for URL \(site.url)")
}
let error = conn.executeChange(update, withArgs: updateArgs)
if error != nil {
log.warning("Update failed with \(error?.localizedDescription)")
return 0
}
return conn.numberOfRowsModified
}
return 0
}
fileprivate func insertSite(_ site: Site, atTime time: Timestamp, withConnection conn: SQLiteDBConnection) -> Int {
if let host = (site.url as String).asURL?.normalizedHost {
if let error = conn.executeChange("INSERT OR IGNORE INTO \(TableDomains) (domain) VALUES (?)", withArgs: [host]) {
log.warning("Domain insertion failed with \(error.localizedDescription)")
return 0
}
let insert = "INSERT INTO \(TableHistory) " +
"(guid, url, title, local_modified, is_deleted, should_upload, domain_id) " +
"SELECT ?, ?, ?, ?, 0, 1, id FROM \(TableDomains) WHERE domain = ?"
let insertArgs: Args? = [site.guid ?? Bytes.generateGUID(), site.url, site.title, time, host]
if let error = conn.executeChange(insert, withArgs: insertArgs) {
log.warning("Site insertion failed with \(error.localizedDescription)")
return 0
}
return 1
}
if Logger.logPII {
log.warning("Invalid URL \(site.url). Not stored in history.")
}
return 0
}
// TODO: thread siteID into this to avoid the need to do the lookup.
func addLocalVisitForExistingSite(_ visit: SiteVisit) -> Success {
var error: NSError? = nil
let _ = db.withConnection(&error) { (conn, _) -> Int in
// INSERT OR IGNORE because we *might* have a clock error that causes a timestamp
// collision with an existing visit, and it would really suck to error out for that reason.
let insert = "INSERT OR IGNORE INTO \(TableVisits) (siteID, date, type, is_local) VALUES (" +
"(SELECT id FROM \(TableHistory) WHERE url = ?), ?, ?, 1)"
let realDate = visit.date
let insertArgs: Args? = [visit.site.url, realDate, visit.type.rawValue]
error = conn.executeChange(insert, withArgs: insertArgs)
if error != nil {
//log.warning("Visit insertion failed with \(err?.localizedDescription)")
return 0
}
return 1
}
return failOrSucceed(error, op: "Record visit")
}
public func addLocalVisit(_ visit: SiteVisit) -> Success {
return recordVisitedSite(visit.site)
>>> { self.addLocalVisitForExistingSite(visit) }
}
public func getSitesByFrecencyWithHistoryLimit(_ limit: Int) -> Deferred<Maybe<Cursor<Site>>> {
return self.getSitesByFrecencyWithHistoryLimit(limit, includeIcon: true)
}
public func getSitesByFrecencyWithHistoryLimit(_ limit: Int, includeIcon: Bool) -> Deferred<Maybe<Cursor<Site>>> {
// Exclude redirect domains. Bug 1194852.
let (whereData, groupBy) = self.topSiteClauses()
return self.getFilteredSitesByFrecencyWithHistoryLimit(limit, bookmarksLimit: 0, groupClause: groupBy, whereData: whereData, includeIcon: includeIcon)
}
public func getTopSitesWithLimit(_ limit: Int) -> Deferred<Maybe<Cursor<Site>>> {
return self.db.runQuery(topSitesQuery, args: [limit], factory: SQLiteHistory.iconHistoryMetadataColumnFactory)
}
public func setTopSitesNeedsInvalidation() {
prefs.setBool(false, forKey: PrefsKeys.KeyTopSitesCacheIsValid)
}
public func updateTopSitesCacheIfInvalidated() -> Deferred<Maybe<Bool>> {
if prefs.boolForKey(PrefsKeys.KeyTopSitesCacheIsValid) ?? false {
return deferMaybe(false)
}
return refreshTopSitesCache() >>> always(true)
}
public func setTopSitesCacheSize(_ size: Int32) {
let oldValue = prefs.intForKey(PrefsKeys.KeyTopSitesCacheSize) ?? 0
if oldValue != size {
prefs.setInt(size, forKey: PrefsKeys.KeyTopSitesCacheSize)
setTopSitesNeedsInvalidation()
}
}
public func refreshTopSitesCache() -> Success {
let cacheSize = Int(prefs.intForKey(PrefsKeys.KeyTopSitesCacheSize) ?? 0)
return updateTopSitesCacheWithLimit(cacheSize)
}
//swiftlint:disable opening_brace
public func areTopSitesDirty(withLimit limit: Int) -> Deferred<Maybe<Bool>> {
let (whereData, groupBy) = self.topSiteClauses()
let (query, args) = self.filteredSitesByFrecencyQueryWithHistoryLimit(limit, bookmarksLimit: 0, groupClause: groupBy, whereData: whereData)
let cacheArgs: Args = [limit]
return accumulate([
{ self.db.runQuery(query, args: args, factory: SQLiteHistory.iconHistoryColumnFactory) },
{ self.db.runQuery(topSitesQuery, args: cacheArgs, factory: SQLiteHistory.iconHistoryColumnFactory) }
]).bind { results in
guard let results = results.successValue else {
// Something weird happened - default to dirty.
return deferMaybe(true)
}
let frecencyResults = results[0]
let cacheResults = results[1]
// Counts don't match? Exit early and say we're dirty.
if frecencyResults.count != cacheResults.count {
return deferMaybe(true)
}
var isDirty = false
// Check step-wise that the ordering and entries are the same
(0..<frecencyResults.count).forEach { index in
guard let frecencyID = frecencyResults[index]?.id,
let cacheID = cacheResults[index]?.id, frecencyID == cacheID else {
// It only takes one difference to make everything dirty
isDirty = true
return
}
}
return deferMaybe(isDirty)
}
}
//swiftlint:enable opening_brace
fileprivate func updateTopSitesCacheWithLimit(_ limit: Int) -> Success {
let (whereData, groupBy) = self.topSiteClauses()
let (query, args) = self.filteredSitesByFrecencyQueryWithHistoryLimit(limit, bookmarksLimit: 0, groupClause: groupBy, whereData: whereData)
// We must project, because we get bookmarks in these results.
let insertQuery = [
"INSERT INTO \(TableCachedTopSites)",
"SELECT historyID, url, title, guid, domain_id, domain,",
"localVisitDate, remoteVisitDate, localVisitCount, remoteVisitCount,",
"iconID, iconURL, iconDate, iconType, iconWidth, frecencies",
"FROM (", query, ")"
].joined(separator: " ")
return self.clearTopSitesCache() >>> {
return self.db.run(insertQuery, withArgs: args)
} >>> {
self.prefs.setBool(true, forKey: PrefsKeys.KeyTopSitesCacheIsValid)
return succeed()
}
}
public func clearTopSitesCache() -> Success {
let deleteQuery = "DELETE FROM \(TableCachedTopSites)"
return self.db.run(deleteQuery, withArgs: nil) >>> {
self.prefs.removeObjectForKey(PrefsKeys.KeyTopSitesCacheIsValid)
return succeed()
}
}
public func getSitesByFrecencyWithHistoryLimit(_ limit: Int, bookmarksLimit: Int, whereURLContains filter: String) -> Deferred<Maybe<Cursor<Site>>> {
return self.getFilteredSitesByFrecencyWithHistoryLimit(limit, bookmarksLimit: bookmarksLimit, whereURLContains: filter, includeIcon: true)
}
public func getSitesByFrecencyWithHistoryLimit(_ limit: Int, whereURLContains filter: String) -> Deferred<Maybe<Cursor<Site>>> {
return self.getFilteredSitesByFrecencyWithHistoryLimit(limit, bookmarksLimit: 0, whereURLContains: filter, includeIcon: true)
}
public func getSitesByLastVisit(_ limit: Int) -> Deferred<Maybe<Cursor<Site>>> {
return self.getFilteredSitesByVisitDateWithLimit(limit, whereURLContains: nil, includeIcon: true)
}
fileprivate func topSiteClauses() -> (String, String) {
let whereData = "(\(TableDomains).showOnTopSites IS 1) AND (\(TableDomains).domain NOT LIKE 'r.%') "
let groupBy = "GROUP BY domain_id "
return (whereData, groupBy)
}
fileprivate func computeWordsWithFilter(_ filter: String) -> [String] {
// Split filter on whitespace.
let words = filter.components(separatedBy: CharacterSet.whitespaces)
// Remove substrings and duplicates.
// TODO: this can probably be improved.
return words.enumerated().filter({ (index: Int, word: String) in
if word.isEmpty {
return false
}
for i in words.indices where i != index {
if words[i].range(of: word) != nil && (words[i].characters.count != word.characters.count || i < index) {
return false
}
}
return true
}).map({ $0.1 })
}
/**
* Take input like "foo bar" and a template fragment and produce output like
*
* ((x.y LIKE ?) OR (x.z LIKE ?)) AND ((x.y LIKE ?) OR (x.z LIKE ?))
*
* with args ["foo", "foo", "bar", "bar"].
*/
internal func computeWhereFragmentWithFilter(_ filter: String, perWordFragment: String, perWordArgs: (String) -> Args) -> (fragment: String, args: Args) {
precondition(!filter.isEmpty)
let words = computeWordsWithFilter(filter)
return self.computeWhereFragmentForWords(words, perWordFragment: perWordFragment, perWordArgs: perWordArgs)
}
internal func computeWhereFragmentForWords(_ words: [String], perWordFragment: String, perWordArgs: (String) -> Args) -> (fragment: String, args: Args) {
assert(!words.isEmpty)
let fragment = Array(repeating: perWordFragment, count: words.count).joined(separator: " AND ")
let args = words.flatMap(perWordArgs)
return (fragment, args)
}
fileprivate func getFilteredSitesByVisitDateWithLimit(_ limit: Int,
whereURLContains filter: String? = nil,
includeIcon: Bool = true) -> Deferred<Maybe<Cursor<Site>>> {
let args: Args?
let whereClause: String
if let filter = filter?.trimmingCharacters(in: CharacterSet.whitespaces), !filter.isEmpty {
let perWordFragment = "((\(TableHistory).url LIKE ?) OR (\(TableHistory).title LIKE ?))"
let perWordArgs: (String) -> Args = { ["%\($0)%", "%\($0)%"] }
let (filterFragment, filterArgs) = computeWhereFragmentWithFilter(filter, perWordFragment: perWordFragment, perWordArgs: perWordArgs)
// No deleted item has a URL, so there is no need to explicitly add that here.
whereClause = "WHERE (\(filterFragment))"
args = filterArgs
} else {
whereClause = "WHERE (\(TableHistory).is_deleted = 0)"
args = []
}
let ungroupedSQL = [
"SELECT \(TableHistory).id AS historyID, \(TableHistory).url AS url, title, guid, domain_id, domain,",
"COALESCE(max(case \(TableVisits).is_local when 1 then \(TableVisits).date else 0 end), 0) AS localVisitDate,",
"COALESCE(max(case \(TableVisits).is_local when 0 then \(TableVisits).date else 0 end), 0) AS remoteVisitDate,",
"COALESCE(count(\(TableVisits).is_local), 0) AS visitCount",
"FROM \(TableHistory)",
"INNER JOIN \(TableDomains) ON \(TableDomains).id = \(TableHistory).domain_id",
"INNER JOIN \(TableVisits) ON \(TableVisits).siteID = \(TableHistory).id",
whereClause,
"GROUP BY historyID",
].joined(separator: " ")
let historySQL = [
"SELECT historyID, url, title, guid, domain_id, domain, visitCount,",
"max(localVisitDate) AS localVisitDate,",
"max(remoteVisitDate) AS remoteVisitDate",
"FROM (", ungroupedSQL, ")",
"WHERE (visitCount > 0)", // Eliminate dead rows from coalescing.
"GROUP BY historyID",
"ORDER BY max(localVisitDate, remoteVisitDate) DESC",
"LIMIT \(limit)",
].joined(separator: " ")
if includeIcon {
// We select the history items then immediately join to get the largest icon.
// We do this so that we limit and filter *before* joining against icons.
let sql = [
"SELECT",
"historyID, url, title, guid, domain_id, domain,",
"localVisitDate, remoteVisitDate, visitCount, ",
"iconID, iconURL, iconDate, iconType, iconWidth ",
"FROM (", historySQL, ") LEFT OUTER JOIN ",
"view_history_id_favicon ON historyID = view_history_id_favicon.id",
].joined(separator: " ")
let factory = SQLiteHistory.iconHistoryColumnFactory
return db.runQuery(sql, args: args, factory: factory)
}
let factory = SQLiteHistory.basicHistoryColumnFactory
return db.runQuery(historySQL, args: args, factory: factory)
}
fileprivate func getFilteredSitesByFrecencyWithHistoryLimit(_ limit: Int,
bookmarksLimit: Int,
whereURLContains filter: String? = nil,
groupClause: String = "GROUP BY historyID ",
whereData: String? = nil,
includeIcon: Bool = true) -> Deferred<Maybe<Cursor<Site>>> {
let factory: (SDRow) -> Site
if includeIcon {
factory = SQLiteHistory.iconHistoryColumnFactory
} else {
factory = SQLiteHistory.basicHistoryColumnFactory
}
let (query, args) = filteredSitesByFrecencyQueryWithHistoryLimit(
limit,
bookmarksLimit: bookmarksLimit,
whereURLContains: filter,
groupClause: groupClause,
whereData: whereData,
includeIcon: includeIcon
)
return db.runQuery(query, args: args, factory: factory)
}
fileprivate func filteredSitesByFrecencyQueryWithHistoryLimit(_ historyLimit: Int,
bookmarksLimit: Int,
whereURLContains filter: String? = nil,
groupClause: String = "GROUP BY historyID ",
whereData: String? = nil,
includeIcon: Bool = true) -> (String, Args?) {
let includeBookmarks = bookmarksLimit > 0
let localFrecencySQL = getLocalFrecencySQL()
let remoteFrecencySQL = getRemoteFrecencySQL()
let sixMonthsInMicroseconds: UInt64 = 15_724_800_000_000 // 182 * 1000 * 1000 * 60 * 60 * 24
let sixMonthsAgo = Date.nowMicroseconds() - sixMonthsInMicroseconds
let args: Args
let whereClause: String
let whereFragment = (whereData == nil) ? "" : " AND (\(whereData!))"
if let filter = filter?.trimmingCharacters(in: CharacterSet.whitespaces), !filter.isEmpty {
let perWordFragment = "((url LIKE ?) OR (title LIKE ?))"
let perWordArgs: (String) -> Args = { ["%\($0)%", "%\($0)%"] }
let (filterFragment, filterArgs) = computeWhereFragmentWithFilter(filter, perWordFragment: perWordFragment, perWordArgs: perWordArgs)
// No deleted item has a URL, so there is no need to explicitly add that here.
whereClause = "WHERE (\(filterFragment))\(whereFragment)"
if includeBookmarks {
// We'll need them twice: once to filter history, and once to filter bookmarks.
args = filterArgs + filterArgs
} else {
args = filterArgs
}
} else {
whereClause = " WHERE (\(TableHistory).is_deleted = 0)\(whereFragment)"
args = []
}
// Innermost: grab history items and basic visit/domain metadata.
var ungroupedSQL =
"SELECT \(TableHistory).id AS historyID, \(TableHistory).url AS url, \(TableHistory).title AS title, \(TableHistory).guid AS guid, domain_id, domain" +
", COALESCE(max(case \(TableVisits).is_local when 1 then \(TableVisits).date else 0 end), 0) AS localVisitDate" +
", COALESCE(max(case \(TableVisits).is_local when 0 then \(TableVisits).date else 0 end), 0) AS remoteVisitDate" +
", COALESCE(sum(\(TableVisits).is_local), 0) AS localVisitCount" +
", COALESCE(sum(case \(TableVisits).is_local when 1 then 0 else 1 end), 0) AS remoteVisitCount" +
" FROM \(TableHistory) " +
"INNER JOIN \(TableDomains) ON \(TableDomains).id = \(TableHistory).domain_id " +
"INNER JOIN \(TableVisits) ON \(TableVisits).siteID = \(TableHistory).id "
if includeBookmarks {
ungroupedSQL.append("LEFT JOIN \(ViewAllBookmarks) on \(ViewAllBookmarks).url = \(TableHistory).url ")
}
ungroupedSQL.append(whereClause.replacingOccurrences(of: "url", with: "\(TableHistory).url").replacingOccurrences(of: "title", with: "\(TableHistory).title"))
if includeBookmarks {
ungroupedSQL.append(" AND \(ViewAllBookmarks).url IS NULL")
}
ungroupedSQL.append(" GROUP BY historyID")
// Next: limit to only those that have been visited at all within the last six months.
// (Don't do that in the innermost: we want to get the full count, even if some visits are older.)
// Discard all but the 1000 most frecent.
// Compute and return the frecency for all 1000 URLs.
let frecenciedSQL =
"SELECT *, (\(localFrecencySQL) + \(remoteFrecencySQL)) AS frecency" +
" FROM (" + ungroupedSQL + ")" +
" WHERE (" +
"((localVisitCount > 0) OR (remoteVisitCount > 0)) AND " + // Eliminate dead rows from coalescing.
"((localVisitDate > \(sixMonthsAgo)) OR (remoteVisitDate > \(sixMonthsAgo)))" + // Exclude really old items.
") ORDER BY frecency DESC" +
" LIMIT 1000" // Don't even look at a huge set. This avoids work.
// Next: merge by domain and sum frecency, ordering by that sum and reducing to a (typically much lower) limit.
// TODO: make is_bookmarked here accurate by joining against ViewAllBookmarks.
// TODO: ensure that the same URL doesn't appear twice in the list, either from duplicate
// bookmarks or from being in both bookmarks and history.
let historySQL = [
"SELECT historyID, url, title, guid, domain_id, domain,",
"max(localVisitDate) AS localVisitDate,",
"max(remoteVisitDate) AS remoteVisitDate,",
"sum(localVisitCount) AS localVisitCount,",
"sum(remoteVisitCount) AS remoteVisitCount,",
"sum(frecency) AS frecencies,",
"0 AS is_bookmarked",
"FROM (", frecenciedSQL, ") ",
groupClause,
"ORDER BY frecencies DESC",
"LIMIT \(historyLimit)",
].joined(separator: " ")
if includeIcon {
// We select the history items then immediately join to get the largest icon.
// We do this so that we limit and filter *before* joining against icons.
let historyWithIconsSQL = [
"SELECT historyID, url, title, guid, domain_id, domain,",
"localVisitDate, remoteVisitDate, localVisitCount, remoteVisitCount,",
"iconID, iconURL, iconDate, iconType, iconWidth, frecencies, is_bookmarked",
"FROM (", historySQL, ") LEFT OUTER JOIN",
"view_history_id_favicon ON historyID = view_history_id_favicon.id",
"ORDER BY frecencies DESC",
].joined(separator: " ")
if !includeBookmarks {
return (historyWithIconsSQL, args)
}
// Find bookmarks, too.
// This isn't required by the protocol we're implementing, but we're able to do
// it because we share storage with bookmarks.
// Note that this is part-duplicated below.
let bookmarksWithIconsSQL = [
"SELECT NULL AS historyID, url, title, guid, NULL AS domain_id, NULL AS domain,",
"visitDate AS localVisitDate, 0 AS remoteVisitDate, 0 AS localVisitCount,",
"0 AS remoteVisitCount,",
"iconID, iconURL, iconDate, iconType, iconWidth,",
"visitDate AS frecencies,", // Fake this for ordering purposes.
"1 AS is_bookmarked",
"FROM", ViewAwesomebarBookmarksWithIcons,
whereClause, // The columns match, so we can reuse this.
"GROUP BY url",
"ORDER BY visitDate DESC LIMIT \(bookmarksLimit)",
].joined(separator: " ")
let sql =
"SELECT * FROM (SELECT * FROM (\(historyWithIconsSQL)) UNION SELECT * FROM (\(bookmarksWithIconsSQL))) ORDER BY is_bookmarked DESC, frecencies DESC"
return (sql, args)
}
if !includeBookmarks {
return (historySQL, args)
}
// Note that this is part-duplicated above.
let bookmarksSQL = [
"SELECT NULL AS historyID, url, title, guid, NULL AS domain_id, NULL AS domain,",
"visitDate AS localVisitDate, 0 AS remoteVisitDate, 0 AS localVisitCount,",
"0 AS remoteVisitCount,",
"visitDate AS frecencies,", // Fake this for ordering purposes.
"1 AS is_bookmarked",
"FROM", ViewAwesomebarBookmarks,
whereClause, // The columns match, so we can reuse this.
"GROUP BY url",
"ORDER BY visitDate DESC LIMIT \(bookmarksLimit)",
].joined(separator: " ")
let allSQL = "SELECT * FROM (SELECT * FROM (\(historySQL)) UNION SELECT * FROM (\(bookmarksSQL))) ORDER BY is_bookmarked DESC, frecencies DESC"
return (allSQL, args)
}
}
extension SQLiteHistory: Favicons {
// These two getter functions are only exposed for testing purposes (and aren't part of the public interface).
func getFaviconsForURL(_ url: String) -> Deferred<Maybe<Cursor<Favicon?>>> {
let sql = "SELECT iconID AS id, iconURL AS url, iconDate AS date, iconType AS type, iconWidth AS width FROM " +
"\(ViewWidestFaviconsForSites), \(TableHistory) WHERE " +
"\(TableHistory).id = siteID AND \(TableHistory).url = ?"
let args: Args = [url]
return db.runQuery(sql, args: args, factory: SQLiteHistory.iconColumnFactory)
}
func getFaviconsForBookmarkedURL(_ url: String) -> Deferred<Maybe<Cursor<Favicon?>>> {
let sql =
"SELECT " +
" \(TableFavicons).id AS id" +
", \(TableFavicons).url AS url" +
", \(TableFavicons).date AS date" +
", \(TableFavicons).type AS type" +
", \(TableFavicons).width AS width" +
" FROM \(TableFavicons), \(ViewBookmarksLocalOnMirror) AS bm" +
" WHERE bm.faviconID = \(TableFavicons).id AND bm.bmkUri IS ?"
let args: Args = [url]
return db.runQuery(sql, args: args, factory: SQLiteHistory.iconColumnFactory)
}
public func getSitesForURLs(_ urls: [String]) -> Deferred<Maybe<Cursor<Site?>>> {
let inExpression = urls.joined(separator: "\",\"")
let sql = "SELECT \(TableHistory).id AS historyID, \(TableHistory).url AS url, title, guid, iconID, iconURL, iconDate, iconType, iconWidth FROM " +
"\(ViewWidestFaviconsForSites), \(TableHistory) WHERE " +
"\(TableHistory).id = siteID AND \(TableHistory).url IN (\"\(inExpression)\")"
let args: Args = []
return db.runQuery(sql, args: args, factory: SQLiteHistory.iconHistoryColumnFactory)
}
public func clearAllFavicons() -> Success {
var err: NSError? = nil
let _ = db.withConnection(&err) { (conn, err: inout NSError?) -> Int in
err = conn.executeChange("DELETE FROM \(TableFaviconSites)")
if err == nil {
err = conn.executeChange("DELETE FROM \(TableFavicons)")
}
return 1
}
return failOrSucceed(err, op: "Clear favicons")
}
public func addFavicon(_ icon: Favicon) -> Deferred<Maybe<Int>> {
var err: NSError?
let res = db.withConnection(&err) { (conn, err: inout NSError?) -> Int in
// Blind! We don't see failure here.
let id = self.favicons.insertOrUpdate(conn, obj: icon)
return id ?? 0
}
if err == nil {
return deferMaybe(res)
}
return deferMaybe(DatabaseError(err: err))
}
/**
* This method assumes that the site has already been recorded
* in the history table.
*/
public func addFavicon(_ icon: Favicon, forSite site: Site) -> Deferred<Maybe<Int>> {
if Logger.logPII {
log.verbose("Adding favicon \(icon.url) for site \(site.url).")
}
func doChange(_ query: String, args: Args?) -> Deferred<Maybe<Int>> {
var err: NSError?
let res = db.withConnection(&err) { (conn, err: inout NSError?) -> Int in
// Blind! We don't see failure here.
let id = self.favicons.insertOrUpdate(conn, obj: icon)
// Now set up the mapping.
err = conn.executeChange(query, withArgs: args)
if let err = err {
log.error("Got error adding icon: \(err).")
return 0
}
// Try to update the favicon ID column in each bookmarks table. There can be
// multiple bookmarks with a particular URI, and a mirror bookmark can be
// locally changed, so either or both of these statements can update multiple rows.
if let id = id {
let _ = conn.executeChange("UPDATE \(TableBookmarksLocal) SET faviconID = ? WHERE bmkUri = ?", withArgs: [id, site.url])
let _ = conn.executeChange("UPDATE \(TableBookmarksMirror) SET faviconID = ? WHERE bmkUri = ?", withArgs: [id, site.url])
}
return id ?? 0
}
if res == 0 {
return deferMaybe(DatabaseError(err: err))
}
return deferMaybe(icon.id!)
}
let siteSubselect = "(SELECT id FROM \(TableHistory) WHERE url = ?)"
let iconSubselect = "(SELECT id FROM \(TableFavicons) WHERE url = ?)"
let insertOrIgnore = "INSERT OR IGNORE INTO \(TableFaviconSites)(siteID, faviconID) VALUES "
if let iconID = icon.id {
// Easy!
if let siteID = site.id {
// So easy!
let args: Args? = [siteID, iconID]
return doChange("\(insertOrIgnore) (?, ?)", args: args)
}
// Nearly easy.
let args: Args? = [site.url, iconID]
return doChange("\(insertOrIgnore) (\(siteSubselect), ?)", args: args)
}
// Sigh.
if let siteID = site.id {
let args: Args? = [siteID, icon.url]
return doChange("\(insertOrIgnore) (?, \(iconSubselect))", args: args)
}
// The worst.
let args: Args? = [site.url, icon.url]
return doChange("\(insertOrIgnore) (\(siteSubselect), \(iconSubselect))", args: args)
}
}
extension SQLiteHistory: SyncableHistory {
/**
* TODO:
* When we replace an existing row, we want to create a deleted row with the old
* GUID and switch the new one in -- if the old record has escaped to a Sync server,
* we want to delete it so that we don't have two records with the same URL on the server.
* We will know if it's been uploaded because it'll have a server_modified time.
*/
public func ensurePlaceWithURL(_ url: String, hasGUID guid: GUID) -> Success {
let args: Args = [guid, url, guid]
// The additional IS NOT is to ensure that we don't do a write for no reason.
return db.run("UPDATE \(TableHistory) SET guid = ? WHERE url = ? AND guid IS NOT ?", withArgs: args)
}
public func deleteByGUID(_ guid: GUID, deletedAt: Timestamp) -> Success {
let args: Args = [guid]
// This relies on ON DELETE CASCADE to remove visits.
return db.run("DELETE FROM \(TableHistory) WHERE guid = ?", withArgs: args)
}
// Fails on non-existence.
fileprivate func getSiteIDForGUID(_ guid: GUID) -> Deferred<Maybe<Int>> {
let args: Args = [guid]
let query = "SELECT id FROM history WHERE guid = ?"
let factory: (SDRow) -> Int = { return $0["id"] as! Int }
return db.runQuery(query, args: args, factory: factory)
>>== { cursor in
if cursor.count == 0 {
return deferMaybe(NoSuchRecordError(guid: guid))
}
return deferMaybe(cursor[0]!)
}
}
public func storeRemoteVisits(_ visits: [Visit], forGUID guid: GUID) -> Success {
return self.getSiteIDForGUID(guid)
>>== { (siteID: Int) -> Success in
let visitArgs = visits.map { (visit: Visit) -> Args in
let realDate = visit.date
let isLocal = 0
let args: Args = [siteID, realDate, visit.type.rawValue, isLocal]
return args
}
// Magic happens here. The INSERT OR IGNORE relies on the multi-column uniqueness
// constraint on `visits`: we allow only one row for (siteID, date, type), so if a
// local visit already exists, this silently keeps it. End result? Any new remote
// visits are added with only one query, keeping any existing rows.
return self.db.bulkInsert(TableVisits, op: .InsertOrIgnore, columns: ["siteID", "date", "type", "is_local"], values: visitArgs)
}
}
fileprivate struct HistoryMetadata {
let id: Int
let serverModified: Timestamp?
let localModified: Timestamp?
let isDeleted: Bool
let shouldUpload: Bool
let title: String
}
fileprivate func metadataForGUID(_ guid: GUID) -> Deferred<Maybe<HistoryMetadata?>> {
let select = "SELECT id, server_modified, local_modified, is_deleted, should_upload, title FROM \(TableHistory) WHERE guid = ?"
let args: Args = [guid]
let factory = { (row: SDRow) -> HistoryMetadata in
return HistoryMetadata(
id: row["id"] as! Int,
serverModified: row.getTimestamp("server_modified"),
localModified: row.getTimestamp("local_modified"),
isDeleted: row.getBoolean("is_deleted"),
shouldUpload: row.getBoolean("should_upload"),
title: row["title"] as! String
)
}
return db.runQuery(select, args: args, factory: factory) >>== { cursor in
return deferMaybe(cursor[0])
}
}
public func insertOrUpdatePlace(_ place: Place, modified: Timestamp) -> Deferred<Maybe<GUID>> {
// One of these things will be true here.
// 0. The item is new.
// (a) We have a local place with the same URL but a different GUID.
// (b) We have never visited this place locally.
// In either case, reconcile and proceed.
// 1. The remote place is not modified when compared to our mirror of it. This
// can occur when we redownload after a partial failure.
// (a) And it's not modified locally, either. Nothing to do. Ideally we
// will short-circuit so we don't need to update visits. (TODO)
// (b) It's modified locally. Don't overwrite anything; let the upload happen.
// 2. The remote place is modified (either title or visits).
// (a) And it's not locally modified. Update the local entry.
// (b) And it's locally modified. Preserve the title of whichever was modified last.
// N.B., this is the only instance where we compare two timestamps to see
// which one wins.
// We use this throughout.
let serverModified = modified
// Check to see if our modified time is unchanged, if the record exists locally, etc.
let insertWithMetadata = { (metadata: HistoryMetadata?) -> Deferred<Maybe<GUID>> in
if let metadata = metadata {
// The item exists locally (perhaps originally with a different GUID).
if metadata.serverModified == modified {
log.verbose("History item \(place.guid) is unchanged; skipping insert-or-update.")
return deferMaybe(place.guid)
}
// Otherwise, the server record must have changed since we last saw it.
if metadata.shouldUpload {
// Uh oh, it changed locally.
// This might well just be a visit change, but we can't tell. Usually this conflict is harmless.
log.debug("Warning: history item \(place.guid) changed both locally and remotely. Comparing timestamps from different clocks!")
if metadata.localModified! > modified {
log.debug("Local changes overriding remote.")
// Update server modified time only. (Though it'll be overwritten again after a successful upload.)
let update = "UPDATE \(TableHistory) SET server_modified = ? WHERE id = ?"
let args: Args = [serverModified, metadata.id]
return self.db.run(update, withArgs: args) >>> always(place.guid)
}
log.verbose("Remote changes overriding local.")
// Fall through.
}
// The record didn't change locally. Update it.
log.verbose("Updating local history item for guid \(place.guid).")
let update = "UPDATE \(TableHistory) SET title = ?, server_modified = ?, is_deleted = 0 WHERE id = ?"
let args: Args = [place.title, serverModified, metadata.id]
return self.db.run(update, withArgs: args) >>> always(place.guid)
}
// The record doesn't exist locally. Insert it.
log.verbose("Inserting remote history item for guid \(place.guid).")
if let host = place.url.asURL?.normalizedHost {
if Logger.logPII {
log.debug("Inserting: \(place.url).")
}
let insertDomain = "INSERT OR IGNORE INTO \(TableDomains) (domain) VALUES (?)"
let insertHistory = "INSERT INTO \(TableHistory) (guid, url, title, server_modified, is_deleted, should_upload, domain_id) " +
"SELECT ?, ?, ?, ?, 0, 0, id FROM \(TableDomains) where domain = ?"
return self.db.run([
(insertDomain, [host]),
(insertHistory, [place.guid, place.url, place.title, serverModified, host])
]) >>> always(place.guid)
} else {
// This is a URL with no domain. Insert it directly.
if Logger.logPII {
log.debug("Inserting: \(place.url) with no domain.")
}
let insertHistory = "INSERT INTO \(TableHistory) (guid, url, title, server_modified, is_deleted, should_upload, domain_id) " +
"VALUES (?, ?, ?, ?, 0, 0, NULL)"
return self.db.run([
(insertHistory, [place.guid, place.url, place.title, serverModified])
]) >>> always(place.guid)
}
}
// Make sure that we only need to compare GUIDs by pre-merging on URL.
return self.ensurePlaceWithURL(place.url, hasGUID: place.guid)
>>> { self.metadataForGUID(place.guid) >>== insertWithMetadata }
}
public func getDeletedHistoryToUpload() -> Deferred<Maybe<[GUID]>> {
// Use the partial index on should_upload to make this nice and quick.
let sql = "SELECT guid FROM \(TableHistory) WHERE \(TableHistory).should_upload = 1 AND \(TableHistory).is_deleted = 1"
let f: (SDRow) -> String = { $0["guid"] as! String }
return self.db.runQuery(sql, args: nil, factory: f) >>== { deferMaybe($0.asArray()) }
}
public func getModifiedHistoryToUpload() -> Deferred<Maybe<[(Place, [Visit])]>> {
// What we want to do: find all items flagged for update, selecting some number of their
// visits alongside.
//
// A difficulty here: we don't want to fetch *all* visits, only some number of the most recent.
// (It's not enough to only get new ones, because the server record should contain more.)
//
// That's the greatest-N-per-group problem in SQL. Please read and understand the solution
// to this (particularly how the LEFT OUTER JOIN/HAVING clause works) before changing this query!
//
// We can do this in a single query, rather than the N+1 that desktop takes.
// We then need to flatten the cursor. We do that by collecting
// places as a side-effect of the factory, producing visits as a result, and merging in memory.
let args: Args = [20] // Maximum number of visits to retrieve.
// Exclude 'unknown' visits, because they're not syncable.
let filter = "history.should_upload = 1 AND v1.type IS NOT 0"
let sql =
"SELECT " +
"history.id AS siteID, history.guid AS guid, history.url AS url, history.title AS title, " +
"v1.siteID AS siteID, v1.date AS visitDate, v1.type AS visitType " +
"FROM " +
"visits AS v1 " +
"JOIN history ON history.id = v1.siteID AND \(filter) " +
"LEFT OUTER JOIN " +
"visits AS v2 " +
"ON v1.siteID = v2.siteID AND v1.date < v2.date " +
"GROUP BY v1.date " +
"HAVING COUNT(*) < ? " +
"ORDER BY v1.siteID, v1.date DESC"
var places = [Int: Place]()
var visits = [Int: [Visit]]()
// Add a place to the accumulator, prepare to accumulate visits, return the ID.
let ensurePlace: (SDRow) -> Int = { row in
let id = row["siteID"] as! Int
if places[id] == nil {
let guid = row["guid"] as! String
let url = row["url"] as! String
let title = row["title"] as! String
places[id] = Place(guid: guid, url: url, title: title)
visits[id] = Array()
}
return id
}
// Store the place and the visit.
let factory: (SDRow) -> Int = { row in
let date = row.getTimestamp("visitDate")!
let type = VisitType(rawValue: row["visitType"] as! Int)!
let visit = Visit(date: date, type: type)
let id = ensurePlace(row)
visits[id]?.append(visit)
return id
}
return db.runQuery(sql, args: args, factory: factory)
>>== { c in
// Consume every row, with the side effect of populating the places
// and visit accumulators.
var ids = Set<Int>()
for row in c {
// Collect every ID first, so that we're guaranteed to have
// fully populated the visit lists, and we don't have to
// worry about only collecting each place once.
ids.insert(row!)
}
// Now we're done with the cursor. Close it.
c.close()
// Now collect the return value.
return deferMaybe(ids.map { return (places[$0]!, visits[$0]!) })
}
}
public func markAsDeleted(_ guids: [GUID]) -> Success {
if guids.isEmpty {
return succeed()
}
log.debug("Wiping \(guids.count) deleted GUIDs.")
return self.db.run(chunk(guids, by: BrowserDB.MaxVariableNumber).flatMap(markAsDeletedStatementForGUIDs))
}
fileprivate func markAsDeletedStatementForGUIDs(_ guids: ArraySlice<String>) -> (String, Args?) {
// We deliberately don't limit this to records marked as should_upload, just
// in case a coding error leaves records with is_deleted=1 but not flagged for
// upload -- this will catch those and throw them away.
let inClause = BrowserDB.varlist(guids.count)
let sql = "DELETE FROM \(TableHistory) WHERE is_deleted = 1 AND guid IN \(inClause)"
let args: Args = guids.map { $0 }
return (sql, args)
}
public func markAsSynchronized(_ guids: [GUID], modified: Timestamp) -> Deferred<Maybe<Timestamp>> {
if guids.isEmpty {
return deferMaybe(modified)
}
log.debug("Marking \(guids.count) GUIDs as synchronized. Returning timestamp \(modified).")
return self.db.run(chunk(guids, by: BrowserDB.MaxVariableNumber).flatMap { chunk in
return markAsSynchronizedStatementForGUIDs(chunk, modified: modified)
}) >>> always(modified)
}
fileprivate func markAsSynchronizedStatementForGUIDs(_ guids: ArraySlice<String>, modified: Timestamp) -> (String, Args?) {
let inClause = BrowserDB.varlist(guids.count)
let sql =
"UPDATE \(TableHistory) SET " +
"should_upload = 0, server_modified = \(modified) " +
"WHERE guid IN \(inClause)"
let args: Args = guids.map { $0 }
return (sql, args)
}
public func doneApplyingRecordsAfterDownload() -> Success {
self.db.checkpoint()
return succeed()
}
public func doneUpdatingMetadataAfterUpload() -> Success {
self.db.checkpoint()
return succeed()
}
}
extension SQLiteHistory {
// Returns a deferred `true` if there are rows in the DB that have a server_modified time.
// Because we clear this when we reset or remove the account, and never set server_modified
// without syncing, the presence of matching rows directly indicates that a deletion
// would be synced to the server.
public func hasSyncedHistory() -> Deferred<Maybe<Bool>> {
return self.db.queryReturnsResults("SELECT 1 FROM \(TableHistory) WHERE server_modified IS NOT NULL LIMIT 1")
}
}
extension SQLiteHistory: ResettableSyncStorage {
// We don't drop deletions when we reset -- we might need to upload a deleted item
// that never made it to the server.
public func resetClient() -> Success {
let flag = "UPDATE \(TableHistory) SET should_upload = 1, server_modified = NULL"
return self.db.run(flag)
}
}
extension SQLiteHistory: AccountRemovalDelegate {
public func onRemovedAccount() -> Success {
log.info("Clearing history metadata and deleted items after account removal.")
let discard = "DELETE FROM \(TableHistory) WHERE is_deleted = 1"
return self.db.run(discard) >>> self.resetClient
}
}
|
mpl-2.0
|
de5537395a2941b0b109a083711c4f21
| 44.534987 | 259 | 0.592231 | 4.782233 | false | false | false | false |
kitasuke/TwitterClientDemo
|
TwitterClientDemo/Classes/Stores/AlertStore.swift
|
1
|
2426
|
//
// AlertStore.swift
// TwitterClientDemo
//
// Created by Yusuke Kita on 5/20/15.
// Copyright (c) 2015 kitasuke. All rights reserved.
//
import Foundation
import UIKit
import Accounts
enum LoginAlert {
case Success(name: String, completionHandler: () -> Void)
case Failure
case Account(accounts: [ACAccount], completionHandler: (account: ACAccount) -> Void)
var alertController: UIAlertController {
let alertController: UIAlertController
let alertAction: UIAlertAction
switch self {
case .Success(let name, let completionHandler):
alertController = UIAlertController(title: "Success", message: "Welcome \(name)!", preferredStyle: .Alert)
alertAction = UIAlertAction(title: "OK", style: .Default, handler: { (action: UIAlertAction!) -> Void in
completionHandler()
})
case .Failure:
alertController = UIAlertController(title: "Error", message: "Please configure your twitter account in Setting", preferredStyle: .Alert)
alertAction = UIAlertAction(title: "OK", style: .Default, handler: { (action: UIAlertAction!) -> Void in
})
case .Account(let accounts, let completionHandler):
alertController = UIAlertController(title: "Twitter accounts", message: "Please choose your account", preferredStyle: .ActionSheet)
for account in accounts {
alertController.addAction(UIAlertAction(title: account.username, style: .Default, handler: { (action: UIAlertAction!) -> Void in
completionHandler(account: account)
}))
}
alertAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
}
alertController.addAction(alertAction)
return alertController
}
}
enum ConnectionAlert {
case Error(message: String)
var alertController: UIAlertController {
let alertController: UIAlertController
let alertAction: UIAlertAction
switch self {
case .Error(let message):
alertController = UIAlertController(title: "Error", message: message, preferredStyle: .Alert)
alertAction = UIAlertAction(title: "OK", style: .Default, handler: { (action: UIAlertAction!) -> Void in
})
}
alertController.addAction(alertAction)
return alertController
}
}
|
mit
|
b8aa563c1a8b7d90b97b642bba7538d7
| 39.45 | 148 | 0.647156 | 5.239741 | false | false | false | false |
Derek-Chiu/Mr-Ride-iOS
|
Mr-Ride-iOS/SideMenuTableViewController.swift
|
1
|
3958
|
//
// SideMenuTableViewController.swift
// Mr-Ride-iOS
//
// Created by Derek on 5/23/16.
// Copyright © 2016 AppWorks School Derek. All rights reserved.
//
import UIKit
enum CurrentSelected: Int {
case HomePage
case HistoryPage
}
class SideMenuTableViewController: UITableViewController {
var tableArray = [String]()
var currentIndexPath: NSIndexPath = NSIndexPath(forRow: 0, inSection: 0)
var currentSelected = CurrentSelected.HomePage
enum PageSelected: Int {
case HomePage
case HistroyPage
case MapPage
}
override func viewDidLoad() {
super.viewDidLoad()
tableArray = ["Home", "History", "Map"]
setupNavigationBarAndTableView()
tableView.bounces = false
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
tableView.selectRowAtIndexPath(currentIndexPath, animated: true, scrollPosition: .None)
TrackingActionHelper.getInstance().trackingAction(viewName: "menu", action: "view_in_menu")
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CellTableViewCell
cell.label.text = tableArray[indexPath.row]
return cell
}
func setupNavigationBarAndTableView() {
tableView.backgroundColor = UIColor.mrDarkSlateBlueColor()
tableView.separatorStyle = UITableViewCellSeparatorStyle.None
let shadowImg = UIImage()
navigationController?.navigationBar.shadowImage = shadowImg
navigationController?.navigationBar.setBackgroundImage(shadowImg, forBarMetrics: UIBarMetrics.Default)
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
currentIndexPath = indexPath
if let page = PageSelected(rawValue: indexPath.row) {
switch page {
case .HomePage:
TrackingActionHelper.getInstance().trackingAction(viewName: "menu", action: "select_ride_in_menu")
let homeNavigationController = storyboard?.instantiateViewControllerWithIdentifier("HomeNavigationController") as! UINavigationController
let segue = SWRevealViewControllerSeguePushController.init(identifier: nil, source: self, destination: homeNavigationController)
segue.perform()
case .HistroyPage:
TrackingActionHelper.getInstance().trackingAction(viewName: "menu", action: "select_history_in_menu")
let historyNavigationController = storyboard?.instantiateViewControllerWithIdentifier("HistoryNavigationController") as! UINavigationController
let segue = SWRevealViewControllerSeguePushController.init(identifier: nil, source: self, destination: historyNavigationController)
segue.perform()
case .MapPage:
TrackingActionHelper.getInstance().trackingAction(viewName: "menu", action: "select_map_in_menu")
let informationNavigationController = storyboard?.instantiateViewControllerWithIdentifier("InformationNavigationController") as! UINavigationController
let segue = SWRevealViewControllerSeguePushController.init(identifier: nil, source: self, destination: informationNavigationController)
segue.perform()
}
} else {
print("no such page")
}
}
}
|
mit
|
fa44dbc351a506d82e70a711a6245530
| 38.969697 | 167 | 0.677028 | 5.90597 | false | false | false | false |
MartinOSix/DemoKit
|
dSwift/SwiftSyntaxDemo/SwiftSyntaxDemo/ViewController_AnyObject.swift
|
1
|
2731
|
//
// ViewController_AnyObject.swift
// SwiftSyntaxDemo
//
// Created by runo on 16/12/27.
// Copyright © 2016年 com.runo. All rights reserved.
//
import UIKit
class Movie {
var name:String = ""
var director:String = ""
init(name:String ,director:String) {
self.name = name
self.director = director
}
}
class Human {
var name:String = ""
init(name :String) {
self.name = name
}
}
class Female: Human {
var sex = ""
override init(name :String) {
super.init(name: name)
self.sex = "女性"
}
}
class Male: Human {
var sex = ""
override init(name :String) {
super.init(name: name)
self.sex = "男性"
}
}
class ViewController_AnyObject: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//AnyObject 可以代表任何class类型实例
//Any可以表示任何类型,除了方法类型
let someObjects:[AnyObject] = [
Movie.init(name: "2010", director: "stanley"),
Movie.init(name: "Moon", director: "Duncan"),
Movie.init(name: "Alien", director: "Ridley")
]
for obj in someObjects{
let movie = obj as! Movie
print("Movie \(movie.name) ,dir \(movie.director)")
}
var things = [Any]()
things.append(0)
things.append(0.0)
things.append(42)
things.append("hello")
things.append(Movie.init(name: "name", director: "ivan Reitman"))
print(things)
for thing in things {
switch thing {
case 0 as Int:
print("zero as an Int")
case 0 as Double :
print("zero as a Double")
case let someInt as Int:
print("integer value of \(someInt)")
case let moview as Movie:
print("a movie called \(moview.name)")
default:
print("unknow object")
}
}
let mans = [
Male.init(name: "haha"),
Female.init(name: "songzhixiao"),
Male.init(name: "guangshu")
]
for man in mans {
if man is Male {
print((man as! Male).sex)
}
if let val = man as? Female {
print(val.name)
}
switch man {
case let c1 as Male:
print(c1.name)
case let c2 as Female:
print(c2.name)
default:
print("error")
}
}
}
}
|
apache-2.0
|
318dff217ec03ccbde9f34c657e03d63
| 19.227273 | 73 | 0.472659 | 4.204724 | false | false | false | false |
beeth0ven/BNKit
|
BNKit/Source/CoreGraphics+/CoreGraphics+.swift
|
1
|
2418
|
//
// CoreGraphics+.swift
// PhotoMap
//
// Created by luojie on 16/8/10.
//
//
import CoreGraphics
extension CGSize {
public static var thumbnailImageSize: CGSize {
return CGSize(width: 128, height: 128)
}
public static var profileImagelSize: CGSize {
return CGSize(width: 384, height: 384)
}
}
extension CGRect {
public init(center: CGPoint, size: CGSize) {
self.init(origin: .zero, size: size)
self.center = center
}
public var center: CGPoint {
get { return CGPoint(x: self.midX, y: self.midY) }
set {
origin.x = newValue.x - size.width/2
origin.y = newValue.y - size.height/2
}
}
}
public func *(size: CGSize, scale: CGFloat) -> CGSize {
return CGSize(width: size.width * scale, height: size.height * scale)
}
public func + (left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x + right.x, y: left.y + right.y)
}
public func += (left: inout CGPoint, right: CGPoint) {
left = left + right
}
public func - (left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x - right.x, y: left.y - right.y)
}
public func -= (left: inout CGPoint, right: CGPoint) {
left = left - right
}
public func * (left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x * right.x, y: left.y * right.y)
}
public func *= (left: inout CGPoint, right: CGPoint) {
left = left * right
}
public func * (point: CGPoint, scalar: CGFloat) -> CGPoint {
return CGPoint(x: point.x * scalar, y: point.y * scalar)
}
public func *= (point: inout CGPoint, scalar: CGFloat) {
point = point * scalar
}
public func / (left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x / right.x, y: left.y / right.y)
}
public func /= (left: inout CGPoint, right: CGPoint) {
left = left / right
}
public func / (point: CGPoint, scalar: CGFloat) -> CGPoint {
return CGPoint(x: point.x / scalar, y: point.y / scalar)
}
public func /= (point: inout CGPoint, scalar: CGFloat) {
point = point / scalar
}
extension CGFloat {
public static func random() -> CGFloat {
return CGFloat(Float(arc4random()) / Float(UInt32.max))
}
public static func random(min: CGFloat, max: CGFloat) -> CGFloat {
assert(min < max)
return CGFloat.random() * (max - min) + min
}
}
|
mit
|
449e4c6e307f6acdc251550b06a95aae
| 22.940594 | 73 | 0.607527 | 3.444444 | false | false | false | false |
darren90/rubbish
|
Example-Swift/SwiftExample/FullCalendarController.swift
|
1
|
5047
|
//
// FullCalendarController.swift
// SwiftExample
//
// Created by Fengtf on 2017/1/7.
// Copyright © 2017年 wenchao. All rights reserved.
//
import UIKit
import EventKit
class FullCalendarController: UIViewController {
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
initLunarCanlendar()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: --- 属性
lazy var calendar:FSCalendar = FSCalendar()
lazy var lunarCanlendar = Calendar(identifier: .chinese) //农历
var lunarChars:[String] = [String]()
var dateFormatter:DateFormatter = DateFormatter()
var showsLunar:Bool = true //默认显示农历
var showsEvents:Bool = false
var minimumDate:Date = Date()
var maximumDate:Date = Date()
var events:[EKEvent]?
// var lunarChars:[String]?
// var cache:NSCache<EKEvent, Date>?
override func viewDidLoad() {
super.viewDidLoad()
dateFormatter.dateFormat = "yyyy-MM-dd"
minimumDate = getDate(dateStr: "2016-02-03")
maximumDate = getDate(dateStr: "2018-04-10")
loadCalendar()
initUI()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// self.cache?.removeAllObjects()
}
func getDate(dateStr:String) -> Date{
let fm = DateFormatter()
fm.dateFormat = "yyyy-MM-dd"
let date = fm.date(from: dateStr)
return date!
}
}
extension FullCalendarController {
func initCalendar(){
}
//MARK:-- 农
func initLunarCanlendar(){
lunarCanlendar.locale = Locale(identifier: "zh-CN");
lunarChars = ["初一","初二","初三","初四","初五","初六","初七","初八","初九","初十","十一","十二","十三","十四","十五","十六","十七","十八","十九","二十","二一","二二","二三","二四","二五","二六","二七","二八","二九","三十"];
}
func loadCalendar(){
view.addSubview(calendar)
calendar.frame = CGRect(x: 0, y: 64, width: view.frame.width, height: view.frame.height-64)
calendar.backgroundColor = UIColor.white
calendar.delegate = self
calendar.dataSource = self
calendar.pagingEnabled = false
calendar.allowsMultipleSelection = true
calendar.firstWeekday = 2
calendar.allowsMultipleSelection = false
calendar.placeholderType = .fillHeadTail
calendar.appearance.caseOptions = [ .headerUsesUpperCase , .weekdayUsesUpperCase]
view.addSubview(calendar)
}
func initUI(){
let todayItem = UIBarButtonItem(title: "Today", style: .plain, target: self, action: #selector(self.todayItemClicked))
let lunarItem = UIBarButtonItem(title: "Lunar", style: .plain, target: self, action: #selector(self.lunarItemClicked))
let eventItem = UIBarButtonItem(title: "Event", style: .plain, target: self, action: #selector(self.eventItemClicked))
navigationItem.rightBarButtonItems = [todayItem,lunarItem,eventItem]
}
//MARK: --- 回到今天
func todayItemClicked(){
print("now:\(Date())")
calendar.setCurrentPage(Date(), animated: false)
}
//MARK: --- 显示农历
func lunarItemClicked(){
showsLunar = !showsLunar
calendar.reloadData()
}
//MARK: --- 回到事件
func eventItemClicked(){
showsEvents = !showsEvents
calendar .reloadData()
}
}
extension FullCalendarController : FSCalendarDataSource,FSCalendarDelegate,FSCalendarDelegateAppearance{
//MARK: --- FSCalendarDataSource
func minimumDate(for calendar: FSCalendar) -> Date {
return self.minimumDate
}
func maximumDate(for calendar: FSCalendar) -> Date {
return self.maximumDate
}
func calendar(_ calendar: FSCalendar, subtitleFor date: Date) -> String? {
// if showsEvents {
//
// }
if showsLunar {
let day = lunarCanlendar.component(.day, from: date)
return lunarChars[day - 1]
}
return nil
}
//MARK: --- FSCalendarDelegate
func calendar(_ calendar: FSCalendar, didDeselect date: Date, at monthPosition: FSCalendarMonthPosition) {
print("did select :\(dateFormatter.string(from: date))")
}
func calendarCurrentPageDidChange(_ calendar: FSCalendar) {
print("did change page :\(dateFormatter.string(from: calendar.currentPage))")
}
// func calendar(_ calendar: FSCalendar, numberOfEventsFor date: Date) -> Int {
//
// }
//MARK: --- FSCalendarDelegateAppearance
}
//MARK: --- 方法补充 -- Private methods
extension FullCalendarController {
// func eventsForDate:(date:Date) -> [EKEvent]? {
// let evs = cache?.object(forKey: date)
//// if evs {
//
//// }
//
// return nil
// }
}
|
apache-2.0
|
2dc7a5863c7454b02358d6dbee87eb35
| 21.237443 | 173 | 0.627105 | 4.004934 | false | false | false | false |
joncottonskyuk/SwiftValidation
|
SwiftValidation/ComparableValidator.swift
|
1
|
1399
|
//
// ComparableValidator.swift
// SwiftValidation
//
// Created by Jon on 01/06/2016.
// Copyright © 2016 joncotton. All rights reserved.
//
import Foundation
public enum ComparableValidator<T: Comparable>: Validator {
case minimumValue(T)
case maximumValue(T)
case range(T, T)
public func isValid(value: T) throws -> Bool {
var min: T?
var max: T?
switch self {
case .minimumValue(let inMin):
min = inMin
case .maximumValue(let inMax):
max = inMax
case .range(let inMin, let inMax):
min = Swift.min(inMin, inMax)
max = Swift.max(inMin, inMax)
}
if let min = min {
guard value >= min else {
throw ComparableValidationError.valueIsBelowMinimumBounds(min)
}
}
if let max = max {
guard value <= max else {
throw ComparableValidationError.valueIsAboveMaximumBounds(max)
}
}
return true
}
}
extension Int: Validateable {
public typealias ValidatorType = ComparableValidator<Int>
}
extension Double: Validateable {
public typealias ValidatorType = ComparableValidator<Double>
}
extension Float: Validateable {
public typealias ValidatorType = ComparableValidator<Float>
}
|
apache-2.0
|
263f563f64e259b7e5905c3b9bdb6b65
| 23.12069 | 78 | 0.58083 | 4.509677 | false | false | false | false |
ktatroe/MPA-Horatio
|
HoratioDemo/HoratioDemo/Classes/AppConfiguration.swift
|
2
|
10254
|
//
// Copyright © 2016 Kevin Tatroe. All rights reserved.
// See LICENSE.txt for this sample’s licensing information
import Foundation
import UIKit
/**
A container for various global configuration values, such as behaviors, endpoints,
and so on. Implements and is registered as several providers, including the
`ServiceEndpointProvider`, as well as on its own.
*/
class AppConfiguration: ServiceEndpointProvider, BehaviorProvider, WebviewURLProvider, FeatureProvider {
struct Values {
static let ReleaseLastUpdated = "last_updated"
static let LatestVersion = "latest_version"
static let MandatoryVersion = "mandatory_version"
static let AppStoreURL = "appstore_url"
static let AcademicYear = "academic_year"
static let FeedbackEmailAddress = "feedback_email"
static let ActiveSportIdentifier = "active_sport_identifier"
static let ProductionDFPNetwork = "production_dfp"
}
struct Endpoints {
static let TeamLogo = "schoollogo"
}
struct WebViews {
static let TermsOfUse = "terms"
static let PrivacyPolicy = "privacy_policy"
static let FAQ = "FAQ"
}
// MARK: - Initialization
init() {
self.subject = RandomFeatureSubject()
self.features[FeatureCatalog.UseLocalEnvironments] = StaticFeature(identifier: FeatureCatalog.UseLocalEnvironments, value: .unavailable)
var debugValue: FeatureValue = .unavailable
if let infoDictionary = NSBundle.mainBundle().infoDictionary {
if let debugEnabled = infoDictionary["DebugEnabled"] as? Bool {
debugValue = debugEnabled ? .available : .unavailable
}
}
self.features[FeatureCatalog.DebugEnabled] = StaticFeature(identifier: FeatureCatalog.DebugEnabled, value: debugValue)
}
func loadUserDefaults() {
let userDefaults = NSUserDefaults.standardUserDefaults()
self.values[Values.ActiveSportIdentifier] = userDefaults.objectForKey(Values.ActiveSportIdentifier) as? String ?? "basketball-men"
self.values[Values.ProductionDFPNetwork] = userDefaults.boolForKey(Values.ProductionDFPNetwork)
}
// MARK: - Properties
var values = [String : AnyObject]()
var endpoints = [String : ServiceEndpoint]()
var behaviors = [String : Bool]()
var webviewURLConfigs = [String : WebviewURLConfig]()
func synchronize() {
let userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setObject(values[Values.ActiveSportIdentifier], forKey: Values.ActiveSportIdentifier)
if let useProductionDFPNetwork = values[Values.ProductionDFPNetwork] as? Bool {
userDefaults.setBool(useProductionDFPNetwork, forKey: Values.ProductionDFPNetwork)
}
userDefaults.synchronize()
}
// MARK: - Protocols
// MARK: <ServiceEndpointProvider>
func endpoint(identifier: String) -> ServiceEndpoint? {
return endpoints[identifier]
}
// MARK: <BehaviorProvider>
func behaviorEnabled(identifier: String) -> Bool {
return behaviors[identifier] ?? false
}
// MARK: <WebviewURLProvider>
func webviewURLConfig(identifier: String) -> WebviewURLConfig? {
return webviewURLConfigs[identifier]
}
// MARK: <FeatureProvider>
func feature(named: String) -> Feature? {
return features[named]
}
func activeSubject() -> FeatureSubject? {
return subject
}
// MARK: - Private
private var subject: FeatureSubject
private var features = [String : Feature]()
}
/**
Processes a config file into values, endpoints, behaviors, and webview URLs
and stores them on the globally-registered `AppConfiguration`.
*/
class AppEnvironmentConfigProcessor: EnvironmentConfigProcessor {
// MARK: - Protocols
// MARK: <EnvironmentConfigProcessor>
func process(configValues: EnvironmentConfigValues) {
processConfigValues(configValues)
processEndpoints(configValues)
processImageEndpoints(configValues)
processBehaviors(configValues)
processWebviewURLConfigs(configValues)
}
// MARK: - Private
/// Extract general configuration values from the config dictionary and set them on the active `AppConfiguration`.
func processConfigValues(configValues: EnvironmentConfigValues) {
guard let config = Container.resolve(AppConfiguration.self) else { return }
// App Info
let appData = configValues["app"] as? EnvironmentConfigValues ?? EnvironmentConfigValues()
let releaseData = appData["release"] as? EnvironmentConfigValues ?? EnvironmentConfigValues()
config.values[AppConfiguration.Values.LatestVersion] = JSONParser.parseString(releaseData["latest_version"]) ?? 0
config.values[AppConfiguration.Values.MandatoryVersion] = JSONParser.parseString(releaseData["mandatory_version"]) ?? 0
if let appStoreURLString = JSONParser.parseString(releaseData["appstore_url"]) {
if let appStoreURL = NSURL(string: appStoreURLString) {
config.values[AppConfiguration.Values.AppStoreURL] = appStoreURL
}
}
// General
let generalData = configValues["default"] as? EnvironmentConfigValues ?? EnvironmentConfigValues()
let calendar = NSCalendar.currentCalendar()
let currentYear = calendar.component(.Year, fromDate: NSDate())
config.values[AppConfiguration.Values.AcademicYear] = JSONParser.parseInt(generalData["academic_year"]) ?? currentYear
config.values[AppConfiguration.Values.FeedbackEmailAddress] = JSONParser.parseString(generalData["feedback_email"])
}
/// Extract `ServiceEndpoint` values from the config dictionary and set them on the active `AppConfiguration`.
func processEndpoints(configValues: EnvironmentConfigValues) {
guard let config = Container.resolve(AppConfiguration.self) else { return }
guard let apiData = configValues["api"] as? EnvironmentConfigValues else { return }
guard let baseData = apiData["base"] as? EnvironmentConfigValues else { return }
guard let endpointsData = apiData["links"] as? EnvironmentConfigValues else { return }
let baseScheme = baseData["scheme"] as? String
let baseHost = baseData["host"] as? String
let basePath = baseData["base_path"] as? String ?? ""
for (identifier, endpointData) in endpointsData {
guard let path = JSONParser.parseString(endpointData["href"]) else { continue }
let basePath = JSONParser.parseString(endpointData["base_path"]) ?? basePath
let components = NSURLComponents()
components.scheme = JSONParser.parseString(endpointData["scheme"]) ?? baseScheme
components.host = JSONParser.parseString(endpointData["host"]) ?? baseHost
components.path = "\(basePath)\(path)"
let endpoint = ServiceEndpoint(identifier: identifier)
endpoint.urlContainer = .components(components)
config.endpoints[identifier] = endpoint
}
}
/// Extract `ServiceEndpoint` values from the config dictionary and set them on the active `AppConfiguration`.
func processImageEndpoints(configValues: EnvironmentConfigValues) {
guard let config = Container.resolve(AppConfiguration.self) else { return }
guard let endpointsData = configValues["images"] as? EnvironmentConfigValues else { return }
for (identifier, endpointData) in endpointsData {
guard let path = JSONParser.parseString(endpointData["href"]) else { continue }
let endpoint = ServiceEndpoint(identifier: identifier)
endpoint.urlContainer = .absolutePath(path)
config.endpoints[identifier] = endpoint
}
}
/// Extract Behavior switch values from the config dictionary and set them on the active `AppConfiguration`.
func processBehaviors(configValues: EnvironmentConfigValues) {
guard let config = Container.resolve(AppConfiguration.self) else { return }
let behaviorsData = configValues["behaviors"] as? EnvironmentConfigValues ?? EnvironmentConfigValues()
for (key, value) in behaviorsData {
if let value = value as? Bool {
config.behaviors[key] = value
}
}
}
/// Extract `WebviewURLConfig` values from the config dictionary and set them on the active `AppConfiguration`.
func processWebviewURLConfigs(configValues: EnvironmentConfigValues) {
guard let config = Container.resolve(AppConfiguration.self) else { return }
guard let webviewsData = configValues["webviews"] as? EnvironmentConfigValues else { return }
for (identifier, webviewData) in webviewsData {
guard let urlString = JSONParser.parseString(webviewData["href"]) else { continue }
guard let url = NSURL(string: urlString) else { continue }
let styleString = JSONParser.parseString(webviewData["style"]) ?? "undefined"
var style: WebviewURLStyle = .undefined
switch styleString {
case "inline":
style = .inline
case "external":
style = .external
default:
style = .undefined
}
let webviewConfig = WebviewURLConfig(identifier: identifier, url: url, style: style)
config.webviewURLConfigs[identifier] = webviewConfig
}
}
}
class FeatureCatalog {
static let DebugEnabled = "DebugEnabled"
static let DebugVideoContent = "DebugVideoContent"
static let UseLocalEnvironments = "UseLocalEnvironments"
static let UseDebugLiveStream = "UseDebugLiveStream"
static let NotificationsEnabled = "NotificationsEnabled"
static let NotificationCategoriesEnabled = "NotificationCategoriesEnabled"
static let Rotation = "Rotation"
}
|
mit
|
d9071b9ac5ed3a6362719fc473776887
| 35.874101 | 144 | 0.670471 | 5.110169 | false | true | false | false |
lypiut/WhereAmI
|
Source/WhereAmI.swift
|
1
|
11751
|
// WhereAmI.swift
//
// Copyright (c) 2014 Romain Rivollier
//
// 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 CoreLocation
/**
Location authorization type
- AlwaysAuthorization: The location is updated even if the application is in background
- InUseAuthorization: The location is updated when the application is running
*/
public enum WAILocationAuthorization {
case alwaysAuthorization
case inUseAuthorization
}
/**
Represent responses returned when you call the whereAmI method
- LocationUpdated: Location retrieved with success, contains a CLLocation object
- LocationFail: The CLLocationManager fails to retreive the current location
- Unauthorized: The user unauthorized the geolocation
*/
public enum WAILocationResponse {
case locationUpdated(CLLocation)
case locationFail(NSError)
case unauthorized
}
/**
Represent responses returned when you call the whatIsThisPlace method
- Success: The reverse geocoding retrieve the current place
- Failure: An error occured during the reverse geocoding
- PlaceNotFound: No place was found for the given coordinate
- Unauthorized: The user unauthorized the geolocation
*/
public enum WAIGeocoderResponse {
case success(CLPlacemark)
case failure(NSError)
case placeNotFound
case unauthorized
}
public typealias WAIAuthorizationResult = (_ locationIsAuthorized : Bool) -> Void
public typealias WAILocationUpdate = (_ response : WAILocationResponse) -> Void
public typealias WAIReversGeocodedLocationResult = (_ response : WAIGeocoderResponse) -> Void
// MARK: - Class Implementation
public final class WhereAmI : NSObject {
// Singleton
public static let sharedInstance = WhereAmI()
public let locationManager = CLLocationManager()
/// Max location validity in seconds
public var locationValidity : TimeInterval = 40.0
public var horizontalAccuracy : CLLocationDistance = 500.0
public var continuousUpdate : Bool = false
public var locationAuthorization : WAILocationAuthorization = .inUseAuthorization
public var locationPrecision : LocationProfile {
didSet {
self.locationManager.distanceFilter = locationPrecision.distanceFilter
self.locationManager.desiredAccuracy = locationPrecision.desiredAccuracy
self.horizontalAccuracy = locationPrecision.horizontalAccuracy
}
}
var authorizationHandler : WAIAuthorizationResult?;
var locationUpdateHandler : WAILocationUpdate?;
fileprivate lazy var geocoder : CLGeocoder = CLGeocoder()
// MARK: - Class methods
/**
Check if the location authorization has been asked
- returns: return false if the authorization has not been asked, otherwise true
*/
public class func userHasBeenPromptedForLocationUse() -> Bool {
return CLLocationManager.authorizationStatus() != .notDetermined
}
/**
Check if the localization is authorized
- returns: false if the user's location was denied, otherwise true
*/
public class func locationIsAuthorized() -> Bool {
let authorizationStatus = CLLocationManager.authorizationStatus()
let locationServicesEnabled = CLLocationManager.locationServicesEnabled()
if authorizationStatus == .denied || authorizationStatus == .restricted || locationServicesEnabled == false {
return false
}
return true
}
// MARK: - Object methods
override init() {
self.locationPrecision = WAILocationProfile.default
super.init()
self.locationManager.delegate = self
}
/**
All in one method, the easiest way to obtain the user's GPS coordinate
- parameter locationHandler: The closure return the latest valid user's positon
*/
public func whereAmI(_ locationHandler : @escaping WAILocationUpdate) {
self.askLocationAuthorization{ [weak self] (locationIsAuthorized) -> Void in
if locationIsAuthorized {
self?.startUpdatingLocation(locationHandler)
} else {
locationHandler(.unauthorized)
}
}
}
/**
All in one method, the easiest way to obtain the user's location (street, city, etc.)
- parameter geocoderHandler: The closure return a placemark corresponding to the current user's location. If an error occured it return nil
- parameter locationRefusedHandler: When the user refuse location, this closure is called.
*/
public func whatIsThisPlace(_ geocoderHandler : @escaping WAIReversGeocodedLocationResult) {
self.whereAmI({ [weak self] (location) -> Void in
switch location {
case let .locationUpdated(location):
self?.geocoder.cancelGeocode()
self?.geocoder.reverseGeocodeLocation(location, completionHandler: { (placesmark, error) -> Void in
if let anError = error {
geocoderHandler(.failure(anError as NSError))
return
}
if let placemark = placesmark?.first {
geocoderHandler(.success(placemark))
} else {
geocoderHandler(.placeNotFound)
}
})
case let .locationFail(error):
geocoderHandler(.failure(error))
case .unauthorized:
geocoderHandler(.unauthorized)
}
})
}
/**
Start the location update. If the continuousUpdate is at true the locationHandler will be used for each postion update.
- parameter locationHandler: The closure returns an updated location conforms to the accuracy filters
*/
public func startUpdatingLocation(_ locationHandler : WAILocationUpdate?) {
self.locationUpdateHandler = locationHandler
#if os(watchOS) || os(tvOS)
locationManager.requestLocation()
#elseif os(iOS)
if #available(iOS 9, *) {
if continuousUpdate == false {
locationManager.requestLocation()
} else {
locationManager.startUpdatingLocation()
}
if locationAuthorization == .alwaysAuthorization {
locationManager.allowsBackgroundLocationUpdates = true
}
} else {
locationManager.startUpdatingLocation()
}
#endif
}
/**
Stop the location update and release the location handler.
*/
public func stopUpdatingLocation() {
locationManager.stopUpdatingLocation()
locationUpdateHandler = nil
}
/**
Request location authorization
- parameter resultHandler: The closure return if the authorization is granted or not
*/
public func askLocationAuthorization(_ resultHandler : @escaping WAIAuthorizationResult) {
// if the authorization was already asked we return the result
if WhereAmI.userHasBeenPromptedForLocationUse() {
resultHandler(WhereAmI.locationIsAuthorized())
return
}
self.authorizationHandler = resultHandler
#if os(iOS)
if locationAuthorization == .alwaysAuthorization {
locationManager.requestAlwaysAuthorization()
} else {
locationManager.requestWhenInUseAuthorization()
}
#elseif os(watchOS)
if self.locationAuthorization == .alwaysAuthorization {
locationManager.requestAlwaysAuthorization()
} else {
locationManager.requestWhenInUseAuthorization()
}
#elseif os(tvOS)
locationManager.requestWhenInUseAuthorization()
#endif
}
deinit {
//Cleaning closure
locationUpdateHandler = nil
authorizationHandler = nil
}
}
extension WhereAmI : CLLocationManagerDelegate {
// MARK: - CLLocationManager Delegate
public func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
switch status {
case .authorizedAlways, .authorizedWhenInUse:
authorizationHandler?(true);
case .notDetermined, .denied, .restricted:
authorizationHandler?(false)
@unknown default:
print("default")
}
authorizationHandler = nil;
}
public func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
self.locationUpdateHandler?(.locationFail(error as NSError))
}
public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
//Get the latest location data
guard let latestPosition = locations.first else { return }
let locationAge = -latestPosition.timestamp.timeIntervalSinceNow
//Check if the location is valid for the accuracy profil selected
if locationAge < locationValidity && CLLocationCoordinate2DIsValid(latestPosition.coordinate) && latestPosition.horizontalAccuracy < horizontalAccuracy {
locationUpdateHandler?(.locationUpdated(latestPosition))
if continuousUpdate == false {
stopUpdatingLocation()
}
}
}
}
/**
Out of the box function, the easiest way to obtain the user's GPS coordinate
- parameter locationHandler: The closure return the latest valid user's positon
- parameter locationRefusedHandler: When the user refuse location, this closure is called.
*/
public func whereAmI(_ locationHandler : @escaping WAILocationUpdate) {
WhereAmI.sharedInstance.whereAmI(locationHandler)
}
/**
Out of the box function, the easiest way to obtain the user's location (street, city, etc.)
- parameter geocoderHandler: The closure return a placemark corresponding to the current user's location. If an error occured it return nil
- parameter locationRefusedHandler: When the user refuse location, this closure is called.
*/
public func whatIsThisPlace(_ geocoderHandler : @escaping WAIReversGeocodedLocationResult) {
WhereAmI.sharedInstance.whatIsThisPlace(geocoderHandler);
}
|
mit
|
a6be64ca08954033b7f131976206f282
| 35.380805 | 161 | 0.655519 | 5.715467 | false | false | false | false |
esttorhe/RxSwift
|
RxExample/RxExample/Services/Randomizer.swift
|
1
|
6802
|
//
// Randomizer.swift
// RxExample
//
// Created by Krunoslav Zaher on 6/28/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
typealias NumberSection = HashableSectionModel<String, Int>
let insertItems = true
let deleteItems = true
let moveItems = true
let reloadItems = true
let deleteSections = true
let insertSections = true
let explicitlyMoveSections = true
let reloadSections = true
class Randomizer {
var sections: [NumberSection]
var rng: PseudoRandomGenerator
var unusedItems: [Int]
var unusedSections: [String]
init(rng: PseudoRandomGenerator, sections: [NumberSection]) {
self.rng = rng
self.sections = sections
self.unusedSections = []
self.unusedItems = []
}
func countTotalItemsInSections(sections: [NumberSection]) -> Int {
return sections.reduce(0) { p, s in
return p + s.items.count
}
}
func randomize() {
var nextUnusedSections = [String]()
var nextUnusedItems = [Int]()
let sectionCount = sections.count
let itemCount = countTotalItemsInSections(sections)
let startItemCount = itemCount + unusedItems.count
let startSectionCount = sections.count + unusedSections.count
// insert sections
for section in unusedSections {
let index = rng.get_random() % (sections.count + 1)
if insertSections {
sections.insert(NumberSection(model: section, items: []), atIndex: index)
}
else {
nextUnusedSections.append(section)
}
}
// insert/reload items
for unusedValue in unusedItems {
let sectionIndex = rng.get_random() % sections.count
let section = sections[sectionIndex]
let itemCount = section.items.count
// insert
if rng.get_random() % 2 == 0 {
let itemIndex = rng.get_random() % (itemCount + 1)
if insertItems {
sections[sectionIndex].items.insert(unusedValue, atIndex: itemIndex)
}
else {
nextUnusedItems.append(unusedValue)
}
}
// update
else {
if itemCount == 0 {
sections[sectionIndex].items.insert(unusedValue, atIndex: 0)
continue
}
let itemIndex = rng.get_random() % itemCount
if reloadItems {
nextUnusedItems.append(sections[sectionIndex].items.removeAtIndex(itemIndex))
sections[sectionIndex].items.insert(unusedValue, atIndex: itemIndex)
}
else {
nextUnusedItems.append(unusedValue)
}
}
}
assert(countTotalItemsInSections(sections) + nextUnusedItems.count == startItemCount)
assert(sections.count + nextUnusedSections.count == startSectionCount)
let itemActionCount = itemCount / 7
let sectionActionCount = sectionCount / 3
// move items
for i in 0 ..< itemActionCount {
if self.sections.count == 0 {
continue
}
let sourceSectionIndex = rng.get_random() % self.sections.count
let destinationSectionIndex = rng.get_random() % self.sections.count
let sectionItemCount = sections[sourceSectionIndex].items.count
if sectionItemCount == 0 {
continue
}
let sourceItemIndex = rng.get_random() % sectionItemCount
let nextRandom = rng.get_random()
if moveItems {
let item = sections[sourceSectionIndex].items.removeAtIndex(sourceItemIndex)
let targetItemIndex = nextRandom % (self.sections[destinationSectionIndex].items.count + 1)
sections[destinationSectionIndex].items.insert(item, atIndex: targetItemIndex)
}
}
assert(countTotalItemsInSections(sections) + nextUnusedItems.count == startItemCount)
assert(sections.count + nextUnusedSections.count == startSectionCount)
// delete items
for i in 0 ..< itemActionCount {
if self.sections.count == 0 {
continue
}
let sourceSectionIndex = rng.get_random() % self.sections.count
let sectionItemCount = sections[sourceSectionIndex].items.count
if sectionItemCount == 0 {
continue
}
let sourceItemIndex = rng.get_random() % sectionItemCount
if deleteItems {
nextUnusedItems.append(sections[sourceSectionIndex].items.removeAtIndex(sourceItemIndex))
}
}
assert(countTotalItemsInSections(sections) + nextUnusedItems.count == startItemCount)
assert(sections.count + nextUnusedSections.count == startSectionCount)
// move sections
for i in 0 ..< sectionActionCount {
if sections.count == 0 {
continue
}
let sectionIndex = rng.get_random() % sections.count
let targetIndex = rng.get_random() % sections.count
if explicitlyMoveSections {
let section = sections.removeAtIndex(sectionIndex)
sections.insert(section, atIndex: targetIndex)
}
}
assert(countTotalItemsInSections(sections) + nextUnusedItems.count == startItemCount)
assert(sections.count + nextUnusedSections.count == startSectionCount)
// delete sections
for i in 0 ..< sectionActionCount {
if sections.count == 0 {
continue
}
let sectionIndex = rng.get_random() % sections.count
if deleteSections {
let section = sections.removeAtIndex(sectionIndex)
for item in section.items {
nextUnusedItems.append(item)
}
nextUnusedSections.append(section.model)
}
}
assert(countTotalItemsInSections(sections) + nextUnusedItems.count == startItemCount)
assert(sections.count + nextUnusedSections.count == startSectionCount)
unusedSections = nextUnusedSections
unusedItems = nextUnusedItems
}
}
|
mit
|
291d24b0bde323c453f4a2d3fd501919
| 32.348039 | 107 | 0.55616 | 5.43725 | false | false | false | false |
pawel-sp/PSZFormNavigationManager
|
PSZFormNavigationManager/FormNavigationManager.swift
|
1
|
4393
|
//
// FormNavigationManager.swift
// PSZFormNavigationManager
//
// Created by Paweł Sporysz on 24.12.2014.
// Copyright (c) 2014 Paweł Sporysz. All rights reserved.
//
import UIKit
public class FormNavigationManager: NSObject {
// MARK: - Settings
/// Infinite navigation means that after typing next button when last input field is active, the first input field become active. It works the same in different direction. Default value = false.
public var infiniteNavigation:Bool = false
// MARK: - Properties
/// Delegate. You can use it to display different keyboard toolbar according to active input field.
public var delegate:FormNavigationManagerDelegate? {
didSet {
assignKeyboardToolbarFromDelegate()
}
}
/// Assigned input fields, for example UITextField, UITextView.
public var inputFields:[InputFieldProtocol] = []
/// Assigned keyboard toolbar.
public var keyboardToolBar:KeyboardToolbar?
// MARK: - Utilities
func assignKeyboardToolbarFromDelegate() {
if delegate != nil {
for inputField in inputFields {
let _inputField = inputField
let keyboardToolbar = delegate?.formNavigationManager(self, keyboardToolbarForInputField: _inputField)
keyboardToolbar?.barButtonItemsDelegate = self
_inputField.inputAccessoryView = keyboardToolbar
}
}
}
func assignKeyboardToolbar(keyboardToolbar:KeyboardToolbar) {
for inputField in inputFields {
let _inputField = inputField
_inputField.inputAccessoryView = keyboardToolBar
}
}
/**
Use this function to register input fields. It causes for every input field there will be specified keyboard toolbar displayed.
- parameter inputFields: Input fields to register. It can be UITextField, UITextView or any other object which implement InputProtocol.
- parameter keyboardToolBar: Keyboard toolbar to register.
*/
public func registerInputFields(inputFields:[InputFieldProtocol], forKeyboardToolBar keyboardToolBar:KeyboardToolbar) {
self.keyboardToolBar = keyboardToolBar
keyboardToolBar.barButtonItemsDelegate = self
self.inputFields = inputFields
if delegate != nil {
assignKeyboardToolbarFromDelegate()
} else {
assignKeyboardToolbar(keyboardToolBar)
}
}
func neighboringInputFieldsFrom(inputField inputField:InputFieldProtocol?) -> (InputFieldProtocol?,InputFieldProtocol?) {
let count = inputFields.count
for (index,element) in inputFields.enumerate() {
if element.isEqual(inputField) {
switch index {
case 0: return (infiniteNavigation ? inputFields.last : nil, index + 1 < count ? inputFields[index+1] : inputFields.first)
case count - 1: return (index - 1 >= 0 ? inputFields[index-1] : inputFields.last ,infiniteNavigation ? inputFields.first : nil)
default: return (inputFields[index-1],inputFields[index+1])
}
}
}
return (nil,nil)
}
func activeInputField() -> InputFieldProtocol? {
let currentFirstResponder = UIResponder.currentFirstResponder()
return inputFields.filter{ $0.isEqual(currentFirstResponder) }.first
}
// MARK: - Navigation
func moveToNextInputField() {
if let activeInputField = activeInputField() {
if let input = neighboringInputFieldsFrom(inputField: activeInputField).1 {
input.becomeFirstResponder()
} else {
activeInputField.resignFirstResponder()
}
}
}
func moveToPreviousInputField() {
if let activeInputField = activeInputField() {
if let input = neighboringInputFieldsFrom(inputField: activeInputField).0 {
input.becomeFirstResponder()
} else {
activeInputField.resignFirstResponder()
}
}
}
func finishNavigation() {
activeInputField()?.resignFirstResponder()
}
}
|
mit
|
19c05778168416f0e4e819fe2154b037
| 36.529915 | 198 | 0.625142 | 5.622279 | false | false | false | false |
MaartenBrijker/project
|
project/External/AudioKit-master/AudioKit/Common/Nodes/Playback/Time Pitch Stretching/AKVariSpeed.swift
|
2
|
1739
|
//
// AKVariSpeed.swift
// AudioKit
//
// Created by Eiríkur Orri Ólafsson, revision history on GitHub
// Copyright © 2016 AudioKit. All rights reserved.
//
import AVFoundation
/// AudioKit version of Apple's VariSpeed Audio Unit
///
/// - parameter input: Input node to process
/// - parameter rate: Rate (rate) ranges from 0.25 to 4.0 (Default: 1.0)
///
public class AKVariSpeed: AKNode, AKToggleable {
private let variSpeedAU = AVAudioUnitVarispeed()
/// Rate (rate) ranges form 0.25 to 4.0 (Default: 1.0)
public var rate : Double = 1.0 {
didSet {
if rate < 0.25 {
rate = 0.25
}
if rate > 4.0 {
rate = 4.0
}
variSpeedAU.rate = Float(rate)
}
}
/// Tells whether the node is processing (ie. started, playing, or active)
public var isStarted: Bool {
return rate != 1.0
}
private var lastKnownRate: Double = 1.0
/// Initialize the varispeed node
///
/// - parameter input: Input node to process
/// - parameter rate: Rate (rate) ranges from 0.25 to 4.0 (Default: 1.0)
///
public init(_ input: AKNode, rate: Double = 1.0) {
self.rate = rate
lastKnownRate = rate
super.init()
self.avAudioNode = variSpeedAU
AudioKit.engine.attachNode(self.avAudioNode)
input.addConnectionPoint(self)
}
/// Function to start, play, or activate the node, all do the same thing
public func start() {
rate = lastKnownRate
}
/// Function to stop or bypass the node, both are equivalent
public func stop() {
lastKnownRate = rate
rate = 1.0
}
}
|
apache-2.0
|
0cb249b880c805a704a526d9096f0e68
| 25.707692 | 78 | 0.577765 | 3.97254 | false | false | false | false |
SwifterSwift/SwifterSwift
|
Sources/SwifterSwift/SwiftStdlib/StringExtensions.swift
|
1
|
47631
|
// StringExtensions.swift - Copyright 2020 SwifterSwift
#if canImport(Foundation)
import Foundation
#endif
#if canImport(UIKit)
import UIKit
#endif
#if canImport(AppKit)
import AppKit
#endif
#if canImport(CoreGraphics)
import CoreGraphics
#endif
// MARK: - Properties
public extension String {
#if canImport(Foundation)
/// SwifterSwift: String decoded from base64 (if applicable).
///
/// "SGVsbG8gV29ybGQh".base64Decoded = Optional("Hello World!")
///
var base64Decoded: String? {
if let data = Data(base64Encoded: self,
options: .ignoreUnknownCharacters) {
return String(data: data, encoding: .utf8)
}
let remainder = count % 4
var padding = ""
if remainder > 0 {
padding = String(repeating: "=", count: 4 - remainder)
}
guard let data = Data(base64Encoded: self + padding,
options: .ignoreUnknownCharacters) else { return nil }
return String(data: data, encoding: .utf8)
}
#endif
#if canImport(Foundation)
/// SwifterSwift: String encoded in base64 (if applicable).
///
/// "Hello World!".base64Encoded -> Optional("SGVsbG8gV29ybGQh")
///
var base64Encoded: String? {
// https://github.com/Reza-Rg/Base64-Swift-Extension/blob/master/Base64.swift
let plainData = data(using: .utf8)
return plainData?.base64EncodedString()
}
#endif
/// SwifterSwift: Array of characters of a string.
var charactersArray: [Character] {
return Array(self)
}
#if canImport(Foundation)
/// SwifterSwift: CamelCase of string.
///
/// "sOme vAriable naMe".camelCased -> "someVariableName"
///
var camelCased: String {
let source = lowercased()
let first = source[..<source.index(after: source.startIndex)]
if source.contains(" ") {
let connected = source.capitalized.replacingOccurrences(of: " ", with: "")
let camel = connected.replacingOccurrences(of: "\n", with: "")
let rest = String(camel.dropFirst())
return first + rest
}
let rest = String(source.dropFirst())
return first + rest
}
#endif
/// SwifterSwift: Check if string contains one or more emojis.
///
/// "Hello 😀".containEmoji -> true
///
var containEmoji: Bool {
// http://stackoverflow.com/questions/30757193/find-out-if-character-in-string-is-emoji
for scalar in unicodeScalars {
switch scalar.value {
case 0x1F600...0x1F64F, // Emoticons
0x1F300...0x1F5FF, // Misc Symbols and Pictographs
0x1F680...0x1F6FF, // Transport and Map
0x1F1E6...0x1F1FF, // Regional country flags
0x2600...0x26FF, // Misc symbols
0x2700...0x27BF, // Dingbats
0xE0020...0xE007F, // Tags
0xFE00...0xFE0F, // Variation Selectors
0x1F900...0x1F9FF, // Supplemental Symbols and Pictographs
127_000...127_600, // Various asian characters
65024...65039, // Variation selector
9100...9300, // Misc items
8400...8447: // Combining Diacritical Marks for Symbols
return true
default:
continue
}
}
return false
}
/// SwifterSwift: First character of string (if applicable).
///
/// "Hello".firstCharacterAsString -> Optional("H")
/// "".firstCharacterAsString -> nil
///
var firstCharacterAsString: String? {
guard let first = first else { return nil }
return String(first)
}
/// SwifterSwift: Check if string contains one or more letters.
///
/// "123abc".hasLetters -> true
/// "123".hasLetters -> false
///
var hasLetters: Bool {
return rangeOfCharacter(from: .letters, options: .numeric, range: nil) != nil
}
/// SwifterSwift: Check if string contains one or more numbers.
///
/// "abcd".hasNumbers -> false
/// "123abc".hasNumbers -> true
///
var hasNumbers: Bool {
return rangeOfCharacter(from: .decimalDigits, options: .literal, range: nil) != nil
}
/// SwifterSwift: Check if string contains only letters.
///
/// "abc".isAlphabetic -> true
/// "123abc".isAlphabetic -> false
///
var isAlphabetic: Bool {
let hasLetters = rangeOfCharacter(from: .letters, options: .numeric, range: nil) != nil
let hasNumbers = rangeOfCharacter(from: .decimalDigits, options: .literal, range: nil) != nil
return hasLetters && !hasNumbers
}
/// SwifterSwift: Check if string contains at least one letter and one number.
///
/// // useful for passwords
/// "123abc".isAlphaNumeric -> true
/// "abc".isAlphaNumeric -> false
///
var isAlphaNumeric: Bool {
let hasLetters = rangeOfCharacter(from: .letters, options: .numeric, range: nil) != nil
let hasNumbers = rangeOfCharacter(from: .decimalDigits, options: .literal, range: nil) != nil
let comps = components(separatedBy: .alphanumerics)
return comps.joined(separator: "").count == 0 && hasLetters && hasNumbers
}
/// SwifterSwift: Check if string is palindrome.
///
/// "abcdcba".isPalindrome -> true
/// "Mom".isPalindrome -> true
/// "A man a plan a canal, Panama!".isPalindrome -> true
/// "Mama".isPalindrome -> false
///
var isPalindrome: Bool {
let letters = filter { $0.isLetter }
guard !letters.isEmpty else { return false }
let midIndex = letters.index(letters.startIndex, offsetBy: letters.count / 2)
let firstHalf = letters[letters.startIndex..<midIndex]
let secondHalf = letters[midIndex..<letters.endIndex].reversed()
return !zip(firstHalf, secondHalf).contains(where: { $0.lowercased() != $1.lowercased() })
}
#if canImport(Foundation)
/// SwifterSwift: Check if string is valid email format.
///
/// - Note: Note that this property does not validate the email address against an email server. It merely attempts to determine whether its format is suitable for an email address.
///
/// "[email protected]".isValidEmail -> true
///
var isValidEmail: Bool {
// http://emailregex.com/
let regex =
"^(?:[\\p{L}0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[\\p{L}0-9!#$%\\&'*+/=?\\^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[\\p{L}0-9](?:[a-z0-9-]*[\\p{L}0-9])?\\.)+[\\p{L}0-9](?:[\\p{L}0-9-]*[\\p{L}0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[\\p{L}0-9-]*[\\p{L}0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])$"
return range(of: regex, options: .regularExpression, range: nil, locale: nil) != nil
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Check if string is a valid URL.
///
/// "https://google.com".isValidUrl -> true
///
var isValidUrl: Bool {
return URL(string: self) != nil
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Check if string is a valid schemed URL.
///
/// "https://google.com".isValidSchemedUrl -> true
/// "google.com".isValidSchemedUrl -> false
///
var isValidSchemedUrl: Bool {
guard let url = URL(string: self) else { return false }
return url.scheme != nil
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Check if string is a valid https URL.
///
/// "https://google.com".isValidHttpsUrl -> true
///
var isValidHttpsUrl: Bool {
guard let url = URL(string: self) else { return false }
return url.scheme == "https"
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Check if string is a valid http URL.
///
/// "http://google.com".isValidHttpUrl -> true
///
var isValidHttpUrl: Bool {
guard let url = URL(string: self) else { return false }
return url.scheme == "http"
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Check if string is a valid file URL.
///
/// "file://Documents/file.txt".isValidFileUrl -> true
///
var isValidFileUrl: Bool {
return URL(string: self)?.isFileURL ?? false
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Check if string is a valid Swift number. Note: In North America, "." is the decimal separator, while in many parts of Europe "," is used.
///
/// "123".isNumeric -> true
/// "1.3".isNumeric -> true (en_US)
/// "1,3".isNumeric -> true (fr_FR)
/// "abc".isNumeric -> false
///
var isNumeric: Bool {
let scanner = Scanner(string: self)
scanner.locale = NSLocale.current
#if os(Linux) || targetEnvironment(macCatalyst)
return scanner.scanDecimal() != nil && scanner.isAtEnd
#else
return scanner.scanDecimal(nil) && scanner.isAtEnd
#endif
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Check if string only contains digits.
///
/// "123".isDigits -> true
/// "1.3".isDigits -> false
/// "abc".isDigits -> false
///
var isDigits: Bool {
return CharacterSet.decimalDigits.isSuperset(of: CharacterSet(charactersIn: self))
}
#endif
/// SwifterSwift: Last character of string (if applicable).
///
/// "Hello".lastCharacterAsString -> Optional("o")
/// "".lastCharacterAsString -> nil
///
var lastCharacterAsString: String? {
guard let last = last else { return nil }
return String(last)
}
#if canImport(Foundation)
/// SwifterSwift: Latinized string.
///
/// "Hèllö Wórld!".latinized -> "Hello World!"
///
var latinized: String {
return folding(options: .diacriticInsensitive, locale: Locale.current)
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Bool value from string (if applicable).
///
/// "1".bool -> true
/// "False".bool -> false
/// "Hello".bool = nil
///
var bool: Bool? {
let selfLowercased = trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
switch selfLowercased {
case "true", "yes", "1":
return true
case "false", "no", "0":
return false
default:
return nil
}
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Date object from "yyyy-MM-dd" formatted string.
///
/// "2007-06-29".date -> Optional(Date)
///
var date: Date? {
let selfLowercased = trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
let formatter = DateFormatter()
formatter.timeZone = TimeZone.current
formatter.dateFormat = "yyyy-MM-dd"
return formatter.date(from: selfLowercased)
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Date object from "yyyy-MM-dd HH:mm:ss" formatted string.
///
/// "2007-06-29 14:23:09".dateTime -> Optional(Date)
///
var dateTime: Date? {
let selfLowercased = trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
let formatter = DateFormatter()
formatter.timeZone = TimeZone.current
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return formatter.date(from: selfLowercased)
}
#endif
/// SwifterSwift: Integer value from string (if applicable).
///
/// "101".int -> 101
///
var int: Int? {
return Int(self)
}
/// SwifterSwift: Lorem ipsum string of given length.
///
/// - Parameter length: number of characters to limit lorem ipsum to (default is 445 - full lorem ipsum).
/// - Returns: Lorem ipsum dolor sit amet... string.
static func loremIpsum(ofLength length: Int = 445) -> String {
guard length > 0 else { return "" }
// https://www.lipsum.com/
let loremIpsum = """
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
"""
if loremIpsum.count > length {
return String(loremIpsum[loremIpsum.startIndex..<loremIpsum.index(loremIpsum.startIndex, offsetBy: length)])
}
return loremIpsum
}
#if canImport(Foundation)
/// SwifterSwift: URL from string (if applicable).
///
/// "https://google.com".url -> URL(string: "https://google.com")
/// "not url".url -> nil
///
var url: URL? {
return URL(string: self)
}
#endif
#if canImport(Foundation)
/// SwifterSwift: String with no spaces or new lines in beginning and end.
///
/// " hello \n".trimmed -> "hello"
///
var trimmed: String {
return trimmingCharacters(in: .whitespacesAndNewlines)
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Readable string from a URL string.
///
/// "it's%20easy%20to%20decode%20strings".urlDecoded -> "it's easy to decode strings"
///
var urlDecoded: String {
return removingPercentEncoding ?? self
}
#endif
#if canImport(Foundation)
/// SwifterSwift: URL escaped string.
///
/// "it's easy to encode strings".urlEncoded -> "it's%20easy%20to%20encode%20strings"
///
var urlEncoded: String {
return addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Escaped string for inclusion in a regular expression pattern.
///
/// "hello ^$ there" -> "hello \\^\\$ there"
///
var regexEscaped: String {
return NSRegularExpression.escapedPattern(for: self)
}
#endif
#if canImport(Foundation)
/// SwifterSwift: String without spaces and new lines.
///
/// " \n Swifter \n Swift ".withoutSpacesAndNewLines -> "SwifterSwift"
///
var withoutSpacesAndNewLines: String {
return replacingOccurrences(of: " ", with: "").replacingOccurrences(of: "\n", with: "")
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Check if the given string contains only white spaces.
var isWhitespace: Bool {
return trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
}
#endif
#if os(iOS) || os(tvOS)
/// SwifterSwift: Check if the given string spelled correctly.
var isSpelledCorrectly: Bool {
let checker = UITextChecker()
let range = NSRange(startIndex..<endIndex, in: self)
let misspelledRange = checker.rangeOfMisspelledWord(
in: self,
range: range,
startingAt: 0,
wrap: false,
language: Locale.preferredLanguages.first ?? "en")
return misspelledRange.location == NSNotFound
}
#endif
}
// MARK: - Methods
public extension String {
#if canImport(Foundation)
/// SwifterSwift: Float value from string (if applicable).
///
/// - Parameter locale: Locale (default is Locale.current)
/// - Returns: Optional Float value from given string.
func float(locale: Locale = .current) -> Float? {
let formatter = NumberFormatter()
formatter.locale = locale
formatter.allowsFloats = true
return formatter.number(from: self)?.floatValue
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Double value from string (if applicable).
///
/// - Parameter locale: Locale (default is Locale.current)
/// - Returns: Optional Double value from given string.
func double(locale: Locale = .current) -> Double? {
let formatter = NumberFormatter()
formatter.locale = locale
formatter.allowsFloats = true
return formatter.number(from: self)?.doubleValue
}
#endif
#if canImport(CoreGraphics) && canImport(Foundation)
/// SwifterSwift: CGFloat value from string (if applicable).
///
/// - Parameter locale: Locale (default is Locale.current)
/// - Returns: Optional CGFloat value from given string.
func cgFloat(locale: Locale = .current) -> CGFloat? {
let formatter = NumberFormatter()
formatter.locale = locale
formatter.allowsFloats = true
return formatter.number(from: self) as? CGFloat
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Array of strings separated by new lines.
///
/// "Hello\ntest".lines() -> ["Hello", "test"]
///
/// - Returns: Strings separated by new lines.
func lines() -> [String] {
var result = [String]()
enumerateLines { line, _ in
result.append(line)
}
return result
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Returns a localized string, with an optional comment for translators.
///
/// "Hello world".localized -> Hallo Welt
///
func localized(comment: String = "") -> String {
return NSLocalizedString(self, comment: comment)
}
#endif
/// SwifterSwift: The most common character in string.
///
/// "This is a test, since e is appearing everywhere e should be the common character".mostCommonCharacter() -> "e"
///
/// - Returns: The most common character.
func mostCommonCharacter() -> Character? {
let mostCommon = withoutSpacesAndNewLines.reduce(into: [Character: Int]()) {
let count = $0[$1] ?? 0
$0[$1] = count + 1
}.max { $0.1 < $1.1 }?.key
return mostCommon
}
/// SwifterSwift: Array with unicodes for all characters in a string.
///
/// "SwifterSwift".unicodeArray() -> [83, 119, 105, 102, 116, 101, 114, 83, 119, 105, 102, 116]
///
/// - Returns: The unicodes for all characters in a string.
func unicodeArray() -> [Int] {
return unicodeScalars.map { Int($0.value) }
}
#if canImport(Foundation)
/// SwifterSwift: an array of all words in a string.
///
/// "Swift is amazing".words() -> ["Swift", "is", "amazing"]
///
/// - Returns: The words contained in a string.
func words() -> [String] {
// https://stackoverflow.com/questions/42822838
let chararacterSet = CharacterSet.whitespacesAndNewlines.union(.punctuationCharacters)
let comps = components(separatedBy: chararacterSet)
return comps.filter { !$0.isEmpty }
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Count of words in a string.
///
/// "Swift is amazing".wordsCount() -> 3
///
/// - Returns: The count of words contained in a string.
func wordCount() -> Int {
// https://stackoverflow.com/questions/42822838
let chararacterSet = CharacterSet.whitespacesAndNewlines.union(.punctuationCharacters)
let comps = components(separatedBy: chararacterSet)
let words = comps.filter { !$0.isEmpty }
return words.count
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Transforms the string into a slug string.
///
/// "Swift is amazing".toSlug() -> "swift-is-amazing"
///
/// - Returns: The string in slug format.
func toSlug() -> String {
let lowercased = self.lowercased()
let latinized = lowercased.folding(options: .diacriticInsensitive, locale: Locale.current)
let withDashes = latinized.replacingOccurrences(of: " ", with: "-")
let alphanumerics = NSCharacterSet.alphanumerics
var filtered = withDashes.filter {
guard String($0) != "-" else { return true }
guard String($0) != "&" else { return true }
return String($0).rangeOfCharacter(from: alphanumerics) != nil
}
while filtered.lastCharacterAsString == "-" {
filtered = String(filtered.dropLast())
}
while filtered.firstCharacterAsString == "-" {
filtered = String(filtered.dropFirst())
}
return filtered.replacingOccurrences(of: "--", with: "-")
}
#endif
/// SwifterSwift: Safely subscript string with index.
///
/// "Hello World!"[safe: 3] -> "l"
/// "Hello World!"[safe: 20] -> nil
///
/// - Parameter index: index.
subscript(safe index: Int) -> Character? {
guard index >= 0, index < count else { return nil }
return self[self.index(startIndex, offsetBy: index)]
}
/// SwifterSwift: Safely subscript string within a given range.
///
/// "Hello World!"[safe: 6..<11] -> "World"
/// "Hello World!"[safe: 21..<110] -> nil
///
/// "Hello World!"[safe: 6...11] -> "World!"
/// "Hello World!"[safe: 21...110] -> nil
///
/// - Parameter range: Range expression.
subscript<R>(safe range: R) -> String? where R: RangeExpression, R.Bound == Int {
let range = range.relative(to: Int.min..<Int.max)
guard range.lowerBound >= 0,
let lowerIndex = index(startIndex, offsetBy: range.lowerBound, limitedBy: endIndex),
let upperIndex = index(startIndex, offsetBy: range.upperBound, limitedBy: endIndex) else {
return nil
}
return String(self[lowerIndex..<upperIndex])
}
#if os(iOS) || os(macOS)
/// SwifterSwift: Copy string to global pasteboard.
///
/// "SomeText".copyToPasteboard() // copies "SomeText" to pasteboard
///
func copyToPasteboard() {
#if os(iOS)
UIPasteboard.general.string = self
#elseif os(macOS)
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(self, forType: .string)
#endif
}
#endif
/// SwifterSwift: Converts string format to CamelCase.
///
/// var str = "sOme vaRiabLe Name"
/// str.camelize()
/// print(str) // prints "someVariableName"
///
@discardableResult
mutating func camelize() -> String {
let source = lowercased()
let first = source[..<source.index(after: source.startIndex)]
if source.contains(" ") {
let connected = source.capitalized.replacingOccurrences(of: " ", with: "")
let camel = connected.replacingOccurrences(of: "\n", with: "")
let rest = String(camel.dropFirst())
self = first + rest
return self
}
let rest = String(source.dropFirst())
self = first + rest
return self
}
/// SwifterSwift: First character of string uppercased(if applicable) while keeping the original string.
///
/// "hello world".firstCharacterUppercased() -> "Hello world"
/// "".firstCharacterUppercased() -> ""
///
mutating func firstCharacterUppercased() {
guard let first = first else { return }
self = String(first).uppercased() + dropFirst()
}
/// SwifterSwift: Check if string contains only unique characters.
///
func hasUniqueCharacters() -> Bool {
guard count > 0 else { return false }
var uniqueChars = Set<String>()
for char in self {
if uniqueChars.contains(String(char)) { return false }
uniqueChars.insert(String(char))
}
return true
}
#if canImport(Foundation)
/// SwifterSwift: Check if string contains one or more instance of substring.
///
/// "Hello World!".contain("O") -> false
/// "Hello World!".contain("o", caseSensitive: false) -> true
///
/// - Parameters:
/// - string: substring to search for.
/// - caseSensitive: set true for case sensitive search (default is true).
/// - Returns: true if string contains one or more instance of substring.
func contains(_ string: String, caseSensitive: Bool = true) -> Bool {
if !caseSensitive {
return range(of: string, options: .caseInsensitive) != nil
}
return range(of: string) != nil
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Count of substring in string.
///
/// "Hello World!".count(of: "o") -> 2
/// "Hello World!".count(of: "L", caseSensitive: false) -> 3
///
/// - Parameters:
/// - string: substring to search for.
/// - caseSensitive: set true for case sensitive search (default is true).
/// - Returns: count of appearance of substring in string.
func count(of string: String, caseSensitive: Bool = true) -> Int {
if !caseSensitive {
return lowercased().components(separatedBy: string.lowercased()).count - 1
}
return components(separatedBy: string).count - 1
}
#endif
/// SwifterSwift: Check if string ends with substring.
///
/// "Hello World!".ends(with: "!") -> true
/// "Hello World!".ends(with: "WoRld!", caseSensitive: false) -> true
///
/// - Parameters:
/// - suffix: substring to search if string ends with.
/// - caseSensitive: set true for case sensitive search (default is true).
/// - Returns: true if string ends with substring.
func ends(with suffix: String, caseSensitive: Bool = true) -> Bool {
if !caseSensitive {
return lowercased().hasSuffix(suffix.lowercased())
}
return hasSuffix(suffix)
}
#if canImport(Foundation)
/// SwifterSwift: Latinize string.
///
/// var str = "Hèllö Wórld!"
/// str.latinize()
/// print(str) // prints "Hello World!"
///
@discardableResult
mutating func latinize() -> String {
self = folding(options: .diacriticInsensitive, locale: Locale.current)
return self
}
#endif
/// SwifterSwift: Random string of given length.
///
/// String.random(ofLength: 18) -> "u7MMZYvGo9obcOcPj8"
///
/// - Parameter length: number of characters in string.
/// - Returns: random string of given length.
static func random(ofLength length: Int) -> String {
guard length > 0 else { return "" }
let base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
var randomString = ""
for _ in 1...length {
randomString.append(base.randomElement()!)
}
return randomString
}
/// SwifterSwift: Reverse string.
@discardableResult
mutating func reverse() -> String {
let chars: [Character] = reversed()
self = String(chars)
return self
}
/// SwifterSwift: Sliced string from a start index with length.
///
/// "Hello World".slicing(from: 6, length: 5) -> "World"
///
/// - Parameters:
/// - index: string index the slicing should start from.
/// - length: amount of characters to be sliced after given index.
/// - Returns: sliced substring of length number of characters (if applicable) (example: "Hello World".slicing(from: 6, length: 5) -> "World").
func slicing(from index: Int, length: Int) -> String? {
guard length >= 0, index >= 0, index < count else { return nil }
guard index.advanced(by: length) <= count else {
return self[safe: index..<count]
}
guard length > 0 else { return "" }
return self[safe: index..<index.advanced(by: length)]
}
/// SwifterSwift: Slice given string from a start index with length (if applicable).
///
/// var str = "Hello World"
/// str.slice(from: 6, length: 5)
/// print(str) // prints "World"
///
/// - Parameters:
/// - index: string index the slicing should start from.
/// - length: amount of characters to be sliced after given index.
@discardableResult
mutating func slice(from index: Int, length: Int) -> String {
if let str = slicing(from: index, length: length) {
self = String(str)
}
return self
}
/// SwifterSwift: Slice given string from a start index to an end index (if applicable).
///
/// var str = "Hello World"
/// str.slice(from: 6, to: 11)
/// print(str) // prints "World"
///
/// - Parameters:
/// - start: string index the slicing should start from.
/// - end: string index the slicing should end at.
@discardableResult
mutating func slice(from start: Int, to end: Int) -> String {
guard end >= start else { return self }
if let str = self[safe: start..<end] {
self = str
}
return self
}
/// SwifterSwift: Slice given string from a start index (if applicable).
///
/// var str = "Hello World"
/// str.slice(at: 6)
/// print(str) // prints "World"
///
/// - Parameter index: string index the slicing should start from.
@discardableResult
mutating func slice(at index: Int) -> String {
guard index < count else { return self }
if let str = self[safe: index..<count] {
self = str
}
return self
}
/// SwifterSwift: Check if string starts with substring.
///
/// "hello World".starts(with: "h") -> true
/// "hello World".starts(with: "H", caseSensitive: false) -> true
///
/// - Parameters:
/// - suffix: substring to search if string starts with.
/// - caseSensitive: set true for case sensitive search (default is true).
/// - Returns: true if string starts with substring.
func starts(with prefix: String, caseSensitive: Bool = true) -> Bool {
if !caseSensitive {
return lowercased().hasPrefix(prefix.lowercased())
}
return hasPrefix(prefix)
}
#if canImport(Foundation)
/// SwifterSwift: Date object from string of date format.
///
/// "2017-01-15".date(withFormat: "yyyy-MM-dd") -> Date set to Jan 15, 2017
/// "not date string".date(withFormat: "yyyy-MM-dd") -> nil
///
/// - Parameter format: date format.
/// - Returns: Date object from string (if applicable).
func date(withFormat format: String) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.date(from: self)
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Removes spaces and new lines in beginning and end of string.
///
/// var str = " \n Hello World \n\n\n"
/// str.trim()
/// print(str) // prints "Hello World"
///
@discardableResult
mutating func trim() -> String {
self = trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
return self
}
#endif
/// SwifterSwift: Truncate string (cut it to a given number of characters).
///
/// var str = "This is a very long sentence"
/// str.truncate(toLength: 14)
/// print(str) // prints "This is a very..."
///
/// - Parameters:
/// - toLength: maximum number of characters before cutting.
/// - trailing: string to add at the end of truncated string (default is "...").
@discardableResult
mutating func truncate(toLength length: Int, trailing: String? = "...") -> String {
guard length > 0 else { return self }
if count > length {
self = self[startIndex..<index(startIndex, offsetBy: length)] + (trailing ?? "")
}
return self
}
/// SwifterSwift: Truncated string (limited to a given number of characters).
///
/// "This is a very long sentence".truncated(toLength: 14) -> "This is a very..."
/// "Short sentence".truncated(toLength: 14) -> "Short sentence"
///
/// - Parameters:
/// - toLength: maximum number of characters before cutting.
/// - trailing: string to add at the end of truncated string.
/// - Returns: truncated string (this is an extr...).
func truncated(toLength length: Int, trailing: String? = "...") -> String {
guard 0..<count ~= length else { return self }
return self[startIndex..<index(startIndex, offsetBy: length)] + (trailing ?? "")
}
#if canImport(Foundation)
/// SwifterSwift: Convert URL string to readable string.
///
/// var str = "it's%20easy%20to%20decode%20strings"
/// str.urlDecode()
/// print(str) // prints "it's easy to decode strings"
///
@discardableResult
mutating func urlDecode() -> String {
if let decoded = removingPercentEncoding {
self = decoded
}
return self
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Escape string.
///
/// var str = "it's easy to encode strings"
/// str.urlEncode()
/// print(str) // prints "it's%20easy%20to%20encode%20strings"
///
@discardableResult
mutating func urlEncode() -> String {
if let encoded = addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) {
self = encoded
}
return self
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Verify if string matches the regex pattern.
///
/// - Parameter pattern: Pattern to verify.
/// - Returns: `true` if string matches the pattern.
func matches(pattern: String) -> Bool {
return range(of: pattern, options: .regularExpression, range: nil, locale: nil) != nil
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Verify if string matches the regex.
///
/// - Parameters:
/// - regex: Regex to verify.
/// - options: The matching options to use.
/// - Returns: `true` if string matches the regex.
func matches(regex: NSRegularExpression, options: NSRegularExpression.MatchingOptions = []) -> Bool {
let range = NSRange(startIndex..<endIndex, in: self)
return regex.firstMatch(in: self, options: options, range: range) != nil
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Overload Swift's 'contains' operator for matching regex pattern.
///
/// - Parameters:
/// - lhs: String to check on regex pattern.
/// - rhs: Regex pattern to match against.
/// - Returns: true if string matches the pattern.
static func ~= (lhs: String, rhs: String) -> Bool {
return lhs.range(of: rhs, options: .regularExpression) != nil
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Overload Swift's 'contains' operator for matching regex.
///
/// - Parameters:
/// - lhs: String to check on regex.
/// - rhs: Regex to match against.
/// - Returns: `true` if there is at least one match for the regex in the string.
static func ~= (lhs: String, rhs: NSRegularExpression) -> Bool {
let range = NSRange(lhs.startIndex..<lhs.endIndex, in: lhs)
return rhs.firstMatch(in: lhs, range: range) != nil
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Returns a new string in which all occurrences of a regex in a specified range of the receiver are replaced by the template.
/// - Parameters:
/// - regex Regex to replace.
/// - template: The template to replace the regex.
/// - options: The matching options to use
/// - searchRange: The range in the receiver in which to search.
/// - Returns: A new string in which all occurrences of regex in searchRange of the receiver are replaced by template.
func replacingOccurrences(
of regex: NSRegularExpression,
with template: String,
options: NSRegularExpression.MatchingOptions = [],
range searchRange: Range<String.Index>? = nil) -> String {
let range = NSRange(searchRange ?? startIndex..<endIndex, in: self)
return regex.stringByReplacingMatches(in: self, options: options, range: range, withTemplate: template)
}
#endif
/// SwifterSwift: Pad string to fit the length parameter size with another string in the start.
///
/// "hue".padStart(10) -> " hue"
/// "hue".padStart(10, with: "br") -> "brbrbrbhue"
///
/// - Parameters:
/// - length: The target length to pad.
/// - string: Pad string. Default is " ".
@discardableResult
mutating func padStart(_ length: Int, with string: String = " ") -> String {
self = paddingStart(length, with: string)
return self
}
/// SwifterSwift: Returns a string by padding to fit the length parameter size with another string in the start.
///
/// "hue".paddingStart(10) -> " hue"
/// "hue".paddingStart(10, with: "br") -> "brbrbrbhue"
///
/// - Parameters:
/// - length: The target length to pad.
/// - string: Pad string. Default is " ".
/// - Returns: The string with the padding on the start.
func paddingStart(_ length: Int, with string: String = " ") -> String {
guard count < length else { return self }
let padLength = length - count
if padLength < string.count {
return string[string.startIndex..<string.index(string.startIndex, offsetBy: padLength)] + self
} else {
var padding = string
while padding.count < padLength {
padding.append(string)
}
return padding[padding.startIndex..<padding.index(padding.startIndex, offsetBy: padLength)] + self
}
}
/// SwifterSwift: Pad string to fit the length parameter size with another string in the start.
///
/// "hue".padEnd(10) -> "hue "
/// "hue".padEnd(10, with: "br") -> "huebrbrbrb"
///
/// - Parameters:
/// - length: The target length to pad.
/// - string: Pad string. Default is " ".
@discardableResult
mutating func padEnd(_ length: Int, with string: String = " ") -> String {
self = paddingEnd(length, with: string)
return self
}
/// SwifterSwift: Returns a string by padding to fit the length parameter size with another string in the end.
///
/// "hue".paddingEnd(10) -> "hue "
/// "hue".paddingEnd(10, with: "br") -> "huebrbrbrb"
///
/// - Parameters:
/// - length: The target length to pad.
/// - string: Pad string. Default is " ".
/// - Returns: The string with the padding on the end.
func paddingEnd(_ length: Int, with string: String = " ") -> String {
guard count < length else { return self }
let padLength = length - count
if padLength < string.count {
return self + string[string.startIndex..<string.index(string.startIndex, offsetBy: padLength)]
} else {
var padding = string
while padding.count < padLength {
padding.append(string)
}
return self + padding[padding.startIndex..<padding.index(padding.startIndex, offsetBy: padLength)]
}
}
/// SwifterSwift: Removes given prefix from the string.
///
/// "Hello, World!".removingPrefix("Hello, ") -> "World!"
///
/// - Parameter prefix: Prefix to remove from the string.
/// - Returns: The string after prefix removing.
func removingPrefix(_ prefix: String) -> String {
guard hasPrefix(prefix) else { return self }
return String(dropFirst(prefix.count))
}
/// SwifterSwift: Removes given suffix from the string.
///
/// "Hello, World!".removingSuffix(", World!") -> "Hello"
///
/// - Parameter suffix: Suffix to remove from the string.
/// - Returns: The string after suffix removing.
func removingSuffix(_ suffix: String) -> String {
guard hasSuffix(suffix) else { return self }
return String(dropLast(suffix.count))
}
/// SwifterSwift: Adds prefix to the string.
///
/// "www.apple.com".withPrefix("https://") -> "https://www.apple.com"
///
/// - Parameter prefix: Prefix to add to the string.
/// - Returns: The string with the prefix prepended.
func withPrefix(_ prefix: String) -> String {
// https://www.hackingwithswift.com/articles/141/8-useful-swift-extensions
guard !hasPrefix(prefix) else { return self }
return prefix + self
}
}
// MARK: - Initializers
public extension String {
#if canImport(Foundation)
/// SwifterSwift: Create a new string from a base64 string (if applicable).
///
/// String(base64: "SGVsbG8gV29ybGQh") = "Hello World!"
/// String(base64: "hello") = nil
///
/// - Parameter base64: base64 string.
init?(base64: String) {
guard let decodedData = Data(base64Encoded: base64) else { return nil }
guard let str = String(data: decodedData, encoding: .utf8) else { return nil }
self.init(str)
}
#endif
/// SwifterSwift: Create a new random string of given length.
///
/// String(randomOfLength: 10) -> "gY8r3MHvlQ"
///
/// - Parameter length: number of characters in string.
init(randomOfLength length: Int) {
guard length > 0 else {
self.init()
return
}
let base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
var randomString = ""
for _ in 1...length {
randomString.append(base.randomElement()!)
}
self = randomString
}
}
#if !os(Linux)
// MARK: - NSAttributedString
public extension String {
#if os(iOS) || os(macOS)
/// SwifterSwift: Bold string.
var bold: NSAttributedString {
return NSMutableAttributedString(
string: self,
attributes: [.font: SFFont.boldSystemFont(ofSize: SFFont.systemFontSize)])
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Underlined string
var underline: NSAttributedString {
return NSAttributedString(string: self, attributes: [.underlineStyle: NSUnderlineStyle.single.rawValue])
}
#endif
#if canImport(Foundation)
/// SwifterSwift: Strikethrough string.
var strikethrough: NSAttributedString {
return NSAttributedString(
string: self,
attributes: [.strikethroughStyle: NSNumber(value: NSUnderlineStyle.single.rawValue as Int)])
}
#endif
#if os(iOS)
/// SwifterSwift: Italic string.
var italic: NSAttributedString {
return NSMutableAttributedString(
string: self,
attributes: [.font: UIFont.italicSystemFont(ofSize: UIFont.systemFontSize)])
}
#endif
#if canImport(AppKit) || canImport(UIKit)
/// SwifterSwift: Add color to string.
///
/// - Parameter color: text color.
/// - Returns: a NSAttributedString versions of string colored with given color.
func colored(with color: SFColor) -> NSAttributedString {
return NSMutableAttributedString(string: self, attributes: [.foregroundColor: color])
}
#endif
}
#endif
// MARK: - Operators
public extension String {
/// SwifterSwift: Repeat string multiple times.
///
/// 'bar' * 3 -> "barbarbar"
///
/// - Parameters:
/// - lhs: string to repeat.
/// - rhs: number of times to repeat character.
/// - Returns: new string with given string repeated n times.
static func * (lhs: String, rhs: Int) -> String {
guard rhs > 0 else { return "" }
return String(repeating: lhs, count: rhs)
}
/// SwifterSwift: Repeat string multiple times.
///
/// 3 * 'bar' -> "barbarbar"
///
/// - Parameters:
/// - lhs: number of times to repeat character.
/// - rhs: string to repeat.
/// - Returns: new string with given string repeated n times.
static func * (lhs: Int, rhs: String) -> String {
guard lhs > 0 else { return "" }
return String(repeating: rhs, count: lhs)
}
}
#if canImport(Foundation)
// MARK: - NSString extensions
public extension String {
/// SwifterSwift: NSString from a string.
var nsString: NSString {
return NSString(string: self)
}
/// SwifterSwift: The full `NSRange` of the string.
var fullNSRange: NSRange { NSRange(startIndex..<endIndex, in: self) }
/// SwifterSwift: NSString lastPathComponent.
var lastPathComponent: String {
return (self as NSString).lastPathComponent
}
/// SwifterSwift: NSString pathExtension.
var pathExtension: String {
return (self as NSString).pathExtension
}
/// SwifterSwift: NSString deletingLastPathComponent.
var deletingLastPathComponent: String {
return (self as NSString).deletingLastPathComponent
}
/// SwifterSwift: NSString deletingPathExtension.
var deletingPathExtension: String {
return (self as NSString).deletingPathExtension
}
/// SwifterSwift: NSString pathComponents.
var pathComponents: [String] {
return (self as NSString).pathComponents
}
/// SwifterSwift: Convert an `NSRange` into `Range<String.Index>`.
/// - Parameter nsRange: The `NSRange` within the receiver.
/// - Returns: The equivalent `Range<String.Index>` of `nsRange` found within the receiving string.
func range(from nsRange: NSRange) -> Range<Index> {
guard let range = Range(nsRange, in: self) else { fatalError("Failed to find range \(nsRange) in \(self)") }
return range
}
/// SwifterSwift: Convert a `Range<String.Index>` into `NSRange`.
/// - Parameter range: The `Range<String.Index>` within the receiver.
/// - Returns: The equivalent `NSRange` of `range` found within the receiving string.
func nsRange(from range: Range<Index>) -> NSRange {
return NSRange(range, in: self)
}
/// SwifterSwift: NSString appendingPathComponent(str: String).
///
/// - Note: This method only works with file paths (not, for example, string representations of URLs.
/// See NSString [appendingPathComponent(_:)](https://developer.apple.com/documentation/foundation/nsstring/1417069-appendingpathcomponent)
/// - Parameter str: the path component to append to the receiver.
/// - Returns: a new string made by appending aString to the receiver, preceded if necessary by a path separator.
func appendingPathComponent(_ str: String) -> String {
return (self as NSString).appendingPathComponent(str)
}
/// SwifterSwift: NSString appendingPathExtension(str: String).
///
/// - Parameter str: The extension to append to the receiver.
/// - Returns: a new string made by appending to the receiver an extension separator followed by ext (if applicable).
func appendingPathExtension(_ str: String) -> String? {
return (self as NSString).appendingPathExtension(str)
}
/// SwifterSwift: Accesses a contiguous subrange of the collection’s elements.
/// - Parameter nsRange: A range of the collection’s indices. The bounds of the range must be valid indices of the collection.
/// - Returns: A slice of the receiving string.
subscript(bounds: NSRange) -> Substring {
guard let range = Range(bounds, in: self) else { fatalError("Failed to find range \(bounds) in \(self)") }
return self[range]
}
}
#endif
|
mit
|
7b069da73768298a5d24016d24df3e46
| 34.509321 | 521 | 0.603112 | 4.334031 | false | false | false | false |
vlribeiro/loja-desafio-ios
|
LojaDesafio/LojaDesafio/ProductApi.swift
|
1
|
2837
|
//
// ProductApi.swift
// LojaDesafio
//
// Created by Vinicius Ribeiro on 29/11/15.
// Copyright © 2015 Vinicius Ribeiro. All rights reserved.
//
import Foundation
class ProductApi: LojaApi {
var delegate : ProductApiProtocol?
let resourcePath = "Product"
init(delegate: ProductApiProtocol) {
self.delegate = delegate
}
func getAll() {
//self.startConnectionForPath(self.resourcePath)
var products = Array<Product>()
products.append(Product(id: 1, name: "iPhone 6S Plus 16 GB", description: "Novo iPhone 6S Plus 16GB de armazenamento. Cor: Prata.", price: 3999, imageUrl: "http://novo2015.com.br/wp-content/uploads/2015/06/iphone-6-2.jpg"))
products.append(Product(id: 2, name: "iPhone 6S Plus 64 GB", description: "Novo iPhone 6S Plus 64GB de armazenamento. Cor: Prata.", price: 4299, imageUrl: "http://www.promoinfo.com.br/img/anuncios/107479.jpg"))
products.append(Product(id: 3, name: "iPhone 6S Plus 128 GB", description: "Novo iPhone 6S Plus 128GB de armazenamento. Cor: Prata.", price: 4699, imageUrl: "http://iacom.s8.com.br/produtos/01/00/item/120998/6/120998637G1.jpg"))
products.append(Product(id: 4, name: "Lumia 950", description: "Lumia 950 rodando Windows Phone", price: 2899, imageUrl: "http://s2.glbimg.com/vBWIFeph0puoygVRPNogxqYYgrk=/0x0:750x375/695x348/s.glbimg.com/po/tt2/f/original/2015/10/13/lumia-950-2.jpg"))
products.append(Product(id: 5, name: "Lumia 950 XL", description: "Lumia 950 XL rodando Windows Phone", price: 3299, imageUrl: "https://www.thurrott.com/wp-content/uploads/2015/10/Lumia950.jpg"))
self.delegate?.didReceiveResponse(products)
}
//NSURLConnection delegate function
func connectionDidFinishLoading(connection: NSURLConnection!) {
let jsonResult = self.getDictionaryFromData()
var fetchedProducts = Array<Product>()
if (jsonResult.count > 0) {
let productsData: AnyObject = jsonResult.valueForKey("data")!
for i in 0..<productsData.count {
let product = self.fetchFromJSONDictionary(productsData[i]! as! NSDictionary)
//ProductData.insertOrUpdate(product)
fetchedProducts.append(product)
}
}
delegate?.didReceiveResponse(fetchedProducts)
}
func fetchFromJSONDictionary(dictionary: NSDictionary) -> Product {
return Product(id: dictionary["Id"] as! Int, name: dictionary["Name"] as! String, description: dictionary["Description"] as! String, price: dictionary["Price"] as! Float, imageUrl: dictionary["ÏmageUrl"] as! String)
}
}
protocol ProductApiProtocol {
func didReceiveResponse(products: Array<Product>)
}
|
mit
|
9a98ef3959a80bf37a464622c6083c57
| 45.491803 | 260 | 0.663139 | 3.740106 | false | false | false | false |
raykle/CustomTransition
|
CircleTransition/ViewControllerTransition/CircleTransitionAnimator.swift
|
1
|
2336
|
//
// CircleTransitionAnimator.swift
// CircleTransition
//
// Created by guomin on 16/3/9.
// Copyright © 2016年 iBinaryOrg. All rights reserved.
//
import UIKit
class CircleTransitionAnimator: NSObject, UIViewControllerAnimatedTransitioning {
weak var transitionContext: UIViewControllerContextTransitioning?
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return 0.5
}
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
self.transitionContext = transitionContext
let containerView = transitionContext.containerView()
let fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as! ViewController
let toViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) as! ViewController
let button = fromViewController.button
containerView?.addSubview(toViewController.view)
let circleMaskPathInitial = UIBezierPath(ovalInRect: button.frame)
let extremePoint = CGPoint(x: button.center.x - 0, y: button.center.y - CGRectGetHeight(toViewController.view.bounds))
let radius = sqrt((extremePoint.x * extremePoint.x) + (extremePoint.y * extremePoint.y))
let circleMaskPathFinal = UIBezierPath(ovalInRect: CGRectInset(button.frame, -radius, -radius))
let maskLayer = CAShapeLayer()
maskLayer.path = circleMaskPathFinal.CGPath
toViewController.view.layer.mask = maskLayer
let maskLayerAnimation = CABasicAnimation(keyPath: "path")
maskLayerAnimation.fromValue = circleMaskPathInitial.CGPath
maskLayerAnimation.toValue = circleMaskPathFinal.CGPath
maskLayerAnimation.duration = self.transitionDuration(transitionContext)
maskLayerAnimation.delegate = self
maskLayer.addAnimation(maskLayerAnimation, forKey: "path")
}
override func animationDidStop(anim: CAAnimation, finished flag: Bool) {
self.transitionContext?.completeTransition(!self.transitionContext!.transitionWasCancelled())
self.transitionContext?.viewControllerForKey(UITransitionContextFromViewControllerKey)?.view.layer.mask = nil
}
}
|
mit
|
dff59f852b731a8b90c225bcbf9b6165
| 45.66 | 132 | 0.74282 | 5.876574 | false | false | false | false |
tekezo/Karabiner-Elements
|
src/apps/PreferencesWindow/src/StateJsonMonitor.swift
|
1
|
3237
|
import Foundation
private func callback(_ filePath: UnsafePointer<Int8>?,
_ context: UnsafeMutableRawPointer?)
{
let obj: StateJsonMonitor! = unsafeBitCast(context, to: StateJsonMonitor.self)
let path = String(cString: filePath!)
DispatchQueue.main.async { [weak obj] in
guard let obj = obj else { return }
obj.update(path)
}
}
private struct State: Codable {
var driver_loaded: Bool?
var driver_version_matched: Bool?
var hid_device_open_permitted: Bool?
}
@objc
public class StateJsonMonitor: NSObject {
@IBOutlet private var alertWindowsManager: AlertWindowsManager!
private var states: [String: State] = [:]
private var driverVersionNotMatchedAlertViewShown = false
@objc
public func start() {
let obj = unsafeBitCast(self, to: UnsafeMutableRawPointer.self)
libkrbn_enable_observer_state_json_file_monitor(callback, obj)
libkrbn_enable_grabber_state_json_file_monitor(callback, obj)
}
@objc
public func stop() {
libkrbn_disable_observer_state_json_file_monitor()
libkrbn_disable_grabber_state_json_file_monitor()
}
public func update(_ filePath: String) {
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: filePath)) {
let decoder = JSONDecoder()
if let state = try? decoder.decode(State.self, from: jsonData) {
states[filePath] = state
}
}
//
// Show alerts
//
var driverNotLoaded = false
var driverVersionNotMatched = false
var inputMonitoringNotPermitted = false
for state in states {
if state.value.driver_loaded == false {
driverNotLoaded = true
}
if state.value.driver_version_matched == false {
driverVersionNotMatched = true
}
if state.value.hid_device_open_permitted == false {
inputMonitoringNotPermitted = true
}
}
//
// - DriverNotLoadedAlertWindow
// - DriverVersionNotMatchedAlertWindow
//
if driverVersionNotMatchedAlertViewShown {
// If DriverVersionNotMatchedAlertWindow is shown,
// do nothing here to prevent showing DriverNotLoadedAlertWindow after the driver is deactivated.
} else {
if driverNotLoaded {
alertWindowsManager.showDriverNotLoadedAlertWindow()
} else {
alertWindowsManager.hideDriverNotLoadedAlertWindow()
if driverVersionNotMatched {
alertWindowsManager.showDriverVersionNotMatchedAlertWindow()
driverVersionNotMatchedAlertViewShown = true
} else {
alertWindowsManager.hideDriverVersionNotMatchedAlertWindow()
}
}
}
//
// - InputMonitoringPermissionsAlertWindow
//
if inputMonitoringNotPermitted {
alertWindowsManager.showInputMonitoringPermissionsAlertWindow()
} else {
alertWindowsManager.hideInputMonitoringPermissionsAlertWindow()
}
}
}
|
unlicense
|
5f32e256f57e2c55fc96d6498a034e2d
| 31.049505 | 109 | 0.614767 | 4.941985 | false | false | false | false |
antonio081014/LeetCode-CodeBase
|
Swift/binary-tree-cameras.swift
|
2
|
2127
|
/**
* https://leetcode.com/problems/binary-tree-cameras/
*
*
*/
// Date: Sun May 16 16:56:04 PDT 2021
/**
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init() { self.val = 0; self.left = nil; self.right = nil; }
* public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
* public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
* self.val = val
* self.left = left
* self.right = right
* }
* }
*/
/**
Let solve(node) be some information about how many cameras it takes to cover the subtree at this node in various states. There are essentially 3 states:
[State 0] Strict subtree: All the nodes below this node are covered, but not this node.
[State 1] Normal subtree: All the nodes below and including this node are covered, but there is no camera here.
[State 2] Placed camera: All the nodes below and including this node are covered, and there is a camera here (which may cover nodes above this node).
Once we frame the problem in this way, the answer falls out:
To cover a strict subtree, the children of this node must be in state 1.
To cover a normal subtree without placing a camera here, the children of this node must be in states 1 or 2, and at least one of those children must be in state 2.
To cover the subtree when placing a camera here, the children can be in any state.
*/
class Solution {
func minCameraCover(_ root: TreeNode?) -> Int {
func calc(_ node: TreeNode?) -> (Int, Int, Int) {
guard let node = node else { return (0, 0, 9999) }
let left = calc(node.left)
let right = calc(node.right)
let d0 = left.1 + right.1
let d1 = min(left.2 + min(right.1, right.2), right.2 + min(left.1, left.2))
let d2 = 1 + min(left.0, min(left.1, left.2)) + min(right.0, min(right.1, right.2))
return (d0, d1, d2)
}
let result = calc(root)
return min(result.1, result.2)
}
}
|
mit
|
a72b867f3c57552d77294638026b0e02
| 40.705882 | 164 | 0.629525 | 3.556856 | false | false | false | false |
SwiftKidz/Slip
|
Sources/Protocols/FlowStateActions.swift
|
1
|
2681
|
/*
MIT License
Copyright (c) 2016 SwiftKidz
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
//protocol FlowStateActions: class, FlowCoreApi, FlowState, FlowTypeBlocks, FlowRun, FlowHandlerBlocks {}
//
//extension FlowStateActions {
//
// func queued() {
// guard testFlow else { unsafeState = .running; return }
// guard testAtBeginning else { unsafeState = .running; return }
// unsafeState = .testing
// }
//
// func testing() {
// runTest ()
// }
//
// func running() {
// testFlow ? runClosure() : runFlowOfBlocks()
// }
//
// func failed() {
// opQueue.cancelAllOperations()
// guard
// let _ = errorBlock,
// let error = unsafeState.error
// else {
// finished()
// return
// }
// DispatchQueue.main.async {
// self.errorBlock?(error)
// self.errorBlock = nil
// self.finishBlock = { _ in }
// }
// }
//
// func canceled() {
// opQueue.cancelAllOperations()
// guard let _ = cancelBlock else {
// finished()
// return
// }
// DispatchQueue.main.async {
// self.cancelBlock?()
// self.cancelBlock = nil
// self.finishBlock = { _ in }
// }
//
// }
//
// func finished() {
// let state = self.unsafeState
// let result = state.error == nil ? Result.success((state.value as? [T]) ?? []) : Result.failure(state.error!)
//
// DispatchQueue.main.async {
// self.finishBlock(state, result)
// self.finishBlock = { _ in }
// }
// }
//}
|
mit
|
d7ebd2c915ec543ef920b519c09de576
| 30.916667 | 118 | 0.617307 | 4.11828 | false | true | false | false |
darthpelo/SurviveAmsterdam
|
mobile/SurviveAmsterdam/Extensions.swift
|
1
|
2431
|
import Foundation
import UIKit
import CoreLocation
import QuadratTouch
// Created by Sem Shafiq on 11/12/15.
extension UIImage {
public func resizeByWidth(newWidth: CGFloat) -> UIImage {
let scale = newWidth / self.size.width
let newHeight = self.size.height * scale
UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight))
self.drawInRect(CGRectMake(0, 0, newWidth, newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
public func resizeByHeight(newHeight: CGFloat) -> UIImage {
let scale = newHeight / self.size.height
let newWidth = self.size.width * scale
UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight))
self.drawInRect(CGRectMake(0, 0, newWidth, newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
extension UIImageView {
/**
Convert the image of UIImageView in NSData, if presents
- returns: Optional NSData rappresentation of the image
*/
public func convertImageToData() -> NSData? {
guard let image = self.image else {
return nil
}
return UIImageJPEGRepresentation(image, 1)
}
}
extension CLLocation {
func parameters() -> Parameters
{
let ll = "\(self.coordinate.latitude),\(self.coordinate.longitude)"
let llAcc = "\(self.horizontalAccuracy)"
let alt = "\(self.altitude)"
let altAcc = "\(self.verticalAccuracy)"
let parameters = [
Parameter.ll:ll,
Parameter.llAcc:llAcc,
Parameter.alt:alt,
Parameter.altAcc:altAcc
]
return parameters
}
}
extension UIViewController {
func dismiss() {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
extension String {
var length: Int {
return characters.count
}
}
extension UISearchBar {
func setBarTintColorWithAnimation(color:UIColor) {
let transition = CATransition()
transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
transition.type = kCATransitionFade
transition.duration = 0.2
layer.addAnimation(transition, forKey: nil)
barTintColor = color
}
}
|
mit
|
a6137ff03092d2e3dc69006bf527bdd6
| 28.301205 | 100 | 0.65364 | 5.117895 | false | false | false | false |
almazrafi/Metatron
|
Tests/MetatronTests/Lyrics3/Lyrics3TagCommentsTest.swift
|
1
|
11126
|
//
// Lyrics3TagCommentsTest.swift
// Metatron
//
// Copyright (c) 2016 Almaz Ibragimov
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import XCTest
@testable import Metatron
class Lyrics3TagCommentsTest: XCTestCase {
// MARK: Instance Methods
func test() {
let textEncoding = ID3v1Latin1TextEncoding.regular
let tag = Lyrics3Tag()
do {
let value: [String] = []
let joined = value.joined(separator: "\n")
tag.comments = value
XCTAssert(tag.comments == [])
let field = tag.appendField(Lyrics3FieldID.inf)
XCTAssert(field.stuff == nil)
do {
tag.version = Lyrics3Version.v1
XCTAssert(tag.toData() == nil)
}
do {
tag.version = Lyrics3Version.v2
XCTAssert(tag.toData() == nil)
}
field.imposeStuff(format: Lyrics3TextInformationFormat.regular).content = joined
XCTAssert(tag.comments == [])
}
do {
let value = [""]
let joined = value.joined(separator: "\n")
tag.comments = value
XCTAssert(tag.comments == [])
let field = tag.appendField(Lyrics3FieldID.inf)
XCTAssert(field.stuff == nil)
do {
tag.version = Lyrics3Version.v1
XCTAssert(tag.toData() == nil)
}
do {
tag.version = Lyrics3Version.v2
XCTAssert(tag.toData() == nil)
}
field.imposeStuff(format: Lyrics3TextInformationFormat.regular).content = joined
XCTAssert(tag.comments == [])
}
do {
let value = ["Abc 123"]
let joined = value.joined(separator: "\n")
tag.comments = value
XCTAssert(tag.comments == [joined])
let field = tag.appendField(Lyrics3FieldID.inf)
XCTAssert(field.stuff(format: Lyrics3TextInformationFormat.regular).content == joined)
do {
tag.version = Lyrics3Version.v1
XCTAssert(tag.toData() == nil)
}
do {
tag.version = Lyrics3Version.v2
guard let data = tag.toData() else {
return XCTFail()
}
guard let other = Lyrics3Tag(fromData: data) else {
return XCTFail()
}
XCTAssert(other.comments == [joined.deencoded(with: textEncoding)])
}
field.imposeStuff(format: Lyrics3TextInformationFormat.regular).content = joined
XCTAssert(tag.comments == [joined])
}
do {
let value = ["Абв 123"]
let joined = value.joined(separator: "\n")
tag.comments = value
XCTAssert(tag.comments == [joined])
let field = tag.appendField(Lyrics3FieldID.inf)
XCTAssert(field.stuff(format: Lyrics3TextInformationFormat.regular).content == joined)
do {
tag.version = Lyrics3Version.v1
XCTAssert(tag.toData() == nil)
}
do {
tag.version = Lyrics3Version.v2
guard let data = tag.toData() else {
return XCTFail()
}
guard let other = Lyrics3Tag(fromData: data) else {
return XCTFail()
}
XCTAssert(other.comments == [joined.deencoded(with: textEncoding)])
}
field.imposeStuff(format: Lyrics3TextInformationFormat.regular).content = joined
XCTAssert(tag.comments == [joined])
}
do {
let value = ["Abc 1", "Abc 2"]
let joined = value.joined(separator: "\n")
tag.comments = value
XCTAssert(tag.comments == [joined])
let field = tag.appendField(Lyrics3FieldID.inf)
XCTAssert(field.stuff(format: Lyrics3TextInformationFormat.regular).content == joined)
do {
tag.version = Lyrics3Version.v1
XCTAssert(tag.toData() == nil)
}
do {
tag.version = Lyrics3Version.v2
guard let data = tag.toData() else {
return XCTFail()
}
guard let other = Lyrics3Tag(fromData: data) else {
return XCTFail()
}
XCTAssert(other.comments == [joined.deencoded(with: textEncoding)])
}
field.imposeStuff(format: Lyrics3TextInformationFormat.regular).content = joined
XCTAssert(tag.comments == [joined])
}
do {
let value = ["", "Abc 2"]
let joined = value.joined(separator: "\n")
tag.comments = value
XCTAssert(tag.comments == [joined])
let field = tag.appendField(Lyrics3FieldID.inf)
XCTAssert(field.stuff(format: Lyrics3TextInformationFormat.regular).content == joined)
do {
tag.version = Lyrics3Version.v1
XCTAssert(tag.toData() == nil)
}
do {
tag.version = Lyrics3Version.v2
guard let data = tag.toData() else {
return XCTFail()
}
guard let other = Lyrics3Tag(fromData: data) else {
return XCTFail()
}
XCTAssert(other.comments == [joined.deencoded(with: textEncoding)])
}
field.imposeStuff(format: Lyrics3TextInformationFormat.regular).content = joined
XCTAssert(tag.comments == [joined])
}
do {
let value = ["Abc 1", ""]
let joined = value.joined(separator: "\n")
tag.comments = value
XCTAssert(tag.comments == [joined])
let field = tag.appendField(Lyrics3FieldID.inf)
XCTAssert(field.stuff(format: Lyrics3TextInformationFormat.regular).content == joined)
do {
tag.version = Lyrics3Version.v1
XCTAssert(tag.toData() == nil)
}
do {
tag.version = Lyrics3Version.v2
guard let data = tag.toData() else {
return XCTFail()
}
guard let other = Lyrics3Tag(fromData: data) else {
return XCTFail()
}
XCTAssert(other.comments == [joined.deencoded(with: textEncoding)])
}
field.imposeStuff(format: Lyrics3TextInformationFormat.regular).content = joined
XCTAssert(tag.comments == [joined])
}
do {
let value = ["", ""]
let joined = value.joined(separator: "\n")
tag.comments = value
XCTAssert(tag.comments == [joined])
let field = tag.appendField(Lyrics3FieldID.inf)
XCTAssert(field.stuff(format: Lyrics3TextInformationFormat.regular).content == joined)
do {
tag.version = Lyrics3Version.v1
XCTAssert(tag.toData() == nil)
}
do {
tag.version = Lyrics3Version.v2
guard let data = tag.toData() else {
return XCTFail()
}
guard let other = Lyrics3Tag(fromData: data) else {
return XCTFail()
}
XCTAssert(other.comments == [joined.deencoded(with: textEncoding)])
}
field.imposeStuff(format: Lyrics3TextInformationFormat.regular).content = joined
XCTAssert(tag.comments == [joined])
}
do {
let value = [Array<String>(repeating: "Abc", count: 123).joined(separator: "\n")]
let joined = value.joined(separator: "\n")
tag.comments = value
XCTAssert(tag.comments == [joined])
let field = tag.appendField(Lyrics3FieldID.inf)
XCTAssert(field.stuff(format: Lyrics3TextInformationFormat.regular).content == joined)
do {
tag.version = Lyrics3Version.v1
XCTAssert(tag.toData() == nil)
}
do {
tag.version = Lyrics3Version.v2
guard let data = tag.toData() else {
return XCTFail()
}
guard let other = Lyrics3Tag(fromData: data) else {
return XCTFail()
}
XCTAssert(other.comments == [joined.deencoded(with: textEncoding)])
}
field.imposeStuff(format: Lyrics3TextInformationFormat.regular).content = joined
XCTAssert(tag.comments == [joined])
}
do {
let value = Array<String>(repeating: "Abc", count: 123)
let joined = value.joined(separator: "\n")
tag.comments = value
XCTAssert(tag.comments == [joined])
let field = tag.appendField(Lyrics3FieldID.inf)
XCTAssert(field.stuff(format: Lyrics3TextInformationFormat.regular).content == joined)
do {
tag.version = Lyrics3Version.v1
XCTAssert(tag.toData() == nil)
}
do {
tag.version = Lyrics3Version.v2
guard let data = tag.toData() else {
return XCTFail()
}
guard let other = Lyrics3Tag(fromData: data) else {
return XCTFail()
}
XCTAssert(other.comments == [joined.deencoded(with: textEncoding)])
}
field.imposeStuff(format: Lyrics3TextInformationFormat.regular).content = joined
XCTAssert(tag.comments == [joined])
}
}
}
|
mit
|
34f81767c071203c385c49f6de4795d4
| 26.600496 | 98 | 0.529533 | 4.939165 | false | false | false | false |
byu-oit/ios-byuSuite
|
byuSuite/Apps/LockerRental/model/LockerRentalClient.swift
|
1
|
6311
|
//
// LockerRentalClient.swift
// byuSuite
//
// Created by Erik Brady on 7/19/17.
// Copyright © 2017 Brigham Young University. All rights reserved.
//
private let BASE_URL = "https://api.byu.edu/domains/locker-rental/v1"
class LockerRentalClient: ByuClient2 {
static func getAgreements(callback: @escaping ([LockerRentalAgreement]?, ByuError?) -> Void) {
let req = createRequest(pathParams: ["lockers", "person"])
makeRequest(req) { (response) in
if response.succeeded,
let responseData = response.getDataJson() as? [String: Any],
let data = responseData["agreements"] as? [[String: Any]] {
callback(data.map { LockerRentalAgreement(dict: $0) }, nil)
} else {
callback(nil, response.error)
}
}
}
static func getLocker(lockerId: Int, callback: @escaping (LockerRentalLocker?, ByuError?) -> Void) {
let req = createRequest(pathParams: ["lockers", "locations", "\(lockerId)"])
makeRequest(req) { (response) in
if response.succeeded,
let data = response.getDataJson() as? [String: Any],
let lockerDict = data["locker"] as? [String: Any] {
callback(LockerRentalLocker(dict: lockerDict), nil)
} else {
callback(nil, response.error)
}
}
}
static func getLockerCombination(serialNumber: String, callback: @escaping (String?, ByuError?) -> Void) {
let req = createRequest(pathParams: ["locks", serialNumber])
makeRequest(req) { (response) in
if response.succeeded,
let data = response.getDataJson() as? [String: Any],
let combination = data["locks"] as? String {
callback(combination, nil)
} else {
callback(nil, response.error)
}
}
}
static func getFees(locker: LockerRentalLocker, callback: @escaping ([LockerRentalLockerFee]?, ByuError?) -> Void) {
if let building = locker.building,
let lockerNumber = locker.displayedLockerNumber {
let req = createRequest(pathParams: ["buildings", building, "lockers", lockerNumber, "fees"])
makeRequest(req) { (response) in
if response.succeeded,
let responseData = response.getDataJson() as? [String: Any],
let data = responseData["fees"] as? [[String: Any]] {
callback(data.map { LockerRentalLockerFee(dict: $0) }, nil)
} else {
callback(nil, response.error)
}
}
} else {
callback(nil, ByuError(error: nil, readableMessage: "Insufficient data to perform this operation"))
}
}
static func rent(locker: LockerRentalLocker, with fee:LockerRentalLockerFee, callback: @escaping (String?, ByuError?) -> Void) {
if let building = locker.building,
let lockerNumber = locker.displayedLockerNumber,
let feeId = fee.feeId {
let req = createRequest(method: .POST, pathParams: ["buildings", building, "lockers", lockerNumber, feeId])
makeRequest(req) { (response) in
if response.succeeded,
let data = response.getDataJson() as? [String: Any],
let rentStatus = data["registerLocker"] as? String {
callback(rentStatus, nil)
} else {
callback(nil, response.error)
}
}
} else {
callback(nil, ByuError(error: nil, readableMessage: "Insufficient data to perform this operation"))
}
}
static func getBuildings(callback: @escaping ([LockerRentalBuilding]?, ByuError?) -> Void) {
let req = createRequest(pathParams: ["buildings"])
makeRequest(req) { (response) in
if response.succeeded,
let responseData = response.getDataJson() as? [String: Any],
let data = responseData["buildings"] as? [[String: Any]] {
callback(data.map { LockerRentalBuilding(dict: $0) }, nil)
} else {
callback(nil, response.error)
}
}
}
static func getFloors(buildingAbbreviation: String, callback: @escaping ([LockerRentalBuildingFloor]?, ByuError?) -> Void) {
let req = createRequest(pathParams: ["buildings", buildingAbbreviation, "floors"])
makeRequest(req) { (response) in
if response.succeeded,
let responseData = response.getDataJson() as? [String: Any],
let data = responseData["buildingFloorWithAvailableCountList"] as? [[String: Any]] {
callback(data.map { LockerRentalBuildingFloor(dict: $0) }, nil)
} else {
callback(nil, response.error)
}
}
}
static func getLockers(floor: LockerRentalBuildingFloor, callback: @escaping ([LockerRentalLocker]?, ByuError?) -> Void) {
if let building = floor.building,
let buildingFloor = floor.floor {
let req = createRequest(pathParams: ["buildings", building, "floors", buildingFloor])
makeRequest(req) { (response) in
if response.succeeded,
let responseData = response.getDataJson() as? [String: Any],
let data = responseData["lockers"] as? [[String: Any]] {
callback(data.map { LockerRentalLocker(dict: $0) }, nil)
} else {
callback(nil, response.error)
}
}
} else {
callback(nil, ByuError(error: nil, readableMessage: "Insufficient data to perform this operation"))
}
}
private static func createRequest(method: ByuRequest2.RequestMethod = .GET, pathParams: [String]) -> ByuRequest2 {
return ByuRequest2(requestMethod: method, url: super.url(base: BASE_URL, pathParams: pathParams))
}
}
|
apache-2.0
|
3f7bc42c7672f17252c3e49c20fa41e7
| 41.92517 | 132 | 0.552932 | 4.733683 | false | false | false | false |
zakkhoyt/ColorPicKit
|
ColorPicKit/Classes/YUVASpectrum.swift
|
1
|
779
|
//
// YUVASpectrum.swift
// ColorPicKitExample
//
// Created by Zakk Hoyt on 10/26/16.
// Copyright © 2016 Zakk Hoyt. All rights reserved.
//
import UIKit
private let invalidPositionValue = CGFloat(-1.0)
@IBDesignable public class YUVASpectrum: Spectrum {
fileprivate var yuvaSpectrumView = YUVSpectrumView()
override func configureSpectrum() {
yuvaSpectrumView.borderWidth = borderWidth
yuvaSpectrumView.borderColor = borderColor
addSubview(yuvaSpectrumView)
self.spectrumView = yuvaSpectrumView
}
override func colorAt(position: CGPoint) -> UIColor {
let rgb = yuvaSpectrumView.rgbaFor(point: position)
return UIColor(red: rgb.red, green: rgb.green, blue: rgb.blue, alpha: 1.0)
}
}
|
mit
|
6a7f0bb1349c6e88472a173b9fe93f49
| 26.785714 | 82 | 0.687661 | 3.652582 | false | false | false | false |
zakkhoyt/ColorPicKit
|
ColorPicKit/Classes/DeleteButton.swift
|
1
|
2219
|
//
// DeleteButton.swift
// ColorPicKitExample
//
// Created by Zakk Hoyt on 1/23/17.
// Copyright © 2017 Zakk Hoyt. All rights reserved.
//
import UIKit
class DeleteButton: KeyPadButton {
var topLine: CAShapeLayer!
var bottomLine: CAShapeLayer!
override func layoutSubviews() {
super.layoutSubviews()
if let _ = self.topLine {
self.topLine?.removeFromSuperlayer()
self.topLine = nil
}
if let _ = self.bottomLine {
self.bottomLine?.removeFromSuperlayer()
self.bottomLine = nil
}
let lineColor = UIColor.black.cgColor
topLine = CAShapeLayer()
layer.addSublayer(topLine!)
bottomLine = CAShapeLayer()
layer.addSublayer(bottomLine!)
let centerX = self.bounds.midX
let centerY = self.bounds.midY
do {
let path = UIBezierPath()
// Right triangle with an hyp of 15. Each side is 10.6, half that is 5.3
do {
let x: CGFloat = centerX - 5.3
let y: CGFloat = centerY + 1
path.move(to: CGPoint(x: x, y: y))
}
do {
let x: CGFloat = centerX + 5.3
let y: CGFloat = centerY - 10.6
path.addLine(to: CGPoint(x: x, y: y))
}
topLine?.fillColor = lineColor
topLine?.strokeColor = lineColor
topLine.path = path.cgPath
topLine.lineWidth = 3.0
}
do {
let path = UIBezierPath()
do {
let x: CGFloat = centerX - 5.3
let y: CGFloat = centerY - 1
path.move(to: CGPoint(x: x, y: y))
}
do {
let x: CGFloat = centerX + 5.3
let y: CGFloat = centerY + 10.6
path.addLine(to: CGPoint(x: x, y: y))
}
bottomLine?.fillColor = lineColor
bottomLine?.strokeColor = lineColor
bottomLine.path = path.cgPath
bottomLine.lineWidth = 3.0
}
}
}
|
mit
|
8b2c5b183a3b1b497c20298d69b69c91
| 25.722892 | 84 | 0.48422 | 4.842795 | false | false | false | false |
meanjoe45/JKBCrypt
|
examples/JKBCrypt/JKBCrypt/ViewController.swift
|
2
|
2018
|
//
// ViewController.swift
// JKBCrypt
//
// Created by Joe Kramer on 6/19/15.
// Copyright (c) 2015 Joe Kramer. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
// MARK: - Property List
@IBOutlet weak var hashLabel: UILabel!
@IBOutlet weak var hashInputTextField: UITextField!
@IBOutlet weak var saltInputTextField: UITextField!
@IBOutlet weak var compareLabel: UILabel!
@IBOutlet weak var compareInputTextField: UITextField!
// MARK: - Action Methods
@IBAction func generateSaltPressed() {
self.hashLabel.text = self.generateSalt()
}
@IBAction func createHashPressed() {
if let hash = JKBCrypt.hashPassword(self.hashInputTextField.text, withSalt: self.generateSalt()) {
self.hashLabel.text = hash
}
else {
self.hashLabel.text = "Hash generation failed"
}
}
@IBAction func compareHashPressed() {
if let compare = JKBCrypt.verifyPassword(self.compareInputTextField.text, matchesHash:self.hashLabel.text!) {
if compare {
self.compareLabel.text = "The phrase was a SUCCESS!"
}
else {
self.compareLabel.text = "Compare phrase does NOT match hashed value"
}
}
else {
self.compareLabel.text = "Compare hash generation failed"
}
}
@IBAction func hideKeyboard() {
self.hashInputTextField.resignFirstResponder()
self.saltInputTextField.resignFirstResponder()
self.compareInputTextField.resignFirstResponder()
}
// MARK: - Internal Methods
func generateSalt() -> String {
let rounds : Int? = self.saltInputTextField.text.toInt()
var salt : String
if rounds != nil && rounds >= 4 && rounds <= 31 {
salt = JKBCrypt.generateSaltWithNumberOfRounds(UInt(rounds!))
}
else {
salt = JKBCrypt.generateSalt()
}
return salt
}
}
|
apache-2.0
|
44bce91a5cbe87b7cb3042de7370c6d5
| 27.422535 | 117 | 0.620416 | 4.660508 | false | false | false | false |
pcperini/JavascriptEngine
|
JavascriptEngine/JSRemoteSourceFile.swift
|
1
|
4785
|
//
// JSRemoteSourceFile.swift
// JavascriptEngine
//
// Created by PATRICK PERINI on 7/19/15.
// Copyright (c) 2015 Atomic. All rights reserved.
//
import Foundation
import AFNetworking
@objc public protocol JSRemoteSourceFileDelegate {
// MARK: Optionals
func remoteSoureFile(file: JSRemoteSourceFile, didUpdateContent content: String?)
}
public class JSRemoteSourceFile: NSObject {
// MARK: Properties
public weak var delegate: JSRemoteSourceFileDelegate?
private let fileName: String
private let localCachePath: String
private var updatingFromLocal: Bool = false
private(set) public var content: String? {
didSet {
if oldValue != self.content {
self.delegate?.remoteSoureFile(self, didUpdateContent: self.content)
}
if !self.updatingFromLocal {
self.saveContentToFileAtPath(self.localCachePath)
}
}
}
public var remoteRetryDelay: NSTimeInterval = 1.0
private let remoteURL: NSURL
private var updatingFromRemote: Bool = false
private let networkManager: AFHTTPRequestOperationManager = {
let manager = AFHTTPRequestOperationManager()
manager.responseSerializer = AFHTTPResponseSerializer()
manager.completionQueue = dispatch_get_main_queue()
return manager
}()
// MARK: Class Initializers
public override class func initialize() {
super.initialize()
AFNetworkReachabilityManager.sharedManager().startMonitoring()
}
// MARK: Initializers
public required init(remoteURL: NSURL) {
self.fileName = remoteURL.lastPathComponent!
self.remoteURL = remoteURL
let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory,
NSSearchPathDomainMask.UserDomainMask,
true)
self.localCachePath = (paths.first! as NSString).stringByAppendingPathComponent(self.fileName)
super.init()
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "remoteReachabilityDidChange:",
name: AFNetworkingReachabilityDidChangeNotification,
object: nil)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
// MARK: Mutators
public func updateContent(retryDelay: NSTimeInterval = 0.0) {
// Wait for delay
if retryDelay > 0.0 {
let afterTime = Int64(NSTimeInterval(NSEC_PER_SEC) * retryDelay)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, afterTime), dispatch_get_main_queue()) {
self.updateContent(0.0)
}
return
}
// Grab from disk if possible
self.updateContentFromFileAtPath(self.localCachePath)
// Update from remote
if !self.updatingFromRemote && AFNetworkReachabilityManager.sharedManager().reachable {
self.updatingFromRemote = true
self.networkManager.GET(self.remoteURL.absoluteString, parameters: nil, success: { (op: AFHTTPRequestOperation!, response: AnyObject!) in
if let responseData = response as? NSData {
self.content = NSString(data: responseData, encoding: NSUTF8StringEncoding) as String?
}
self.updatingFromRemote = false
if self.content == nil {
self.updateContent(self.remoteRetryDelay)
}
}, failure: { (op: AFHTTPRequestOperation?, error: NSError?) in
self.updatingFromRemote = false
self.updateContent(self.remoteRetryDelay)
})
}
}
private func updateContentFromFileAtPath(filePath: String) {
self.updatingFromLocal = true
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
let content = (try? NSString(contentsOfFile: filePath,
encoding: NSUTF8StringEncoding)) as String?
dispatch_async(dispatch_get_main_queue()) {
self.content = content
self.updatingFromLocal = false
}
}
}
private func saveContentToFileAtPath(filePath: String) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
let _ = try? self.content?.writeToFile(filePath,
atomically: true,
encoding: NSUTF8StringEncoding)
}
}
// MARK: Responders
internal func remoteReachabilityDidChange(notification: NSNotification) {
self.updateContent()
}
}
|
mit
|
1a2b10ed4d8067f8fc41420a3aa7ba14
| 34.183824 | 149 | 0.621944 | 5.388514 | false | false | false | false |
frootloops/swift
|
stdlib/public/core/UTFEncoding.swift
|
4
|
3365
|
//===--- UTFEncoding.swift - Common guts of the big 3 UnicodeEncodings ----===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// These components would be internal if it were possible to use internal
// protocols to supply public conformance requirements.
//
//===----------------------------------------------------------------------===//
public protocol _UTFParser {
associatedtype Encoding : _UnicodeEncoding
func _parseMultipleCodeUnits() -> (isValid: Bool, bitCount: UInt8)
func _bufferedScalar(bitCount: UInt8) -> Encoding.EncodedScalar
var _buffer: _UIntBuffer<UInt32, Encoding.CodeUnit> { get set }
}
extension _UTFParser
where Encoding.EncodedScalar : RangeReplaceableCollection {
@_inlineable // FIXME(sil-serialize-all)
@inline(__always)
public mutating func parseScalar<I : IteratorProtocol>(
from input: inout I
) -> Unicode.ParseResult<Encoding.EncodedScalar>
where I.Element == Encoding.CodeUnit {
// Bufferless single-scalar fastpath.
if _fastPath(_buffer.isEmpty) {
guard let codeUnit = input.next() else { return .emptyInput }
// ASCII, return immediately.
if Encoding._isScalar(codeUnit) {
return .valid(Encoding.EncodedScalar(CollectionOfOne(codeUnit)))
}
// Non-ASCII, proceed to buffering mode.
_buffer.append(codeUnit)
} else if Encoding._isScalar(
Encoding.CodeUnit(truncatingIfNeeded: _buffer._storage)
) {
// ASCII in _buffer. We don't refill the buffer so we can return
// to bufferless mode once we've exhausted it.
let codeUnit = Encoding.CodeUnit(truncatingIfNeeded: _buffer._storage)
_buffer.remove(at: _buffer.startIndex)
return .valid(Encoding.EncodedScalar(CollectionOfOne(codeUnit)))
}
// Buffering mode.
// Fill buffer back to 4 bytes (or as many as are left in the iterator).
repeat {
if let codeUnit = input.next() {
_buffer.append(codeUnit)
} else {
if _buffer.isEmpty { return .emptyInput }
break // We still have some bytes left in our buffer.
}
} while _buffer.count < _buffer.capacity
// Find one unicode scalar.
let (isValid, scalarBitCount) = _parseMultipleCodeUnits()
_sanityCheck(scalarBitCount % numericCast(Encoding.CodeUnit.bitWidth) == 0)
_sanityCheck(1...4 ~= scalarBitCount / 8)
_sanityCheck(scalarBitCount <= _buffer._bitCount)
// Consume the decoded bytes (or maximal subpart of ill-formed sequence).
let encodedScalar = _bufferedScalar(bitCount: scalarBitCount)
_buffer._storage = UInt32(
// widen to 64 bits so that we can empty the buffer in the 4-byte case
truncatingIfNeeded: UInt64(_buffer._storage) &>> scalarBitCount)
_buffer._bitCount = _buffer._bitCount &- scalarBitCount
if _fastPath(isValid) {
return .valid(encodedScalar)
}
return .error(
length: Int(scalarBitCount / numericCast(Encoding.CodeUnit.bitWidth)))
}
}
|
apache-2.0
|
9dbb643ddc1eca5d80cc4ab0643b4881
| 37.238636 | 80 | 0.657355 | 4.565807 | false | false | false | false |
jpsim/Yams
|
Sources/Yams/String+Yams.swift
|
1
|
3136
|
//
// String+Yams.swift
// Yams
//
// Created by Norio Nomura on 12/7/16.
// Copyright (c) 2016 Yams. All rights reserved.
//
import Foundation
extension String {
typealias LineNumberColumnAndContents = (lineNumber: Int, column: Int, contents: String)
/// line number, column and contents at offset.
///
/// - parameter offset: Int
///
/// - returns: lineNumber: line number start from 0,
/// column: utf16 column start from 0,
/// contents: substring of line
func lineNumberColumnAndContents(at offset: Int) -> LineNumberColumnAndContents? {
return index(startIndex, offsetBy: offset, limitedBy: endIndex).flatMap(lineNumberColumnAndContents)
}
/// line number, column and contents at Index.
///
/// - parameter index: String.Index
///
/// - returns: lineNumber: line number start from 0,
/// column: utf16 column start from 0,
/// contents: substring of line
func lineNumberColumnAndContents(at index: Index) -> LineNumberColumnAndContents {
assert((startIndex..<endIndex).contains(index))
var number = 0
var outStartIndex = startIndex, outEndIndex = startIndex, outContentsEndIndex = startIndex
getLineStart(&outStartIndex, end: &outEndIndex, contentsEnd: &outContentsEndIndex,
for: startIndex..<startIndex)
while outEndIndex <= index && outEndIndex < endIndex {
number += 1
let range: Range = outEndIndex..<outEndIndex
getLineStart(&outStartIndex, end: &outEndIndex, contentsEnd: &outContentsEndIndex,
for: range)
}
let utf16StartIndex = outStartIndex.samePosition(in: utf16)!
let utf16Index = index.samePosition(in: utf16)!
return (
number,
utf16.distance(from: utf16StartIndex, to: utf16Index),
String(self[outStartIndex..<outEndIndex])
)
}
/// substring indicated by line number.
///
/// - parameter line: line number starts from 0.
///
/// - returns: substring of line contains line ending characters
func substring(at line: Int) -> String {
var number = 0
var outStartIndex = startIndex, outEndIndex = startIndex, outContentsEndIndex = startIndex
getLineStart(&outStartIndex, end: &outEndIndex, contentsEnd: &outContentsEndIndex,
for: startIndex..<startIndex)
while number < line && outEndIndex < endIndex {
number += 1
let range: Range = outEndIndex..<outEndIndex
getLineStart(&outStartIndex, end: &outEndIndex, contentsEnd: &outContentsEndIndex,
for: range)
}
return String(self[outStartIndex..<outEndIndex])
}
/// String appending newline if is not ending with newline.
var endingWithNewLine: String {
let isEndsWithNewLines = unicodeScalars.last.map(CharacterSet.newlines.contains) ?? false
if isEndsWithNewLines {
return self
} else {
return self + "\n"
}
}
}
|
mit
|
4633d1ff073746c10aaa6c07d270c5c9
| 37.716049 | 108 | 0.62213 | 5.001595 | false | false | false | false |
RMizin/PigeonMessenger-project
|
FalconMessenger/ChatsControllers/InAppNotificationManager.swift
|
1
|
7097
|
//
// InAppNotificationManager.swift
// FalconMessenger
//
// Created by Roman Mizin on 8/21/18.
// Copyright © 2018 Roman Mizin. All rights reserved.
//
import UIKit
import FirebaseDatabase
import FirebaseAuth
import AudioToolbox
import SafariServices
import CropViewController
class InAppNotificationManager: NSObject {
fileprivate var notificationReference: DatabaseReference!
fileprivate var notificationHandle = [(handle: DatabaseHandle, chatID: String)]()
fileprivate var conversations = [Conversation]()
func updateConversations(to conversations: [Conversation]) {
self.conversations = conversations
}
func removeAllObservers() {
guard let currentUserID = Auth.auth().currentUser?.uid, notificationReference != nil else { return }
let reference = Database.database().reference()
for handle in notificationHandle {
notificationReference = reference.child("user-messages").child(currentUserID).child(handle.chatID).child(messageMetaDataFirebaseFolder)
notificationReference.removeObserver(withHandle: handle.handle)
}
notificationHandle.removeAll()
}
func observersForNotifications(conversations: [Conversation]) {
removeAllObservers()
updateConversations(to: conversations)
for conversation in self.conversations {
guard let currentUserID = Auth.auth().currentUser?.uid, let chatID = conversation.chatID else { continue }
let handle = DatabaseHandle()
let element = (handle: handle, chatID: chatID)
notificationHandle.insert(element, at: 0)
notificationReference = Database.database().reference().child("user-messages").child(currentUserID).child(chatID).child(messageMetaDataFirebaseFolder)
notificationHandle[0].handle = notificationReference.observe(.childChanged, with: { (snapshot) in
guard snapshot.key == "lastMessageID" else { return }
guard let messageID = snapshot.value as? String else { return }
guard let oldMessageID = conversation.lastMessageID, messageID > oldMessageID else { return }
let lastMessageReference = Database.database().reference().child("messages").child(messageID)
lastMessageReference.observeSingleEvent(of: .value, with: { (snapshot) in
guard var dictionary = snapshot.value as? [String: AnyObject] else { return }
dictionary.updateValue(messageID as AnyObject, forKey: "messageUID")
let message = Message(dictionary: dictionary)
guard let uid = Auth.auth().currentUser?.uid, message.fromId != uid else { return }
self.handleInAppSoundPlaying(message: message, conversation: conversation, conversations: self.conversations)
})
})
}
}
func handleInAppSoundPlaying(message: Message, conversation: Conversation, conversations: [Conversation]) {
if UIApplication.topViewController() is SFSafariViewController ||
UIApplication.topViewController() is CropViewController ||
UIApplication.topViewController() is INSPhotosViewController { return }
if DeviceType.isIPad {
if let chatLogController = UIApplication.topViewController() as? ChatLogViewController,
let currentOpenedChat = chatLogController.conversation?.chatID,
let conversationID = conversation.chatID {
if currentOpenedChat == conversationID { return }
}
} else {
if UIApplication.topViewController() is ChatLogViewController { return }
}
if let index = conversations.firstIndex(where: { (conv) -> Bool in
return conv.chatID == conversation.chatID
}) {
let isGroupChat = conversations[index].isGroupChat.value ?? false
if let muted = conversations[index].muted.value, !muted, let chatName = conversations[index].chatName {
self.playNotificationSound()
if userDefaults.currentBoolObjectState(for: userDefaults.inAppNotifications) {
self.showInAppNotification(conversation: conversations[index], title: chatName, subtitle: self.subtitleForMessage(message: message), resource: conversationAvatar(resource: conversations[index].chatThumbnailPhotoURL, isGroupChat: isGroupChat), placeholder: conversationPlaceholder(isGroupChat: isGroupChat) )
}
} else if let chatName = conversations[index].chatName, conversations[index].muted.value == nil {
self.playNotificationSound()
if userDefaults.currentBoolObjectState(for: userDefaults.inAppNotifications) {
self.showInAppNotification(conversation: conversations[index], title: chatName, subtitle: self.subtitleForMessage(message: message), resource: conversationAvatar(resource: conversations[index].chatThumbnailPhotoURL, isGroupChat: isGroupChat), placeholder: conversationPlaceholder(isGroupChat: isGroupChat))
}
}
}
}
fileprivate func subtitleForMessage(message: Message) -> String {
if (message.imageUrl != nil || message.localImage != nil) && message.videoUrl == nil {
return MessageSubtitle.image
} else if (message.imageUrl != nil || message.localImage != nil) && message.videoUrl != nil {
return MessageSubtitle.video
} else if message.voiceEncodedString != nil {
return MessageSubtitle.audio
} else {
return message.text ?? ""
}
}
fileprivate func conversationAvatar(resource: String?, isGroupChat: Bool) -> Any {
let placeHolderImage = isGroupChat ? UIImage(named: "GroupIcon") : UIImage(named: "UserpicIcon")
guard let imageURL = resource, imageURL != "" else { return placeHolderImage! }
return URL(string: imageURL)!
}
fileprivate func conversationPlaceholder(isGroupChat: Bool) -> Data? {
let placeHolderImage = isGroupChat ? UIImage(named: "GroupIcon") : UIImage(named: "UserpicIcon")
guard let data = placeHolderImage?.asJPEGData else {
return nil
}
return data
}
fileprivate func showInAppNotification(conversation: Conversation, title: String, subtitle: String, resource: Any?, placeholder: Data?) {
let notification: InAppNotification = InAppNotification(resource: resource, title: title, subtitle: subtitle, data: placeholder)
InAppNotificationDispatcher.shared.show(notification: notification) { (_) in
guard let controller = UIApplication.shared.keyWindow?.rootViewController else { return }
guard let id = conversation.chatID, let realmConversation = RealmKeychain.defaultRealm.objects(Conversation.self).filter("chatID == %@", id).first else {
chatLogPresenter.open(conversation, controller: controller)
return
}
chatLogPresenter.open(realmConversation, controller: controller)
}
}
fileprivate func playNotificationSound() {
if userDefaults.currentBoolObjectState(for: userDefaults.inAppSounds) {
SystemSoundID.playFileNamed(fileName: "notification", withExtenstion: "caf")
}
if userDefaults.currentBoolObjectState(for: userDefaults.inAppVibration) {
AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))
}
}
}
|
gpl-3.0
|
2a5d86c1c3c1f5f996a50cdcdcf0b070
| 47.937931 | 317 | 0.721674 | 5.029057 | false | false | false | false |
BBRick/wp
|
wp/AppAPI/SocketAPI/SocketReqeust/APISocketHelper.swift
|
1
|
4849
|
//
// APISocketHelper.swift
// viossvc
//
// Created by yaowang on 2016/11/21.
// Copyright © 2016年 ywwlcom.yundian. All rights reserved.
//
import UIKit
import CocoaAsyncSocket
//import XCGLogger
import SVProgressHUD
class APISocketHelper:NSObject, GCDAsyncSocketDelegate,SocketHelper {
var socket: GCDAsyncSocket?;
var dispatch_queue: DispatchQueue!;
var mutableData: NSMutableData = NSMutableData();
var packetHead:SocketPacketHead = SocketPacketHead();
var isConnected : Bool {
return socket!.isConnected
}
override init() {
super.init()
dispatch_queue = DispatchQueue(label: "APISocket_Queue", attributes: DispatchQueue.Attributes.concurrent)
socket = GCDAsyncSocket.init(delegate: self, delegateQueue: dispatch_queue);
connect()
}
func connect() {
mutableData = NSMutableData()
do {
if !socket!.isConnected {
var host = ""
var port: UInt16 = 0
if AppConst.isMock{
host = UserModel.share().token.length() > 0 ? "61.147.114.87" : "61.147.114.78"
port = UserModel.share().token.length() > 0 ? 16001 : 30001
}else{
host = AppConst.Network.TcpServerIP
port = AppConst.Network.TcpServerPort
}
try socket?.connect(toHost: host, onPort: port, withTimeout: 5)
}
} catch GCDAsyncSocketError.closedError {
print("¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯")
} catch GCDAsyncSocketError.connectTimeoutError {
print("<<<<<<<<<<<<<<<<<<<<<<<<")
} catch {
print(">>>>>>>>>>>>>>>>>>>>>>>")
}
}
func disconnect() {
socket?.delegate = nil;
socket?.disconnect()
}
func sendData(_ data: Data) {
objc_sync_enter(self)
socket?.write(data, withTimeout: -1, tag: 0)
objc_sync_exit(self)
}
func onPacketData(_ data: Data) {
memset(&packetHead,0, MemoryLayout<SocketPacketHead>.size)
(data as NSData).getBytes(&packetHead, length: MemoryLayout<SocketPacketHead>.size)
if( Int(packetHead.packet_length) - MemoryLayout<SocketPacketHead>.size == Int(packetHead.data_length) ) {
let packet: SocketDataPacket = SocketDataPacket(socketData: data as NSData)
SocketRequestManage.shared.notifyResponsePacket(packet)
}
else {
debugPrint("onPacketData error packet_length:\(packetHead.packet_length) packet_length:\(packetHead.data_length) data:\(data.count)");
}
// XCGLogger.debug("onPacketData:\(packet.packetHead.type) \(packet.packetHead.packet_length) \(packet.packetHead.operate_code)")
}
//MARK: GCDAsyncSocketDelegate
@objc func socket(_ sock: GCDAsyncSocket, didConnectToHost host: String, port: UInt16) {
debugPrint("didConnectToHost host:\(host) port:\(port)")
sock.perform({
() -> Void in
sock.enableBackgroundingOnSocket()
});
socket?.readData(withTimeout: -1, tag: 0)
}
@objc func socket(_ sock: GCDAsyncSocket, didRead data: Data, withTag tag: CLong) {
// XCGLogger.debug("socket:\(data)")
mutableData.append(data)
while mutableData.length >= 26 {
var packetLen: Int16 = 0;
mutableData.getBytes(&packetLen, length: MemoryLayout<Int16>.size)
if mutableData.length >= Int(packetLen) {
var range: NSRange = NSMakeRange(0, Int(packetLen))
onPacketData(mutableData.subdata(with: range))
range.location = range.length;
range.length = mutableData.length - range.location;
mutableData = (mutableData.subdata(with: range) as NSData).mutableCopy() as! NSMutableData;
} else {
break
}
}
socket?.readData(withTimeout: -1, tag: 0)
}
@objc func socket(_ sock: GCDAsyncSocket, shouldTimeoutReadWithTag tag: CLong, elapsed: TimeInterval, bytesDone length: UInt) -> TimeInterval {
return 0
}
@objc func socket(_ sock: GCDAsyncSocket, shouldTimeoutWriteWithTag tag: CLong, elapsed: TimeInterval, bytesDone length: UInt) -> TimeInterval {
return 0
}
@objc func socketDidDisconnect(_ sock: GCDAsyncSocket, withError err: Error?) {
// XCGLogger.error("socketDidDisconnect:\(err)")
// self.performSelector(#selector(APISocketHelper.connect), withObject: nil, afterDelay: 5)
// SVProgressHUD.showErrorMessage(ErrorMessage: "连接失败,5秒后重连", ForDuration: 5) {[weak self] in
// self?.connect()
// }
}
deinit {
socket?.disconnect()
}
}
|
apache-2.0
|
9bc57318775ca5871417e166f4d8905b
| 36.554688 | 148 | 0.598918 | 4.484142 | false | false | false | false |
ello/ello-ios
|
Specs/Utilities/SafariActivitySpec.swift
|
1
|
2833
|
////
/// SafariActivitySpec.swift
//
@testable import Ello
import Quick
import Nimble
class SafariActivitySpec: QuickSpec {
override func spec() {
describe("SafariActivity") {
var subject: SafariActivity!
beforeEach {
subject = SafariActivity()
}
it("activityType()") {
expect(subject.activityType.rawValue) == "SafariActivity"
}
it("activityTitle()") {
expect(subject.activityTitle) == "Open in Safari"
}
it("activityImage()") {
expect(subject.activityImage).toNot(beNil())
}
context("canPerformWithActivityItems(items: [Any]) -> Bool") {
let url = URL(string: "https://ello.co")!
let url2 = URL(string: "https://google.com")!
let string = "ignore"
let image = UIImage.imageWithColor(.blue)!
let expectations: [(String, [Any], Bool)] = [
("a url", [url], true),
("a url and a string", [url, string], true),
("two urls", [string, url, string, url2], true),
("a string", [string], false),
("a string and an image", [image, string], false),
]
for (description, items, expected) in expectations {
it("should return \(expected) for \(description)") {
expect(subject.canPerform(withActivityItems: items)) == expected
}
}
}
context("prepareWithActivityItems(items: [Any])") {
let url = URL(string: "https://ello.co")!
let url2 = URL(string: "https://google.com")!
let string = "ignore"
let image = UIImage.imageWithColor(.blue)!
let expectations: [(String, [Any], URL?)] = [
("a url", [url], url),
("a url and a string", [url, string], url),
("two urls", [string, url, string, url2], url),
("a string", [string], nil),
("a string and an image", [image, string], nil),
]
for (description, items, expected) in expectations {
it("should assign \(String(describing: expected)) for \(description)") {
subject.prepare(withActivityItems: items)
if expected == nil {
expect(subject.url).to(beNil())
}
else {
expect(subject.url) == expected
}
}
}
}
}
}
}
|
mit
|
c80c82f8b2269c4872922a87c239fcd6
| 34.860759 | 92 | 0.443346 | 5.150909 | false | false | false | false |
QQLS/YouTobe
|
YouTube/Class/Base/View/BQSettingView.swift
|
1
|
3822
|
//
// BQSettingView.swift
// YouTube
//
// Created by xiupai on 2017/3/16.
// Copyright © 2017年 QQLS. All rights reserved.
//
import UIKit
import SnapKit
private let reuseIdentifier = UITableViewCell.nameOfClass
protocol BQSettingViewDelegate: class {
func switchSettingViewTo(hidden: Bool)
}
class BQSettingView: UIView {
// Variate & Constant
let rowHeight: Float = 45
let items = ["设置", "条款和隐私政策", "反馈", "帮助", "切换账户", "取消"]
let itemsImageName = [Asset.Settings.image, Asset.TermsPrivacyPolicy.image, Asset.SendFeedback.image, Asset.Help.image, Asset.SwithAccount.image, Asset.Cancel.image]
weak var delegate: BQSettingViewDelegate?
// MARK: - Lazy
private lazy var tableView: UITableView = {
let tableView = UITableView(frame: .zero, style: .plain)
tableView.delegate = self
tableView.dataSource = self
tableView.separatorStyle = .none
tableView.rowHeight = CGFloat(self.rowHeight)
tableView.register(UITableViewCell.self, forCellReuseIdentifier: reuseIdentifier)
return tableView
}()
private lazy var bgView: UIView = {
let bgView = UIView()
bgView.alpha = 0
bgView.backgroundColor = .black
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(BQSettingView.dismiss))
bgView.addGestureRecognizer(tapGesture)
return bgView
}()
// MARK: - Action
func show() {
tableView.snp.updateConstraints { (make) in
make.top.equalTo(self.snp.bottom).offset(-rowHeight * Float(items.count))
}
UIView.animate(withDuration: 0.25, animations: {
self.bgView.alpha = 0.5
self.tableView.superview?.layoutIfNeeded()
}) { (_) in
self.tableView.reloadData()
}
}
@objc fileprivate func dismiss() {
tableView.snp.updateConstraints { (make) in
make.top.equalTo(self.snp.bottom).offset(0)
}
UIView.animate(withDuration: 0.25, animations: {
self.bgView.alpha = 0
self.tableView.superview?.layoutIfNeeded()
}) { (_) in
self.removeFromSuperview()
self.delegate?.switchSettingViewTo(hidden: true)
}
}
// MARK: - Initial
override init(frame: CGRect) {
super.init(frame: frame)
p_setupView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func p_setupView() {
addSubview(bgView)
bgView.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
addSubview(tableView)
tableView.snp.makeConstraints { (make) in
make.left.centerX.equalToSuperview()
make.top.equalTo(self.snp.bottom).offset(0)
make.height.equalTo(rowHeight * Float(items.count))
}
// 下面的方法只有作用在父视图上才会起作用
layoutIfNeeded()
}
}
extension BQSettingView: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath)
cell.textLabel?.text = items[indexPath.row]
cell.imageView?.image = itemsImageName[indexPath.row]
cell.selectionStyle = .none
return cell
}
}
extension BQSettingView: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
dismiss()
}
}
|
apache-2.0
|
6b0cc5e0ea36fc3f67db3c33ce6aec73
| 30.191667 | 169 | 0.632915 | 4.520531 | false | false | false | false |
stefanilie/swift-playground
|
Swift3 and iOS10/Playgrounds/variables.playground/Contents.swift
|
1
|
298
|
//: Playground - noun: a place where people can play
import UIKit
var message = "Hello, playground"
var amIcool = true
amIcool = !amIcool
var feelGood = true
feelGood = amIcool ? true : false
var account = 100
var cashRegister = account >= 150 ? "you just bought the item" : "you are poor"
|
mit
|
c54d28b5ad6717ef8e50f03bfc73fc39
| 16.529412 | 79 | 0.701342 | 3.274725 | false | false | false | false |
bradhilton/HttpRequest
|
Pods/Convertible/Convertible/Utilities/Keys.swift
|
1
|
3293
|
//
// Properties.swift
// Convertibles
//
// Created by Bradley Hilton on 6/9/15.
// Copyright © 2015 Skyvive. All rights reserved.
//
import Foundation
public protocol UnderscoreToCamelCase {}
public protocol CustomKeyMapping {
var keyMapping: [String : String] { get }
}
public protocol IgnoredKeys {
var ignoredKeys: [String] { get }
}
public protocol RequiredKeys {
var requiredKeys: [String] { get }
}
public protocol OptionalKeys {
var optionalKeys: [String] { get }
}
public protocol AllRequiredKeys {}
public protocol OptionalsAsOptionalKeys {}
let ignoredKeys = ["super", "keyMapping", "ignoredKeys", "requiredKeys", "optionalKeys"]
public struct Key {
let object: Any
public let key: String
let value: Any
let valueType: Any.Type
let summary: String
}
extension Key {
var mappedKey: String {
var mappedKey = key
if let object = object as? CustomKeyMapping, let customKey = object.keyMapping[key] {
mappedKey = customKey
} else if object is UnderscoreToCamelCase {
mappedKey = underscoreFromCamelCase(key)
}
return mappedKey
}
var setKey: String {
var setKey = "set"
if key.length > 0 {
setKey += (key[0] as String).uppercaseString
}
if key.length > 1 {
setKey += (key[1..<key.length] as String)
}
return setKey + ":"
}
}
func requiredKeys(object: Any) -> [Key] {
if let object = object as? RequiredKeys {
return allKeys(object).filter { object.requiredKeys.contains($0.key) }
} else if let object = object as? OptionalKeys {
return allKeys(object).filter { !object.optionalKeys.contains($0.key) }
} else if let object = object as? OptionalsAsOptionalKeys {
return allKeys(object).filter { !($0.valueType is OptionalProtocol.Type) }
} else if let object = object as? AllRequiredKeys {
return allKeys(object)
} else {
return [Key]()
}
}
func allKeys(object: Any) -> [Key] {
var keys = [Key]()
for child in Mirror(reflecting: object).children {
if let key = child.label {
if ignoredKeys.contains(key) {
continue
} else if let object = object as? IgnoredKeys where object.ignoredKeys.contains(key) {
continue
} else {
keys.append(Key(object: object, key: key, value: child.value, valueType: child.value.dynamicType, summary: String(child.value)))
}
}
}
return keys
}
func underscoreFromCamelCase(camelCase: String) -> String {
let options = NSStringEnumerationOptions.ByComposedCharacterSequences
let range = Range<String.Index>(start: camelCase.startIndex, end: camelCase.endIndex)
var underscore = ""
camelCase.enumerateSubstringsInRange(range, options: options) { (substring, substringRange, enclosingRange, shouldContinue) -> () in
if let substring = substring {
if substring.lowercaseString != substring {
underscore += "_" + substring.lowercaseString
} else {
underscore += substring
}
}
}
return underscore
}
|
mit
|
8b745b92c085973000bd0a5c3a855879
| 25.991803 | 144 | 0.615431 | 4.314548 | false | false | false | false |
isaced/fir-mac
|
fir-mac/Controllers/AppDetailViewController.swift
|
1
|
3599
|
//
// AppDetailViewController.swift
// fir-mac
//
// Created by isaced on 2017/5/8.
//
//
import Cocoa
import Kingfisher
class AppDetailViewController: NSViewController {
@IBOutlet weak var appNameTextField: NSTextField!
@IBOutlet weak var appIDTextField: NSTextField!
@IBOutlet weak var bundleIDTextField: NSTextField!
@IBOutlet weak var shortLinkTextField: NSTextField!
@IBOutlet weak var iconImageView: NSImageView!
@IBOutlet weak var shortLinkGoButton: NSButton!
@IBOutlet weak var isOpenedSwitch: NSButton!
@IBOutlet weak var isShowPlazaSwitch: NSButton!
@IBOutlet weak var releaseVersionTextField: NSTextField!
@IBOutlet weak var releaseBuildTextField: NSTextField!
@IBOutlet weak var releaseCreatedAtTextField: NSTextField!
@IBOutlet weak var releaseDistributionNameTextField: NSTextField!
@IBOutlet weak var releaseTypeTextField: NSTextField!
var app: FIRApp? {
didSet{
loadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(forName: NSNotification.Name.FIRListSelectionChange, object: nil, queue: nil) { (noti) in
if let app = noti.object as? FIRApp {
self.app = app
self.loadData()
if app.short == nil {
HTTPManager.shared.fatchAppDetail(app: app, callback: {
self.loadData()
})
}
}
}
}
func loadData() {
appNameTextField.stringValue = app?.name ?? ""
appIDTextField.stringValue = app?.ID ?? ""
bundleIDTextField.stringValue = app?.bundleID ?? ""
shortLinkTextField.stringValue = app?.shortURLString ?? ""
isOpenedSwitch.state = (app?.isOpened ?? false) ? 1 : 0
isShowPlazaSwitch.state = (app?.isShowPlaza ?? false) ? 1 : 0
releaseBuildTextField.stringValue = app?.masterRelease.build ?? ""
releaseVersionTextField.stringValue = app?.masterRelease.version ?? ""
releaseTypeTextField.stringValue = app?.masterRelease.type ?? ""
releaseDistributionNameTextField.stringValue = app?.masterRelease.distributonName ?? ""
if let date = app?.masterRelease.createdAt {
let dateformatter = DateFormatter()
dateformatter.dateStyle = .short
dateformatter.timeStyle = .short
releaseCreatedAtTextField.stringValue = dateformatter.string(from: date)
}
if let shortUrl = app?.shortURLString {
iconImageView.image = Util.generateQRCode(from: shortUrl)
}else{
iconImageView.image = nil
}
// short link go button position
if app?.short == nil {
shortLinkGoButton.isHidden = true
}else{
shortLinkGoButton.isHidden = false
shortLinkTextField.sizeToFit()
shortLinkGoButton.frame = NSRect(x: shortLinkTextField.frame.maxX + 10,
y: shortLinkTextField.frame.minY,
width: shortLinkGoButton.frame.width,
height: shortLinkGoButton.frame.height)
}
}
@IBAction func shortLinkGoAction(_ sender: NSButton) {
if let urlString = self.app?.shortURLString {
if let url = URL(string: urlString) {
NSWorkspace.shared().open(url)
}
}
}
}
|
gpl-3.0
|
4a1d21109626e81342d031fa3540aa6b
| 35.353535 | 136 | 0.600167 | 5.076164 | false | false | false | false |
googlearchive/science-journal-ios
|
ScienceJournal/UI/TimeSelectionView.swift
|
1
|
2975
|
/*
* Copyright 2019 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
import third_party_objective_c_material_components_ios_components_Buttons_Buttons
import third_party_objective_c_material_components_ios_components_Palettes_Palettes
import third_party_objective_c_material_components_ios_components_Typography_Typography
/// A view that displays a timestamp and a confirm button. Used when editing a note's timestamp.
class TimeSelectionView: ShadowedView {
// MARK: - Properties
/// Whether or not to show the confirm button.
var shouldShowConfirmButton: Bool = true {
didSet {
// Set alpha instead of `isHidden`, because the height of the confirm button is what is
// setting the overall height of the stack view.
confirmButton.alpha = shouldShowConfirmButton ? 1 : 0
}
}
private let clockIcon = UIImageView()
let timestampLabel = UILabel()
let confirmButton = MDCFlatButton()
// MARK: - Public
override init(frame: CGRect) {
super.init(frame: frame)
configureView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configureView()
}
// MARK: - Private
private func configureView() {
backgroundColor = .white
layer.cornerRadius = 2
clockIcon.image = UIImage(named: "ic_access_time")
clockIcon.tintColor = MDCPalette.grey.tint500
clockIcon.translatesAutoresizingMaskIntoConstraints = false
clockIcon.setContentHuggingPriority(.defaultHigh, for: .horizontal)
timestampLabel.font = MDCTypography.fontLoader().regularFont(ofSize: 12)
timestampLabel.translatesAutoresizingMaskIntoConstraints = false
confirmButton.setImage(UIImage(named: "ic_check_circle"), for: .normal)
confirmButton.tintColor = MDCPalette.blue.tint500
confirmButton.translatesAutoresizingMaskIntoConstraints = false
confirmButton.setContentHuggingPriority(.defaultHigh, for: .horizontal)
confirmButton.accessibilityLabel = String.saveBtnContentDescription
let stackView = UIStackView(arrangedSubviews: [clockIcon, timestampLabel, confirmButton])
stackView.distribution = .fill
stackView.alignment = .center
stackView.spacing = 10
stackView.translatesAutoresizingMaskIntoConstraints = false
addSubview(stackView)
stackView.pinToEdgesOfView(self,
withInsets: UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 0))
}
}
|
apache-2.0
|
242a1f31f1f52c0119367175fd65a6d2
| 34.843373 | 96 | 0.73916 | 4.663009 | false | false | false | false |
coderMONSTER/iosstar
|
iOSStar/Scenes/Deal/Controllers/DealDetailViewController.swift
|
1
|
2691
|
//
// DealDetailViewController.swift
// iOSStar
//
// Created by J-bb on 17/5/23.
// Copyright © 2017年 YunDian. All rights reserved.
//
import UIKit
class DealDetailViewController: DealBaseViewController ,DealScrollViewScrollDelegate,MenuViewDelegate{
lazy var backView: DealScrollView = {
let view = DealScrollView(frame: CGRect(x: 0, y: 40, width: kScreenWidth, height: kScreenHeight - 40))
return view
}()
var menuView:YD_VMenuView?
override func viewDidLoad() {
super.viewDidLoad()
setupMenuView()
automaticallyAdjustsScrollViewInsets = false
view.addSubview(backView)
backView.delegate = self
addSubViews()
}
func setupMenuView() {
let layout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 0, left: 25, bottom: 0, right: 25)
layout.minimumInteritemSpacing = (kScreenWidth - 50 - 62 * 4) / 3
layout.minimumLineSpacing = (kScreenWidth - 50 - 62 * 4) / 3
layout.scrollDirection = .horizontal
menuView = YD_VMenuView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 30), layout: layout)
menuView?.backgroundColor = UIColor.clear
menuView?.isScreenWidth = true
menuView?.isShowLineView = false
menuView?.isSelectZoom = true
menuView?.items = ["当日成交","当日委托","历史委托","历史成交"]
menuView?.reloadData()
menuView?.delegate = self
view.addSubview(menuView!)
}
func addSubViews() {
let identifiers = ["DetailCommenViewController","DetailCommenViewController","DetailCommenViewController","DetailCommenViewController"]
let types:[UInt16] = [6007, 6001, 6005, 6009]
let stroyBoard = UIStoryboard(name: AppConst.StoryBoardName.Deal.rawValue, bundle: nil)
var views = [UIView]()
for (index,identifier) in identifiers.enumerated() {
let vc = stroyBoard.instantiateViewController(withIdentifier: identifier) as! DetailCommenViewController
vc.type = AppConst.DealDetailType(rawValue: types[index])!
views.append(vc.view)
vc.view.frame = CGRect(x: CGFloat(index) * kScreenWidth, y: 0, width: kScreenWidth, height: backView.frame.size.height - 64)
addChildViewController(vc)
}
backView.setSubViews(customSubViews: views)
}
//menuDelegate
func menuViewDidSelect(indexPath: IndexPath) {
backView.moveToIndex(index: indexPath.item)
}
//backViewDelegate
func scrollToIndex(index: Int) {
menuView?.selected(index: index)
}
}
|
gpl-3.0
|
df138ec8922862aa23c44dde0c5ed68d
| 34.891892 | 143 | 0.652108 | 4.595156 | false | false | false | false |
austinzheng/swift
|
test/SILOptimizer/specialize_self_conforming_error.swift
|
30
|
3372
|
// RUN: %target-swift-frontend -module-name specialize_self_conforming -emit-sil -O -primary-file %s | %FileCheck %s
// Test 1: apply the substitution
// [U:Error => Error:Error]
// to the type argument map
// [T:Error => U:Error]
// on the call to takesError.
@_optimize(none)
func takesError<T : Error>(_: T) {}
@inline(__always)
func callsTakesError<U : Error>(_ error: U) {
takesError(error)
}
// CHECK-LABEL: sil hidden @$s26specialize_self_conforming5test1yys5Error_pF : $@convention(thin) (@guaranteed Error) -> () {
// CHECK: [[TEMP:%.*]] = alloc_stack $Error
// CHECK: store %0 to [[TEMP]]
// CHECK: [[FN:%.*]] = function_ref @$s26specialize_self_conforming10takesErroryyxs0E0RzlF : $@convention(thin) <τ_0_0 where τ_0_0 : Error> (@in_guaranteed τ_0_0) -> ()
// CHECK: apply [[FN]]<Error>([[TEMP]]) : $@convention(thin) <τ_0_0 where τ_0_0 : Error> (@in_guaranteed τ_0_0) -> ()
// CHECK: dealloc_stack [[TEMP]]
// CHECK: return
func test1(_ error: Error) {
callsTakesError(error)
}
// Test 2: apply the substitution
// [U => Int]
// to the type argument map
// [T:Error => Error:Error]
// on the call to takesError.
@inline(__always)
func callsTakesErrorWithError<U>(_ error: Error, _ value : U) {
takesError(error)
}
// CHECK-LABEL: sil hidden @$s26specialize_self_conforming5test2yys5Error_pF : $@convention(thin) (@guaranteed Error) -> () {
// CHECK: [[TEMP:%.*]] = alloc_stack $Error
// CHECK: store %0 to [[TEMP]]
// CHECK: [[FN:%.*]] = function_ref @$s26specialize_self_conforming10takesErroryyxs0E0RzlF : $@convention(thin) <τ_0_0 where τ_0_0 : Error> (@in_guaranteed τ_0_0) -> ()
// CHECK: apply [[FN]]<Error>([[TEMP]]) : $@convention(thin) <τ_0_0 where τ_0_0 : Error> (@in_guaranteed τ_0_0) -> ()
// CHECK: dealloc_stack [[TEMP]]
// CHECK: return
func test2(_ error: Error) {
callsTakesErrorWithError(error, 0)
}
// Test 3: apply the substitution
// [V => Int]
// to the type argument map
// [T:Error => Error:Error, U => V]
// on the call to takesErrorAndValue.
@_optimize(none)
func takesErrorAndValue<T : Error, U>(_: T, _: U) {}
@inline(__always)
func callsTakesErrorAndValueWithError<U>(_ error: Error, _ value : U) {
takesErrorAndValue(error, value)
}
// CHECK-LABEL: sil hidden @$s26specialize_self_conforming5test3yys5Error_pF : $@convention(thin) (@guaranteed Error) -> () {
// CHECK: [[TEMP:%.*]] = alloc_stack $Error
// CHECK: store %0 to [[TEMP]]
// CHECK: [[FN:%.*]] = function_ref @$s26specialize_self_conforming18takesErrorAndValueyyx_q_ts0E0Rzr0_lF : $@convention(thin) <τ_0_0, τ_0_1 where τ_0_0 : Error> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_1) -> ()
// CHECK: apply [[FN]]<Error, Int>([[TEMP]], {{%.*}}) :
// CHECK: dealloc_stack [[TEMP]]
// CHECK: return
func test3(_ error: Error) {
callsTakesErrorAndValueWithError(error, 0)
}
// Test 4: just clone the type argument map
// [Self:P => opened:P, T:Error => Error:Error]
// When the inliner is cloning a substitution map that includes an opened
// archetype, it uses a substitution function that expects not to be called
// on types it's not expecting.
protocol P {}
extension P {
@_optimize(none)
func exTakesError<T: Error>(_: T) {}
}
@inline(__always)
func callsExTakesErrorWithError(_ p: P, _ error: Error) {
p.exTakesError(error)
}
func test4(_ p: P, _ error: Error) {
callsExTakesErrorWithError(p, error)
}
|
apache-2.0
|
20a57900d69ee1e2b719a165afac8907
| 33.587629 | 212 | 0.657526 | 3.058341 | false | true | false | false |
klundberg/swift-corelibs-foundation
|
Foundation/DateComponents.swift
|
1
|
14332
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/**
`DateComponents` encapsulates the components of a date in an extendable, structured manner.
It is used to specify a date by providing the temporal components that make up a date and time in a particular calendar: hour, minutes, seconds, day, month, year, and so on. It can also be used to specify a duration of time, for example, 5 hours and 16 minutes. A `DateComponents` is not required to define all the component fields.
When a new instance of `DateComponents` is created, the date components are set to `nil`.
*/
public struct DateComponents : ReferenceConvertible, Hashable, Equatable, _MutableBoxing {
public typealias ReferenceType = NSDateComponents
internal var _handle: _MutableHandle<NSDateComponents>
/// Initialize a `DateComponents`, optionally specifying values for its fields.
public init(calendar: Calendar? = nil,
timeZone: TimeZone? = nil,
era: Int? = nil,
year: Int? = nil,
month: Int? = nil,
day: Int? = nil,
hour: Int? = nil,
minute: Int? = nil,
second: Int? = nil,
nanosecond: Int? = nil,
weekday: Int? = nil,
weekdayOrdinal: Int? = nil,
quarter: Int? = nil,
weekOfMonth: Int? = nil,
weekOfYear: Int? = nil,
yearForWeekOfYear: Int? = nil) {
_handle = _MutableHandle(adoptingReference: NSDateComponents())
if let _calendar = calendar { self.calendar = _calendar }
if let _timeZone = timeZone { self.timeZone = _timeZone }
if let _era = era { self.era = _era }
if let _year = year { self.year = _year }
if let _month = month { self.month = _month }
if let _day = day { self.day = _day }
if let _hour = hour { self.hour = _hour }
if let _minute = minute { self.minute = _minute }
if let _second = second { self.second = _second }
if let _nanosecond = nanosecond { self.nanosecond = _nanosecond }
if let _weekday = weekday { self.weekday = _weekday }
if let _weekdayOrdinal = weekdayOrdinal { self.weekdayOrdinal = _weekdayOrdinal }
if let _quarter = quarter { self.quarter = _quarter }
if let _weekOfMonth = weekOfMonth { self.weekOfMonth = _weekOfMonth }
if let _weekOfYear = weekOfYear { self.weekOfYear = _weekOfYear }
if let _yearForWeekOfYear = yearForWeekOfYear { self.yearForWeekOfYear = _yearForWeekOfYear }
}
// MARK: - Properties
/// Translate from the NSDateComponentUndefined value into a proper Swift optional
private func _getter(_ x : Int) -> Int? { return x == NSDateComponentUndefined ? nil : x }
/// Translate from the proper Swift optional value into an NSDateComponentUndefined
private func _setter(_ x : Int?) -> Int { if let xx = x { return xx } else { return NSDateComponentUndefined } }
/// The `Calendar` used to interpret the other values in this structure.
///
/// - note: API which uses `DateComponents` may have different behavior if this value is `nil`. For example, assuming the current calendar or ignoring certain values.
public var calendar: Calendar? {
get { return _handle.map { $0.calendar } }
set { _applyMutation { $0.calendar = newValue } }
}
/// A time zone.
/// - note: This value is interpreted in the context of the calendar in which it is used.
public var timeZone: TimeZone? {
get { return _handle.map { $0.timeZone } }
set { _applyMutation { $0.timeZone = newValue } }
}
/// An era or count of eras.
/// - note: This value is interpreted in the context of the calendar in which it is used.
public var era: Int? {
get { return _handle.map { _getter($0.era) } }
set { _applyMutation { $0.era = _setter(newValue) } }
}
/// A year or count of years.
/// - note: This value is interpreted in the context of the calendar in which it is used.
public var year: Int? {
get { return _handle.map { _getter($0.year) } }
set { _applyMutation { $0.year = _setter(newValue) } }
}
/// A month or count of months.
/// - note: This value is interpreted in the context of the calendar in which it is used.
public var month: Int? {
get { return _handle.map { _getter($0.month) } }
set { _applyMutation { $0.month = _setter(newValue) } }
}
/// A day or count of days.
/// - note: This value is interpreted in the context of the calendar in which it is used.
public var day: Int? {
get { return _handle.map { _getter($0.day) } }
set { _applyMutation { $0.day = _setter(newValue) } }
}
/// An hour or count of hours.
/// - note: This value is interpreted in the context of the calendar in which it is used.
public var hour: Int? {
get { return _handle.map { _getter($0.hour) } }
set { _applyMutation { $0.hour = _setter(newValue) } }
}
/// A minute or count of minutes.
/// - note: This value is interpreted in the context of the calendar in which it is used.
public var minute: Int? {
get { return _handle.map { _getter($0.minute) } }
set { _applyMutation { $0.minute = _setter(newValue) } }
}
/// A second or count of seconds.
/// - note: This value is interpreted in the context of the calendar in which it is used.
public var second: Int? {
get { return _handle.map { _getter($0.second) } }
set { _applyMutation { $0.second = _setter(newValue) } }
}
/// A nanosecond or count of nanoseconds.
/// - note: This value is interpreted in the context of the calendar in which it is used.
public var nanosecond: Int? {
get { return _handle.map { _getter($0.nanosecond) } }
set { _applyMutation { $0.nanosecond = _setter(newValue) } }
}
/// A weekday or count of weekdays.
/// - note: This value is interpreted in the context of the calendar in which it is used.
public var weekday: Int? {
get { return _handle.map { _getter($0.weekday) } }
set { _applyMutation { $0.weekday = _setter(newValue) } }
}
/// A weekday ordinal or count of weekday ordinals.
/// Weekday ordinal units represent the position of the weekday within the next larger calendar unit, such as the month. For example, 2 is the weekday ordinal unit for the second Friday of the month.///
/// - note: This value is interpreted in the context of the calendar in which it is used.
public var weekdayOrdinal: Int? {
get { return _handle.map { _getter($0.weekdayOrdinal) } }
set { _applyMutation { $0.weekdayOrdinal = _setter(newValue) } }
}
/// A quarter or count of quarters.
/// - note: This value is interpreted in the context of the calendar in which it is used.
public var quarter: Int? {
get { return _handle.map { _getter($0.quarter) } }
set { _applyMutation { $0.quarter = _setter(newValue) } }
}
/// A week of the month or a count of weeks of the month.
/// - note: This value is interpreted in the context of the calendar in which it is used.
public var weekOfMonth: Int? {
get { return _handle.map { _getter($0.weekOfMonth) } }
set { _applyMutation { $0.weekOfMonth = _setter(newValue) } }
}
/// A week of the year or count of the weeks of the year.
/// - note: This value is interpreted in the context of the calendar in which it is used.
public var weekOfYear: Int? {
get { return _handle.map { _getter($0.weekOfYear) } }
set { _applyMutation { $0.weekOfYear = _setter(newValue) } }
}
/// The ISO 8601 week-numbering year of the receiver.
///
/// The Gregorian calendar defines a week to have 7 days, and a year to have 356 days, or 366 in a leap year. However, neither 356 or 366 divide evenly into a 7 day week, so it is often the case that the last week of a year ends on a day in the next year, and the first week of a year begins in the preceding year. To reconcile this, ISO 8601 defines a week-numbering year, consisting of either 52 or 53 full weeks (364 or 371 days), such that the first week of a year is designated to be the week containing the first Thursday of the year.
///
/// You can use the yearForWeekOfYear property with the weekOfYear and weekday properties to get the date corresponding to a particular weekday of a given week of a year. For example, the 6th day of the 53rd week of the year 2005 (ISO 2005-W53-6) corresponds to Sat 1 January 2005 on the Gregorian calendar.
/// - note: This value is interpreted in the context of the calendar in which it is used.
public var yearForWeekOfYear: Int? {
get { return _handle.map { _getter($0.yearForWeekOfYear) } }
set { _applyMutation { $0.yearForWeekOfYear = _setter(newValue) } }
}
/// Set to true if these components represent a leap month.
public var isLeapMonth: Bool? {
get { return _handle.map { $0.isLeapMonth } }
set {
_applyMutation {
// Technically, the underlying class does not support setting isLeapMonth to nil, but it could - so we leave the API consistent.
if let b = newValue {
$0.isLeapMonth = b
} else {
$0.isLeapMonth = false
}
}
}
}
/// Returns a `Date` calculated from the current components using the `calendar` property.
public var date: Date? {
if let d = _handle.map({$0.date}) {
return d as Date
} else {
return nil
}
}
// MARK: - Generic Setter/Getters
/// Set the value of one of the properties, using an enumeration value instead of a property name.
///
/// The calendar and timeZone and isLeapMonth properties cannot be set by this method.
public mutating func setValue(_ value: Int?, forComponent unit: Calendar.Unit) {
_applyMutation { $0.setValue(_setter(value), forComponent: unit) }
}
/// Returns the value of one of the properties, using an enumeration value instead of a property name.
///
/// The calendar and timeZone and isLeapMonth property values cannot be retrieved by this method.
public func value(forComponent unit: Calendar.Unit) -> Int? {
return _handle.map { $0.value(forComponent: unit) }
}
// MARK: -
/// Returns true if the combination of properties which have been set in the receiver is a date which exists in the `calendar` property.
///
/// This method is not appropriate for use on `DateComponents` values which are specifying relative quantities of calendar components.
///
/// Except for some trivial cases (e.g., 'seconds' should be 0 - 59 in any calendar), this method is not necessarily cheap.
///
/// If the time zone property is set in the `DateComponents`, it is used.
///
/// The calendar property must be set, or the result is always `false`.
public var isValidDate: Bool {
return _handle.map { $0.isValidDate }
}
/// Returns true if the combination of properties which have been set in the receiver is a date which exists in the specified `Calendar`.
///
/// This method is not appropriate for use on `DateComponents` values which are specifying relative quantities of calendar components.
///
/// Except for some trivial cases (e.g., 'seconds' should be 0 - 59 in any calendar), this method is not necessarily cheap.
///
/// If the time zone property is set in the `DateComponents`, it is used.
public func isValidDate(in calendar: Calendar) -> Bool {
return _handle.map { $0.isValidDate(in: calendar) }
}
// MARK: -
public var hashValue : Int {
return _handle.map { $0.hash }
}
public var description: String {
return _handle.map { $0.description }
}
public var debugDescription: String {
return _handle.map { $0.debugDescription }
}
// MARK: - Bridging Helpers
internal init(reference: NSDateComponents) {
_handle = _MutableHandle(reference: reference)
}
}
public func ==(lhs : DateComponents, rhs: DateComponents) -> Bool {
// Don't copy references here; no one should be storing anything
return lhs._handle._uncopiedReference().isEqual(rhs._handle._uncopiedReference())
}
// MARK: - Bridging
extension DateComponents {
public static func _isBridgedToObjectiveC() -> Bool {
return true
}
public static func _getObjectiveCType() -> Any.Type {
return NSDateComponents.self
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSDateComponents {
return _handle._copiedReference()
}
public static func _forceBridgeFromObjectiveC(_ dateComponents: NSDateComponents, result: inout DateComponents?) {
if !_conditionallyBridgeFromObjectiveC(dateComponents, result: &result) {
fatalError("Unable to bridge \(NSDateComponents.self) to \(self)")
}
}
public static func _conditionallyBridgeFromObjectiveC(_ dateComponents: NSDateComponents, result: inout DateComponents?) -> Bool {
result = DateComponents(reference: dateComponents)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSDateComponents?) -> DateComponents {
var result: DateComponents? = nil
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
|
apache-2.0
|
3e69140fa30774e816a9eea8b35a90f2
| 44.789137 | 544 | 0.625174 | 4.525418 | false | false | false | false |
ReiVerdugo/uikit-fundamentals
|
step5.8-makeYourOwnAdventure-complete/MYOA/StoryNodeViewController.swift
|
1
|
2520
|
//
// StoryNodeViewController.swift
// MYOA
//
// Created by Jarrod Parkes on 11/2/14.
// Copyright (c) 2014 Udacity. All rights reserved.
//
import UIKit
// MARK: - StoryNodeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource
class StoryNodeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// MARK: Properties
var storyNode: StoryNode!
// MARK: Outlets
@IBOutlet weak var adventureImageView: UIImageView!
@IBOutlet weak var messageTextView: UITextView!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var restartButton: UIButton!
// MARK: Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
// Set the image
if let imageName = storyNode.imageName {
self.adventureImageView.image = UIImage(named: imageName)
}
// Set the message text
self.messageTextView.text = storyNode.message
// Hide the restart button if there are choices to be made
restartButton.hidden = storyNode.promptCount() > 0
}
// MARK: Table Placeholder Implementation
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//Push the next story node.
let nextStoryNode = storyNode.storyNodeForIndex(indexPath.row)
let controller = self.storyboard!.instantiateViewControllerWithIdentifier("StoryNodeViewController") as! StoryNodeViewController
controller.storyNode = nextStoryNode
self.navigationController!.pushViewController(controller, animated: true)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of prompts in the storyNode (The 2 is just a place holder)
return storyNode.promptCount()
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//Dequeue a cell and populate it with text from the correct prompt.
let cell = tableView.dequeueReusableCellWithIdentifier("Cell")!
cell.textLabel!.text = storyNode.promptForIndex(indexPath.row)
return cell
}
// MARK: Actions
@IBAction func restartStory() {
let controller = self.navigationController!.viewControllers[1]
self.navigationController?.popToViewController(controller, animated: true)
}
}
|
mit
|
e1299ff533fd610582b7e0fd8cea8f96
| 32.6 | 136 | 0.681746 | 5.350318 | false | false | false | false |
LinDing/Positano
|
Positano/Extensions/String+Yep.swift
|
1
|
7735
|
//
// String+Yep.swift
// Yep
//
// Created by kevinzhow on 15/4/2.
// Copyright (c) 2015年 Catch Inc. All rights reserved.
//
import Foundation
import RealmSwift
import UIKit
extension String {
func toDate() -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
if let date = dateFormatter.date(from: self) {
return date
} else {
return nil
}
}
}
extension String {
enum TrimmingType {
case whitespace
case whitespaceAndNewline
}
func trimming(_ trimmingType: TrimmingType) -> String {
switch trimmingType {
case .whitespace:
return trimmingCharacters(in: CharacterSet.whitespaces)
case .whitespaceAndNewline:
return trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
}
var yep_removeAllWhitespaces: String {
return self.replacingOccurrences(of: " ", with: "").replacingOccurrences(of: " ", with: "")
}
var yep_removeAllNewLines: String {
return self.components(separatedBy: CharacterSet.newlines).joined(separator: "")
}
func yep_truncate(_ length: Int, trailing: String? = nil) -> String {
if self.characters.count > length {
return self.substring(to: self.characters.index(self.startIndex, offsetBy: length)) + (trailing ?? "")
} else {
return self
}
}
var yep_truncatedForFeed: String {
return yep_truncate(120, trailing: "...")
}
}
extension String {
func yep_rangeFromNSRange(_ nsRange: NSRange) -> Range<Index>? {
let from16 = utf16.startIndex.advanced(by: nsRange.location)
let to16 = from16.advanced(by: nsRange.length)
guard let from = String.Index(from16, within: self),
let to = String.Index(to16, within: self) else {
return nil
}
return from ..< to
}
func yep_NSRangeFromRange(_ range: Range<Index>) -> NSRange {
let utf16view = self.utf16
let from = String.UTF16View.Index(range.lowerBound, within: utf16view)
let to = String.UTF16View.Index(range.upperBound, within: utf16view)
return NSMakeRange(utf16view.startIndex.distance(to: from), from.distance(to: to))
}
}
extension String {
func yep_mentionWordInIndex(_ index: Int) -> (wordString: String, mentionWordRange: Range<Index>)? {
//println("startIndex: \(startIndex), endIndex: \(endIndex), index: \(index), length: \((self as NSString).length), count: \(self.characters.count)")
guard index > 0 else {
return nil
}
let nsRange = NSMakeRange(index, 0)
guard let range = self.yep_rangeFromNSRange(nsRange) else {
return nil
}
let index = range.lowerBound
var wordString: String?
var wordRange: Range<Index>?
self.enumerateSubstrings(in: startIndex..<endIndex, options: [.byWords, .reverse]) { (substring, substringRange, enclosingRange, stop) -> () in
//println("substring: \(substring)")
//println("substringRange: \(substringRange)")
//println("enclosingRange: \(enclosingRange)")
if substringRange.contains(index) {
wordString = substring
wordRange = substringRange
stop = true
}
}
guard let _wordString = wordString, let _wordRange = wordRange else {
return nil
}
guard _wordRange.lowerBound != startIndex else {
return nil
}
let mentionWordRange = self.index(_wordRange.lowerBound, offsetBy: -1)..<_wordRange.upperBound
let mentionWord = substring(with: mentionWordRange)
guard mentionWord.hasPrefix("@") else {
return nil
}
return (_wordString, mentionWordRange)
}
}
extension String {
var yep_embeddedURLs: [URL] {
guard let detector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) else {
return []
}
var URLs = [URL]()
detector.enumerateMatches(in: self, options: [], range: NSMakeRange(0, (self as NSString).length)) { result, flags, stop in
if let URL = result?.url {
URLs.append(URL)
}
}
return URLs
}
}
extension String {
func yep_hightlightSearchKeyword(_ keyword: String, baseFont: UIFont, baseColor: UIColor) -> NSAttributedString? {
return yep_highlightKeyword(keyword, withColor: UIColor.yepTintColor(), baseFont: baseFont, baseColor: baseColor)
}
func yep_highlightKeyword(_ keyword: String, withColor color: UIColor, baseFont: UIFont, baseColor: UIColor) -> NSAttributedString? {
guard !keyword.isEmpty else {
return nil
}
let text = self
let attributedString = NSMutableAttributedString(string: text)
let textRange = NSMakeRange(0, (text as NSString).length)
attributedString.addAttribute(NSForegroundColorAttributeName, value: baseColor, range: textRange)
attributedString.addAttribute(NSFontAttributeName, value: baseFont, range: textRange)
// highlight keyword
let highlightTextAttributes: [String: Any] = [
NSForegroundColorAttributeName: color,
]
let highlightExpression = try! NSRegularExpression(pattern: keyword, options: [.caseInsensitive])
highlightExpression.enumerateMatches(in: text, options: NSRegularExpression.MatchingOptions(), range: textRange, using: { result, flags, stop in
if let result = result {
attributedString.addAttributes(highlightTextAttributes, range: result.range )
}
})
return attributedString
}
func yep_keywordSetOfEmphasisTags() -> Set<String> {
let text = self
let textRange = NSMakeRange(0, (text as NSString).length)
let keywordExpression = try! NSRegularExpression(pattern: "<em>(.+?)</em>", options: [.caseInsensitive])
let matches = keywordExpression.matches(in: self, options: [], range: textRange)
let keywords: [String] = matches.map({
let matchRange = $0.rangeAt(1)
let keyword = (text as NSString).substring(with: matchRange)
return keyword.lowercased()
})
let keywordSet = Set(keywords)
return keywordSet
}
func yep_highlightWithKeywordSet(_ keywordSet: Set<String>, color: UIColor, baseFont: UIFont, baseColor: UIColor) -> NSAttributedString? {
let text = self
let textRange = NSMakeRange(0, (self as NSString).length)
let attributedString = NSMutableAttributedString(string: text)
attributedString.addAttribute(NSForegroundColorAttributeName, value: baseColor, range: textRange)
attributedString.addAttribute(NSFontAttributeName, value: baseFont, range: textRange)
let highlightTextAttributes: [String: Any] = [
NSForegroundColorAttributeName: color,
]
keywordSet.forEach({
if let highlightExpression = try? NSRegularExpression(pattern: $0, options: [.caseInsensitive]) {
highlightExpression.enumerateMatches(in: text, options: NSRegularExpression.MatchingOptions(), range: textRange, using: { result, flags, stop in
if let result = result {
attributedString.addAttributes(highlightTextAttributes, range: result.range )
}
})
}
})
return attributedString
}
}
|
mit
|
0899e55c00055f70f685a7dc4ff717bd
| 30.299595 | 160 | 0.622429 | 4.880682 | false | false | false | false |
milseman/swift
|
stdlib/public/SDK/Foundation/PlistEncoder.swift
|
4
|
80503
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// Plist Encoder
//===----------------------------------------------------------------------===//
/// `PropertyListEncoder` facilitates the encoding of `Encodable` values into property lists.
open class PropertyListEncoder {
// MARK: - Options
/// The output format to write the property list data in. Defaults to `.binary`.
open var outputFormat: PropertyListSerialization.PropertyListFormat = .binary
/// Contextual user-provided information for use during encoding.
open var userInfo: [CodingUserInfoKey : Any] = [:]
/// Options set on the top-level encoder to pass down the encoding hierarchy.
fileprivate struct _Options {
let outputFormat: PropertyListSerialization.PropertyListFormat
let userInfo: [CodingUserInfoKey : Any]
}
/// The options set on the top-level encoder.
fileprivate var options: _Options {
return _Options(outputFormat: outputFormat, userInfo: userInfo)
}
// MARK: - Constructing a Property List Encoder
/// Initializes `self` with default strategies.
public init() {}
// MARK: - Encoding Values
/// Encodes the given top-level value and returns its property list representation.
///
/// - parameter value: The value to encode.
/// - returns: A new `Data` value containing the encoded property list data.
/// - throws: `EncodingError.invalidValue` if a non-conforming floating-point value is encountered during encoding, and the encoding strategy is `.throw`.
/// - throws: An error if any value throws an error during encoding.
open func encode<Value : Encodable>(_ value: Value) throws -> Data {
let topLevel = try encodeToTopLevelContainer(value)
if topLevel is NSNumber {
throw EncodingError.invalidValue(value,
EncodingError.Context(codingPath: [],
debugDescription: "Top-level \(Value.self) encoded as number property list fragment."))
} else if topLevel is NSString {
throw EncodingError.invalidValue(value,
EncodingError.Context(codingPath: [],
debugDescription: "Top-level \(Value.self) encoded as string property list fragment."))
} else if topLevel is NSDate {
throw EncodingError.invalidValue(value,
EncodingError.Context(codingPath: [],
debugDescription: "Top-level \(Value.self) encoded as date property list fragment."))
}
do {
return try PropertyListSerialization.data(fromPropertyList: topLevel, format: self.outputFormat, options: 0)
} catch {
throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: [], debugDescription: "Unable to encode the given top-level value as a property list", underlyingError: error))
}
}
/// Encodes the given top-level value and returns its plist-type representation.
///
/// - parameter value: The value to encode.
/// - returns: A new top-level array or dictionary representing the value.
/// - throws: `EncodingError.invalidValue` if a non-conforming floating-point value is encountered during encoding, and the encoding strategy is `.throw`.
/// - throws: An error if any value throws an error during encoding.
internal func encodeToTopLevelContainer<Value : Encodable>(_ value: Value) throws -> Any {
let encoder = _PlistEncoder(options: self.options)
try value.encode(to: encoder)
guard encoder.storage.count > 0 else {
throw EncodingError.invalidValue(value,
EncodingError.Context(codingPath: [],
debugDescription: "Top-level \(Value.self) did not encode any values."))
}
let topLevel = encoder.storage.popContainer()
return topLevel
}
}
// MARK: - _PlistEncoder
fileprivate class _PlistEncoder : Encoder {
// MARK: Properties
/// The encoder's storage.
fileprivate var storage: _PlistEncodingStorage
/// Options set on the top-level encoder.
fileprivate let options: PropertyListEncoder._Options
/// The path to the current point in encoding.
fileprivate(set) public var codingPath: [CodingKey]
/// Contextual user-provided information for use during encoding.
public var userInfo: [CodingUserInfoKey : Any] {
return self.options.userInfo
}
// MARK: - Initialization
/// Initializes `self` with the given top-level encoder options.
fileprivate init(options: PropertyListEncoder._Options, codingPath: [CodingKey] = []) {
self.options = options
self.storage = _PlistEncodingStorage()
self.codingPath = codingPath
}
/// Returns whether a new element can be encoded at this coding path.
///
/// `true` if an element has not yet been encoded at this coding path; `false` otherwise.
fileprivate var canEncodeNewValue: Bool {
// Every time a new value gets encoded, the key it's encoded for is pushed onto the coding path (even if it's a nil key from an unkeyed container).
// At the same time, every time a container is requested, a new value gets pushed onto the storage stack.
// If there are more values on the storage stack than on the coding path, it means the value is requesting more than one container, which violates the precondition.
//
// This means that anytime something that can request a new container goes onto the stack, we MUST push a key onto the coding path.
// Things which will not request containers do not need to have the coding path extended for them (but it doesn't matter if it is, because they will not reach here).
return self.storage.count == self.codingPath.count
}
// MARK: - Encoder Methods
public func container<Key>(keyedBy: Key.Type) -> KeyedEncodingContainer<Key> {
// If an existing keyed container was already requested, return that one.
let topContainer: NSMutableDictionary
if self.canEncodeNewValue {
// We haven't yet pushed a container at this level; do so here.
topContainer = self.storage.pushKeyedContainer()
} else {
guard let container = self.storage.containers.last as? NSMutableDictionary else {
preconditionFailure("Attempt to push new keyed encoding container when already previously encoded at this path.")
}
topContainer = container
}
let container = _PlistKeyedEncodingContainer<Key>(referencing: self, codingPath: self.codingPath, wrapping: topContainer)
return KeyedEncodingContainer(container)
}
public func unkeyedContainer() -> UnkeyedEncodingContainer {
// If an existing unkeyed container was already requested, return that one.
let topContainer: NSMutableArray
if self.canEncodeNewValue {
// We haven't yet pushed a container at this level; do so here.
topContainer = self.storage.pushUnkeyedContainer()
} else {
guard let container = self.storage.containers.last as? NSMutableArray else {
preconditionFailure("Attempt to push new unkeyed encoding container when already previously encoded at this path.")
}
topContainer = container
}
return _PlistUnkeyedEncodingContainer(referencing: self, codingPath: self.codingPath, wrapping: topContainer)
}
public func singleValueContainer() -> SingleValueEncodingContainer {
return self
}
}
// MARK: - Encoding Storage and Containers
fileprivate struct _PlistEncodingStorage {
// MARK: Properties
/// The container stack.
/// Elements may be any one of the plist types (NSNumber, NSString, NSDate, NSArray, NSDictionary).
private(set) fileprivate var containers: [NSObject] = []
// MARK: - Initialization
/// Initializes `self` with no containers.
fileprivate init() {}
// MARK: - Modifying the Stack
fileprivate var count: Int {
return self.containers.count
}
fileprivate mutating func pushKeyedContainer() -> NSMutableDictionary {
let dictionary = NSMutableDictionary()
self.containers.append(dictionary)
return dictionary
}
fileprivate mutating func pushUnkeyedContainer() -> NSMutableArray {
let array = NSMutableArray()
self.containers.append(array)
return array
}
fileprivate mutating func push(container: NSObject) {
self.containers.append(container)
}
fileprivate mutating func popContainer() -> NSObject {
precondition(self.containers.count > 0, "Empty container stack.")
return self.containers.popLast()!
}
}
// MARK: - Encoding Containers
fileprivate struct _PlistKeyedEncodingContainer<K : CodingKey> : KeyedEncodingContainerProtocol {
typealias Key = K
// MARK: Properties
/// A reference to the encoder we're writing to.
private let encoder: _PlistEncoder
/// A reference to the container we're writing to.
private let container: NSMutableDictionary
/// The path of coding keys taken to get to this point in encoding.
private(set) public var codingPath: [CodingKey]
// MARK: - Initialization
/// Initializes `self` with the given references.
fileprivate init(referencing encoder: _PlistEncoder, codingPath: [CodingKey], wrapping container: NSMutableDictionary) {
self.encoder = encoder
self.codingPath = codingPath
self.container = container
}
// MARK: - KeyedEncodingContainerProtocol Methods
public mutating func encodeNil(forKey key: Key) throws { self.container[key.stringValue] = _plistNullNSString }
public mutating func encode(_ value: Bool, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) }
public mutating func encode(_ value: Int, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) }
public mutating func encode(_ value: Int8, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) }
public mutating func encode(_ value: Int16, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) }
public mutating func encode(_ value: Int32, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) }
public mutating func encode(_ value: Int64, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) }
public mutating func encode(_ value: UInt, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) }
public mutating func encode(_ value: UInt8, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) }
public mutating func encode(_ value: UInt16, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) }
public mutating func encode(_ value: UInt32, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) }
public mutating func encode(_ value: UInt64, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) }
public mutating func encode(_ value: String, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) }
public mutating func encode(_ value: Float, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) }
public mutating func encode(_ value: Double, forKey key: Key) throws { self.container[key.stringValue] = self.encoder.box(value) }
public mutating func encode<T : Encodable>(_ value: T, forKey key: Key) throws {
self.encoder.codingPath.append(key)
defer { self.encoder.codingPath.removeLast() }
self.container[key.stringValue] = try self.encoder.box(value)
}
public mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> {
let dictionary = NSMutableDictionary()
self.container[key.stringValue] = dictionary
self.codingPath.append(key)
defer { self.codingPath.removeLast() }
let container = _PlistKeyedEncodingContainer<NestedKey>(referencing: self.encoder, codingPath: self.codingPath, wrapping: dictionary)
return KeyedEncodingContainer(container)
}
public mutating func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer {
let array = NSMutableArray()
self.container[key.stringValue] = array
self.codingPath.append(key)
defer { self.codingPath.removeLast() }
return _PlistUnkeyedEncodingContainer(referencing: self.encoder, codingPath: self.codingPath, wrapping: array)
}
public mutating func superEncoder() -> Encoder {
return _PlistReferencingEncoder(referencing: self.encoder, at: _PlistKey.super, wrapping: self.container)
}
public mutating func superEncoder(forKey key: Key) -> Encoder {
return _PlistReferencingEncoder(referencing: self.encoder, at: key, wrapping: self.container)
}
}
fileprivate struct _PlistUnkeyedEncodingContainer : UnkeyedEncodingContainer {
// MARK: Properties
/// A reference to the encoder we're writing to.
private let encoder: _PlistEncoder
/// A reference to the container we're writing to.
private let container: NSMutableArray
/// The path of coding keys taken to get to this point in encoding.
private(set) public var codingPath: [CodingKey]
/// The number of elements encoded into the container.
public var count: Int {
return self.container.count
}
// MARK: - Initialization
/// Initializes `self` with the given references.
fileprivate init(referencing encoder: _PlistEncoder, codingPath: [CodingKey], wrapping container: NSMutableArray) {
self.encoder = encoder
self.codingPath = codingPath
self.container = container
}
// MARK: - UnkeyedEncodingContainer Methods
public mutating func encodeNil() throws { self.container.add(_plistNullNSString) }
public mutating func encode(_ value: Bool) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: Int) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: Int8) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: Int16) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: Int32) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: Int64) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: UInt) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: UInt8) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: UInt16) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: UInt32) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: UInt64) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: Float) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: Double) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode(_ value: String) throws { self.container.add(self.encoder.box(value)) }
public mutating func encode<T : Encodable>(_ value: T) throws {
self.encoder.codingPath.append(_PlistKey(index: self.count))
defer { self.encoder.codingPath.removeLast() }
self.container.add(try self.encoder.box(value))
}
public mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer<NestedKey> {
self.codingPath.append(_PlistKey(index: self.count))
defer { self.codingPath.removeLast() }
let dictionary = NSMutableDictionary()
self.container.add(dictionary)
let container = _PlistKeyedEncodingContainer<NestedKey>(referencing: self.encoder, codingPath: self.codingPath, wrapping: dictionary)
return KeyedEncodingContainer(container)
}
public mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer {
self.codingPath.append(_PlistKey(index: self.count))
defer { self.codingPath.removeLast() }
let array = NSMutableArray()
self.container.add(array)
return _PlistUnkeyedEncodingContainer(referencing: self.encoder, codingPath: self.codingPath, wrapping: array)
}
public mutating func superEncoder() -> Encoder {
return _PlistReferencingEncoder(referencing: self.encoder, at: self.container.count, wrapping: self.container)
}
}
extension _PlistEncoder : SingleValueEncodingContainer {
// MARK: - SingleValueEncodingContainer Methods
private func assertCanEncodeNewValue() {
precondition(self.canEncodeNewValue, "Attempt to encode value through single value container when previously value already encoded.")
}
public func encodeNil() throws {
assertCanEncodeNewValue()
self.storage.push(container: _plistNullNSString)
}
public func encode(_ value: Bool) throws {
assertCanEncodeNewValue()
self.storage.push(container: box(value))
}
public func encode(_ value: Int) throws {
assertCanEncodeNewValue()
self.storage.push(container: box(value))
}
public func encode(_ value: Int8) throws {
assertCanEncodeNewValue()
self.storage.push(container: box(value))
}
public func encode(_ value: Int16) throws {
assertCanEncodeNewValue()
self.storage.push(container: box(value))
}
public func encode(_ value: Int32) throws {
assertCanEncodeNewValue()
self.storage.push(container: box(value))
}
public func encode(_ value: Int64) throws {
assertCanEncodeNewValue()
self.storage.push(container: box(value))
}
public func encode(_ value: UInt) throws {
assertCanEncodeNewValue()
self.storage.push(container: box(value))
}
public func encode(_ value: UInt8) throws {
assertCanEncodeNewValue()
self.storage.push(container: box(value))
}
public func encode(_ value: UInt16) throws {
assertCanEncodeNewValue()
self.storage.push(container: box(value))
}
public func encode(_ value: UInt32) throws {
assertCanEncodeNewValue()
self.storage.push(container: box(value))
}
public func encode(_ value: UInt64) throws {
assertCanEncodeNewValue()
self.storage.push(container: box(value))
}
public func encode(_ value: String) throws {
assertCanEncodeNewValue()
self.storage.push(container: box(value))
}
public func encode(_ value: Float) throws {
assertCanEncodeNewValue()
self.storage.push(container: box(value))
}
public func encode(_ value: Double) throws {
assertCanEncodeNewValue()
self.storage.push(container: box(value))
}
public func encode<T : Encodable>(_ value: T) throws {
assertCanEncodeNewValue()
try self.storage.push(container: box(value))
}
}
// MARK: - Concrete Value Representations
extension _PlistEncoder {
/// Returns the given value boxed in a container appropriate for pushing onto the container stack.
fileprivate func box(_ value: Bool) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: Int) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: Int8) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: Int16) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: Int32) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: Int64) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: UInt) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: UInt8) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: UInt16) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: UInt32) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: UInt64) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: Float) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: Double) -> NSObject { return NSNumber(value: value) }
fileprivate func box(_ value: String) -> NSObject { return NSString(string: value) }
fileprivate func box(_ value: Data) -> NSObject { return NSData(data: value) }
fileprivate func box<T : Encodable>(_ value: T) throws -> NSObject {
if T.self == Date.self {
// PropertyListSerialization handles Date directly.
return NSDate(timeIntervalSinceReferenceDate: (value as! Date).timeIntervalSinceReferenceDate)
} else if T.self == Data.self {
// PropertyListSerialization handles Data directly.
return NSData(data: (value as! Data))
}
// The value should request a container from the _PlistEncoder.
let currentTopContainer = self.storage.containers.last
try value.encode(to: self)
// The top container should be a new container.
guard self.storage.containers.last! !== currentTopContainer else {
// If the value didn't request a container at all, encode the default container instead.
return NSDictionary()
}
return self.storage.popContainer()
}
}
// MARK: - _PlistReferencingEncoder
/// _PlistReferencingEncoder is a special subclass of _PlistEncoder which has its own storage, but references the contents of a different encoder.
/// It's used in superEncoder(), which returns a new encoder for encoding a superclass -- the lifetime of the encoder should not escape the scope it's created in, but it doesn't necessarily know when it's done being used (to write to the original container).
fileprivate class _PlistReferencingEncoder : _PlistEncoder {
// MARK: Reference types.
/// The type of container we're referencing.
private enum Reference {
/// Referencing a specific index in an array container.
case array(NSMutableArray, Int)
/// Referencing a specific key in a dictionary container.
case dictionary(NSMutableDictionary, String)
}
// MARK: - Properties
/// The encoder we're referencing.
private let encoder: _PlistEncoder
/// The container reference itself.
private let reference: Reference
// MARK: - Initialization
/// Initializes `self` by referencing the given array container in the given encoder.
fileprivate init(referencing encoder: _PlistEncoder, at index: Int, wrapping array: NSMutableArray) {
self.encoder = encoder
self.reference = .array(array, index)
super.init(options: encoder.options, codingPath: encoder.codingPath)
self.codingPath.append(_PlistKey(index: index))
}
/// Initializes `self` by referencing the given dictionary container in the given encoder.
fileprivate init(referencing encoder: _PlistEncoder, at key: CodingKey, wrapping dictionary: NSMutableDictionary) {
self.encoder = encoder
self.reference = .dictionary(dictionary, key.stringValue)
super.init(options: encoder.options, codingPath: encoder.codingPath)
self.codingPath.append(key)
}
// MARK: - Coding Path Operations
fileprivate override var canEncodeNewValue: Bool {
// With a regular encoder, the storage and coding path grow together.
// A referencing encoder, however, inherits its parents coding path, as well as the key it was created for.
// We have to take this into account.
return self.storage.count == self.codingPath.count - self.encoder.codingPath.count - 1
}
// MARK: - Deinitialization
// Finalizes `self` by writing the contents of our storage to the referenced encoder's storage.
deinit {
let value: Any
switch self.storage.count {
case 0: value = NSDictionary()
case 1: value = self.storage.popContainer()
default: fatalError("Referencing encoder deallocated with multiple containers on stack.")
}
switch self.reference {
case .array(let array, let index):
array.insert(value, at: index)
case .dictionary(let dictionary, let key):
dictionary[NSString(string: key)] = value
}
}
}
//===----------------------------------------------------------------------===//
// Plist Decoder
//===----------------------------------------------------------------------===//
/// `PropertyListDecoder` facilitates the decoding of property list values into semantic `Decodable` types.
open class PropertyListDecoder {
// MARK: Options
/// Contextual user-provided information for use during decoding.
open var userInfo: [CodingUserInfoKey : Any] = [:]
/// Options set on the top-level encoder to pass down the decoding hierarchy.
fileprivate struct _Options {
let userInfo: [CodingUserInfoKey : Any]
}
/// The options set on the top-level decoder.
fileprivate var options: _Options {
return _Options(userInfo: userInfo)
}
// MARK: - Constructing a Property List Decoder
/// Initializes `self` with default strategies.
public init() {}
// MARK: - Decoding Values
/// Decodes a top-level value of the given type from the given property list representation.
///
/// - parameter type: The type of the value to decode.
/// - parameter data: The data to decode from.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.dataCorrupted` if values requested from the payload are corrupted, or if the given data is not a valid property list.
/// - throws: An error if any value throws an error during decoding.
open func decode<T : Decodable>(_ type: T.Type, from data: Data) throws -> T {
var format: PropertyListSerialization.PropertyListFormat = .binary
return try decode(T.self, from: data, format: &format)
}
/// Decodes a top-level value of the given type from the given property list representation.
///
/// - parameter type: The type of the value to decode.
/// - parameter data: The data to decode from.
/// - parameter format: The parsed property list format.
/// - returns: A value of the requested type along with the detected format of the property list.
/// - throws: `DecodingError.dataCorrupted` if values requested from the payload are corrupted, or if the given data is not a valid property list.
/// - throws: An error if any value throws an error during decoding.
open func decode<T : Decodable>(_ type: T.Type, from data: Data, format: inout PropertyListSerialization.PropertyListFormat) throws -> T {
let topLevel: Any
do {
topLevel = try PropertyListSerialization.propertyList(from: data, options: [], format: &format)
} catch {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: [], debugDescription: "The given data was not a valid property list.", underlyingError: error))
}
return try decode(T.self, fromTopLevel: topLevel)
}
/// Decodes a top-level value of the given type from the given property list container (top-level array or dictionary).
///
/// - parameter type: The type of the value to decode.
/// - parameter container: The top-level plist container.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.dataCorrupted` if values requested from the payload are corrupted, or if the given data is not a valid property list.
/// - throws: An error if any value throws an error during decoding.
internal func decode<T : Decodable>(_ type: T.Type, fromTopLevel container: Any) throws -> T {
let decoder = _PlistDecoder(referencing: container, options: self.options)
return try T(from: decoder)
}
}
// MARK: - _PlistDecoder
fileprivate class _PlistDecoder : Decoder {
// MARK: Properties
/// The decoder's storage.
fileprivate var storage: _PlistDecodingStorage
/// Options set on the top-level decoder.
fileprivate let options: PropertyListDecoder._Options
/// The path to the current point in encoding.
fileprivate(set) public var codingPath: [CodingKey]
/// Contextual user-provided information for use during encoding.
public var userInfo: [CodingUserInfoKey : Any] {
return self.options.userInfo
}
// MARK: - Initialization
/// Initializes `self` with the given top-level container and options.
fileprivate init(referencing container: Any, at codingPath: [CodingKey] = [], options: PropertyListDecoder._Options) {
self.storage = _PlistDecodingStorage()
self.storage.push(container: container)
self.codingPath = codingPath
self.options = options
}
// MARK: - Decoder Methods
public func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> {
guard !(self.storage.topContainer is NSNull) else {
throw DecodingError.valueNotFound(KeyedDecodingContainer<Key>.self,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get keyed decoding container -- found null value instead."))
}
guard let topContainer = self.storage.topContainer as? [String : Any] else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: [String : Any].self, reality: self.storage.topContainer)
}
let container = _PlistKeyedDecodingContainer<Key>(referencing: self, wrapping: topContainer)
return KeyedDecodingContainer(container)
}
public func unkeyedContainer() throws -> UnkeyedDecodingContainer {
guard !(self.storage.topContainer is NSNull) else {
throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get unkeyed decoding container -- found null value instead."))
}
guard let topContainer = self.storage.topContainer as? [Any] else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: [Any].self, reality: self.storage.topContainer)
}
return _PlistUnkeyedDecodingContainer(referencing: self, wrapping: topContainer)
}
public func singleValueContainer() throws -> SingleValueDecodingContainer {
return self
}
}
// MARK: - Decoding Storage
fileprivate struct _PlistDecodingStorage {
// MARK: Properties
/// The container stack.
/// Elements may be any one of the plist types (NSNumber, Date, String, Array, [String : Any]).
private(set) fileprivate var containers: [Any] = []
// MARK: - Initialization
/// Initializes `self` with no containers.
fileprivate init() {}
// MARK: - Modifying the Stack
fileprivate var count: Int {
return self.containers.count
}
fileprivate var topContainer: Any {
precondition(self.containers.count > 0, "Empty container stack.")
return self.containers.last!
}
fileprivate mutating func push(container: Any) {
self.containers.append(container)
}
fileprivate mutating func popContainer() {
precondition(self.containers.count > 0, "Empty container stack.")
self.containers.removeLast()
}
}
// MARK: Decoding Containers
fileprivate struct _PlistKeyedDecodingContainer<K : CodingKey> : KeyedDecodingContainerProtocol {
typealias Key = K
// MARK: Properties
/// A reference to the decoder we're reading from.
private let decoder: _PlistDecoder
/// A reference to the container we're reading from.
private let container: [String : Any]
/// The path of coding keys taken to get to this point in decoding.
private(set) public var codingPath: [CodingKey]
// MARK: - Initialization
/// Initializes `self` by referencing the given decoder and container.
fileprivate init(referencing decoder: _PlistDecoder, wrapping container: [String : Any]) {
self.decoder = decoder
self.container = container
self.codingPath = decoder.codingPath
}
// MARK: - KeyedDecodingContainerProtocol Methods
public var allKeys: [Key] {
return self.container.keys.flatMap { Key(stringValue: $0) }
}
public func contains(_ key: Key) -> Bool {
return self.container[key.stringValue] != nil
}
public func decodeNil(forKey key: Key) throws -> Bool {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
guard let value = entry as? String else {
return false
}
return value == _plistNull
}
public func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: Bool.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: Int.Type, forKey key: Key) throws -> Int {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: Int.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: Int8.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: Int16.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: Int32.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: Int64.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: UInt.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: UInt8.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: UInt16.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: UInt32.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: UInt64.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: Float.Type, forKey key: Key) throws -> Float {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: Float.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: Double.Type, forKey key: Key) throws -> Double {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: Double.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode(_ type: String.Type, forKey key: Key) throws -> String {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: String.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func decode<T : Decodable>(_ type: T.Type, forKey key: Key) throws -> T {
guard let entry = self.container[key.stringValue] else {
throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "No value associated with key \(key) (\"\(key.stringValue)\")."))
}
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = try self.decoder.unbox(entry, as: T.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) value but found null instead."))
}
return value
}
public func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> {
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = self.container[key.stringValue] else {
throw DecodingError.valueNotFound(KeyedDecodingContainer<NestedKey>.self,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get nested keyed container -- no value found for key \"\(key.stringValue)\""))
}
guard let dictionary = value as? [String : Any] else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: [String : Any].self, reality: value)
}
let container = _PlistKeyedDecodingContainer<NestedKey>(referencing: self.decoder, wrapping: dictionary)
return KeyedDecodingContainer(container)
}
public func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer {
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
guard let value = self.container[key.stringValue] else {
throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get nested unkeyed container -- no value found for key \"\(key.stringValue)\""))
}
guard let array = value as? [Any] else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: [Any].self, reality: value)
}
return _PlistUnkeyedDecodingContainer(referencing: self.decoder, wrapping: array)
}
private func _superDecoder(forKey key: CodingKey) throws -> Decoder {
self.decoder.codingPath.append(key)
defer { self.decoder.codingPath.removeLast() }
let value: Any = self.container[key.stringValue] ?? NSNull()
return _PlistDecoder(referencing: value, at: self.decoder.codingPath, options: self.decoder.options)
}
public func superDecoder() throws -> Decoder {
return try _superDecoder(forKey: _PlistKey.super)
}
public func superDecoder(forKey key: Key) throws -> Decoder {
return try _superDecoder(forKey: key)
}
}
fileprivate struct _PlistUnkeyedDecodingContainer : UnkeyedDecodingContainer {
// MARK: Properties
/// A reference to the decoder we're reading from.
private let decoder: _PlistDecoder
/// A reference to the container we're reading from.
private let container: [Any]
/// The path of coding keys taken to get to this point in decoding.
private(set) public var codingPath: [CodingKey]
/// The index of the element we're about to decode.
private(set) public var currentIndex: Int
// MARK: - Initialization
/// Initializes `self` by referencing the given decoder and container.
fileprivate init(referencing decoder: _PlistDecoder, wrapping container: [Any]) {
self.decoder = decoder
self.container = container
self.codingPath = decoder.codingPath
self.currentIndex = 0
}
// MARK: - UnkeyedDecodingContainer Methods
public var count: Int? {
return self.container.count
}
public var isAtEnd: Bool {
return self.currentIndex >= self.count!
}
public mutating func decodeNil() throws -> Bool {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(Any?.self, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
if self.container[self.currentIndex] is NSNull {
self.currentIndex += 1
return true
} else {
return false
}
}
public mutating func decode(_ type: Bool.Type) throws -> Bool {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_PlistKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Bool.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: Int.Type) throws -> Int {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_PlistKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: Int8.Type) throws -> Int8 {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_PlistKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int8.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: Int16.Type) throws -> Int16 {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_PlistKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int16.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: Int32.Type) throws -> Int32 {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_PlistKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int32.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: Int64.Type) throws -> Int64 {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_PlistKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Int64.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: UInt.Type) throws -> UInt {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_PlistKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: UInt8.Type) throws -> UInt8 {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_PlistKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt8.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: UInt16.Type) throws -> UInt16 {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_PlistKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt16.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: UInt32.Type) throws -> UInt32 {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_PlistKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt32.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: UInt64.Type) throws -> UInt64 {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_PlistKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: UInt64.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: Float.Type) throws -> Float {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_PlistKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Float.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: Double.Type) throws -> Double {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_PlistKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: Double.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode(_ type: String.Type) throws -> String {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_PlistKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: String.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func decode<T : Decodable>(_ type: T.Type) throws -> T {
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Unkeyed container is at end."))
}
self.decoder.codingPath.append(_PlistKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard let decoded = try self.decoder.unbox(self.container[self.currentIndex], as: T.self) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [_PlistKey(index: self.currentIndex)], debugDescription: "Expected \(type) but found null instead."))
}
self.currentIndex += 1
return decoded
}
public mutating func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer<NestedKey> {
self.decoder.codingPath.append(_PlistKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(KeyedDecodingContainer<NestedKey>.self,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get nested keyed container -- unkeyed container is at end."))
}
let value = self.container[self.currentIndex]
guard !(value is NSNull) else {
throw DecodingError.valueNotFound(KeyedDecodingContainer<NestedKey>.self,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get keyed decoding container -- found null value instead."))
}
guard let dictionary = value as? [String : Any] else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: [String : Any].self, reality: value)
}
self.currentIndex += 1
let container = _PlistKeyedDecodingContainer<NestedKey>(referencing: self.decoder, wrapping: dictionary)
return KeyedDecodingContainer(container)
}
public mutating func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer {
self.decoder.codingPath.append(_PlistKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get nested unkeyed container -- unkeyed container is at end."))
}
let value = self.container[self.currentIndex]
guard !(value is NSNull) else {
throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self,
DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get keyed decoding container -- found null value instead."))
}
guard let array = value as? [Any] else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: [Any].self, reality: value)
}
self.currentIndex += 1
return _PlistUnkeyedDecodingContainer(referencing: self.decoder, wrapping: array)
}
public mutating func superDecoder() throws -> Decoder {
self.decoder.codingPath.append(_PlistKey(index: self.currentIndex))
defer { self.decoder.codingPath.removeLast() }
guard !self.isAtEnd else {
throw DecodingError.valueNotFound(Decoder.self, DecodingError.Context(codingPath: self.codingPath,
debugDescription: "Cannot get superDecoder() -- unkeyed container is at end."))
}
let value = self.container[self.currentIndex]
self.currentIndex += 1
return _PlistDecoder(referencing: value, at: self.decoder.codingPath, options: self.decoder.options)
}
}
extension _PlistDecoder : SingleValueDecodingContainer {
// MARK: SingleValueDecodingContainer Methods
private func expectNonNull<T>(_ type: T.Type) throws {
guard !self.decodeNil() else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Expected \(type) but found null value instead."))
}
}
public func decodeNil() -> Bool {
guard let string = self.storage.topContainer as? String else {
return false
}
return string == _plistNull
}
public func decode(_ type: Bool.Type) throws -> Bool {
try expectNonNull(Bool.self)
return try self.unbox(self.storage.topContainer, as: Bool.self)!
}
public func decode(_ type: Int.Type) throws -> Int {
try expectNonNull(Int.self)
return try self.unbox(self.storage.topContainer, as: Int.self)!
}
public func decode(_ type: Int8.Type) throws -> Int8 {
try expectNonNull(Int8.self)
return try self.unbox(self.storage.topContainer, as: Int8.self)!
}
public func decode(_ type: Int16.Type) throws -> Int16 {
try expectNonNull(Int16.self)
return try self.unbox(self.storage.topContainer, as: Int16.self)!
}
public func decode(_ type: Int32.Type) throws -> Int32 {
try expectNonNull(Int32.self)
return try self.unbox(self.storage.topContainer, as: Int32.self)!
}
public func decode(_ type: Int64.Type) throws -> Int64 {
try expectNonNull(Int64.self)
return try self.unbox(self.storage.topContainer, as: Int64.self)!
}
public func decode(_ type: UInt.Type) throws -> UInt {
try expectNonNull(UInt.self)
return try self.unbox(self.storage.topContainer, as: UInt.self)!
}
public func decode(_ type: UInt8.Type) throws -> UInt8 {
try expectNonNull(UInt8.self)
return try self.unbox(self.storage.topContainer, as: UInt8.self)!
}
public func decode(_ type: UInt16.Type) throws -> UInt16 {
try expectNonNull(UInt16.self)
return try self.unbox(self.storage.topContainer, as: UInt16.self)!
}
public func decode(_ type: UInt32.Type) throws -> UInt32 {
try expectNonNull(UInt32.self)
return try self.unbox(self.storage.topContainer, as: UInt32.self)!
}
public func decode(_ type: UInt64.Type) throws -> UInt64 {
try expectNonNull(UInt64.self)
return try self.unbox(self.storage.topContainer, as: UInt64.self)!
}
public func decode(_ type: Float.Type) throws -> Float {
try expectNonNull(Float.self)
return try self.unbox(self.storage.topContainer, as: Float.self)!
}
public func decode(_ type: Double.Type) throws -> Double {
try expectNonNull(Double.self)
return try self.unbox(self.storage.topContainer, as: Double.self)!
}
public func decode(_ type: String.Type) throws -> String {
try expectNonNull(String.self)
return try self.unbox(self.storage.topContainer, as: String.self)!
}
public func decode<T : Decodable>(_ type: T.Type) throws -> T {
try expectNonNull(T.self)
return try self.unbox(self.storage.topContainer, as: T.self)!
}
}
// MARK: - Concrete Value Representations
extension _PlistDecoder {
/// Returns the given value unboxed from a container.
fileprivate func unbox(_ value: Any, as type: Bool.Type) throws -> Bool? {
if let string = value as? String, string == _plistNull { return nil }
if let number = value as? NSNumber {
// TODO: Add a flag to coerce non-boolean numbers into Bools?
if number === kCFBooleanTrue as NSNumber {
return true
} else if number === kCFBooleanFalse as NSNumber {
return false
}
/* FIXME: If swift-corelibs-foundation doesn't change to use NSNumber, this code path will need to be included and tested:
} else if let bool = value as? Bool {
return bool
*/
}
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
fileprivate func unbox(_ value: Any, as type: Int.Type) throws -> Int? {
if let string = value as? String, string == _plistNull { return nil }
guard let number = value as? NSNumber else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let int = number.intValue
guard NSNumber(value: int) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed property list number <\(number)> does not fit in \(type)."))
}
return int
}
fileprivate func unbox(_ value: Any, as type: Int8.Type) throws -> Int8? {
if let string = value as? String, string == _plistNull { return nil }
guard let number = value as? NSNumber else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let int8 = number.int8Value
guard NSNumber(value: int8) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed property list number <\(number)> does not fit in \(type)."))
}
return int8
}
fileprivate func unbox(_ value: Any, as type: Int16.Type) throws -> Int16? {
if let string = value as? String, string == _plistNull { return nil }
guard let number = value as? NSNumber else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let int16 = number.int16Value
guard NSNumber(value: int16) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed property list number <\(number)> does not fit in \(type)."))
}
return int16
}
fileprivate func unbox(_ value: Any, as type: Int32.Type) throws -> Int32? {
if let string = value as? String, string == _plistNull { return nil }
guard let number = value as? NSNumber else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let int32 = number.int32Value
guard NSNumber(value: int32) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed property list number <\(number)> does not fit in \(type)."))
}
return int32
}
fileprivate func unbox(_ value: Any, as type: Int64.Type) throws -> Int64? {
if let string = value as? String, string == _plistNull { return nil }
guard let number = value as? NSNumber else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let int64 = number.int64Value
guard NSNumber(value: int64) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed property list number <\(number)> does not fit in \(type)."))
}
return int64
}
fileprivate func unbox(_ value: Any, as type: UInt.Type) throws -> UInt? {
if let string = value as? String, string == _plistNull { return nil }
guard let number = value as? NSNumber else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let uint = number.uintValue
guard NSNumber(value: uint) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed property list number <\(number)> does not fit in \(type)."))
}
return uint
}
fileprivate func unbox(_ value: Any, as type: UInt8.Type) throws -> UInt8? {
if let string = value as? String, string == _plistNull { return nil }
guard let number = value as? NSNumber else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let uint8 = number.uint8Value
guard NSNumber(value: uint8) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed property list number <\(number)> does not fit in \(type)."))
}
return uint8
}
fileprivate func unbox(_ value: Any, as type: UInt16.Type) throws -> UInt16? {
if let string = value as? String, string == _plistNull { return nil }
guard let number = value as? NSNumber else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let uint16 = number.uint16Value
guard NSNumber(value: uint16) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed property list number <\(number)> does not fit in \(type)."))
}
return uint16
}
fileprivate func unbox(_ value: Any, as type: UInt32.Type) throws -> UInt32? {
if let string = value as? String, string == _plistNull { return nil }
guard let number = value as? NSNumber else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let uint32 = number.uint32Value
guard NSNumber(value: uint32) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed property list number <\(number)> does not fit in \(type)."))
}
return uint32
}
fileprivate func unbox(_ value: Any, as type: UInt64.Type) throws -> UInt64? {
if let string = value as? String, string == _plistNull { return nil }
guard let number = value as? NSNumber else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let uint64 = number.uint64Value
guard NSNumber(value: uint64) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed property list number <\(number)> does not fit in \(type)."))
}
return uint64
}
fileprivate func unbox(_ value: Any, as type: Float.Type) throws -> Float? {
if let string = value as? String, string == _plistNull { return nil }
guard let number = value as? NSNumber else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let float = number.floatValue
guard NSNumber(value: float) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed property list number <\(number)> does not fit in \(type)."))
}
return float
}
fileprivate func unbox(_ value: Any, as type: Double.Type) throws -> Double? {
if let string = value as? String, string == _plistNull { return nil }
guard let number = value as? NSNumber else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
let double = number.doubleValue
guard NSNumber(value: double) == number else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: self.codingPath, debugDescription: "Parsed property list number <\(number)> does not fit in \(type)."))
}
return double
}
fileprivate func unbox(_ value: Any, as type: String.Type) throws -> String? {
guard let string = value as? String else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
return string == _plistNull ? nil : string
}
fileprivate func unbox(_ value: Any, as type: Date.Type) throws -> Date? {
if let string = value as? String, string == _plistNull { return nil }
guard let date = value as? Date else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
return date
}
fileprivate func unbox(_ value: Any, as type: Data.Type) throws -> Data? {
if let string = value as? String, string == _plistNull { return nil }
guard let data = value as? Data else {
throw DecodingError._typeMismatch(at: self.codingPath, expectation: type, reality: value)
}
return data
}
fileprivate func unbox<T : Decodable>(_ value: Any, as type: T.Type) throws -> T? {
let decoded: T
if T.self == Date.self {
guard let date = try self.unbox(value, as: Date.self) else { return nil }
decoded = date as! T
} else if T.self == Data.self {
guard let data = try self.unbox(value, as: Data.self) else { return nil }
decoded = data as! T
} else {
self.storage.push(container: value)
decoded = try T(from: self)
self.storage.popContainer()
}
return decoded
}
}
//===----------------------------------------------------------------------===//
// Shared Plist Null Representation
//===----------------------------------------------------------------------===//
// Since plists do not support null values by default, we will encode them as "$null".
fileprivate let _plistNull = "$null"
fileprivate let _plistNullNSString = NSString(string: _plistNull)
//===----------------------------------------------------------------------===//
// Shared Key Types
//===----------------------------------------------------------------------===//
fileprivate struct _PlistKey : CodingKey {
public var stringValue: String
public var intValue: Int?
public init?(stringValue: String) {
self.stringValue = stringValue
self.intValue = nil
}
public init?(intValue: Int) {
self.stringValue = "\(intValue)"
self.intValue = intValue
}
fileprivate init(index: Int) {
self.stringValue = "Index \(index)"
self.intValue = index
}
fileprivate static let `super` = _PlistKey(stringValue: "super")!
}
|
apache-2.0
|
f6c34afaa88a5a2df7a32b2b5e30d730
| 43.624723 | 258 | 0.660522 | 4.8452 | false | false | false | false |
qiuncheng/study-for-swift
|
learn-rx-swift/Chocotastic-starter/Pods/RxSwift/RxSwift/Observables/Implementations/SubscribeOn.swift
|
6
|
1706
|
//
// SubscribeOn.swift
// RxSwift
//
// Created by Krunoslav Zaher on 6/14/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class SubscribeOnSink<Ob: ObservableType, O: ObserverType> : Sink<O>, ObserverType where Ob.E == O.E {
typealias Element = O.E
typealias Parent = SubscribeOn<Ob>
let parent: Parent
init(parent: Parent, observer: O) {
self.parent = parent
super.init(observer: observer)
}
func on(_ event: Event<Element>) {
forwardOn(event)
if event.isStopEvent {
self.dispose()
}
}
func run() -> Disposable {
let disposeEverything = SerialDisposable()
let cancelSchedule = SingleAssignmentDisposable()
disposeEverything.disposable = cancelSchedule
cancelSchedule.disposable = parent.scheduler.schedule(()) { (_) -> Disposable in
let subscription = self.parent.source.subscribe(self)
disposeEverything.disposable = ScheduledDisposable(scheduler: self.parent.scheduler, disposable: subscription)
return Disposables.create()
}
return disposeEverything
}
}
class SubscribeOn<Ob: ObservableType> : Producer<Ob.E> {
let source: Ob
let scheduler: ImmediateSchedulerType
init(source: Ob, scheduler: ImmediateSchedulerType) {
self.source = source
self.scheduler = scheduler
}
override func run<O : ObserverType>(_ observer: O) -> Disposable where O.E == Ob.E {
let sink = SubscribeOnSink(parent: self, observer: observer)
sink.disposable = sink.run()
return sink
}
}
|
mit
|
9e1638598914d3e2f8b84b767a4b9f4f
| 27.416667 | 122 | 0.626979 | 4.65847 | false | false | false | false |
SBGMobile/Charts
|
Source/ChartsRealm/Data/RealmBaseDataSet.swift
|
4
|
16284
|
//
// RealmBaseDataSet.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
#if NEEDS_CHARTS
import Charts
#endif
import Realm
import Realm.Dynamic
open class RealmBaseDataSet: ChartBaseDataSet
{
open func initialize()
{
fatalError("RealmBaseDataSet is an abstract class, you must inherit from it. Also please do not call super.initialize().")
}
public required init()
{
super.init()
// default color
colors.append(NSUIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0))
initialize()
}
public override init(label: String?)
{
super.init()
// default color
colors.append(NSUIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0))
self.label = label
initialize()
}
public init(results: RLMResults<RLMObject>?, xValueField: String?, yValueField: String, label: String?)
{
super.init()
// default color
colors.append(NSUIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0))
self.label = label
_results = results
_yValueField = yValueField
_xValueField = xValueField
if _xValueField != nil
{
_results = _results?.sortedResults(usingProperty: _xValueField!, ascending: true)
}
notifyDataSetChanged()
initialize()
}
public convenience init(results: RLMResults<RLMObject>?, yValueField: String, label: String?)
{
self.init(results: results, xValueField: nil, yValueField: yValueField, label: label)
}
public convenience init(results: RLMResults<RLMObject>?, xValueField: String?, yValueField: String)
{
self.init(results: results, xValueField: xValueField, yValueField: yValueField, label: "DataSet")
}
public convenience init(results: RLMResults<RLMObject>?, yValueField: String)
{
self.init(results: results, yValueField: yValueField)
}
public init(realm: RLMRealm?, modelName: String, resultsWhere: String, xValueField: String?, yValueField: String, label: String?)
{
super.init()
// default color
colors.append(NSUIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0))
self.label = label
_yValueField = yValueField
_xValueField = xValueField
if realm != nil
{
loadResults(realm: realm!, modelName: modelName)
}
initialize()
}
public convenience init(realm: RLMRealm?, modelName: String, resultsWhere: String, yValueField: String, label: String?)
{
self.init(realm: realm, modelName: modelName, resultsWhere: resultsWhere, xValueField: nil, yValueField: yValueField, label: label)
}
open func loadResults(realm: RLMRealm, modelName: String)
{
loadResults(realm: realm, modelName: modelName, predicate: nil)
}
open func loadResults(realm: RLMRealm, modelName: String, predicate: NSPredicate?)
{
if predicate == nil
{
_results = realm.allObjects(modelName)
}
else
{
_results = realm.objects(modelName, with: predicate!)
}
if _xValueField != nil
{
_results = _results?.sortedResults(usingProperty: _xValueField!, ascending: true)
}
notifyDataSetChanged()
}
// MARK: - Data functions and accessors
internal var _results: RLMResults<RLMObject>?
internal var _yValueField: String?
internal var _xValueField: String?
internal var _cache = [ChartDataEntry]()
internal var _yMax: Double = -DBL_MAX
internal var _yMin: Double = DBL_MAX
internal var _xMax: Double = -DBL_MAX
internal var _xMin: Double = DBL_MAX
/// Makes sure that the cache is populated for the specified range
internal func buildCache()
{
guard let results = _results else { return }
_cache.removeAll()
_cache.reserveCapacity(Int(results.count))
var xValue: Double = 0.0
let iterator = NSFastEnumerationIterator(results)
while let e = iterator.next()
{
_cache.append(buildEntryFromResultObject(e as! RLMObject, x: xValue))
xValue += 1.0
}
}
internal func buildEntryFromResultObject(_ object: RLMObject, x: Double) -> ChartDataEntry
{
let entry = ChartDataEntry(x: _xValueField == nil ? x : object[_xValueField!] as! Double, y: object[_yValueField!] as! Double)
return entry
}
/// Makes sure that the cache is populated for the specified range
internal func clearCache()
{
_cache.removeAll()
}
/// Use this method to tell the data set that the underlying data has changed
open override func notifyDataSetChanged()
{
buildCache()
calcMinMax()
}
open override func calcMinMax()
{
if _cache.count == 0
{
return
}
_yMax = -DBL_MAX
_yMin = DBL_MAX
_xMax = -DBL_MAX
_xMin = DBL_MAX
for e in _cache
{
calcMinMax(entry: e)
}
}
/// Updates the min and max x and y value of this DataSet based on the given Entry.
///
/// - parameter e:
internal func calcMinMax(entry e: ChartDataEntry)
{
if e.y < _yMin
{
_yMin = e.y
}
if e.y > _yMax
{
_yMax = e.y
}
if e.x < _xMin
{
_xMin = e.x
}
if e.x > _xMax
{
_xMax = e.x
}
}
/// - returns: The minimum y-value this DataSet holds
open override var yMin: Double { return _yMin }
/// - returns: The maximum y-value this DataSet holds
open override var yMax: Double { return _yMax }
/// - returns: The minimum x-value this DataSet holds
open override var xMin: Double { return _xMin }
/// - returns: The maximum x-value this DataSet holds
open override var xMax: Double { return _xMax }
/// - returns: The number of y-values this DataSet represents
open override var entryCount: Int { return Int(_results?.count ?? 0) }
/// - returns: The entry object found at the given index (not x-value!)
/// - throws: out of bounds
/// if `i` is out of bounds, it may throw an out-of-bounds exception
open override func entryForIndex(_ i: Int) -> ChartDataEntry?
{
if _cache.count == 0
{
buildCache()
}
return _cache[i]
}
/// - returns: The first Entry object found at the given x-value with binary search.
/// If the no Entry at the specified x-value is found, this method returns the Entry at the closest x-value according to the rounding.
/// nil if no Entry object at that x-value.
/// - parameter xValue: the x-value
/// - parameter closestToY: If there are multiple y-values for the specified x-value,
/// - parameter rounding: determine whether to round up/down/closest if there is no Entry matching the provided x-value
open override func entryForXValue(
_ xValue: Double,
closestToY yValue: Double,
rounding: ChartDataSetRounding) -> ChartDataEntry?
{
let index = self.entryIndex(x: xValue, closestToY: yValue, rounding: rounding)
if index > -1
{
return entryForIndex(index)
}
return nil
}
/// - returns: The first Entry object found at the given x-value with binary search.
/// If the no Entry at the specified x-value is found, this method returns the Entry at the closest x-value.
/// nil if no Entry object at that x-value.
/// - parameter xValue: the x-value
/// - parameter closestToY: If there are multiple y-values for the specified x-value,
open override func entryForXValue(
_ xValue: Double,
closestToY y: Double) -> ChartDataEntry?
{
return entryForXValue(xValue, closestToY: y, rounding: .closest)
}
/// - returns: All Entry objects found at the given x-value with binary search.
/// An empty array if no Entry object at that x-value.
open override func entriesForXValue(_ xValue: Double) -> [ChartDataEntry]
{
/*var entries = [ChartDataEntry]()
guard let results = _results else { return entries }
if _xValueField != nil
{
let foundObjects = results.objectsWithPredicate(
NSPredicate(format: "%K == %f", _xValueField!, x)
)
for e in foundObjects
{
entries.append(buildEntryFromResultObject(e as! RLMObject, x: x))
}
}
return entries*/
var entries = [ChartDataEntry]()
var low = 0
var high = _cache.count - 1
while low <= high
{
var m = (high + low) / 2
var entry = _cache[m]
if xValue == entry.x
{
while m > 0 && _cache[m - 1].x == xValue
{
m -= 1
}
high = _cache.count
while m < high
{
entry = _cache[m]
if entry.x == xValue
{
entries.append(entry)
}
else
{
break
}
m += 1
}
break
}
else
{
if xValue > entry.x
{
low = m + 1
}
else
{
high = m - 1
}
}
}
return entries
}
/// - returns: The array-index of the specified entry.
/// If the no Entry at the specified x-value is found, this method returns the index of the Entry at the closest x-value according to the rounding.
///
/// - parameter xValue: x-value of the entry to search for
/// - parameter closestToY: If there are multiple y-values for the specified x-value,
/// - parameter rounding: Rounding method if exact value was not found
open override func entryIndex(
x xValue: Double,
closestToY yValue: Double,
rounding: ChartDataSetRounding) -> Int
{
/*guard let results = _results else { return -1 }
let foundIndex = results.indexOfObjectWithPredicate(
NSPredicate(format: "%K == %f", _xValueField!, x)
)
// TODO: Figure out a way to quickly find the closest index
return Int(foundIndex)*/
var low = 0
var high = _cache.count - 1
var closest = high
while low < high
{
let m = (low + high) / 2
let d1 = _cache[m].x - xValue
let d2 = _cache[m + 1].x - xValue
let ad1 = abs(d1), ad2 = abs(d2)
if ad2 < ad1
{
// [m + 1] is closer to xValue
// Search in an higher place
low = m + 1
}
else if ad1 < ad2
{
// [m] is closer to xValue
// Search in a lower place
high = m
}
else
{
// We have multiple sequential x-value with same distance
if d1 >= 0.0
{
// Search in a lower place
high = m
}
else if d1 < 0.0
{
// Search in an higher place
low = m + 1
}
}
closest = high
}
if closest != -1
{
let closestXValue = _cache[closest].x
if rounding == .up
{
// If rounding up, and found x-value is lower than specified x, and we can go upper...
if closestXValue < xValue && closest < _cache.count - 1
{
closest += 1
}
}
else if rounding == .down
{
// If rounding down, and found x-value is upper than specified x, and we can go lower...
if closestXValue > xValue && closest > 0
{
closest -= 1
}
}
// Search by closest to y-value
if !yValue.isNaN
{
while closest > 0 && _cache[closest - 1].x == closestXValue
{
closest -= 1
}
var closestYValue = _cache[closest].y
var closestYIndex = closest
while true
{
closest += 1
if closest >= _cache.count { break }
let value = _cache[closest]
if value.x != closestXValue { break }
if abs(value.y - yValue) < abs(closestYValue - yValue)
{
closestYValue = yValue
closestYIndex = closest
}
}
closest = closestYIndex
}
}
return closest
}
/// - returns: The array-index of the specified entry
///
/// - parameter e: the entry to search for
open override func entryIndex(entry e: ChartDataEntry) -> Int
{
for i in 0 ..< _cache.count
{
if _cache[i] === e || _cache[i].isEqual(e)
{
return i
}
}
return -1
}
/// Not supported on Realm datasets
open override func addEntry(_ e: ChartDataEntry) -> Bool
{
return false
}
/// Not supported on Realm datasets
open override func addEntryOrdered(_ e: ChartDataEntry) -> Bool
{
return false
}
/// Not supported on Realm datasets
open override func removeEntry(_ entry: ChartDataEntry) -> Bool
{
return false
}
/// Checks if this DataSet contains the specified Entry.
/// - returns: `true` if contains the entry, `false` ifnot.
open override func contains(_ e: ChartDataEntry) -> Bool
{
for entry in _cache
{
if entry.isEqual(e)
{
return true
}
}
return false
}
/// - returns: The fieldname that represents the "y-values" in the realm-data.
open var yValueField: String?
{
get
{
return _yValueField
}
}
/// - returns: The fieldname that represents the "x-values" in the realm-data.
open var xValueField: String?
{
get
{
return _xValueField
}
}
// MARK: - NSCopying
open override func copyWithZone(_ zone: NSZone?) -> AnyObject
{
let copy = super.copyWithZone(zone) as! RealmBaseDataSet
copy._results = _results
copy._yValueField = _yValueField
copy._xValueField = _xValueField
copy._yMax = _yMax
copy._yMin = _yMin
copy._xMax = _xMax
copy._xMin = _xMin
return copy
}
}
|
apache-2.0
|
5bc651bd4feec58d85b45d49c5168cf1
| 28.026738 | 151 | 0.50786 | 4.87399 | false | false | false | false |
tomasharkema/HoelangTotTrein.iOS
|
Pods/Observable-Swift/Observable-Swift/TupleObservable.swift
|
17
|
2230
|
//
// TupleObservable.swift
// Observable-Swift
//
// Created by Leszek Ślażyński on 20/06/14.
// Copyright (c) 2014 Leszek Ślażyński. All rights reserved.
//
public class PairObservable<O1: AnyObservable, O2: AnyObservable> : OwnableObservable {
internal typealias T1 = O1.ValueType
internal typealias T2 = O2.ValueType
public typealias ValueType = (T1, T2)
public /*internal(set)*/ var beforeChange = EventReference<ValueChange<(T1, T2)>>()
public /*internal(set)*/ var afterChange = EventReference<ValueChange<(T1, T2)>>()
internal var first : T1
internal var second : T2
public var value : (T1, T2) { return (first, second) }
internal let _base1 : O1
internal let _base2 : O2
public init (_ o1: O1, _ o2: O2) {
_base1 = o1
_base2 = o2
first = o1.value
second = o2.value
o1.beforeChange.add(owner: self) { [weak self] c1 in
let oldV = (c1.oldValue, self!.second)
let newV = (c1.newValue, self!.second)
let change = ValueChange(oldV, newV)
self!.beforeChange.notify(change)
}
o1.afterChange.add(owner: self) { [weak self] c1 in
let nV1 = c1.newValue
self!.first = nV1
let oldV = (c1.oldValue, self!.second)
let newV = (c1.newValue, self!.second)
let change = ValueChange(oldV, newV)
self!.afterChange.notify(change)
}
o2.beforeChange.add(owner: self) { [weak self] c2 in
let oldV = (self!.first, c2.oldValue)
let newV = (self!.first, c2.newValue)
let change = ValueChange(oldV, newV)
self!.beforeChange.notify(change)
}
o2.afterChange.add(owner: self) { [weak self] c2 in
let nV2 = c2.newValue
self!.second = nV2
let oldV = (self!.first, c2.oldValue)
let newV = (self!.first, c2.newValue)
let change = ValueChange(oldV, newV)
self!.afterChange.notify(change)
}
}
}
public func & <O1 : AnyObservable, O2: AnyObservable> (x: O1, y: O2) -> PairObservable<O1, O2> {
return PairObservable(x, y)
}
|
apache-2.0
|
14afceb508ab2a47f14227630671bb00
| 32.69697 | 96 | 0.578237 | 3.633987 | false | false | false | false |
RockyAo/Dictionary
|
Dictionary/Classes/Main/View/MainTabbarController.swift
|
1
|
2803
|
//
// MainTabbarController.swift
// BeiJingJiaoJing
//
// Created by Rocky on 2017/3/7.
// Copyright © 2017年 Rocky. All rights reserved.
//
import UIKit
import ESTabBarController_swift
final class MainTabbarController: ESTabBarController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
addChildViewControllers()
setTabbar()
delegate = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true);
selectedIndex = 0
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(true)
}
func bindViewModel() {
}
}
// MARK: - 设置界面
extension MainTabbarController {
fileprivate func setTabbar(){
UITabBarItem.appearance().setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 13)], for: .normal)
UITabBarItem.appearance().setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 13)], for: .selected)
}
fileprivate func addChildViewControllers(){
addChildViewController(HomeViewController(), title: "词典", normalImage: #imageLiteral(resourceName: "tabbar_dictionary"), selectedImage: #imageLiteral(resourceName: "tabbar_dictionary_selected"))
addChildViewController(BookViewController(), title:"单词本", normalImage: #imageLiteral(resourceName: "tabbar_notebook"), selectedImage: #imageLiteral(resourceName: "tabbar_dictionary_selected"))
addChildViewController(SettingViewController.createViewControllerFromStoryboard()!, title: "设置", normalImage: #imageLiteral(resourceName: "tabbar_setting"), selectedImage: #imageLiteral(resourceName: "tabbar_setting_selected"))
}
fileprivate func addChildViewController(_ vc: UIViewController, title: String, normalImage: UIImage,selectedImage:UIImage) {
vc.title = title
vc.tabBarItem = ESTabBarItem.init(TabbarItemBounceContentView(), title: title, image:normalImage, selectedImage: selectedImage)
let nav:CustomNavigationController = CustomNavigationController(rootViewController: vc)
addChildViewController(nav)
}
}
// MARK: - UITabBarControllerDelegate
extension MainTabbarController:UITabBarControllerDelegate{
func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
return true
}
//
}
|
agpl-3.0
|
43b5dad4b6ffe80f05228b57a6dfe416
| 27.346939 | 235 | 0.664867 | 5.7875 | false | false | false | false |
krzysztofzablocki/Sourcery
|
Sourcery/Utils/Xcode+Extensions.swift
|
1
|
4696
|
import Foundation
import PathKit
import XcodeProj
import SourceryRuntime
private struct UnableToAddSourceFile: Error {
var targetName: String
var path: String
}
extension XcodeProj {
func target(named targetName: String) -> PBXTarget? {
return pbxproj.targets(named: targetName).first
}
func fullPath<E: PBXFileElement>(fileElement: E, sourceRoot: Path) -> Path? {
return try? fileElement.fullPath(sourceRoot: sourceRoot)
}
func sourceFilesPaths(target: PBXTarget, sourceRoot: Path) -> [Path] {
let sourceFiles = (try? target.sourceFiles()) ?? []
return sourceFiles
.compactMap({ fullPath(fileElement: $0, sourceRoot: sourceRoot) })
}
var rootGroup: PBXGroup? {
do {
return try pbxproj.rootGroup()
} catch {
Log.error("Can't find root group for pbxproj")
return nil
}
}
func addGroup(named groupName: String, to toGroup: PBXGroup, options: GroupAddingOptions = []) -> PBXGroup? {
do {
return try toGroup.addGroup(named: groupName, options: options).last
} catch {
Log.error("Can't add group \(groupName) to group (uuid: \(toGroup.uuid), name: \(String(describing: toGroup.name))")
return nil
}
}
func addSourceFile(at filePath: Path, toGroup: PBXGroup, target: PBXTarget, sourceRoot: Path) throws {
let fileReference = try toGroup.addFile(at: filePath, sourceRoot: sourceRoot)
let file = PBXBuildFile(file: fileReference, product: nil, settings: nil)
guard let fileElement = file.file, let sourcePhase = try target.sourcesBuildPhase() else {
throw UnableToAddSourceFile(targetName: target.name, path: filePath.string)
}
let buildFile = try sourcePhase.add(file: fileElement)
pbxproj.add(object: buildFile)
}
func createGroupIfNeeded(named group: String? = nil, sourceRoot: Path) -> PBXGroup? {
guard let rootGroup = rootGroup else {
Log.warning("Unable to find rootGroup for the project")
return nil
}
guard let group = group else {
return rootGroup
}
var fileGroup: PBXGroup = rootGroup
var parentGroup: PBXGroup = rootGroup
let components = group.components(separatedBy: "/")
// Find existing group to reuse
// Having `ProjectRoot/Data/` exists and given group to create `ProjectRoot/Data/Generated`
// will create `Generated` group under ProjectRoot/Data to link files to
let existingGroup = findGroup(in: fileGroup, components: components)
var groupName: String?
switch existingGroup {
case let (group, components) where group != nil:
if components.isEmpty {
// Group path is already exists
fileGroup = group!
} else {
// Create rest of the group and attach to last found parent
groupName = components.joined(separator: "/")
parentGroup = group!
}
default:
// Create new group from scratch
groupName = group
}
if let groupName = groupName {
do {
if let addedGroup = addGroup(named: groupName, to: parentGroup),
let groupPath = fullPath(fileElement: addedGroup, sourceRoot: sourceRoot) {
fileGroup = addedGroup
try groupPath.mkpath()
}
} catch {
Log.warning("Failed to create a folder for group '\(fileGroup.name ?? "")'. \(error)")
}
}
return fileGroup
}
}
private extension XcodeProj {
func findGroup(in group: PBXGroup, components: [String]) -> (group: PBXGroup?, components: [String]) {
let existingGroup = findGroup(in: group, components: components, validate: { $0?.path == $1 })
if existingGroup.group?.path != nil {
return existingGroup
}
return findGroup(in: group, components: components, validate: { $0?.name == $1 })
}
func findGroup(in group: PBXGroup, components: [String], validate: (PBXFileElement?, String?) -> Bool) -> (group: PBXGroup?, components: [String]) {
return components.reduce((group: group as PBXGroup?, components: components)) { current, name in
let first = current.group?.children.first { validate($0, name) } as? PBXGroup
let result = first ?? current.group
return (result, current.components.filter { !validate(result, $0) })
}
}
}
|
mit
|
db73507f5f2cb535d9fd40fe5bba175b
| 35.403101 | 152 | 0.601576 | 4.714859 | false | false | false | false |
dnevera/IMProcessing
|
IMProcessing/Classes/Math/IMPDistribution.swift
|
1
|
10025
|
//
// IMPDistribution.swift
// IMProcessing
//
// Created by denis svinarchuk on 22.12.15.
// Copyright © 2015 Dehancer.photo. All rights reserved.
//
import Foundation
import Accelerate
public extension Int {
/// Create gaussian kernel distribution with kernel size in pixels
///
/// - parameter size: kernel size
///
/// - returns: gaussian kernel piecewise distribution
public var gaussianKernel:[Float]{
get{
let size = self % 2 == 1 ? self : self + 1
let epsilon:Float = 2e-2 / size.float
var searchStep:Float = 1.0
var sigma:Float = 1.0
while( true )
{
let kernel = sigma.gaussianKernel(size: size)
if kernel[0] > epsilon {
if searchStep > 0.02 {
sigma -= searchStep
searchStep *= 0.1
sigma += searchStep
continue
}
var retVal = [Float]()
for i in 0 ..< size {
retVal.append(kernel[i])
}
return retVal
}
sigma += searchStep
if sigma > 1000.0{
return [0]
}
}
}
}
}
// MARK: - Gaussian kernel distribution
public extension Float {
/// Create gaussian kernel distribution with sigma and kernel size
///
/// - parameter sigma: kernel sigma
/// - parameter size: kernel size, must be odd number
///
/// - returns: gaussian kernel piecewise distribution
///
public static func gaussianKernel(sigma sigma:Float, size:Int) -> [Float] {
assert(size%2==1, "gaussian kernel size must be odd number...")
var kernel = [Float](count: size, repeatedValue: 0)
let mean = Float(size/2)
var sum:Float = 0.0
//for var x = 0; x < size; x += 1 {
for x in 0..<size {
kernel[x] = sqrt( exp( -0.5 * (pow((x.float-mean)/sigma, 2.0) + pow((mean)/sigma,2.0)) )
/ (M_2_PI.float * sigma * sigma) )
sum += kernel[x]
}
vDSP_vsdiv(kernel, 1, &sum, &kernel, 1, vDSP_Length(kernel.count))
return kernel
}
/// Create gaussian kernel distribution from sigma value with kernel size
///
/// - parameter size: kernel size, must be odd number
///
/// - returns: gaussian kernel piecewise distribution
///
public func gaussianKernel(size size:Int) -> [Float] {
return Float.gaussianKernel(sigma: self, size: size)
}
}
// MARK: - Gaussian value in certain point of x
public extension Float{
/// Get gaussian Y point from distripbution of X in certain point
///
/// - parameter fi: ƒ
/// - parameter mu: µ
/// - parameter sigma: ß
///
/// - returns: Y value
public func gaussianPoint(fi fi:Float, mu:Float, sigma:Float) -> Float {
return fi * exp( -(pow(( self - mu ),2)) / (2*pow(sigma, 2)) )
}
/// Get double pointed gaussian Y point from distripbution of two X points
///
/// - parameter fi: float2(ƒ1,ƒ2)
/// - parameter mu: float2(µ1,µ2)
/// - parameter sigma: float2(ß1,ß2)
///
/// - returns: y value
public func gaussianPoint(fi fi:float2, mu:float2, sigma:float2) -> Float {
let c1 = self <= mu.x ? 1.float : 0.float
let c2 = self >= mu.y ? 1.float : 0.float
let y1 = self.gaussianPoint(fi: fi.x, mu: mu.x, sigma: sigma.x) * c1 + (1.0-c1)
let y2 = self.gaussianPoint(fi: fi.y, mu: mu.y, sigma: sigma.y) * c2 + (1.0-c2)
return y1 * y2
}
/// Get normalized gaussian Y point from distripbution of two X points
///
/// - parameter fi: ƒ
/// - parameter mu: µ
/// - parameter sigma: ß
///
/// - returns: y value
public func gaussianPoint(mu:Float, sigma:Float) -> Float {
return self.gaussianPoint(fi: 1/(sigma*sqrt(2*M_PI.float)), mu: mu, sigma: sigma)
}
/// Get double normalized gaussian Y point from distripbution of two X points
///
/// - parameter fi: float2(ƒ1,ƒ2)
/// - parameter mu: float2(µ1,µ2)
/// - parameter sigma: float2(ß1,ß2)
///
/// - returns: Y value
public func gaussianPoint(mu:float2, sigma:float2) -> Float {
return self.gaussianPoint(fi:float2(1), mu: mu, sigma: sigma)
}
/// Create linear range X points within range
///
/// - parameter r: range
///
/// - returns: X list
static func range(r:Range<Int>) -> [Float]{
return range(start: Float(r.startIndex), step: 1, end: Float(r.endIndex))
}
/// Create linear range X points within range scaled to particular value
///
/// - parameter r: range
///
/// - returns: X list
static func range(r:Range<Int>, scale:Float) -> [Float]{
var r = range(start: Float(r.startIndex), step: 1, end: Float(r.endIndex))
var denom:Float = 0
vDSP_maxv(r, 1, &denom, vDSP_Length(r.count))
denom /= scale
vDSP_vsdiv(r, 1, &denom, &r, 1, vDSP_Length(r.count))
return r
}
/// Create linear range X points within range of start/end with certain step
///
/// - parameter start: start value
/// - parameter step: step, must be less then end-start
/// - parameter end: end, must be great the start
///
/// - returns: X list
static func range(start start:Float, step:Float, end:Float) -> [Float] {
let size = Int((end-start)/step)
var h:[Float] = [Float](count: size, repeatedValue: 0)
var zero:Float = start
var v:Float = step
vDSP_vramp(&zero, &v, &h, 1, vDSP_Length(size))
return h
}
}
// MARK: - Gaussian distribution
public extension SequenceType where Generator.Element == Float {
/// Create gaussian distribution of discrete values of Y's from mean parameters
///
/// - parameter fi: ƒ
/// - parameter mu: µ
/// - parameter sigma: ß
///
/// - returns: discrete gaussian distribution
public func gaussianDistribution(fi fi:Float, mu:Float, sigma:Float) -> [Float]{
var a = [Float]()
for i in self{
a.append(i.gaussianPoint(fi: fi, mu: mu, sigma: sigma))
}
return a
}
/// Create gaussian distribution of discrete values of Y points from two points of means
///
/// - parameter fi: float2(ƒ1,ƒ2)
/// - parameter mu: float2(µ1,µ2)
/// - parameter sigma: float2(ß1,ß2)
///
/// - returns: discrete gaussian distribution
public func gaussianDistribution(fi fi:float2, mu:float2, sigma:float2) -> [Float]{
var a = [Float]()
for i in self{
a.append(i.gaussianPoint(fi: fi, mu: mu, sigma: sigma))
}
return a
}
/// Create normalized gaussian distribution of discrete values of Y's from mean parameters
///
/// - parameter mu: µ
/// - parameter sigma: ß
///
/// - returns: discrete gaussian distribution
public func gaussianDistribution(mu mu:Float, sigma:Float) -> [Float]{
return self.gaussianDistribution(fi: 1/(sigma*sqrt(2*M_PI.float)), mu: mu, sigma: sigma)
}
/// Create normalized gaussian distribution of discrete values of Y points from two points of means
///
/// - parameter mu: float2(µ1,µ2)
/// - parameter sigma: float2(ß1,ß2)
///
/// - returns: discrete gaussian distribution
public func gaussianDistribution(mu mu:float2, sigma:float2) -> [Float]{
return self.gaussianDistribution(fi: float2(1/(sigma.x*sigma.y*sqrt(2*M_PI.float))), mu: mu, sigma: sigma)
}
}
///
/// In two dimensions, the circular Gaussian function is the distribution function for uncorrelated variates X and Y having
/// a bivariate normal distribution and equal standard deviation sigma=sigma_x=sigma_y,
///
public extension CollectionType where Generator.Element == [Float] {
/// Create 2D gaussian distribution of discrete values of X/Y's
///
/// - parameter fi: ƒ
/// - parameter mu: µ
/// - parameter sigma: ß
///
/// - returns: discrete 2D gaussian distribution
///
/// http://mathworld.wolfram.com/GaussianFunction.html
///
public func gaussianDistribution(fi fi:Float, mu:float2, sigma:float2) -> [Float]{
if self.count != 2 {
fatalError("CollectionType must have 2 dimension Float array with X-points and Y-points lists...")
}
var a = [Float]()
for y in self[1 as! Self.Index]{
let yd = pow(( y - mu.y ),2) / (2*pow(sigma.y, 2))
for x in self[0 as! Self.Index]{
let xd = pow(( x - mu.x ),2) / (2*pow(sigma.x, 2))
a.append(fi * exp( -(xd+yd) ))
}
}
return a
}
/// Create normalized 2D gaussian distribution of discrete values of X/Y's
///
/// - parameter mu: µ
/// - parameter sigma: ß
///
/// - returns: discrete 2D gaussian distribution
///
/// http://mathworld.wolfram.com/GaussianFunction.html
///
public func gaussianDistribution(mu mu:float2, sigma:float2) -> [Float]{
if self.count != 2 {
fatalError("CollectionType must have 2 dimension Float array with X-points and Y-points lists...")
}
let fi = 1/(sigma.x*sigma.y*sqrt(2*M_PI.float))
return gaussianDistribution(fi: fi, mu: mu, sigma: sigma)
}
}
|
mit
|
7ee2237e553bb8a957ce22c17bc2ed1a
| 32.17608 | 123 | 0.54306 | 3.85411 | false | false | false | false |
thatseeyou/SpriteKitExamples.playground
|
Sources/Log.swift
|
1
|
2446
|
import UIKit
extension UIApplication {
class func topViewController(_ base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
return base
}
}
extension CGRect {
func rectString() -> String {
// frame = (0 0; 320 480)
return "(\(Int(self.origin.x)) \(Int(self.origin.y)); \(Int(self.size.width)) \(Int(self.size.height)))"
}
}
var eventTraceDepth = -1
public extension NSObject {
func enterEventTrace(_ funcname:String = #function, filename:String = #file) {
eventTraceDepth += 1
let space = String(repeating: " ", count: eventTraceDepth * 4)
print("\(space)--> \(type(of: self))(\(Unmanaged.passUnretained(self).toOpaque()))::\(funcname)")
func printView(_ view:UIView) {
print("\(space) frame = \(view.frame.rectString())")
if view.bounds.origin != CGPoint.zero {
print("\(space) bounds = \(view.bounds.rectString())")
}
if view.window != nil {
if let superview = view.superview {
let rect = superview.convert(view.frame, to: nil)
print("\(space) screen = \(rect.rectString())")
}
}
}
if let view = self as? UIView {
printView(view)
}
if let viewController = self as? UIViewController {
if let view = viewController.view {
printView(view)
}
}
}
func exitEventTrace(_ funcname:String = #function, filename:String = #file) {
eventTraceDepth -= 1
// print("<-- \(self.dynamicType)(\(unsafeAddressOf(self)))::\(funcname)")
}
func logTrace(_ funcname:String = #function) {
print("\(type(of: self))(\(Unmanaged.passUnretained(self).toOpaque()))::\(funcname) called")
}
func logDebug(_ msg:String, funcname:String = #function) {
print("\(type(of: self))(\(Unmanaged.passUnretained(self).toOpaque()))::\(funcname) \(msg)")
}
func logViewHierarchy(_ funcname:String = #function) {
if let view = UIApplication.topViewController()?.view {
print("\n>>> View hierarcy at \(funcname)")
print(view.perform(NSSelectorFromString("recursiveDescription")))
print("<<< View hierarcy at \(funcname)\n")
}
else {
print("no top view")
}
}
}
|
isc
|
d911768b058c666821c3982f08a231d3
| 33.942857 | 135 | 0.561733 | 4.375671 | false | false | false | false |
evgenyneu/Cosmos
|
Demo/ViewController.swift
|
2
|
2194
|
import UIKit
import Cosmos
class ViewController: UIViewController {
@IBOutlet weak var cosmosViewFull: CosmosView!
@IBOutlet weak var cosmosViewHalf: CosmosView!
@IBOutlet weak var cosmosViewPrecise: CosmosView!
@IBOutlet weak var ratingSlider: UISlider!
@IBOutlet weak var ratingLabel: UILabel!
private let startRating: Float = 3.7
override func viewDidLoad() {
super.viewDidLoad()
// Register touch handlers
cosmosViewFull.didTouchCosmos = didTouchCosmos
cosmosViewHalf.didTouchCosmos = didTouchCosmos
cosmosViewPrecise.didTouchCosmos = didTouchCosmos
cosmosViewFull.didFinishTouchingCosmos = didFinishTouchingCosmos
cosmosViewHalf.didFinishTouchingCosmos = didFinishTouchingCosmos
cosmosViewPrecise.didFinishTouchingCosmos = didFinishTouchingCosmos
//update with initial data
ratingSlider.value = startRating
updateRating(requiredRating: nil)
}
@IBAction func onSliderChanged(_ sender: AnyObject) {
updateRating(requiredRating: nil)
}
private func updateRating(requiredRating: Double?) {
var newRatingValue: Double = 0
if let nonEmptyRequiredRating = requiredRating {
newRatingValue = nonEmptyRequiredRating
} else {
newRatingValue = Double(ratingSlider.value)
}
cosmosViewFull.rating = newRatingValue
cosmosViewHalf.rating = newRatingValue
cosmosViewPrecise.rating = newRatingValue
self.ratingLabel.text = ViewController.formatValue(newRatingValue)
}
private class func formatValue(_ value: Double) -> String {
return String(format: "%.2f", value)
}
private func didTouchCosmos(_ rating: Double) {
ratingSlider.value = Float(rating)
updateRating(requiredRating: rating)
ratingLabel.text = ViewController.formatValue(rating)
ratingLabel.textColor = UIColor(red: 133/255, green: 116/255, blue: 154/255, alpha: 1)
}
private func didFinishTouchingCosmos(_ rating: Double) {
ratingSlider.value = Float(rating)
self.ratingLabel.text = ViewController.formatValue(rating)
ratingLabel.textColor = UIColor(red: 183/255, green: 186/255, blue: 204/255, alpha: 1)
}
}
|
mit
|
9ef02df7ec2df3826ce18f9fdb00f46e
| 30.797101 | 90 | 0.731541 | 4.658174 | false | false | false | false |
redarcgroup/UIInsetLabel
|
Source/UIInsetLabel-Swift3.0.swift
|
1
|
2099
|
//
// UIInsetLabel.swift - Swift 3.0
// Copyright © 2016 RedArc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
class UIInsetLabel: UILabel
{
var paddingInsets: UIEdgeInsets?
override func drawText(in rect: CGRect)
{
guard let insets: UIEdgeInsets = paddingInsets else
{
super.drawText(in: rect)
return
}
super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
override var intrinsicContentSize : CGSize
{
get
{
let superViewContentSize: CGSize = super.intrinsicContentSize
guard let insets: UIEdgeInsets = paddingInsets else
{
return (superViewContentSize)
}
let insetWidth: CGFloat = insets.left + insets.right
let insetHeight: CGFloat = insets.top + insets.bottom
return (CGSize(width: (superViewContentSize.width + insetWidth), height: (superViewContentSize.height + insetHeight)))
}
}
var RectforPopover: CGRect
{
get
{
return(CGRect(x: 0.0, y: 0.0, width: super.frame.width, height: super.frame.height))
}
}
}
|
mit
|
e26e4501495bb2d7cc5f343db0b76c62
| 32.301587 | 121 | 0.733079 | 3.885185 | false | false | false | false |
alltheflow/iCopyPasta
|
iCopyPastaTests/PasteboardItemTests.swift
|
1
|
1144
|
//
// PasteboardItemTests.swift
// iCopyPasta
//
// Created by Vásárhelyi Ágnes on 26/01/16.
// Copyright © 2016 Agnes Vasarhelyi. All rights reserved.
//
import XCTest
@testable import iCopyPasta
class PasteboardItemTests: XCTestCase {
func testTextItem() {
let textItem = PasteboardItem.Text("copy")
XCTAssert(textItem == .Text("copy"), "should handle equal operator")
XCTAssert(textItem != .Text("copy pasta"), "should handle not equal operator")
}
func testImageItem() {
let imageItem = PasteboardItem.Image(UIImage(named: "pasta.png")!)
XCTAssert(imageItem == .Image(UIImage(named: "pasta.png")!), "should handle equal operator")
XCTAssert(imageItem != .Image(UIImage(named: "copy_pasta.png")!), "should handle not equal operator")
}
func testURLItem() {
let urlItem = PasteboardItem.URL(NSURL(string: "http://url.com")!)
XCTAssert(urlItem == .URL(NSURL(string: "http://url.com")!), "should handle equal operator")
XCTAssert(urlItem != .URL(NSURL(string: "http://url.co.uk")!), "should handle not equal operator")
}
}
|
mit
|
af387d88508a767e2e78353a01405cd8
| 35.774194 | 109 | 0.654386 | 3.774834 | false | true | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.