repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
apple/swift-lldb
packages/Python/lldbsuite/test/lang/swift/protocols/class_protocol/main.swift
2
970
import Foundation protocol HasWhy { var why : Int { get } } protocol ClassHasWhy : class { var why : Int { get } } class ShouldBeWhy : NSObject, ClassHasWhy, HasWhy { var before_why : Int = 0xfeedface var why : Int = 10 var after_why : Int = 0xdeadbeef } class ClassByWhy<T> where T : ClassHasWhy { let myWhy : Int init(input : T) { myWhy = input.why // FIXME <rdar://problem/43057063> } } class ByWhy<T> where T : HasWhy { let myWhy : Int init(input : T) { myWhy = input.why //%self.expect('expr -d run -- input', substrs=['a.ShouldBeWhy', 'isa = a.ShouldBeWhy', 'before_why = 4277009102', 'why = 10']) //%self.expect('expr -d run -- input', substrs=['a.ShouldBeWhy', 'isa = a.ShouldBeWhy', 'before_why = 4277009102', 'why = 10']) } } func doIt() { let mySBW = ShouldBeWhy() let byWhy = ByWhy(input: mySBW) let classByWhy = ClassByWhy(input: mySBW) print(byWhy.myWhy, classByWhy.myWhy) } doIt()
apache-2.0
848faef203e1ee6d5ec1c976aeb42b3b
19.638298
149
0.624742
2.811594
false
false
false
false
loganSims/wsdot-ios-app
wsdot/AlertInAreaViewController.swift
1
7660
// // AlertInAreaViewController.swift // WSDOT // // Copyright (c) 2016 Washington State Department of Transportation // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/> // import Foundation import UIKit import SafariServices class AlertsInAreaViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, INDLinkLabelDelegate { let cellIdentifier = "AlertCell" let SegueHighwayAlertViewController = "HighwayAlertViewController" var alerts = [HighwayAlertItem]() var trafficAlerts = [HighwayAlertItem]() var constructionAlerts = [HighwayAlertItem]() var specialEvents = [HighwayAlertItem]() @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() for alert in alerts{ if alert.eventCategory.lowercased() == "special event"{ specialEvents.append(alert) } else if alert.headlineDesc.lowercased().contains("construction") || alert.eventCategory.lowercased().contains("construction") { constructionAlerts.append(alert) }else { trafficAlerts.append(alert) } } trafficAlerts = trafficAlerts.sorted(by: {$0.lastUpdatedTime.timeIntervalSince1970 > $1.lastUpdatedTime.timeIntervalSince1970}) constructionAlerts = constructionAlerts.sorted(by: {$0.lastUpdatedTime.timeIntervalSince1970 > $1.lastUpdatedTime.timeIntervalSince1970}) specialEvents = specialEvents.sorted(by: {$0.lastUpdatedTime.timeIntervalSince1970 > $1.lastUpdatedTime.timeIntervalSince1970}) tableView.rowHeight = UITableView.automaticDimension } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) MyAnalytics.screenView(screenName: "AreaAlerts") } // MARK: Table View Data Source Methods func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { return UITableView.automaticDimension } func numberOfSections(in tableView: UITableView) -> Int { return 3 } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch(section){ case 0: return "Traffic Incidents" + (self.title != "Alert" && (trafficAlerts.count == 0) ? " - None Reported": "") case 1: return "Construction" + (self.title != "Alert" && (constructionAlerts.count == 0) ? " - None Reported": "") case 2: return "Special Events" + (self.title != "Alert" && (specialEvents.count == 0) ? " - None Reported": "") default: return nil } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch(section){ case 0: return trafficAlerts.count case 1: return constructionAlerts.count case 2: return specialEvents.count default: return 0 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! LinkCell let htmlStyleString = "<style>body{font-family: '\(cell.linkLabel.font.familyName)'; font-size:\(cell.linkLabel.font.pointSize)px;}</style>" var htmlString = "" switch indexPath.section{ case 0: cell.updateTime.text = TimeUtils.timeAgoSinceDate(date: trafficAlerts[indexPath.row].lastUpdatedTime, numericDates: false) htmlString = htmlStyleString + trafficAlerts[indexPath.row].headlineDesc break case 1: cell.updateTime.text = TimeUtils.timeAgoSinceDate(date: constructionAlerts[indexPath.row].lastUpdatedTime, numericDates: false) htmlString = htmlStyleString + constructionAlerts[indexPath.row].headlineDesc break case 2: cell.updateTime.text = TimeUtils.timeAgoSinceDate(date: specialEvents[indexPath.row].lastUpdatedTime, numericDates: false) htmlString = htmlStyleString + specialEvents[indexPath.row].headlineDesc break default: break } let attrStr = try! NSMutableAttributedString( data: htmlString.data(using: String.Encoding.unicode, allowLossyConversion: false)!, options: [ NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) cell.linkLabel.attributedText = attrStr cell.linkLabel.delegate = self if #available(iOS 13, *){ cell.linkLabel.textColor = UIColor.label } return cell } // MARK: Table View Delegate Methods func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch(indexPath.section){ case 0: performSegue(withIdentifier: SegueHighwayAlertViewController, sender: trafficAlerts[indexPath.row]) break case 1: performSegue(withIdentifier: SegueHighwayAlertViewController, sender: constructionAlerts[indexPath.row]) break case 2: performSegue(withIdentifier: SegueHighwayAlertViewController, sender: specialEvents[indexPath.row]) break default: break } tableView.deselectRow(at: indexPath, animated: true) } // MARK: Naviagtion // Get refrence to child VC override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == SegueHighwayAlertViewController { let alertItem = (sender as! HighwayAlertItem) let destinationViewController = segue.destination as! HighwayAlertViewController destinationViewController.alertId = alertItem.alertId } } // MARK: INDLinkLabelDelegate func linkLabel(_ label: INDLinkLabel, didLongPressLinkWithURL URL: Foundation.URL) { let activityController = UIActivityViewController(activityItems: [URL], applicationActivities: nil) self.present(activityController, animated: true, completion: nil) } func linkLabel(_ label: INDLinkLabel, didTapLinkWithURL URL: Foundation.URL) { let config = SFSafariViewController.Configuration() config.entersReaderIfAvailable = true let svc = SFSafariViewController(url: URL, configuration: config) if #available(iOS 10.0, *) { svc.preferredControlTintColor = ThemeManager.currentTheme().secondaryColor svc.preferredBarTintColor = ThemeManager.currentTheme().mainColor } else { svc.view.tintColor = ThemeManager.currentTheme().mainColor } self.present(svc, animated: true, completion: nil) } }
gpl-3.0
2e19c2b182f30b76ca830d3bd1376517
38.689119
148
0.657963
5.250171
false
false
false
false
ryanbooker/Swiftz
Sources/Bifunctor.swift
1
1767
// // Bifunctor.swift // Swiftz // // Created by Robert Widmann on 7/25/14. // Copyright (c) 2014-2016 Maxwell Swadling. All rights reserved. // #if !XCODE_BUILD import Swiftx #endif /// A Functor where the first and second arguments are covariant. /// /// FIXME: Something in swiftc doesn't like it when conforming instances use a /// generic <D> in definitions of rightMap. It has been removed in all /// instances for now. public protocol Bifunctor { associatedtype L associatedtype B associatedtype R associatedtype D associatedtype PAC = K2<L, R> associatedtype PAD = K2<L, D> associatedtype PBC = K2<B, R> associatedtype PBD = K2<B, D> /// Map two functions individually over both sides of the bifunctor at the /// same time. func bimap(_ f : (L) -> B, _ g : (R) -> D) -> PBD // TODO: File Radar. Left/Right Map cannot be generalized. /// Map over just the first argument of the bifunctor. /// /// Default definition: /// bimap(f, identity) func leftMap(_ f : (L) -> B) -> PBC /// Map over just the second argument of the bifunctor. /// /// Default definition: /// bimap(identity, g) func rightMap(_ g : (R) -> D) -> PAD } public struct TupleBF<L, R> /*: Bifunctor*/ { public typealias B = Any public typealias D = Any public typealias PAC = (L, R) public typealias PAD = (L, D) public typealias PBC = (B, R) public typealias PBD = (B, D) public let t : (L, R) public init(_ t : (L, R)) { self.t = t } public func bimap<B, D>(_ f : ((L) -> B), _ g : ((R) -> D)) -> (B, D) { return (f(t.0), g(t.1)) } public func leftMap<B>(_ f : @escaping (L) -> B) -> (B, R) { return self.bimap(f, identity) } public func rightMap(g : @escaping (R) -> D) -> (L, D) { return self.bimap(identity, g) } }
bsd-3-clause
c93a739babbbbec4355e02248131aaa9
23.541667
79
0.627617
2.90625
false
false
false
false
zning1994/practice
Swift学习/code4xcode6/ch11/11.4.2再谈:值类型和引用类型.playground/section-1.swift
1
1133
// 本书网站:http://www.51work6.com/swift.php // 智捷iOS课堂在线课堂:http://v.51work6.com // 智捷iOS课堂新浪微博:http://weibo.com/u/3215753973 // 智捷iOS课堂微信公共账号:智捷iOS课堂 // 作者微博:http://weibo.com/516inc // 官方csdn博客:http://blog.csdn.net/tonny_guan // Swift语言QQ讨论群:362298485 联系QQ:1575716557 邮箱:[email protected] class Employee { var no : Int = 0 var name : String = "" var job : String? var salary : Double = 0 var dept : Department? } struct Department { var no : Int = 0 var name : String = "" } var dept = Department() dept.no = 10 dept.name = "Sales" var emp = Employee() emp.no = 1000 emp.name = "Martin" emp.job = "Salesman" emp.salary = 1250 emp.dept = dept func updateDept (inout dept : Department) { dept.name = "Research" } println("Department更新前:\(dept.name)") updateDept(&dept) println("Department更新后:\(dept.name)") func updateEmp (emp : Employee) { emp.job = "Clerk" } println("Employee更新前:\(emp.job)") updateEmp(emp) println("Employee更新后:\(emp.job)")
gpl-2.0
b8b6cb1c46b31b89ff0a88b9046210c9
20.042553
62
0.665319
2.770308
false
false
false
false
ashfurrow/pragma-2015-rx-workshop
Session 4/Signup Demo/Pods/RxSwift/RxSwift/Event.swift
17
2335
// // Event.swift // Rx // // Created by Krunoslav Zaher on 2/8/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation /** Represents sequence event Sequence grammar: Next\* (Error | Completed) */ public enum Event<Element> : CustomStringConvertible { /** Next element is produced */ case Next(Element) /** Sequence terminates with error */ case Error(ErrorType) /** Sequence completes sucessfully */ case Completed /** - returns: Description of event */ public var description: String { get { switch self { case .Next(let value): return "Next(\(value))" case .Error(let error): return "Error(\(error))" case .Completed: return "Completed" } } } } /** Compares two events. They are equal if they are both the same member of `Event` enumeration. In case `Error` events are being compared, they are equal in case their `NSError` representations are equal (domain and code). */ public func == <T: Equatable>(lhs: Event<T>, rhs: Event<T>) -> Bool { switch (lhs, rhs) { case (.Completed, .Completed): return true case (.Error(let e1), .Error(let e2)): let error1 = e1 as NSError let error2 = e2 as NSError return error1.domain == error2.domain && error1.code == error2.code case (.Next(let v1), .Next(let v2)): return v1 == v2 default: return false } } extension Event { /** - returns: Is `Completed` or `Error` event */ public var isStopEvent: Bool { get { switch self { case .Next: return false case .Error, .Completed: return true } } } /** - returns: If `Next` event, returns element value. */ public var element: Element? { get { if case .Next(let value) = self { return value } return nil } } /** - returns: If `Error` event, returns error. */ public var error: ErrorType? { get { if case .Error(let error) = self { return error } return nil } } }
mit
e28f94fcdd76a950a8e8e45abaf4ccab
21.037736
126
0.529336
4.276557
false
false
false
false
OscarSwanros/swift
stdlib/public/SDK/Dispatch/Data.swift
2
14030
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// import _SwiftDispatchOverlayShims public struct DispatchData : RandomAccessCollection, _ObjectiveCBridgeable { public typealias Iterator = DispatchDataIterator public typealias Index = Int public typealias Indices = DefaultRandomAccessIndices<DispatchData> public static let empty: DispatchData = DispatchData(data: _swift_dispatch_data_empty()) public enum Deallocator { /// Use `free` case free /// Use `munmap` case unmap /// A custom deallocator case custom(DispatchQueue?, @convention(block) () -> Void) fileprivate var _deallocator: (DispatchQueue?, @convention(block) () -> Void) { switch self { case .free: return (nil, _swift_dispatch_data_destructor_free()) case .unmap: return (nil, _swift_dispatch_data_destructor_munmap()) case .custom(let q, let b): return (q, b) } } } fileprivate var __wrapped: __DispatchData /// Initialize a `Data` with copied memory content. /// /// - parameter bytes: A pointer to the memory. It will be copied. /// - parameter count: The number of bytes to copy. @available(swift, deprecated: 4, message: "Use init(bytes: UnsafeRawBufferPointer) instead") public init(bytes buffer: UnsafeBufferPointer<UInt8>) { __wrapped = buffer.baseAddress == nil ? _swift_dispatch_data_empty() : _swift_dispatch_data_create(buffer.baseAddress!, buffer.count, nil, _swift_dispatch_data_destructor_default()) as! __DispatchData } /// Initialize a `Data` with copied memory content. /// /// - parameter bytes: A pointer to the memory. It will be copied. /// - parameter count: The number of bytes to copy. public init(bytes buffer: UnsafeRawBufferPointer) { __wrapped = buffer.baseAddress == nil ? _swift_dispatch_data_empty() : _swift_dispatch_data_create(buffer.baseAddress!, buffer.count, nil, _swift_dispatch_data_destructor_default()) as! __DispatchData } /// Initialize a `Data` without copying the bytes. /// /// - parameter bytes: A pointer to the bytes. /// - parameter count: The size of the bytes. /// - parameter deallocator: Specifies the mechanism to free the indicated buffer. @available(swift, deprecated: 4, message: "Use init(bytesNoCopy: UnsafeRawBufferPointer, deallocater: Deallocator) instead") public init(bytesNoCopy bytes: UnsafeBufferPointer<UInt8>, deallocator: Deallocator = .free) { let (q, b) = deallocator._deallocator __wrapped = bytes.baseAddress == nil ? _swift_dispatch_data_empty() : _swift_dispatch_data_create(bytes.baseAddress!, bytes.count, q, b) as! __DispatchData } /// Initialize a `Data` without copying the bytes. /// /// - parameter bytes: A pointer to the bytes. /// - parameter count: The size of the bytes. /// - parameter deallocator: Specifies the mechanism to free the indicated buffer. public init(bytesNoCopy bytes: UnsafeRawBufferPointer, deallocator: Deallocator = .free) { let (q, b) = deallocator._deallocator __wrapped = bytes.baseAddress == nil ? _swift_dispatch_data_empty() : _swift_dispatch_data_create(bytes.baseAddress!, bytes.count, q, b) as! __DispatchData } internal init(data: __DispatchData) { __wrapped = data } public var count: Int { return __dispatch_data_get_size(__wrapped) } public func withUnsafeBytes<Result, ContentType>( body: (UnsafePointer<ContentType>) throws -> Result) rethrows -> Result { var ptr: UnsafeRawPointer? var size = 0 let data = __dispatch_data_create_map(__wrapped, &ptr, &size) let contentPtr = ptr!.bindMemory( to: ContentType.self, capacity: size / MemoryLayout<ContentType>.stride) defer { _fixLifetime(data) } return try body(contentPtr) } public func enumerateBytes( block: (_ buffer: UnsafeBufferPointer<UInt8>, _ byteIndex: Int, _ stop: inout Bool) -> Void) { _swift_dispatch_data_apply(__wrapped) { (_, offset: Int, ptr: UnsafeRawPointer, size: Int) in let bytePtr = ptr.bindMemory(to: UInt8.self, capacity: size) let bp = UnsafeBufferPointer(start: bytePtr, count: size) var stop = false block(bp, offset, &stop) return stop ? 0 : 1 } } /// Append bytes to the data. /// /// - parameter bytes: A pointer to the bytes to copy in to the data. /// - parameter count: The number of bytes to copy. @available(swift, deprecated: 4, message: "Use append(_: UnsafeRawBufferPointer) instead") public mutating func append(_ bytes: UnsafePointer<UInt8>, count: Int) { let data = _swift_dispatch_data_create(bytes, count, nil, _swift_dispatch_data_destructor_default()) as! __DispatchData self.append(DispatchData(data: data)) } /// Append bytes to the data. /// /// - parameter bytes: A pointer to the bytes to copy in to the data. /// - parameter count: The number of bytes to copy. public mutating func append(_ bytes: UnsafeRawBufferPointer) { // Nil base address does nothing. guard bytes.baseAddress != nil else { return } let data = _swift_dispatch_data_create(bytes.baseAddress!, bytes.count, nil, _swift_dispatch_data_destructor_default()) as! __DispatchData self.append(DispatchData(data: data)) } /// Append data to the data. /// /// - parameter data: The data to append to this data. public mutating func append(_ other: DispatchData) { let data = __dispatch_data_create_concat(__wrapped, other.__wrapped) __wrapped = data } /// Append a buffer of bytes to the data. /// /// - parameter buffer: The buffer of bytes to append. The size is calculated from `SourceType` and `buffer.count`. public mutating func append<SourceType>(_ buffer : UnsafeBufferPointer<SourceType>) { buffer.baseAddress!.withMemoryRebound(to: UInt8.self, capacity: buffer.count * MemoryLayout<SourceType>.stride) { self.append($0, count: buffer.count * MemoryLayout<SourceType>.stride) } } private func _copyBytesHelper(to pointer: UnsafeMutableRawPointer, from range: CountableRange<Index>) { var copiedCount = 0 if range.isEmpty { return } let rangeSize = range.count __dispatch_data_apply(__wrapped) { (_, offset: Int, ptr: UnsafeRawPointer, size: Int) in if offset >= range.endIndex { return false } // This region is after endIndex let copyOffset = range.startIndex > offset ? range.startIndex - offset : 0 // offset of first byte, in this region if copyOffset >= size { return true } // This region is before startIndex let count = Swift.min(rangeSize - copiedCount, size - copyOffset) memcpy(pointer + copiedCount, ptr + copyOffset, count) copiedCount += count return copiedCount < rangeSize } } /// Copy the contents of the data to a pointer. /// /// - parameter pointer: A pointer to the buffer you wish to copy the bytes into. /// - parameter count: The number of bytes to copy. /// - warning: This method does not verify that the contents at pointer have enough space to hold `count` bytes. @available(swift, deprecated: 4, message: "Use copyBytes(to: UnsafeMutableRawBufferPointer, count: Int) instead") public func copyBytes(to pointer: UnsafeMutablePointer<UInt8>, count: Int) { _copyBytesHelper(to: pointer, from: 0..<count) } /// Copy the contents of the data to a pointer. /// /// - parameter pointer: A pointer to the buffer you wish to copy the bytes into. The buffer must be large /// enough to hold `count` bytes. /// - parameter count: The number of bytes to copy. public func copyBytes(to pointer: UnsafeMutableRawBufferPointer, count: Int) { assert(count <= pointer.count, "Buffer too small to copy \(count) bytes") guard pointer.baseAddress != nil else { return } _copyBytesHelper(to: pointer.baseAddress!, from: 0..<count) } /// Copy a subset of the contents of the data to a pointer. /// /// - parameter pointer: A pointer to the buffer you wish to copy the bytes into. /// - parameter range: The range in the `Data` to copy. /// - warning: This method does not verify that the contents at pointer have enough space to hold the required number of bytes. @available(swift, deprecated: 4, message: "Use copyBytes(to: UnsafeMutableRawBufferPointer, from: CountableRange<Index>) instead") public func copyBytes(to pointer: UnsafeMutablePointer<UInt8>, from range: CountableRange<Index>) { _copyBytesHelper(to: pointer, from: range) } /// Copy a subset of the contents of the data to a pointer. /// /// - parameter pointer: A pointer to the buffer you wish to copy the bytes into. The buffer must be large /// enough to hold `count` bytes. /// - parameter range: The range in the `Data` to copy. public func copyBytes(to pointer: UnsafeMutableRawBufferPointer, from range: CountableRange<Index>) { assert(range.count <= pointer.count, "Buffer too small to copy \(range.count) bytes") guard pointer.baseAddress != nil else { return } _copyBytesHelper(to: pointer.baseAddress!, from: range) } /// Copy the contents of the data into a buffer. /// /// This function copies the bytes in `range` from the data into the buffer. If the count of the `range` is greater than `MemoryLayout<DestinationType>.stride * buffer.count` then the first N bytes will be copied into the buffer. /// - precondition: The range must be within the bounds of the data. Otherwise `fatalError` is called. /// - parameter buffer: A buffer to copy the data into. /// - parameter range: A range in the data to copy into the buffer. If the range is empty, this function will return 0 without copying anything. If the range is nil, as much data as will fit into `buffer` is copied. /// - returns: Number of bytes copied into the destination buffer. public func copyBytes<DestinationType>(to buffer: UnsafeMutableBufferPointer<DestinationType>, from range: CountableRange<Index>? = nil) -> Int { let cnt = count guard cnt > 0 else { return 0 } let copyRange : CountableRange<Index> if let r = range { guard !r.isEmpty else { return 0 } precondition(r.startIndex >= 0) precondition(r.startIndex < cnt, "The range is outside the bounds of the data") precondition(r.endIndex >= 0) precondition(r.endIndex <= cnt, "The range is outside the bounds of the data") copyRange = r.startIndex..<(r.startIndex + Swift.min(buffer.count * MemoryLayout<DestinationType>.stride, r.count)) } else { copyRange = 0..<Swift.min(buffer.count * MemoryLayout<DestinationType>.stride, cnt) } guard !copyRange.isEmpty else { return 0 } _copyBytesHelper(to: buffer.baseAddress!, from: copyRange) return copyRange.count } /// Sets or returns the byte at the specified index. public subscript(index: Index) -> UInt8 { var offset = 0 let subdata = __dispatch_data_copy_region(__wrapped, index, &offset) var ptr: UnsafeRawPointer? var size = 0 let map = __dispatch_data_create_map(subdata, &ptr, &size) defer { _fixLifetime(map) } return ptr!.load(fromByteOffset: index - offset, as: UInt8.self) } public subscript(bounds: Range<Int>) -> RandomAccessSlice<DispatchData> { return RandomAccessSlice(base: self, bounds: bounds) } /// Return a new copy of the data in a specified range. /// /// - parameter range: The range to copy. public func subdata(in range: CountableRange<Index>) -> DispatchData { let subrange = __dispatch_data_create_subrange( __wrapped, range.startIndex, range.endIndex - range.startIndex) return DispatchData(data: subrange) } public func region(location: Int) -> (data: DispatchData, offset: Int) { var offset: Int = 0 let data = __dispatch_data_copy_region(__wrapped, location, &offset) return (DispatchData(data: data), offset) } public var startIndex: Index { return 0 } public var endIndex: Index { return count } public func index(before i: Index) -> Index { return i - 1 } public func index(after i: Index) -> Index { return i + 1 } /// An iterator over the contents of the data. /// /// The iterator will increment byte-by-byte. public func makeIterator() -> DispatchData.Iterator { return DispatchDataIterator(_data: self) } } public struct DispatchDataIterator : IteratorProtocol, Sequence { public typealias Element = UInt8 /// Create an iterator over the given DispatchData public init(_data: DispatchData) { var ptr: UnsafeRawPointer? self._count = 0 self._data = __dispatch_data_create_map( _data as __DispatchData, &ptr, &self._count) self._ptr = ptr self._position = _data.startIndex // The only time we expect a 'nil' pointer is when the data is empty. assert(self._ptr != nil || self._count == self._position) } /// Advance to the next element and return it, or `nil` if no next /// element exists. public mutating func next() -> DispatchData.Element? { if _position == _count { return nil } let element = _ptr.load(fromByteOffset: _position, as: UInt8.self) _position = _position + 1 return element } internal let _data: __DispatchData internal var _ptr: UnsafeRawPointer! internal var _count: Int internal var _position: DispatchData.Index } extension DispatchData { @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> __DispatchData { return __wrapped } public static func _forceBridgeFromObjectiveC(_ input: __DispatchData, result: inout DispatchData?) { result = DispatchData(data: input) } public static func _conditionallyBridgeFromObjectiveC(_ input: __DispatchData, result: inout DispatchData?) -> Bool { result = DispatchData(data: input) return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: __DispatchData?) -> DispatchData { var result: DispatchData? _forceBridgeFromObjectiveC(source!, result: &result) return result! } }
apache-2.0
a957f3d2719143b2aa221e6d3a7c9423
38.857955
230
0.705346
3.853337
false
false
false
false
tempestrock/CarPlayer
CarPlayer/PlayerViewController.swift
1
41691
// // PlayerViewController.swift // CarPlayer // // Created by Peter Störmer on 27.11.14. // Copyright (c) 2014 Tempest Rock Studios. All rights reserved. // import UIKit import MediaPlayer import CoreLocation /* func handleTap(gesture: UITapGestureRecognizer) { let tapLocation = gesture.locationInView(bug.superview) if bug.layer.presentationLayer().frame.contains(tapLocation) { print("Bug tapped!") // add bug-squashing code here } else { print("Bug not tapped!") } } */ // // The PlayerViewController is the view that shows the "standard" playing of a song (the one without the map). // class PlayerViewController: UIViewController, UIGestureRecognizerDelegate { // ----- Attributes ----- @IBOutlet weak var _mainTapButton: UIButton! @IBOutlet weak var _albumCoverImage: UIImageView! @IBOutlet weak var _indexIndicator: UILabel! @IBOutlet weak var _trackListButton: UIButton! @IBOutlet weak var _lyricsButton: UIButton! // Speed display: var _speedLabel: UILabel! var _longLabel: UILabel! var _latLabel: UILabel! var _altLabel: UILabel! var _courseLabel: UILabel! var _courseArrow: UIImageView! var _crossLines: UIImageView! // A timer for the animation of longish labels: var _animationTimer: NSTimer! = nil // All you need for the artist label: var _artistLabel: UILabel! var _artistContainerView: UIView! var _artistLabelStartingFrame: CGRect! var _artistLabelNeedsAnimation: Bool = false var _speedDisplayModeButton: UIButton! = UIButton() // All you need for the album label: var _albumLabel: UILabel! var _albumContainerView: UIView! var _albumLabelStartingFrame: CGRect! var _albumLabelNeedsAnimation: Bool = false // The progress bar to watch the progress of a track playing and its timer for the updates: var _progressBar: UIProgressView! var _progressTimer: NSTimer // An array of buttons above the progress bar to switch manually to some place inside the track: var _sliderButton: [UIButtonWithFeatures]! = nil // Container for the animation of the track title: var _trackTitleLabel: UILabel! var _trackTitleContainerView: UIView! var _trackTitleLabelStartingFrame: CGRect! var _trackTitleLabelNeedsAnimation: Bool = false // A flag that says whether the user has switched the track by panning the track title: var _userSwitchedTrack: Bool // The previous translation factor during panning. Used to realize whether the panning stopped: var _previousTranslation: CGFloat // A function to call in order to set the background color of the speed view (if that view is active) var _speedViewBackgroundColorNotification: ((UIColor) -> Void)? = nil // ----- Constants ----- // z positions of view elements: let _zPosition_ArtistLabel: CGFloat = 0 let _zPosition_TrackTitleLabel: CGFloat = 0 let _zPosition_ProgressBar: CGFloat = 0 let _zPosition_SliderButtons: CGFloat = 1000 // ----- Methods ----- // // Initializing function. // required init?(coder aDecoder: NSCoder) { _progressTimer = NSTimer() _userSwitchedTrack = false _previousTranslation = 0.0 // Call superclass initializer: super.init(coder: aDecoder) } // init // // This function is called whenever the user reaches the player view. // override func viewDidLoad() { super.viewDidLoad() // DEBUG print("PlayerViewController.viewDidLoad()") // Tell the locator who to call: _locator.setNotifierFunction(self.updateSpeedDisplay) // Set notification handler for music changing in the background: _controller.setNotificationHandler(self, notificationFunctionName: #selector(PlayerViewController.updateDisplayedInformation)) // Set the progress timer to update the progress bar: _progressTimer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: #selector(PlayerViewController.updateProgressBar), userInfo: nil, repeats: true) // Create the speed display: createSpeedDisplay() if !_controller.thisWasADirectJump() && !_controller.albumAndArtistWerePreviouslySelected() { // The user intends to play a newly selected album. // Create the actual playlist that shall be played by the music player: _controller.createPlayListOfCurrentArtistAndAlbumIDs() // Start playing: _controller.playMusic() } else { // This was a direct jump to this view without selecting a new album. // Reset the according flag: _controller.resetFlagOfDirectJump() } // Create an initial progress bar: _progressBar = UIProgressView() view.addSubview(_progressBar) // Update the player directly without waiting for a notification in order to get around artifacts at first sight of the player view: updateDisplayedInformation() } // // This handler is called whenever this view becomes visible. // override func viewDidAppear(animated: Bool) { // Tell the controller about this: _controller.setCurrentlyVisibleView(self) } // // Updates all displayed information on the player view. // func updateDisplayedInformation() { // DEBUG print("PlayerViewController.updateDisplayedInformation()") // Set labels and enable or disable some buttons: setLabelsAndButtons() // Create a nicely colored background: createBackGround() // Set the buttons' positions according to the currently set speed display mode: createSliderButtons() updateSliderButtons() // Set the timer that animates longish labels if it is not already running: resetAnimationTimer() } // // Sets the basic labels and buttons on the view. // func setLabelsAndButtons() { // var nowPlayingItem = _controller.nowPlayingItem() // Reset and create the artist name display: createArtistDisplay() // Reset some flags and values: _userSwitchedTrack = false _previousTranslation = 0.0 // Reset and create the track title display: createTrackTitleDisplay() finalizePositionOfTrackTitle() // Show the artist and the track title in an animated fashion: showArtistAndTrackTitle() // Create all the album label stuff: createAlbumDisplay() // Take care of the index indicator in the top right corner: if _controller.currentNumberOfTracksIsKnown() { // Add the number of tracks: _indexIndicator.text = (_controller.indexOfNowPlayingItem()).description + " / " + (_controller.currentNumberOfTracks()).description // Enable the button for the track list: _trackListButton.hidden = false } else { // We have no track information => Do not show the track list indicators and button: _indexIndicator.text = "" _trackListButton.hidden = true } // Set the parameters for the progress bar: _progressBar.frame = MyBasics.PlayerView_FrameForProgressBar(_controller.speedDisplayMode()) _progressBar.trackTintColor = UIColor.darkGrayColor() _progressBar.tintColor = UIColor.whiteColor() _progressBar.alpha = 0.8 _progressBar.layer.zPosition = _zPosition_ProgressBar updateProgressBar() } // // Creates everything that has to do with displaying the artist name. If a former artist label existed, this is deleted first. // func createArtistDisplay() { let nowPlayingItem = _controller.nowPlayingItem() // Erase a possible previous version of the artist label: if _artistLabel != nil { _artistLabel.text = "" } // Create the artist label itself and place it into the container: _artistLabel = UILabel() _artistLabel.text = nowPlayingItem.artist _artistLabel.font = MyBasics.fontForLargeText _artistLabel.textColor = UIColor.whiteColor() _artistLabel.layer.zPosition = _zPosition_ArtistLabel _artistLabel.sizeToFit() _artistLabelStartingFrame = _artistLabel.frame // Embed the artist label into a container in order to animate the text if is too long to be displayed at once: // Create the container to put the artist label into: _artistContainerView = UIView(frame: MyBasics.PlayerView_FrameForArtistLabel(_controller.speedDisplayMode())) _artistContainerView.clipsToBounds = true _artistContainerView.alpha = 0.0 _artistContainerView.layer.zPosition = _zPosition_ArtistLabel // Assign views: _artistContainerView.addSubview(_artistLabel) view.addSubview(_artistContainerView) // Only do the animation if the text does not fit into the container: if _artistLabelStartingFrame.width > MyBasics.PlayerView_ArtistLabel_Width { // Add this label to the list of to-be-animated labels: _artistLabelNeedsAnimation = true } else { // The artist label fits into the space => Just do some alignment: _artistLabel.frame = CGRect(x: 0, y: 0, width: MyBasics.PlayerView_ArtistLabel_Width, height: _artistLabelStartingFrame.height) _artistLabel.textAlignment = NSTextAlignment.Right _artistLabelNeedsAnimation = false } // Buttons to switch between display modes: _speedDisplayModeButton.frame = _artistLabel.frame // DEBUG _speedDisplayModeButton.backgroundColor = UIColor.blackColor() // DEBUG _speedDisplayModeButton.alpha = 0.5 _speedDisplayModeButton.addTarget(self, action: #selector(PlayerViewController.speedButtonTapped), forControlEvents: .TouchUpInside) _speedDisplayModeButton.layer.zPosition = _zPosition_SliderButtons _artistContainerView.addSubview(_speedDisplayModeButton) } // // Creates everything that has to do with displaying the track title. If a former track title label existed, this is deleted first. // func createTrackTitleDisplay() { // DEBUG print("PlayerViewController.createTrackTitleDisplay()") let nowPlayingItem = _controller.nowPlayingItem() // Erase a possible previous version of the track title label: if _trackTitleLabel != nil { _trackTitleLabel.text = "" } // Create the track title label itself and place it into the container: _trackTitleLabel = UILabel() _trackTitleLabel.text = nowPlayingItem.title _trackTitleLabel.font = MyBasics.fontForLargeText _trackTitleLabel.textColor = UIColor.whiteColor() _trackTitleLabel.layer.zPosition = _zPosition_TrackTitleLabel _trackTitleLabel.sizeToFit() _trackTitleLabelStartingFrame = _trackTitleLabel.frame // Create the container to put the artist label into: if _trackTitleContainerView == nil { _trackTitleContainerView = UIView() view.addSubview(_trackTitleContainerView) } // Hide the title initially: _trackTitleContainerView.alpha = 0.0 _trackTitleContainerView.clipsToBounds = true _trackTitleContainerView.layer.zPosition = _zPosition_TrackTitleLabel _trackTitleContainerView.addSubview(_trackTitleLabel) // Only do the animation if the text does not fit into the container: if _trackTitleLabelStartingFrame.width > MyBasics.PlayerView_TrackTitleLabel_Width(_controller.speedDisplayMode()) { // The text is too large to fit into the container. // Add this label to the list of to-be-animated labels: _trackTitleLabelNeedsAnimation = true } else { // The artist label fits into the space => Just do some alignment: _trackTitleLabel.frame = CGRect(x: 0, y: 0, width: MyBasics.PlayerView_TrackTitleLabel_Width(_controller.speedDisplayMode()), height: _trackTitleLabelStartingFrame.height) _trackTitleLabel.textAlignment = NSTextAlignment.Right _trackTitleLabelNeedsAnimation = false } } // // Sets the track title container's final position and size. // func finalizePositionOfTrackTitle() { _trackTitleContainerView.frame = MyBasics.PlayerView_FrameForTrackTitle(_controller.speedDisplayMode()) // Add the pan gesture recognizer for the switching to the next track if we have more than one track: if !_controller.currentNumberOfTracksIsKnown() || _controller.currentNumberOfTracks() > 1 { let panGesture = UIPanGestureRecognizer(target: self, action: #selector(PlayerViewController.trackTitleLabelPanned(_:))) panGesture.delegate = self _trackTitleContainerView.addGestureRecognizer(panGesture) } } // // Shows the artist and the track title by a quick animation. // func showArtistAndTrackTitle() { // Show both titles slowly: let durationForOneDirection: NSTimeInterval = 0.6 UIView.animateWithDuration( durationForOneDirection, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: { self._artistContainerView.alpha = 1.0 self._trackTitleContainerView.alpha = 1.0 }, completion: nil ) } // // Creates the album label and the container around it. // func createAlbumDisplay() { // DEBUG print("PlayerViewController.createAlbumDisplay()") let nowPlayingItem = _controller.nowPlayingItem() // Erase a possible previous version of the album label: if _albumLabel != nil { _albumLabel.text = "" } // Create the album label itself and place it into the container: _albumLabel = UILabel() _albumLabel.text = nowPlayingItem.albumTitle _albumLabel.font = MyBasics.fontForSmallText _albumLabel.textColor = UIColor.whiteColor() _albumLabel.sizeToFit() _albumLabelStartingFrame = _albumLabel.frame // Embed the album label into a container in order to animate the text if is too long to be displayed at once: // Create the container to put the album label into: _albumContainerView = UIView(frame: MyBasics.PlayerView_FrameForAlbumLabel) _albumContainerView.clipsToBounds = true // Assign views: _albumContainerView.addSubview(_albumLabel) view.addSubview(_albumContainerView) // Only do the animation if the text does not fit into the container: if _albumLabelStartingFrame.width > MyBasics.PlayerView_AlbumLabel_Width { // Add this label to the list of to-be-animated labels: _albumLabelNeedsAnimation = true } else { // The album label fits into the space => Just do some alignment: _albumLabel.frame = CGRect(x: 0, y: 0, width: MyBasics.PlayerView_AlbumLabel_Width, height: _albumLabelStartingFrame.height) _albumLabel.textAlignment = NSTextAlignment.Center _albumLabelNeedsAnimation = false } } // // Updates the progress bar according to the current playback time in relation to the complete time of the current track. // func updateProgressBar() { // DEBUG print("PlayerViewController.updateProgressBar()") // DEBUG _controller.printMusicPlayerPlaybackState(addInfo: "updateProgressBar()") // Show current playback progress: _progressBar.progress = Float(_controller.progressOfCurrentlyPlayingTrack()) } // // This method is called when the timer for the animation of the longish labels is fired. // func animationTimerFired() { // DEBUG print("PlayerViewController.animationTimerFired()") // Reset the timer that animates longish labels if it is not already running: _animationTimer = NSTimer.scheduledTimerWithTimeInterval( MyBasics.PlayerView_TimeForAnimation + MyBasics.PlayerView_TimeForToWaitForNextAnimation * 2, target: self, selector: #selector(PlayerViewController.animationTimerFired), userInfo: nil, repeats: false) if _artistLabelNeedsAnimation { UIView.animateLongishLabel( _artistLabel, frameAroundLabel: _artistLabelStartingFrame, timeForAnimation: MyBasics.PlayerView_TimeForAnimation, timeToWaitForNextAnimation: MyBasics.PlayerView_TimeForToWaitForNextAnimation, totalWidth: MyBasics.PlayerView_ArtistLabel_Width ) } if _trackTitleLabelNeedsAnimation { UIView.animateLongishLabel( _trackTitleLabel, frameAroundLabel: _trackTitleLabelStartingFrame, timeForAnimation: MyBasics.PlayerView_TimeForAnimation, timeToWaitForNextAnimation: MyBasics.PlayerView_TimeForToWaitForNextAnimation, totalWidth: MyBasics.PlayerView_TrackTitleLabel_Width(_controller.speedDisplayMode()) ) } if _albumLabelNeedsAnimation { UIView.animateLongishLabel( _albumLabel, frameAroundLabel: _albumLabelStartingFrame, timeForAnimation: MyBasics.PlayerView_TimeForAnimation, timeToWaitForNextAnimation: MyBasics.PlayerView_TimeForToWaitForNextAnimation, totalWidth: MyBasics.PlayerView_AlbumLabel_Width ) } } // // Creates a nice background that takes into account the average color of the artwork of the track. // func createBackGround() { let nowPlayingItem = _controller.nowPlayingItem() if nowPlayingItem.artwork == nil { // No artwork => Set black background color and leave: view.backgroundColor = UIColor.randomDarkColor() return } // We have an artwork. // Set the artist image in the top left corner: let sizeOfArtistImage = CGSize(width: MyBasics.PlayerView_ArtistImage_Width, height: MyBasics.PlayerView_ArtistImage_Height) _albumCoverImage.image = nowPlayingItem.artwork!.imageWithSize(sizeOfArtistImage) // Create a background color that is similar to the average of the artwork color. let sizeOfView = CGSize(width: MyBasics.screenWidth, height: MyBasics.screenHeight) let artworkImage: UIImage? = nowPlayingItem.artwork!.imageWithSize(sizeOfView) // Setup context with the given size: let onePixelSize = CGSize(width: 1, height: 1) UIGraphicsBeginImageContext(onePixelSize) // let context = UIGraphicsGetCurrentContext() // Scale the artwork image down to one pixel, thereby generating an average color over the whole image: artworkImage!.drawInRect(CGRectMake(0, 0, 1, 1)) // Drawing complete, retrieve the finished image and cleanup let imageWithOneColor: UIImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() // Find out the newly generated color: let backColor = imageWithOneColor.getPixelColor(CGPointMake(0, 0)) // Get the "lightness factor" out of the current background color: let lightnessFactor = backColor.lightnessFactor() // DEBUG print("color = \(backColor), lightnessFactor = \(lightnessFactor)") if lightnessFactor > 0.0 { // The new color is too light for the background, yet. Darken it a bit. // Create a Core Image context let params: [ String : AnyObject ] = [ kCIContextUseSoftwareRenderer : true ] let ciContext = CIContext(options: params) // Darken the image: let inputCiImage = CIImage(image: imageWithOneColor) let darkenFilter = CIFilter(name: "CIColorControls") darkenFilter!.setValue(inputCiImage, forKey: kCIInputImageKey) darkenFilter!.setValue(-1.0 * lightnessFactor, forKey: kCIInputBrightnessKey) // kCIInputSaturationKey let darkenedImageData = darkenFilter!.valueForKey(kCIOutputImageKey) as! CIImage let darkenedImageRef = ciContext.createCGImage(darkenedImageData, fromRect: darkenedImageData.extent) let finalImageForBackground = UIImage(CGImage: darkenedImageRef) // Now the background color is dark enough to be used. view.backgroundColor = UIColor(patternImage: finalImageForBackground) } else { // The background color is dark enough to be directly used. view.backgroundColor = UIColor(patternImage: imageWithOneColor) } // Also update the speed view's background if it is currently active: if _speedViewBackgroundColorNotification != nil { _speedViewBackgroundColorNotification!(view.backgroundColor!) } } // // Creates those buttons that lie above the progress bar in order for the user to advance in the track. // func createSliderButtons() { // DEBUG print("PlayerViewController.createSliderButtons()") // Define the number of slider buttons: let numberOfButtons: Int = 50 // Remove possibly previously existing buttons (this is necessary due to a bug somewhere): if _sliderButton != nil { // DEBUG print(" Removing previous buttons.") // Remove previous buttons first: for button in _sliderButton { button.removeFromSuperview() } } // Initialize the array of buttons: _sliderButton = [UIButtonWithFeatures]() for index in 0 ..< numberOfButtons { // Create a new button: let button = UIButtonWithFeatures(type: UIButtonType.Custom) // DEBUG button.backgroundColor = UIColor.blackColor() // DEBUG button.alpha = 0.5 button.addTarget(self, action: #selector(PlayerViewController.sliderButtonTapped(_:)), forControlEvents: .TouchDown) button.setPosition(Double(index) / Double(numberOfButtons)) button.layer.zPosition = _zPosition_SliderButtons // Add the new button to the array of slider buttons: _sliderButton.append(button) // Add the new button to the view: view.addSubview(button) } } // // Repositions the slider buttons according the the current speed display mode. // func updateSliderButtons() { // DEBUG print("PlayerViewController.updateSliderButtons() with speed display mode \(_controller.speedDisplayMode())") let xStartPos: CGFloat = MyBasics.PlayerView_SliderButtons_XStartPos(_controller.speedDisplayMode()) let yPos: CGFloat = MyBasics.PlayerView_SliderButtons_YPos(_controller.speedDisplayMode()) let sliderWidth: CGFloat = MyBasics.PlayerView_SliderButtons_SliderWidth(_controller.speedDisplayMode()) let buttonHeight: CGFloat = MyBasics.PlayerView_SliderButtons_ButtonHeight let numberOfButtons: Int = _sliderButton.count let buttonWidth: CGFloat = sliderWidth / CGFloat(numberOfButtons) var index: Int = 0 for button in _sliderButton { // Calculate x position of the button: let xPos: CGFloat = xStartPos + (sliderWidth * CGFloat(index) / CGFloat(numberOfButtons)) button.frame = CGRect(x: xPos, y: yPos - buttonHeight/2, width: buttonWidth, height: buttonHeight) index += 1 } } // // Resets the timer for the animation of longish labels. // func resetAnimationTimer() { stopAnimationTimer() _animationTimer = NSTimer.scheduledTimerWithTimeInterval( MyBasics.PlayerView_TimeForToWaitForNextAnimation, target: self, selector: #selector(PlayerViewController.animationTimerFired), userInfo: nil, repeats: false) } // // Handles the panning events for the switch to the previous or the next track. // func trackTitleLabelPanned(recognizer: UIPanGestureRecognizer) { // Ignore the panning events if we are already in the switching process: if _userSwitchedTrack { return } // Get the translation data from the recognizer, i.e. the position of the panning finger in x direction: var translation: CGFloat = recognizer.translationInView(self.view).x // DEBUG print("translation: \(translation)") // We know that the view we are looking at is the track title: let pannedView = recognizer.view! if translation == _previousTranslation { // DEBUG print("panning stopped -> back to normal size") // This is the signal that the user stopped panning. // => Scale the title back to the normal size: UIView.animateWithDuration( 0.4, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: { pannedView.alpha = 1.0 self._artistContainerView.alpha = 1.0 }, completion: nil ) // Reset the "previous translation" memory: _previousTranslation = 0.0 return } // Store the translation value for later comparison: _previousTranslation = translation // Define the panning direction: let skippingDirection: MusicSkippingDirection = (translation < 0 ? .Next : .Previous) if skippingDirection == MusicSkippingDirection.Previous { // This is a panning to the right. // Make the translation value negative: translation = -translation } // Define the scale factor for the actual scaling: let scaleFactor: CGFloat = 1.0 + translation / CGFloat(MyBasics.PlayerView_ArtistLabel_Width / 2) // DEBUG print("scaleFactor: \(scaleFactor)") // Scale the track title to the necessary format: pannedView.alpha = scaleFactor _artistContainerView.alpha = scaleFactor // Define the threshold that needs to be reached in order to start the switch to the next track: let scaleThreshold: CGFloat = 0.2 if scaleFactor < scaleThreshold { // DEBUG print("threshold reached") // We have reached a threshold that says that the user really wants to switch the track. _userSwitchedTrack = true // Now do the rest animatedly: let durationForOneDirection: NSTimeInterval = 0.5 UIView.animateWithDuration( durationForOneDirection, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: { pannedView.alpha = 0.0 self._artistContainerView.alpha = 0.0 }, completion: { finished in self.stopAnimationTimer() if skippingDirection == MusicSkippingDirection.Next { _controller.skipToNextItem() } else { _controller.skipToPreviousItem() } } ) } } // // Creates the "speed display" that shows the whole navigation stuff at the bottom of the page. // func createSpeedDisplay() { // let fullWidth: CGFloat = CGFloat(MyBasics.screenWidth) let speedLabelWidth: CGFloat = MyBasics.PlayerView_ArtistImage_Width let xPosGap: CGFloat = CGFloat(MyBasics.PlayerView_ArtistLabel_Width) / 4 let labelWidth: CGFloat = xPosGap let labelHeight: CGFloat = CGFloat(MyBasics.screenHeight) - MyBasics.PlayerView_speed_yPos // Speed label: _speedLabel = UILabel() _speedLabel.frame = CGRectMake(0, MyBasics.PlayerView_speed_yPos, speedLabelWidth, labelHeight) _speedLabel.font = MyBasics.fontForLargeText _speedLabel.textAlignment = NSTextAlignment.Center _speedLabel.textColor = UIColor.whiteColor() view.addSubview(_speedLabel) var curXPos: CGFloat = MyBasics.PlayerView_ArtistLabel_XPos // Longitude and latitude labels: _latLabel = UILabel() _latLabel.frame = CGRectMake(curXPos, MyBasics.PlayerView_speed_yPos, 2*labelWidth, labelHeight / 2) _latLabel.font = MyBasics.fontForMediumText _latLabel.textColor = UIColor.whiteColor() view.addSubview(_latLabel) _longLabel = UILabel() _longLabel.frame = CGRectMake(curXPos, MyBasics.PlayerView_speed_yPos + labelHeight/2, 2*labelWidth, labelHeight / 2) _longLabel.font = MyBasics.fontForMediumText _longLabel.textColor = UIColor.whiteColor() view.addSubview(_longLabel) curXPos += (2*xPosGap) // Altitude: _altLabel = UILabel() _altLabel.frame = CGRectMake(curXPos, MyBasics.PlayerView_speed_yPos, labelWidth, labelHeight) _altLabel.font = MyBasics.fontForMediumText _altLabel.textAlignment = NSTextAlignment.Center _altLabel.textColor = UIColor.whiteColor() view.addSubview(_altLabel) curXPos += xPosGap // Course: _courseLabel = UILabel() _courseLabel.frame = CGRectMake(curXPos-2, CGFloat(MyBasics.screenHeight) - (labelHeight * 3/4) + 5, labelWidth, labelHeight) _courseLabel.font = MyBasics.fontForSmallThinText _courseLabel.textAlignment = NSTextAlignment.Center _courseLabel.textColor = UIColor.whiteColor() view.addSubview(_courseLabel) _courseArrow = UIImageView(image: UIImage(named: "arrow.png")) _courseArrow.frame = CGRectMake(curXPos+20, MyBasics.PlayerView_speed_yPos+15, labelHeight / 2, labelHeight / 2) _courseArrow.alpha = 0.0 _crossLines = UIImageView(image: UIImage(named: "crosslines.png")) _crossLines.frame = CGRectMake(curXPos+20, MyBasics.PlayerView_speed_yPos+15, labelHeight / 2, labelHeight / 2) _crossLines.alpha = 0.0 view.addSubview(_courseArrow) view.addSubview(_crossLines) } // // Handles the case that the speed button has been tapped by the user. // Switched the view mode of the speed display. // func speedButtonTapped() { // Advance the speed display mode: _controller.advanceSpeedDisplayMode() moveLabels() // Set some initial values before the updates from the locator arrive: switch _controller.speedDisplayMode() { case 0: // of _speedLabel.text = "" _latLabel.text = "" _longLabel.text = "" _altLabel.text = "" _courseLabel.text = "" _courseArrow.alpha = 0.0 // invisible _crossLines.alpha = 0.0 // invisible case 1: // speed only _speedLabel.text = Locator.defaultSpeedString _latLabel.text = "" _longLabel.text = "" _altLabel.text = "" _courseLabel.text = "" _courseArrow.alpha = 0.0 // invisible _crossLines.alpha = 0.0 // invisible case 2: // all _latLabel.text = _locator.defaultLatitude() _longLabel.text = _locator.defaultLongitude() _altLabel.text = _locator.defaultAltitude() _courseLabel.text = _locator.defaultCourse() _courseArrow.alpha = 0.0 // invisible _crossLines.alpha = 1.0 // visible default: assert(false, "PlayerViewController.speedButtonTapped(): Reached illegal value \(_controller.speedDisplayMode())") } } // // Moves the labels to the currently reasonable position, depending on the speedDisplayMode. // func moveLabels() { // DEBUG print("PlayerViewController.moveLabels()") let delayForArtist: [Double] = [ 0.1, 0.0, 0.0 ] let delayForProgressBar: Double = 0.05 let delayForTrackTitle: [Double] = [ 0.0, 0.0, 0.1 ] // Re-create the label animation for the track title label: createTrackTitleDisplay() // Show the artist and the track title in an animated fashion: showArtistAndTrackTitle() UIView.jumpSpringyToPosition(_artistContainerView, delay: delayForArtist[_controller.speedDisplayMode()], frameToJumpTo: MyBasics.PlayerView_FrameForArtistLabel(_controller.speedDisplayMode())) UIView.jumpSpringyToPosition(_progressBar, delay: delayForProgressBar, frameToJumpTo: MyBasics.PlayerView_FrameForProgressBar(_controller.speedDisplayMode())) UIView.jumpSpringyToPosition( _trackTitleContainerView, delay: delayForTrackTitle[_controller.speedDisplayMode()], frameToJumpTo: MyBasics.PlayerView_FrameForTrackTitle(_controller.speedDisplayMode()), completion: { finished in self.finalizePositionOfTrackTitle() } ) // Update also the slider buttons above the progress bar: createSliderButtons() updateSliderButtons() if (_trackTitleLabelNeedsAnimation && !_albumLabelNeedsAnimation && !_artistLabelNeedsAnimation) { // The track title label is the only animated label. // => Start the animation after this move immediately: resetAnimationTimer() } } // // Is called when the locator has new data. // func updateSpeedDisplay(speed: Int, lat: String, long: String, alt: String, courseStr: String, course: Double, _: CLLocationCoordinate2D) { switch _controller.speedDisplayMode() { case 0: _speedLabel.text = "" _latLabel.text = "" _longLabel.text = "" _altLabel.text = "" _courseLabel.text = "" _courseArrow.alpha = 0.0 // invisible _crossLines.alpha = 0.0 // invisible case 1: _speedLabel.text = (speed != Locator.defaultSpeed ? speed.description : Locator.defaultSpeedString) _latLabel.text = "" _longLabel.text = "" _altLabel.text = "" _courseLabel.text = "" _courseArrow.alpha = 0.0 // invisible _crossLines.alpha = 0.0 // invisible case 2: _speedLabel.text = (speed != Locator.defaultSpeed ? speed.description : Locator.defaultSpeedString) _latLabel.text = lat _longLabel.text = long _altLabel.text = alt _courseLabel.text = courseStr _crossLines.alpha = 1.0 // visible if course >= 0 { _courseArrow.alpha = 1.0 UIView.animateWithDuration(0.5, animations: { self._courseArrow.transform = CGAffineTransformMakeRotation(2*CGFloat(M_PI) * (CGFloat(course)/360)) }) } else { // Invalid course => make arrow invisible _courseArrow.alpha = 0.0 } default: assert(true, "PlayerViewController.updateSpeedDisplay(): Reached illegal value \(_controller.speedDisplayMode())") } } // // Handles the event of the button above the album image being tapped. // Opens a modal view and show the complete list of tracks in the playlist. // @IBAction func trackListButtonTapped(sender: UIButton) { let tracklistView = TracklistViewController() tracklistView.modalPresentationStyle = UIModalPresentationStyle.OverCurrentContext tracklistView.modalTransitionStyle = UIModalTransitionStyle.CoverVertical UIView.animateSlightShrink( _indexIndicator, completion: { finished in self.presentViewController(tracklistView, animated: true, completion: nil) }) } // // Handles the event of the lyrics button above the album image being tapped. // Opens a modal view showing the lyrics if they exist. // @IBAction func lyricsButtonTapped(sender: UIButton) { let lyricsView = LyricsViewController() lyricsView.modalPresentationStyle = UIModalPresentationStyle.OverCurrentContext lyricsView.modalTransitionStyle = UIModalTransitionStyle.CoverVertical UIView.animateSlightShrink( _albumCoverImage, completion: { finished in self.presentViewController(lyricsView, animated: true, completion: nil) }) } // // Handles the event of a slider button being tapped. // Skips the track to the button's position. // func sliderButtonTapped(sender: UIButtonWithFeatures) { // DEBUG print("PlayerViewController.sliderButtonTapped()") // DEBUG print(" Sender's position: \(sender.position())") // Animate the new progress bar: UIView.animateSlightGrowthInYDir( _progressBar, completion: { finished in // Set the current track to the defined position. // The parameter must be between 0.0 and 1.0. _controller.setCurrentTrackPosition(sender.position()) } ) } // // Handles the button event which starts and pauses the player. // @IBAction func startAndPauseButtonTapped(sender: UIButton) { UIView.animateTinyShrink(self.view, completion: nil) _controller.togglePlaying() } // // This method is called when we are coming back from the speed view. // @IBAction func unwindToViewController (sender: UIStoryboardSegue){ // DEBUG print("PlayerViewController.unwindToViewController()") // Tell the locator again to call our notifier function as this was changed by the speed view: _locator.setNotifierFunction(self.updateSpeedDisplay) // Deactivate the background color notification: _speedViewBackgroundColorNotification = nil } // // This handler switches over to the speed view whenever the user swipes up. // @IBAction func userHasSwipedUp(sender: UISwipeGestureRecognizer) { // DEBUG print("PlayerViewController.userHasSwipedUp()") performSegueWithIdentifier(MyBasics.nameOfSegue_playerToSpeed, sender: self) } // // This function is called shortly before we switch back to one of the calling views. // override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // DEBUG print("PlayerViewController.prepareForSegue()") // DEBUG print("PlayerView --> \(segue.destinationViewController.title!!)") if segue.destinationViewController.title! != MyBasics.nameOfSpeedView { // This is a seque that either goes to the album or the main view. // We do not need the running timers anymore: // DEBUG print("PlayerViewController.prepareForSegue(): stopping all timers.") stopAllTimers() } else { // We are switching to the speed view. // Tell the speed view which background color to take and keep the background color setter in mind for later updates: let speedView = segue.destinationViewController as! SpeedViewController _speedViewBackgroundColorNotification = speedView.setBackgroundColor _speedViewBackgroundColorNotification!(view.backgroundColor!) // Animate the transition from this view to the speed view and tell the speed view which swipe leads back to this view: _slidingTransition.setDirectionToStartWith(TransitionManager_Sliding.DirectionToStartWith.Up) speedView.setDirectionToSwipeBack(SpeedViewController.DirectionToSwipeBack.Down) speedView.transitioningDelegate = _slidingTransition } } // // Handles the users pinching which changes the brightness of the screen. // @IBAction func userHasPinched(sender: UIPinchGestureRecognizer) { // DEBUG print("PlayerControllerView.userHasPinched()") _controller.setBrightness(sender.scale) } // // Stops all running timers. // func stopAllTimers() { if _progressTimer.valid { _progressTimer.invalidate() // DEBUG print("_progressTimer stopped.") } stopAnimationTimer() } // // Stops the timer for the text animation. // func stopAnimationTimer() { if (_animationTimer != nil) && _animationTimer.valid { _animationTimer.invalidate() _animationTimer = nil // DEBUG print("Animation timer stopped.") } } }
gpl-3.0
1e8104ccc696231c77e63eee4dd5ec57
35.828622
166
0.641785
5.07981
false
false
false
false
aatalyk/swift-algorithm-club
Shell Sort/shellsort.swift
12
1732
// The MIT License (MIT) // Copyright (c) 2016 Mike Taghavi (mitghi[at]me.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. public func insertionSort(_ list: inout [Int], start: Int, gap: Int) { for i in stride(from: (start + gap), to: list.count, by: gap) { let currentValue = list[i] var pos = i while pos >= gap && list[pos - gap] > currentValue { list[pos] = list[pos - gap] pos -= gap } list[pos] = currentValue } } public func shellSort(_ list: inout [Int]) { var sublistCount = list.count / 2 while sublistCount > 0 { for pos in 0..<sublistCount { insertionSort(&list, start: pos, gap: sublistCount) } sublistCount = sublistCount / 2 } }
mit
1a39270ac28d7dd777444883df8a3581
39.27907
81
0.710739
4.12381
false
false
false
false
Cookiezby/YiIndex
YiIndex/Util/YiIndex.swift
1
12798
// // YiIndex.swift // YiIndex // // Created by cookie on 23/07/2017. // Copyright © 2017 cookie. All rights reserved. // import Foundation import UIKit class YiIndex { var originalStr: [String]! var processedStr: [String]! var level: Int = 0 var tree: TreeNode! var sameCountList: [Int]! var indexList: [IndexPath]! var indexDict: [String: IndexPath]! var dataSource:[[String]] = { var data = [[String]]() for i in 0 ..< 26 { data.append([String]()) } return data }() var sectionHeader = [String]() init(originalStr: [String], level:Int) { self.originalStr = originalStr self.processedStr = StringUtil.strListToUppercaseLetters(data: originalStr, level: level) self.level = level let (tempTree, tempList) = YiIndexUtil.createTree(data: self.processedStr) self.tree = tempTree YiIndexUtil.update(tree: tree) self.sameCountList = tempList! createIndexPath() createDataSource() } func insert(str: String) { let proStr = StringUtil.strToUppercaseLetters(str: str, level: level) let sameCount = YiIndexUtil.insertStr(root: tree, str: proStr) originalStr.append(str) processedStr.append(proStr) sameCountList.append(sameCount) YiIndexUtil.update(tree: tree) createIndexPath() } func createDataSource() { for i in 0 ..< indexList.count { let index = indexList[i] let section = index.section let row = index.row dataSource[section][row] = originalStr[i] } dataSource = dataSource.filter({ (value) -> Bool in return value.count != 0 }) for section in dataSource { let first = section[0] let header = StringUtil.strToUppercaseLetters(str: first, level: 1) sectionHeader.append(header) } } func delete(index: Int) { guard index < originalStr.count else{ return } let proStr = processedStr[index] originalStr.remove(at: index) processedStr.remove(at: index) sameCountList.removeAll() YiIndexUtil.deleteStr(tree: tree, str: proStr) tree.removeEmptyBarnch() YiIndexUtil.update(tree: tree) for i in 0 ..< processedStr.count { sameCountList.append(YiIndexUtil.updateSameCount(tree: tree, str: processedStr[i])) } createIndexPath() } func createIndexPath(){ indexList = [IndexPath]() indexDict = [String: IndexPath]() for i in 0 ..< originalStr.count { let index = YiIndexUtil.createIndex(tree: tree, str: processedStr[i], sameCount: sameCountList[i]) indexList.append(index) let section = index.section dataSource[section].append("") indexDict[processedStr[i]] = index for j in 0 ..< level { let startIndex = processedStr[i].startIndex let endIndex = processedStr[i].index(startIndex, offsetBy: j) let str = processedStr[i][startIndex ... endIndex] if let currIndex = indexDict[str] { if (currIndex.row < index.row){ indexDict[str] = currIndex } }else{ indexDict[str] = index } } } } } class TreeNode { var value: Character var uniValue: UInt32 weak var parent: TreeNode? var children: [TreeNode] = [] var isLeaf: Bool = false var sameCount = 0 var childLeafCount = 0 // the amount of leaf under this node var preChildLeafCount = 0 // the amount of node on the left init(value: Character) { self.value = value let uni = String(value).unicodeScalars self.uniValue = uni[uni.startIndex].value } func addChild(_ child: TreeNode, isLeaf: Bool) -> Int? { if children.count == 0 { children.append(child) child.parent = self if (isLeaf) { let result = child.sameCount child.sameCount += 1 child.updateChildLeafCount(1) child.childLeafCount += 1 return result } return nil }else{ for i in 0 ..< children.count { if (child.uniValue == children[i].uniValue) { if (isLeaf) { let result = children[i].sameCount children[i].sameCount += 1 children[i].childLeafCount += 1 children[i].updateChildLeafCount(1) return result } break }else if (child.uniValue < children[i].uniValue) { children.insert(child, at: i) child.parent = self if (isLeaf) { let result = child.sameCount child.sameCount += 1 child.updateChildLeafCount(1) child.childLeafCount += 1 return result } break }else if (i == children.count - 1) { children.append(child) child.parent = self if (isLeaf){ let result = child.sameCount child.sameCount += 1 child.updateChildLeafCount(1) child.childLeafCount += 1 return result } break } } return nil } } // FIXME: need to check func removeChild(_ child: TreeNode) { if (children.count > 1) { for i in 0 ..< children.count { if (child.uniValue == children[i].uniValue) { for j in i+1 ..< children.count { children[j].preChildLeafCount -= 1 } if (children[i].isLeaf) { children[i].updateChildLeafCount(-1) if (children[i].sameCount > 1) { children[i].sameCount -= 1 children[i].childLeafCount -= 1 } } break } } }else if(children.count == 1){ if (children[0].isLeaf) { children[0].updateChildLeafCount(-1) if (children[0].sameCount > 1){ children[0].sameCount -= 1 children[0].childLeafCount -= 1 } } }else{ // will never happen } } func removeEmptyBarnch() { for i in 0 ..< children.count { if (children[i].childLeafCount == 0) { children.remove(at: i) return }else{ children[i].removeEmptyBarnch() } } } // from the child node, update the childLeafCount until the root of tree func updateChildLeafCount(_ value: Int) { guard parent != nil else{ return } parent?.childLeafCount += value parent?.updateChildLeafCount(value) } } class YiIndexUtil { // childLeafCount is the amount of all leaf before current node static func createTree(data: [String]) -> (tree: TreeNode?, sameIndex: [Int]?) { guard data.count > 0 else { return (nil, nil) } let level = data[0].characters.count let root = TreeNode(value: Character("0")) var sameIndex = [Int]() for i in 0 ..< level { for str in data { let char = str[str.index(str.startIndex, offsetBy: i)] let node = TreeNode(value: char) var parent:TreeNode! // sarch for parent node if (i == 0) { parent = root }else{ parent = root for j in 0 ..< i { for child in parent.children { if child.value == str[str.index(str.startIndex, offsetBy: j)] { parent = child } } } } if (i < level - 1) { _ = parent.addChild(node, isLeaf: false) }else if ( i == level - 1) { node.isLeaf = true let count = parent.addChild(node, isLeaf: true)! sameIndex.append(count) } } } return (root, sameIndex) } // insert a str to the IndexTree // return the sameCount for this str static func insertStr(root: TreeNode, str: String) -> Int{ let level = str.characters.count var sameCount = 0 for i in 0 ..< level { let char = str[str.index(str.startIndex, offsetBy: i)] let node = TreeNode(value: char) var parent:TreeNode! // sarch for parent node if (i == 0) { parent = root }else{ parent = root for j in 0 ..< i { for child in parent.children { if child.value == str[str.index(str.startIndex, offsetBy: j)] { parent = child } } } } if (i < level - 1) { _ = parent.addChild(node, isLeaf: false) }else if ( i == level - 1) { node.isLeaf = true let count = parent.addChild(node, isLeaf: true)! sameCount = count } } return sameCount } static func deleteStr(tree: TreeNode, str: String) { let level = str.characters.count // sarch for parent node var root = tree for i in 0 ..< level { let char = str[str.index(str.startIndex, offsetBy: i)] for child in root.children { if child.value == char { root = child } } if (i == level - 1){ let node = TreeNode(value: char) root.parent?.removeChild(node) } } } // update the childLeafCount for the tree // the childLeafCount means how many leafs do this node have static func update(tree: TreeNode) { if (tree.children.count < 1) { return } tree.children[0].preChildLeafCount = 0 for i in 1 ..< tree.children.count { tree.children[i].preChildLeafCount = tree.children[i-1].childLeafCount + tree.children[i-1].preChildLeafCount } for child in tree.children { update(tree: child) } } // through the childLeafCount, we can transfer the tree to IndexPath static func createIndex(tree: TreeNode, str: String, sameCount: Int) -> IndexPath { var section = 0 var row = 0 var root = tree for i in 0 ..< str.characters.count { let char = str[str.index(str.startIndex, offsetBy: i)] for childIndex in 0 ..< root.children.count { if (char == root.children[childIndex].value) { if i == 0 { section = childIndex }else { row += root.children[childIndex].preChildLeafCount } root = root.children[childIndex] break } } } row += sameCount return IndexPath(row: row, section: section) } static func updateSameCount(tree: TreeNode, str: String) -> Int { var sameCount = 0 var root = tree let level = str.characters.count for i in 0 ..< level { let char = str[str.index(str.startIndex, offsetBy: i)] for child in root.children { if child.value == char{ root = child } } if (i == (level - 1)) { sameCount = root.sameCount - 1 } } return sameCount } }
mit
c58b3c6e3ce49dae58a8a10a38f9ea93
32.325521
121
0.475502
4.732618
false
false
false
false
mercadopago/px-ios
MercadoPagoSDK/MercadoPagoSDK/Flows/OneTap/UI/PXOneTapInstallments/PXOneTapInstallmentInfoViewModel.swift
1
940
import Foundation final class PXOneTapInstallmentInfoViewModel { var text: NSAttributedString var installmentData: PXInstallment? var selectedPayerCost: PXPayerCost? var shouldShowArrow: Bool var status: PXStatus let benefits: PXBenefits? let shouldShowInstallmentsHeader: Bool let behaviours: [String: PXBehaviour]? init(text: NSAttributedString, installmentData: PXInstallment?, selectedPayerCost: PXPayerCost?, shouldShowArrow: Bool, status: PXStatus, benefits: PXBenefits?, shouldShowInstallmentsHeader: Bool, behaviours: [String: PXBehaviour]?) { self.text = text self.installmentData = installmentData self.selectedPayerCost = selectedPayerCost self.shouldShowArrow = shouldShowArrow self.status = status self.benefits = benefits self.shouldShowInstallmentsHeader = shouldShowInstallmentsHeader self.behaviours = behaviours } }
mit
b4e86f94d1c39c378bebbc6216402780
39.869565
238
0.744681
4.653465
false
false
false
false
buyiyang/iosstar
iOSStar/Model/DiscoverModel/DiscoverRequestModel.swift
3
2165
// // DiscoverRequestModel.swift // iOSStar // // Created by J-bb on 17/7/10. // Copyright © 2017年 YunDian. All rights reserved. // import Foundation class StarSortListRequestModel: StarScrollListRequestModel { var sort:Int64 = 0 var pos:Int64 = 1 var count:Int32 = 20 } class StarScrollListRequestModel: MarketBaseModel { var aType:Int64 = 5 } class StarRealtimeRequestModel: StarScrollListRequestModel{ var starcode = "" } class BuyRemainingTimeRequestModel: BaseModel { var uid:Int64 = StarUserModel.getCurrentUser()?.userinfo?.id ?? 0 var token = StarUserModel.getCurrentUser()?.token ?? "" var symbol = "" } class PanicBuyRequestModel: BaseModel { var symbol = "" } class StarDetaiInfoRequestModel: BaseModel { var star_code = "" } class BuyStarTimeRequestModel:BuyRemainingTimeRequestModel { var amount:Int64 = 0 var price = 0.0 } class MiuCountRequestModel: BaseModel{ var uid = StarUserModel.getCurrentUser()?.userinfo?.id ?? 0 var star_code = "" } class AskRequestModel: BaseModel{ var uid = StarUserModel.getCurrentUser()?.userinfo?.id ?? 0 var token = StarUserModel.getCurrentUser()?.token ?? "" var starcode = "" var aType = 0 var pType = 0 var cType = 0 var uask = "" var videoUrl = "" var thumbnail = "" } class UserAskRequestModel: BaseModel{ var uid = StarUserModel.getCurrentUser()?.userinfo?.id ?? 0 var token = StarUserModel.getCurrentUser()?.token ?? "" var pos = 0 var aType = 0 var pType = 0 var count = 10 var starcode = "" var thumbnail = "" } class StarAskRequestModel: BaseModel{ var starcode = "" var uid = StarUserModel.getCurrentUser()?.userinfo?.id ?? 0 var token = StarUserModel.getCurrentUser()?.token ?? "" var pos = 0 var count = 10 var aType = 0 var pType = 0 } class PeepVideoOrvoice: BaseModel { var uid = StarUserModel.getCurrentUser()?.userinfo?.id ?? 0 var qid = 0 var starcode = "" var cType = 0 var askUid = 0 }
gpl-3.0
0db4428614160a47e234fa78b4e6f5e2
24.435294
73
0.628585
3.930909
false
false
false
false
3ph/SplitSlider
SplitSlider/Classes/SplitSliderTrack.swift
1
5083
// // SplitSliderTrack.swift // SplitSlider // // Created by Tomas Friml on 23/06/17. // // MIT License // // Copyright (c) 2017 Tomas Friml // // 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. // public enum SplitSliderTrackDirection: Int { case toLeft case toRight } public class SplitSliderTrack: CALayer { /// Direction of the slider public var direction: SplitSliderTrackDirection = .toRight { didSet { setNeedsDisplay() } } /// How much of the track is highlighted 0..1 public var highlightRatio: CGFloat = 0.25 { didSet { highlightRatio = min(1, highlightRatio) } } /// Padding on the zero side (to accomodate thumbs not clashing while still showing the track all the way public var zeroOffset: CGFloat = 0 /// Frame's X value for currently highlighted ratio public var x: CGFloat { set { let width = frame.width - zeroOffset let startX: CGFloat if direction == .toRight { startX = frame.origin.x + zeroOffset let newX = max(startX, min(newValue, frame.origin.x + frame.width)) highlightRatio = (newX - startX) / width } else { startX = frame.origin.x + frame.width - zeroOffset let newX = min(startX, max(newValue, frame.origin.x)) highlightRatio = (startX - newX) / width } } get { return direction == .toRight ? frame.origin.x + zeroOffset + highlightRatio * (frame.width - zeroOffset) : frame.origin.x + frame.width - zeroOffset - highlightRatio * (frame.width - zeroOffset) } } /// Color of the unselected part of track public var color: UIColor = UIColor.lightGray /// Color of the selected part of track public var highlightColor: UIColor = UIColor.green /// Should round the corners on the minimum side of the track public var roundMinSide: Bool = false public override init() { super.init() initialize() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } public override init(layer: Any) { super.init(layer: layer) initialize() } public override func draw(in ctx: CGContext) { let path = UIBezierPath(roundedRect: bounds, cornerRadius: bounds.height / 2) ctx.addPath(path.cgPath) ctx.setFillColor(color.cgColor) ctx.fillPath() if roundMinSide == false { ctx.fill(CGRect(x: direction == .toRight ? 0 : bounds.width - bounds.height, y: 0, width: bounds.height, height: bounds.height)) } // calculate rect for highlight let width = zeroOffset + bounds.width * highlightRatio ctx.setFillColor(highlightColor.cgColor) if roundMinSide { let highlightPath = UIBezierPath(roundedRect: CGRect(x: direction == .toRight ? 0 : bounds.width - width, y: 0, width: width, height: bounds.height), cornerRadius: bounds.height / 2) ctx.addPath(highlightPath.cgPath) ctx.fillPath() } else { ctx.fill(CGRect(x: direction == .toRight ? 0 : bounds.width - width, y: 0, width: width, height: bounds.height)) } } // MARK: - Private fileprivate func initialize() { backgroundColor = UIColor.clear.cgColor contentsScale = UIScreen.main.scale } }
mit
4f79e6d74f72d100e207ed3632ba5d98
34.795775
117
0.573874
4.882805
false
false
false
false
IvanRublev/PersistentStorageSerializable
PersistentStorageSerializable/Classes/PropertiesIteration.swift
1
2998
// // PropertiesIteration.swift // Pods // // Created by Ivan Rublev on 4/7/17. // // import Foundation import Reflection let persistentStorageSerializableProtocolVariableNames: Set<String> = ["persistentStorage", "persistentStorageKeyPrefix"] extension PersistentStorageSerializable { func selfPropertiesNames() throws -> [String] { let skipNames = persistentStorageSerializableProtocolVariableNames let propertiesDescription = try properties(Self.self) let keys: [String] = propertiesDescription.flatMap { skipNames.contains($0.key) ? nil : $0.key } return keys } /// Performs a closure over each of type instance's properties. /// /// - Parameter names: Set of properties names to skip during enumeration. /// - Parameter perform: Closure to be called on each property key and value pair. /// - Throws: Error from perform closure. func eachSelfProperty(perform: (_ key: String, _ value: Any) throws -> ()) throws { let keys: [String] = try selfPropertiesNames() var keyedValues = [String : Any]() var kvcSuccseed = false if let objcObj = self as? NSObject { SwiftTryCatch.try({ keyedValues = objcObj.dictionaryWithValues(forKeys: keys) kvcSuccseed = true }, catch: nil, finallyBlock: nil) } if kvcSuccseed == false { // pure Swift object for aKey in keys { let propertyValue: Any? = try Reflection.get(aKey, from: self) guard let value = propertyValue else { throw PersistentStorageSerializableError.FailedToGetIntancePropertyValueForName(aKey) } keyedValues[aKey] = value } } for (key, value) in keyedValues { try perform(key, value) } } /// Sets a value for each property of type instance. /// /// - Parameter valueFor: Closure that returns value for specified property name. If returns nil then property is left untouched. /// - Throws: Error from valueFor closure. mutating func setEachSelfProperty(with valueFor: (_ propertyName: String) throws -> Any?) throws { let keys: [String] = try selfPropertiesNames() var keyedValues = [String : Any]() for aKey in keys { if let value = try valueFor(aKey) { keyedValues[aKey] = value } } var kvcSuccseed = false if let objcObj = self as? NSObject { SwiftTryCatch.try({ objcObj.setValuesForKeys(keyedValues) kvcSuccseed = true }, catch: nil, finallyBlock: nil) } if kvcSuccseed == false { // pure Swift object for (key, value) in keyedValues { try Reflection.set(value, key: key, for: &self) } } } }
mit
e249141fb530a92ad7c00e1a46b96067
34.690476
133
0.587725
4.843296
false
false
false
false
Antidote-for-Tox/Antidote-for-Mac
Antidote/BaseConstants.swift
1
1041
// // BaseConstants.swift // Antidote // // Created by Yoba on 04/01/2017. // Copyright © 2017 Dmytro Vorobiov. All rights reserved. // struct BaseConstants { static let offset = 10 static let edgeOffset = 20 static let dividerLineHeight: CGFloat = 1.0 static let primaryFontSize: CGFloat = 14.0 static let secondaryFontSize: CGFloat = 12.0 static let iconButtonSize: CGFloat = 30.0 static let dateLabelWidth: CGFloat = 70.0 struct Colors { static let primaryFontColor = NSColor.black static let secondaryFontColor = NSColor(white: 0.3, alpha: 0.5) static let contourColor = NSColor(white: 0.3, alpha: 0.5) static let messageDeliveredBorderColor = NSColor.green static let messageSentBorderColor = NSColor.purple static let senderNameColor = NSColor.purple static let altPrimaryFontColor = NSColor.white static let altSecondaryFontColor = NSColor.white static let barBackgroundColor = NSColor.white } }
gpl-3.0
65e9985c61eb9b200a5aa195cb3e295d
31.5
71
0.682692
4.502165
false
false
false
false
jay18001/brickkit-ios
Tests/Layout/BrickAppearBehaviorTests.swift
1
2706
// // BrickAppearBehaviorTests.swift // BrickKit // // Created by Ruben Cagnie on 10/11/16. // Copyright © 2016 Wayfair. All rights reserved. // import XCTest @testable import BrickKit class BrickAppearBehaviorTests: XCTestCase { var attributes: UICollectionViewLayoutAttributes! var brickCollectionView: BrickCollectionView! override func setUp() { super.setUp() attributes = UICollectionViewLayoutAttributes(forCellWith: IndexPath(item: 0, section: 0)) attributes.frame = CGRect(x: 0, y: 0, width: 320, height: 200) brickCollectionView = BrickCollectionView(frame: CGRect(x: 0, y: 0, width: 320, height: 480)) brickCollectionView.contentSize = brickCollectionView.frame.size } func testShouldInitializeWithoutAppearBehavior() { let brickLayout = BrickFlowLayout() XCTAssertNil(brickLayout.appearBehavior) } // Mark: - Top func testTopAppear() { let topAppear = BrickAppearTopBehavior() topAppear.configureAttributesForAppearing(attributes, in: brickCollectionView) XCTAssertEqual(attributes.frame, CGRect(x: 0, y: -200, width: 320, height: 200)) } func testTopDisappear() { let topAppear = BrickAppearTopBehavior() topAppear.configureAttributesForDisappearing(attributes, in: brickCollectionView) XCTAssertEqual(attributes.frame, CGRect(x: 0, y: -200, width: 320, height: 200)) } // Mark: - Bottom func testBottomAppear() { let bottomAppear = BrickAppearBottomBehavior() bottomAppear.configureAttributesForAppearing(attributes, in: brickCollectionView) XCTAssertEqual(attributes.frame, CGRect(x: 0, y: 480, width: 320, height: 200)) } func testBottomDisappear() { let bottomAppear = BrickAppearBottomBehavior() bottomAppear.configureAttributesForDisappearing(attributes, in: brickCollectionView) XCTAssertEqual(attributes.frame, CGRect(x: 0, y: 480, width: 320, height: 200)) } func testBottomAppearWithSmallContentHeight() { brickCollectionView.contentSize.height = 10 let bottomAppear = BrickAppearBottomBehavior() bottomAppear.configureAttributesForAppearing(attributes, in: brickCollectionView) XCTAssertEqual(attributes.frame, CGRect(x: 0, y: 480, width: 320, height: 200)) } func testBottomAppearWithLargeContentHeight() { brickCollectionView.contentSize.height = 1000 let bottomAppear = BrickAppearBottomBehavior() bottomAppear.configureAttributesForAppearing(attributes, in: brickCollectionView) XCTAssertEqual(attributes.frame, CGRect(x: 0, y: 1000, width: 320, height: 200)) } }
apache-2.0
c598a2b12bbe47aaa6286085e092644c
36.569444
101
0.711275
4.696181
false
true
false
false
h-n-y/UICollectionView-TheCompleteGuide
chapter-6/ImprovedCircleLayout/CircleLayout/DecorationView.swift
2
856
// // DecorationView.swift // CircleLayout // // Created by Hans Yelek on 5/13/16. // Copyright © 2016 Hans Yelek. All rights reserved. // import UIKit class DecorationView: UICollectionReusableView { override init(frame: CGRect) { super.init(frame: frame) setupGradientMask() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupGradientMask() } private func setupGradientMask() { backgroundColor = UIColor.whiteColor() let gradientLayer = CAGradientLayer() gradientLayer.contentsScale = UIScreen.mainScreen().scale gradientLayer.colors = [UIColor.blackColor().CGColor, UIColor.clearColor().CGColor] gradientLayer.frame = bounds layer.mask = gradientLayer } }
mit
0ef6d26e0aaf0fb5aedaf74dcd403b60
22.75
91
0.622222
5.029412
false
false
false
false
exoplatform/exo-ios
eXo/Sources/JSScript.swift
1
910
// // JSScript.swift // eXo // // Created by Wajih Benabdessalem on 7/11/2022. // Copyright © 2022 eXo. All rights reserved. // import Foundation class JSScript { static let captureLogSource = "function captureLog(msg) { window.webkit.messageHandlers.logHandler.postMessage(msg); } window.console.log = captureLog;" static let iOSListenerSource = "document.addEventListener('mouseout', function(){ window.webkit.messageHandlers.iosListener.postMessage('iOS Listener executed!'); })" static let responsibleTappingSource = "var meta = document.createElement('meta');meta.setAttribute('name', 'viewport');meta.setAttribute('content', 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no');document.getElementsByTagName('head')[0].appendChild(meta);" static let closeWindowErrorSource = "[Jitsi] error: Scripts may not close windows that were not opened by script." }
lgpl-3.0
5f291e174c9bee4b74c4c488517e4c61
55.8125
290
0.752475
3.851695
false
false
false
false
daferpi/LocateKangarooAR
LocateKangarooAR/Pods/HDAugmentedReality/HDAugmentedReality/Classes/ARTrackingManager.swift
1
14526
// // ARTrackingManager.swift // HDAugmentedRealityDemo // // Created by Danijel Huis on 22/04/15. // Copyright (c) 2015 Danijel Huis. All rights reserved. // import UIKit import CoreMotion import CoreLocation @objc protocol ARTrackingManagerDelegate : NSObjectProtocol { @objc optional func arTrackingManager(_ trackingManager: ARTrackingManager, didUpdateUserLocation location: CLLocation?) @objc optional func arTrackingManager(_ trackingManager: ARTrackingManager, didUpdateReloadLocation location: CLLocation?) @objc optional func arTrackingManager(_ trackingManager: ARTrackingManager, didFailToFindLocationAfter elapsedSeconds: TimeInterval) @objc optional func logText(_ text: String) } /// Class used internally by ARViewController for location and orientation calculations. open class ARTrackingManager: NSObject, CLLocationManagerDelegate { /** * Defines whether altitude is taken into account when calculating distances. Set this to false if your annotations * don't have altitude values. Note that this is only used for distance calculation, it doesn't have effect on vertical * levels of annotations. Default value is false. */ open var altitudeSensitive = false /** * Specifies how often the visibilities of annotations are reevaluated. * * Annotation's visibility depends on number of factors - azimuth, distance from user, vertical level etc. * Note: These calculations are quite heavy if many annotations are present, so don't use value lower than 50m. * Default value is 75m. * */ open var reloadDistanceFilter: CLLocationDistance! // Will be set in init /** * Specifies how often are distances and azimuths recalculated for visible annotations. * Default value is 25m. */ open var userDistanceFilter: CLLocationDistance! // Will be set in init { didSet { self.locationManager.distanceFilter = self.userDistanceFilter } } //===== Internal variables fileprivate(set) internal var locationManager: CLLocationManager = CLLocationManager() fileprivate(set) internal var tracking = false fileprivate(set) internal var userLocation: CLLocation? fileprivate(set) internal var heading: Double = 0 internal weak var delegate: ARTrackingManagerDelegate? internal var orientation: CLDeviceOrientation = CLDeviceOrientation.portrait { didSet { self.locationManager.headingOrientation = self.orientation } } internal var pitch: Double { get { return self.calculatePitch() } } //===== Private variables fileprivate var motionManager: CMMotionManager = CMMotionManager() fileprivate var lastAcceleration: CMAcceleration = CMAcceleration(x: 0, y: 0, z: 0) fileprivate var reloadLocationPrevious: CLLocation? fileprivate var pitchPrevious: Double = 0 fileprivate var reportLocationTimer: Timer? fileprivate var reportLocationDate: TimeInterval? fileprivate var debugLocation: CLLocation? fileprivate var locationSearchTimer: Timer? = nil fileprivate var locationSearchStartTime: TimeInterval? = nil override init() { super.init() self.initialize() } deinit { self.stopTracking() } fileprivate func initialize() { // Defaults self.reloadDistanceFilter = 75 self.userDistanceFilter = 25 // Setup location manager self.locationManager.desiredAccuracy = kCLLocationAccuracyBest self.locationManager.distanceFilter = CLLocationDistance(self.userDistanceFilter) self.locationManager.headingFilter = 1 self.locationManager.delegate = self } //========================================================================================================================================================== // MARK: Tracking //========================================================================================================================================================== /** Starts location and motion manager - Parameter: notifyFailure if true, will call arTrackingManager:didFailToFindLocationAfter: */ internal func startTracking(notifyLocationFailure: Bool = false) { // Request authorization if state is not determined if CLLocationManager.locationServicesEnabled() { if CLLocationManager.authorizationStatus() == CLAuthorizationStatus.notDetermined { if #available(iOS 8.0, *) { self.locationManager.requestWhenInUseAuthorization() } else { // Fallback on earlier versions } } } // Start motion and location managers self.motionManager.startAccelerometerUpdates() self.locationManager.startUpdatingHeading() self.locationManager.startUpdatingLocation() self.tracking = true // Location search self.stopLocationSearchTimer() if notifyLocationFailure { self.startLocationSearchTimer() // Calling delegate with value 0 to be flexible, for example user might want to show indicator when search is starting. self.delegate?.arTrackingManager?(self, didFailToFindLocationAfter: 0) } } /// Stops location and motion manager internal func stopTracking() { self.reloadLocationPrevious = nil self.userLocation = nil self.reportLocationDate = nil // Stop motion and location managers self.motionManager.stopAccelerometerUpdates() self.locationManager.stopUpdatingHeading() self.locationManager.stopUpdatingLocation() self.tracking = false self.stopLocationSearchTimer() } //========================================================================================================================================================== // MARK: CLLocationManagerDelegate //========================================================================================================================================================== open func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) { self.heading = fmod(newHeading.trueHeading, 360.0) } open func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if locations.count > 0 { let location = locations[0] // Disregarding old and low quality location detections let age = location.timestamp.timeIntervalSinceNow; if age < -30 || location.horizontalAccuracy > 500 || location.horizontalAccuracy < 0 { print("Disregarding location: age: \(age), ha: \(location.horizontalAccuracy)") return } self.stopLocationSearchTimer() //println("== \(location!.horizontalAccuracy), \(age) \(location!.coordinate.latitude), \(location!.coordinate.longitude)" ) self.userLocation = location // Setting altitude to 0 if altitudeSensitive == false if self.userLocation != nil && !self.altitudeSensitive { let location = self.userLocation! self.userLocation = CLLocation(coordinate: location.coordinate, altitude: 0, horizontalAccuracy: location.horizontalAccuracy, verticalAccuracy: location.verticalAccuracy, timestamp: location.timestamp) } if debugLocation != nil {self.userLocation = debugLocation} if self.reloadLocationPrevious == nil { self.reloadLocationPrevious = self.userLocation } //===== Reporting location 5s after we get location, this will filter multiple locations calls and make only one delegate call let reportIsScheduled = self.reportLocationTimer != nil // First time, reporting immediately if self.reportLocationDate == nil { self.reportLocationToDelegate() } // Report is already scheduled, doing nothing, it will report last location delivered in that 5s else if reportIsScheduled { } // Scheduling report in 5s else { self.reportLocationTimer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(ARTrackingManager.reportLocationToDelegate), userInfo: nil, repeats: false) } } } internal func reportLocationToDelegate() { self.reportLocationTimer?.invalidate() self.reportLocationTimer = nil self.reportLocationDate = Date().timeIntervalSince1970 guard let userLocation = self.userLocation, let reloadLocationPrevious = self.reloadLocationPrevious else { return } guard let reloadDistanceFilter = self.reloadDistanceFilter else { return } self.delegate?.arTrackingManager?(self, didUpdateUserLocation: userLocation) if reloadLocationPrevious.distance(from: userLocation) > reloadDistanceFilter { self.reloadLocationPrevious = userLocation self.delegate?.arTrackingManager?(self, didUpdateReloadLocation: userLocation) } } //========================================================================================================================================================== // MARK: Calculations //========================================================================================================================================================== internal func calculatePitch() -> Double { if self.motionManager.accelerometerData == nil { return 0 } let acceleration: CMAcceleration = self.motionManager.accelerometerData!.acceleration // Filtering data so its not jumping around let filterFactor: Double = 0.05 self.lastAcceleration.x = (acceleration.x * filterFactor) + (self.lastAcceleration.x * (1.0 - filterFactor)); self.lastAcceleration.y = (acceleration.y * filterFactor) + (self.lastAcceleration.y * (1.0 - filterFactor)); self.lastAcceleration.z = (acceleration.z * filterFactor) + (self.lastAcceleration.z * (1.0 - filterFactor)); let deviceOrientation = self.orientation var angle: Double = 0 if deviceOrientation == CLDeviceOrientation.portrait { angle = atan2(self.lastAcceleration.y, self.lastAcceleration.z) } else if deviceOrientation == CLDeviceOrientation.portraitUpsideDown { angle = atan2(-self.lastAcceleration.y, self.lastAcceleration.z) } else if deviceOrientation == CLDeviceOrientation.landscapeLeft { angle = atan2(self.lastAcceleration.x, self.lastAcceleration.z) } else if deviceOrientation == CLDeviceOrientation.landscapeRight { angle = atan2(-self.lastAcceleration.x, self.lastAcceleration.z) } angle += M_PI_2 angle = (self.pitchPrevious + angle) / 2.0 self.pitchPrevious = angle return angle } internal func azimuthFromUserToLocation(_ location: CLLocation) -> Double { var azimuth: Double = 0 if self.userLocation == nil { return 0 } let coordinate: CLLocationCoordinate2D = location.coordinate let userCoordinate: CLLocationCoordinate2D = self.userLocation!.coordinate // Calculating azimuth let latitudeDistance: Double = userCoordinate.latitude - coordinate.latitude; let longitudeDistance: Double = userCoordinate.longitude - coordinate.longitude; // Simplified azimuth calculation azimuth = radiansToDegrees(atan2(longitudeDistance, (latitudeDistance * Double(LAT_LON_FACTOR)))) azimuth += 180.0 return azimuth; } internal func startDebugMode(_ location: CLLocation) { self.debugLocation = location self.userLocation = location; } internal func stopDebugMode(_ location: CLLocation) { self.debugLocation = nil; self.userLocation = nil } //========================================================================================================================================================== // MARK: Location search //========================================================================================================================================================== func startLocationSearchTimer(resetStartTime: Bool = true) { self.stopLocationSearchTimer() if resetStartTime { self.locationSearchStartTime = Date().timeIntervalSince1970 } self.locationSearchTimer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(ARTrackingManager.locationSearchTimerTick), userInfo: nil, repeats: false) } func stopLocationSearchTimer(resetStartTime: Bool = true) { self.locationSearchTimer?.invalidate() self.locationSearchTimer = nil } func locationSearchTimerTick() { guard let locationSearchStartTime = self.locationSearchStartTime else { return } let elapsedSeconds = Date().timeIntervalSince1970 - locationSearchStartTime self.startLocationSearchTimer(resetStartTime: false) self.delegate?.arTrackingManager?(self, didFailToFindLocationAfter: elapsedSeconds) } }
mit
31bc2c0556c6096aa759838b31ea5dba
39.016529
217
0.572697
6.199744
false
false
false
false
ainopara/Stage1st-Reader
Stage1st/Scene/Report/ReportComposeViewModel.swift
1
1411
// // ReportComposeViewModel.swift // Stage1st // // Created by Zheng Li on 2018/6/15. // Copyright © 2018 Renaissance. All rights reserved. // import ReactiveSwift final class ReportComposeViewModel { let topic: S1Topic let floor: Floor let content = MutableProperty("") let canSubmit = MutableProperty(false) let isSubmitting = MutableProperty(false) init(topic: S1Topic, floor: Floor) { self.topic = topic self.floor = floor canSubmit <~ content.producer .map { $0.count > 0 } .combineLatest(with: isSubmitting.producer) .map { (hasCotent, isSubmitting) in hasCotent && !isSubmitting } } func submit(_ completion: @escaping (Error?) -> Void) { S1LogDebug("submit") guard let forumID = topic.fID, let formhash = topic.formhash else { return } AppEnvironment.current.dataCenter.blockUser(with: floor.author.id) isSubmitting.value = true AppEnvironment.current.apiService.report( topicID: "\(topic.topicID)", floorID: "\(floor.id)", forumID: "\(forumID)", reason: content.value, formhash: formhash ) { [weak self] error in guard let strongSelf = self else { return } strongSelf.isSubmitting.value = false completion(error) } } }
bsd-3-clause
e437faa2f8dbec1138c58503a2749694
26.647059
76
0.598582
4.221557
false
false
false
false
rnystrom/GitHawk
Local Pods/SwipeCellKit/Source/SwipeActionsView.swift
2
10551
// // SwipeActionsView.swift // // Created by Jeremy Koch // Copyright © 2017 Jeremy Koch. All rights reserved. // import UIKit protocol SwipeActionsViewDelegate: class { func swipeActionsView(_ swipeActionsView: SwipeActionsView, didSelect action: SwipeAction) } class SwipeActionsView: UIView { weak var delegate: SwipeActionsViewDelegate? let transitionLayout: SwipeTransitionLayout var layoutContext: ActionsViewLayoutContext var feedbackGenerator: SwipeFeedback var expansionAnimator: SwipeAnimator? var expansionDelegate: SwipeExpanding? { return options.expansionDelegate ?? (expandableAction?.hasBackgroundColor == false ? ScaleAndAlphaExpansion.default : nil) } let orientation: SwipeActionsOrientation let actions: [SwipeAction] let options: SwipeTableOptions var buttons: [SwipeActionButton] = [] var minimumButtonWidth: CGFloat = 0 var maximumImageHeight: CGFloat { return actions.reduce(0, { initial, next in max(initial, next.image?.size.height ?? 0) }) } var visibleWidth: CGFloat = 0 { didSet { let preLayoutVisibleWidths = transitionLayout.visibleWidthsForViews(with: layoutContext) layoutContext = ActionsViewLayoutContext.newContext(for: self) transitionLayout.container(view: self, didChangeVisibleWidthWithContext: layoutContext) setNeedsLayout() layoutIfNeeded() notifyVisibleWidthChanged(oldWidths: preLayoutVisibleWidths, newWidths: transitionLayout.visibleWidthsForViews(with: layoutContext)) } } var preferredWidth: CGFloat { return minimumButtonWidth * CGFloat(actions.count) } var contentSize: CGSize { if options.expansionStyle?.elasticOverscroll != true || visibleWidth < preferredWidth { return CGSize(width: visibleWidth, height: bounds.height) } else { let scrollRatio = max(0, visibleWidth - preferredWidth) return CGSize(width: preferredWidth + (scrollRatio * 0.25), height: bounds.height) } } private(set) var expanded: Bool = false var expandableAction: SwipeAction? { return options.expansionStyle != nil ? actions.last : nil } init(maxSize: CGSize, options: SwipeTableOptions, orientation: SwipeActionsOrientation, actions: [SwipeAction]) { self.options = options self.orientation = orientation self.actions = actions.reversed() switch options.transitionStyle { case .border: transitionLayout = BorderTransitionLayout() case .reveal: transitionLayout = RevealTransitionLayout() default: transitionLayout = DragTransitionLayout() } self.layoutContext = ActionsViewLayoutContext(numberOfActions: actions.count, orientation: orientation) feedbackGenerator = SwipeFeedback(style: .light) feedbackGenerator.prepare() super.init(frame: .zero) clipsToBounds = true translatesAutoresizingMaskIntoConstraints = false backgroundColor = options.backgroundColor ?? #colorLiteral(red: 0.862745098, green: 0.862745098, blue: 0.862745098, alpha: 1) buttons = addButtons(for: self.actions, withMaximum: maxSize) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func addButtons(for actions: [SwipeAction], withMaximum size: CGSize) -> [SwipeActionButton] { let buttons: [SwipeActionButton] = actions.map({ action in let actionButton = SwipeActionButton(action: action) actionButton.addTarget(self, action: #selector(actionTapped(button:)), for: .touchUpInside) actionButton.autoresizingMask = [.flexibleHeight, orientation == .right ? .flexibleRightMargin : .flexibleLeftMargin] actionButton.spacing = options.buttonSpacing ?? 8 actionButton.contentEdgeInsets = buttonEdgeInsets(fromOptions: options) return actionButton }) let maximum = options.maximumButtonWidth ?? (size.width - 30) / CGFloat(actions.count) minimumButtonWidth = buttons.reduce(options.minimumButtonWidth ?? 74, { initial, next in max(initial, next.preferredWidth(maximum: maximum)) }) buttons.enumerated().forEach { (index, button) in let action = actions[index] let frame = CGRect(origin: .zero, size: CGSize(width: bounds.width, height: bounds.height)) let wrapperView = SwipeActionButtonWrapperView(frame: frame, action: action, orientation: orientation, contentWidth: minimumButtonWidth) wrapperView.autoresizingMask = [.flexibleHeight, .flexibleWidth] wrapperView.addSubview(button) if let effect = action.backgroundEffect { let effectView = UIVisualEffectView(effect: effect) effectView.frame = wrapperView.frame effectView.autoresizingMask = [.flexibleHeight, .flexibleWidth] effectView.contentView.addSubview(wrapperView) addSubview(effectView) } else { addSubview(wrapperView) } button.frame = wrapperView.contentRect button.maximumImageHeight = maximumImageHeight button.verticalAlignment = options.buttonVerticalAlignment button.shouldHighlight = action.hasBackgroundColor } return buttons } @objc func actionTapped(button: SwipeActionButton) { guard let index = buttons.index(of: button) else { return } delegate?.swipeActionsView(self, didSelect: actions[index]) } func buttonEdgeInsets(fromOptions options: SwipeTableOptions) -> UIEdgeInsets { let padding = options.buttonPadding ?? 8 return UIEdgeInsets(top: padding, left: padding, bottom: padding, right: padding) } func setExpanded(expanded: Bool, feedback: Bool = false) { guard self.expanded != expanded else { return } self.expanded = expanded if feedback { feedbackGenerator.impactOccurred() feedbackGenerator.prepare() } let timingParameters = expansionDelegate?.animationTimingParameters(buttons: buttons.reversed(), expanding: expanded) if expansionAnimator?.isRunning == true { expansionAnimator?.stopAnimation(true) } if #available(iOS 10, *) { expansionAnimator = UIViewPropertyAnimator(duration: timingParameters?.duration ?? 0.6, dampingRatio: 1.0) } else { expansionAnimator = UIViewSpringAnimator(duration: timingParameters?.duration ?? 0.6, damping: 1.0, initialVelocity: 1.0) } expansionAnimator?.addAnimations { self.setNeedsLayout() self.layoutIfNeeded() } expansionAnimator?.startAnimation(afterDelay: timingParameters?.delay ?? 0) notifyExpansion(expanded: expanded) } func notifyVisibleWidthChanged(oldWidths: [CGFloat], newWidths: [CGFloat]) { DispatchQueue.main.async { oldWidths.enumerated().forEach { index, oldWidth in let newWidth = newWidths[index] if oldWidth != newWidth { let context = SwipeActionTransitioningContext(actionIdentifier: self.actions[index].identifier, button: self.buttons[index], newPercentVisible: newWidth / self.minimumButtonWidth, oldPercentVisible: oldWidth / self.minimumButtonWidth, wrapperView: self.subviews[index]) self.actions[index].transitionDelegate?.didTransition(with: context) } } } } func notifyExpansion(expanded: Bool) { guard let expandedButton = buttons.last else { return } expansionDelegate?.actionButton(expandedButton, didChange: expanded, otherActionButtons: buttons.dropLast().reversed()) } func createDeletionMask() -> UIView { let mask = UIView(frame: CGRect(x: min(0, frame.minX), y: 0, width: bounds.width * 2, height: bounds.height)) mask.backgroundColor = UIColor.white return mask } override func layoutSubviews() { super.layoutSubviews() for subview in subviews.enumerated() { transitionLayout.layout(view: subview.element, atIndex: subview.offset, with: layoutContext) } if expanded { subviews.last?.frame.origin.x = 0 + bounds.origin.x } } } class SwipeActionButtonWrapperView: UIView { let contentRect: CGRect init(frame: CGRect, action: SwipeAction, orientation: SwipeActionsOrientation, contentWidth: CGFloat) { switch orientation { case .left: contentRect = CGRect(x: frame.width - contentWidth, y: 0, width: contentWidth, height: frame.height) case .right: contentRect = CGRect(x: 0, y: 0, width: contentWidth, height: frame.height) } super.init(frame: frame) configureBackgroundColor(with: action) } func configureBackgroundColor(with action: SwipeAction) { guard action.hasBackgroundColor else { return } if let backgroundColor = action.backgroundColor { self.backgroundColor = backgroundColor } else { switch action.style { case .destructive: backgroundColor = #colorLiteral(red: 1, green: 0.2352941176, blue: 0.1882352941, alpha: 1) default: backgroundColor = #colorLiteral(red: 0.862745098, green: 0.862745098, blue: 0.862745098, alpha: 1) } } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
8bb25d22ea2bbb47cdf83bf508aa2769
38.513109
151
0.616493
5.540966
false
false
false
false
V3ronique/TailBook
TailBook/TailBook/AddDogViewController.swift
1
3627
// // AddDogViewController.swift // TailBook // // Created by Roni Beberoni on 2/6/16. // Copyright © 2016 Veronica. All rights reserved. // import UIKit import Parse class AddDogViewController : UIViewController, UIPickerViewDataSource,UIPickerViewDelegate{ var dog = PFObject(className: "Dog") @IBOutlet weak var dogSizeLabel: UILabel! @IBOutlet weak var breedField: UITextField! @IBOutlet weak var ageField: UITextField! @IBOutlet weak var dogNameField: UITextField! @IBOutlet weak var genderPicker: UISegmentedControl! @IBOutlet weak var sizePicker: UIPickerView! let pickerData = ["toy < 2.5kg", "small 2.5 ~ 5.0 kg", "medium 5.0 ~ 15.0", "large > 15.0"] override func viewDidLoad() { super.viewDidLoad() sizePicker.dataSource = self sizePicker.delegate = self } func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return pickerData.count } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return pickerData[row] } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { dogSizeLabel.text = pickerData[row] } @IBAction func genderPickerAction(sender: UISegmentedControl) { switch genderPicker.selectedSegmentIndex { case 0: dog["Gender"] = false break case 1: dog["Gender"] = true break default: break; } } @IBAction func addDogAction(sender: AnyObject) { dog["Name"] = self.dogNameField.text dog["Breed"] = self.breedField.text dog["Age"] = Int(self.ageField.text!) dog["Size"] = self.dogSizeLabel.text if dog["Gender"] == nil{ var alert = UIAlertView(title: "Invalid", message: "Please select gender", delegate: self, cancelButtonTitle: "OK") alert.show() } if dog["Breed"] == nil { var alert = UIAlertView(title: "Invalid", message: "Please fill the breed of your dog", delegate: self, cancelButtonTitle: "OK") alert.show() } if dog["Name"] == nil { var alert = UIAlertView(title: "Invalid", message: "Please fill the name of your dog", delegate: self, cancelButtonTitle: "OK") alert.show() } dog["UserId"] = PFUser.currentUser()?.objectId dog.saveInBackgroundWithBlock { (success: Bool, error: NSError?) -> Void in if (success) { var alert = UIAlertView(title: "Success", message: (PFUser.currentUser()!["username"] as? String)! + ", you successfully registered your dog!", delegate: self, cancelButtonTitle: "OK") alert.show() dispatch_async(dispatch_get_main_queue(), { () -> Void in let storyboard = UIStoryboard(name: "Main", bundle: nil) let vc = storyboard.instantiateViewControllerWithIdentifier("Home") as! HomeViewController self.presentViewController(vc, animated: true, completion: nil) }) } else { var alert = UIAlertView(title: "Error", message: "\(error)", delegate: self, cancelButtonTitle: "OK") alert.show() } } } }
mit
0f43b8af9cf75013a7f895dc271a3d45
34.558824
200
0.588803
4.815405
false
false
false
false
keatongreve/fastlane
fastlane/swift/ArgumentProcessor.swift
11
3218
// // ArgumentProcessor.swift // FastlaneRunner // // Created by Joshua Liebowitz on 9/28/17. // // // ** NOTE ** // This file is provided by fastlane and WILL be overwritten in future updates // If you want to add extra functionality to this project, create a new file in a // new group so that it won't be marked for upgrade // import Foundation struct ArgumentProcessor { let args: [RunnerArgument] let currentLane: String let commandTimeout: Int let port: UInt32 init(args: [String]) { // Dump the first arg which is the program name let fastlaneArgs = stride(from: 1, to: args.count - 1, by: 2).map { RunnerArgument(name: args[$0], value: args[$0+1]) } self.args = fastlaneArgs let fastlaneArgsMinusLanes = fastlaneArgs.filter { arg in return arg.name.lowercased() != "lane" } let potentialLogMode = fastlaneArgsMinusLanes.filter { arg in return arg.name.lowercased() == "logmode" } port = UInt32(fastlaneArgsMinusLanes.first(where: { $0.name == "swiftServerPort" })?.value ?? "") ?? 2000 // Configure logMode since we might need to use it before we finish parsing if let logModeArg = potentialLogMode.first { let logModeString = logModeArg.value Logger.logMode = Logger.LogMode(logMode: logModeString) } let lanes = self.args.filter { arg in return arg.name.lowercased() == "lane" } verbose(message: lanes.description) guard lanes.count == 1 else { let message = "You must have exactly one lane specified as an arg, here's what I got: \(lanes)" log(message: message) fatalError(message) } let lane = lanes.first! self.currentLane = lane.value // User might have configured a timeout for the socket connection let potentialTimeout = fastlaneArgsMinusLanes.filter { arg in return arg.name.lowercased() == "timeoutseconds" } if let logModeArg = potentialLogMode.first { let logModeString = logModeArg.value Logger.logMode = Logger.LogMode(logMode: logModeString) } if let timeoutArg = potentialTimeout.first { let timeoutString = timeoutArg.value self.commandTimeout = (timeoutString as NSString).integerValue } else { self.commandTimeout = SocketClient.defaultCommandTimeoutSeconds } } func laneParameters() -> [String : String] { let laneParametersArgs = self.args.filter { arg in let lowercasedName = arg.name.lowercased() return lowercasedName != "timeoutseconds" && lowercasedName != "lane" && lowercasedName != "logmode" } var laneParameters = [String : String]() for arg in laneParametersArgs { laneParameters[arg.name] = arg.value } return laneParameters } } // Please don't remove the lines below // They are used to detect outdated files // FastlaneRunnerAPIVersion [0.9.2]
mit
866c831ea63789b6966c08d73c9b2841
33.602151
113
0.605966
4.597143
false
false
false
false
anthonyApptist/Poplur
Poplur/LogInScreen.swift
1
6262
// // LogInScreen.swift // Poplur // // Created by Mark Meritt on 2016-11-20. // Copyright © 2016 Apptist. All rights reserved. // import UIKit class LogInScreen: PoplurScreen { var usernameBtn: CircleButton! var passwordBtn: CircleButton! var nameTextField: CustomTextFieldContainer! var pwTextField: CustomTextFieldContainer! let checkMarkImg = UIImage(named: "checkmark") var entered = false override func viewDidLoad() { super.viewDidLoad() self.banner?.initWithOffsetY(frame: (self.banner?.frame)!, offsetY: 55) self.name = PoplurScreenName.logIn self.setScreenDirections(current: self, leftScreen: HomeScreen(), rightScreen: nil, downScreen: nil, middleScreen: ProfileScreen(), upScreen: nil) self.setRemoteEnabled(leftFunc: true, rightFunc: false, downFunc: false, middleFunc: false, upFunc: false) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(false) backgroundImageView.frame = CGRect(x: 0, y: 0, width: 375, height:667) backgroundImage = UIImage(named: "bitmap")! backgroundImageView.image = backgroundImage usernameBtn = CircleButton(frame: CGRect(x: 27, y: 61, width: 95.4, height:91.2)) usernameBtn.addText(string: "name", color: 0) usernameBtn.setColorClear() self.view.addSubview(usernameBtn) passwordBtn = CircleButton(frame: CGRect(x: 27, y: 174.8, width:95.4, height: 91.2)) passwordBtn.addText(string: "pw", color: 0) passwordBtn.setColorClear() self.view.addSubview(passwordBtn) nameTextField = CustomTextFieldContainer(frame: CGRect(x: 134.4, y: 89.5, width:215.6, height: 36.6)) self.view.addSubview(nameTextField) pwTextField = CustomTextFieldContainer(frame: CGRect(x: 134.4, y:201.5, width: 215.6, height: 36.6)) self.view.addSubview(pwTextField) nameTextField.setup(placeholder: "Email", validator: "email", type: "email") pwTextField.setup(placeholder: "Password", validator: "required", type: "password") self.nameTextField.textField.delegate = self self.pwTextField.textField.delegate = self let forgotPasswordBtn = UIButton(frame: CGRect(x: 106, y: 334, width: 164, height: 123)) let forgotPasswordImg = UIImage(named: "forgotPw") forgotPasswordBtn.contentMode = .scaleAspectFill forgotPasswordBtn.setImage(forgotPasswordImg, for: .normal) self.view.addSubview(forgotPasswordBtn) } func textFieldDidBeginEditing(_ textField: UITextField) { ErrorHandler.sharedInstance.errorMessageView.resetImagePosition() if(textField == nameTextField.textField) { self.usernameBtn.animateRadius(scale: 1.5, soundOn: false) } if(textField == pwTextField.textField) { self.passwordBtn.animateRadius(scale: 1.5, soundOn: false) } } override func textFieldDidEndEditing(_ textField: UITextField) { ErrorHandler.sharedInstance.errorMessageView.resetImagePosition() textField.resignFirstResponder() if !entered { if nameTextField.textField.text?.isEmpty == false && pwTextField.textField.text?.isEmpty == false { self.setRemoteEnabled(leftFunc: true, rightFunc: false, downFunc: false, middleFunc: true, upFunc: false) self.remote.middleBtn?.setColourVerifiedGreen() self.remote.middleBtn?.animateWithNewImage(scale: 1.2, soundOn: true, image: checkMarkImg!) self.remote.middleBtn?.addTarget(self, action: #selector(self.loginButtonFunction(_:)), for: .touchUpInside) entered = true } } } func validate(showError: Bool) -> Bool { ErrorHandler.sharedInstance.errorMessageView.resetImagePosition() if(!nameTextField.validate()) { if(showError) { if(nameTextField.validationError == "blank") { ErrorHandler.sharedInstance.show(message: "Email Field Cannot Be Blank", container: self) } if(nameTextField.validationError == "not_email") { ErrorHandler.sharedInstance.show(message: "You should double-check that email address....", container: self) } } return false } if(!pwTextField.validate()) { if(showError) { if(pwTextField.validationError == "blank") { ErrorHandler.sharedInstance.show(message: "Password Field Cannot Be Blank", container: self) } } return false } return true } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { nameTextField.textField.resignFirstResponder() pwTextField.textField.resignFirstResponder() } func loginButtonFunction(_ sender: AnyObject) { _ = validate(showError: true) if(!validate(showError: true)) { return } else { AuthService.instance.login(email: self.nameTextField.textField.text!, password: self.pwTextField.textField.text!) { Completion in if(Completion.0 == nil) { self.app.userDefaults.set(self.nameTextField.textField.text!, forKey: "userName") self.app.userDefaults.synchronize() currentState = remoteStates[4] print("remote state is: " + currentState) NotificationCenter.default.post(name: myNotification, object: nil, userInfo: ["message": currentState]) } else { ErrorHandler.sharedInstance.show(message: Completion.0!, container: self) } } } } }
apache-2.0
f55d2f0d8b09ca06dd215626940e6ecc
33.977654
154
0.592397
4.941594
false
false
false
false
dimitris-c/Omicron
Demo/OmicronDemo/ViewController.swift
1
2661
// // ViewController.swift // OmicronDemo // // Created by Dimitris C. on 24/06/2017. // Copyright © 2017 Decimal. All rights reserved. // import UIKit import SwiftyJSON import Alamofire import Omicron class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let service = APIService<HTTPBin>() service.callJSON(with: .get) { (success, result, response) in if let json = result.value, success { print(json) } } let serviceType = APIService<GithubService>() serviceType.callJSON(with: .user(name: "dimitris-c")) { (success, result, response) in if let json = result.value, success { print(json) } } serviceType.call(with: .user(name: "dimitris-c"), parse: GithubUserResponse()) { (success, result, _) in if let user = result.value, success { print(user) } } } } class GithubUserResponse: APIResponse<GithubUser> { override func toData(rawData data: JSON) -> GithubUser { return GithubUser(with: data) } } struct GithubUser { let id: String let user: String let name: String init(with json: JSON) { self.id = json["id"].stringValue self.user = json["user"].stringValue self.name = json["name"].stringValue } } enum GithubService { case user(name: String) } extension GithubService: Service { var baseURL: URL { return URL(string: "https://api.github.com")! } var path: String { switch self { case .user(let name): return "/users/\(name)" } } var method: HTTPMethod { return .get } var params: RequestParameters { return RequestParameters.default } } enum HTTPBin { case get case nonExistingPath case anything(value: String) } extension HTTPBin: Service { var baseURL: URL { return URL(string: "https://httpbin.org")! } var path: String { switch self { case .get: return "/get" case .nonExistingPath: return "/non.existing.path" case .anything(_): return "/anything" } } var method: HTTPMethod { return .get } var params: RequestParameters { switch self { case .anything(let value): return RequestParameters(parameters: ["user": value], encoding: URLEncoding.default) default: return RequestParameters.default } } }
mit
1aaf98a06fa321e1d69e2b8993d6c67a
21.352941
112
0.564286
4.433333
false
false
false
false
BilalReffas/Dashii
Dashi/DashboardDataSource.swift
1
1076
// // DashboardDataSource.swift // Dashi // // Created by Bilal Karim Reffas on 28.01.17. // Copyright © 2017 Bilal Karim Reffas. All rights reserved. // import UIKit class DashboardDataSource: NSObject, UICollectionViewDataSource { private let reuseIdentifier = "Cell" var microscopes = [Microscope]() func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.microscopes.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: self.reuseIdentifier, for: indexPath) as? DashboardCollectionViewCell if let cell = cell { cell.micro = self.microscopes[indexPath.row] return cell } return UICollectionViewCell() } }
mit
03503a8cc98af7e084029507f62e7ca9
25.875
144
0.654884
5.375
false
false
false
false
oursky/Redux
Example/Tests/StoreTests.swift
1
2135
// // StoreTests.swift // SwiftRedux // // Created by Steven Chan on 30/12/15. // Copyright © 2015 CocoaPods. All rights reserved. // import XCTest @testable import Redux class StoreTests: XCTestCase { var store: ReduxStore? override func setUp() { super.setUp() store = Store.configureStore() } override func tearDown() { super.tearDown() } func testGetState() { XCTAssert(store?.getCountState() == CounterState(count: 0)) XCTAssert(store?.getListState() == ListState(list: [String]())) } func testDispatch() { store?.dispatch(ReduxAction(payload: CounterAction.increment)) store?.dispatch(ReduxAction(payload: ListAction.append("hi"))) XCTAssert(store?.getCountState()!.count == 1) XCTAssert((store?.getListState()!.list)! == [ "hi" ]) XCTAssert((store?.getListState()!.list)! != [ "bye" ]) } func testDispatchWithinDispatch() { expectFatalError { self.store?.dispatch( ReduxAction( payload: CounterAction.dispatchWithinDispatch(self.store!) ) ) } } func testSubcribe() { let expectation = self.expectation(description: "subscribed action") var result: [[String]] = [[String]]() func render() { result.append((store?.getListState()!.list)!) if result.count == 2 { XCTAssert(result[0] == [ "Now" ]) XCTAssert(result[1] == [ "Now", "You see me" ]) expectation.fulfill() } } let unsubscribe = store?.subscribe(render) store?.dispatch( ReduxAction(payload: ListAction.append("Now")) ) store?.dispatch( ReduxAction(payload: ListAction.append("You see me")) ) unsubscribe!() store?.dispatch( ReduxAction(payload: ListAction.append("Now you don't")) ) self.waitForExpectations(timeout: 0.5) { (error) -> Void in XCTAssert(result.count == 2) } } }
mit
d15119efc9ca0b3d7c31fa639b24b90f
24.105882
78
0.553421
4.464435
false
true
false
false
tuannme/Up
Up+/Pods/NVActivityIndicatorView/NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationLineSpinFadeLoader.swift
2
4007
// // NVActivityIndicatorAnimationLineSpinFadeLoader.swift // NVActivityIndicatorViewDemo // // The MIT License (MIT) // Copyright (c) 2016 Vinh Nguyen // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit class NVActivityIndicatorAnimationLineSpinFadeLoader: NVActivityIndicatorAnimationDelegate { func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) { let lineSpacing: CGFloat = 2 let lineSize = CGSize(width: (size.width - 4 * lineSpacing) / 5, height: (size.height - 2 * lineSpacing) / 3) let x = (layer.bounds.size.width - size.width) / 2 let y = (layer.bounds.size.height - size.height) / 2 let duration: CFTimeInterval = 1.2 let beginTime = CACurrentMediaTime() let beginTimes: [CFTimeInterval] = [0.12, 0.24, 0.36, 0.48, 0.6, 0.72, 0.84, 0.96] let timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) // Animation let animation = CAKeyframeAnimation(keyPath: "opacity") animation.keyTimes = [0, 0.5, 1] animation.timingFunctions = [timingFunction, timingFunction] animation.values = [1, 0.3, 1] animation.duration = duration animation.repeatCount = HUGE animation.isRemovedOnCompletion = false // Draw lines for i in 0 ..< 8 { let line = lineAt(angle: CGFloat(M_PI_4 * Double(i)), size: lineSize, origin: CGPoint(x: x, y: y), containerSize: size, color: color) animation.beginTime = beginTime + beginTimes[i] line.add(animation, forKey: "animation") layer.addSublayer(line) } } func lineAt(angle: CGFloat, size: CGSize, origin: CGPoint, containerSize: CGSize, color: UIColor) -> CALayer { let radius = containerSize.width / 2 - max(size.width, size.height) / 2 let lineContainerSize = CGSize(width: max(size.width, size.height), height: max(size.width, size.height)) let lineContainer = CALayer() let lineContainerFrame = CGRect( x: origin.x + radius * (cos(angle) + 1), y: origin.y + radius * (sin(angle) + 1), width: lineContainerSize.width, height: lineContainerSize.height) let line = NVActivityIndicatorShape.line.layerWith(size: size, color: color) let lineFrame = CGRect( x: (lineContainerSize.width - size.width) / 2, y: (lineContainerSize.height - size.height) / 2, width: size.width, height: size.height) lineContainer.frame = lineContainerFrame line.frame = lineFrame lineContainer.addSublayer(line) lineContainer.sublayerTransform = CATransform3DMakeRotation(CGFloat(M_PI_2) + angle, 0, 0, 1) return lineContainer } }
mit
eb63132f712313b924edbf0e43faa38e
44.022472
117
0.647118
4.621684
false
false
false
false
DylanModesitt/Picryption_iOS
Pods/Eureka/Source/Rows/SegmentedRow.swift
5
8190
// SegmentedRow.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.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 Foundation //MARK: SegmentedCell open class SegmentedCell<T: Equatable> : Cell<T>, CellType { open var titleLabel : UILabel? { textLabel?.translatesAutoresizingMaskIntoConstraints = false textLabel?.setContentHuggingPriority(500, for: .horizontal) return textLabel } lazy open var segmentedControl : UISegmentedControl = { let result = UISegmentedControl() result.translatesAutoresizingMaskIntoConstraints = false result.setContentHuggingPriority(250, for: .horizontal) return result }() private var dynamicConstraints = [NSLayoutConstraint]() required public init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) NotificationCenter.default.addObserver(forName: Notification.Name.UIApplicationWillResignActive, object: nil, queue: nil){ [weak self] notification in guard let me = self else { return } me.titleLabel?.removeObserver(me, forKeyPath: "text") } NotificationCenter.default.addObserver(forName: Notification.Name.UIApplicationDidBecomeActive, object: nil, queue: nil){ [weak self] notification in self?.titleLabel?.addObserver(self!, forKeyPath: "text", options: NSKeyValueObservingOptions.old.union(.new), context: nil) } NotificationCenter.default.addObserver(forName: Notification.Name.UIContentSizeCategoryDidChange, object: nil, queue: nil){ [weak self] notification in self?.setNeedsUpdateConstraints() } } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { segmentedControl.removeTarget(self, action: nil, for: .allEvents) titleLabel?.removeObserver(self, forKeyPath: "text") imageView?.removeObserver(self, forKeyPath: "image") NotificationCenter.default.removeObserver(self, name: Notification.Name.UIApplicationWillResignActive, object: nil) NotificationCenter.default.removeObserver(self, name: Notification.Name.UIApplicationDidBecomeActive, object: nil) NotificationCenter.default.removeObserver(self, name: Notification.Name.UIContentSizeCategoryDidChange, object: nil) } open override func setup() { super.setup() height = { BaseRow.estimatedRowHeight } selectionStyle = .none contentView.addSubview(titleLabel!) contentView.addSubview(segmentedControl) titleLabel?.addObserver(self, forKeyPath: "text", options: [.old, .new], context: nil) imageView?.addObserver(self, forKeyPath: "image", options: [.old, .new], context: nil) segmentedControl.addTarget(self, action: #selector(SegmentedCell.valueChanged), for: .valueChanged) contentView.addConstraint(NSLayoutConstraint(item: segmentedControl, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1, constant: 0)) } open override func update() { super.update() detailTextLabel?.text = nil updateSegmentedControl() segmentedControl.selectedSegmentIndex = selectedIndex() ?? UISegmentedControlNoSegment segmentedControl.isEnabled = !row.isDisabled } func valueChanged() { row.value = (row as! SegmentedRow<T>).options[segmentedControl.selectedSegmentIndex] } open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { let obj = object as AnyObject? if let changeType = change, let _ = keyPath, ((obj === titleLabel && keyPath == "text") || (obj === imageView && keyPath == "image")) && (changeType[NSKeyValueChangeKey.kindKey] as? NSNumber)?.uintValue == NSKeyValueChange.setting.rawValue{ setNeedsUpdateConstraints() updateConstraintsIfNeeded() } } func updateSegmentedControl() { segmentedControl.removeAllSegments() items().enumerated().forEach { segmentedControl.insertSegment(withTitle: $0.element, at: $0.offset, animated: false) } } open override func updateConstraints() { contentView.removeConstraints(dynamicConstraints) dynamicConstraints = [] var views : [String: AnyObject] = ["segmentedControl": segmentedControl] var hasImageView = false var hasTitleLabel = false if let imageView = imageView, let _ = imageView.image { views["imageView"] = imageView hasImageView = true } if let titleLabel = titleLabel, let text = titleLabel.text, !text.isEmpty { views["titleLabel"] = titleLabel hasTitleLabel = true dynamicConstraints.append(NSLayoutConstraint(item: titleLabel, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1, constant: 0)) } dynamicConstraints.append(NSLayoutConstraint(item: segmentedControl, attribute: .width, relatedBy: .greaterThanOrEqual, toItem: contentView, attribute: .width, multiplier: 0.3, constant: 0.0)) if hasImageView && hasTitleLabel { dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:[imageView]-(15)-[titleLabel]-[segmentedControl]-|", options: [], metrics: nil, views: views) } else if hasImageView && !hasTitleLabel { dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:[imageView]-[segmentedControl]-|", options: [], metrics: nil, views: views) } else if !hasImageView && hasTitleLabel { dynamicConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-[titleLabel]-[segmentedControl]-|", options: .alignAllCenterY, metrics: nil, views: views) } else { dynamicConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-[segmentedControl]-|", options: .alignAllCenterY, metrics: nil, views: views) } contentView.addConstraints(dynamicConstraints) super.updateConstraints() } func items() -> [String] {// or create protocol for options var result = [String]() for object in (row as! SegmentedRow<T>).options { result.append(row.displayValueFor?(object) ?? "") } return result } func selectedIndex() -> Int? { guard let value = row.value else { return nil } return (row as! SegmentedRow<T>).options.index(of: value) } } //MARK: SegmentedRow /// An options row where the user can select an option from an UISegmentedControl public final class SegmentedRow<T: Equatable>: OptionsRow<SegmentedCell<T>>, RowType { required public init(tag: String?) { super.init(tag: tag) } }
mit
a92ddc12f7c0f6aee2695506ee450b0e
46.894737
248
0.685592
5.233227
false
false
false
false
tanweirush/TodayHistory
TodayHistory/mode/THMode.swift
1
795
// // THMode.swift // TodayHistory // // Created by 谭伟 on 15/9/10. // Copyright (c) 2015年 谭伟. All rights reserved. // import UIKit class THMode: NSObject { var url : String? var title : String? var subTitle : String? var solarYear : String? var id : AnyObject? init(data: NSDictionary) { url = data["url"] as? String title = data["title"] as? String subTitle = data["description"] as? String solarYear = data["solaryear"] as? String id = data["id"] as? String } static func makeArrayWithData(arr: NSArray) -> NSArray { let mArr = NSMutableArray() for dic in arr { mArr.addObject(THMode(data: dic as! NSDictionary)) } return mArr } }
mit
4149171822bc9b25dd57a6f2b0eb8194
20.805556
62
0.564331
3.70283
false
false
false
false
soverby/SOUIControlsContainer
SOUIControls/Utilities/CircleUtility.swift
1
3043
// // CircleUtility.swift // PercentCompleteControl // // Created by Overby, Sean on 6/16/15. // Copyright (c) 2015 Sean Overby. All rights reserved. // import Foundation import UIKit public class CircleUtility: NSObject { public typealias CircleAttributes = (centerPoint: CGPoint, outerRadius: Double, innerRadius: Double, animationRadius: Double, animationLineWidth: Double) public class func degreesToRadians(angle: CFloat) -> CGFloat { return CGFloat(angle / 180.0 * CFloat(M_PI)) } public class func radiansToDegress(radians: CFloat) -> CGFloat { return CGFloat(radians * (180.0 / CFloat(M_PI))) } public class func baseCircle(center: CGPoint, radius: Double, strokeColor: UIColor, lineWidth: Double) -> CAShapeLayer { let bCircle = CAShapeLayer() bCircle.path = UIBezierPath(arcCenter: center, radius: CGFloat(radius), startAngle: CGFloat(0), endAngle: degreesToRadians(360), clockwise: true).CGPath bCircle.fillColor = UIColor.clearColor().CGColor bCircle.strokeColor = strokeColor.CGColor bCircle.lineWidth = CGFloat(lineWidth) return bCircle } public class func animatedPercentCircle(center: CGPoint, radius: Double, percentComplete: Double, strokeColor: UIColor, lineWidth: Double) -> CAShapeLayer { let aProgress = CAShapeLayer() let endAngleComputed = CFloat(90 + (360 * (percentComplete / 100.0))) let endAngle = degreesToRadians(endAngleComputed) aProgress.path = UIBezierPath(arcCenter: center, radius: CGFloat(radius), startAngle: degreesToRadians(90), endAngle: endAngle, clockwise: true).CGPath aProgress.fillColor = UIColor.clearColor().CGColor aProgress.strokeColor = strokeColor.CGColor aProgress.lineWidth = CGFloat(lineWidth) return aProgress } public class func strokeAnimation(duration: Double) -> CABasicAnimation { let strokeAnimation = CABasicAnimation(keyPath: "strokeEnd") strokeAnimation.duration = duration strokeAnimation.repeatCount = 1.0 strokeAnimation.autoreverses = false strokeAnimation.removedOnCompletion = false strokeAnimation.fromValue = 0.0 strokeAnimation.toValue = 1.0 strokeAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn) return strokeAnimation } public class func baseCircleFromFrame(frameSize: CGSize, circleWidth: Int) -> CircleUtility.CircleAttributes { let ibCenterPoint = CGPoint(x: frameSize.width / 2, y: frameSize.height / 2) let ibOuterRadius = Double((min(frameSize.width, frameSize.height) - 4) / 2) let ibInnerRadius = ibOuterRadius - Double(circleWidth) let ibAnimationRadius = ibInnerRadius + Double(circleWidth / 2) let ibAnimationLineWidth = ibOuterRadius - ibInnerRadius - 1 return (ibCenterPoint, ibOuterRadius, ibInnerRadius, ibAnimationRadius, ibAnimationLineWidth) } }
mit
12cd3b3b339138a3a7d720257699d09b
44.432836
160
0.702267
4.769592
false
false
false
false
yinhaofrancis/YHAlertView
YHKit/YHAlertView.swift
1
9754
// // YHAlertView.swift // ViewTool // // Created by Francis on 2017/5/27. // Copyright © 2017年 yyk. All rights reserved. // import UIKit public enum YHAlertAction{ case ok(title:String,action:YHActionCallBack) case cancel(title:String,action:YHActionCallBack) func gen(style:AlertStyle)->YHButtonStyle{ switch self { case let .ok(title: s, action: c): return YHButtonStyle.title(title: s, action: c, style: style.okStyle) case let .cancel(title: s, action: c): return YHButtonStyle.title(title: s, action: c, style: style.cancelStyle) } } } //MARK:- 风格 public protocol AlertStyle{ var onlyTop:UIImage{get} var seperate:UIImage{get} var onlyTopPress:UIImage{get} var seperatePress:UIImage{get} } public extension AlertStyle{ public var contentStyle:YHViewStyle<UIView>{ return makeStyle { (l) in l.margin(view: nil, value: 15, direct: .left) l.margin(view: nil, value: 15, direct: .top) l.margin(view: nil, value: 15, direct: .right) l.equal(Value: 96, attr: .height) } } public var contentNoButtonStyle:YHViewStyle<UIView>{ return makeStyle { (l) in l.edge(value: 15) } } public var containerStyle:YHViewStyle<UIView>{ return makeStyle(style: { (view) in view.backgroundColor = UIColor.white self.layoutContainer(view: view, width: UIScreen.main.bounds.width - 40) view.animator = YHAlertAnimator() }) } public var alertViewStyle:YHViewStyle<UIView>{ return makeStyle(style: { (v) in self.fill(view: v) }) } public var backgroundStyle:YHViewStyle<UIView>{ return makeStyle(style: { (v) in self.fill(view: v) v.animator = YHAlertBackgroundAnimator() v.backgroundColor = UIColor.gray.withAlphaComponent(0.5) }) } public var okStyle:YHViewStyle<UIButton>{ return {b in b.setTitleColor(UIColor.red, for: .normal) b.setTitleColor(UIColor.gray, for: .highlighted) } } public var cancelStyle:YHViewStyle<UIButton>{ return {b in b.setTitleColor(UIColor.black, for: .normal) b.setTitleColor(UIColor.gray, for: .highlighted) } } public func layoutContainer(view:UIView,width:CGFloat){ let cx = NSLayoutConstraint(item: view.superview!, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant: 0) let cy = NSLayoutConstraint(item: view.superview!, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1, constant: 0) view.translatesAutoresizingMaskIntoConstraints = false let w = NSLayoutConstraint(item: view, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: width) view.addConstraint(w) view.superview!.addConstraint(cx) view.superview!.addConstraint(cy) } public func fill(view:UIView){ view.translatesAutoresizingMaskIntoConstraints = false let v = NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[view]-0-|", options: .alignAllBottom, metrics: nil, views: ["view":view]) let h = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[view]-0-|", options: .alignAllBottom, metrics: nil, views: ["view":view]) view.superview!.addConstraints(v + h) } public var buttonLayout:YHViewStyle<([UIButton],UIView)>{ return makeStyle(style: { (actions) in if actions.0.count < 4{ actions.1.margin(view: actions.0[0], value: 15, direct: .bottom) actions.0[0].margin(view: nil, value: 0, direct: .bottom) actions.0[0].equal(Value: 44, attr: .height) for i in 0 ..< actions.0.count{ if i == 0{ actions.0[i].setBackgroundImage(self.onlyTop, for: .normal) actions.0[i].setBackgroundImage(self.onlyTop, for: .highlighted) }else{ actions.0[i].setBackgroundImage(self.seperate, for: .normal) actions.0[i].setBackgroundImage(self.seperate, for: .highlighted) } let left:UIView? = i - 1 < 0 ? nil : actions.0[i - 1] let right:UIView? = i + 1 >= actions.0.count ? nil : actions.0[i + 1] actions.0[i].margin(view: left, value: 0, direct: .left) actions.0[i].margin(view: right, value: 0, direct: .right) if let c = left ?? right{ actions.0[i].equal(v: c, attr: .width) actions.0[i].equal(v: c, attr: .height) actions.0[i].equal(v: c, attr: .centerY) } } }else{ for i in 0..<actions.0.count{ let j = actions.0.count - 1 - i let b:UIView? = j + 1 >= actions.0.count ? nil :actions.0[j + 1] actions.0[j].margin(view: b, value: 0, direct: .bottom) actions.0[j].margin(view: nil, value: 0, direct: .left) actions.0[j].margin(view: nil, value: 0, direct: .right) actions.0[j].equal(Value: 44, attr: .height) actions.0[j].setBackgroundImage(self.onlyTop, for: .normal) actions.0[j].setBackgroundImage(self.onlyTop, for: .highlighted) } actions.1.margin(view: actions.0[0], value: 15, direct: .bottom) } }) } } public func buttonBackground(onlyTop:Bool,backColor:UIColor,lineColor:UIColor)->UIImage{ UIGraphicsBeginImageContextWithOptions(CGSize.init(width: 10, height: 10), true, UIScreen.main.scale) let back = UIBezierPath(rect: CGRect(x: 0, y: 0, width: 10, height: 10)) backColor.setFill() back.fill() let line = UIBezierPath() line.move(to: CGPoint.zero) line.addLine(to: CGPoint(x: 10, y: 0)) if !onlyTop{ line.move(to: CGPoint.zero) line.addLine(to: CGPoint(x: 0, y: 10)) } lineColor.setStroke() line.stroke() let img = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return img!.resizableImage(withCapInsets: UIEdgeInsets(top: 3, left: 3, bottom: 3, right: 3)) } class defaultStyle:AlertStyle{ public lazy var onlyTop:UIImage = { return buttonBackground(onlyTop: true, backColor: UIColor.white, lineColor: UIColor.lightGray) }() public lazy var seperate:UIImage = { return buttonBackground(onlyTop: false, backColor: UIColor.white, lineColor: UIColor.lightGray) }() public lazy var onlyTopPress:UIImage = { buttonBackground(onlyTop: true, backColor: UIColor.lightGray, lineColor: UIColor.lightGray) }() public lazy var seperatePress:UIImage = { buttonBackground(onlyTop: false, backColor: UIColor.lightGray, lineColor: UIColor.lightGray) }() } // MARK: - 弹窗 public class YHAlertView<T:UIView>: UIView { public typealias action = ()->Void public weak var manager:YHAlertManager? public let back:action? public let background:UIView = UIView(frame: UIScreen.main.bounds) public let container:UIView = UIView() public let content:T public init(back:action? = nil, model:Bool = false, style:YHViewStyle<YHAlertView>?, containerStyle:YHViewStyle<UIView>?, backgroundStyle:YHViewStyle<UIView>?) { self.back = back self.model = model content = T() cancel = UITapGestureRecognizer() self.style = style super.init(frame:.infinite) self.addSubview(background) self.addSubview(container) containerStyle?(self.container) container.addSubview(self.content) cancel.addTarget(self, action: #selector(backaction)) self.background.addGestureRecognizer(self.cancel) backgroundStyle?(self.background) } public func loadSuperView(view:UIView){ view.addSubview(self) self.style?(self) self.show(complete: nil) } override func hiden(complete: (() -> Void)?) { self.background.hiden { self.back?() complete?() self.removeFromSuperview() } self.container.hiden(complete: nil) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public func setContent(config:(T)->Void,style:YHViewStyle<UIView>?){ config(self.content) style?(self.content) } public func setAction(actions:[YHAlertAction],styleClass:AlertStyle){ let actionBtn:[UIButton] = actions.map{ let b = UIButton.init(action: $0.gen(style: styleClass)) b.addTarget(self, action: #selector(backDefault), for: .touchUpInside) return b } actionBtn.forEach{self.container.addSubview($0)} styleClass.buttonLayout(actionBtn,self.content as UIView) } public func backaction(){ if !model{ backDefault() } } func backDefault(){ self.manager?.hidden() } private let cancel:UITapGestureRecognizer private var _actions:[UIButton] = [] private let model:Bool private let style:YHViewStyle<YHAlertView>? }
mit
cdab8996ca731bfc017150abe92b21c1
38.28629
161
0.594991
4.154797
false
false
false
false
Rag0n/QuNotes
QuNotes/Library/LibraryEvaluatorSpec.swift
1
16227
// // LibraryEvaluatorSpec.swift // QuNotesTests // // Created by Alexander Guschin on 19.10.2017. // Copyright © 2017 Alexander Guschin. All rights reserved. // import Quick import Nimble import Result import Core class LibraryEvaluatorSpec: QuickSpec { override func spec() { var e: Library.Evaluator! beforeEach { e = Library.Evaluator() } describe("-evaluating:ViewEvent") { var event: Library.ViewEvent! context("when receiving addNotebook event") { let notebook = Dummy.notebook(withName: "", uuid: "newUUID") let firstNotebook = Dummy.notebook(withName: "abc") let secondNotebook = Dummy.notebook(withName: "cde") beforeEach { e = Library.Evaluator(notebooks: [firstNotebook, secondNotebook]) event = .addNotebook e.generateUUID = { "newUUID" } e = e.evaluating(event: event) } it("creates notebook model with unique uuid") { let firstAction = e.evaluating(event: event).actions[0] let secondAction = e.evaluating(event: event).actions[0] expect(firstAction).toNot(equal(secondAction)) } it("updates model by adding notebook meta and sorting notebooks") { expect(e.model).to(equalDiff( Library.Model(notebooks: [notebook, firstNotebook, secondNotebook]) )) } it("has addNotebook action with notebook model") { e.generateUUID = { "newUUID" } expect(e.actions).to(equalDiff([ .addNotebook(notebook) ])) } it("has addNotebook effect with correct viewModels and index") { expect(e.effects).to(equalDiff([ .addNotebook(index: 0, notebooks: [Library.NotebookViewModel(title: ""), Library.NotebookViewModel(title: "abc"), Library.NotebookViewModel(title: "cde")]) ])) } } context("when receiving deleteNotebook event") { let firstNotebook = Dummy.notebook(withName: "a") let secondNotebook = Dummy.notebook(withName: "c") let model = Library.Model(notebooks: [firstNotebook, secondNotebook]) beforeEach { e = Library.Evaluator(notebooks: [firstNotebook, secondNotebook]) } context("when notebook with that index exists") { beforeEach { event = .deleteNotebook(index: 1) e = e.evaluating(event: event) } it("updates model by removing notebook meta") { expect(e.model).to(equalDiff( Library.Model(notebooks: [firstNotebook]) )) } it("has deleteNotebook action with correct notebook") { expect(e.actions).to(equalDiff([ .deleteNotebook(secondNotebook) ])) } it("has addNotebook effect with correct viewModels and index") { expect(e.effects).to(equalDiff([ .deleteNotebook(index: 1, notebooks: [Library.NotebookViewModel(title: "a")]) ])) } } context("when notebook with that index doesnt exist") { beforeEach { event = .deleteNotebook(index: 3) e = e.evaluating(event: event) } it("doesnt update model") { expect(e.model).to(equalDiff(model)) } it("hasnt got any actions") { expect(e.actions).to(beEmpty()) } it("hasnt got any effects") { expect(e.effects).to(beEmpty()) } } } context("when receiving selectNotebook event") { beforeEach { event = .selectNotebook(index: 0) e = Library.Evaluator(notebooks: [Core.Notebook.Meta(uuid: "uuid", name: "name")]) e = e.evaluating(event: event) } it("has showNotebook action") { expect(e.actions).to(equalDiff([ .showNotebook(Core.Notebook.Meta(uuid: "uuid", name: "name"), isNew: false) ])) } } } describe("-evaluating:CoordinatorEvent") { var event: Library.CoordinatorEvent! context("when receiving updateNotebook event") { let notebook = Dummy.notebook(withName: "aname") let secondNotebook = Dummy.notebook(withName: "sname") beforeEach { event = .updateNotebook(notebook) } context("when notebook with that uuid exist in model") { beforeEach { let oldNotebook = Core.Notebook.Meta(uuid: notebook.uuid, name: "old name") e = e.evaluating(event: .didLoadNotebooks([secondNotebook, oldNotebook])) .evaluating(event: event) } it("updates notebook with that uuid in model") { expect(e.model).to(equalDiff( Library.Model(notebooks: [notebook, secondNotebook]) )) } it("has updateAllNotebooks effect") { expect(e.effects).to(equalDiff([ .updateAllNotebooks([ Library.NotebookViewModel(title: "aname"), Library.NotebookViewModel(title: "sname") ]) ])) } } context("when notebook with that uuid doesnt exist in model") { beforeEach { e = e.evaluating(event: .didLoadNotebooks([secondNotebook])) .evaluating(event: event) } it("doesnt update model") { expect(e.model).to(equalDiff( Library.Model(notebooks: [secondNotebook]) )) } it("doesnt have actions") { expect(e.actions).to(beEmpty()) } it("doesnt have effects") { expect(e.effects).to(beEmpty()) } } } context("when receiving deleteNotebook event") { let notebook = Dummy.notebook(withName: "aname") let secondNotebook = Dummy.notebook(withName: "sname") beforeEach { event = .deleteNotebook(notebook) } context("when notebook with that uuid exist in model") { beforeEach { e = e.evaluating(event: .didLoadNotebooks([notebook, secondNotebook])) .evaluating(event: event) } it("removes notebook from model") { expect(e.model).to(equalDiff( Library.Model(notebooks: [secondNotebook]) )) } it("has deleteNotebook action") { expect(e.actions).to(equalDiff([ .deleteNotebook(notebook) ])) } it("has deleteNotebook effect") { expect(e.effects).to(equalDiff([ .deleteNotebook(index: 0, notebooks: [Library.NotebookViewModel(title: "sname")]) ])) } } context("when notebook with that uuid doesnt exist in model") { beforeEach { e = e.evaluating(event: .didLoadNotebooks([secondNotebook])) .evaluating(event: event) } it("doesnt update model") { expect(e.model).to(equalDiff( Library.Model(notebooks: [secondNotebook]) )) } it("doesnt have actions") { expect(e.actions).to(beEmpty()) } it("doesnt have effects") { expect(e.effects).to(beEmpty()) } } } context("when receiving didLoadNotebooks") { context("when notebook list is empty") { beforeEach { event = .didLoadNotebooks([]) e = e.evaluating(event: event) } it("has model with empty notebooks") { expect(e.model).to(equalDiff(Library.Model(notebooks: []))) } it("has updateAllNotebooks effect with empty viewModels") { expect(e.effects).to(equalDiff([ .updateAllNotebooks([]) ])) } } context("when notebook list is not empty") { let firstNotebook = Dummy.notebook(withName: "bcd") let secondNotebook = Dummy.notebook(withName: "abc") let thirdNotebook = Dummy.notebook(withName: "Cde") beforeEach { event = .didLoadNotebooks([firstNotebook, secondNotebook, thirdNotebook]) e = e.evaluating(event: event) } it("has model with sorted by name notebooks") { expect(e.model).to(equalDiff( Library.Model(notebooks: [secondNotebook, firstNotebook, thirdNotebook]) )) } it("has updateAllNotebooks effect with sorted viewModels") { expect(e.effects).to(equalDiff([ .updateAllNotebooks([ Library.NotebookViewModel(title: "abc"), Library.NotebookViewModel(title: "bcd"), Library.NotebookViewModel(title: "Cde"), ]) ])) } } } context("when receiving didAddNotebook event") { let notebook = Dummy.notebook(withName: "name") let anotherNotebook = Dummy.notebook(withName: "anotherName") let model = Library.Model(notebooks: [notebook, anotherNotebook]) beforeEach { e = Library.Evaluator(notebooks: [notebook, anotherNotebook]) } context("when successfully adds notebook") { beforeEach { event = .didAddNotebook(notebook, error: nil) e = e.evaluating(event: event) } it("doesnt update model") { expect(e.model).to(equalDiff(model)) } it("has showNotebook action") { expect(e.actions).to(equalDiff([ .showNotebook(notebook, isNew: true) ])) } it("hasnt got any effects") { expect(e.effects).to(beEmpty()) } } context("when failed to add notebook") { beforeEach { event = .didAddNotebook(notebook, error: Dummy.error) e = e.evaluating(event: event) } it("removes that notebook from model") { expect(e.model).to(equalDiff( Library.Model(notebooks: [anotherNotebook]) )) } it("has updateAllNotebooks effect with view models without notebook") { expect(e.effects).to(equalDiff([ .updateAllNotebooks([Library.NotebookViewModel(title: "anotherName")]) ])) } it("has showFailure action") { expect(e.actions).to(equalDiff([ .showFailure(.addNotebook, reason: "message") ])) } } } context("when receiving didDeleteNotebook event") { let notebook = Dummy.notebook(withName: "name") let anotherNotebook = Dummy.notebook(withName: "anotherName") let model = Library.Model(notebooks: [anotherNotebook]) beforeEach { e = Library.Evaluator(notebooks: [anotherNotebook]) } context("when successfully deletes notebook") { beforeEach { event = .didDeleteNotebook(notebook, error: nil) e = e.evaluating(event: event) } it("doesnt update model") { expect(e.model).to(equalDiff(model)) } it("hasnt got any actions") { expect(e.actions).to(beEmpty()) } it("hasnt got any effects") { expect(e.effects).to(beEmpty()) } } context("when fails to delete notebook") { beforeEach { event = .didDeleteNotebook(notebook, error: Dummy.anyError) e = e.evaluating(event: event) } it("adds that notebook back to model") { expect(e.model).to(equalDiff( Library.Model(notebooks: [anotherNotebook, notebook]) )) } it("has updateAllNotebooks effect with view models with notebook") { expect(e.effects).to(equalDiff([ .updateAllNotebooks([Library.NotebookViewModel(title: "anotherName"), Library.NotebookViewModel(title: "name")]) ])) } it("has showFailure action") { expect(e.actions).to(equalDiff([ .showFailure(.deleteNotebook, reason: "message") ])) } } } } } } private enum Dummy { static let error = NSError(domain: "error domain", code: 1, userInfo: [NSLocalizedDescriptionKey: errorMessage]) static let anyError = AnyError(error) static let errorMessage = "message" static let filter = "" static func notebook(withName name: String, uuid: String = UUID().uuidString) -> Core.Notebook.Meta { return Core.Notebook.Meta(uuid: uuid, name: name) } }
gpl-3.0
d2778ff57ad929f463a00d8d3245cfed
38.193237
116
0.43646
5.768219
false
false
false
false
openhab/openhab.ios
OpenHABCore/Sources/OpenHABCore/Model/OpenHABServerProperties.swift
1
907
// Copyright (c) 2010-2022 Contributors to the openHAB project // // See the NOTICE file(s) distributed with this work for additional // information. // // This program and the accompanying materials are made available under the // terms of the Eclipse Public License 2.0 which is available at // http://www.eclipse.org/legal/epl-2.0 // // SPDX-License-Identifier: EPL-2.0 import Foundation public class OpenHABServerProperties: Decodable { class OpenHABLink: Decodable { public var type = "" public var url = "" } public let version: String let links: [OpenHABLink] public var habPanelUrl: String? { linkUrl(byType: "habpanel") } public func linkUrl(byType type: String?) -> String? { if let index = links.firstIndex(where: { $0.type == type }) { return links[index].url } else { return nil } } }
epl-1.0
849127534d4504912cd7571008ad74a2
25.676471
75
0.644983
4.049107
false
false
false
false
LeeShiYoung/RxSwiftXinWen
XW/XW/Classes/Main/View/PageTitleView/PageTitleView.swift
1
1939
// // PageTitleView.swift // XW // // Created by shying li on 2017/9/4. // Copyright © 2017年 浙江聚有财金融服务外包有限公司. All rights reserved. // import UIKit import RxSwift import RxCocoa import ObjectMapper public let itemHeight = 36 class PageTitleView: GenericView { var titles = Variable([PageModel]()) override func awakeFromNib() { super.awakeFromNib() addSubview(titleCollectionView) titleCollectionView.snp.makeConstraints { (make) in make.top.left.right.equalTo(self) make.bottom.equalTo(self.snp.bottom).offset(-0.5) } titles.asObservable().bind(to: titleCollectionView.rx.items(cellIdentifier: R.nib.pageTitleCollectionViewCell.identifier)) { (item, element, cell) in if cell is PageTitleCollectionViewCell { (cell as! PageTitleCollectionViewCell).titleLabel.text = element.title } } .addDisposableTo(disposeBag) } fileprivate lazy var titleCollectionView: UICollectionView = { let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: 55, height: itemHeight) layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.scrollDirection = .horizontal let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout) collectionView.backgroundColor = UIColor.white collectionView.showsHorizontalScrollIndicator = false collectionView.showsVerticalScrollIndicator = false collectionView.scrollsToTop = false collectionView.register(R.nib.pageTitleCollectionViewCell(), forCellWithReuseIdentifier: R.nib.pageTitleCollectionViewCell.identifier) collectionView.backgroundColor = UIColor.colorWithHex("#f6f6f7") return collectionView }() }
apache-2.0
33d883bf5a094d81e87652ab61894eec
33.654545
157
0.678909
5.165312
false
false
false
false
ResearchSuite/ResearchSuiteExtensions-iOS
Example/Pods/ResearchSuiteTaskBuilder/ResearchSuiteTaskBuilder/Classes/Step Providers/Generators/RSTBInstructionStepGenerator.swift
1
1083
// // RSTBInstructionStepGenerator.swift // Pods // // Created by James Kizer on 1/9/17. // // import ResearchKit import Gloss open class RSTBInstructionStepGenerator: RSTBBaseStepGenerator { public init(){} let _supportedTypes = [ "instruction" ] public var supportedTypes: [String]! { return self._supportedTypes } open func generateStep(type: String, jsonObject: JSON, helper: RSTBTaskBuilderHelper) -> ORKStep? { guard let element = RSTBInstructionStepDescriptor(json: jsonObject) else { return nil } let step = ORKInstructionStep(identifier: element.identifier) step.title = element.title step.text = element.text step.detailText = element.detailText return step } open func processStepResult(type: String, jsonObject: JsonObject, result: ORKStepResult, helper: RSTBTaskBuilderHelper) -> JSON? { return nil } }
apache-2.0
279ef39361abdb749dca68dcf351ee80
24.785714
103
0.586334
5.206731
false
false
false
false
shorlander/firefox-ios
Shared/Extensions/NSURLExtensions.swift
5
18317
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit private struct ETLDEntry: CustomStringConvertible { let entry: String var isNormal: Bool { return isWild || !isException } var isWild: Bool = false var isException: Bool = false init(entry: String) { self.entry = entry self.isWild = entry.hasPrefix("*") self.isException = entry.hasPrefix("!") } fileprivate var description: String { return "{ Entry: \(entry), isWildcard: \(isWild), isException: \(isException) }" } } private typealias TLDEntryMap = [String:ETLDEntry] private func loadEntriesFromDisk() -> TLDEntryMap? { if let data = String.contentsOfFileWithResourceName("effective_tld_names", ofType: "dat", fromBundle: Bundle(identifier: "org.mozilla.Shared")!, encoding: String.Encoding.utf8, error: nil) { let lines = data.components(separatedBy: "\n") let trimmedLines = lines.filter { !$0.hasPrefix("//") && $0 != "\n" && $0 != "" } var entries = TLDEntryMap() for line in trimmedLines { let entry = ETLDEntry(entry: line) let key: String if entry.isWild { // Trim off the '*.' part of the line key = line.substring(from: line.characters.index(line.startIndex, offsetBy: 2)) } else if entry.isException { // Trim off the '!' part of the line key = line.substring(from: line.characters.index(line.startIndex, offsetBy: 1)) } else { key = line } entries[key] = entry } return entries } return nil } private var etldEntries: TLDEntryMap? = { return loadEntriesFromDisk() }() // MARK: - Local Resource URL Extensions extension URL { public func allocatedFileSize() -> Int64 { // First try to get the total allocated size and in failing that, get the file allocated size return getResourceLongLongForKey(URLResourceKey.totalFileAllocatedSizeKey.rawValue) ?? getResourceLongLongForKey(URLResourceKey.fileAllocatedSizeKey.rawValue) ?? 0 } public func getResourceValueForKey(_ key: String) -> Any? { let resourceKey = URLResourceKey(key) let keySet = Set<URLResourceKey>([resourceKey]) var val: Any? do { let values = try resourceValues(forKeys: keySet) val = values.allValues[resourceKey] } catch _ { return nil } return val } public func getResourceLongLongForKey(_ key: String) -> Int64? { return (getResourceValueForKey(key) as? NSNumber)?.int64Value } public func getResourceBoolForKey(_ key: String) -> Bool? { return getResourceValueForKey(key) as? Bool } public var isRegularFile: Bool { return getResourceBoolForKey(URLResourceKey.isRegularFileKey.rawValue) ?? false } public func lastComponentIsPrefixedBy(_ prefix: String) -> Bool { return (pathComponents.last?.hasPrefix(prefix) ?? false) } } // The list of permanent URI schemes has been taken from http://www.iana.org/assignments/uri-schemes/uri-schemes.xhtml private let permanentURISchemes = ["aaa", "aaas", "about", "acap", "acct", "cap", "cid", "coap", "coaps", "crid", "data", "dav", "dict", "dns", "example", "file", "ftp", "geo", "go", "gopher", "h323", "http", "https", "iax", "icap", "im", "imap", "info", "ipp", "ipps", "iris", "iris.beep", "iris.lwz", "iris.xpc", "iris.xpcs", "jabber", "ldap", "mailto", "mid", "msrp", "msrps", "mtqp", "mupdate", "news", "nfs", "ni", "nih", "nntp", "opaquelocktoken", "pkcs11", "pop", "pres", "reload", "rtsp", "rtsps", "rtspu", "service", "session", "shttp", "sieve", "sip", "sips", "sms", "snmp", "soap.beep", "soap.beeps", "stun", "stuns", "tag", "tel", "telnet", "tftp", "thismessage", "tip", "tn3270", "turn", "turns", "tv", "urn", "vemmi", "vnc", "ws", "wss", "xcon", "xcon-userid", "xmlrpc.beep", "xmlrpc.beeps", "xmpp", "z39.50r", "z39.50s"] extension URL { public func withQueryParams(_ params: [URLQueryItem]) -> URL { var components = URLComponents(url: self, resolvingAgainstBaseURL: false)! var items = (components.queryItems ?? []) for param in params { items.append(param) } components.queryItems = items return components.url! } public func withQueryParam(_ name: String, value: String) -> URL { var components = URLComponents(url: self, resolvingAgainstBaseURL: false)! let item = URLQueryItem(name: name, value: value) components.queryItems = (components.queryItems ?? []) + [item] return components.url! } public func getQuery() -> [String: String] { var results = [String: String]() let keyValues = self.query?.components(separatedBy: "&") if keyValues?.count ?? 0 > 0 { for pair in keyValues! { let kv = pair.components(separatedBy: "=") if kv.count > 1 { results[kv[0]] = kv[1] } } } return results } public var hostPort: String? { if let host = self.host { if let port = (self as NSURL).port?.int32Value { return "\(host):\(port)" } return host } return nil } public var origin: String? { guard isWebPage(includeDataURIs: false), let hostPort = self.hostPort, let scheme = scheme else { return nil } return "\(scheme)://\(hostPort)" } /** * Returns the second level domain (SLD) of a url. It removes any subdomain/TLD * * E.g., https://m.foo.com/bar/baz?noo=abc#123 => foo **/ public var hostSLD: String { guard let publicSuffix = self.publicSuffix, let baseDomain = self.baseDomain else { return self.normalizedHost ?? self.absoluteString } return baseDomain.replacingOccurrences(of: ".\(publicSuffix)", with: "") } public var normalizedHostAndPath: String? { if let normalizedHost = self.normalizedHost { return normalizedHost + self.path } return nil } public var absoluteDisplayString: String { var urlString = self.absoluteString // For http URLs, get rid of the trailing slash if the path is empty or '/' if (self.scheme == "http" || self.scheme == "https") && (self.path == "/") && urlString.endsWith("/") { urlString = urlString.substring(to: urlString.characters.index(urlString.endIndex, offsetBy: -1)) } // If it's basic http, strip out the string but leave anything else in if urlString.hasPrefix("http://") { return urlString.substring(from: urlString.characters.index(urlString.startIndex, offsetBy: 7)) } else { return urlString } } public var displayURL: URL? { if self.isReaderModeURL { return self.decodeReaderModeURL?.havingRemovedAuthorisationComponents() } if self.isErrorPageURL { if let decodedURL = self.originalURLFromErrorURL { return decodedURL.displayURL } else { return nil } } if !self.isAboutURL { return self.havingRemovedAuthorisationComponents() } return nil } /** Returns the base domain from a given hostname. The base domain name is defined as the public domain suffix with the base private domain attached to the front. For example, for the URL www.bbc.co.uk, the base domain would be bbc.co.uk. The base domain includes the public suffix (co.uk) + one level down (bbc). :returns: The base domain string for the given host name. */ public var baseDomain: String? { guard !isIPv6, let host = host else { return nil } // If this is just a hostname and not a FQDN, use the entire hostname. if !host.contains(".") { return host } return publicSuffixFromHost(host, withAdditionalParts: 1) } /** * Returns just the domain, but with the same scheme, and a trailing '/'. * * E.g., https://m.foo.com/bar/baz?noo=abc#123 => https://foo.com/ * * Any failure? Return this URL. */ public var domainURL: URL { if let normalized = self.normalizedHost { // Use NSURLComponents instead of NSURL since the former correctly preserves // brackets for IPv6 hosts, whereas the latter escapes them. var components = URLComponents() components.scheme = self.scheme components.host = normalized components.path = "/" return components.url ?? self } return self } public var normalizedHost: String? { // Use components.host instead of self.host since the former correctly preserves // brackets for IPv6 hosts, whereas the latter strips them. guard let components = URLComponents(url: self, resolvingAgainstBaseURL: false), var host = components.host, host != "" else { return nil } if let range = host.range(of: "^(www|mobile|m)\\.", options: .regularExpression) { host.replaceSubrange(range, with: "") } return host } /** Returns the public portion of the host name determined by the public suffix list found here: https://publicsuffix.org/list/. For example for the url www.bbc.co.uk, based on the entries in the TLD list, the public suffix would return co.uk. :returns: The public suffix for within the given hostname. */ public var publicSuffix: String? { if let host = self.host { return publicSuffixFromHost(host, withAdditionalParts: 0) } else { return nil } } public func isWebPage(includeDataURIs: Bool = true) -> Bool { let schemes = includeDataURIs ? ["http", "https", "data"] : ["http", "https"] if let scheme = scheme, schemes.contains(scheme) { return true } return false } public var isLocal: Bool { guard isWebPage(includeDataURIs: false) else { return false } // iOS forwards hostless URLs (e.g., http://:6571) to localhost. guard let host = host, !host.isEmpty else { return true } return host.lowercased() == "localhost" || host == "127.0.0.1" } public var isIPv6: Bool { return host?.contains(":") ?? false } /** Returns whether the URL's scheme is one of those listed on the official list of URI schemes. This only accepts permanent schemes: historical and provisional schemes are not accepted. */ public var schemeIsValid: Bool { guard let scheme = scheme else { return false } return permanentURISchemes.contains(scheme.lowercased()) } public func havingRemovedAuthorisationComponents() -> URL { guard var urlComponents = URLComponents(url: self, resolvingAgainstBaseURL: false) else { return self } urlComponents.user = nil urlComponents.password = nil if let url = urlComponents.url { return url } return self } } // Extensions to deal with ReaderMode URLs extension URL { public var isReaderModeURL: Bool { let scheme = self.scheme, host = self.host, path = self.path return scheme == "http" && host == "localhost" && path == "/reader-mode/page" } public var decodeReaderModeURL: URL? { if self.isReaderModeURL { if let components = URLComponents(url: self, resolvingAgainstBaseURL: false), let queryItems = components.queryItems, queryItems.count == 1 { if let queryItem = queryItems.first, let value = queryItem.value { return URL(string: value) } } } return nil } public func encodeReaderModeURL(_ baseReaderModeURL: String) -> URL? { if let encodedURL = absoluteString.addingPercentEncoding(withAllowedCharacters: CharacterSet.alphanumerics) { if let aboutReaderURL = URL(string: "\(baseReaderModeURL)?url=\(encodedURL)") { return aboutReaderURL } } return nil } } // Helpers to deal with ErrorPage URLs extension URL { public var isErrorPageURL: Bool { if let host = self.host { return self.scheme == "http" && host == "localhost" && path == "/errors/error.html" } return false } public var originalURLFromErrorURL: URL? { let components = URLComponents(url: self, resolvingAgainstBaseURL: false) if let queryURL = components?.queryItems?.find({ $0.name == "url" })?.value { return URL(string: queryURL) } return nil } } // Helpers to deal with About URLs extension URL { public var isAboutHomeURL: Bool { if let urlString = self.getQuery()["url"]?.unescape(), isErrorPageURL { let url = URL(string: urlString) ?? self return url.aboutComponent == "home" } return self.aboutComponent == "home" } public var isAboutURL: Bool { return self.aboutComponent != nil } /// If the URI is an about: URI, return the path after "about/" in the URI. /// For example, return "home" for "http://localhost:1234/about/home/#panel=0". public var aboutComponent: String? { let aboutPath = "/about/" guard let scheme = self.scheme, let host = self.host else { return nil } if scheme == "http" && host == "localhost" && path.startsWith(aboutPath) { return path.substring(from: aboutPath.endIndex) } return nil } } //MARK: Private Helpers private extension URL { func publicSuffixFromHost( _ host: String, withAdditionalParts additionalPartCount: Int) -> String? { if host.isEmpty { return nil } // Check edge case where the host is either a single or double '.'. if host.isEmpty || NSString(string: host).lastPathComponent == "." { return "" } /** * The following algorithm breaks apart the domain and checks each sub domain against the effective TLD * entries from the effective_tld_names.dat file. It works like this: * * Example Domain: test.bbc.co.uk * TLD Entry: bbc * * 1. Start off by checking the current domain (test.bbc.co.uk) * 2. Also store the domain after the next dot (bbc.co.uk) * 3. If we find an entry that matches the current domain (test.bbc.co.uk), perform the following checks: * i. If the domain is a wildcard AND the previous entry is not nil, then the current domain matches * since it satisfies the wildcard requirement. * ii. If the domain is normal (no wildcard) and we don't have anything after the next dot, then * currentDomain is a valid TLD * iii. If the entry we matched is an exception case, then the base domain is the part after the next dot * * On the next run through the loop, we set the new domain to check as the part after the next dot, * update the next dot reference to be the string after the new next dot, and check the TLD entries again. * If we reach the end of the host (nextDot = nil) and we haven't found anything, then we've hit the * top domain level so we use it by default. */ let tokens = host.components(separatedBy: ".") let tokenCount = tokens.count var suffix: String? var previousDomain: String? = nil var currentDomain: String = host for offset in 0..<tokenCount { // Store the offset for use outside of this scope so we can add additional parts if needed let nextDot: String? = offset + 1 < tokenCount ? tokens[offset + 1..<tokenCount].joined(separator: ".") : nil if let entry = etldEntries?[currentDomain] { if entry.isWild && (previousDomain != nil) { suffix = previousDomain break } else if entry.isNormal || (nextDot == nil) { suffix = currentDomain break } else if entry.isException { suffix = nextDot break } } previousDomain = currentDomain if let nextDot = nextDot { currentDomain = nextDot } else { break } } var baseDomain: String? if additionalPartCount > 0 { if let suffix = suffix { // Take out the public suffixed and add in the additional parts we want. let literalFromEnd: NSString.CompareOptions = [NSString.CompareOptions.literal, // Match the string exactly. NSString.CompareOptions.backwards, // Search from the end. NSString.CompareOptions.anchored] // Stick to the end. let suffixlessHost = host.replacingOccurrences(of: suffix, with: "", options: literalFromEnd, range: nil) let suffixlessTokens = suffixlessHost.components(separatedBy: ".").filter { $0 != "" } let maxAdditionalCount = max(0, suffixlessTokens.count - additionalPartCount) let additionalParts = suffixlessTokens[maxAdditionalCount..<suffixlessTokens.count] let partsString = additionalParts.joined(separator: ".") baseDomain = [partsString, suffix].joined(separator: ".") } else { return nil } } else { baseDomain = suffix } return baseDomain } }
mpl-2.0
688999a8aec743f19a9b65056c92271b
37.002075
835
0.593765
4.452358
false
false
false
false
KeepGoing2016/Swift-
DUZB_XMJ/DUZB_XMJ/Classes/Home/Model/NormalCellModel.swift
1
844
// // NormalCellModel.swift // DUZB_XMJ // // Created by user on 16/12/27. // Copyright © 2016年 XMJ. All rights reserved. // import UIKit class NormalCellModel: NSObject { /// 房间ID var room_id : Int = 0 /// 房间图片对应的URLString var vertical_src : String = "" /// 判断是手机直播还是电脑直播 // 0 : 电脑直播(普通房间) 1 : 手机直播(秀场房间) var isVertical : Int = 0 /// 房间名称 var room_name : String = "" /// 主播昵称 var nickname : String = "" /// 观看人数 var online : Int = 0 /// 所在城市 var anchor_city : String = "" init(dict : [String:Any]) { super.init() setValuesForKeys(dict) } override func setValue(_ value: Any?, forUndefinedKey key: String) { } }
apache-2.0
5f925336dc7bed939a50a311a8618121
19.361111
72
0.548431
3.507177
false
false
false
false
Shopify/mobile-buy-sdk-ios
Buy/Generated/Storefront/DisplayableError.swift
1
5520
// // DisplayableError.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 /// Represents an error in the input of a mutation. public protocol DisplayableError { var field: [String]? { get } var message: String { get } } extension Storefront { /// Represents an error in the input of a mutation. open class DisplayableErrorQuery: GraphQL.AbstractQuery, GraphQLQuery { public typealias Response = DisplayableError /// The path to the input field that caused the error. @discardableResult open func field(alias: String? = nil) -> DisplayableErrorQuery { addField(field: "field", aliasSuffix: alias) return self } /// The error message. @discardableResult open func message(alias: String? = nil) -> DisplayableErrorQuery { addField(field: "message", aliasSuffix: alias) return self } override init() { super.init() addField(field: "__typename") } /// Represents an error in the input of a mutation. @discardableResult open func onCartUserError(subfields: (CartUserErrorQuery) -> Void) -> DisplayableErrorQuery { let subquery = CartUserErrorQuery() subfields(subquery) addInlineFragment(on: "CartUserError", subfields: subquery) return self } /// Represents an error in the input of a mutation. @discardableResult open func onCheckoutUserError(subfields: (CheckoutUserErrorQuery) -> Void) -> DisplayableErrorQuery { let subquery = CheckoutUserErrorQuery() subfields(subquery) addInlineFragment(on: "CheckoutUserError", subfields: subquery) return self } /// Represents an error in the input of a mutation. @discardableResult open func onCustomerUserError(subfields: (CustomerUserErrorQuery) -> Void) -> DisplayableErrorQuery { let subquery = CustomerUserErrorQuery() subfields(subquery) addInlineFragment(on: "CustomerUserError", subfields: subquery) return self } /// Represents an error in the input of a mutation. @discardableResult open func onUserError(subfields: (UserErrorQuery) -> Void) -> DisplayableErrorQuery { let subquery = UserErrorQuery() subfields(subquery) addInlineFragment(on: "UserError", subfields: subquery) return self } } /// Represents an error in the input of a mutation. open class UnknownDisplayableError: GraphQL.AbstractResponse, GraphQLObject, DisplayableError { public typealias Query = DisplayableErrorQuery internal override func deserializeValue(fieldName: String, value: Any) throws -> Any? { let fieldValue = value switch fieldName { case "field": if value is NSNull { return nil } guard let value = value as? [String] else { throw SchemaViolationError(type: UnknownDisplayableError.self, field: fieldName, value: fieldValue) } return value.map { return $0 } case "message": guard let value = value as? String else { throw SchemaViolationError(type: UnknownDisplayableError.self, field: fieldName, value: fieldValue) } return value default: throw SchemaViolationError(type: UnknownDisplayableError.self, field: fieldName, value: fieldValue) } } internal static func create(fields: [String: Any]) throws -> DisplayableError { guard let typeName = fields["__typename"] as? String else { throw SchemaViolationError(type: UnknownDisplayableError.self, field: "__typename", value: fields["__typename"] ?? NSNull()) } switch typeName { case "CartUserError": return try CartUserError.init(fields: fields) case "CheckoutUserError": return try CheckoutUserError.init(fields: fields) case "CustomerUserError": return try CustomerUserError.init(fields: fields) case "UserError": return try UserError.init(fields: fields) default: return try UnknownDisplayableError.init(fields: fields) } } /// The path to the input field that caused the error. open var field: [String]? { return internalGetField() } func internalGetField(alias: String? = nil) -> [String]? { return field(field: "field", aliasSuffix: alias) as! [String]? } /// The error message. open var message: String { return internalGetMessage() } func internalGetMessage(alias: String? = nil) -> String { return field(field: "message", aliasSuffix: alias) as! String } internal override func childResponseObjectMap() -> [GraphQL.AbstractResponse] { return [] } } }
mit
5561ee68c35817ab7bf9f742a0af9007
33.074074
128
0.724638
4.134831
false
false
false
false
kennyledet/Algorithm-Implementations
Quick_Sort/Swift/QuickSort.swift
2
1003
// // QuickSort.swift // Practice // // Created by Greg Price on 3/31/18. // import Foundation public func quick(_ ints: inout [Int]) { divide(&ints, thisStart: 0, thisEnd: ints.count - 1) } fileprivate func divide(_ ints: inout [Int], thisStart: Int, thisEnd: Int) { if thisStart < thisEnd { let p = partition(&ints, start: thisStart, p: thisEnd) divide(&ints, thisStart: thisStart, thisEnd: p - 1) divide(&ints, thisStart: p + 1, thisEnd: thisEnd) } } fileprivate func partition(_ ints: inout [Int], start: Int, p: Int) -> Int { var leftPileFrontIdx = start - 1 for i in start..<p { if ints[i] <= ints[p] { leftPileFrontIdx += 1 swap(&ints, idx1: leftPileFrontIdx, idx2: i) } } swap(&ints, idx1: leftPileFrontIdx + 1, idx2: p) return leftPileFrontIdx + 1 } fileprivate func swap( _ ints: inout [Int], idx1: Int, idx2: Int) { let t = ints[idx2] ints[idx2] = ints[idx1] ints[idx1] = t }
mit
58a081e16c9fb697517df75f5828e2ec
25.394737
76
0.598205
3.086154
false
false
false
false
kickstarter/ios-oss
Kickstarter-iOS/Features/DiscoveryFilters/Views/Cells/DiscoverySelectableRowCell.swift
1
1918
import Library import Prelude import UIKit internal final class DiscoverySelectableRowCell: UITableViewCell, ValueCell { @IBOutlet private var filterTitleLabel: UILabel! private var rowIsSelected: Bool = false func configureWith(value: (row: SelectableRow, categoryId: Int?)) { if value.row.params.staffPicks == true { self.filterTitleLabel.text = Strings.Projects_We_Love() self.filterTitleLabel.accessibilityLabel = Strings.Filter_by_projects_we_love() } else if value.row.params.starred == true { self.filterTitleLabel.text = Strings.Saved() self.filterTitleLabel.accessibilityLabel = Strings.Filter_by_saved_projects() } else if value.row.params.social == true { self.filterTitleLabel.text = Strings.Backed_by_people_you_follow() self.filterTitleLabel.accessibilityLabel = Strings.Filter_by_projects_backed_by_friends() } else if let category = value.row.params.category { self.filterTitleLabel.text = category.name } else if value.row.params.recommended == true { self.filterTitleLabel.text = Strings.Recommended_For_You() self.filterTitleLabel.accessibilityLabel = Strings.Filter_by_projects_recommended_for_you() } else { self.filterTitleLabel.text = Strings.All_Projects() self.filterTitleLabel.accessibilityLabel = Strings.Filter_by_all_projects() } _ = self.filterTitleLabel |> discoveryFilterLabelStyle(categoryId: value.categoryId, isSelected: value.row.isSelected) |> UILabel.lens.numberOfLines .~ 0 self.rowIsSelected = value.row.isSelected } override func bindStyles() { super.bindStyles() _ = self |> discoveryFilterRowMarginStyle |> UITableViewCell.lens.accessibilityTraits .~ UIAccessibilityTraits.button } internal func willDisplay() { _ = self.filterTitleLabel |> discoveryFilterLabelFontStyle(isSelected: self.rowIsSelected) } }
apache-2.0
d5e1a5c1f1f3be8b88e5359b21b587d1
38.142857
98
0.73097
4.369021
false
false
false
false
need2edit/swift-snippets
Snippets.swift
1
1814
// // Snippets.swift // // // Created by Jake Young on 1/19/15. // Website: http://www.thoughtsfromarobot.com // // These snippets have been collected or developed // over my timeline of learning Swift, I did my best // to credit the original creators, I hope you find them // useful and helpful. For more resources, please visit // my website at http://www.thoughtsfromarobot.com // // My hope is that you learn from these examples and put them to use // // import Foundation import UIKit // MARK: -- String Extensions // Quickly replace a string within a string // Credit: Stack Overflow - 24200888 public extension String { // === Example Usage === // let string = "How cool is Swift?" // let updatedString = string.replace("cool", withString: "awesome") func replace(target: String, withString: String) -> String { return self.stringByReplacingOccurrencesOfString(target, withString: withString, options: NSStringCompareOptions.LiteralSearch, range: nil) } // Further adapted 24200888 to create string removal // === Example Usage === // let string = "How cool is Swift?" // let updatedString = string.replace("cool", withString: "awesome") func remove(stringToRemove: String) -> String { return self.replace(target: stringToRemove, withString: "") } } // MARK: -- Grand Central Dispatch // Delay a main queue dispatch by seconds and provide a closure // Credit: Stack Overflow - 24034544 // === Example Usage === // delay(0.5) { // doSomething() // } public func delay(delay:Double, closure:()->()) { dispatch_after( dispatch_time( DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)) ), dispatch_get_main_queue(), closure) }
unlicense
8265e218495fee2739d7ff845b994a66
25.676471
147
0.649945
4.040089
false
false
false
false
uphold/uphold-sdk-ios
Source/Model/Card/CardRequest.swift
1
1381
import Foundation import ObjectMapper /// Card request model. open class CardRequest: Mappable { /// The currency of the card. public private(set) final var currency: String? /// The label of the card. public private(set) final var label: String? /// The card settings. public private(set) final var settings: CardSettings? /** Constructor. - parameter currency: The currency of the card. - parameter label: The label of the card. */ public init(currency: String, label: String) { self.currency = currency self.label = label } /** Constructor. - parameter currency: The currency of the card. - parameter label: The label of the card. - parameter settings: The settings of the card. */ public init(currency: String, label: String, settings: CardSettings) { self.currency = currency self.label = label self.settings = settings } // MARK: Required by the ObjectMapper. /** Constructor. - parameter map: Mapping data object. */ required public init?(map: Map) { } /** Maps the JSON to the Object. - parameter map: The object to map. */ open func mapping(map: Map) { currency <- map["currency"] label <- map["label"] settings <- map["settings"] } }
mit
33bed6cc3083ceee6e840a238c17c7f1
21.639344
74
0.603186
4.454839
false
false
false
false
wireapp/wire-ios-data-model
Tests/Source/Model/Utils/LinkPreview+ProtobufTests.swift
1
3073
// // Wire // Copyright (C) 2016 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import XCTest import WireDataModel import WireLinkPreview class LinkPreview_ProtobufTests: XCTestCase { func testThatItCreatesAValidArticle_OldStyleProtos() { // given let protos = LinkPreview.with { $0.url = "www.example.com/original" $0.permanentURL = "www.example.com/permanent" $0.urlOffset = 42 $0.title = "title" $0.summary = "summary" $0.article = Article.with { $0.title = "title" $0.summary = "summary" $0.permanentURL = "www.example.com/permanent" } } // when let preview = ArticleMetadata(protocolBuffer: protos) // then XCTAssertEqual(preview.permanentURL?.absoluteString, "www.example.com/permanent") XCTAssertEqual(preview.originalURLString, "www.example.com/original") XCTAssertEqual(preview.characterOffsetInText, 42) } func testThatItCreatesAValidArticle_NewStyleProtos() { // given let protos = LinkPreview.with { $0.url = "www.example.com/original" $0.permanentURL = "www.example.com/permanent" $0.urlOffset = 42 $0.title = "title" $0.summary = "summary" } // when let preview = ArticleMetadata(protocolBuffer: protos) // then XCTAssertEqual(preview.permanentURL?.absoluteString, "www.example.com/permanent") XCTAssertEqual(preview.originalURLString, "www.example.com/original") XCTAssertEqual(preview.characterOffsetInText, 42) } func testThatItCreatesAValidArticleWithTweet_NewStyle() { // given let protos = LinkPreview.with { $0.url = "www.example.com/original" $0.permanentURL = "www.example.com/permanent" $0.urlOffset = 42 $0.title = "title" $0.tweet = Tweet.with { $0.author = "author" $0.username = "username" } } // when let preview = TwitterStatusMetadata(protocolBuffer: protos) // then XCTAssertEqual(preview.permanentURL?.absoluteString, "www.example.com/permanent") XCTAssertEqual(preview.originalURLString, "www.example.com/original") XCTAssertEqual(preview.characterOffsetInText, 42) } }
gpl-3.0
a058082a1abec7cc4f5fee9276cc56a4
33.144444
89
0.627075
4.316011
false
true
false
false
ubi-naist/SenStick
ios/Pods/iOSDFULibrary/iOSDFULibrary/Classes/Implementation/LegacyDFU/Peripherals/LegacyDFUPeripheral.swift
5
8378
/* * Copyright (c) 2016, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES LOSS OF USE, DATA, OR PROFITS OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import CoreBluetooth internal class LegacyDFUPeripheral : BaseCommonDFUPeripheral<LegacyDFUExecutor, LegacyDFUService> { // MARK: - Peripheral API override var requiredServices: [CBUUID]? { return [LegacyDFUService.UUID] } override func isInitPacketRequired() -> Bool { // Init packet has started being required the same time when the DFU Version // characteristic was introduced (SDK 7.0.0). It version exists, and we are not // in Application mode, then the Init Packet is required. if let version = dfuService!.version { // In the application mode we don't know whether init packet is required // as the app is indepenrent from the DFU Bootloader. let isInApplicationMode = version.major == 0 && version.minor == 1 return !isInApplicationMode } return false } // MARK: - Implementation /** Enables notifications on DFU Control Point characteristic. */ func enableControlPoint() { dfuService!.enableControlPoint( onSuccess: { self.delegate?.peripheralDidEnableControlPoint() }, onError: defaultErrorCallback ) } override func isInApplicationMode(_ forceDfu: Bool) -> Bool { let applicationMode = dfuService!.isInApplicationMode() ?? !forceDfu if applicationMode { logger.w("Application with buttonless update found") } return applicationMode } /** Switches target device to the DFU Bootloader mode. */ func jumpToBootloader() { jumpingToBootloader = true dfuService!.jumpToBootloaderMode( // onSuccess the device gets disconnected and centralManager(_:didDisconnectPeripheral:error) will be called onError: { (error, message) in self.jumpingToBootloader = false self.delegate?.error(error, didOccurWithMessage: message) } ) } /** Sends the DFU Start command with the specified firmware type to the DFU Control Point characteristic followed by firmware sizes (in bytes) to the DFU Packet characteristic. Then it waits for a response notification from the device. In case of a Success, it calls `delegate.peripheralDidStartDfu()`. If the response has an error code NotSupported it means, that the target device does not support updating Softdevice or Bootloader and the old Start DFU command needs to be used. The old command (without a type) allowed to send only an application firmware. - parameter type: the firmware type bitfield. See FIRMWARE_TYPE_* constants - parameter size: the size of all parts of the firmware */ func sendStartDfu(withFirmwareType type: UInt8, andSize size: DFUFirmwareSize) { dfuService!.sendDfuStart(withFirmwareType: type, andSize: size, onSuccess: { self.delegate?.peripheralDidStartDfu() }, onError: { error, message in if error == .remoteLegacyDFUNotSupported { self.logger.w("DFU target does not support DFU v.2") self.delegate?.peripheralDidFailToStartDfuWithType() } else { self.delegate?.error(error, didOccurWithMessage: message) } } ) } /** Sends the old Start DFU command, where there was no type byte. The old format allowed to send the application update only. Try this method if `sendStartDfuWithFirmwareType(_:andSize:)` returned NotSupported and the firmware contains only the application. - parameter size: the size of all parts of the firmware, where size of softdevice and bootloader are 0 */ func sendStartDfu(withFirmwareSize size: DFUFirmwareSize) { logger.v("Switching to DFU v.1") dfuService!.sendStartDfu(withFirmwareSize: size, onSuccess: { self.delegate?.peripheralDidStartDfu() }, onError: defaultErrorCallback ) } /** Sends the Init Packet with firmware metadata. When complete, the `delegate.peripheralDidReceiveInitPacket()` callback is called. - parameter data: Init Packet data */ func sendInitPacket(_ data: Data) { dfuService!.sendInitPacket(data, onSuccess: { self.delegate?.peripheralDidReceiveInitPacket() }, onError: defaultErrorCallback ) } /** Sends the firmware to the DFU target device. Before that, it will send the desired number of packets to be received before sending a new Packet Receipt Notification. When the whole firmware is transferred the `delegate.peripheralDidReceiveFirmware()` callback is invoked. - parameter aFirmware: the firmware - parameter aPRNValue: number of packets of firmware data to be received by the DFU target before sending a new Packet Receipt Notification. Set 0 to disable PRNs (not recommended) - parameter progressDelegate: the deleagate that will be informed about progress changes */ func sendFirmware(_ aFirmware: DFUFirmware, withPacketReceiptNotificationNumber aPRNValue: UInt16, andReportProgressTo progressDelegate: DFUProgressDelegate?) { dfuService!.sendPacketReceiptNotificationRequest(aPRNValue, onSuccess: { // Now the service is ready to send the firmware self.dfuService!.sendFirmware(aFirmware, andReportProgressTo: progressDelegate, onSuccess: { self.delegate?.peripheralDidReceiveFirmware() }, onError: self.defaultErrorCallback ) }, onError: defaultErrorCallback ) } /** Sends the Validate Firmware request to DFU Control Point characteristic. On success, the `delegate.peripheralDidVerifyFirmware()` method will be called. */ func validateFirmware() { dfuService!.sendValidateFirmwareRequest( onSuccess: { self.delegate?.peripheralDidVerifyFirmware() }, onError: defaultErrorCallback ) } /** Sends the Activate and Reset command to the DFU Control Point characteristic. */ func activateAndReset() { activating = true dfuService!.sendActivateAndResetRequest( // onSuccess the device gets disconnected and centralManager(_:didDisconnectPeripheral:error) will be called onError: defaultErrorCallback ) } override func resetDevice() { guard let dfuService = dfuService, dfuService.supportsReset() else { super.resetDevice() return } dfuService.sendReset(onError: defaultErrorCallback) } }
mit
4cc67cf57310a4a3f687c36d8a33d8c9
43.56383
164
0.680234
5.275819
false
false
false
false
djflsdl08/BasicIOS
Aaron Hillegass/Photorama/Photorama/Photo.swift
1
647
// // Photo.swift // Photorama // // Created by 김예진 on 2017. 11. 1.. // Copyright © 2017년 Kim,Yejin. All rights reserved. // import UIKit class Photo { // MARK: - Properties let title: String let remoteURL: URL let photoID: String let dateTaken: Date var image: UIImage? init(title: String, photoID: String, remoteURL: URL, dateTaken: Date) { self.title = title self.photoID = photoID self.remoteURL = remoteURL self.dateTaken = dateTaken } } extension Photo: Equatable {} func == (lhs: Photo, rhs: Photo) -> Bool { return lhs.photoID == rhs.photoID }
mit
2ce5bd9ca0f579a22204d3f385d18edb
18.9375
75
0.61442
3.60452
false
false
false
false
doronkatz/firefox-ios
SyncTests/TestBookmarkTreeMerging.swift
2
52523
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Deferred import Foundation import Shared @testable import Storage @testable import Sync import XCTest extension Dictionary { init<S: Sequence>(seq: S) where S.Iterator.Element == Element { self.init() for (k, v) in seq { self[k] = v } } } class MockLocalItemSource: LocalItemSource { var local: [GUID: BookmarkMirrorItem] = [:] func getLocalItemWithGUID(_ guid: GUID) -> Deferred<Maybe<BookmarkMirrorItem>> { guard let item = self.local[guid] else { return deferMaybe(DatabaseError(description: "Couldn't find item \(guid).")) } return deferMaybe(item) } func getLocalItemsWithGUIDs<T: Collection>(_ guids: T) -> Deferred<Maybe<[GUID: BookmarkMirrorItem]>> where T.Iterator.Element == GUID { var acc: [GUID: BookmarkMirrorItem] = [:] guids.forEach { guid in if let item = self.local[guid] { acc[guid] = item } } return deferMaybe(acc) } func prefetchLocalItemsWithGUIDs<T: Collection>(_ guids: T) -> Success where T.Iterator.Element == GUID { return succeed() } } class MockMirrorItemSource: MirrorItemSource { var mirror: [GUID: BookmarkMirrorItem] = [:] func getMirrorItemWithGUID(_ guid: GUID) -> Deferred<Maybe<BookmarkMirrorItem>> { guard let item = self.mirror[guid] else { return deferMaybe(DatabaseError(description: "Couldn't find item \(guid).")) } return deferMaybe(item) } func getMirrorItemsWithGUIDs<T: Collection>(_ guids: T) -> Deferred<Maybe<[GUID: BookmarkMirrorItem]>> where T.Iterator.Element == GUID { var acc: [GUID: BookmarkMirrorItem] = [:] guids.forEach { guid in if let item = self.mirror[guid] { acc[guid] = item } } return deferMaybe(acc) } func prefetchMirrorItemsWithGUIDs<T: Collection>(_ guids: T) -> Success where T.Iterator.Element == GUID { return succeed() } } class MockBufferItemSource: BufferItemSource { var buffer: [GUID: BookmarkMirrorItem] = [:] func getBufferItemsWithGUIDs<T: Collection>(_ guids: T) -> Deferred<Maybe<[GUID: BookmarkMirrorItem]>> where T.Iterator.Element == GUID { var acc: [GUID: BookmarkMirrorItem] = [:] guids.forEach { guid in if let item = self.buffer[guid] { acc[guid] = item } } return deferMaybe(acc) } func getBufferItemWithGUID(_ guid: GUID) -> Deferred<Maybe<BookmarkMirrorItem>> { guard let item = self.buffer[guid] else { return deferMaybe(DatabaseError(description: "Couldn't find item \(guid).")) } return deferMaybe(item) } func prefetchBufferItemsWithGUIDs<T: Collection>(_ guids: T) -> Success where T.Iterator.Element == GUID { return succeed() } } class MockUploader { var deletions: Set<GUID> = Set<GUID>() var added: Set<GUID> = Set<GUID>() var records: [GUID: Record<BookmarkBasePayload>] = [:] func getStorer() -> TrivialBookmarkStorer { return TrivialBookmarkStorer(uploader: self.doUpload) } func doUpload(recs: [Record<BookmarkBasePayload>], lastTimestamp: Timestamp?, onUpload: (POSTResult, Timestamp) -> DeferredTimestamp) -> DeferredTimestamp { var success: [GUID] = [] recs.forEach { rec in success.append(rec.id) self.records[rec.id] = rec if rec.payload.deleted { self.deletions.insert(rec.id) } else { self.added.insert(rec.id) } } // Now pretend we did the upload. return onUpload(POSTResult(success: success, failed: [:]), Date.now()) } } // Thieved mercilessly from TestSQLiteBookmarks. private func getBrowserDBForFile(filename: String, files: FileAccessor) -> BrowserDB? { let db = BrowserDB(filename: filename, files: files) db.attachDB(filename: "metadata.db", as: AttachedDatabaseMetadata) // BrowserTable exists only to perform create/update etc. operations -- it's not // a queryable thing that needs to stick around. if db.createOrUpdate(BrowserTable()) != .success { return nil } return db } class FailFastTestCase: XCTestCase { // This is how to make an assertion failure stop the current test function // but continue with other test functions in the same test case. // See http://stackoverflow.com/a/27016786/22003 override func invokeTest() { self.continueAfterFailure = false defer { self.continueAfterFailure = true } super.invokeTest() } } class TestBookmarkTreeMerging: FailFastTestCase { let files = MockFiles() override func tearDown() { do { try self.files.removeFilesInDirectory() } catch { } super.tearDown() } private func getBrowserDB(name: String) -> BrowserDB? { let file = "TBookmarkTreeMerging\(name).db" return getBrowserDBForFile(filename: file, files: self.files) } private func mockStatsSessionForBookmarks() -> SyncEngineStatsSession { let session = SyncEngineStatsSession(collection: "bookmarks") session.start() return session } func getSyncableBookmarks(name: String) -> MergedSQLiteBookmarks? { guard let db = self.getBrowserDB(name: name) else { XCTFail("Couldn't get prepared DB.") return nil } return MergedSQLiteBookmarks(db: db) } func getSQLiteBookmarks(name: String) -> SQLiteBookmarks? { guard let db = self.getBrowserDB(name: name) else { XCTFail("Couldn't get prepared DB.") return nil } return SQLiteBookmarks(db: db) } func dbLocalTree(name: String) -> BookmarkTree? { guard let bookmarks = self.getSQLiteBookmarks(name: name) else { XCTFail("Couldn't get bookmarks.") return nil } return bookmarks.treeForLocal().value.successValue } func localTree() -> BookmarkTree { let roots = BookmarkRoots.RootChildren.map { BookmarkTreeNode.folder(guid: $0, children: []) } let places = BookmarkTreeNode.folder(guid: BookmarkRoots.RootGUID, children: roots) var lookup: [GUID: BookmarkTreeNode] = [:] var parents: [GUID: GUID] = [:] for n in roots { lookup[n.recordGUID] = n parents[n.recordGUID] = BookmarkRoots.RootGUID } lookup[BookmarkRoots.RootGUID] = places return BookmarkTree(subtrees: [places], lookup: lookup, parents: parents, orphans: Set(), deleted: Set(), modified: Set(lookup.keys), virtual: Set()) } // Our synthesized tree is the same as the one we pull out of a brand new local DB. func testLocalTreeAssumption() { let constructed = self.localTree() let fromDB = self.dbLocalTree(name: "A") XCTAssertNotNil(fromDB) XCTAssertTrue(fromDB!.isFullyRootedIn(constructed)) XCTAssertTrue(constructed.isFullyRootedIn(fromDB!)) XCTAssertTrue(fromDB!.virtual.isEmpty) XCTAssertTrue(constructed.virtual.isEmpty) } // This should never occur in the wild: local will never be empty. func testMergingEmpty() { let r = BookmarkTree.emptyTree() let m = BookmarkTree.emptyMirrorTree() let l = BookmarkTree.emptyTree() let s = ItemSources(local: MockLocalItemSource(), mirror: MockMirrorItemSource(), buffer: MockBufferItemSource()) XCTAssertEqual(m.virtual, BookmarkRoots.Real) let merger = ThreeWayTreeMerger(local: l, mirror: m, remote: r, itemSources: s) guard let mergedTree = merger.produceMergedTree().value.successValue else { XCTFail("Couldn't merge.") return } mergedTree.dump() XCTAssertEqual(mergedTree.allGUIDs, BookmarkRoots.Real) guard let result = merger.produceMergeResultFromMergedTree(mergedTree).value.successValue else { XCTFail("Couldn't produce result.") return } // We don't test the local override completion, because of course we saw mirror items. XCTAssertTrue(result.uploadCompletion.isNoOp) XCTAssertTrue(result.bufferCompletion.isNoOp) } func getItemSourceIncludingEmptyRoots() -> ItemSources { let local = MockLocalItemSource() func makeRoot(guid: GUID, _ name: String) { local.local[guid] = BookmarkMirrorItem.folder(guid, modified: Date.now(), hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: name, description: nil, children: []) } makeRoot(guid: BookmarkRoots.MenuFolderGUID, "Bookmarks Menu") makeRoot(guid: BookmarkRoots.ToolbarFolderGUID, "Bookmarks Toolbar") makeRoot(guid: BookmarkRoots.MobileFolderGUID, "Mobile Bookmarks") makeRoot(guid: BookmarkRoots.UnfiledFolderGUID, "Unsorted Bookmarks") makeRoot(guid: BookmarkRoots.RootGUID, "") return ItemSources(local: local, mirror: MockMirrorItemSource(), buffer: MockBufferItemSource()) } func testMergingOnlyLocalRoots() { let r = BookmarkTree.emptyTree() let m = BookmarkTree.emptyMirrorTree() let l = self.localTree() let s = self.getItemSourceIncludingEmptyRoots() let merger = ThreeWayTreeMerger(local: l, mirror: m, remote: r, itemSources: s) guard let mergedTree = merger.produceMergedTree().value.successValue else { XCTFail("Couldn't merge.") return } mergedTree.dump() XCTAssertEqual(mergedTree.allGUIDs, BookmarkRoots.Real) guard let result = merger.produceMergeResultFromMergedTree(mergedTree).value.successValue else { XCTFail("Couldn't produce result.") return } XCTAssertFalse(result.isNoOp) XCTAssertTrue(result.overrideCompletion.processedLocalChanges.isSuperset(of: Set(BookmarkRoots.RootChildren))) // We should be dropping the roots from local, and uploading roots to the server. // The outgoing records should use Sync-style IDs. // We never upload the places root. let banned = Set<GUID>(["places", BookmarkRoots.RootGUID]) XCTAssertTrue(banned.isDisjoint(with: Set(result.uploadCompletion.records.map { $0.id }))) XCTAssertTrue(banned.isDisjoint(with: result.uploadCompletion.amendChildrenFromBuffer.keys)) XCTAssertTrue(banned.isDisjoint(with: result.uploadCompletion.amendChildrenFromMirror.keys)) XCTAssertTrue(banned.isDisjoint(with: result.uploadCompletion.amendChildrenFromLocal.keys)) XCTAssertEqual(Set(BookmarkRoots.RootChildren), Set(result.uploadCompletion.amendChildrenFromLocal.keys)) XCTAssertEqual(Set(BookmarkRoots.Real), result.overrideCompletion.processedLocalChanges) } func testMergingStorageLocalRootsEmptyServer() { guard let bookmarks = self.getSyncableBookmarks(name: "B") else { XCTFail("Couldn't get bookmarks.") return } // The mirror is never actually empty. let mirrorTree = bookmarks.treeForMirror().value.successValue! XCTAssertFalse(mirrorTree.isEmpty) XCTAssertEqual(mirrorTree.lookup.keys.count, 5) // Root and four children. XCTAssertEqual(1, mirrorTree.subtrees.count) let edgesBefore = bookmarks.treesForEdges().value.successValue! XCTAssertFalse(edgesBefore.local.isEmpty) XCTAssertTrue(edgesBefore.buffer.isEmpty) let uploader = MockUploader() let storer = uploader.getStorer() let applier = MergeApplier(buffer: bookmarks, storage: bookmarks, client: storer, statsSession: mockStatsSessionForBookmarks(), greenLight: { true }) applier.go().succeeded() // Now the local contents are replicated into the mirror, and both the buffer and local are empty. guard let mirror = bookmarks.treeForMirror().value.successValue else { XCTFail("Couldn't get mirror!") return } XCTAssertFalse(mirror.isEmpty) XCTAssertTrue(mirror.subtrees[0].recordGUID == BookmarkRoots.RootGUID) let edgesAfter = bookmarks.treesForEdges().value.successValue! XCTAssertTrue(edgesAfter.local.isEmpty) XCTAssertTrue(edgesAfter.buffer.isEmpty) XCTAssertEqual(uploader.added, Set(BookmarkRoots.RootChildren.map(BookmarkRoots.translateOutgoingRootGUID))) } func testComplexOrphaning() { // This test describes a scenario like this: // // [] [] [] // [M] [T] [M] [T] [M] [T] // | | | | | | // [C] [A] [C] [A] [C] [A] // | | | | // [D] [D] [B] [B] // | | // F E // // That is: we have locally added 'E' to folder B and deleted folder D, // and remotely added 'F' to folder D and deleted folder B. // // This is a fundamental conflict that would ordinarily produce orphans. // Our resolution for this is to put those orphans _somewhere_. // // That place is the lowest surviving parent: walk the tree until we find // a folder that still exists, and put the orphans there. This is a little // better than just dumping the records into Unsorted Bookmarks, and no // more complex than dumping them into the closest root. // // We expect: // // [] // [M] [T] // | | // [C] [A] // | | // F E // guard let bookmarks = self.getSyncableBookmarks(name: "G") else { XCTFail("Couldn't get bookmarks.") return } // Set up the mirror. let mirrorDate = Date.now() - 100000 let records = [ BookmarkMirrorItem.folder(BookmarkRoots.RootGUID, modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "", description: "", children: BookmarkRoots.RootChildren), BookmarkMirrorItem.folder(BookmarkRoots.MenuFolderGUID, modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "Bookmarks Menu", description: "", children: ["folderCCCCCC"]), BookmarkMirrorItem.folder(BookmarkRoots.UnfiledFolderGUID, modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "Unsorted Bookmarks", description: "", children: []), BookmarkMirrorItem.folder(BookmarkRoots.ToolbarFolderGUID, modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "Bookmarks Toolbar", description: "", children: ["folderAAAAAA"]), BookmarkMirrorItem.folder(BookmarkRoots.MobileFolderGUID, modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "Mobile Bookmarks", description: "", children: []), BookmarkMirrorItem.folder("folderAAAAAA", modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.ToolbarFolderGUID, parentName: "Bookmarks Toolbar", title: "A", description: "", children: ["folderBBBBBB"]), BookmarkMirrorItem.folder("folderBBBBBB", modified: mirrorDate, hasDupe: false, parentID: "folderAAAAAA", parentName: "A", title: "B", description: "", children: []), BookmarkMirrorItem.folder("folderCCCCCC", modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.MenuFolderGUID, parentName: "Bookmarks Menu", title: "C", description: "", children: ["folderDDDDDD"]), BookmarkMirrorItem.folder("folderDDDDDD", modified: mirrorDate, hasDupe: false, parentID: "folderCCCCCC", parentName: "C", title: "D", description: "", children: []), ] bookmarks.populateMirrorViaBuffer(items: records, atDate: mirrorDate) bookmarks.wipeLocal() // Now the buffer is empty, and the mirror tree is what we expect. let mirrorTree = bookmarks.treeForMirror().value.successValue! XCTAssertFalse(mirrorTree.isEmpty) XCTAssertEqual(mirrorTree.lookup.keys.count, 9) XCTAssertEqual(1, mirrorTree.subtrees.count) XCTAssertEqual(mirrorTree.find("folderAAAAAA")!.children!.map { $0.recordGUID }, ["folderBBBBBB"]) XCTAssertEqual(mirrorTree.find("folderCCCCCC")!.children!.map { $0.recordGUID }, ["folderDDDDDD"]) let edgesBefore = bookmarks.treesForEdges().value.successValue! XCTAssertTrue(edgesBefore.local.isEmpty) // Because we're fully synced. XCTAssertTrue(edgesBefore.buffer.isEmpty) // Set up the buffer. let bufferDate = Date.now() let changedBufferRecords = [ BookmarkMirrorItem.deleted(BookmarkNodeType.folder, guid: "folderBBBBBB", modified: bufferDate), BookmarkMirrorItem.folder("folderAAAAAA", modified: bufferDate, hasDupe: false, parentID: BookmarkRoots.ToolbarFolderGUID, parentName: "Bookmarks Toolbar", title: "A", description: "", children: []), BookmarkMirrorItem.folder("folderDDDDDD", modified: bufferDate, hasDupe: false, parentID: "folderCCCCCC", parentName: "C", title: "D", description: "", children: ["bookmarkFFFF"]), BookmarkMirrorItem.bookmark("bookmarkFFFF", modified: bufferDate, hasDupe: false, parentID: "folderDDDDDD", parentName: "D", title: "F", description: nil, URI: "http://example.com/f", tags: "", keyword: nil), ] bookmarks.applyRecords(changedBufferRecords).succeeded() // Make local changes. bookmarks.local.modelFactory.value.successValue!.removeByGUID("folderDDDDDD").succeeded() bookmarks.local.insertBookmark("http://example.com/e".asURL!, title: "E", favicon: nil, intoFolder: "folderBBBBBB", withTitle: "B").succeeded() let insertedGUID = bookmarks.local.db.getGUIDs("SELECT guid FROM \(TableBookmarksLocal) WHERE title IS 'E'")[0] let edges = bookmarks.treesForEdges().value.successValue! XCTAssertFalse(edges.local.isEmpty) XCTAssertFalse(edges.buffer.isEmpty) XCTAssertTrue(edges.local.isFullyRootedIn(mirrorTree)) XCTAssertTrue(edges.buffer.isFullyRootedIn(mirrorTree)) XCTAssertTrue(edges.buffer.deleted.contains("folderBBBBBB")) XCTAssertFalse(edges.buffer.deleted.contains("folderDDDDDD")) XCTAssertFalse(edges.local.deleted.contains("folderBBBBBB")) XCTAssertTrue(edges.local.deleted.contains("folderDDDDDD")) // Now merge. let storageMerger = ThreeWayBookmarksStorageMerger(buffer: bookmarks, storage: bookmarks) let merger = storageMerger.getMerger().value.successValue! guard let mergedTree = merger.produceMergedTree().value.successValue else { XCTFail("Couldn't get merge result.") return } // Dump it so we can see it. mergedTree.dump() XCTAssertTrue(mergedTree.deleteLocally.contains("folderBBBBBB")) XCTAssertTrue(mergedTree.deleteFromMirror.contains("folderBBBBBB")) XCTAssertTrue(mergedTree.deleteRemotely.contains("folderDDDDDD")) XCTAssertTrue(mergedTree.deleteFromMirror.contains("folderDDDDDD")) XCTAssertTrue(mergedTree.acceptLocalDeletion.contains("folderDDDDDD")) XCTAssertTrue(mergedTree.acceptRemoteDeletion.contains("folderBBBBBB")) // E and F still exist, in Menu and Toolbar respectively. // Note that the merge itself includes asserts for this; we shouldn't even get here if // this part will fail. XCTAssertTrue(mergedTree.allGUIDs.contains(insertedGUID)) XCTAssertTrue(mergedTree.allGUIDs.contains("bookmarkFFFF")) let menu = mergedTree.root.mergedChildren![0] // menu, toolbar, unfiled, mobile, so 0. let toolbar = mergedTree.root.mergedChildren![1] // menu, toolbar, unfiled, mobile, so 1. XCTAssertEqual(BookmarkRoots.MenuFolderGUID, menu.guid) XCTAssertEqual(BookmarkRoots.ToolbarFolderGUID, toolbar.guid) let folderC = menu.mergedChildren![0] let folderA = toolbar.mergedChildren![0] XCTAssertEqual("folderCCCCCC", folderC.guid) XCTAssertEqual("folderAAAAAA", folderA.guid) XCTAssertEqual(insertedGUID, folderA.mergedChildren![0].guid) XCTAssertEqual("bookmarkFFFF", folderC.mergedChildren![0].guid) guard let result = merger.produceMergeResultFromMergedTree(mergedTree).value.successValue else { XCTFail("Couldn't get merge result.") return } XCTAssertFalse(result.isNoOp) // Everything in local is getting dropped. let formerLocalIDs = Set(edges.local.lookup.keys) XCTAssertTrue(result.overrideCompletion.processedLocalChanges.isSuperset(of: formerLocalIDs)) // Everything in the buffer is getting dropped. let formerBufferIDs = Set(edges.buffer.lookup.keys) XCTAssertTrue(result.bufferCompletion.processedBufferChanges.isSuperset(of: formerBufferIDs)) // The mirror will now contain everything added by each side, and not the deleted folders. XCTAssertEqual(result.overrideCompletion.mirrorItemsToDelete, Set(["folderBBBBBB", "folderDDDDDD"])) XCTAssertTrue(result.overrideCompletion.mirrorValuesToCopyFromLocal.isEmpty) XCTAssertTrue(result.overrideCompletion.mirrorValuesToCopyFromBuffer.isEmpty) XCTAssertTrue(result.overrideCompletion.mirrorItemsToInsert.keys.contains(insertedGUID)) // Because it was reparented. XCTAssertTrue(result.overrideCompletion.mirrorItemsToInsert.keys.contains("bookmarkFFFF")) // Because it was reparented. // The mirror now has the right structure. XCTAssertEqual(result.overrideCompletion.mirrorStructures["folderCCCCCC"]!, ["bookmarkFFFF"]) XCTAssertEqual(result.overrideCompletion.mirrorStructures["folderAAAAAA"]!, [insertedGUID]) // We're going to upload new records for C (lost a child), F (changed parent), // insertedGUID (new local record), A (new child), and D (deleted). // Anything that was in the mirror and only changed structure: let expected: [GUID: [GUID]] = ["folderCCCCCC": ["bookmarkFFFF"], "folderAAAAAA": [insertedGUID]] let actual: [GUID: [GUID]] = result.uploadCompletion.amendChildrenFromMirror XCTAssertEqual(actual as NSDictionary, expected as NSDictionary) // Anything deleted: XCTAssertTrue(result.uploadCompletion.records.contains(where: { (($0.id == "folderDDDDDD") && ($0.payload["deleted"].bool ?? false)) })) // Inserted: let uploadE = result.uploadCompletion.records.find { $0.id == insertedGUID } XCTAssertNotNil(uploadE) XCTAssertEqual(uploadE!.payload["title"].stringValue, "E") // We fixed the parent before uploading. XCTAssertEqual(uploadE!.payload["parentid"].stringValue, "folderAAAAAA") XCTAssertEqual(uploadE!.payload["parentName"].string ?? "", "A") // Reparented: let uploadF = result.uploadCompletion.records.find { $0.id == "bookmarkFFFF" } XCTAssertNotNil(uploadF) XCTAssertEqual(uploadF!.payload["title"].stringValue, "F") // We fixed the parent before uploading. XCTAssertEqual(uploadF!.payload["parentid"].stringValue, "folderCCCCCC") XCTAssertEqual(uploadF!.payload["parentName"].string ?? "", "C") } func testComplexMoveWithAdditions() { // This test describes a scenario like this: // // [] [] [] // [X] [Y] [X] [Y] [X] [Y] // | | | | // [A] C [A] [A] // / \ / \ / | \ // B E B C B D C // // That is: we have locally added 'D' to folder A, and remotely moved // A to a different root, added 'E', and moved 'C' back to the old root. // // Our expected result is: // // [] // [X] [Y] // | | // [A] C // / | \ // B D E // // … but we'll settle for any order of children for [A] that preserves B < E // and B < D -- in other words, (B E D) and (B D E) are both acceptable. // guard let bookmarks = self.getSyncableBookmarks(name: "F") else { XCTFail("Couldn't get bookmarks.") return } // Set up the mirror. let mirrorDate = Date.now() - 100000 let records = [ BookmarkMirrorItem.folder(BookmarkRoots.RootGUID, modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "", description: "", children: BookmarkRoots.RootChildren), BookmarkMirrorItem.folder(BookmarkRoots.MenuFolderGUID, modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "Bookmarks Menu", description: "", children: ["folderAAAAAA"]), BookmarkMirrorItem.folder(BookmarkRoots.UnfiledFolderGUID, modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "Unsorted Bookmarks", description: "", children: []), BookmarkMirrorItem.folder(BookmarkRoots.ToolbarFolderGUID, modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "Bookmarks Toolbar", description: "", children: []), BookmarkMirrorItem.folder(BookmarkRoots.MobileFolderGUID, modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "Mobile Bookmarks", description: "", children: []), BookmarkMirrorItem.folder("folderAAAAAA", modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.MenuFolderGUID, parentName: "Bookmarks Menu", title: "A", description: "", children: ["bookmarkBBBB", "bookmarkCCCC"]), BookmarkMirrorItem.bookmark("bookmarkBBBB", modified: mirrorDate, hasDupe: false, parentID: "folderAAAAAA", parentName: "A", title: "B", description: nil, URI: "http://example.com/b", tags: "", keyword: nil), BookmarkMirrorItem.bookmark("bookmarkCCCC", modified: mirrorDate, hasDupe: false, parentID: "folderAAAAAA", parentName: "A", title: "C", description: nil, URI: "http://example.com/c", tags: "", keyword: nil), ] bookmarks.populateMirrorViaBuffer(items: records, atDate: mirrorDate) bookmarks.wipeLocal() // Now the buffer is empty, and the mirror tree is what we expect. let mirrorTree = bookmarks.treeForMirror().value.successValue! XCTAssertFalse(mirrorTree.isEmpty) XCTAssertEqual(mirrorTree.lookup.keys.count, 8) XCTAssertEqual(1, mirrorTree.subtrees.count) XCTAssertEqual(mirrorTree.find("folderAAAAAA")!.children!.map { $0.recordGUID }, ["bookmarkBBBB", "bookmarkCCCC"]) let edgesBefore = bookmarks.treesForEdges().value.successValue! XCTAssertTrue(edgesBefore.local.isEmpty) // Because we're fully synced. XCTAssertTrue(edgesBefore.buffer.isEmpty) // Set up the buffer. let bufferDate = Date.now() let changedBufferRecords = [ BookmarkMirrorItem.folder(BookmarkRoots.MenuFolderGUID, modified: bufferDate, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "Bookmarks Menu", description: "", children: ["bookmarkCCCC"]), BookmarkMirrorItem.folder(BookmarkRoots.ToolbarFolderGUID, modified: bufferDate, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "Bookmarks Toolbar", description: "", children: ["folderAAAAAA"]), BookmarkMirrorItem.folder("folderAAAAAA", modified: bufferDate, hasDupe: false, parentID: BookmarkRoots.ToolbarFolderGUID, parentName: "Bookmarks Toolbar", title: "A", description: "", children: ["bookmarkBBBB", "bookmarkEEEE"]), BookmarkMirrorItem.bookmark("bookmarkCCCC", modified: bufferDate, hasDupe: false, parentID: BookmarkRoots.MenuFolderGUID, parentName: "A", title: "C", description: nil, URI: "http://example.com/c", tags: "", keyword: nil), BookmarkMirrorItem.bookmark("bookmarkEEEE", modified: bufferDate, hasDupe: false, parentID: "folderAAAAAA", parentName: "A", title: "E", description: nil, URI: "http://example.com/e", tags: "", keyword: nil), ] bookmarks.applyRecords(changedBufferRecords).succeeded() let populatedBufferTree = bookmarks.treesForEdges().value.successValue!.buffer XCTAssertFalse(populatedBufferTree.isEmpty) XCTAssertTrue(populatedBufferTree.isFullyRootedIn(mirrorTree)) XCTAssertFalse(populatedBufferTree.find("bookmarkEEEE")!.isUnknown) XCTAssertFalse(populatedBufferTree.find("bookmarkCCCC")!.isUnknown) XCTAssertTrue(populatedBufferTree.find("bookmarkBBBB")!.isUnknown) // Now let's make local changes with the API. bookmarks.local.insertBookmark("http://example.com/d".asURL!, title: "D (local)", favicon: nil, intoFolder: "folderAAAAAA", withTitle: "A").succeeded() let populatedLocalTree = bookmarks.treesForEdges().value.successValue!.local let newMirrorTree = bookmarks.treeForMirror().value.successValue! XCTAssertEqual(1, newMirrorTree.subtrees.count) XCTAssertFalse(populatedLocalTree.isEmpty) XCTAssertTrue(populatedLocalTree.isFullyRootedIn(mirrorTree)) XCTAssertTrue(populatedLocalTree.isFullyRootedIn(newMirrorTree)) // It changed. XCTAssertNil(populatedLocalTree.find("bookmarkEEEE")) XCTAssertTrue(populatedLocalTree.find("bookmarkCCCC")!.isUnknown) XCTAssertTrue(populatedLocalTree.find("bookmarkBBBB")!.isUnknown) XCTAssertFalse(populatedLocalTree.find("folderAAAAAA")!.isUnknown) // Now merge. let storageMerger = ThreeWayBookmarksStorageMerger(buffer: bookmarks, storage: bookmarks) let merger = storageMerger.getMerger().value.successValue! guard let mergedTree = merger.produceMergedTree().value.successValue else { XCTFail("Couldn't get merge result.") return } // Dump it so we can see it. mergedTree.dump() guard let menu = mergedTree.root.mergedChildren?[0] else { XCTFail("Expected a child of the root.") return } XCTAssertEqual(menu.guid, BookmarkRoots.MenuFolderGUID) XCTAssertEqual(menu.mergedChildren?[0].guid, "bookmarkCCCC") guard let toolbar = mergedTree.root.mergedChildren?[1] else { XCTFail("Expected a second child of the root.") return } XCTAssertEqual(toolbar.guid, BookmarkRoots.ToolbarFolderGUID) let toolbarChildren = toolbar.mergedChildren! XCTAssertEqual(toolbarChildren.count, 1) // A. let aaa = toolbarChildren[0] XCTAssertEqual(aaa.guid, "folderAAAAAA") let aaaChildren = aaa.mergedChildren! XCTAssertEqual(aaaChildren.count, 3) // B, E, new local. XCTAssertFalse(aaaChildren.contains { $0.guid == "bookmarkCCCC" }) } func testApplyingTwoEmptyFoldersDoesntSmush() { guard let bookmarks = self.getSyncableBookmarks(name: "C") else { XCTFail("Couldn't get bookmarks.") return } // Insert two identical folders. We mark them with hasDupe because that's the Syncy // thing to do. let now = Date.now() let records = [ BookmarkMirrorItem.folder(BookmarkRoots.MobileFolderGUID, modified: now, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "Mobile Bookmarks", description: "", children: ["emptyempty01", "emptyempty02"]), BookmarkMirrorItem.folder("emptyempty01", modified: now, hasDupe: true, parentID: BookmarkRoots.MobileFolderGUID, parentName: "Mobile Bookmarks", title: "Empty", description: "", children: []), BookmarkMirrorItem.folder("emptyempty02", modified: now, hasDupe: true, parentID: BookmarkRoots.MobileFolderGUID, parentName: "Mobile Bookmarks", title: "Empty", description: "", children: []), ] bookmarks.buffer.applyRecords(records).succeeded() bookmarks.buffer.db.assertQueryReturns("SELECT COUNT(*) FROM \(TableBookmarksBuffer)", int: 3) bookmarks.buffer.db.assertQueryReturns("SELECT COUNT(*) FROM \(TableBookmarksBufferStructure)", int: 2) let storageMerger = ThreeWayBookmarksStorageMerger(buffer: bookmarks, storage: bookmarks) let merger = storageMerger.getMerger().value.successValue! guard let mergedTree = merger.produceMergedTree().value.successValue else { XCTFail("Couldn't get merge result.") return } // Dump it so we can see it. mergedTree.dump() // Now let's look at the tree. XCTAssertTrue(mergedTree.deleteFromMirror.isEmpty) XCTAssertEqual(BookmarkRoots.RootGUID, mergedTree.root.guid) XCTAssertEqual(BookmarkRoots.RootGUID, mergedTree.root.mirror?.recordGUID) XCTAssertNil(mergedTree.root.remote) XCTAssertTrue(MergeState<BookmarkMirrorItem>.unchanged == mergedTree.root.valueState) XCTAssertTrue(MergeState<BookmarkTreeNode>.unchanged == mergedTree.root.structureState) XCTAssertEqual(4, mergedTree.root.mergedChildren?.count) guard let mergedMobile = mergedTree.root.mergedChildren?[BookmarkRoots.RootChildren.index(of: BookmarkRoots.MobileFolderGUID) ?? -1] else { XCTFail("Didn't get a merged mobile folder.") return } XCTAssertEqual(BookmarkRoots.MobileFolderGUID, mergedMobile.guid) XCTAssertTrue(MergeState<BookmarkMirrorItem>.remote == mergedMobile.valueState) // This ends up as Remote because we didn't change any of its structure // when compared to the incoming record. guard case MergeState<BookmarkTreeNode>.remote = mergedMobile.structureState else { XCTFail("Didn't get expected Remote state.") return } XCTAssertEqual(["emptyempty01", "emptyempty02"], mergedMobile.remote!.children!.map { $0.recordGUID }) XCTAssertEqual(["emptyempty01", "emptyempty02"], mergedMobile.asMergedTreeNode().children!.map { $0.recordGUID }) XCTAssertEqual(["emptyempty01", "emptyempty02"], mergedMobile.mergedChildren!.map { $0.guid }) let empty01 = mergedMobile.mergedChildren![0] let empty02 = mergedMobile.mergedChildren![1] XCTAssertNil(empty01.local) XCTAssertNil(empty02.local) XCTAssertNil(empty01.mirror) XCTAssertNil(empty02.mirror) XCTAssertNotNil(empty01.remote) XCTAssertNotNil(empty02.remote) XCTAssertEqual("emptyempty01", empty01.remote!.recordGUID) XCTAssertEqual("emptyempty02", empty02.remote!.recordGUID) XCTAssertTrue(MergeState<BookmarkTreeNode>.remote == empty01.structureState) XCTAssertTrue(MergeState<BookmarkTreeNode>.remote == empty02.structureState) XCTAssertTrue(MergeState<BookmarkMirrorItem>.remote == empty01.valueState) XCTAssertTrue(MergeState<BookmarkMirrorItem>.remote == empty02.valueState) XCTAssertTrue(empty01.mergedChildren?.isEmpty ?? false) XCTAssertTrue(empty02.mergedChildren?.isEmpty ?? false) guard let result = merger.produceMergeResultFromMergedTree(mergedTree).value.successValue else { XCTFail("Couldn't get merge result.") return } let uploader = MockUploader() let storer = uploader.getStorer() let applier = MergeApplier(buffer: bookmarks, storage: bookmarks, client: storer, statsSession: mockStatsSessionForBookmarks(), greenLight: { true }) applier.applyResult(result).succeeded() guard let mirror = bookmarks.treeForMirror().value.successValue else { XCTFail("Couldn't get mirror!") return } // After merge, the buffer and local are empty. let edgesAfter = bookmarks.treesForEdges().value.successValue! XCTAssertTrue(edgesAfter.local.isEmpty) XCTAssertTrue(edgesAfter.buffer.isEmpty) // When merged in, we do not smush these two records together! XCTAssertFalse(mirror.isEmpty) XCTAssertTrue(mirror.subtrees[0].recordGUID == BookmarkRoots.RootGUID) XCTAssertNotNil(mirror.find("emptyempty01")) XCTAssertNotNil(mirror.find("emptyempty02")) XCTAssertTrue(mirror.deleted.isEmpty) guard let mobile = mirror.find(BookmarkRoots.MobileFolderGUID) else { XCTFail("No mobile folder in mirror.") return } if case let .folder(_, children) = mobile { XCTAssertEqual(children.map { $0.recordGUID }, ["emptyempty01", "emptyempty02"]) } else { XCTFail("Mobile isn't a folder.") } } /** * Input: * * [M] [] [M] * _______|_______ _____|_____ * / | \ / \ * [e01] [e02] [e03] [e02] [eL0] * * Expected output: * * Take remote, delete emptyemptyL0, upload the roots that * weren't remotely present. */ func testApplyingTwoEmptyFoldersMatchesOnlyOne() { guard let bookmarks = self.getSyncableBookmarks(name: "D") else { XCTFail("Couldn't get bookmarks.") return } // Insert three identical folders. We mark them with hasDupe because that's the Syncy // thing to do. let now = Date.now() let records = [ BookmarkMirrorItem.folder(BookmarkRoots.MobileFolderGUID, modified: now, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "Mobile Bookmarks", description: "", children: ["emptyempty01", "emptyempty02", "emptyempty03"]), BookmarkMirrorItem.folder("emptyempty01", modified: now, hasDupe: true, parentID: BookmarkRoots.MobileFolderGUID, parentName: "Mobile Bookmarks", title: "Empty", description: "", children: []), BookmarkMirrorItem.folder("emptyempty02", modified: now, hasDupe: true, parentID: BookmarkRoots.MobileFolderGUID, parentName: "Mobile Bookmarks", title: "Empty", description: "", children: []), BookmarkMirrorItem.folder("emptyempty03", modified: now, hasDupe: true, parentID: BookmarkRoots.MobileFolderGUID, parentName: "Mobile Bookmarks", title: "Empty", description: "", children: []), ] bookmarks.buffer.validate().succeeded() // It's valid! Empty. bookmarks.buffer.applyRecords(records).succeeded() bookmarks.buffer.validate().succeeded() // It's valid! Rooted in mobile_______. bookmarks.buffer.db.assertQueryReturns("SELECT COUNT(*) FROM \(TableBookmarksBuffer)", int: 4) bookmarks.buffer.db.assertQueryReturns("SELECT COUNT(*) FROM \(TableBookmarksBufferStructure)", int: 3) // Add one matching empty folder locally. // Add one by GUID, too. This is the most complex possible case. bookmarks.local.db.run("INSERT INTO \(TableBookmarksLocal) (guid, type, title, parentid, parentName, sync_status, local_modified) VALUES ('emptyempty02', \(BookmarkNodeType.folder.rawValue), 'Empty', '\(BookmarkRoots.MobileFolderGUID)', 'Mobile Bookmarks', \(SyncStatus.changed.rawValue), \(Date.now()))").succeeded() bookmarks.local.db.run("INSERT INTO \(TableBookmarksLocal) (guid, type, title, parentid, parentName, sync_status, local_modified) VALUES ('emptyemptyL0', \(BookmarkNodeType.folder.rawValue), 'Empty', '\(BookmarkRoots.MobileFolderGUID)', 'Mobile Bookmarks', \(SyncStatus.new.rawValue), \(Date.now()))").succeeded() bookmarks.local.db.run("INSERT INTO \(TableBookmarksLocalStructure) (parent, child, idx) VALUES ('\(BookmarkRoots.MobileFolderGUID)', 'emptyempty02', 0)").succeeded() bookmarks.local.db.run("INSERT INTO \(TableBookmarksLocalStructure) (parent, child, idx) VALUES ('\(BookmarkRoots.MobileFolderGUID)', 'emptyemptyL0', 1)").succeeded() let uploader = MockUploader() let storer = uploader.getStorer() let applier = MergeApplier(buffer: bookmarks, storage: bookmarks, client: storer, statsSession: mockStatsSessionForBookmarks(), greenLight: { true }) applier.go().succeeded() guard let mirror = bookmarks.treeForMirror().value.successValue else { XCTFail("Couldn't get mirror!") return } // After merge, the buffer and local are empty. let edgesAfter = bookmarks.treesForEdges().value.successValue! XCTAssertTrue(edgesAfter.local.isEmpty) XCTAssertTrue(edgesAfter.buffer.isEmpty) // All of the incoming records exist. XCTAssertFalse(mirror.isEmpty) XCTAssertEqual(mirror.subtrees[0].recordGUID, BookmarkRoots.RootGUID) XCTAssertNotNil(mirror.find("emptyempty01")) XCTAssertNotNil(mirror.find("emptyempty02")) XCTAssertNotNil(mirror.find("emptyempty03")) // The other roots are now in the mirror. XCTAssertTrue(BookmarkRoots.Real.every({ mirror.find($0) != nil })) // And are queued for upload. XCTAssertTrue(uploader.added.contains("toolbar")) XCTAssertTrue(uploader.added.contains("menu")) XCTAssertTrue(uploader.added.contains("unfiled")) XCTAssertFalse(uploader.added.contains("mobile")) // Structure and value didn't change. // The local record that was smushed is not present… XCTAssertNil(mirror.find("emptyemptyL0")) // … and because it was marked New, we don't bother trying to delete it. XCTAssertFalse(uploader.deletions.contains("emptyemptyL0")) guard let mobile = mirror.find(BookmarkRoots.MobileFolderGUID) else { XCTFail("No mobile folder in mirror.") return } if case let .folder(_, children) = mobile { // This order isn't strictly specified, but try to preserve the remote order if we can. XCTAssertEqual(children.map { $0.recordGUID }, ["emptyempty01", "emptyempty02", "emptyempty03"]) } else { XCTFail("Mobile isn't a folder.") } } // TODO: this test should be extended to also exercise the case of a conflict. func testLocalRecordsKeepTheirFavicon() { guard let bookmarks = self.getSyncableBookmarks(name: "E") else { XCTFail("Couldn't get bookmarks.") return } bookmarks.buffer.db.assertQueryReturns("SELECT COUNT(*) FROM \(TableBookmarksBuffer)", int: 0) bookmarks.buffer.db.assertQueryReturns("SELECT COUNT(*) FROM \(TableBookmarksBufferStructure)", int: 0) bookmarks.buffer.db.assertQueryReturns("SELECT COUNT(*) FROM \(TableBookmarksLocal)", int: 5) bookmarks.buffer.db.assertQueryReturns("SELECT COUNT(*) FROM \(TableBookmarksLocalStructure)", int: 4) bookmarks.local.db.run("INSERT INTO \(TableFavicons) (id, url, width, height, type, date) VALUES (11, 'http://example.org/favicon.ico', 16, 16, 0, \(Date.now()))").succeeded() bookmarks.local.db.run("INSERT INTO \(TableBookmarksLocal) (guid, type, title, parentid, parentName, sync_status, bmkUri, faviconID) VALUES ('somebookmark', \(BookmarkNodeType.bookmark.rawValue), 'Some Bookmark', '\(BookmarkRoots.MobileFolderGUID)', 'Mobile Bookmarks', \(SyncStatus.new.rawValue), 'http://example.org/', 11)").succeeded() bookmarks.local.db.run("INSERT INTO \(TableBookmarksLocalStructure) (parent, child, idx) VALUES ('\(BookmarkRoots.MobileFolderGUID)', 'somebookmark', 0)").succeeded() let uploader = MockUploader() let storer = uploader.getStorer() let applier = MergeApplier(buffer: bookmarks, storage: bookmarks, client: storer, statsSession: mockStatsSessionForBookmarks(), greenLight: { true }) applier.go().succeeded() // After merge, the buffer and local are empty. let edgesAfter = bookmarks.treesForEdges().value.successValue! XCTAssertTrue(edgesAfter.local.isEmpty) XCTAssertTrue(edgesAfter.buffer.isEmpty) // New record was uploaded. XCTAssertTrue(uploader.added.contains("somebookmark")) // So were all the roots, with the Sync-native names. XCTAssertTrue(uploader.added.contains("toolbar")) XCTAssertTrue(uploader.added.contains("menu")) XCTAssertTrue(uploader.added.contains("unfiled")) XCTAssertTrue(uploader.added.contains("mobile")) // … but not the Places root. XCTAssertFalse(uploader.added.contains("places")) XCTAssertFalse(uploader.added.contains(BookmarkRoots.RootGUID)) // Their parent IDs are translated. XCTAssertEqual(uploader.records["mobile"]?.payload["parentid"].string, "places") XCTAssertEqual(uploader.records["somebookmark"]?.payload["parentid"].string, "mobile") XCTAssertTrue(uploader.deletions.isEmpty) // The record looks sane. let bm = uploader.records["somebookmark"]! XCTAssertEqual("bookmark", bm.payload["type"].string) XCTAssertEqual("Some Bookmark", bm.payload["title"].string) // New record still has its icon ID in the local DB. bookmarks.local.db.assertQueryReturns("SELECT faviconID FROM \(TableBookmarksMirror) WHERE bmkUri = 'http://example.org/'", int: 11) } func testRemoteValueOnlyChange() { guard let bookmarks = self.getSyncableBookmarks(name: "F") else { XCTFail("Couldn't get bookmarks.") return } // Insert one folder and one child. let now = Date.now() let records = [ BookmarkMirrorItem.folder(BookmarkRoots.UnfiledFolderGUID, modified: now, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "Unsorted Bookmarks", description: "", children: ["folderAAAAAA"]), BookmarkMirrorItem.folder("folderAAAAAA", modified: now, hasDupe: false, parentID: BookmarkRoots.UnfiledFolderGUID, parentName: "Unsorted Bookmarks", title: "Folder A", description: "", children: ["bookmarkBBBB"]), BookmarkMirrorItem.bookmark("bookmarkBBBB", modified: now, hasDupe: false, parentID: "folderAAAAAA", parentName: "Folder A", title: "Initial Title", description: "No desc.", URI: "http://example.org/foo", tags: "", keyword: nil), ] bookmarks.buffer.validate().succeeded() // It's valid! Empty. bookmarks.buffer.applyRecords(records).succeeded() bookmarks.buffer.validate().succeeded() // It's valid! Rooted in mobile_______. bookmarks.buffer.db.assertQueryReturns("SELECT COUNT(*) FROM \(TableBookmarksBuffer)", int: 3) bookmarks.buffer.db.assertQueryReturns("SELECT COUNT(*) FROM \(TableBookmarksBufferStructure)", int: 2) let uploader = MockUploader() let storer = uploader.getStorer() let applier = MergeApplier(buffer: bookmarks, storage: bookmarks, client: storer, statsSession: mockStatsSessionForBookmarks(), greenLight: { true }) applier.go().succeeded() guard let _ = bookmarks.treeForMirror().value.successValue else { XCTFail("Couldn't get mirror!") return } // After merge, the buffer and local are empty. let edgesAfter = bookmarks.treesForEdges().value.successValue! XCTAssertTrue(edgesAfter.local.isEmpty) XCTAssertTrue(edgesAfter.buffer.isEmpty) // Check the title. let folder = bookmarks.modelFactory.value.successValue! .modelForFolder("folderAAAAAA").value.successValue!.current[0]! XCTAssertEqual(folder.title, "Initial Title") // Now process an incoming change. let changed = [ BookmarkMirrorItem.bookmark("bookmarkBBBB", modified: now, hasDupe: false, parentID: "folderAAAAAA", parentName: "Folder A", title: "New Title", description: "No desc.", URI: "http://example.org/foo", tags: "", keyword: nil), ] bookmarks.buffer.validate().succeeded() // It's valid! Empty. bookmarks.buffer.applyRecords(changed).succeeded() bookmarks.buffer.validate().succeeded() // It's valid! One record. bookmarks.buffer.db.assertQueryReturns("SELECT COUNT(*) FROM \(TableBookmarksBuffer)", int: 1) bookmarks.buffer.db.assertQueryReturns("SELECT COUNT(*) FROM \(TableBookmarksBufferStructure)", int: 0) let uu = MockUploader() let ss = uu.getStorer() let changeApplier = MergeApplier(buffer: bookmarks, storage: bookmarks, client: ss, statsSession: mockStatsSessionForBookmarks(), greenLight: { true }) changeApplier.go().succeeded() // The title changed. let updatedFolder = bookmarks.modelFactory.value.successValue! .modelForFolder("folderAAAAAA").value.successValue!.current[0]! XCTAssertEqual(updatedFolder.title, "New Title") // The buffer is empty. bookmarks.buffer.db.assertQueryReturns("SELECT COUNT(*) FROM \(TableBookmarksBuffer)", int: 0) bookmarks.buffer.db.assertQueryReturns("SELECT COUNT(*) FROM \(TableBookmarksBufferStructure)", int: 0) } } class TestMergedTree: FailFastTestCase { func testInitialState() { let children = BookmarkRoots.RootChildren.map { BookmarkTreeNode.unknown(guid: $0) } let root = BookmarkTreeNode.folder(guid: BookmarkRoots.RootGUID, children: children) let tree = MergedTree(mirrorRoot: root) XCTAssertTrue(tree.root.hasDecidedChildren) if case let .folder(guid, unmergedChildren) = tree.root.asUnmergedTreeNode() { XCTAssertEqual(guid, BookmarkRoots.RootGUID) XCTAssertEqual(unmergedChildren, children) } else { XCTFail("Root should start as Folder.") } // We haven't processed the children. XCTAssertNil(tree.root.mergedChildren) XCTAssertTrue(tree.root.asMergedTreeNode().isUnknown) // Simulate a merge. let mergedRoots = children.map { MergedTreeNode(guid: $0.recordGUID, mirror: $0, structureState: MergeState.unchanged) } tree.root.mergedChildren = mergedRoots // Now we have processed children. XCTAssertNotNil(tree.root.mergedChildren) XCTAssertFalse(tree.root.asMergedTreeNode().isUnknown) } } private extension MergedSQLiteBookmarks { func populateMirrorViaBuffer(items: [BookmarkMirrorItem], atDate mirrorDate: Timestamp) { self.applyRecords(items).succeeded() // … and add the root relationships that will be missing (we don't do those for the buffer, // so we need to manually add them and move them across). self.buffer.db.run([ "INSERT INTO \(TableBookmarksBufferStructure) (parent, child, idx) VALUES", "('\(BookmarkRoots.RootGUID)', '\(BookmarkRoots.MenuFolderGUID)', 0),", "('\(BookmarkRoots.RootGUID)', '\(BookmarkRoots.ToolbarFolderGUID)', 1),", "('\(BookmarkRoots.RootGUID)', '\(BookmarkRoots.UnfiledFolderGUID)', 2),", "('\(BookmarkRoots.RootGUID)', '\(BookmarkRoots.MobileFolderGUID)', 3)", ].joined(separator: " ")).succeeded() // Move it all to the mirror. self.local.db.moveBufferToMirrorForTesting() } func wipeLocal() { self.local.db.run(["DELETE FROM \(TableBookmarksLocalStructure)", "DELETE FROM \(TableBookmarksLocal)"]).succeeded() } }
mpl-2.0
85772ad8af7655f174a8fef090e3ca4b
50.033042
346
0.65818
4.833671
false
false
false
false
VirgilSecurity/virgil-sdk-keys-ios
Tests/Cards/VSS008_DataExtensionsTests.swift
1
2675
// // Copyright (C) 2015-2020 Virgil Security Inc. // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // (1) Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // (2) Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // // (3) Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING // IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Lead Maintainer: Virgil Security Inc. <[email protected]> // import VirgilSDK import XCTest class VSS008_DataExtensionsTests: XCTestCase { func test001_base64Url() { let base64encoded = "MFEwDQYJYIZIAWUDBAIDBQAEQJuTxlQ7r+RG2P8D12OFOdgPsIDmZMd4UBMIG1c1Amqm/oc1wRUzk7ccz1RbTWEt2XP+1GbkF0Z6s6FYf1QEUQI=" let base64UrlEncoded = "MFEwDQYJYIZIAWUDBAIDBQAEQJuTxlQ7r-RG2P8D12OFOdgPsIDmZMd4UBMIG1c1Amqm_oc1wRUzk7ccz1RbTWEt2XP-1GbkF0Z6s6FYf1QEUQI" let data = Data(base64Encoded: base64encoded)! let base64url = data.base64UrlEncodedString() XCTAssert(base64url == base64UrlEncoded) let newData = Data(base64UrlEncoded: base64url) XCTAssert(newData != nil) XCTAssert(data == newData!) } func test002_hex() { let str = "This is a test." let strHex = "54686973206973206120746573742e" XCTAssert(str.data(using: .utf8)!.hexEncodedString() == strHex) XCTAssert(String(data: Data(hexEncodedString: strHex)!, encoding: .utf8) == str) } }
bsd-3-clause
24dc182a5b0fe367c2dbde818c9afa9f
39.530303
144
0.721869
3.778249
false
true
false
false
Isahkaren/ND-OnTheMap
Helps/MyPlayground.playground/Contents.swift
1
5575
//: Playground - noun: a place where people can play import UIKit import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true class JSONUtils: NSObject { class func serialize(dictionary: [String: Any]) -> Data? { do { let jsonData = try JSONSerialization.data(withJSONObject: dictionary, options: .prettyPrinted) return jsonData } catch { // Return nil if serialization fails return nil } } class func deserialize(data: Data) -> [String: Any]? { do { let jsonDict = try JSONSerialization.jsonObject(with: data, options: .allowFragments) return jsonDict as? [String: Any] } catch { return nil } } } class ServiceResponse { var request: URLRequest? var response: URLResponse? var data: Data? var rawValue: String? var title: String? var message: String? } class ServiceManager { enum HTTPMethod: String { case get = "GET" case put = "PUT" case post = "POST" case delete = "DELETE" } class func criaRequest(url: URL, httpMethod: HTTPMethod, payload: Data? = nil, headers: [String: String]? = nil) -> URLRequest { // Cria request default var request = URLRequest(url: url) request.httpMethod = httpMethod.rawValue request.httpBody = payload // Se não existir header retorna a request default guard let headers = headers else { return request } // Se existir header adiciona e retorna a request com os headers for header in headers { request.addValue(header.value, forHTTPHeaderField: header.key) } return request } class func dispatch(request: URLRequest, onSuccess succeed: @escaping (_ serviceResponse: ServiceResponse) -> Void, onFailure failed: @escaping (_ serviceResponse: ServiceResponse) -> Void, onCompletion completed: @escaping () -> Void) { let session = URLSession.shared let task = session.dataTask(with: request) { data, response, error in let sr = ServiceResponse() sr.data = data sr.request = request guard error == nil else { sr.title = "Um error ocorreu" sr.message = "Seu deu mal" failed(sr) completed() return } guard let statusCode = (response as? HTTPURLResponse)?.statusCode else { sr.title = "Um error ocorreu" sr.message = "Seu deu mal" failed(sr) completed() return } guard 200...299 ~= statusCode else { // TODO map errors failed(sr) completed() return } guard let unData = data else { succeed(sr) completed() return } sr.rawValue = String(data: unData, encoding: .utf8) succeed(sr) completed() } task.resume() } } class UdacityServices { class func login(user: String, pass: String, onSuccess succeed: () -> Void, onFailure failed: () -> Void, onCompletion completed: () -> Void) { let url = URL(string: "https://www.udacity.com/api/session")! let params: [String: Any] = [ "udacity": [ "username": user, "password": pass ] ] let headers: [String: String] = [ "user-agen": "iOS 10.2.1; iPhone 6S" ] let request = ServiceManager.criaRequest(url: url, httpMethod: .post, payload: JSONUtils.serialize(dictionary: params), headers: headers) ServiceManager.dispatch(request: request, onSuccess: { (serviceResponse) in let data = serviceResponse.data! print(serviceResponse.rawValue!) }, onFailure: { (serviceResponse) in print(serviceResponse.title) print(serviceResponse.message) }, onCompletion: { print("completou") }) } } class MyView { var username: String? var password: String? // MARK: - IBAction func loginButton_Clicked() { username = "[email protected]" password = "123456" guard let username = username, let password = password else { // show alert print("Campos obrigatórios não preenchidos") return } login(username: username, password: password) } // MARK: - Service func login(username: String, password: String) { UdacityServices.login(user: username, pass: password, onSuccess: { }, onFailure: { }, onCompletion: { }) } } let view = MyView() view.loginButton_Clicked()
mit
5d8ff0c643d442b86680a328f62f62fe
22.216667
145
0.495154
5.236842
false
false
false
false
blstream/TOZ_iOS
TOZ_iOS/GalleryDetailViewController.swift
1
6493
// // GalleryDetailViewController.swift // TOZ_iOS // // Copyright © 2017 intive. All rights reserved. // import UIKit import Foundation class GalleryDetailViewController: UIViewController { @IBOutlet weak var animalName: UILabel! @IBOutlet weak var animalType: UILabel! @IBOutlet weak var animalSex: UILabel! @IBOutlet weak var animalDescription: UILabel! @IBOutlet weak var pictureCaption: UILabel! @IBOutlet weak var photosContainer: UIView! @IBOutlet weak var helpAnimalLabel: UILabel! @IBOutlet weak var helpAnimalAccount: UILabel! @IBOutlet weak var helpAnimalView: UIView! @IBOutlet weak var helpThisAnimalButton: Button! @IBOutlet weak var animalDescriptionDivider: UIView! var selectedCellID: String? var photoURL: URL? var photos: [URL] = [] var animalOperation: AnimalOperation? var organizationInfoOperation = OrganizationInfoOperation() var galleryDetailPhotoViewController: GalleryDetailPhotoViewController? func makeAnimalOperation() { if let selectedCellID = selectedCellID { animalOperation = AnimalOperation(animalID: selectedCellID) } else { animalOperation = nil } } override func viewDidLoad() { super.viewDidLoad() self.helpAnimalLabel.text = "Jeżeli chcesz pomóc temu zwierzakowi wyślij przelew na podany numer konta w tytule wpisując jego imię" isHelpViewHidden(hidden: true) galleryDetailPhotoViewController = storyboard?.instantiateViewController(withIdentifier: "GalleryDetailPhotoViewController") as? GalleryDetailPhotoViewController if let galleryDetailPhotoViewController = galleryDetailPhotoViewController { addChildViewController(galleryDetailPhotoViewController) galleryDetailPhotoViewController.view.translatesAutoresizingMaskIntoConstraints = false photosContainer.addSubview(galleryDetailPhotoViewController.view) NSLayoutConstraint.activate([ galleryDetailPhotoViewController.view.leadingAnchor.constraint(equalTo: photosContainer.leadingAnchor), galleryDetailPhotoViewController.view.trailingAnchor.constraint(equalTo: photosContainer.trailingAnchor), galleryDetailPhotoViewController.view.topAnchor.constraint(equalTo: photosContainer.topAnchor), galleryDetailPhotoViewController.view.bottomAnchor.constraint(equalTo: photosContainer.bottomAnchor) ]) galleryDetailPhotoViewController.didMove(toParentViewController: self) } makeAnimalOperation() getAnimal() getOrganizationInfo() _ = NotificationCenter.default.addObserver(forName: .pictureChanged, object: nil, queue: nil, using: updateCaption) } @IBAction func helpThisAnimalAction(_ sender: Any) { isHelpViewHidden(hidden: helpViewHeight == nil) } var helpViewHeight: NSLayoutConstraint? func isHelpViewHidden(hidden: Bool) { if hidden == true { helpViewHeight = NSLayoutConstraint(item: helpAnimalView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 0) if let helpViewHeight = helpViewHeight { self.view.addConstraint(helpViewHeight) helpViewHeight.isActive = true self.helpThisAnimalButton.backgroundColor = Color.Cell.Button.primary } } else { if let helpViewHeight = helpViewHeight { helpViewHeight.isActive = false self.helpViewHeight = nil self.helpThisAnimalButton.backgroundColor = Color.Cell.Button.pressed } } } func getAnimal() { animalOperation?.resultCompletion = { result in switch result { case .success(let localAnimal): DispatchQueue.main.async { self.animalName.text = localAnimal.name self.helpAnimalLabel.text = "Jeżeli chcesz pomóc temu zwierzakowi wyślij przelew na podany numer konta w tytule wpisując \"\(localAnimal.name)\"" self.navigationItem.title = localAnimal.name self.animalType.text = localAnimal.type.localizedType self.galleryDetailPhotoViewController?.animalType = localAnimal.type self.animalSex.text = localAnimal.sex.localizedSex if let localAnimalDescription = localAnimal.description { self.animalDescription.text = localAnimalDescription } else { self.animalDescriptionDivider.layer.isHidden = true } // If there is an imageURL for the Animal than add it to array of photos. if let photoURL = localAnimal.imageUrl { self.photos.append(photoURL) self.pictureCaption.text = "Zdjęcie 1 / \(self.photos.count)" } else { self.pictureCaption.text = "Brak zdjęcia" } // If there is a nonempty gallery, than overwrite 'photos' with it if let galleryURLs = localAnimal.galleryURLs { if !galleryURLs.isEmpty { self.photos = galleryURLs } } self.galleryDetailPhotoViewController?.photos = self.photos } case .failure(let error): print ("\(error)") } } animalOperation?.start() } func getOrganizationInfo() { organizationInfoOperation.resultCompletion = { result in switch result { case .success (let organizationInfo): DispatchQueue.main.async { self.helpAnimalAccount.text = organizationInfo.accountNumber } case .failure(let error): print ("\(error)") } } organizationInfoOperation.start() } func updateCaption(notification: Notification) { guard let index = notification.userInfo?["index"] else { return } if photos.count > 0 { self.pictureCaption.text = "Zdjęcie \(index) / \(photos.count)" } else { self.pictureCaption.text = "Brak zdjęcia" } } }
apache-2.0
865dd9c676cefab7c4a02ab958461031
42.483221
169
0.632814
5.225
false
false
false
false
Acidburn0zzz/firefox-ios
XCUITests/FindInPageTest.swift
1
7794
/* 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 XCTest class FindInPageTests: BaseTestCase { private func openFindInPageFromMenu() { navigator.goto(BrowserTab) waitUntilPageLoad() navigator.goto(PageOptionsMenu) navigator.goto(FindInPage) waitForExistence(app.buttons["FindInPage.find_next"], timeout: 5) waitForExistence(app.buttons["FindInPage.find_previous"], timeout: 5) XCTAssertTrue(app.textFields["FindInPage.searchField"].exists) } func testFindInLargeDoc() { navigator.openURL("http://localhost:\(serverPort)/test-fixture/find-in-page-test.html") // Workaround until FxSGraph is fixed to allow the previos way with goto navigator.nowAt(BrowserTab) waitForNoExistence(app.staticTexts["Fennec pasted from XCUITests-Runner"]) waitForExistence(app.buttons["TabLocationView.pageOptionsButton"], timeout: 15) app.buttons["TabLocationView.pageOptionsButton"].tap() waitForExistence(app.tables["Context Menu"].cells["menu-FindInPage"], timeout: 10) app.tables["Context Menu"].cells["menu-FindInPage"].tap() // Enter some text to start finding app.textFields["FindInPage.searchField"].typeText("Book") waitForExistence(app.textFields["Book"], timeout: 15) XCTAssertEqual(app.staticTexts["FindInPage.matchCount"].label, "1/500+", "The book word count does match") } // Smoketest func testFindFromMenu() { userState.url = path(forTestPage: "test-mozilla-book.html") openFindInPageFromMenu() // Enter some text to start finding app.textFields["FindInPage.searchField"].typeText("Book") // Once there are matches, test previous/next buttons waitForExistence(app.staticTexts["1/6"]) XCTAssertTrue(app.staticTexts["1/6"].exists) let nextInPageResultButton = app.buttons["FindInPage.find_next"] nextInPageResultButton.tap() waitForExistence(app.staticTexts["2/6"]) XCTAssertTrue(app.staticTexts["2/6"].exists) nextInPageResultButton.tap() waitForExistence(app.staticTexts["3/6"]) XCTAssertTrue(app.staticTexts["3/6"].exists) let previousInPageResultButton = app.buttons["FindInPage.find_previous"] previousInPageResultButton.tap() waitForExistence(app.staticTexts["2/6"]) XCTAssertTrue(app.staticTexts["2/6"].exists) previousInPageResultButton.tap() waitForExistence(app.staticTexts["1/6"]) XCTAssertTrue(app.staticTexts["1/6"].exists) // Tapping on close dismisses the search bar navigator.goto(BrowserTab) waitForNoExistence(app.textFields["Book"]) } func testFindInPageTwoWordsSearch() { userState.url = path(forTestPage: "test-mozilla-book.html") openFindInPageFromMenu() // Enter some text to start finding app.textFields["FindInPage.searchField"].typeText("The Book of") // Once there are matches, test previous/next buttons waitForExistence(app.staticTexts["1/6"]) XCTAssertTrue(app.staticTexts["1/6"].exists) } func testFindInPageTwoWordsSearchLargeDoc() { navigator.openURL("http://localhost:\(serverPort)/test-fixture/find-in-page-test.html") // Workaround until FxSGraph is fixed to allow the previos way with goto waitUntilPageLoad() navigator.nowAt(BrowserTab) waitForExistence(app/*@START_MENU_TOKEN@*/.buttons["TabLocationView.pageOptionsButton"]/*[[".buttons[\"Page Options Menu\"]",".buttons[\"TabLocationView.pageOptionsButton\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/, timeout: 15) app/*@START_MENU_TOKEN@*/.buttons["TabLocationView.pageOptionsButton"]/*[[".buttons[\"Page Options Menu\"]",".buttons[\"TabLocationView.pageOptionsButton\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap() // Enter some text to start finding app.tables["Context Menu"].cells["menu-FindInPage"].tap() app.textFields["FindInPage.searchField"].typeText("The Book of") waitForExistence(app.textFields["The Book of"], timeout: 15) XCTAssertEqual(app.staticTexts["FindInPage.matchCount"].label, "1/500+", "The book word count does match") } func testFindInPageResultsPageShowHideContent() { userState.url = "lorem2.com" openFindInPageFromMenu() // Enter some text to start finding app.textFields["FindInPage.searchField"].typeText("lorem") // There should be matches waitForExistence(app.staticTexts["1/5"]) XCTAssertTrue(app.staticTexts["1/5"].exists) } func testQueryWithNoMatches() { userState.url = path(forTestPage: "test-mozilla-book.html") openFindInPageFromMenu() // Try to find text which does not match and check that there are not results app.textFields["FindInPage.searchField"].typeText("foo") waitForExistence(app.staticTexts["0/0"]) XCTAssertTrue(app.staticTexts["0/0"].exists, "There should not be any matches") } func testBarDissapearsWhenReloading() { userState.url = path(forTestPage: "test-mozilla-book.html") openFindInPageFromMenu() // Before reloading, it is necessary to hide the keyboard app.textFields["url"].tap() app.textFields["address"].typeText("\n") // Once the page is reloaded the search bar should not appear waitForNoExistence(app.textFields[""]) XCTAssertFalse(app.textFields[""].exists) } func testBarDissapearsWhenOpeningTabsTray() { userState.url = path(forTestPage: "test-mozilla-book.html") openFindInPageFromMenu() // Dismiss keyboard app.buttons["FindInPage.close"].tap() navigator.nowAt(BrowserTab) // Going to tab tray and back to the website hides the search field. navigator.goto(TabTray) waitForExistence(app.cells.staticTexts["The Book of Mozilla"]) app.cells.staticTexts["The Book of Mozilla"].tap() XCTAssertFalse(app.textFields[""].exists) XCTAssertFalse(app.buttons["FindInPage.find_next"].exists) XCTAssertFalse(app.buttons["FindInPage.find_previous"].exists) } func testFindFromSelection() { userState.url = path(forTestPage: "test-mozilla-book.html") navigator.goto(BrowserTab) let textToFind = "from" // Long press on the word to be found waitUntilPageLoad() waitForExistence(app.webViews.staticTexts[textToFind]) let stringToFind = app.webViews.staticTexts.matching(identifier: textToFind) let firstStringToFind = stringToFind.element(boundBy: 0) firstStringToFind.press(forDuration: 3) waitForExistence(app.menuItems["Copy"], timeout: 5) // Find in page is correctly launched, bar with text pre-filled and // the buttons to find next and previous if (app.menuItems["Find in Page"].exists) { app.menuItems["Find in Page"].tap() } else { app.menuItems["show.next.items.menu.button"].tap() waitForExistence(app.menuItems["Find in Page"]) app.menuItems["Find in Page"].tap() } waitForExistence(app.textFields[textToFind]) XCTAssertTrue(app.textFields[textToFind].exists, "The bar does not appear with the text selected to be found") XCTAssertTrue(app.buttons["FindInPage.find_previous"].exists, "Find previous button exists") XCTAssertTrue(app.buttons["FindInPage.find_next"].exists, "Find next button exists") } }
mpl-2.0
4e7614d7ab5d18f6cbd15a8a7104ac61
43.537143
238
0.672697
4.59823
false
true
false
false
toshiapp/toshi-ios-client
Toshi/Controllers/Wallet/Models/Token.swift
1
3572
// Copyright (c) 2018 Token Browser, Inc // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. import Foundation /// An individual Token class Token: Codable { let name: String let symbol: String let value: String let decimals: Int let contractAddress: String let icon: String? fileprivate(set) var canShowFiatValue = false lazy var displayValueString: String = { return self.value.toDisplayValue(with: self.decimals) }() var isEtherToken: Bool { return symbol == "ETH" } enum CodingKeys: String, CodingKey { case name, symbol, value, decimals, contractAddress = "contract_address", icon } init(name: String, symbol: String, value: String, decimals: Int, contractAddress: String, iconPath: String) { self.name = name self.symbol = symbol self.value = value self.decimals = decimals self.contractAddress = contractAddress self.icon = iconPath } var localIcon: UIImage? { guard let iconName = icon else { return nil } return UIImage(named: iconName) } func convertToFiat() -> String? { return nil } } // MARK: - Ether Token /// A class which uses token to view Ether balances final class EtherToken: Token { let wei: NSDecimalNumber init(valueInWei: NSDecimalNumber) { wei = valueInWei super.init(name: Localized.wallet_ether_name, symbol: "ETH", value: wei.toHexString, decimals: 5, contractAddress: "", iconPath: AssetCatalogItem.ether_logo.rawValue) canShowFiatValue = true } override var displayValueString: String { get { return EthereumConverter.ethereumValueString(forWei: wei, withSymbol: false, fractionDigits: 6) } set { // do nothing - this is read-only since it's lazy, but the compiler doesn't think so since it's still a var. } } required init(from decoder: Decoder) throws { fatalError("init(from:) has not been implemented") } override func convertToFiat() -> String? { return EthereumConverter.fiatValueString(forWei: wei, exchangeRate: ExchangeRateClient.exchangeRate) } } /// Convenience class for decoding an array of Token with the key "tokens" final class TokenResults: Codable { let tokens: [Token] enum CodingKeys: String, CodingKey { case tokens } } // MARK: - Wallet Item extension Token: WalletItem { var title: String? { return name } var subtitle: String? { return symbol } var iconPath: String? { return icon } var details: String? { return displayValueString } var uniqueIdentifier: String { return symbol } }
gpl-3.0
1a9de47d245f02e58079f19d4141b782
24.333333
120
0.62206
4.532995
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/BlockchainComponentLibrary/Sources/BlockchainComponentLibrary/3 - Compositions/Alert.swift
1
8013
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import SwiftUI public struct Alert<TopView: View>: View { public struct Button { public enum Style { case primary, standard, destructive } let title: String let style: Style let action: () -> Void public init(title: String, style: Style, action: @escaping () -> Void) { self.title = title self.style = style self.action = action } } private let topView: () -> TopView? private let title: String? private let message: String? private let buttons: [Alert.Button] private let close: () -> Void public init( @ViewBuilder topView: @escaping () -> TopView?, title: String?, message: String?, buttons: [Alert.Button], close: @escaping () -> Void ) { self.topView = topView self.title = title self.message = message self.buttons = buttons self.close = close } public var body: some View { VStack { Spacer() VStack(spacing: Spacing.padding2) { HStack { Spacer() Icon.closeCirclev2 .frame(width: 24, height: 24) .onTapGesture(perform: close) } // The check for EmptyView is not ideal but // returning a nil TopView doesn't compile. // This might be related to a bug fixed in Swift 5.4: https://forums.swift.org/t/nil-requires-contextual-type-swiftui-function-builder-bug/46915 if let topView = topView(), !(topView is EmptyView) { topView } if title != nil || message != nil { VStack(spacing: Spacing.padding1) { if let title = title { Text(title) .typography(.title3) .foregroundColor(.semantic.title) } if let message = message { Text(message) .typography(.paragraph1) .foregroundColor(.semantic.body) } } .fixedSize(horizontal: false, vertical: true) } VStack(spacing: Spacing.padding1) { ForEach(buttons, id: \.title) { button in buttonView(for: button) } } .padding(.top, Spacing.padding1) } .multilineTextAlignment(.center) .padding(Spacing.padding2) .background( RoundedRectangle(cornerRadius: Spacing.containerBorderRadius) .fill(Color.semantic.background) ) .frame(maxWidth: 320) .padding(Spacing.padding3) Spacer() } .frame(maxWidth: .infinity) .background(Color.semantic.fadedBackground) .ignoresSafeArea() } @ViewBuilder private func buttonView(for button: Alert.Button) -> some View { switch button.style { case .primary: PrimaryButton(title: button.title, action: button.action) case .standard: MinimalButton(title: button.title, action: button.action) case .destructive: DestructivePrimaryButton(title: button.title, action: button.action) } } } extension Alert where TopView == EmptyView { public init( title: String?, message: String?, buttons: [Alert.Button], close: @escaping () -> Void ) { self.init( topView: EmptyView.init, // using a closure returning nil doesn't compile title: title, message: message, buttons: buttons, close: close ) } } struct Alert_Previews: PreviewProvider { static var previews: some View { // swiftlint:disable line_length Group { Alert( topView: { Icon.blockchain .frame(width: 24, height: 24) }, title: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", message: "Etiam pharetra, velit vitae convallis elementum, velit ex efficitur justo, et hendrerit lorem turpis dignissim augue.", buttons: [ Alert.Button( title: "Primary Button", style: .primary, action: {} ), Alert.Button( title: "Standard Button", style: .standard, action: {} ), Alert.Button( title: "Destructive Button", style: .destructive, action: {} ) ], close: {} ) } Group { Alert( title: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", message: "Etiam pharetra, velit vitae convallis elementum, velit ex efficitur justo, et hendrerit lorem turpis dignissim augue.", buttons: [ Alert.Button( title: "Primary Button", style: .primary, action: {} ), Alert.Button( title: "Standard Button", style: .standard, action: {} ), Alert.Button( title: "Destructive Button", style: .destructive, action: {} ) ], close: {} ) } Group { Alert( title: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", message: "Etiam pharetra, velit vitae convallis elementum, velit ex efficitur justo, et hendrerit lorem turpis dignissim augue.", buttons: [], close: {} ) } Group { Alert( title: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", message: nil, buttons: [ Alert.Button( title: "Primary Button", style: .primary, action: {} ) ], close: {} ) } Group { Alert( title: nil, message: "Etiam pharetra, velit vitae convallis elementum, velit ex efficitur justo, et hendrerit lorem turpis dignissim augue.", buttons: [ Alert.Button( title: "Primary Button", style: .primary, action: {} ) ], close: {} ) } Group { Alert( title: nil, message: nil, buttons: [ Alert.Button( title: "Primary Button", style: .primary, action: {} ) ], close: {} ) } Group { Alert( title: nil, message: nil, buttons: [], close: {} ) } // swiftlint:enable line_length } }
lgpl-3.0
f57aabff68f586b4c91b4969d0b1dd2f
30.296875
160
0.430729
5.743369
false
false
false
false
simonnarang/Fandom
Desktop/Fandom-IOS-master/Fandomm/ShareCameraViewController.swift
1
1218
// // ShareCameraViewController.swift // Fandomm // // Created by Simon Narang on 12/21/15. // Copyright © 2015 Simon Narang. All rights reserved. // import UIKit import AVFoundation class ShareCameraViewController: UIViewController, /* For capturing barcodes */AVCaptureMetadataOutputObjectsDelegate { let captureSession = AVCaptureSession() var previewLayer : AVCaptureVideoPreviewLayer? var captureDevice : AVCaptureDevice? override func viewDidLoad() { super.viewDidLoad() captureSession.sessionPreset = AVCaptureSessionPresetHigh let devices = AVCaptureDevice.devices() func beginSession() { } for device in devices { if (device.hasMediaType(AVMediaTypeVideo)) { if(device.position == AVCaptureDevicePosition.Back) { captureDevice = device as? AVCaptureDevice if captureDevice != nil { print("Capture device found") beginSession() } } } } } @IBAction func sup(sender: AnyObject) { performSegueWithIdentifier("segueFour", sender: nil) } }
unlicense
c753b26191bb2cf2bb4d8ebe154e51f7
31.052632
119
0.611339
5.822967
false
false
false
false
volodg/iAsync.social
Pods/iAsync.utils/iAsync.utils/String/NSString+Search.swift
3
1980
// // NSString+Search.swift // JUtils // // Created by Vladimir Gorbenko on 06.06.14. // Copyright (c) 2014 EmbeddedSources. All rights reserved. // import Foundation public extension NSString { private func numberofOccurencesWithRangeSearcher( @noescape rangeSearcher: (NSRange) -> NSRange, step: Int) -> Int { var result = 0 var searchRange = NSMakeRange(0, length) var range = rangeSearcher(searchRange) while range.location != Foundation.NSNotFound { ++result searchRange.location = range.location + step searchRange.length = length - searchRange.location if searchRange.location >= length { break } range = rangeSearcher(searchRange) } return result } func numberOfCharacterFromString(string: String) -> Int { let set = NSCharacterSet(charactersInString: string) let rangeSearcher = { (rangeToSearch: NSRange) -> NSRange in return self.rangeOfCharacterFromSet(set, options: .LiteralSearch, range: rangeToSearch) } return numberofOccurencesWithRangeSearcher(rangeSearcher, step: 1) } func numberOfStringsFromString(string: String) -> Int { let rangeSearcher = { (rangeToSearch: NSRange) -> NSRange in return self.rangeOfString(string, options: .LiteralSearch, range: rangeToSearch) } let nsStringLength = (string as NSString).length return numberofOccurencesWithRangeSearcher(rangeSearcher, step: nsStringLength) } func caseInsensitiveContainsString(string: String) -> Bool { let range = self.rangeOfString(string, options: .CaseInsensitiveSearch, range: NSMakeRange(0, length)) return range.location != Foundation.NSNotFound } }
mit
92f874ad904723da45dc07b8bee458d4
29.9375
110
0.610101
5.336927
false
false
false
false
linkedin/LayoutKit
LayoutKitTests/LayoutArrangementTests.swift
1
6784
// Copyright 2016 LinkedIn Corp. // 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. import XCTest import LayoutKit class LayoutArrangementTests: XCTestCase { func testMakeViewsSingle() { let layout = SizeLayout<View>(width: 50, height: 50) let view = layout.arrangement().makeViews() XCTAssertTrue(view.subviews.isEmpty) XCTAssertEqual(view.frame, CGRect(x: 0, y: 0, width: 50, height: 50)) } func testMakeViewsMultiple() { let insets = EdgeInsets(top: 10, left: 10, bottom: 10, right: 10) let layout1 = InsetLayout(insets: insets, sublayout: SizeLayout<View>(width: 50, height: 50) { _ in }) let layout2 = InsetLayout(insets: insets, sublayout: SizeLayout<View>(width: 50, height: 50) { _ in }) let stack = StackLayout(axis: .horizontal, sublayouts: [layout1, layout2]) let view = stack.arrangement(origin: CGPoint(x: 1, y: 2)).makeViews() XCTAssertEqual(view.frame, CGRect(x: 1, y: 2, width: 140, height: 70)) XCTAssertEqual(view.subviews.count, 2) XCTAssertEqual(view.subviews[0].frame, CGRect(x: 10, y: 10, width: 50, height: 50)) XCTAssertEqual(view.subviews[1].frame, CGRect(x: 80, y: 10, width: 50, height: 50)) } func testMakeViewsDifferentCalls() { var createdView: View? let sublayout0 = SizeLayout<View>(width: 50, height: 50, viewReuseId: "someID" ) { view in createdView = view } let sublayout1 = SizeLayout<View>(width: 50, height: 50, viewReuseId: "otherID" ) { _ in } let stackLayout = StackLayout(axis: .vertical, sublayouts: [sublayout0, sublayout1]) let arrangement = stackLayout.arrangement() let hostView = View() hostView.addSubview(arrangement.makeViews()) let firstView = createdView arrangement.makeViews(in: hostView) let secondView = createdView XCTAssertTrue(firstView == secondView) } func testSubviewOrderIsStable() { // Forces the SizeLayout to produce a view. let forceViewConfig: (View) -> Void = { _ in } let top = SizeLayout(width: 5, height: 10, config: forceViewConfig) let middle = SizeLayout(width: 5, height: 20, viewReuseId: "middle", config: forceViewConfig) let bottom = SizeLayout(width: 5, height: 30, config: forceViewConfig) let stack = StackLayout(axis: .vertical, sublayouts: [top, middle, bottom]) let container = View() stack.arrangement().makeViews(in: container) XCTAssertEqual(container.subviews[0].frame, CGRect(x: 0, y: 0, width: 5, height: 10)) XCTAssertEqual(container.subviews[1].frame, CGRect(x: 0, y: 10, width: 5, height: 20)) XCTAssertEqual(container.subviews[2].frame, CGRect(x: 0, y: 30, width: 5, height: 30)) // Make sure that if we apply the same layout again that the views stay in the same order // even if some views are reused and others are not. stack.arrangement().makeViews(in: container) XCTAssertEqual(container.subviews[0].frame, CGRect(x: 0, y: 0, width: 5, height: 10)) XCTAssertEqual(container.subviews[1].frame, CGRect(x: 0, y: 10, width: 5, height: 20)) XCTAssertEqual(container.subviews[2].frame, CGRect(x: 0, y: 30, width: 5, height: 30)) } func testAnimation() { let forceViewConfig: (View) -> Void = { _ in } var redSquare: View? = nil let before = InsetLayout( inset: 10, sublayout: StackLayout( axis: .vertical, distribution: .fillEqualSpacing, sublayouts: [ SizeLayout<View>( width: 100, height: 100, alignment: .topLeading, viewReuseId: "bigSquare", sublayout: SizeLayout<View>( width: 10, height: 10, alignment: .bottomTrailing, viewReuseId: "redSquare", config: { view in redSquare = view } ), config: forceViewConfig ), SizeLayout<View>( width: 80, height: 80, alignment: .bottomTrailing, viewReuseId: "littleSquare", config: forceViewConfig ) ] ) ) let after = InsetLayout( inset: 10, sublayout: StackLayout( axis: .vertical, distribution: .fillEqualSpacing, sublayouts: [ SizeLayout<View>( width: 100, height: 100, alignment: .topLeading, viewReuseId: "bigSquare", config: forceViewConfig ), SizeLayout<View>( width: 50, height: 50, alignment: .bottomTrailing, viewReuseId: "littleSquare", sublayout: SizeLayout<View>( width: 20, height: 20, alignment: .topLeading, viewReuseId: "redSquare", config: { view in redSquare = view } ), config: forceViewConfig ) ] ) ) let rootView = View(frame: CGRect(x: 0, y: 0, width: 250, height: 250)) before.arrangement(width: 250, height: 250).makeViews(in: rootView) XCTAssertEqual(redSquare?.frame, CGRect(x: 90, y: 90, width: 10, height: 10)) let animation = after.arrangement(width: 250, height: 250).prepareAnimation(for: rootView, direction: .rightToLeft) XCTAssertEqual(redSquare?.frame, CGRect(x: -60, y: -60, width: 10, height: 10)) animation.apply() XCTAssertEqual(redSquare?.frame, CGRect(x: 30, y: 0, width: 20, height: 20)) } }
apache-2.0
ed1ce3193ae82d85b99af2a12b93eda6
43.927152
131
0.540684
4.637047
false
true
false
false
NocturneZX/TTT-Pre-Internship-Exercises
Swift/class 15/Gravity/Gravity/ViewController.swift
1
2353
// // ViewController.swift // Gravity // // Created by Oren Goldberg on 9/2/14. // Copyright (c) 2014 TurnToTech. All rights reserved. // import UIKit import MapKit class ViewController: UIViewController, UICollisionBehaviorDelegate { @IBOutlet var mainView: UIView! @IBOutlet weak var fallingLabel: UILabel! @IBOutlet weak var square2: UIImageView! @IBOutlet weak var square3: UIImageView! @IBOutlet weak var square4: UIImageView! @IBOutlet weak var slider: UISlider! @IBOutlet weak var boolSwitch: UISwitch! @IBOutlet var stableLabel: UILabel! @IBOutlet weak var mapDisplay: MKMapView! @IBOutlet weak var stepperControl: UIStepper! @IBOutlet weak var segmentedControl: UISegmentedControl! var animator:UIDynamicAnimator? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. animator = UIDynamicAnimator(referenceView: self.view) var items = [self.fallingLabel, self.square2,self.square3,self.square4,self.slider,self.boolSwitch, self.mapDisplay, self.stepperControl] var items2 = [self.fallingLabel, self.square2,self.square3,self.square4, self.slider, self.boolSwitch, self.stepperControl, self.stableLabel] var gravityBehavior : UIGravityBehavior = UIGravityBehavior(items: items) gravityBehavior.gravityDirection = CGVectorMake(0,0) animator?.addBehavior(gravityBehavior) var collisionBehavior : UICollisionBehavior = UICollisionBehavior(items: items2) collisionBehavior.translatesReferenceBoundsIntoBoundary = true animator?.addBehavior(collisionBehavior) } @IBAction func upDownSwitch(sender: AnyObject) { var gravity:UIGravityBehavior = animator?.behaviors[0] as UIGravityBehavior switch segmentedControl.selectedSegmentIndex { case 0: gravity.gravityDirection = CGVectorMake(0,-1) case 1: gravity.gravityDirection = CGVectorMake(0, 1) default: break } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
gpl-2.0
5198382ddf0a2003e8c49643cd2b280e
32.140845
149
0.677008
5.017058
false
false
false
false
paulz/ImageCoordinateSpace
ImageCoordinateSpace/SizeTransformer.swift
1
946
// // SizeTransformer.swift // ImageCoordinateSpace // // Created by Paul Zabelin on 3/10/19. // struct SizeTransformer { let boundsSize, contentSize: CGSize func isIdentity() -> Bool { return boundsSize == contentSize } func scaleToFill() -> CGAffineTransform { return .init(scaleTo: boundsSize, from: contentSize) } func translateAndScale(by factor: SizeFactor = SizeFactor(height: .center, width: .center), sizeScale scale: CGFloat = 1.0) -> CGAffineTransform { return .init(translation: factor.axesPathMap { path, factorValue in factorValue * (boundsSize[keyPath: path] - contentSize[keyPath: path] * scale) }) } func centerAndScale(using reduce: (CGFloat, CGFloat) -> CGFloat) -> CGAffineTransform { let scale = scaleToFill().scale(using: reduce) return translateAndScale(sizeScale: scale).scaledBy(scale) } }
mit
6ce137ab8e2e0cee3882230c79310b96
30.533333
95
0.650106
4.462264
false
false
false
false
stonegithubs/actor-platform
actor-apps/app-ios/ActorApp/Controllers/Conversation/Cells/BubbleBackgroundProcessor.swift
1
6175
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import Foundation class BubbleBackgroundProcessor: NSObject, ARBackgroundProcessor { let layoutCache: LayoutCache = LayoutCache() func processInBackgroundWithId(item: AnyObject!) { var message = item as! ACMessage Actor.getUserWithUid(message.senderId) var cached = layoutCache.pick(message.rid) if (cached != nil) { return } println("process \(message.rid)") var layout = MessagesLayouting.buildLayout(message, layoutCache: layoutCache) self.layoutCache.cache(message.rid, layout: layout) } } class ListProcessor: NSObject, ARListProcessor { let layoutCache: LayoutCache let isGroup: Bool init(layoutCache: LayoutCache, isGroup: Bool) { self.layoutCache = layoutCache self.isGroup = isGroup } func processWithItems(items: JavaUtilList!, withPrevious previous: AnyObject!) -> AnyObject! { var objs = [ACMessage]() var indexes = [jlong: Int]() for i in 0..<items.size() { var msg = items.getWithInt(i) as! ACMessage indexes.updateValue(Int(i), forKey: msg.rid) objs.append(msg) } var settings = [CellSetting]() for i in 0..<objs.count { settings.append(buildCellSetting(i, items: objs)) } var layouts = [CellLayout]() for i in 0..<objs.count { layouts.append(MessagesLayouting.buildLayout(objs[i], layoutCache: layoutCache)) } var heights = [CGFloat]() for i in 0..<objs.count { heights.append(buildHeight(i, items: objs, settings: settings)) } var forceUpdates = [Bool]() var updates = [Bool]() if let prevList = previous as? PreprocessedList { for i in 0..<objs.count { var obj = objs[i] var oldIndex = prevList.indexMap[obj.rid] if oldIndex != nil { var oldSetting = prevList.cellSettings[oldIndex!] var setting = settings[i] if setting.clenchTop != oldSetting.clenchTop || setting.clenchBottom != oldSetting.clenchBottom || setting.showDate != oldSetting.showDate { if setting.showDate != oldSetting.showDate { forceUpdates.append(true) updates.append(false) } else { forceUpdates.append(false) updates.append(true) } } else { forceUpdates.append(false) updates.append(false) } } else { forceUpdates.append(false) updates.append(false) } } } else { for i in 0..<objs.count { forceUpdates.append(false) updates.append(false) } } var res = PreprocessedList() res.items = objs res.cellSettings = settings res.layouts = layouts res.layoutCache = layoutCache res.heights = heights res.indexMap = indexes res.forceUpdated = forceUpdates res.updated = updates return res } func buildCellSetting(index: Int, items: [ACMessage]) -> CellSetting { var current = items[index] var next: ACMessage! = index > 0 ? items[index - 1] : nil var prev: ACMessage! = index + 1 < items.count ? items[index + 1] : nil var isShowDate = true var isShowDateNext = true var clenchTop = false var clenchBottom = false if (prev != nil) { isShowDate = !areSameDate(current, prev: prev) if !isShowDate { clenchTop = useCompact(current, next: prev) } } if (next != nil) { if areSameDate(next, prev: current) { clenchBottom = useCompact(current, next: next) } } return CellSetting(showDate: isShowDate, clenchTop: clenchTop, clenchBottom: clenchBottom) } func areSameDate(source:ACMessage, prev: ACMessage) -> Bool { let calendar = NSCalendar.currentCalendar() var currentDate = NSDate(timeIntervalSince1970: Double(source.date)/1000.0) var currentDateComp = calendar.components(.CalendarUnitDay | .CalendarUnitYear | .CalendarUnitMonth, fromDate: currentDate) var nextDate = NSDate(timeIntervalSince1970: Double(prev.date)/1000.0) var nextDateComp = calendar.components(.CalendarUnitDay | .CalendarUnitYear | .CalendarUnitMonth, fromDate: nextDate) return (currentDateComp.year == nextDateComp.year && currentDateComp.month == nextDateComp.month && currentDateComp.day == nextDateComp.day) } func useCompact(source: ACMessage, next: ACMessage) -> Bool { if (source.content is ACServiceContent) { if (next.content is ACServiceContent) { return true } } else { if (next.content is ACServiceContent) { return false } if (source.senderId == next.senderId) { return true } } return false } func buildHeight(index: Int, items: [ACMessage], settings: [CellSetting]) -> CGFloat { var message = items[index] var setting = settings[index] return MessagesLayouting.measureHeight(message, group: isGroup, setting: setting, layoutCache: layoutCache) } } @objc class PreprocessedList { var items: [ACMessage]! var cellSettings: [CellSetting]! var layouts: [CellLayout]! var layoutCache: LayoutCache! var heights: [CGFloat]! var forceUpdated: [Bool]! var updated: [Bool]! var indexMap: [jlong: Int]! }
mit
fae84da44bee2d6b55f29dfedaf8dc49
33.502793
160
0.553198
4.955859
false
false
false
false
pidjay/SideMenu
Pod/Classes/SideMenuTransition.swift
1
24059
// // SideMenuTransition.swift // Pods // // Created by Jon Kent on 1/14/16. // // import UIKit open class SideMenuTransition: UIPercentDrivenInteractiveTransition, UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate { fileprivate var presenting = false fileprivate var interactive = false fileprivate static weak var originalSuperview: UIView? fileprivate static var switchMenus = false internal static let singleton = SideMenuTransition() internal static var presentDirection: UIRectEdge = .left; internal static weak var tapView: UIView? internal static weak var statusBarView: UIView? // prevent instantiation fileprivate override init() {} fileprivate class var viewControllerForPresentedMenu: UIViewController? { get { return SideMenuManager.menuLeftNavigationController?.presentingViewController != nil ? SideMenuManager.menuLeftNavigationController?.presentingViewController : SideMenuManager.menuRightNavigationController?.presentingViewController } } fileprivate class var visibleViewController: UIViewController? { get { return getVisibleViewControllerFromViewController(UIApplication.shared.keyWindow?.rootViewController) } } fileprivate class func getVisibleViewControllerFromViewController(_ viewController: UIViewController?) -> UIViewController? { if let navigationController = viewController as? UINavigationController { return getVisibleViewControllerFromViewController(navigationController.visibleViewController) } else if let tabBarController = viewController as? UITabBarController { return getVisibleViewControllerFromViewController(tabBarController.selectedViewController) } else if let presentedViewController = viewController?.presentedViewController { return getVisibleViewControllerFromViewController(presentedViewController) } return viewController } internal class func handlePresentMenuLeftScreenEdge(_ edge: UIScreenEdgePanGestureRecognizer) { SideMenuTransition.presentDirection = .left handlePresentMenuPan(edge) } internal class func handlePresentMenuRightScreenEdge(_ edge: UIScreenEdgePanGestureRecognizer) { SideMenuTransition.presentDirection = .right handlePresentMenuPan(edge) } internal class func handlePresentMenuPan(_ pan: UIPanGestureRecognizer) { if !SideMenuManager.menuEnableSwipeGestures { return } // how much distance have we panned in reference to the parent view? guard let view = viewControllerForPresentedMenu != nil ? viewControllerForPresentedMenu?.view : pan.view else { return } let transform = view.transform view.transform = CGAffineTransform.identity let translation = pan.translation(in: pan.view!) view.transform = transform // do some math to translate this to a percentage based value if !singleton.interactive { if translation.x == 0 { return // not sure which way the user is swiping yet, so do nothing } if !(pan is UIScreenEdgePanGestureRecognizer) { SideMenuTransition.presentDirection = translation.x > 0 ? .left : .right } if let menuViewController = SideMenuTransition.presentDirection == .left ? SideMenuManager.menuLeftNavigationController : SideMenuManager.menuRightNavigationController, let visibleViewController = visibleViewController { singleton.interactive = true visibleViewController.present(menuViewController, animated: true, completion: nil) } } let direction: CGFloat = SideMenuTransition.presentDirection == .left ? 1 : -1 let distance = translation.x / SideMenuManager.menuWidth // now lets deal with different states that the gesture recognizer sends switch (pan.state) { case .began, .changed: if pan is UIScreenEdgePanGestureRecognizer { singleton.update(min(distance * direction, 1)) } else if distance > 0 && SideMenuTransition.presentDirection == .right && SideMenuManager.menuLeftNavigationController != nil { SideMenuTransition.presentDirection = .left switchMenus = true singleton.cancel() } else if distance < 0 && SideMenuTransition.presentDirection == .left && SideMenuManager.menuRightNavigationController != nil { SideMenuTransition.presentDirection = .right switchMenus = true singleton.cancel() } else { singleton.update(min(distance * direction, 1)) } default: singleton.interactive = false view.transform = CGAffineTransform.identity let velocity = pan.velocity(in: pan.view!).x * direction view.transform = transform if velocity >= 100 || velocity >= -50 && abs(distance) >= 0.5 { // bug workaround: animation briefly resets after call to finishInteractiveTransition() but before animateTransition completion is called. if ProcessInfo().operatingSystemVersion.majorVersion == 8 && singleton.percentComplete > 1 - CGFloat(FLT_EPSILON) { singleton.update(0.9999) } singleton.finish() } else { singleton.cancel() } } } internal class func handleHideMenuPan(_ pan: UIPanGestureRecognizer) { if !SideMenuManager.menuEnableSwipeGestures { return } let translation = pan.translation(in: pan.view!) let direction:CGFloat = SideMenuTransition.presentDirection == .left ? -1 : 1 let distance = translation.x / SideMenuManager.menuWidth * direction switch (pan.state) { case .began: singleton.interactive = true viewControllerForPresentedMenu?.dismiss(animated: true, completion: nil) case .changed: singleton.update(max(min(distance, 1), 0)) default: singleton.interactive = false let velocity = pan.velocity(in: pan.view!).x * direction if velocity >= 100 || velocity >= -50 && distance >= 0.5 { // bug workaround: animation briefly resets after call to finishInteractiveTransition() but before animateTransition completion is called. if ProcessInfo().operatingSystemVersion.majorVersion == 8 && singleton.percentComplete > 1 - CGFloat(FLT_EPSILON) { singleton.update(0.9999) } singleton.finish() } else { singleton.cancel() } } } internal class func handleHideMenuTap(_ tap: UITapGestureRecognizer) { viewControllerForPresentedMenu?.dismiss(animated: true, completion: nil) } internal class func hideMenuStart() { NotificationCenter.default.removeObserver(SideMenuTransition.singleton) guard let mainViewController = SideMenuTransition.viewControllerForPresentedMenu, let menuView = SideMenuTransition.presentDirection == .left ? SideMenuManager.menuLeftNavigationController?.view : SideMenuManager.menuRightNavigationController?.view else {return} menuView.transform = CGAffineTransform.identity mainViewController.view.transform = CGAffineTransform.identity mainViewController.view.alpha = 1 SideMenuTransition.tapView?.frame = CGRect(x: 0, y: 0, width: mainViewController.view.frame.width, height: mainViewController.view.frame.height) menuView.frame.origin.y = 0 menuView.frame.size.width = SideMenuManager.menuWidth menuView.frame.size.height = mainViewController.view.frame.height SideMenuTransition.statusBarView?.frame = UIApplication.shared.statusBarFrame SideMenuTransition.statusBarView?.alpha = 0 switch SideMenuManager.menuPresentMode { case .viewSlideOut: menuView.alpha = 1 - SideMenuManager.menuAnimationFadeStrength menuView.frame.origin.x = SideMenuTransition.presentDirection == .left ? 0 : mainViewController.view.frame.width - SideMenuManager.menuWidth mainViewController.view.frame.origin.x = 0 menuView.transform = CGAffineTransform(scaleX: SideMenuManager.menuAnimationTransformScaleFactor, y: SideMenuManager.menuAnimationTransformScaleFactor) case .viewSlideInOut: menuView.alpha = 1 menuView.frame.origin.x = SideMenuTransition.presentDirection == .left ? -menuView.frame.width : mainViewController.view.frame.width mainViewController.view.frame.origin.x = 0 case .menuSlideIn: menuView.alpha = 1 menuView.frame.origin.x = SideMenuTransition.presentDirection == .left ? -menuView.frame.width : mainViewController.view.frame.width case .menuDissolveIn: menuView.alpha = 0 menuView.frame.origin.x = SideMenuTransition.presentDirection == .left ? 0 : mainViewController.view.frame.width - SideMenuManager.menuWidth mainViewController.view.frame.origin.x = 0 } } internal class func hideMenuComplete() { guard let mainViewController = SideMenuTransition.viewControllerForPresentedMenu, let menuView = SideMenuTransition.presentDirection == .left ? SideMenuManager.menuLeftNavigationController?.view : SideMenuManager.menuRightNavigationController?.view else { return } SideMenuTransition.tapView?.removeFromSuperview() SideMenuTransition.statusBarView?.removeFromSuperview() mainViewController.view.motionEffects.removeAll() mainViewController.view.layer.shadowOpacity = 0 menuView.layer.shadowOpacity = 0 if let topNavigationController = mainViewController as? UINavigationController { topNavigationController.interactivePopGestureRecognizer!.isEnabled = true } originalSuperview?.addSubview(mainViewController.view) } internal class func presentMenuStart(forSize size: CGSize = SideMenuManager.appScreenRect.size) { guard let menuView = SideMenuTransition.presentDirection == .left ? SideMenuManager.menuLeftNavigationController?.view : SideMenuManager.menuRightNavigationController?.view, let mainViewController = SideMenuTransition.viewControllerForPresentedMenu else { return } menuView.transform = CGAffineTransform.identity mainViewController.view.transform = CGAffineTransform.identity menuView.frame.size.width = SideMenuManager.menuWidth menuView.frame.size.height = size.height menuView.frame.origin.x = SideMenuTransition.presentDirection == .left ? 0 : size.width - SideMenuManager.menuWidth SideMenuTransition.statusBarView?.frame = UIApplication.shared.statusBarFrame SideMenuTransition.statusBarView?.alpha = 1 switch SideMenuManager.menuPresentMode { case .viewSlideOut: menuView.alpha = 1 let direction:CGFloat = SideMenuTransition.presentDirection == .left ? 1 : -1 mainViewController.view.frame.origin.x = direction * (menuView.frame.width) mainViewController.view.layer.shadowColor = SideMenuManager.menuShadowColor.cgColor mainViewController.view.layer.shadowRadius = SideMenuManager.menuShadowRadius mainViewController.view.layer.shadowOpacity = SideMenuManager.menuShadowOpacity mainViewController.view.layer.shadowOffset = CGSize(width: 0, height: 0) case .viewSlideInOut: menuView.alpha = 1 mainViewController.view.layer.shadowColor = SideMenuManager.menuShadowColor.cgColor mainViewController.view.layer.shadowRadius = SideMenuManager.menuShadowRadius mainViewController.view.layer.shadowOpacity = SideMenuManager.menuShadowOpacity mainViewController.view.layer.shadowOffset = CGSize(width: 0, height: 0) let direction:CGFloat = SideMenuTransition.presentDirection == .left ? 1 : -1 mainViewController.view.frame = CGRect(x: direction * (menuView.frame.width), y: 0, width: size.width, height: size.height) mainViewController.view.transform = CGAffineTransform(scaleX: SideMenuManager.menuAnimationTransformScaleFactor, y: SideMenuManager.menuAnimationTransformScaleFactor) mainViewController.view.alpha = 1 - SideMenuManager.menuAnimationFadeStrength case .menuSlideIn, .menuDissolveIn: menuView.alpha = 1 if SideMenuManager.menuBlurEffectStyle == nil { menuView.layer.shadowColor = SideMenuManager.menuShadowColor.cgColor menuView.layer.shadowRadius = SideMenuManager.menuShadowRadius menuView.layer.shadowOpacity = SideMenuManager.menuShadowOpacity menuView.layer.shadowOffset = CGSize(width: 0, height: 0) } mainViewController.view.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height) mainViewController.view.transform = CGAffineTransform(scaleX: SideMenuManager.menuAnimationTransformScaleFactor, y: SideMenuManager.menuAnimationTransformScaleFactor) mainViewController.view.alpha = 1 - SideMenuManager.menuAnimationFadeStrength } } internal class func presentMenuComplete() { NotificationCenter.default.addObserver(SideMenuTransition.singleton, selector:#selector(SideMenuTransition.applicationDidEnterBackgroundNotification), name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil) guard let mainViewController = SideMenuTransition.viewControllerForPresentedMenu else { return } switch SideMenuManager.menuPresentMode { case .menuSlideIn, .menuDissolveIn, .viewSlideInOut: if SideMenuManager.menuParallaxStrength != 0 { let horizontal = UIInterpolatingMotionEffect(keyPath: "center.x", type: .tiltAlongHorizontalAxis) horizontal.minimumRelativeValue = -SideMenuManager.menuParallaxStrength horizontal.maximumRelativeValue = SideMenuManager.menuParallaxStrength let vertical = UIInterpolatingMotionEffect(keyPath: "center.y", type: .tiltAlongVerticalAxis) vertical.minimumRelativeValue = -SideMenuManager.menuParallaxStrength vertical.maximumRelativeValue = SideMenuManager.menuParallaxStrength let group = UIMotionEffectGroup() group.motionEffects = [horizontal, vertical] mainViewController.view.addMotionEffect(group) } case .viewSlideOut: break; } if let topNavigationController = mainViewController as? UINavigationController { topNavigationController.interactivePopGestureRecognizer!.isEnabled = false } } // MARK: UIViewControllerAnimatedTransitioning protocol methods // animate a change from one viewcontroller to another open func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { // get reference to our fromView, toView and the container view that we should perform the transition in let container = transitionContext.containerView if let menuBackgroundColor = SideMenuManager.menuAnimationBackgroundColor { container.backgroundColor = menuBackgroundColor } // create a tuple of our screens let screens : (from:UIViewController, to:UIViewController) = (transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)!, transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)!) // assign references to our menu view controller and the 'bottom' view controller from the tuple // remember that our menuViewController will alternate between the from and to view controller depending if we're presenting or dismissing let menuViewController = (!presenting ? screens.from : screens.to) let topViewController = !presenting ? screens.to : screens.from let menuView = menuViewController.view let topView = topViewController.view // prepare menu items to slide in if presenting { var tapView: UIView? if !SideMenuManager.menuPresentingViewControllerUserInteractionEnabled { tapView = UIView() tapView!.autoresizingMask = [.flexibleHeight, .flexibleWidth] let exitPanGesture = UIPanGestureRecognizer() exitPanGesture.addTarget(SideMenuTransition.self, action:#selector(SideMenuTransition.handleHideMenuPan(_:))) let exitTapGesture = UITapGestureRecognizer() exitTapGesture.addTarget(SideMenuTransition.self, action: #selector(SideMenuTransition.handleHideMenuTap(_:))) tapView!.addGestureRecognizer(exitPanGesture) tapView!.addGestureRecognizer(exitTapGesture) SideMenuTransition.tapView = tapView } SideMenuTransition.originalSuperview = topView?.superview // add the both views to our view controller switch SideMenuManager.menuPresentMode { case .viewSlideOut, .viewSlideInOut: container.addSubview(menuView!) container.addSubview(topView!) if let tapView = tapView { topView?.addSubview(tapView) } case .menuSlideIn, .menuDissolveIn: container.addSubview(topView!) if let tapView = tapView { container.addSubview(tapView) } container.addSubview(menuView!) } if SideMenuManager.menuFadeStatusBar { let blackBar = UIView() if let menuShrinkBackgroundColor = SideMenuManager.menuAnimationBackgroundColor { blackBar.backgroundColor = menuShrinkBackgroundColor } else { blackBar.backgroundColor = UIColor.black } blackBar.isUserInteractionEnabled = false container.addSubview(blackBar) SideMenuTransition.statusBarView = blackBar } SideMenuTransition.hideMenuStart() // offstage for interactive } // perform the animation! let duration = transitionDuration(using: transitionContext) let options: UIViewAnimationOptions = interactive ? .curveLinear : UIViewAnimationOptions() UIView.animate(withDuration: duration, delay: 0, options: options, animations: { () -> Void in if self.presenting { SideMenuTransition.presentMenuStart() // onstage items: slide in } else { SideMenuTransition.hideMenuStart() } menuView?.isUserInteractionEnabled = false }) { (finished) -> Void in // tell our transitionContext object that we've finished animating if transitionContext.transitionWasCancelled { let viewControllerForPresentedMenu = SideMenuTransition.viewControllerForPresentedMenu if self.presenting { SideMenuTransition.hideMenuComplete() } else { SideMenuTransition.presentMenuComplete() } menuView?.isUserInteractionEnabled = true transitionContext.completeTransition(false) if SideMenuTransition.switchMenus { SideMenuTransition.switchMenus = false viewControllerForPresentedMenu?.present(SideMenuTransition.presentDirection == .left ? SideMenuManager.menuLeftNavigationController! : SideMenuManager.menuRightNavigationController!, animated: true, completion: nil) } return } if self.presenting { SideMenuTransition.presentMenuComplete() menuView?.isUserInteractionEnabled = true transitionContext.completeTransition(true) switch SideMenuManager.menuPresentMode { case .viewSlideOut, .viewSlideInOut: container.addSubview(topView!) case .menuSlideIn, .menuDissolveIn: container.insertSubview(topView!, at: 0) } if let statusBarView = SideMenuTransition.statusBarView { container.bringSubview(toFront: statusBarView) } return } SideMenuTransition.hideMenuComplete() transitionContext.completeTransition(true) menuView?.removeFromSuperview() } } // return how many seconds the transiton animation will take open func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return presenting ? SideMenuManager.menuAnimationPresentDuration : SideMenuManager.menuAnimationDismissDuration } // MARK: UIViewControllerTransitioningDelegate protocol methods // return the animator when presenting a viewcontroller // rememeber that an animator (or animation controller) is any object that aheres to the UIViewControllerAnimatedTransitioning protocol open func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { self.presenting = true SideMenuTransition.presentDirection = presented == SideMenuManager.menuLeftNavigationController ? .left : .right return self } // return the animator used when dismissing from a viewcontroller open func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { presenting = false return self } open func interactionControllerForPresentation(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { // if our interactive flag is true, return the transition manager object // otherwise return nil return interactive ? SideMenuTransition.singleton : nil } open func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { return interactive ? SideMenuTransition.singleton : nil } internal func applicationDidEnterBackgroundNotification() { if let menuViewController: UINavigationController = SideMenuTransition.presentDirection == .left ? SideMenuManager.menuLeftNavigationController : SideMenuManager.menuRightNavigationController { SideMenuTransition.hideMenuStart() SideMenuTransition.hideMenuComplete() menuViewController.dismiss(animated: false, completion: nil) } } }
mit
f1fcff9d37d2d849246e114d61af9a90
51.302174
243
0.665655
6.664543
false
false
false
false
ntwf/TheTaleClient
TheTale/Controllers/StartScreen/LoginViewController.swift
1
4759
// // LoginViewController.swift // TheTaleClient // // Created by Mikhail Vospennikov on 31/08/2017. // Copyright © 2017 Mikhail Vospennikov. All rights reserved. // import UIKit class LoginViewController: UIViewController { // MARK: - Delegate weak var segueHandlerDelegate: SegueHandlerDelegate? weak var authPathDelegate: AuthPathDelegate? // MARK: - Internal constants enum Constatns { static let borderColorTextFieldOK = #colorLiteral(red: 0.6642242074, green: 0.6642400622, blue: 0.6642315388, alpha: 1) static let borderColorTextFieldError = #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1) } // MARK: - Outlets @IBOutlet weak var loginTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var loginButton: UIButton! // MARK: - Load controller override func viewDidLoad() { super.viewDidLoad() configured(loginButton: loginButton) setupTextField() } func setupTextField() { loginTextField.delegate = self passwordTextField.delegate = self loginTextField.addTarget(self, action: #selector(checkLogin(_:)), for: .editingChanged) passwordTextField.addTarget(self, action: #selector(checkPassword(_:)), for: .editingChanged) } func configured(textField: UITextField, border color: UIColor) { textField.layer.masksToBounds = true textField.layer.cornerRadius = 5.0 textField.layer.borderColor = color.cgColor textField.layer.borderWidth = 0.5 } func configured(loginButton: UIButton) { if loginTextField.isEmail && !passwordTextField.isEmpty { loginButton.isEnabled = true loginButton.alpha = 1 } else { loginButton.isEnabled = false loginButton.alpha = 0.5 } } // MARK: - Check text field func checkLogin(_ textField: UITextField) { var color = Constatns.borderColorTextFieldOK if !loginTextField.isEmail { color = Constatns.borderColorTextFieldError } configured(loginButton: loginButton) configured(textField: loginTextField, border: color) } func checkPassword(_ textField: UITextField) { var color = Constatns.borderColorTextFieldOK if passwordTextField.isEmpty { color = Constatns.borderColorTextFieldError } configured(loginButton: loginButton) configured(textField: passwordTextField, border: color) } // MARK: - View lifecycle override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) loginTextField.clear() passwordTextField.clear() } // MARK: - Request to API func tryLogin(email: String, password: String) { TaleAPI.shared.login(email: email, password: password) { [weak self] (result) in guard let strongSelf = self else { return } switch result { case .success: guard let delegate = strongSelf.segueHandlerDelegate else { return } delegate.segueHandler(identifier: AppConfiguration.Segue.toJournal) case .failure(let error as NSError): let alert = UIAlertController(title: "Ошибка авторизации.", message: "Неправильный логин или пароль.") strongSelf.present(alert, animated: true, completion: nil) strongSelf.passwordTextField.clear() debugPrint("login \(error)") default: break } } } // MARK: - Outlets action @IBAction func loginButtonTapped(_ sender: UIButton) { loginButton.isEnabled = false guard let email = loginTextField.text, let password = passwordTextField.text else { return } tryLogin(email: email, password: password) } @IBAction func loginOnSiteButtonTapped(_ sender: UIButton) { TaleAPI.shared.requestURLPathTologinIntoSite { [weak self] (result) in guard let strongSelf = self else { return } switch result { case .success(let data): guard let segueHandlerDelegate = strongSelf.segueHandlerDelegate else { return } guard let authPathDelegate = strongSelf.authPathDelegate else { return } authPathDelegate.authPath = data.urlPath segueHandlerDelegate.segueHandler(identifier: AppConfiguration.Segue.toWeb) case .failure(let error as NSError): debugPrint("loginOnTheSite \(error)") default: break } } } } // MARK: - UITextFieldDelegate extension LoginViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { loginTextField.resignFirstResponder() passwordTextField.resignFirstResponder() return true } }
mit
051492aed4cb9ffb92d096f45321b7c4
29.031847
126
0.684411
4.686879
false
true
false
false
jarsen/Pipes
PipesTests/TestHelpers.swift
1
554
// // Created by Jason Larsen on 4/27/15. // import XCTest func expect<T: Equatable>(_ value: T, file: String = #file, line: Int = #line) -> (T, String, Int) { return (value, file, line) } func ==<T: Equatable>(lhs: (T, String, Int), rhs: T) { if lhs.0 != rhs { XCTFail("Expected \(rhs), but got \(lhs.0) instead", file: lhs.1, line: UInt(lhs.2)) } } func !=<T: Equatable>(lhs: (T, String, Int), rhs: T) { if lhs.0 == rhs { XCTFail("Expected \(rhs), but got \(lhs.0) instead", file: lhs.1, line: UInt(lhs.2)) } }
mit
2f21af11004be40dba6200db58398fce
25.380952
100
0.557762
2.79798
false
false
false
false
hollance/swift-algorithm-club
Breadth-First Search/Tests/Graph.swift
9
2325
// MARK: - Edge public class Edge: Equatable { public var neighbor: Node public init(neighbor: Node) { self.neighbor = neighbor } } public func == (lhs: Edge, rhs: Edge) -> Bool { return lhs.neighbor == rhs.neighbor } // MARK: - Node public class Node: CustomStringConvertible, Equatable { public var neighbors: [Edge] public private(set) var label: String public var distance: Int? public var visited: Bool public init(label: String) { self.label = label neighbors = [] visited = false } public var description: String { if let distance = distance { return "Node(label: \(label), distance: \(distance))" } return "Node(label: \(label), distance: infinity)" } public var hasDistance: Bool { return distance != nil } public func remove(edge: Edge) { neighbors.remove(at: neighbors.index { $0 === edge }!) } } public func == (lhs: Node, rhs: Node) -> Bool { return lhs.label == rhs.label && lhs.neighbors == rhs.neighbors } // MARK: - Graph public class Graph: CustomStringConvertible, Equatable { public private(set) var nodes: [Node] public init() { self.nodes = [] } public func addNode(_ label: String) -> Node { let node = Node(label: label) nodes.append(node) return node } public func addEdge(_ source: Node, neighbor: Node) { let edge = Edge(neighbor: neighbor) source.neighbors.append(edge) } public var description: String { var description = "" for node in nodes { if !node.neighbors.isEmpty { description += "[node: \(node.label) edges: \(node.neighbors.map { $0.neighbor.label})]" } } return description } public func findNodeWithLabel(_ label: String) -> Node { return nodes.filter { $0.label == label }.first! } public func duplicate() -> Graph { let duplicated = Graph() for node in nodes { _ = duplicated.addNode(node.label) } for node in nodes { for edge in node.neighbors { let source = duplicated.findNodeWithLabel(node.label) let neighbour = duplicated.findNodeWithLabel(edge.neighbor.label) duplicated.addEdge(source, neighbor: neighbour) } } return duplicated } } public func == (lhs: Graph, rhs: Graph) -> Bool { return lhs.nodes == rhs.nodes }
mit
201a08c27dc1a696a2cdd4479ff5782c
20.933962
96
0.634409
3.862126
false
false
false
false
santosli/100-Days-of-Swift-3
Project 05/Project 05/SLDotaTableViewController.swift
1
3207
// // SLDotaTableViewController.swift // Project 05 // // Created by Santos on 28/10/2016. // Copyright © 2016 santos. All rights reserved. // import UIKit class SLDotaTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() self.navigationItem.leftBarButtonItem = self.editButtonItem } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 3 } /* override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
241a982154c761215c570069925acbba
31.714286
136
0.67093
5.334443
false
false
false
false
xiaoxionglaoshi/DNSwiftProject
DNSwiftProject/DNSwiftProject/Classes/Vendor/DNJPush/DNJPushManager.swift
1
1592
// // DNJPushManager.swift // DNJPushDemo // // Created by mainone on 16/12/13. // Copyright © 2016年 wjn. All rights reserved. // import UIKit public typealias TagBlock = ((_ res: Bool, _ tags:Set<AnyHashable>, _ alias: String) -> Void) protocol DNJPushDelegate: class { func receiveMessage(_ userInfo: Dictionary<String, Any>) } private let dnJPushManagerShareInstance = DNJPushManager() class DNJPushManager: NSObject { // 创建一个单例 open class var shared: DNJPushManager { return dnJPushManagerShareInstance } weak var myDelegate: DNJPushDelegate? private var onTagBlock: TagBlock? // 监听接收到的消息 func didReceiveMessage(_ userInfo: Dictionary<String, Any>) { self.myDelegate?.receiveMessage(userInfo) let badge = (userInfo["aps"] as? Dictionary<String, Any>)?["badge"] if let badgeNum = badge as? Int { // 同步badge setBadge(value: badgeNum) } } // MARK: 设置标签 func setTags(tags: Set<AnyHashable>!, alias: String!, object: Any!, callBack: @escaping TagBlock) { JPUSHService.setTags(tags, alias: alias) { (iResCode, tags, alias) in let res = iResCode == 0 ? true : false self.onTagBlock!(res, tags!, alias!) } onTagBlock = callBack } // MARK: 设置Badge值,存储在JPush服务器上 func setBadge(value: Int) { JPUSHService.setBadge(value) } // MARK: 重置Badge值 func resetBadge() { JPUSHService.setBadge(0) } }
apache-2.0
bd4aac037624bbe4fd7ba8d2f662b221
25.258621
103
0.623112
3.84596
false
false
false
false
brave/browser-ios
Shared/Extensions/UIImageExtensions.swift
1
3083
/* 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 WebImage private let imageLock = NSLock() extension UIImage { /// Despite docs that say otherwise, UIImage(data: NSData) isn't thread-safe (see bug 1223132). /// As a workaround, synchronize access to this initializer. /// This fix requires that you *always* use this over UIImage(data: NSData)! public static func imageFromDataThreadSafe(_ data: Data) -> UIImage? { imageLock.lock() let image = UIImage(data: data) imageLock.unlock() return image } /// Generates a UIImage from GIF data by calling out to SDWebImage. The latter in turn uses UIImage(data: NSData) /// in certain cases so we have to synchronize calls (see bug 1223132). public static func imageFromGIFDataThreadSafe(_ data: Data) -> UIImage? { imageLock.lock() let image = UIImage.sd_animatedGIF(with: data) imageLock.unlock() return image } public static func dataIsGIF(_ data: Data) -> Bool { guard data.count > 3 else { return false } // Look for "GIF" header to identify GIF images var header = [UInt8](repeating: 0, count: 3) data.copyBytes(to: &header, count: 3 * MemoryLayout<UInt8>.size) return header == [0x47, 0x49, 0x46] } public static func createWithColor(_ size: CGSize, color: UIColor) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, false, 0.0) let context = UIGraphicsGetCurrentContext() let rect = CGRect(origin: CGPoint.zero, size: size) color.setFill() context!.fill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } public func createScaled(_ size: CGSize) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, false, 0) draw(in: CGRect(origin: CGPoint(x: 0, y: 0), size: size)) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return scaledImage! } public static func templateImageNamed(_ name: String) -> UIImage? { return UIImage(named: name)?.withRenderingMode(.alwaysTemplate) } public func getPixelColor(of point: CGPoint) -> UIColor { guard let pixelData = cgImage?.dataProvider?.data else { return UIColor.white } let data = CFDataGetBytePtr(pixelData)! let pixelInfo = Int(size.width * point.y) + Int(point.x * 4) let pixelValues: CGFloat = 255.0 let r = CGFloat(data[pixelInfo+0]) / pixelValues let g = CGFloat(data[pixelInfo+1]) / pixelValues let b = CGFloat(data[pixelInfo+2]) / pixelValues let a = CGFloat(data[pixelInfo+3]) / pixelValues return UIColor(red: b, green: g, blue: r, alpha: a) } }
mpl-2.0
622c2a0c6e5c82ab1bcdd633864dc3c7
37.5375
117
0.647421
4.494169
false
false
false
false
selfzhou/Swift3
Playground/Swift3-III.playground/Pages/Collection Types.xcplaygroundpage/Contents.swift
1
1601
//: [Previous](@previous) import Foundation var shoppingList = ["Six eggs", "Milk", "Flour", "Baking Powder", "Bananas"] for (index, value) in shoppingList.enumerated() { print("Item \(String(index + 1)): \(value)") } var favoriteGenres: Set = ["Rock", "Classical", "Hip hop"] if let removedGenre = favoriteGenres.remove("Rock") { print("\(removedGenre)? im over it.") } else { print("i never much cared for that.") } favoriteGenres.insert("Rock") for genre in favoriteGenres.sorted() { print("\(genre)") } // 集合操作 let oddDigits: Set = [1, 3, 5, 7, 9] let evenDigits: Set = [0, 2, 4, 6, 8] let singleDigitPrimeNumbers: Set = [2, 3, 5, 7] // union(_:) 方法根据两个集合的值创建一个新的集合,并集 = (A ∪ B) oddDigits.union(evenDigits).sorted() // intersection(_:) 方法根据两个集合中都包含的值创建一个新的集合,交集 = (A ∩ B) oddDigits.intersection(evenDigits).sorted() // subtracting(_:) 方法根据不再该集合中的值创建一个新的集合,A集合 - 交集 = (A - (A ∩ B)) oddDigits.subtracting(singleDigitPrimeNumbers).sorted() // symmetricDifference((_:) 方法根据在一个集合中但不再两个集合中的值创建一个新的集合,并集 - 交集 = ((A ∪ B) - (A ∩ B)) oddDigits.symmetricDifference(singleDigitPrimeNumbers) let houseAnimals: Set = ["🐶", "🐱"] let farmAnimals: Set = ["🐮", "🐔", "🐑", "🐶", "🐱"] let cityAnimals: Set = ["🐦", "🐭"] houseAnimals.isSubset(of: farmAnimals) farmAnimals.isSuperset(of: houseAnimals) farmAnimals.isDisjoint(with: cityAnimals)
mit
79d3330469769705c3ef67a6f8544066
29.659091
86
0.671365
3.008929
false
false
false
false
darina/omim
iphone/Maps/Classes/Components/Modal/IPadModalPresentationController.swift
5
1466
final class IPadModalPresentationController: DimmedModalPresentationController { override var frameOfPresentedViewInContainerView: CGRect { guard let containerView = containerView else { return CGRect.zero } let screenSize = UIScreen.main.bounds let contentSize = presentedViewController.preferredContentSize let r = alternative(iPhone: containerView.bounds, iPad: CGRect(x: screenSize.width/2 - contentSize.width/2, y: screenSize.height/2 - contentSize.height/2, width: contentSize.width, height: contentSize.height)) return r } override func containerViewWillLayoutSubviews() { presentedView?.frame = frameOfPresentedViewInContainerView } override func presentationTransitionWillBegin() { super.presentationTransitionWillBegin() presentedViewController.view.layer.cornerRadius = 8 presentedViewController.view.clipsToBounds = true guard let containerView = containerView, let presentedView = presentedView else { return } containerView.addSubview(presentedView) presentedView.frame = frameOfPresentedViewInContainerView } override func dismissalTransitionDidEnd(_ completed: Bool) { super.presentationTransitionDidEnd(completed) guard let presentedView = presentedView else { return } if completed { presentedView.removeFromSuperview() } } }
apache-2.0
63d2e93a443d317fea37464101c0463d
42.117647
94
0.712142
6.34632
false
false
false
false
Mazy-ma/DemoBySwift
FacialRecognitionDemo/FacialRecognitionDemo/ViewController.swift
1
1845
// // ViewController.swift // FacialRecognitionDemo // // Created by Mazy on 2017/4/25. // Copyright © 2017年 Mazy. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var iconImageView: UIImageView! @IBOutlet weak var originalImageView: UIImageView! let imagePicker = UIImagePickerController() override func viewDidLoad() { super.viewDidLoad() let tapGesture = UITapGestureRecognizer(target: self, action: #selector(selectedImage)) iconImageView.addGestureRecognizer(tapGesture) iconImageView.layer.cornerRadius = iconImageView.bounds.width/2 iconImageView.layer.masksToBounds = true imagePicker.sourceType = .photoLibrary imagePicker.delegate = self } @objc private func selectedImage() { present(imagePicker, animated: true, completion: nil) } } // MARK: - UINavigationControllerDelegate,UIImagePickerControllerDelegate extension ViewController: UINavigationControllerDelegate,UIImagePickerControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { // 任务完成后执行 defer{ picker.dismiss(animated: true, completion: nil) } let pickerImage = info[UIImagePickerControllerOriginalImage] as? UIImage guard let image = pickerImage else { return } /// 设置原始图 originalImageView.image = image /// 设置面部图 iconImageView.set(image, focusOnFaces: true) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { picker.dismiss(animated: true, completion: nil) } }
apache-2.0
19d5ca9894ddfea14ca2eb1c4f1e1c51
27.25
119
0.663717
5.614907
false
false
false
false
Echx/GridOptic
GridOptic/GridOptic/GridOptic/DataStructure/GOArcSegment.swift
1
15338
// // GOArcSegment.swift // GridOptic // // Created by Wang Jinghan on 30/03/15. // Copyright (c) 2015 Echx. All rights reserved. // import UIKit class GOArcSegment: GOSegment { var radius: CGFloat var radian: CGFloat override var bezierPath: UIBezierPath { get { var path = UIBezierPath() path.addArcWithCenter(self.center, radius: self.radius, startAngle: self.endRadian, endAngle: self.startRadian, clockwise: false) return path } } init(center: CGPoint, radius: CGFloat, radian: CGFloat, normalDirection: CGVector) { self.radius = radius self.radian = radian super.init() self.normalDirection = normalDirection self.center = center } required convenience init(coder aDecoder: NSCoder) { let radius = aDecoder.decodeObjectForKey(GOCodingKey.segment_radius) as CGFloat let radian = aDecoder.decodeObjectForKey(GOCodingKey.segment_radian) as CGFloat let willRefract = aDecoder.decodeBoolForKey(GOCodingKey.segment_willRef) let willReflect = aDecoder.decodeBoolForKey(GOCodingKey.segment_willRel) let center = aDecoder.decodeCGPointForKey(GOCodingKey.segment_center) let tag = aDecoder.decodeObjectForKey(GOCodingKey.segment_tag) as NSInteger let parent = aDecoder.decodeObjectForKey(GOCodingKey.segment_parent) as String let direction = aDecoder.decodeCGVectorForKey(GOCodingKey.segment_direction) let normalDirection = aDecoder.decodeCGVectorForKey(GOCodingKey.segment_normalDir) self.init(center: center, radius: radius, radian: radian, normalDirection: normalDirection) self.willReflect = willReflect self.willRefract = willRefract self.tag = tag self.parent = parent } override func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(radius, forKey: GOCodingKey.segment_radius) aCoder.encodeObject(radian, forKey: GOCodingKey.segment_radian) aCoder.encodeBool(willRefract, forKey: GOCodingKey.segment_willRef) aCoder.encodeBool(willReflect, forKey: GOCodingKey.segment_willRel) aCoder.encodeCGPoint(center, forKey: GOCodingKey.segment_center) aCoder.encodeObject(tag, forKey: GOCodingKey.segment_tag) aCoder.encodeObject(parent, forKey: GOCodingKey.segment_parent) aCoder.encodeCGVector(normalDirection, forKey: GOCodingKey.segment_normalDir) } var scaledStartVector: CGVector { get { let startVector = CGVector( dx: normalDirection.dx * cos(-radian / 2) - normalDirection.dy * sin(-radian / 2), dy: normalDirection.dx * sin(-radian / 2) + normalDirection.dy * cos(-radian / 2) ) return startVector.scaleTo(self.radius) } } var scaledEndVector: CGVector { get { let endVector = CGVector( dx: normalDirection.dx * cos(radian / 2) - normalDirection.dy * sin(radian / 2), dy: normalDirection.dx * sin(radian / 2) + normalDirection.dy * cos(radian / 2) ) return endVector.scaleTo(self.radius) } } override var startPoint: CGPoint { get { return CGPoint( x: CGFloat(center.x) + self.scaledStartVector.dx, y: CGFloat(center.y) + self.scaledStartVector.dy ) } } override var endPoint: CGPoint { get { return CGPoint( x: CGFloat(center.x) + self.scaledEndVector.dx, y: CGFloat(center.y) + self.scaledEndVector.dy ) } } // radian will be [0, 2*Pi) var startRadian: CGFloat { get { var result = self.normalDirection.angleFromXPlus - self.radian / 2 return result.restrictWithin2Pi } } var endRadian: CGFloat { get { var result = self.normalDirection.angleFromXPlus + self.radian / 2 return result.restrictWithin2Pi } } override func getIntersectionPoint(ray: GORay) -> CGPoint? { let lineOfRay = ray.line let r1 = CGFloat(self.center.x) let r2 = CGFloat(self.center.y) let r = self.radius // handle dy=0 separatel // in this case, the slope is not calculatable if lineOfRay.direction.dx.equalWithPrecision(CGFloat(0)) { let x = ray.startPoint.x let squareSide = r * r - (x - r1) * (x - r1) if squareSide < 0 { return nil } else { let root = sqrt(squareSide) let y1 = r2 + root let y2 = r2 - root let point1 = CGPoint(x: x, y: y1) let point2 = CGPoint(x: x, y: y2) // check if point 1 is on ray if let xOnRay = ray.getX(y: y1) { if let xOnRay = ray.getX(y: y2) { // both point1 and point2 are on the ray if GOUtilities.getDistanceBetweenPoint(ray.startPoint, andPoint: point1) > GOUtilities.getDistanceBetweenPoint(ray.startPoint, andPoint: point2) { // point 2 is nearer, i.e contact earlier if self.containsPoint(point2) { // confirm that point 2 is on the arc if point2.isNearEnough(ray.startPoint) { // this is the case that the intersection point is exactly the contact point return nil } else { return point2 } } } // point 1 is nearer if self.containsPoint(point1) { // point 1 is on the arc if point1.isNearEnough(ray.startPoint) { return nil } else { return point1 } } else { return nil } } else { // point 2 is not on the ray if self.containsPoint(point1) { // point 1 is on the arc { if point1.isNearEnough(ray.startPoint) { return nil } else { return point1 } } else { return nil } } } else { // point 1 is not on the ray if let xOnRay = ray.getX(y: y2) { // only point 2 is on the ray if self.containsPoint(point2) { // point 2 is on the arc { if point2.isNearEnough(ray.startPoint) { return nil } else { return point2 } } else { return nil } } else { // no point is eligible to be the intersection point return nil } } } } else { let k = lineOfRay.slope let c = lineOfRay.yIntercept if c == nil { return nil } // from the equation, generate the term for the quadratic equation let termA = 1 + k * k let termB = 2 * ((c! - r2) * k - r1) let termC = r1 * r1 + (r2 - c!) * (r2 - c!) - r * r let xs = GOUtilities.solveQuadraticEquation(termA, b: termB, c: termC) if xs.0 == nil { // no solution return nil } else if xs.1 == nil { // only one intersection point, tangent if let y = ray.getY(x: xs.0!) { // the point is on the ray let point = CGPoint(x: xs.0!, y: y) if self.containsPoint(point) { // the point is on the arc if point.isNearEnough(ray.startPoint) { return nil } else { return point } } else { // the point is not valid return nil } } else { // the point is not on the ray return nil } } else { // we have two solutions for the equation, validate both of the points if let y0 = ray.getY(x: xs.0!) { if let y1 = ray.getY(x: xs.1!) { if GOUtilities.getDistanceBetweenPoint(ray.startPoint, andPoint: CGPoint(x: xs.0!, y: y0)) > GOUtilities.getDistanceBetweenPoint(ray.startPoint, andPoint: CGPoint(x: xs.1!, y: y1)) { // the second point is nearer to the contact point let point = CGPoint(x: xs.1!, y: y1) if self.containsPoint(point) { if point.isNearEnough(ray.startPoint) { return nil } else { return point } } } // the first point is nearer let point = CGPoint(x: xs.0!, y: y0) if self.containsPoint(point) { if point.isNearEnough(ray.startPoint) { return nil } else { return point } } else { return nil } } else { let point = CGPoint(x: xs.0!, y: y0) if self.containsPoint(point) { if point.isNearEnough(ray.startPoint) { return nil } else { return point } } else { return nil } } } else { // the first point is invalid, we just check y1 if let y1 = ray.getY(x: xs.1!) { let point = CGPoint(x: xs.1!, y: y1) if self.containsPoint(point) { if point.isNearEnough(ray.startPoint) { return nil } else { return point } } else { return nil } } else { return nil } } } } } // the GORay is the refraction ray, the boolean value marks whether the ray is caused by total reflection override func getRefractionRay(#rayIn: GORay, indexIn: CGFloat, indexOut: CGFloat) -> (GORay, Bool)? { if let intersectionPoint = self.getIntersectionPoint(rayIn) { let l = rayIn.direction.normalised let tangentNormal = CGVector(dx: intersectionPoint.x - self.center.x, dy: intersectionPoint.y - self.center.y) let deg = M_PI / 2 var n: CGVector if CGVector.dot(rayIn.direction, v2: tangentNormal) < 0 { n = tangentNormal.normalised } else { n = CGVectorMake(-tangentNormal.dx, -tangentNormal.dy).normalised } let cosTheta1 = -CGVector.dot(n, v2: l) let cosTheta2 = sqrt(1 - (indexIn / indexOut) * (indexIn / indexOut) * (1 - cosTheta1 * cosTheta1)) // total reflection if 1 - (indexIn / indexOut) * (indexIn / indexOut) * (1 - cosTheta1 * cosTheta1) < 0 { if let reflectionRay = self.getReflectionRay(rayIn: rayIn) { return (reflectionRay, true) } else { return nil } } let x = (indexIn / indexOut) * l.dx + (indexIn / indexOut * cosTheta1 - cosTheta2) * n.dx let y = (indexIn / indexOut) * l.dy + (indexIn / indexOut * cosTheta1 - cosTheta2) * n.dy return (GORay(startPoint: intersectionPoint, direction: CGVectorMake(x, y)), false) } else { return nil } } override func getReflectionRay(#rayIn: GORay) -> GORay? { if let intersectionPoint = self.getIntersectionPoint(rayIn) { let l = rayIn.direction.normalised let tangentNormal = CGVector(dx: intersectionPoint.x - self.center.x, dy: intersectionPoint.y - self.center.y) let deg = M_PI / 2 let tangent = tangentNormal.rotate(CGFloat(deg)) // calculate the ray let tangentAngle = tangent.angleFromXPlus let reflectionAngle = 2 * tangentAngle + CGFloat(2 * M_PI) - rayIn.direction.angleFromXPlus var reflectDirection = GOUtilities.vectorFromRadius(reflectionAngle) return GORay(startPoint: intersectionPoint, direction: reflectDirection) } else { return nil } } func containsPoint(point: CGPoint) -> Bool { if point.getDistanceToPoint(self.center).equalWithPrecision(self.radius) { let pointRadian = point.getRadiusFrom(self.center).restrictWithin2Pi let normalRadian = self.normalDirection.angleFromXPlus let maxRadian = max(self.startRadian, self.endRadian) let minRadian = min(self.startRadian, self.endRadian) if normalRadian > maxRadian || normalRadian < minRadian { return pointRadian > maxRadian || pointRadian < minRadian } else { return pointRadian <= maxRadian && pointRadian >= minRadian } } else { return false } } }
mit
093c9b1011d39ac45131d453e4eccc03
39.469657
117
0.462185
5.06539
false
false
false
false
robertwtucker/kfinder-ios
KFinder/SettingsViewController.swift
1
3083
/** * Copyright 2017 Robert Tucker * * 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 RxCocoa import RxSwift import Action private enum Item { case About case Account } class SettingsViewController: UIViewController { //MARK: Properties var viewModel: SettingsViewModel? private let disposeBag = DisposeBag() @IBOutlet weak var convertMetricSwitch: UISwitch! @IBOutlet weak var acknowledgementsButton: UIButton! @IBOutlet weak var versionLabel: UILabel! //MARK: View Lifecycle override func viewDidLoad() { super.viewDidLoad() configure() print("SetingsVC loaded") } //MARK: Configuration func configure() { guard let vm = viewModel else { return } vm.navigationBarTitle .bindTo(navigationItem.rx.title) .disposed(by: disposeBag) vm.applicationVersion .bindTo(versionLabel.rx.text) .disposed(by: disposeBag) acknowledgementsButton.rx.action = acknowledgementsAction() vm.convertFromMetricSetting .bindTo(convertMetricSwitch.rx.isOn) .disposed(by: disposeBag) convertMetricSwitch.rx.value .bindTo(vm.convertMetricSwitchIsOn) .disposed(by: disposeBag) vm.convertFromMetricTracking .subscribe() .disposed(by: disposeBag) } func acknowledgementsAction() -> CocoaAction { return CocoaAction { _ in if let url = Bundle.main.url(forResource: "acknowledgements", withExtension: "html") { let htmlHeader = "<html>\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<link href=\"default.css\" rel=\"stylesheet\" type=\"text/css\"/>\n</head>\n<body>\n" let htmlFooter = "</body>\n</html>" do { let htmlBody = try String.init(contentsOf: url) let webViewController = WebViewController() webViewController.html = String.init(format: "%@%@%@", htmlHeader, htmlBody, htmlFooter) self.show(webViewController, sender: nil) } catch { print("Unable to load HTML: \(error)") } } return Observable.empty() } } } //MARK: - StoryboardIdentifiable extension SettingsViewController: StoryboardIdentifiable { }
apache-2.0
dad27390df8e5ad8dfeb7a8725d82cdd
29.83
235
0.614012
4.917065
false
false
false
false
mrdepth/EVEUniverse
Legacy/Neocom/Neocom/NCHeaderTableViewCell.swift
2
5264
// // NCHeaderTableViewCell.swift // Neocom // // Created by Artem Shimanski on 05.12.16. // Copyright © 2016 Artem Shimanski. All rights reserved. // import UIKit class NCHeaderTableViewCell: UITableViewCell, Expandable { @IBOutlet weak var titleLabel: UILabel? @IBOutlet weak var iconView: UIImageView? @IBOutlet weak var expandIconView: UIImageView? var object: Any? override func awakeFromNib() { super.awakeFromNib() tintColor = .caption indentationWidth = 16 selectionStyle = .none } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func setExpanded(_ expanded: Bool, animated: Bool) { expandIconView?.image = expanded ? #imageLiteral(resourceName: "collapse") : #imageLiteral(resourceName: "expand") } var indentationConstraint: NSLayoutConstraint? { get { guard let stackView = self.titleLabel?.superview else {return nil} return stackView.superview?.constraints.first { return $0.firstItem === stackView && $0.secondItem === stackView.superview && $0.firstAttribute == .leading && $0.secondAttribute == .leading } } } override var indentationWidth: CGFloat { didSet { updateIndent() } } override var indentationLevel: Int { didSet { updateIndent() } } private func updateIndent() { let level = max(0, indentationLevel) let indent = 8 + CGFloat(level) * indentationWidth self.indentationConstraint?.constant = indent self.separatorInset.left = indent } } typealias NCFooterTableViewCell = NCHeaderTableViewCell class NCActionHeaderTableViewCell: NCHeaderTableViewCell { @IBOutlet weak var button: UIButton? var actionHandler: NCActionHandler<UIButton>? override func prepareForReuse() { super.prepareForReuse() actionHandler = nil } } extension Prototype { enum NCHeaderTableViewCell { static let `default` = Prototype(nib: UINib(nibName: "NCHeaderTableViewCell", bundle: nil), reuseIdentifier: "NCHeaderTableViewCell") static let action = Prototype(nib: UINib(nibName: "NCActionHeaderTableViewCell", bundle: nil), reuseIdentifier: "NCActionHeaderTableViewCell") static let image = Prototype(nib: UINib(nibName: "NCImageHeaderTableViewCell", bundle: nil), reuseIdentifier: "NCImageHeaderTableViewCell") static let empty = Prototype(nib: UINib(nibName: "NCEmptyHeaderTableViewCell", bundle: nil), reuseIdentifier: "NCEmptyHeaderTableViewCell") static let `static` = Prototype(nib: UINib(nibName: "NCStaticHeaderTableViewCell", bundle: nil), reuseIdentifier: "NCStaticHeaderTableViewCell") } enum NCActionHeaderTableViewCell { static let `default` = Prototype(nib: UINib(nibName: "NCActionHeaderTableViewCell", bundle: nil), reuseIdentifier: "NCActionHeaderTableViewCell") } enum NCFooterTableViewCell { static let `default` = Prototype(nib: UINib(nibName: "NCFooterTableViewCell", bundle: nil), reuseIdentifier: "NCFooterTableViewCell") } } class NCActionTreeSection: DefaultTreeSection { override init(prototype: Prototype = Prototype.NCActionHeaderTableViewCell.default, nodeIdentifier: String? = nil, image: UIImage? = nil, title: String? = nil, attributedTitle: NSAttributedString? = nil, isExpandable: Bool = true, children: [TreeNode]? = nil) { super.init(prototype: prototype, nodeIdentifier: nodeIdentifier, image: image, title: title, attributedTitle: attributedTitle, isExpandable: isExpandable, children: children) } override func configure(cell: UITableViewCell) { super.configure(cell: cell) guard let cell = cell as? NCActionHeaderTableViewCell else {return} cell.actionHandler = NCActionHandler(cell.button!, for: .touchUpInside) { [weak self] _ in guard let strongSelf = self else {return} guard let controller = strongSelf.treeController else {return} controller.delegate?.treeController?(controller, accessoryButtonTappedWithNode: strongSelf) } } } class NCSkillsHeaderTableViewCell: NCHeaderTableViewCell { var trainingQueue: NCTrainingQueue? var character: NCCharacter? @IBOutlet weak var trainButton: UIButton? } class NCFooterRow: TreeRow { var title: String? var attributedTitle: NSAttributedString? let nodeIdentifier: String? init(prototype: Prototype = Prototype.NCFooterTableViewCell.default, nodeIdentifier: String? = nil, title: String? = nil, attributedTitle: NSAttributedString? = nil, route: Route? = nil, object: Any? = nil) { self.title = title self.attributedTitle = attributedTitle self.nodeIdentifier = nodeIdentifier super.init(prototype: prototype, route: route, accessoryButtonRoute: nil, object: object) } override func configure(cell: UITableViewCell) { if let cell = cell as? NCFooterTableViewCell { cell.object = self if title != nil { cell.titleLabel?.text = title } else if attributedTitle != nil { cell.titleLabel?.attributedText = attributedTitle } } } override var hash: Int { return nodeIdentifier?.hashValue ?? super.hashValue } override func isEqual(_ object: Any?) -> Bool { guard let nodeIdentifier = nodeIdentifier else {return super.isEqual(object)} return nodeIdentifier.hashValue == (object as? NCFooterRow)?.nodeIdentifier?.hashValue } }
lgpl-2.1
bfb5a68b03412236f289a815744d13dd
34.086667
262
0.750523
4.213771
false
false
false
false
efremidze/NumPad
Sources/Cell.swift
1
1357
// // Cell.swift // NumPad // // Created by Lasha Efremidze on 1/7/18. // Copyright © 2018 Lasha Efremidze. All rights reserved. // import UIKit class Cell: UICollectionViewCell { lazy var button: UIButton = { [unowned self] in let button = UIButton(type: .custom) button.titleLabel?.textAlignment = .center button.addTarget(self, action: #selector(_buttonTapped), for: .touchUpInside) self.contentView.addSubview(button) let edges = UIEdgeInsets(top: 1, left: 1, bottom: 0, right: 0) button.constrainToEdges(edges) return button }() var item: Item! { didSet { button.title = item.title button.titleColor = item.titleColor button.titleLabel?.font = item.font button.image = item.image button.tintColor = item.titleColor var image = item.backgroundColor.map { UIImage(color: $0) } button.backgroundImage = image image = item.selectedBackgroundColor.map { UIImage(color: $0) } button.setBackgroundImage(image, for: .highlighted) button.setBackgroundImage(image, for: .selected) } } var buttonTapped: ((UIButton) -> Void)? @IBAction func _buttonTapped(_ button: UIButton) { buttonTapped?(button) } }
mit
45ad7ed3a5205a3f239aa6fb18753bdc
29.818182
85
0.60767
4.431373
false
false
false
false
lorentey/swift
validation-test/compiler_crashers_fixed/26854-swift-constraints-constraintsystem-matchdeepequalitytypes.swift
65
2539
// 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 // RUN: not %target-swift-frontend %s -typecheck } class n{class c struct c, } class a }class a: var f{class B< }class B<T where h: { struct S<T where B? = " enum a { class B<T where B<T where h: AnyObject.Element struct c<T where h: enum b<T where h{ var _=B{enum a { } struct B<T where T let start = b{ { struct Q{}class B:d{func u(i let a{ struct c<T where h:a{ } let a { { e .c {return" struct b<f: AnyObject.c {class a{{return"[enum B<T where h:B<T where h{let , i { class B<f=B? = A{ class A{ let f=e:a{init(i class B<H:Boolean} }} } struct c class B:A{ }} if true { struct c<T where h:d enum b<I : e :d: { let let f: A {let a {struct A { }class B:Boolean}}struct b<T { if true { }}(i e :Boolean} var _=B } var = A{let {} (i protocol A {enum A{var _=[enum a {return" if true{" func b{ let :Boolean}} struct S<f protocol A {class d{ " let c { ("" let a { e .c { struct c struct S<T {{ var b{{struct B{func a:c<h:Boolean} (e = b{ [1 { class d{ [enum B<T where T: e :AnyObject.c {{typealias f=a{ struct D{var f=e:Boolean}enum b<T where B enum b let d }((){ struct d func b<H:A{ let f enum S<T where h:A{ let :NSManagedObject{ class n{ struct A {return" e :Boolean} }} class c<T where h:B{ {{{ let f=[]deinit{ var d{ enum b<I :a<T where h:Boolean} class a struct B<T where T{enum b ((){ struct A e :A{ let a { []deinit{struct B struct S<T where T: AnyObject.Element class B<T where h:A class C } struct B : A { enum a { let a }class B<T where T: e: let start = true { }} func a{typealias f: e: }} let f=(){ func u((){ } } } var f: C { protocol A { } struct Q{ class d<T where h: e = Swift.Element struct Q{ protocol A {{ ([Void{ }} d struct c if true {:d class B: } ([[]deinit{ } func b{ class B:Boolean}enum B<T where T func b let } struct c<f: d = true {class b struct c<I : b { func g: e :A{class B { []deinit{class B: {enum b<T where h: { class B<T {enum b<T where g: e: } class b{ class b{ class n{struct Q<T where h: Int = A{{ protocol A{ struct c class B:A:B:c<I :d<T where g: Int = " class b<D{return"class B: let d{ let : enum b{ let v: { if true { let a { var d struct B : B:A{ let f=B class B: class d{ protocol A { } } }enum b{ let start = "[Void{ class B:B:A{ e = A }} let d
apache-2.0
6f40944342e839124077878a6fd348b8
13.676301
80
0.640803
2.408918
false
false
false
false
macmade/AtomicKit
AtomicKit/Source/DispatchedDictionaryController.swift
1
4760
/******************************************************************************* * The MIT License (MIT) * * Copyright (c) 2017 Jean-David Gadina - www.xs-labs.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 Cocoa /** * Thread-safe value wrapper for `NSDictionaryController`, using dispatch queues * to achieve synchronization. * This class is KVO-compliant. You may observe its `value` property to be * notified of changes. This is applicable to Cocoa bindings. * * - seealso: DispatchedValueWrapper */ @objc public class DispatchedDictionaryController: NSObject, DispatchedValueWrapper { /** * The wrapped value type, `NSDictionaryController`. */ public typealias ValueType = NSDictionaryController? /** * Initializes a dispatched value object. * This initializer will use the main queue for synchronization. * * - parameter value: The initial value. */ public required convenience init( value: ValueType ) { self.init( value: value, queue: DispatchQueue.main ) } /** * Initializes a dispatched value object. * * - parameter value: The initial `NSDictionaryController` value. * - parameter queue: The queue to use to achieve synchronization. */ public required init( value: ValueType = nil, queue: DispatchQueue = DispatchQueue.main ) { self._value = DispatchedValue< ValueType >( value: value, queue: queue ) } /** * The wrapped `NSDictionaryController` value. * This property is KVO-compliant. */ @objc public dynamic var value: ValueType { get { return self._value.get() } set( value ) { self.willChangeValue( forKey: "value" ) self._value.set( value ) self.didChangeValue( forKey: "value" ) } } /** * Atomically gets the wrapped `NSDictionaryController` value. * The getter will be executed on the queue specified in the initialzer. * * - returns: The actual `NSDictionaryController` value. */ public func get() -> ValueType { return self.value } /** * Atomically sets the wrapped `NSDictionaryController` value. * The setter will be executed on the queue specified in the initialzer. * * -parameter value: The `NSDictionaryController` value to set. */ public func set( _ value: ValueType ) { self.value = value } /** * Atomically executes a closure on the wrapped `NSDictionaryController` * value. * The closure will be passed the actual value of the wrapped * `NSDictionaryController` value, and is guaranteed to be executed * atomically, on the queue specified in the initialzer. * * -parameter closure: The close to execute. */ public func execute( closure: ( ValueType ) -> Swift.Void ) { self._value.execute( closure: closure ) } /** * Atomically executes a closure on the wrapped `NSDictionaryController` * value, returning some value. * The closure will be passed the actual value of the wrapped * `NSDictionaryController` value, and is guaranteed to be executed * atomically, on the queue specified in the initialzer. * * -parameter closure: The close to execute, returning some value. */ public func execute< R >( closure: ( ValueType ) -> R ) -> R { return self._value.execute( closure: closure ) } private var _value: DispatchedValue< ValueType > }
mit
20153f6d4aee0e932f3d3f922bcbd134
33.492754
93
0.636345
4.892086
false
false
false
false
jeffreybergier/WaterMe2
WaterMe/WaterMe/Categories/UITableCollectionView+WaterMe.swift
1
4255
// // UITableCollectionView+WaterMe.swift // WaterMe // // Created by Jeffrey Bergier on 9/20/18. // Copyright © 2018 Saturday Apps. // // This file is part of WaterMe. Simple Plant Watering Reminders for iOS. // // WaterMe is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // WaterMe is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with WaterMe. If not, see <http://www.gnu.org/licenses/>. // import Datum import UIKit extension UICollectionView { func deselectAllItems(animated: Bool) { let indexPaths = self.indexPathsForSelectedItems indexPaths?.forEach({ self.deselectItem(at: $0, animated: animated) }) } var availableContentSize: CGSize { let insets = self.adjustedContentInset let width = self.bounds.width - insets.left - insets.right let height = self.bounds.height - insets.top - insets.bottom return CGSize(width: width, height: height) } } // Extensions for ReminderGedeg extension UICollectionView: ItemAndSectionable {} extension UITableView: ItemAndSectionable { public func numberOfItems(inSection section: Int) -> Int { return self.numberOfRows(inSection: section) } } // Extensions for ReminderSummary Screen extension UITableView { public var lastIndexPath: IndexPath? { let lastSection = self.numberOfSections - 1 guard lastSection >= 0 else { return nil } let lastRow = self.numberOfRows(inSection: lastSection) - 1 guard lastRow >= 0 else { return nil } return IndexPath(row: lastRow, section: lastSection) } public var allRowsVisible: Bool { let visibleIndexPaths = self.indexPathsForVisibleRows ?? [] guard visibleIndexPaths.isEmpty == false else { return false } let numberOfSections = self.dataSource?.numberOfSections?(in: self) ?? 0 guard numberOfSections > 0 else { return false } let numberOfRows = (0..<numberOfSections).reduce(0) { (prevValue, section) -> Int in let numberOfRows = self.dataSource?.tableView(self, numberOfRowsInSection: section) ?? 0 return numberOfRows + prevValue } let test = numberOfRows == visibleIndexPaths.count return test } public var visibleRowsSize: CGSize { let visibleIndexPaths = self.indexPathsForVisibleRows ?? [] guard visibleIndexPaths.isEmpty == false else { return .zero } let sections = Set(visibleIndexPaths.map({ return $0.section })) let sectionHeaderFooterHeights = sections.reduce(0) { (lastValue, section) -> CGFloat in let headerView = self.headerView(forSection: section) let footerView = self.footerView(forSection: section) return lastValue + (headerView?.frame.height ?? 0) + (footerView?.frame.height ?? 0) } let rowHeights = visibleIndexPaths.reduce(0) { (lastValue, indexPath) -> CGFloat in let _cellView = self.cellForRow(at: indexPath) guard let cellView = _cellView else { return lastValue } return lastValue + cellView.frame.height } let tableHeaderFooterHeights = { () -> CGFloat in let headerView = self.tableHeaderView let footerView = self.tableFooterView return (headerView?.frame.height ?? 0) + (footerView?.frame.height ?? 0) }() let width = self.frame.width let height = sectionHeaderFooterHeights + rowHeights + tableHeaderFooterHeights return CGSize(width: width, height: height) } public func scrollToBottom(_ animated: Bool) { guard let lastIndexPath = self.lastIndexPath else { return } self.scrollToRow(at: lastIndexPath, at: .top, animated: animated) } }
gpl-3.0
b047170cdddba700b3dc41a398d351ab
39.514286
100
0.668782
4.763718
false
false
false
false
wallflyrepo/Ject
Example/Ject/ViewController.swift
1
1843
// // ViewController.swift // Ject // // Created by [email protected] on 09/26/2017. // Copyright (c) 2017 [email protected]. All rights reserved. // import UIKit import Ject struct Dependencies { static var instance = Dependencies() lazy var manager = DependencyManager() private init(){ //Default Constructor } } class LogUtils: Injectable { required init() { } func inject(dependencyGraph: DependencyGraph) -> Injectable { return LogUtils() } func isSingleton() -> Bool { return true } func print(statement: String) { print(statement: statement) } } class ViewUtils: Injectable { var logUtils: LogUtils? required init() { } init(_ logUtils: LogUtils) { self.logUtils = logUtils } func inject(dependencyGraph: DependencyGraph) -> Injectable { return ViewUtils(dependencyGraph.inject(LogUtils.self)) } func isSingleton() -> Bool { return false } func printViewStuff(view: UIView) { logUtils?.print(statement: "View - \(view.tag)") } } class ViewController: UIViewController { var manager: DependencyManager { return Dependencies.instance.manager } var logUtils: LogUtils { return manager.inject(LogUtils.self) } var viewUtils: ViewUtils { return manager.inject(ViewUtils.self) } override func viewDidLoad() { super.viewDidLoad() logUtils.print(statement: "Some Statement.") let imageView = UIImageView() imageView.tag = 5 viewUtils.printViewStuff(view: imageView) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
apache-2.0
8b9f4dcf827002bebfceba36016084e1
18
65
0.597396
4.451691
false
false
false
false
gregomni/swift
stdlib/public/Differentiation/ArrayDifferentiation.swift
9
14408
//===--- ArrayDifferentiation.swift ---------------------------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2019 - 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Swift //===----------------------------------------------------------------------===// // Protocol conformances //===----------------------------------------------------------------------===// extension Array where Element: Differentiable { /// The view of an array as the differentiable product manifold of `Element` /// multiplied with itself `count` times. @frozen public struct DifferentiableView { var _base: [Element] } } extension Array.DifferentiableView: Differentiable where Element: Differentiable { /// The viewed array. public var base: [Element] { get { _base } _modify { yield &_base } } @usableFromInline @derivative(of: base) func _vjpBase() -> ( value: [Element], pullback: (Array<Element>.TangentVector) -> TangentVector ) { return (base, { $0 }) } @usableFromInline @derivative(of: base) func _jvpBase() -> ( value: [Element], differential: (Array<Element>.TangentVector) -> TangentVector ) { return (base, { $0 }) } /// Creates a differentiable view of the given array. public init(_ base: [Element]) { self._base = base } @usableFromInline @derivative(of: init(_:)) static func _vjpInit(_ base: [Element]) -> ( value: Array.DifferentiableView, pullback: (TangentVector) -> TangentVector ) { return (Array.DifferentiableView(base), { $0 }) } @usableFromInline @derivative(of: init(_:)) static func _jvpInit(_ base: [Element]) -> ( value: Array.DifferentiableView, differential: (TangentVector) -> TangentVector ) { return (Array.DifferentiableView(base), { $0 }) } public typealias TangentVector = Array<Element.TangentVector>.DifferentiableView public mutating func move(by offset: TangentVector) { if offset.base.isEmpty { return } precondition( base.count == offset.base.count, """ Count mismatch: \(base.count) ('self') and \(offset.base.count) \ ('direction') """) for i in offset.base.indices { base[i].move(by: offset.base[i]) } } } extension Array.DifferentiableView: Equatable where Element: Differentiable & Equatable { public static func == ( lhs: Array.DifferentiableView, rhs: Array.DifferentiableView ) -> Bool { return lhs.base == rhs.base } } extension Array.DifferentiableView: ExpressibleByArrayLiteral where Element: Differentiable { public init(arrayLiteral elements: Element...) { self.init(elements) } } extension Array.DifferentiableView: CustomStringConvertible where Element: Differentiable { public var description: String { return base.description } } extension Array.DifferentiableView: CustomReflectable { public var customMirror: Mirror { return base.customMirror } } /// Makes `Array.DifferentiableView` additive as the product space. /// /// Note that `Array.DifferentiableView([])` is the zero in the product spaces /// of all counts. extension Array.DifferentiableView: AdditiveArithmetic where Element: AdditiveArithmetic & Differentiable { public static var zero: Array.DifferentiableView { return Array.DifferentiableView([]) } public static func + ( lhs: Array.DifferentiableView, rhs: Array.DifferentiableView ) -> Array.DifferentiableView { if lhs.base.count == 0 { return rhs } if rhs.base.count == 0 { return lhs } precondition( lhs.base.count == rhs.base.count, "Count mismatch: \(lhs.base.count) and \(rhs.base.count)") return Array.DifferentiableView(zip(lhs.base, rhs.base).map(+)) } public static func - ( lhs: Array.DifferentiableView, rhs: Array.DifferentiableView ) -> Array.DifferentiableView { if lhs.base.count == 0 { return rhs } if rhs.base.count == 0 { return lhs } precondition( lhs.base.count == rhs.base.count, "Count mismatch: \(lhs.base.count) and \(rhs.base.count)") return Array.DifferentiableView(zip(lhs.base, rhs.base).map(-)) } @inlinable public subscript(_ index: Int) -> Element { if index < base.count { return base[index] } else { return Element.zero } } } /// Makes `Array` differentiable as the product manifold of `Element` /// multiplied with itself `count` times. extension Array: Differentiable where Element: Differentiable { // In an ideal world, `TangentVector` would be `[Element.TangentVector]`. // Unfortunately, we cannot conform `Array` to `AdditiveArithmetic` for // `TangentVector` because `Array` already has a static `+` method with // different semantics from `AdditiveArithmetic.+`. So we use // `Array.DifferentiableView` for all these associated types. public typealias TangentVector = Array<Element.TangentVector>.DifferentiableView public mutating func move(by offset: TangentVector) { var view = DifferentiableView(self) view.move(by: offset) self = view.base } } //===----------------------------------------------------------------------===// // Derivatives //===----------------------------------------------------------------------===// extension Array where Element: Differentiable { @usableFromInline @derivative(of: subscript) func _vjpSubscript(index: Int) -> ( value: Element, pullback: (Element.TangentVector) -> TangentVector ) { func pullback(_ v: Element.TangentVector) -> TangentVector { var dSelf = [Element.TangentVector]( repeating: .zero, count: count) dSelf[index] = v return TangentVector(dSelf) } return (self[index], pullback) } @usableFromInline @derivative(of: subscript) func _jvpSubscript(index: Int) -> ( value: Element, differential: (TangentVector) -> Element.TangentVector ) { func differential(_ v: TangentVector) -> Element.TangentVector { return v[index] } return (self[index], differential) } @usableFromInline @derivative(of: +) static func _vjpConcatenate(_ lhs: Self, _ rhs: Self) -> ( value: Self, pullback: (TangentVector) -> (TangentVector, TangentVector) ) { func pullback(_ v: TangentVector) -> (TangentVector, TangentVector) { if v.base.isEmpty { return (.zero, .zero) } precondition( v.base.count == lhs.count + rhs.count, """ Tangent vector with invalid count \(v.base.count); expected to \ equal the sum of operand counts \(lhs.count) and \(rhs.count) """) return ( TangentVector([Element.TangentVector](v.base[0..<lhs.count])), TangentVector([Element.TangentVector](v.base[lhs.count...])) ) } return (lhs + rhs, pullback) } @usableFromInline @derivative(of: +) static func _jvpConcatenate(_ lhs: Self, _ rhs: Self) -> ( value: Self, differential: (TangentVector, TangentVector) -> TangentVector ) { func differential(_ l: TangentVector, _ r: TangentVector) -> TangentVector { precondition( l.base.count == lhs.count && r.base.count == rhs.count, """ Tangent vectors with invalid count; expected to equal the \ operand counts \(lhs.count) and \(rhs.count) """) return .init(l.base + r.base) } return (lhs + rhs, differential) } } extension Array where Element: Differentiable { @usableFromInline @derivative(of: append) mutating func _vjpAppend(_ element: Element) -> ( value: Void, pullback: (inout TangentVector) -> Element.TangentVector ) { let appendedElementIndex = count append(element) return ((), { v in defer { v.base.removeLast() } return v.base[appendedElementIndex] }) } @usableFromInline @derivative(of: append) mutating func _jvpAppend(_ element: Element) -> ( value: Void, differential: (inout TangentVector, Element.TangentVector) -> Void ) { append(element) return ((), { $0.base.append($1) }) } } extension Array where Element: Differentiable { @usableFromInline @derivative(of: +=) static func _vjpAppend(_ lhs: inout Self, _ rhs: Self) -> ( value: Void, pullback: (inout TangentVector) -> TangentVector ) { let lhsCount = lhs.count lhs += rhs return ((), { v in let drhs = TangentVector(.init(v.base.dropFirst(lhsCount))) let rhsCount = drhs.base.count v.base.removeLast(rhsCount) return drhs }) } @usableFromInline @derivative(of: +=) static func _jvpAppend(_ lhs: inout Self, _ rhs: Self) -> ( value: Void, differential: (inout TangentVector, TangentVector) -> Void ) { lhs += rhs return ((), { $0.base += $1.base }) } } extension Array where Element: Differentiable { @usableFromInline @derivative(of: init(repeating:count:)) static func _vjpInit(repeating repeatedValue: Element, count: Int) -> ( value: Self, pullback: (TangentVector) -> Element.TangentVector ) { ( value: Self(repeating: repeatedValue, count: count), pullback: { v in v.base.reduce(.zero, +) } ) } @usableFromInline @derivative(of: init(repeating:count:)) static func _jvpInit(repeating repeatedValue: Element, count: Int) -> ( value: Self, differential: (Element.TangentVector) -> TangentVector ) { ( value: Self(repeating: repeatedValue, count: count), differential: { v in TangentVector(.init(repeating: v, count: count)) } ) } } //===----------------------------------------------------------------------===// // Differentiable higher order functions for collections //===----------------------------------------------------------------------===// extension Array where Element: Differentiable { @inlinable @differentiable(reverse, wrt: self) public func differentiableMap<Result: Differentiable>( _ body: @differentiable(reverse) (Element) -> Result ) -> [Result] { map(body) } @inlinable @derivative(of: differentiableMap) internal func _vjpDifferentiableMap<Result: Differentiable>( _ body: @differentiable(reverse) (Element) -> Result ) -> ( value: [Result], pullback: (Array<Result>.TangentVector) -> Array.TangentVector ) { var values: [Result] = [] var pullbacks: [(Result.TangentVector) -> Element.TangentVector] = [] for x in self { let (y, pb) = valueWithPullback(at: x, of: body) values.append(y) pullbacks.append(pb) } func pullback(_ tans: Array<Result>.TangentVector) -> Array.TangentVector { .init(zip(tans.base, pullbacks).map { tan, pb in pb(tan) }) } return (value: values, pullback: pullback) } @inlinable @derivative(of: differentiableMap) internal func _jvpDifferentiableMap<Result: Differentiable>( _ body: @differentiable(reverse) (Element) -> Result ) -> ( value: [Result], differential: (Array.TangentVector) -> Array<Result>.TangentVector ) { var values: [Result] = [] var differentials: [(Element.TangentVector) -> Result.TangentVector] = [] for x in self { let (y, df) = valueWithDifferential(at: x, of: body) values.append(y) differentials.append(df) } func differential(_ tans: Array.TangentVector) -> Array<Result>.TangentVector { .init(zip(tans.base, differentials).map { tan, df in df(tan) }) } return (value: values, differential: differential) } } extension Array where Element: Differentiable { @inlinable @differentiable(reverse, wrt: (self, initialResult)) public func differentiableReduce<Result: Differentiable>( _ initialResult: Result, _ nextPartialResult: @differentiable(reverse) (Result, Element) -> Result ) -> Result { reduce(initialResult, nextPartialResult) } @inlinable @derivative(of: differentiableReduce) internal func _vjpDifferentiableReduce<Result: Differentiable>( _ initialResult: Result, _ nextPartialResult: @differentiable(reverse) (Result, Element) -> Result ) -> ( value: Result, pullback: (Result.TangentVector) -> (Array.TangentVector, Result.TangentVector) ) { var pullbacks: [(Result.TangentVector) -> (Result.TangentVector, Element.TangentVector)] = [] let count = self.count pullbacks.reserveCapacity(count) var result = initialResult for element in self { let (y, pb) = valueWithPullback(at: result, element, of: nextPartialResult) result = y pullbacks.append(pb) } return ( value: result, pullback: { tangent in var resultTangent = tangent var elementTangents = TangentVector([]) elementTangents.base.reserveCapacity(count) for pullback in pullbacks.reversed() { let (newResultTangent, elementTangent) = pullback(resultTangent) resultTangent = newResultTangent elementTangents.base.append(elementTangent) } return (TangentVector(elementTangents.base.reversed()), resultTangent) } ) } @inlinable @derivative(of: differentiableReduce, wrt: (self, initialResult)) func _jvpDifferentiableReduce<Result: Differentiable>( _ initialResult: Result, _ nextPartialResult: @differentiable(reverse) (Result, Element) -> Result ) -> (value: Result, differential: (Array.TangentVector, Result.TangentVector) -> Result.TangentVector) { var differentials: [(Result.TangentVector, Element.TangentVector) -> Result.TangentVector] = [] let count = self.count differentials.reserveCapacity(count) var result = initialResult for element in self { let (y, df) = valueWithDifferential(at: result, element, of: nextPartialResult) result = y differentials.append(df) } return (value: result, differential: { dSelf, dInitial in var dResult = dInitial for (dElement, df) in zip(dSelf.base, differentials) { dResult = df(dResult, dElement) } return dResult }) } }
apache-2.0
3278320a692ea882706f4b49371daadc
29.460888
83
0.633606
4.364738
false
false
false
false
jessesquires/Cartography
CartographyTests/DimensionSpec.swift
15
4394
import Cartography import Nimble import Quick class DimensionSpec: QuickSpec { override func spec() { var superview: View! var view: View! beforeEach { superview = TestView(frame: CGRectMake(0, 0, 400, 400)) view = TestView(frame: CGRectZero) superview.addSubview(view) } describe("LayoutProxy.width") { it("should support relative equalities") { layout(view) { view in view.width == view.superview!.width } expect(view.frame.width).to(equal(400)) } it("should support relative inequalities") { layout(view) { view in view.width <= view.superview!.width view.width >= view.superview!.width } expect(view.frame.width).to(equal(400)) } it("should support addition") { layout(view) { view in view.width == view.superview!.width + 100 } expect(view.frame.width).to(equal(500)) } it("should support subtraction") { layout(view) { view in view.width == view.superview!.width - 100 } expect(view.frame.width).to(equal(300)) } it("should support multiplication") { layout(view) { view in view.width == view.superview!.width * 2 } expect(view.frame.width).to(equal(800)) } it("should support division") { layout(view) { view in view.width == view.superview!.width / 2 } expect(view.frame.width).to(equal(200)) } it("should support complex expressions") { layout(view) { view in view.width == view.superview!.width / 2 + 100 } expect(view.frame.width).to(equal(300)) } it("should support numerical equalities") { layout(view) { view in view.width == 200 } expect(view.frame.width).to(equal(200)) } } describe("LayoutProxy.height") { it("should support relative equalities") { layout(view) { view in view.height == view.superview!.height } expect(view.frame.height).to(equal(400)) } it("should support relative inequalities") { layout(view) { view in view.height <= view.superview!.height view.height >= view.superview!.height } expect(view.frame.height).to(equal(400)) } it("should support addition") { layout(view) { view in view.height == view.superview!.height + 100 } expect(view.frame.height).to(equal(500)) } it("should support subtraction") { layout(view) { view in view.height == view.superview!.height - 100 } expect(view.frame.height).to(equal(300)) } it("should support multiplication") { layout(view) { view in view.height == view.superview!.height * 2 } expect(view.frame.height).to(equal(800)) } it("should support division") { layout(view) { view in view.height == view.superview!.height / 2 } expect(view.frame.height).to(equal(200)) } it("should support complex expressions") { layout(view) { view in view.height == view.superview!.height / 2 + 100 } expect(view.frame.height).to(equal(300)) } it("should support numerical equalities") { layout(view) { view in view.height == 200 } expect(view.frame.height).to(equal(200)) } } } }
mit
c1dfbb2c64a5f62cd634ad90f78a6c45
27.907895
67
0.448794
5.097448
false
false
false
false
iDevelopper/PBRevealViewController
Example3Swift/Example3Swift/RevealViewController.swift
1
3313
// // RevealViewController.swift // Example3Swift // // Created by Patrick BODET on 27/08/2016. // Copyright © 2016 iDevelopper. All rights reserved. // import UIKit class RevealViewController: PBRevealViewController, PBRevealViewControllerDelegate { override func viewDidLoad() { super.viewDidLoad() delegate = self leftViewRevealWidth = 180 leftViewBlurEffectStyle = .light leftToggleSpringDampingRatio = 1.0 rightPresentViewHierarchically = true rightViewBlurEffectStyle = .light } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - PBRevealViewController delegate /* func revealController(revealController: PBRevealViewController!, didShowLeftViewController controller: UIViewController!) { revealController.mainViewController.view.userInteractionEnabled = false } func revealController(revealController: PBRevealViewController!, didHideLeftViewController controller: UIViewController!) { revealController.mainViewController.view.userInteractionEnabled = true } func revealController(revealController: PBRevealViewController!, didShowRightViewController controller: UIViewController!) { revealController.mainViewController.view.userInteractionEnabled = false } func revealController(revealController: PBRevealViewController!, didHideRightViewController controller: UIViewController!) { revealController.mainViewController.view.userInteractionEnabled = true } */ func revealController(_ revealController: PBRevealViewController!, blockFor operation: PBRevealControllerOperation, from fromViewController: UIViewController!, to toViewController: UIViewController!, finalBlock: (() -> Void)!) -> (() -> Void)! { if operation == .pushMainControllerFromLeft || operation == .pushMainControllerFromRight { let block = { () -> Void in if operation == .pushMainControllerFromLeft {revealController.revealLeftView()} else {revealController.revealRightView()} // superview: Container view UIView.transition(with: fromViewController.view.superview!, duration: 0.8, options: [.transitionCurlUp, .showHideTransitionViews], animations: { fromViewController.view.isHidden = true }, completion: { (finished) in finalBlock() }) } return block; } if (UIDevice.current.systemVersion as NSString).floatValue >= 10.0 { if operation == .replaceLeftController || operation == .replaceRightController { let block = { () -> Void in UIView.transition(with: fromViewController.view.superview!, duration: 0.25, options: [.showHideTransitionViews, .layoutSubviews], animations: { fromViewController.view.isHidden = true }, completion: { (finished) in finalBlock() }) } return block; } } return nil } }
mit
961837e102129eaab5c0d976a3a20a55
40.4
249
0.648853
5.98915
false
false
false
false
simonprickett/barttv
tvos/barttv/AppDelegate.swift
1
5580
// // AppDelegate.swift // barttv // // Copyright (c) 2016 crudworks.org. All rights reserved. // import UIKit import TVMLKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, TVApplicationControllerDelegate { var window: UIWindow? var appController: TVApplicationController? static let tvBaseURL = "http://localhost:8000/" static let tvBootURL = "\(AppDelegate.tvBaseURL)/application.js" // MARK: Javascript Execution Helper func executeRemoteMethod(_ methodName: String, completion: @escaping (Bool) -> Void) { appController?.evaluate(inJavaScriptContext: { (context: JSContext) in let appObject : JSValue = context.objectForKeyedSubscript("App") if appObject.hasProperty(methodName) { appObject.invokeMethod(methodName, withArguments: []) } }, completion: completion) } // MARK: UIApplicationDelegate func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. window = UIWindow(frame: UIScreen.main.bounds) // Create the TVApplicationControllerContext for this application and set the properties that will be passed to the `App.onLaunch` function in JavaScript. let appControllerContext = TVApplicationControllerContext() // The JavaScript URL is used to create the JavaScript context for your TVMLKit application. Although it is possible to separate your JavaScript into separate files, to help reduce the launch time of your application we recommend creating minified and compressed version of this resource. This will allow for the resource to be retrieved and UI presented to the user quickly. if let javaScriptURL = URL(string: AppDelegate.tvBootURL) { appControllerContext.javaScriptApplicationURL = javaScriptURL } appControllerContext.launchOptions["BASEURL"] = AppDelegate.tvBaseURL if let launchOptions = launchOptions { for (kind, value) in launchOptions { appControllerContext.launchOptions[kind.rawValue] = value } } appController = TVApplicationController(context: appControllerContext, window: window, delegate: self) return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and stop playback executeRemoteMethod("onWillResignActive", completion: { (success: Bool) in // ... }) } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. executeRemoteMethod("onDidEnterBackground", completion: { (success: Bool) in // ... }) } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. executeRemoteMethod("onWillEnterForeground", completion: { (success: Bool) in // ... }) } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. executeRemoteMethod("onDidBecomeActive", completion: { (success: Bool) in // ... }) } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. executeRemoteMethod("onWillTerminate", completion: { (success: Bool) in // ... }) } // MARK: TVApplicationControllerDelegate func appController(_ appController: TVApplicationController, didFinishLaunching options: [String: Any]?) { print("\(#function) invoked with options: \(options)") } func appController(_ appController: TVApplicationController, didFail error: Error) { print("\(#function) invoked with error: \(error)") let title = "Error Launching Application" let message = error.localizedDescription let alertController = UIAlertController(title: title, message: message, preferredStyle:.alert ) self.appController?.navigationController.present(alertController, animated: true, completion: { // ... }) } func appController(_ appController: TVApplicationController, didStop options: [String: Any]?) { print("\(#function) invoked with options: \(options)") } }
mit
902f5d4ac39bf62ed9795885e69e9753
45.890756
383
0.687097
5.782383
false
false
false
false
CooperCorona/Voronoi
Sources/Voronoi/WeakReference.swift
1
1126
// // WeakReference.swift // CoronaMath // // Created by Cooper Knaak on 1/10/19. // import Foundation ///A wrapper for a class object that maintains a weak reference to the object. ///For example, useful for storing weak references in an array. public class WeakReference<T: AnyObject>: Hashable { ///The object to be wrapped. public private(set) weak var object:T? = nil public func hash(into hasher:inout Hasher) { if let obj = self.object { hasher.combine(Unmanaged.passUnretained(obj).toOpaque()) } else { hasher.combine(0) } } ///Initializes a `WeakReference` instance by wrapping the given object. ///- parameter object: The object to wrap in a weak reference. public init(object:T?) { self.object = object } } public func ==<T>(lhs: WeakReference<T>, rhs: WeakReference<T>) -> Bool where T: AnyObject { if lhs.object == nil && rhs.object == nil { return true } guard let leftObject = lhs.object, let rightObject = rhs.object else { return false } return leftObject === rightObject }
mit
50b8e204ee34d765c964bf2c443cd3c8
25.809524
92
0.641208
4.05036
false
false
false
false
Mindera/Alicerce
Tests/AlicerceTests/AutoLayout/XCTAssertConstraint.swift
1
2520
import XCTest func XCTAssertConstraint( _ constraint1: NSLayoutConstraint, _ constraint2: NSLayoutConstraint, file: StaticString = #file, line: UInt = #line ) { if let item = constraint1.firstItem as? UIView, item === constraint2.firstItem { XCTAssertFalse(item.translatesAutoresizingMaskIntoConstraints, file: file, line: line) } XCTAssertIdentical(constraint1.firstItem, constraint2.firstItem, file: file, line: line) XCTAssertEqual(constraint1.firstAttribute, constraint2.firstAttribute, file: file, line: line) XCTAssertIdentical(constraint1.secondItem, constraint2.secondItem, file: file, line: line) XCTAssertEqual(constraint1.secondAttribute, constraint2.secondAttribute, file: file, line: line) XCTAssertEqual(constraint1.relation, constraint2.relation, file: file, line: line) XCTAssertEqual(constraint1.multiplier, constraint2.multiplier, file: file, line: line) XCTAssertEqual(constraint1.constant, constraint2.constant, file: file, line: line) XCTAssertEqual(constraint1.isActive, constraint2.isActive, file: file, line: line) XCTAssertEqual(constraint1.priority, constraint2.priority, file: file, line: line) } func XCTAssertConstraints( _ constraints1: [NSLayoutConstraint], _ constraints2: [NSLayoutConstraint], file: StaticString = #file, line: UInt = #line ) { zip(constraints1, constraints2).forEach { constraint1, constraint2 in if let item = constraint1.firstItem as? UIView, item === constraint2.firstItem { XCTAssertFalse(item.translatesAutoresizingMaskIntoConstraints, file: file, line: line) } XCTAssertIdentical(constraint1.firstItem, constraint2.firstItem, file: file, line: line) XCTAssertEqual(constraint1.firstAttribute, constraint2.firstAttribute, file: file, line: line) XCTAssertIdentical(constraint1.secondItem, constraint2.secondItem, file: file, line: line) XCTAssertEqual(constraint1.secondAttribute, constraint2.secondAttribute, file: file, line: line) XCTAssertEqual(constraint1.relation, constraint2.relation, file: file, line: line) XCTAssertEqual(constraint1.multiplier, constraint2.multiplier, file: file, line: line) XCTAssertEqual(constraint1.constant, constraint2.constant, file: file, line: line) XCTAssertEqual(constraint1.isActive, constraint2.isActive, file: file, line: line) XCTAssertEqual(constraint1.priority, constraint2.priority, file: file, line: line) } }
mit
3d685a82c5d36693b58b78f71f270cd1
44
104
0.747222
4.5
false
false
false
false
resmio/TastyTomato
TastyTomato/Code/Extensions/Public/UIView/UIView (OriginLeftRightTopBottom).swift
1
1997
// // UIView (LeftRightTopBottom).swift // TastyTomato // // Created by Jan Nash on 7/28/16. // Copyright © 2016 resmio. All rights reserved. // import UIKit // MARK: // Public @objc extension UIView { open var origin: CGPoint { get { return self._origin } set(newOrigin) { self._origin = newOrigin } } open var left: CGFloat { get { return self._left } set(newLeft) { self._left = newLeft } } open var right: CGFloat { get { return self._right } set(newRight) { self._right = newRight } } open var top: CGFloat { get { return self._top } set(newTop) { self._top = newTop } } open var bottom: CGFloat { get { return self._bottom } set(newBottom) { self._bottom = newBottom } } } // MARK: // Private private extension UIView { var _origin: CGPoint { get { return self.frame.origin } set(newOrigin) { self.frame.origin = newOrigin } } var _left: CGFloat { get { return self.frame.origin.x } set(newLeft) { self.frame.origin.x = newLeft } } var _right: CGFloat { get { return self.left + self.width } set(newRight) { self.frame.origin.x += newRight - self.right } } var _top: CGFloat { get { return self.frame.origin.y } set(newTop) { self.frame.origin.y = newTop } } var _bottom: CGFloat { get { return self.frame.origin.y + self.height } set(newBottom) { self.frame.origin.y += newBottom - self.bottom } } }
mit
20163413a48195a2b48f1521ec1f89eb
17.654206
58
0.446894
4.175732
false
false
false
false
Sojjocola/EladeDroneControl
EladeDroneControl/StepTwoViewController.swift
1
1610
// // StepTwoViewController.swift // EladeDroneControl // // Created by François Chevalier on 20/09/2015. // Copyright © 2015 François Chevalier. All rights reserved. // import UIKit class StepTwoViewController: UIViewController { @IBOutlet weak var altitudeLabel: UILabel! @IBOutlet weak var slider: UISlider! var appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate override func viewDidLoad() { super.viewDidLoad() appDelegate.droneStartBehaviour?.altitude = Int(slider.value) // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func sliderValueChanged(sender: UISlider) { altitudeLabel.text = String(Int(slider.value)) appDelegate.droneStartBehaviour?.altitude = Int(slider.value) } //Changing Status Bar override func preferredStatusBarStyle() -> UIStatusBarStyle { //LightContent return UIStatusBarStyle.LightContent //Default //return UIStatusBarStyle.Default } // 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?) { if segue.identifier == "Connexion" { segue.destinationViewController.navigationItem.title = "Connexion" } } }
mit
59105023a869d2b13503cdcacf664e43
26.237288
106
0.664592
5.286184
false
false
false
false
ApterKingRepo/VerifyProject
VerifyProject/VerifyProject/AppDelegate.swift
1
2488
// // AppDelegate.swift // VerifyProject // // Created by wangcong on 24/05/2017. // Copyright © 2017 ApterKing. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. window = UIWindow(frame: UIScreen.main.bounds) let homeVC = ViewController(nibName: nil, bundle: nil) let navc = UINavigationController(rootViewController: homeVC) navc.view.backgroundColor = UIColor.white window?.rootViewController = navc window?.makeKeyAndVisible() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
5b09439ad54efdc0820fbdcfcf1e5262
49.755102
285
0.746281
5.563758
false
false
false
false
HongxiangShe/STV
STV/STV/Classes/Main/Lib/SHXPageView/SHXContentView.swift
1
5310
// // SHXContentView.swift // SHXPageView // // Created by 佘红响 on 2017/5/10. // Copyright © 2017年 she. All rights reserved. // import UIKit private let kContentCellId = "kContentCellId" protocol SHXContentViewDelegate: class { func contentView(_ contentView: SHXContentView, didEndScorll inIndex: Int) func contentView(_ contentView: SHXContentView, sourceIndex: Int, targetIndex: Int, progress: CGFloat) } class SHXContentView: UIView { weak var delegate: SHXContentViewDelegate? fileprivate var childVcs: [UIViewController] fileprivate var parentVc: UIViewController fileprivate var startOffestX: CGFloat = 0 fileprivate var isForbidDelegate: Bool = false fileprivate lazy var collectionView: UICollectionView = { let layout = UICollectionViewFlowLayout() layout.itemSize = self.bounds.size layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.scrollDirection = .horizontal let collectionView = UICollectionView(frame: self.bounds, collectionViewLayout: layout) collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier:kContentCellId) collectionView.dataSource = self collectionView.delegate = self collectionView.isPagingEnabled = true collectionView.showsHorizontalScrollIndicator = false collectionView.bounces = false return collectionView }() init(frame: CGRect, childVcs: [UIViewController], parentVc: UIViewController) { self.childVcs = childVcs self.parentVc = parentVc super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension SHXContentView { fileprivate func setupUI() { for childVc in childVcs { parentVc.addChildViewController(childVc) } addSubview(collectionView) } } extension SHXContentView: UICollectionViewDelegate { func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { scrollViewDidEndScroll() } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { if !decelerate { scrollViewDidEndScroll() } } func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { scrollView.isScrollEnabled = false } func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { // 开始调用代理方法 isForbidDelegate = false startOffestX = scrollView.contentOffset.x } func scrollViewDidScroll(_ scrollView: UIScrollView) { let contentOffestX = scrollView.contentOffset.x // 判断最终有没有进行滑动 guard contentOffestX != startOffestX && !isForbidDelegate else { return } var sourceIndex: Int = 0 var targetIndex: Int = 0 var progress: CGFloat = 0 let contentWidth = scrollView.bounds.width if contentOffestX > startOffestX { // 左滑动 sourceIndex = Int(contentOffestX / contentWidth) targetIndex = sourceIndex + 1 if targetIndex >= childVcs.count { targetIndex = childVcs.count - 1 } progress = (contentOffestX - startOffestX)/contentWidth if (contentOffestX - startOffestX) == contentWidth { targetIndex = sourceIndex } } else { // 右滑动 targetIndex = Int(contentOffestX/contentWidth) sourceIndex = targetIndex + 1 progress = (startOffestX - contentOffestX)/contentWidth } delegate?.contentView(self, sourceIndex: sourceIndex, targetIndex: targetIndex, progress: progress) } private func scrollViewDidEndScroll() { let index = Int(collectionView.contentOffset.x / collectionView.bounds.width) delegate?.contentView(self, didEndScorll: index) collectionView.isScrollEnabled = false } } extension SHXContentView: UICollectionViewDataSource { public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return childVcs.count } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kContentCellId, for: indexPath) for view in cell.contentView.subviews { view.removeFromSuperview() } cell.contentView.addSubview(childVcs[indexPath.item].view) return cell } } extension SHXContentView: SHXTitleViewDelegate { func titleView(_ titleView: SHXTitleView, targetIndex: Int) { // 禁止调用代理方法 isForbidDelegate = true let indexPath = IndexPath(item: targetIndex, section: 0) collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: false) } }
apache-2.0
f3a852e54e5df36b8170358987f0ee87
31.515528
148
0.661509
5.436137
false
false
false
false
idappthat/UTANow-iOS
Pods/Kingfisher/Kingfisher/ImageCache.swift
1
27642
// // ImageCache.swift // Kingfisher // // Created by Wei Wang on 15/4/6. // // Copyright (c) 2015 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit /** This notification will be sent when the disk cache got cleaned either there are cached files expired or the total size exceeding the max allowed size. The manually invoking of `clearDiskCache` method will not trigger this notification. The `object` of this notification is the `ImageCache` object which sends the notification. A list of removed hashes (files) could be retrieved by accessing the array under `KingfisherDiskCacheCleanedHashKey` key in `userInfo` of the notification object you received. By checking the array, you could know the hash codes of files are removed. The main purpose of this notification is supplying a chance to maintain some necessary information on the cached files. See [this wiki](https://github.com/onevcat/Kingfisher/wiki/How-to-implement-ETag-based-304-(Not-Modified)-handling-in-Kingfisher) for a use case on it. */ public let KingfisherDidCleanDiskCacheNotification = "com.onevcat.Kingfisher.KingfisherDidCleanDiskCacheNotification" /** Key for array of cleaned hashes in `userInfo` of `KingfisherDidCleanDiskCacheNotification`. */ public let KingfisherDiskCacheCleanedHashKey = "com.onevcat.Kingfisher.cleanedHash" private let defaultCacheName = "default" private let cacheReverseDNS = "com.onevcat.Kingfisher.ImageCache." private let ioQueueName = "com.onevcat.Kingfisher.ImageCache.ioQueue." private let processQueueName = "com.onevcat.Kingfisher.ImageCache.processQueue." private let defaultCacheInstance = ImageCache(name: defaultCacheName) private let defaultMaxCachePeriodInSecond: NSTimeInterval = 60 * 60 * 24 * 7 //Cache exists for 1 week /// It represents a task of retrieving image. You can call `cancel` on it to stop the process. public typealias RetrieveImageDiskTask = dispatch_block_t /** Cache type of a cached image. - None: The image is not cached yet when retrieving it. - Memory: The image is cached in memory. - Disk: The image is cached in disk. */ public enum CacheType { case None, Memory, Disk } /// `ImageCache` represents both the memory and disk cache system of Kingfisher. While a default image cache object will be used if you prefer the extension methods of Kingfisher, you can create your own cache object and configure it as your need. You should use an `ImageCache` object to manipulate memory and disk cache for Kingfisher. public class ImageCache { //Memory private let memoryCache = NSCache() /// The largest cache cost of memory cache. The total cost is pixel count of all cached images in memory. public var maxMemoryCost: UInt = 0 { didSet { self.memoryCache.totalCostLimit = Int(maxMemoryCost) } } //Disk private let ioQueue: dispatch_queue_t private let diskCachePath: String private var fileManager: NSFileManager! /// The longest time duration of the cache being stored in disk. Default is 1 week. public var maxCachePeriodInSecond = defaultMaxCachePeriodInSecond /// The largest disk size can be taken for the cache. It is the total allocated size of cached files in bytes. Default is 0, which means no limit. public var maxDiskCacheSize: UInt = 0 private let processQueue: dispatch_queue_t /// The default cache. public class var defaultCache: ImageCache { return defaultCacheInstance } /** Init method. Passing a name for the cache. It represents a cache folder in the memory and disk. - parameter name: Name of the cache. It will be used as the memory cache name and the disk cache folder name. This value should not be an empty string. - returns: The cache object. */ public init(name: String) { if name.isEmpty { fatalError("[Kingfisher] You should specify a name for the cache. A cache with empty name is not permitted.") } let cacheName = cacheReverseDNS + name memoryCache.name = cacheName let paths = NSSearchPathForDirectoriesInDomains(.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true) diskCachePath = (paths.first! as NSString).stringByAppendingPathComponent(cacheName) ioQueue = dispatch_queue_create(ioQueueName + name, DISPATCH_QUEUE_SERIAL) processQueue = dispatch_queue_create(processQueueName + name, DISPATCH_QUEUE_CONCURRENT) dispatch_sync(ioQueue, { () -> Void in self.fileManager = NSFileManager() }) NSNotificationCenter.defaultCenter().addObserver(self, selector: "clearMemoryCache", name: UIApplicationDidReceiveMemoryWarningNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "cleanExpiredDiskCache", name: UIApplicationWillTerminateNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "backgroundCleanExpiredDiskCache", name: UIApplicationDidEnterBackgroundNotification, object: nil) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } } // MARK: - Store & Remove public extension ImageCache { /** Store an image to cache. It will be saved to both memory and disk. It is an async operation, if you need to do something about the stored image, use `-storeImage:forKey:toDisk:completionHandler:` instead. - parameter image: The image will be stored. - parameter originalData: The original data of the image. Kingfisher will use it to check the format of the image and optimize cache size on disk. If `nil` is supplied, the image data will be saved as a normalized PNG file. It is strongly suggested to supply it whenever possible, to get a better performance and disk usage. - parameter key: Key for the image. */ public func storeImage(image: UIImage, originalData: NSData? = nil, forKey key: String) { storeImage(image, originalData: originalData,forKey: key, toDisk: true, completionHandler: nil) } /** Store an image to cache. It is an async operation. - parameter image: The image will be stored. - parameter originalData: The original data of the image. Kingfisher will use it to check the format of the image and optimize cache size on disk. If `nil` is supplied, the image data will be saved as a normalized PNG file. It is strongly suggested to supply it whenever possible, to get a better performance and disk usage. - parameter key: Key for the image. - parameter toDisk: Whether this image should be cached to disk or not. If false, the image will be only cached in memory. - parameter completionHandler: Called when stroe operation completes. */ public func storeImage(image: UIImage, originalData: NSData? = nil, forKey key: String, toDisk: Bool, completionHandler: (() -> ())?) { memoryCache.setObject(image, forKey: key, cost: image.kf_imageCost) func callHandlerInMainQueue() { if let handler = completionHandler { dispatch_async(dispatch_get_main_queue()) { handler() } } } if toDisk { dispatch_async(ioQueue, { () -> Void in let imageFormat: ImageFormat if let originalData = originalData { imageFormat = originalData.kf_imageFormat } else { imageFormat = .Unknown } let data: NSData? switch imageFormat { case .PNG: data = UIImagePNGRepresentation(image) case .JPEG: data = UIImageJPEGRepresentation(image, 1.0) case .GIF: data = UIImageGIFRepresentation(image) case .Unknown: data = originalData ?? UIImagePNGRepresentation(image.kf_normalizedImage()) } if let data = data { if !self.fileManager.fileExistsAtPath(self.diskCachePath) { do { try self.fileManager.createDirectoryAtPath(self.diskCachePath, withIntermediateDirectories: true, attributes: nil) } catch _ {} } self.fileManager.createFileAtPath(self.cachePathForKey(key), contents: data, attributes: nil) callHandlerInMainQueue() } else { callHandlerInMainQueue() } }) } else { callHandlerInMainQueue() } } /** Remove the image for key for the cache. It will be opted out from both memory and disk. It is an async operation, if you need to do something about the stored image, use `-removeImageForKey:fromDisk:completionHandler:` instead. - parameter key: Key for the image. */ public func removeImageForKey(key: String) { removeImageForKey(key, fromDisk: true, completionHandler: nil) } /** Remove the image for key for the cache. It is an async operation. - parameter key: Key for the image. - parameter fromDisk: Whether this image should be removed from disk or not. If false, the image will be only removed from memory. - parameter completionHandler: Called when removal operation completes. */ public func removeImageForKey(key: String, fromDisk: Bool, completionHandler: (() -> ())?) { memoryCache.removeObjectForKey(key) func callHandlerInMainQueue() { if let handler = completionHandler { dispatch_async(dispatch_get_main_queue()) { handler() } } } if fromDisk { dispatch_async(ioQueue, { () -> Void in do { try self.fileManager.removeItemAtPath(self.cachePathForKey(key)) } catch _ {} callHandlerInMainQueue() }) } else { callHandlerInMainQueue() } } } // MARK: - Get data from cache extension ImageCache { /** Get an image for a key from memory or disk. - parameter key: Key for the image. - parameter options: Options of retrieving image. - parameter completionHandler: Called when getting operation completes with image result and cached type of this image. If there is no such key cached, the image will be `nil`. - returns: The retrieving task. */ public func retrieveImageForKey(key: String, options:KingfisherManager.Options, completionHandler: ((UIImage?, CacheType!) -> ())?) -> RetrieveImageDiskTask? { // No completion handler. Not start working and early return. guard let completionHandler = completionHandler else { return nil } var block: RetrieveImageDiskTask? if let image = self.retrieveImageInMemoryCacheForKey(key) { //Found image in memory cache. if options.shouldDecode { dispatch_async(self.processQueue, { () -> Void in let result = image.kf_decodedImage(scale: options.scale) dispatch_async(options.queue, { () -> Void in completionHandler(result, .Memory) }) }) } else { completionHandler(image, .Memory) } } else { var sSelf: ImageCache! = self block = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS) { // Begin to load image from disk dispatch_async(sSelf.ioQueue, { () -> Void in if let image = sSelf.retrieveImageInDiskCacheForKey(key, scale: options.scale) { if options.shouldDecode { dispatch_async(sSelf.processQueue, { () -> Void in let result = image.kf_decodedImage(scale: options.scale) sSelf.storeImage(result!, forKey: key, toDisk: false, completionHandler: nil) dispatch_async(options.queue, { () -> Void in completionHandler(result, .Memory) sSelf = nil }) }) } else { sSelf.storeImage(image, forKey: key, toDisk: false, completionHandler: nil) dispatch_async(options.queue, { () -> Void in completionHandler(image, .Disk) sSelf = nil }) } } else { // No image found from either memory or disk dispatch_async(options.queue, { () -> Void in completionHandler(nil, nil) sSelf = nil }) } }) } dispatch_async(dispatch_get_main_queue(), block!) } return block } /** Get an image for a key from memory. - parameter key: Key for the image. - returns: The image object if it is cached, or `nil` if there is no such key in the cache. */ public func retrieveImageInMemoryCacheForKey(key: String) -> UIImage? { return memoryCache.objectForKey(key) as? UIImage } /** Get an image for a key from disk. - parameter key: Key for the image. - param scale: The scale factor to assume when interpreting the image data. - returns: The image object if it is cached, or `nil` if there is no such key in the cache. */ public func retrieveImageInDiskCacheForKey(key: String, scale: CGFloat = KingfisherManager.DefaultOptions.scale) -> UIImage? { return diskImageForKey(key, scale: scale) } } // MARK: - Clear & Clean extension ImageCache { /** Clear memory cache. */ @objc public func clearMemoryCache() { memoryCache.removeAllObjects() } /** Clear disk cache. This is an async operation. */ public func clearDiskCache() { clearDiskCacheWithCompletionHandler(nil) } /** Clear disk cache. This is an async operation. - parameter completionHander: Called after the operation completes. */ public func clearDiskCacheWithCompletionHandler(completionHander: (()->())?) { dispatch_async(ioQueue, { () -> Void in do { try self.fileManager.removeItemAtPath(self.diskCachePath) } catch _ { } do { try self.fileManager.createDirectoryAtPath(self.diskCachePath, withIntermediateDirectories: true, attributes: nil) } catch _ { } if let completionHander = completionHander { dispatch_async(dispatch_get_main_queue(), { () -> Void in completionHander() }) } }) } /** Clean expired disk cache. This is an async operation. */ @objc public func cleanExpiredDiskCache() { cleanExpiredDiskCacheWithCompletionHander(nil) } /** Clean expired disk cache. This is an async operation. - parameter completionHandler: Called after the operation completes. */ public func cleanExpiredDiskCacheWithCompletionHander(completionHandler: (()->())?) { // Do things in cocurrent io queue dispatch_async(ioQueue, { () -> Void in let diskCacheURL = NSURL(fileURLWithPath: self.diskCachePath) let resourceKeys = [NSURLIsDirectoryKey, NSURLContentModificationDateKey, NSURLTotalFileAllocatedSizeKey] let expiredDate = NSDate(timeIntervalSinceNow: -self.maxCachePeriodInSecond) var cachedFiles = [NSURL: [NSObject: AnyObject]]() var URLsToDelete = [NSURL]() var diskCacheSize: UInt = 0 if let fileEnumerator = self.fileManager.enumeratorAtURL(diskCacheURL, includingPropertiesForKeys: resourceKeys, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles, errorHandler: nil) { for fileURL in fileEnumerator.allObjects as! [NSURL] { do { let resourceValues = try fileURL.resourceValuesForKeys(resourceKeys) // If it is a Directory. Continue to next file URL. if let isDirectory = resourceValues[NSURLIsDirectoryKey] as? NSNumber { if isDirectory.boolValue { continue } } // If this file is expired, add it to URLsToDelete if let modificationDate = resourceValues[NSURLContentModificationDateKey] as? NSDate { if modificationDate.laterDate(expiredDate) == expiredDate { URLsToDelete.append(fileURL) continue } } if let fileSize = resourceValues[NSURLTotalFileAllocatedSizeKey] as? NSNumber { diskCacheSize += fileSize.unsignedLongValue cachedFiles[fileURL] = resourceValues } } catch _ { } } } for fileURL in URLsToDelete { do { try self.fileManager.removeItemAtURL(fileURL) } catch _ { } } if self.maxDiskCacheSize > 0 && diskCacheSize > self.maxDiskCacheSize { let targetSize = self.maxDiskCacheSize / 2 // Sort files by last modify date. We want to clean from the oldest files. let sortedFiles = cachedFiles.keysSortedByValue({ (resourceValue1, resourceValue2) -> Bool in if let date1 = resourceValue1[NSURLContentModificationDateKey] as? NSDate { if let date2 = resourceValue2[NSURLContentModificationDateKey] as? NSDate { return date1.compare(date2) == .OrderedAscending } } // Not valid date information. This should not happen. Just in case. return true }) for fileURL in sortedFiles { do { try self.fileManager.removeItemAtURL(fileURL) } catch { } URLsToDelete.append(fileURL) if let fileSize = cachedFiles[fileURL]?[NSURLTotalFileAllocatedSizeKey] as? NSNumber { diskCacheSize -= fileSize.unsignedLongValue } if diskCacheSize < targetSize { break } } } dispatch_async(dispatch_get_main_queue(), { () -> Void in if URLsToDelete.count != 0 { let cleanedHashes = URLsToDelete.map({ (url) -> String in return url.lastPathComponent! }) NSNotificationCenter.defaultCenter().postNotificationName(KingfisherDidCleanDiskCacheNotification, object: self, userInfo: [KingfisherDiskCacheCleanedHashKey: cleanedHashes]) } if let completionHandler = completionHandler { completionHandler() } }) }) } /** Clean expired disk cache when app in background. This is an async operation. In most cases, you should not call this method explicitly. It will be called automatically when `UIApplicationDidEnterBackgroundNotification` received. */ @objc public func backgroundCleanExpiredDiskCache() { func endBackgroundTask(inout task: UIBackgroundTaskIdentifier) { UIApplication.sharedApplication().endBackgroundTask(task) task = UIBackgroundTaskInvalid } var backgroundTask: UIBackgroundTaskIdentifier! backgroundTask = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler { () -> Void in endBackgroundTask(&backgroundTask!) } cleanExpiredDiskCacheWithCompletionHander { () -> () in endBackgroundTask(&backgroundTask!) } } } // MARK: - Check cache status public extension ImageCache { /** * Cache result for checking whether an image is cached for a key. */ public struct CacheCheckResult { public let cached: Bool public let cacheType: CacheType? } /** Check whether an image is cached for a key. - parameter key: Key for the image. - returns: The check result. */ public func isImageCachedForKey(key: String) -> CacheCheckResult { if memoryCache.objectForKey(key) != nil { return CacheCheckResult(cached: true, cacheType: .Memory) } let filePath = cachePathForKey(key) if fileManager.fileExistsAtPath(filePath) { return CacheCheckResult(cached: true, cacheType: .Disk) } return CacheCheckResult(cached: false, cacheType: nil) } /** Get the hash for the key. This could be used for matching files. - parameter key: The key which is used for caching. - returns: Corresponding hash. */ public func hashForKey(key: String) -> String { return cacheFileNameForKey(key) } /** Calculate the disk size taken by cache. It is the total allocated size of the cached files in bytes. - parameter completionHandler: Called with the calculated size when finishes. */ public func calculateDiskCacheSizeWithCompletionHandler(completionHandler: ((size: UInt) -> ())?) { dispatch_async(ioQueue, { () -> Void in let diskCacheURL = NSURL(fileURLWithPath: self.diskCachePath) let resourceKeys = [NSURLIsDirectoryKey, NSURLTotalFileAllocatedSizeKey] var diskCacheSize: UInt = 0 if let fileEnumerator = self.fileManager.enumeratorAtURL(diskCacheURL, includingPropertiesForKeys: resourceKeys, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles, errorHandler: nil) { for fileURL in fileEnumerator.allObjects as! [NSURL] { do { let resourceValues = try fileURL.resourceValuesForKeys(resourceKeys) // If it is a Directory. Continue to next file URL. if let isDirectory = resourceValues[NSURLIsDirectoryKey]?.boolValue { if isDirectory { continue } } if let fileSize = resourceValues[NSURLTotalFileAllocatedSizeKey] as? NSNumber { diskCacheSize += fileSize.unsignedLongValue } } catch _ { } } } dispatch_async(dispatch_get_main_queue(), { () -> Void in if let completionHandler = completionHandler { completionHandler(size: diskCacheSize) } }) }) } } // MARK: - Internal Helper extension ImageCache { func diskImageForKey(key: String, scale: CGFloat) -> UIImage? { if let data = diskImageDataForKey(key) { return UIImage.kf_imageWithData(data, scale: scale) } else { return nil } } func diskImageDataForKey(key: String) -> NSData? { let filePath = cachePathForKey(key) return NSData(contentsOfFile: filePath) } func cachePathForKey(key: String) -> String { let fileName = cacheFileNameForKey(key) return (diskCachePath as NSString).stringByAppendingPathComponent(fileName) } func cacheFileNameForKey(key: String) -> String { return key.kf_MD5() } } extension UIImage { var kf_imageCost: Int { return Int(size.height * size.width * scale * scale) } } extension Dictionary { func keysSortedByValue(isOrderedBefore:(Value, Value) -> Bool) -> [Key] { var array = Array(self) array.sortInPlace { let (_, lv) = $0 let (_, rv) = $1 return isOrderedBefore(lv, rv) } return array.map { let (k, _) = $0 return k } } }
mit
111084e6e28f72f2cd470cbac642f5f5
40.442279
337
0.572571
5.805923
false
false
false
false
austinzheng/swift
stdlib/public/core/DictionaryBridging.swift
2
25602
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #if _runtime(_ObjC) import SwiftShims /// Equivalent to `NSDictionary.allKeys`, but does not leave objects on the /// autorelease pool. internal func _stdlib_NSDictionary_allKeys( _ object: AnyObject ) -> _BridgingBuffer { let nsd = unsafeBitCast(object, to: _NSDictionary.self) let count = nsd.count let storage = _BridgingBuffer(count) nsd.getObjects(nil, andKeys: storage.baseAddress, count: count) return storage } extension _NativeDictionary { // Bridging @usableFromInline __consuming internal func bridged() -> AnyObject { // We can zero-cost bridge if our keys are verbatim // or if we're the empty singleton. // Temporary var for SOME type safety. let nsDictionary: _NSDictionaryCore if _storage === _RawDictionaryStorage.empty || count == 0 { nsDictionary = _RawDictionaryStorage.empty } else if _isBridgedVerbatimToObjectiveC(Key.self), _isBridgedVerbatimToObjectiveC(Value.self) { nsDictionary = unsafeDowncast( _storage, to: _DictionaryStorage<Key, Value>.self) } else { nsDictionary = _SwiftDeferredNSDictionary(self) } return nsDictionary } } /// An NSEnumerator that works with any _NativeDictionary of /// verbatim bridgeable elements. Used by the various NSDictionary impls. final internal class _SwiftDictionaryNSEnumerator<Key: Hashable, Value> : __SwiftNativeNSEnumerator, _NSEnumerator { @nonobjc internal var base: _NativeDictionary<Key, Value> @nonobjc internal var bridgedKeys: _BridgingHashBuffer? @nonobjc internal var nextBucket: _NativeDictionary<Key, Value>.Bucket @nonobjc internal var endBucket: _NativeDictionary<Key, Value>.Bucket @objc internal override required init() { _internalInvariantFailure("don't call this designated initializer") } internal init(_ base: __owned _NativeDictionary<Key, Value>) { _internalInvariant(_isBridgedVerbatimToObjectiveC(Key.self)) self.base = base self.bridgedKeys = nil self.nextBucket = base.hashTable.startBucket self.endBucket = base.hashTable.endBucket } @nonobjc internal init(_ deferred: __owned _SwiftDeferredNSDictionary<Key, Value>) { _internalInvariant(!_isBridgedVerbatimToObjectiveC(Key.self)) self.base = deferred.native self.bridgedKeys = deferred.bridgeKeys() self.nextBucket = base.hashTable.startBucket self.endBucket = base.hashTable.endBucket } private func bridgedKey(at bucket: _HashTable.Bucket) -> AnyObject { _internalInvariant(base.hashTable.isOccupied(bucket)) if let bridgedKeys = self.bridgedKeys { return bridgedKeys[bucket] } return _bridgeAnythingToObjectiveC(base.uncheckedKey(at: bucket)) } @objc internal func nextObject() -> AnyObject? { if nextBucket == endBucket { return nil } let bucket = nextBucket nextBucket = base.hashTable.occupiedBucket(after: nextBucket) return self.bridgedKey(at: bucket) } @objc(countByEnumeratingWithState:objects:count:) internal func countByEnumerating( with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>, objects: UnsafeMutablePointer<AnyObject>, count: Int ) -> Int { var theState = state.pointee if theState.state == 0 { theState.state = 1 // Arbitrary non-zero value. theState.itemsPtr = AutoreleasingUnsafeMutablePointer(objects) theState.mutationsPtr = _fastEnumerationStorageMutationsPtr } if nextBucket == endBucket { state.pointee = theState return 0 } // Return only a single element so that code can start iterating via fast // enumeration, terminate it, and continue via NSEnumerator. let unmanagedObjects = _UnmanagedAnyObjectArray(objects) unmanagedObjects[0] = self.bridgedKey(at: nextBucket) nextBucket = base.hashTable.occupiedBucket(after: nextBucket) state.pointee = theState return 1 } } /// This class exists for Objective-C bridging. It holds a reference to a /// _NativeDictionary, and can be upcast to NSSelf when bridging is /// necessary. This is the fallback implementation for situations where /// toll-free bridging isn't possible. On first access, a _NativeDictionary /// of AnyObject will be constructed containing all the bridged elements. final internal class _SwiftDeferredNSDictionary<Key: Hashable, Value> : __SwiftNativeNSDictionary, _NSDictionaryCore { @usableFromInline internal typealias Bucket = _HashTable.Bucket // This stored property must be stored at offset zero. We perform atomic // operations on it. // // Do not access this property directly. @nonobjc private var _bridgedKeys_DoNotUse: AnyObject? // This stored property must be stored at offset one. We perform atomic // operations on it. // // Do not access this property directly. @nonobjc private var _bridgedValues_DoNotUse: AnyObject? /// The unbridged elements. internal var native: _NativeDictionary<Key, Value> internal init(_ native: __owned _NativeDictionary<Key, Value>) { _internalInvariant(native.count > 0) _internalInvariant(!_isBridgedVerbatimToObjectiveC(Key.self) || !_isBridgedVerbatimToObjectiveC(Value.self)) self.native = native super.init() } @objc internal required init( objects: UnsafePointer<AnyObject?>, forKeys: UnsafeRawPointer, count: Int ) { _internalInvariantFailure("don't call this designated initializer") } @nonobjc private var _bridgedKeysPtr: UnsafeMutablePointer<AnyObject?> { return _getUnsafePointerToStoredProperties(self) .assumingMemoryBound(to: Optional<AnyObject>.self) } @nonobjc private var _bridgedValuesPtr: UnsafeMutablePointer<AnyObject?> { return _bridgedKeysPtr + 1 } /// The buffer for bridged keys, if present. @nonobjc private var _bridgedKeys: _BridgingHashBuffer? { guard let ref = _stdlib_atomicLoadARCRef(object: _bridgedKeysPtr) else { return nil } return unsafeDowncast(ref, to: _BridgingHashBuffer.self) } /// The buffer for bridged values, if present. @nonobjc private var _bridgedValues: _BridgingHashBuffer? { guard let ref = _stdlib_atomicLoadARCRef(object: _bridgedValuesPtr) else { return nil } return unsafeDowncast(ref, to: _BridgingHashBuffer.self) } /// Attach a buffer for bridged Dictionary keys. @nonobjc private func _initializeBridgedKeys(_ storage: _BridgingHashBuffer) { _stdlib_atomicInitializeARCRef(object: _bridgedKeysPtr, desired: storage) } /// Attach a buffer for bridged Dictionary values. @nonobjc private func _initializeBridgedValues(_ storage: _BridgingHashBuffer) { _stdlib_atomicInitializeARCRef(object: _bridgedValuesPtr, desired: storage) } @nonobjc internal func bridgeKeys() -> _BridgingHashBuffer? { if _isBridgedVerbatimToObjectiveC(Key.self) { return nil } if let bridgedKeys = _bridgedKeys { return bridgedKeys } // Allocate and initialize heap storage for bridged keys. let bridged = _BridgingHashBuffer.allocate( owner: native._storage, hashTable: native.hashTable) for bucket in native.hashTable { let object = _bridgeAnythingToObjectiveC(native.uncheckedKey(at: bucket)) bridged.initialize(at: bucket, to: object) } // Atomically put the bridged keys in place. _initializeBridgedKeys(bridged) return _bridgedKeys! } @nonobjc internal func bridgeValues() -> _BridgingHashBuffer? { if _isBridgedVerbatimToObjectiveC(Value.self) { return nil } if let bridgedValues = _bridgedValues { return bridgedValues } // Allocate and initialize heap storage for bridged values. let bridged = _BridgingHashBuffer.allocate( owner: native._storage, hashTable: native.hashTable) for bucket in native.hashTable { let value = native.uncheckedValue(at: bucket) let cocoaValue = _bridgeAnythingToObjectiveC(value) bridged.initialize(at: bucket, to: cocoaValue) } // Atomically put the bridged values in place. _initializeBridgedValues(bridged) return _bridgedValues! } @objc(copyWithZone:) internal func copy(with zone: _SwiftNSZone?) -> AnyObject { // Instances of this class should be visible outside of standard library as // having `NSDictionary` type, which is immutable. return self } @inline(__always) private func _key( at bucket: Bucket, bridgedKeys: _BridgingHashBuffer? ) -> AnyObject { if let bridgedKeys = bridgedKeys { return bridgedKeys[bucket] } return _bridgeAnythingToObjectiveC(native.uncheckedKey(at: bucket)) } @inline(__always) private func _value( at bucket: Bucket, bridgedValues: _BridgingHashBuffer? ) -> AnyObject { if let bridgedValues = bridgedValues { return bridgedValues[bucket] } return _bridgeAnythingToObjectiveC(native.uncheckedValue(at: bucket)) } @objc(objectForKey:) internal func object(forKey aKey: AnyObject) -> AnyObject? { guard let nativeKey = _conditionallyBridgeFromObjectiveC(aKey, Key.self) else { return nil } let (bucket, found) = native.find(nativeKey) guard found else { return nil } return _value(at: bucket, bridgedValues: bridgeValues()) } @objc internal func keyEnumerator() -> _NSEnumerator { if _isBridgedVerbatimToObjectiveC(Key.self) { return _SwiftDictionaryNSEnumerator<Key, Value>(native) } return _SwiftDictionaryNSEnumerator<Key, Value>(self) } @objc(getObjects:andKeys:count:) internal func getObjects( _ objects: UnsafeMutablePointer<AnyObject>?, andKeys keys: UnsafeMutablePointer<AnyObject>?, count: Int ) { _precondition(count >= 0, "Invalid count") guard count > 0 else { return } let bridgedKeys = bridgeKeys() let bridgedValues = bridgeValues() var i = 0 // Current position in the output buffers let bucketCount = native._storage._bucketCount defer { _fixLifetime(self) } switch (_UnmanagedAnyObjectArray(keys), _UnmanagedAnyObjectArray(objects)) { case (let unmanagedKeys?, let unmanagedObjects?): for bucket in native.hashTable { unmanagedKeys[i] = _key(at: bucket, bridgedKeys: bridgedKeys) unmanagedObjects[i] = _value(at: bucket, bridgedValues: bridgedValues) i += 1 guard i < count else { break } } case (let unmanagedKeys?, nil): for bucket in native.hashTable { unmanagedKeys[i] = _key(at: bucket, bridgedKeys: bridgedKeys) i += 1 guard i < count else { break } } case (nil, let unmanagedObjects?): for bucket in native.hashTable { unmanagedObjects[i] = _value(at: bucket, bridgedValues: bridgedValues) i += 1 guard i < count else { break } } case (nil, nil): // Do nothing break } } @objc(enumerateKeysAndObjectsWithOptions:usingBlock:) internal func enumerateKeysAndObjects( options: Int, using block: @convention(block) ( Unmanaged<AnyObject>, Unmanaged<AnyObject>, UnsafeMutablePointer<UInt8> ) -> Void) { let bridgedKeys = bridgeKeys() let bridgedValues = bridgeValues() defer { _fixLifetime(self) } var stop: UInt8 = 0 for bucket in native.hashTable { let key = _key(at: bucket, bridgedKeys: bridgedKeys) let value = _value(at: bucket, bridgedValues: bridgedValues) block( Unmanaged.passUnretained(key), Unmanaged.passUnretained(value), &stop) if stop != 0 { return } } } @objc internal var count: Int { return native.count } @objc(countByEnumeratingWithState:objects:count:) internal func countByEnumerating( with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>, objects: UnsafeMutablePointer<AnyObject>?, count: Int ) -> Int { defer { _fixLifetime(self) } let hashTable = native.hashTable var theState = state.pointee if theState.state == 0 { theState.state = 1 // Arbitrary non-zero value. theState.itemsPtr = AutoreleasingUnsafeMutablePointer(objects) theState.mutationsPtr = _fastEnumerationStorageMutationsPtr theState.extra.0 = CUnsignedLong(hashTable.startBucket.offset) } // Test 'objects' rather than 'count' because (a) this is very rare anyway, // and (b) the optimizer should then be able to optimize away the // unwrapping check below. if _slowPath(objects == nil) { return 0 } let unmanagedObjects = _UnmanagedAnyObjectArray(objects!) var bucket = _HashTable.Bucket(offset: Int(theState.extra.0)) let endBucket = hashTable.endBucket _precondition(bucket == endBucket || hashTable.isOccupied(bucket), "Invalid fast enumeration state") var stored = 0 // Only need to bridge once, so we can hoist it out of the loop. let bridgedKeys = bridgeKeys() for i in 0..<count { if bucket == endBucket { break } unmanagedObjects[i] = _key(at: bucket, bridgedKeys: bridgedKeys) stored += 1 bucket = hashTable.occupiedBucket(after: bucket) } theState.extra.0 = CUnsignedLong(bucket.offset) state.pointee = theState return stored } } @usableFromInline @_fixed_layout internal struct _CocoaDictionary { @usableFromInline internal let object: AnyObject @inlinable internal init(_ object: __owned AnyObject) { self.object = object } } extension _CocoaDictionary { @usableFromInline internal func isEqual(to other: _CocoaDictionary) -> Bool { return _stdlib_NSObject_isEqual(self.object, other.object) } } extension _CocoaDictionary: _DictionaryBuffer { @usableFromInline internal typealias Key = AnyObject @usableFromInline internal typealias Value = AnyObject @usableFromInline // FIXME(cocoa-index): Should be inlinable internal var startIndex: Index { @_effects(releasenone) get { let allKeys = _stdlib_NSDictionary_allKeys(self.object) return Index(Index.Storage(self, allKeys), offset: 0) } } @usableFromInline // FIXME(cocoa-index): Should be inlinable internal var endIndex: Index { @_effects(releasenone) get { let allKeys = _stdlib_NSDictionary_allKeys(self.object) return Index(Index.Storage(self, allKeys), offset: allKeys.count) } } @usableFromInline // FIXME(cocoa-index): Should be inlinable @_effects(releasenone) internal func index(after index: Index) -> Index { validate(index) var result = index result._offset += 1 return result } internal func validate(_ index: Index) { _precondition(index.storage.base.object === self.object, "Invalid index") _precondition(index._offset < index.storage.allKeys.count, "Attempt to access endIndex") } @usableFromInline // FIXME(cocoa-index): Should be inlinable internal func formIndex(after index: inout Index, isUnique: Bool) { validate(index) index._offset += 1 } @usableFromInline // FIXME(cocoa-index): Should be inlinable @_effects(releasenone) internal func index(forKey key: Key) -> Index? { // Fast path that does not involve creating an array of all keys. In case // the key is present, this lookup is a penalty for the slow path, but the // potential savings are significant: we could skip a memory allocation and // a linear search. if lookup(key) == nil { return nil } let allKeys = _stdlib_NSDictionary_allKeys(object) for i in 0..<allKeys.count { if _stdlib_NSObject_isEqual(key, allKeys[i]) { return Index(Index.Storage(self, allKeys), offset: i) } } _internalInvariantFailure( "An NSDictionary key wassn't listed amongst its enumerated contents") } @usableFromInline internal var count: Int { let nsd = unsafeBitCast(object, to: _NSDictionary.self) return nsd.count } @usableFromInline internal func contains(_ key: Key) -> Bool { let nsd = unsafeBitCast(object, to: _NSDictionary.self) return nsd.object(forKey: key) != nil } @usableFromInline internal func lookup(_ key: Key) -> Value? { let nsd = unsafeBitCast(object, to: _NSDictionary.self) return nsd.object(forKey: key) } @usableFromInline // FIXME(cocoa-index): Should be inlinable @_effects(releasenone) internal func lookup(_ index: Index) -> (key: Key, value: Value) { _precondition(index.storage.base.object === self.object, "Invalid index") let key: Key = index.storage.allKeys[index._offset] let value: Value = index.storage.base.object.object(forKey: key)! return (key, value) } @usableFromInline // FIXME(cocoa-index): Make inlinable @_effects(releasenone) func key(at index: Index) -> Key { _precondition(index.storage.base.object === self.object, "Invalid index") return index.key } @usableFromInline // FIXME(cocoa-index): Make inlinable @_effects(releasenone) func value(at index: Index) -> Value { _precondition(index.storage.base.object === self.object, "Invalid index") let key = index.storage.allKeys[index._offset] return index.storage.base.object.object(forKey: key)! } } extension _CocoaDictionary { @inlinable internal func mapValues<Key: Hashable, Value, T>( _ transform: (Value) throws -> T ) rethrows -> _NativeDictionary<Key, T> { var result = _NativeDictionary<Key, T>(capacity: self.count) for (cocoaKey, cocoaValue) in self { let key = _forceBridgeFromObjectiveC(cocoaKey, Key.self) let value = _forceBridgeFromObjectiveC(cocoaValue, Value.self) try result.insertNew(key: key, value: transform(value)) } return result } } extension _CocoaDictionary { @_fixed_layout @usableFromInline internal struct Index { internal var _storage: Builtin.BridgeObject internal var _offset: Int internal var storage: Storage { @inline(__always) get { let storage = _bridgeObject(toNative: _storage) return unsafeDowncast(storage, to: Storage.self) } } internal init(_ storage: Storage, offset: Int) { self._storage = _bridgeObject(fromNative: storage) self._offset = offset } } } extension _CocoaDictionary.Index { // FIXME(cocoa-index): Try using an NSEnumerator to speed this up. internal class Storage { // Assumption: we rely on NSDictionary.getObjects when being // repeatedly called on the same NSDictionary, returning items in the same // order every time. // Similarly, the same assumption holds for NSSet.allObjects. /// A reference to the NSDictionary, which owns members in `allObjects`, /// or `allKeys`, for NSSet and NSDictionary respectively. internal let base: _CocoaDictionary // FIXME: swift-3-indexing-model: try to remove the cocoa reference, but // make sure that we have a safety check for accessing `allKeys`. Maybe // move both into the dictionary/set itself. /// An unowned array of keys. internal var allKeys: _BridgingBuffer internal init( _ base: __owned _CocoaDictionary, _ allKeys: __owned _BridgingBuffer ) { self.base = base self.allKeys = allKeys } } } extension _CocoaDictionary.Index { @usableFromInline internal var handleBitPattern: UInt { @_effects(readonly) get { return unsafeBitCast(storage, to: UInt.self) } } @usableFromInline internal var dictionary: _CocoaDictionary { @_effects(releasenone) get { return storage.base } } } extension _CocoaDictionary.Index { @usableFromInline // FIXME(cocoa-index): Make inlinable @nonobjc internal var key: AnyObject { @_effects(readonly) get { _precondition(_offset < storage.allKeys.count, "Attempting to access Dictionary elements using an invalid index") return storage.allKeys[_offset] } } @usableFromInline // FIXME(cocoa-index): Make inlinable @nonobjc internal var age: Int32 { @_effects(readonly) get { return _HashTable.age(for: storage.base.object) } } } extension _CocoaDictionary.Index: Equatable { @usableFromInline // FIXME(cocoa-index): Make inlinable @_effects(readonly) internal static func == ( lhs: _CocoaDictionary.Index, rhs: _CocoaDictionary.Index ) -> Bool { _precondition(lhs.storage.base.object === rhs.storage.base.object, "Comparing indexes from different dictionaries") return lhs._offset == rhs._offset } } extension _CocoaDictionary.Index: Comparable { @usableFromInline // FIXME(cocoa-index): Make inlinable @_effects(readonly) internal static func < ( lhs: _CocoaDictionary.Index, rhs: _CocoaDictionary.Index ) -> Bool { _precondition(lhs.storage.base.object === rhs.storage.base.object, "Comparing indexes from different dictionaries") return lhs._offset < rhs._offset } } extension _CocoaDictionary: Sequence { @usableFromInline final internal class Iterator { // Cocoa Dictionary iterator has to be a class, otherwise we cannot // guarantee that the fast enumeration struct is pinned to a certain memory // location. // This stored property should be stored at offset zero. There's code below // relying on this. internal var _fastEnumerationState: _SwiftNSFastEnumerationState = _makeSwiftNSFastEnumerationState() // This stored property should be stored right after // `_fastEnumerationState`. There's code below relying on this. internal var _fastEnumerationStackBuf = _CocoaFastEnumerationStackBuf() internal let base: _CocoaDictionary internal var _fastEnumerationStatePtr: UnsafeMutablePointer<_SwiftNSFastEnumerationState> { return _getUnsafePointerToStoredProperties(self).assumingMemoryBound( to: _SwiftNSFastEnumerationState.self) } internal var _fastEnumerationStackBufPtr: UnsafeMutablePointer<_CocoaFastEnumerationStackBuf> { return UnsafeMutableRawPointer(_fastEnumerationStatePtr + 1) .assumingMemoryBound(to: _CocoaFastEnumerationStackBuf.self) } // These members have to be word-sized integers, they cannot be limited to // Int8 just because our storage holds 16 elements: fast enumeration is // allowed to return inner pointers to the container, which can be much // larger. internal var itemIndex: Int = 0 internal var itemCount: Int = 0 internal init(_ base: __owned _CocoaDictionary) { self.base = base } } @usableFromInline @_effects(releasenone) internal __consuming func makeIterator() -> Iterator { return Iterator(self) } } extension _CocoaDictionary.Iterator: IteratorProtocol { @usableFromInline internal typealias Element = (key: AnyObject, value: AnyObject) @usableFromInline internal func nextKey() -> AnyObject? { if itemIndex < 0 { return nil } let base = self.base if itemIndex == itemCount { let stackBufCount = _fastEnumerationStackBuf.count // We can't use `withUnsafeMutablePointer` here to get pointers to // properties, because doing so might introduce a writeback storage, but // fast enumeration relies on the pointer identity of the enumeration // state struct. itemCount = base.object.countByEnumerating( with: _fastEnumerationStatePtr, objects: UnsafeMutableRawPointer(_fastEnumerationStackBufPtr) .assumingMemoryBound(to: AnyObject.self), count: stackBufCount) if itemCount == 0 { itemIndex = -1 return nil } itemIndex = 0 } let itemsPtrUP = UnsafeMutableRawPointer(_fastEnumerationState.itemsPtr!) .assumingMemoryBound(to: AnyObject.self) let itemsPtr = _UnmanagedAnyObjectArray(itemsPtrUP) let key: AnyObject = itemsPtr[itemIndex] itemIndex += 1 return key } @usableFromInline internal func next() -> Element? { guard let key = nextKey() else { return nil } let value: AnyObject = base.object.object(forKey: key)! return (key, value) } } //===--- Bridging ---------------------------------------------------------===// extension Dictionary { @inlinable public __consuming func _bridgeToObjectiveCImpl() -> AnyObject { guard _variant.isNative else { return _variant.asCocoa.object } return _variant.asNative.bridged() } /// Returns the native Dictionary hidden inside this NSDictionary; /// returns nil otherwise. public static func _bridgeFromObjectiveCAdoptingNativeStorageOf( _ s: __owned AnyObject ) -> Dictionary<Key, Value>? { // Try all three NSDictionary impls that we currently provide. if let deferred = s as? _SwiftDeferredNSDictionary<Key, Value> { return Dictionary(_native: deferred.native) } if let nativeStorage = s as? _DictionaryStorage<Key, Value> { return Dictionary(_native: _NativeDictionary(nativeStorage)) } if s === _RawDictionaryStorage.empty { return Dictionary() } // FIXME: what if `s` is native storage, but for different key/value type? return nil } } #endif // _runtime(_ObjC)
apache-2.0
cc0250beb65bfe23e5f04d403806bb2d
30.685644
80
0.691001
4.561197
false
false
false
false
kaideyi/KDYSample
KYWebo/KYWebo/Bizs/Home/View/HomeTimelineCell.swift
1
1021
// // HomeTimelineCell.swift // KYWebo // // Created by kaideyi on 2017/8/12. // Copyright © 2017年 mac. All rights reserved. // import UIKit class HomeTimelineCell: UITableViewCell { lazy var statusView: WbStatusView = { let stauts = WbStatusView() stauts.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: 1) return stauts }() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.backgroundColor = .clear self.contentView.addSubview(statusView) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Layout func setupCell(withViewmodel viewModel: HomeItemViewModel) { self.height = viewModel.totalHeight self.contentView.height = viewModel.totalHeight statusView.setupStatus(withViewmodel: viewModel) } }
mit
1f5e685eacb882e7d4a3c4f56a7aa1a2
24.45
74
0.642436
4.350427
false
false
false
false
calkinssean/TIY-Assignments
Day 14/iReview/RestaurantProfileViewController.swift
1
1897
// // RestaurantProfileViewController.swift // iReview // // Created by Sean Calkins on 2/18/16. // Copyright © 2016 Sean Calkins. All rights reserved. // import UIKit class RestaurantProfileViewController: UIViewController { var detailRestaurant: Restaurant? var menusArray = [Menu]() @IBOutlet weak var restaurantImageView: UIImageView! @IBOutlet weak var restaurantNameLabel: UILabel! @IBOutlet weak var restaurantDescriptionLabel: UILabel! @IBOutlet weak var restaurantAddressButton: UIButton! @IBAction func addressButtonTapped(sender: UIButton) { performSegueWithIdentifier("showMapViewSegue", sender: self) } @IBAction func menuButton(sender: BorderButton) { performSegueWithIdentifier("showMenuTableViewSegue", sender: self) } override func viewDidLoad() { print(detailRestaurant?.name) print(detailRestaurant?.menusArray) super.viewDidLoad() self.restaurantImageView.image = UIImage(named: "\(detailRestaurant!.imageName)") self.restaurantNameLabel.text = detailRestaurant?.name self.restaurantDescriptionLabel.text = detailRestaurant?.description self.restaurantAddressButton.setTitle(detailRestaurant?.location, forState: UIControlState .Normal) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showMenuTableViewSegue" { let segueViewController = segue.destinationViewController as! MenuTableViewController segueViewController.menuRestaurant = detailRestaurant } if segue.identifier == "showMapViewSegue" { let segueViewController = segue.destinationViewController as! MapViewController segueViewController.currentRestaurant = detailRestaurant } } }
cc0-1.0
df8bd1d04629bff597ea4c74719a0803
32.263158
107
0.704114
5.59292
false
false
false
false
VojtechBartos/Weather-App
WeatherApp/Classes/Controller/WEANavigationController.swift
1
3347
// // WEANavigationController.swift // WeatherApp // // Created by Vojta Bartos on 13/04/15. // Copyright (c) 2015 Vojta Bartos. All rights reserved. // import UIKit class WEANavigationController: UINavigationController { // MARK: - Screen life cycle override func viewDidLoad() { super.viewDidLoad() self.setup(); self.setupObserver() } // MARK: Setup func setup() { // nice navigation bottom border line // TODO(vojta) reposition/resize on rotation if landscape is supported var image = UIImage(named: "Line") var layer = self.navigationBar.layer var borderLayer = CALayer() borderLayer.borderColor = UIColor(patternImage:image!).CGColor borderLayer.borderWidth = 2 borderLayer.frame = CGRectMake(0, layer.bounds.size.height, layer.bounds.size.width, 2); layer.addSublayer(borderLayer) } func setupObserver() { NSNotificationCenter.defaultCenter().addObserver( self, selector: Selector("showNotification:"), name: "cz.vojtechbartos.WeatherApp.notification", object: nil ) } // MARK: - Notification func showNotification(notification: NSNotification) { let notificationView = UIView() notificationView.backgroundColor = UIColor.wea_colorWithHexString("#ff8847") let label = UILabel(frame: CGRectMake(0, 0, self.view.bounds.size.width, 0)) label.textColor = UIColor.whiteColor() label.font = UIFont.wea_proximaNovaRegularWithSize(15.0) label.textAlignment = NSTextAlignment.Center label.numberOfLines = 0 label.text = notification.object?.valueForKey("message") as? String let size = label.sizeThatFits(CGSizeMake(self.view.bounds.size.width, CGFloat.max)) label.frame = CGRectMake(0, 0, self.view.bounds.size.width, size.height + 30) notificationView.frame = CGRectMake(0, 0, self.view.bounds.size.width, label.frame.size.height) notificationView.addSubview(label) self.view.insertSubview(notificationView, belowSubview: self.navigationBar) UIView.animateWithDuration(0.5, animations: { () -> Void in notificationView.frame = CGRectMake( 0, self.navigationBar.frame.height + self.navigationBar.frame.origin.y, notificationView.frame.size.width, notificationView.frame.size.height ) }, completion: { (finished: Bool) -> Void in self.removeNotification(notificationView) } ) } func removeNotification(view: UIView) { UIView.animateWithDuration(NSTimeInterval(0.5), delay: 3.0, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in view.frame = CGRectMake( 0, 0, view.frame.size.width, view.frame.size.height ) }, completion: { (finished: Bool) -> Void in view.removeFromSuperview() } ) } // MARK: - System deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } }
mit
325e5e0a11324709f51d6be485b15818
33.153061
140
0.602629
4.843705
false
false
false
false
voyages-sncf-technologies/Collor
Example/Collor/MenuSample/MenuViewController.swift
1
2538
// // MenuViewController.swift // Collor // // Created by Guihal Gwenn on 14/08/2017. // Copyright (c) 2017-present, Voyages-sncf.com. All rights reserved.. All rights reserved. // import UIKit import Collor // model struct Example { let title: String let controllerClass: UIViewController.Type } // user event enum MenuUserEvent { case itemTap(Example) } protocol MenuUserEventDelegate: CollectionUserEventDelegate { func onUserEvent(userEvent: MenuUserEvent) } // controller class MenuViewController: UIViewController { @IBOutlet weak var collectionView: UICollectionView! fileprivate(set) lazy var collectionViewDelegate: CollectionDelegate = CollectionDelegate(delegate: nil) fileprivate(set) lazy var collectionViewDatasource: CollectionDataSource = CollectionDataSource(delegate: self) let examples:[Example] = [Example(title: "Panton", controllerClass: PantoneViewController.self), Example(title: "Random", controllerClass: RandomViewController.self), Example(title: "Weather", controllerClass: WeatherViewController.self), Example(title: "Real Time", controllerClass: RealTimeViewController.self), Example(title: "Alphabet", controllerClass: AlphabetViewController.self), Example(title: "TextField", controllerClass: TextFieldViewController.self)] lazy var collectionData: MenuCollectionData = MenuCollectionData(examples: self.examples) override func viewDidLoad() { super.viewDidLoad() title = "Menu" bind(collectionView: collectionView, with: collectionData, and: collectionViewDelegate, and: collectionViewDatasource) collectionViewDelegate.forwardingDelegate = self } } extension MenuViewController: MenuUserEventDelegate { func onUserEvent(userEvent: MenuUserEvent) { switch userEvent { case .itemTap(let example): let controller = example.controllerClass.init() navigationController?.pushViewController(controller, animated: true) break } } } extension MenuViewController : ForwardingUICollectionViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { print("scroll") } func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { print("willAppear") } }
bsd-3-clause
363928b9615b0aeea549cffe18cae1c4
31.961039
133
0.691095
5.388535
false
false
false
false
SandcastleApps/partyup
PartyUP/AuthenticationManager.swift
1
5011
// // AuthenticationManager.swift // PartyUP // // Created by Fritz Vander Heide on 2016-04-17. // Copyright © 2016 Sandcastle Application Development. All rights reserved. // import Foundation import KeychainAccess import AWSCore import AWSCognito enum AuthenticationState: Int { case Unauthenticated, Transitioning, Authenticated } class AuthenticationManager: NSObject, AWSIdentityProviderManager { static let AuthenticationStatusChangeNotification = "AuthenticationStateChangeNotification" static let shared = AuthenticationManager() var authentics: [AuthenticationProvider] { return authenticators.map { $0 as AuthenticationProvider } } let user = User() var identity: NSUUID? { if let identity = credentialsProvider?.identityId { return NSUUID(UUIDString: identity[identity.endIndex.advancedBy(-36)..<identity.endIndex]) } else { return nil } } var isLoggedIn: Bool { return authenticators.reduce(false) { return $0 || $1.isLoggedIn } } private(set) var state: AuthenticationState = .Transitioning override init() { authenticators = [FacebookAuthenticationProvider(keychain: keychain)] super.init() } func loginToProvider(provider: AuthenticationProvider, fromViewController controller: UIViewController) { if let provider = provider as? AuthenticationProviding { postTransitionToState(.Transitioning, withError: nil) provider.loginFromViewController(controller, completionHander: AuthenticationManager.reportLoginWithError(self)) } } func logout() { authenticators.forEach{ $0.logout() } AWSCognito.defaultCognito().wipe() credentialsProvider?.clearKeychain() reportLoginWithError(nil) } func reportLoginWithError(error: NSError?) { var task: AWSTask? if credentialsProvider == nil { task = self.initialize() } else { credentialsProvider?.invalidateCachedTemporaryCredentials() credentialsProvider?.identityProvider.clear() task = credentialsProvider?.getIdentityId() } task?.continueWithBlock { task in var state: AuthenticationState = .Unauthenticated if self.isLoggedIn { state = .Authenticated } self.postTransitionToState(state, withError: task.error) return nil } } // MARK: - Identity Provider Manager func logins() -> AWSTask { let tasks = authenticators.map { $0.token() } return AWSTask(forCompletionOfAllTasksWithResults: tasks).continueWithSuccessBlock { task in if let tokens = task.result as? [String] { var logins = [String:String]() for authentic in zip(self.authenticators,tokens) { logins[authentic.0.identityProviderName] = authentic.1 } return logins } else { return nil } } } // MARK: - Application Delegate Integration func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { let isHandled = authenticators.reduce(false) { $0 || $1.application(application, didFinishLaunchingWithOptions: launchOptions) } resumeSession() return isHandled } func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool { return authenticators.reduce(false) { $0 || $1.application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation) } } // MARK: - Private private let keychain = Keychain(service: NSBundle.mainBundle().bundleIdentifier!) private var authenticators = [AuthenticationProviding]() private var credentialsProvider: AWSCognitoCredentialsProvider? private func resumeSession() { for auth in authenticators { if auth.wasLoggedIn { auth.resumeSessionWithCompletionHandler(AuthenticationManager.reportLoginWithError(self)) } } if credentialsProvider == nil { reportLoginWithError(nil) } } private func initialize() -> AWSTask? { credentialsProvider = AWSCognitoCredentialsProvider( regionType: PartyUpKeys.AwsRegionType, identityPoolId: PartyUpKeys.AwsIdentityPool, identityProviderManager: self) let configuration = AWSServiceConfiguration( region: PartyUpKeys.AwsRegionType, credentialsProvider: credentialsProvider) AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = configuration return self.credentialsProvider?.getIdentityId() } private func postTransitionToState(state: AuthenticationState, withError error: NSError?) { let old = self.state self.state = state dispatch_async(dispatch_get_main_queue()) { let notify = NSNotificationCenter.defaultCenter() var info: [String:AnyObject] = ["old" : old.rawValue, "new" : state.rawValue] if error != nil { info["error"] = error } notify.postNotificationName(AuthenticationManager.AuthenticationStatusChangeNotification, object: self, userInfo: info) } } }
mit
a5dbf90903b99ae6743379cfb9568ad4
31.745098
151
0.724152
4.609016
false
false
false
false
padawan/smartphone-app
MT_iOS/MT_iOS/Classes/ViewController/ImageViewController.swift
1
2247
// // ImageViewController.swift // MT_iOS // // Created by CHEEBOW on 2015/06/17. // Copyright (c) 2015年 Six Apart, Ltd. All rights reserved. // import UIKit class ImageViewController: UIViewController, UIScrollViewDelegate { var scrollView: UIScrollView! var imageView: UIImageView! var asset: Asset! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.view.backgroundColor = Color.black scrollView = UIScrollView(frame: self.view.bounds) scrollView.delegate = self scrollView.minimumZoomScale = 1 scrollView.maximumZoomScale = 4 scrollView.scrollEnabled = true scrollView.showsHorizontalScrollIndicator = true scrollView.showsVerticalScrollIndicator = true scrollView.autoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth view.addSubview(scrollView) imageView = UIImageView(frame: scrollView.bounds) imageView.contentMode = UIViewContentMode.ScaleAspectFit imageView.autoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth scrollView.addSubview(imageView) self.title = asset.dispName() self.imageView.sd_setImageWithURL(NSURL(string: asset.url)) var doubleTapGesture: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action:"doubleTap:") doubleTapGesture.numberOfTapsRequired = 2 imageView.userInteractionEnabled = true imageView.addGestureRecognizer(doubleTapGesture) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? { return imageView } func doubleTap(gesture: UITapGestureRecognizer) -> Void { if scrollView.zoomScale < scrollView.maximumZoomScale { var scale = scrollView.maximumZoomScale scrollView.setZoomScale(scale, animated: true) } else { scrollView.setZoomScale(1.0, animated: true) } } }
mit
c288b50771536b02b5c053e4831e59fb
33.538462
112
0.690423
5.816062
false
false
false
false
nathawes/swift
stdlib/public/core/Diffing.swift
8
12216
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2015 - 2019 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 // //===----------------------------------------------------------------------===// // MARK: Diff application to RangeReplaceableCollection @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) extension CollectionDifference { fileprivate func _fastEnumeratedApply( _ consume: (Change) throws -> Void ) rethrows { let totalRemoves = removals.count let totalInserts = insertions.count var enumeratedRemoves = 0 var enumeratedInserts = 0 while enumeratedRemoves < totalRemoves || enumeratedInserts < totalInserts { let change: Change if enumeratedRemoves < removals.count && enumeratedInserts < insertions.count { let removeOffset = removals[enumeratedRemoves]._offset let insertOffset = insertions[enumeratedInserts]._offset if removeOffset - enumeratedRemoves <= insertOffset - enumeratedInserts { change = removals[enumeratedRemoves] } else { change = insertions[enumeratedInserts] } } else if enumeratedRemoves < totalRemoves { change = removals[enumeratedRemoves] } else if enumeratedInserts < totalInserts { change = insertions[enumeratedInserts] } else { // Not reached, loop should have exited. preconditionFailure() } try consume(change) switch change { case .remove(_, _, _): enumeratedRemoves += 1 case .insert(_, _, _): enumeratedInserts += 1 } } } } // Error type allows the use of throw to unroll state on application failure private enum _ApplicationError : Error { case failed } extension RangeReplaceableCollection { /// Applies the given difference to this collection. /// /// - Parameter difference: The difference to be applied. /// /// - Returns: An instance representing the state of the receiver with the /// difference applied, or `nil` if the difference is incompatible with /// the receiver's state. /// /// - Complexity: O(*n* + *c*), where *n* is `self.count` and *c* is the /// number of changes contained by the parameter. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) public func applying(_ difference: CollectionDifference<Element>) -> Self? { func append( into target: inout Self, contentsOf source: Self, from index: inout Self.Index, count: Int ) throws { let start = index if !source.formIndex(&index, offsetBy: count, limitedBy: source.endIndex) { throw _ApplicationError.failed } target.append(contentsOf: source[start..<index]) } var result = Self() do { var enumeratedRemoves = 0 var enumeratedInserts = 0 var enumeratedOriginals = 0 var currentIndex = self.startIndex try difference._fastEnumeratedApply { change in switch change { case .remove(offset: let offset, element: _, associatedWith: _): let origCount = offset - enumeratedOriginals try append(into: &result, contentsOf: self, from: &currentIndex, count: origCount) if currentIndex == self.endIndex { // Removing nonexistent element off the end of the collection throw _ApplicationError.failed } enumeratedOriginals += origCount + 1 // Removal consumes an original element currentIndex = self.index(after: currentIndex) enumeratedRemoves += 1 case .insert(offset: let offset, element: let element, associatedWith: _): let origCount = (offset + enumeratedRemoves - enumeratedInserts) - enumeratedOriginals try append(into: &result, contentsOf: self, from: &currentIndex, count: origCount) result.append(element) enumeratedOriginals += origCount enumeratedInserts += 1 } _internalInvariant(enumeratedOriginals <= self.count) } if currentIndex < self.endIndex { result.append(contentsOf: self[currentIndex...]) } _internalInvariant(result.count == self.count + enumeratedInserts - enumeratedRemoves) } catch { return nil } return result } } // MARK: Definition of API extension BidirectionalCollection { /// Returns the difference needed to produce this collection's ordered /// elements from the given collection, using the given predicate as an /// equivalence test. /// /// This function does not infer element moves. If you need to infer moves, /// call the `inferringMoves()` method on the resulting difference. /// /// - Parameters: /// - other: The base state. /// - areEquivalent: A closure that returns a Boolean value indicating /// whether two elements are equivalent. /// /// - Returns: The difference needed to produce the reciever's state from /// the parameter's state. /// /// - Complexity: Worst case performance is O(*n* * *m*), where *n* is the /// count of this collection and *m* is `other.count`. You can expect /// faster execution when the collections share many common elements. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) public func difference<C: BidirectionalCollection>( from other: C, by areEquivalent: (C.Element, Element) -> Bool ) -> CollectionDifference<Element> where C.Element == Self.Element { return _myers(from: other, to: self, using: areEquivalent) } } extension BidirectionalCollection where Element: Equatable { /// Returns the difference needed to produce this collection's ordered /// elements from the given collection. /// /// This function does not infer element moves. If you need to infer moves, /// call the `inferringMoves()` method on the resulting difference. /// /// - Parameters: /// - other: The base state. /// /// - Returns: The difference needed to produce this collection's ordered /// elements from the given collection. /// /// - Complexity: Worst case performance is O(*n* * *m*), where *n* is the /// count of this collection and *m* is `other.count`. You can expect /// faster execution when the collections share many common elements, or /// if `Element` conforms to `Hashable`. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) public func difference<C: BidirectionalCollection>( from other: C ) -> CollectionDifference<Element> where C.Element == Self.Element { return difference(from: other, by: ==) } } // MARK: Internal implementation // _V is a rudimentary type made to represent the rows of the triangular matrix // type used by the Myer's algorithm. // // This type is basically an array that only supports indexes in the set // `stride(from: -d, through: d, by: 2)` where `d` is the depth of this row in // the matrix `d` is always known at allocation-time, and is used to preallocate // the structure. private struct _V { private var a: [Int] #if INTERNAL_CHECKS_ENABLED private let isOdd: Bool #endif // The way negative indexes are implemented is by interleaving them in the empty slots between the valid positive indexes @inline(__always) private static func transform(_ index: Int) -> Int { // -3, -1, 1, 3 -> 3, 1, 0, 2 -> 0...3 // -2, 0, 2 -> 2, 0, 1 -> 0...2 return (index <= 0 ? -index : index &- 1) } init(maxIndex largest: Int) { #if INTERNAL_CHECKS_ENABLED _internalInvariant(largest >= 0) isOdd = largest % 2 == 1 #endif a = [Int](repeating: 0, count: largest + 1) } subscript(index: Int) -> Int { get { #if INTERNAL_CHECKS_ENABLED _internalInvariant(isOdd == (index % 2 != 0)) #endif return a[_V.transform(index)] } set(newValue) { #if INTERNAL_CHECKS_ENABLED _internalInvariant(isOdd == (index % 2 != 0)) #endif a[_V.transform(index)] = newValue } } } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) private func _myers<C,D>( from old: C, to new: D, using cmp: (C.Element, D.Element) -> Bool ) -> CollectionDifference<C.Element> where C: BidirectionalCollection, D: BidirectionalCollection, C.Element == D.Element { // Core implementation of the algorithm described at http://www.xmailserver.org/diff2.pdf // Variable names match those used in the paper as closely as possible func _descent(from a: UnsafeBufferPointer<C.Element>, to b: UnsafeBufferPointer<D.Element>) -> [_V] { let n = a.count let m = b.count let max = n + m var result = [_V]() var v = _V(maxIndex: 1) v[1] = 0 var x = 0 var y = 0 iterator: for d in 0...max { let prev_v = v result.append(v) v = _V(maxIndex: d) // The code in this loop is _very_ hot—the loop bounds increases in terms // of the iterator of the outer loop! for k in stride(from: -d, through: d, by: 2) { if k == -d { x = prev_v[k &+ 1] } else { let km = prev_v[k &- 1] if k != d { let kp = prev_v[k &+ 1] if km < kp { x = kp } else { x = km &+ 1 } } else { x = km &+ 1 } } y = x &- k while x < n && y < m { if !cmp(a[x], b[y]) { break; } x &+= 1 y &+= 1 } v[k] = x if x >= n && y >= m { break iterator } } if x >= n && y >= m { break } } _internalInvariant(x >= n && y >= m) return result } // Backtrack through the trace generated by the Myers descent to produce the changes that make up the diff func _formChanges( from a: UnsafeBufferPointer<C.Element>, to b: UnsafeBufferPointer<C.Element>, using trace: [_V] ) -> [CollectionDifference<C.Element>.Change] { var changes = [CollectionDifference<C.Element>.Change]() changes.reserveCapacity(trace.count) var x = a.count var y = b.count for d in stride(from: trace.count &- 1, to: 0, by: -1) { let v = trace[d] let k = x &- y let prev_k = (k == -d || (k != d && v[k &- 1] < v[k &+ 1])) ? k &+ 1 : k &- 1 let prev_x = v[prev_k] let prev_y = prev_x &- prev_k while x > prev_x && y > prev_y { // No change at this position. x &-= 1 y &-= 1 } _internalInvariant((x == prev_x && y > prev_y) || (y == prev_y && x > prev_x)) if y != prev_y { changes.append(.insert(offset: prev_y, element: b[prev_y], associatedWith: nil)) } else { changes.append(.remove(offset: prev_x, element: a[prev_x], associatedWith: nil)) } x = prev_x y = prev_y } return changes } /* Splatting the collections into contiguous storage has two advantages: * * 1) Subscript access is much faster * 2) Subscript index becomes Int, matching the iterator types in the algorithm * * Combined, these effects dramatically improves performance when * collections differ significantly, without unduly degrading runtime when * the parameters are very similar. * * In terms of memory use, the linear cost of creating a ContiguousArray (when * necessary) is significantly less than the worst-case n² memory use of the * descent algorithm. */ func _withContiguousStorage<C: Collection, R>( for values: C, _ body: (UnsafeBufferPointer<C.Element>) throws -> R ) rethrows -> R { if let result = try values.withContiguousStorageIfAvailable(body) { return result } let array = ContiguousArray(values) return try array.withUnsafeBufferPointer(body) } return _withContiguousStorage(for: old) { a in return _withContiguousStorage(for: new) { b in return CollectionDifference(_formChanges(from: a, to: b, using:_descent(from: a, to: b)))! } } }
apache-2.0
9aa88c88dfefbb6b9ee6fda0dd21a6e0
32.368852
123
0.620241
4.14
false
false
false
false
samburnstone/SwiftStudyGroup
Swift Language Guide Playgrounds/StructFun.playground/Pages/Point.xcplaygroundpage/Contents.swift
1
733
//: [Previous](@previous) import UIKit //: Let's start simply let point1 = CGPoint(x: 5, y: 5) let point2 = CGPoint(x: 10, y: 10) func +(p1: CGPoint, p2: CGPoint) -> CGPoint { return CGPoint(x: p1.x + p2.x, y: p1.y + p2.y) } func -(p1: CGPoint, p2: CGPoint) -> CGPoint { return CGPoint(x: p1.x - p2.x, y: p1.y - p2.y) } func *(p1: CGPoint, p2: CGPoint) -> CGPoint { return CGPoint(x: p1.x * p2.x, y: p1.y * p2.y) } func /(p1: CGPoint, p2: CGPoint) -> CGPoint { return CGPoint(x: p1.x / p2.x, y: p1.y / p2.y) } let combinedPointAdding = point1 + point2 let combinedPointSubtracting = point1 - point2 let combinedPointMultiplying = point1 * point2 let combinedPointDividing = point2 / point1 //: [Next](@next)
mit
7d0bae48eee2ce52783af8fbb8839619
22.645161
50
0.633015
2.510274
false
false
false
false
nmdias/FeedParser
Tests/SyndicationTests.swift
2
2457
// // SyndicationTests.swift // // Copyright (c) 2016 Nuno Manuel Dias // // 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 import FeedParser class SyndicationTests: BaseTestCase { func testSyndication() { // Given let URL = fileURL("Syndication", type: "xml") let parser = FeedParser(URL: URL)! // When parser.parse { (result) in let feed = result.rssFeed // Then XCTAssertNotNil(feed) XCTAssertEqual(feed?.syndication?.syUpdatePeriod , SyndicationUpdatePeriod.Hourly) XCTAssertEqual(feed?.syndication?.syUpdateFrequency , Int(2)) XCTAssertNotNil(feed?.syndication?.syUpdateBase) } } func testSyndicationParsingPerformance() { self.measureBlock { // Given let expectation = self.expectationWithDescription("Syndication Parsing Performance") let URL = self.fileURL("Syndication", type: "xml") let parser = FeedParser(URL: URL)! // When parser.parse({ (result) in // Then expectation.fulfill() }) self.waitForExpectationsWithTimeout(self.timeout, handler: nil) } } }
mit
60bca1e8864f54f929d52bb17d256b15
32.202703
96
0.62556
4.953629
false
true
false
false
castillejoale/Bluefruit_LE_Connect_v2_Minimized_UART
bluefruitconnect/Platform/OSX_CommandLine/CommandLineColors.swift
1
995
// // SwiftAnsiColors.swift // Bluefruit Connect // // Created by Antonio García on 06/06/16. // Copyright © 2016 Adafruit. All rights reserved. // import Foundation // Based on: http://stackoverflow.com/questions/27807925/color-ouput-with-swift-command-line-tool and https://gist.github.com/dainkaplan/4651352 enum CommandLineColors: String { /* case black = "\u{001B}[0;30m" case red = "\u{001B}[0;31m" case green = "\u{001B}[0;32m" case yellow = "\u{001B}[0;33m" case blue = "\u{001B}[0;34m" case magenta = "\u{001B}[0;35m" case cyan = "\u{001B}[0;36m" case white = "\u{001B}[0;37m" */ case reset = "\u{001B}[0m" case normal = "\u{001B}[0;37m" case bold = "\u{001B}[1;37m" case dim = "\u{001B}[2;37m" case italic = "\u{001B}[3;37m" case underline = "\u{001B}[4;37m" } func + (let left: CommandLineColors, let right: String) -> String { return left.rawValue + right }
mit
d2b5d864894b637b939311b7c7fd4ee7
25.837838
144
0.590131
2.781513
false
false
false
false
andrzejsemeniuk/ASToolkit
ASToolkit/GenericControllerOfPickerOfFont.swift
1
2947
// // GenericControllerOfFonts // ASToolkit // // Created by Andrzej Semeniuk on 3/25/16. // Copyright © 2017 Andrzej Semeniuk. All rights reserved. // import Foundation import UIKit open class GenericControllerOfPickerOfFont : UITableViewController { public var names : [String] = [] public var selected : String = "" override open func viewDidLoad() { tableView.dataSource = self tableView.delegate = self tableView.separatorStyle = .none names = [] for family in UIFont.familyNames { // names.append(family) for font in UIFont.fontNames(forFamilyName: family) { print("family \(family), font \(font)") names.append(font) } } print("font names:\(names)") reload() super.viewDidLoad() } override open func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // TODO clear data and reload table } override open func numberOfSections (in: UITableView) -> Int { return 1 } override open func tableView (_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return names.count } override open func tableView (_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let name = names[indexPath.row] let cell = UITableViewCell(style:.default,reuseIdentifier:nil) if let label = cell.textLabel { label.text = name // label.textColor = UIColor.grayColor() label.font = UIFont(name:name,size:UIFont.labelFontSize) label.textAlignment = .left } cell.selectionStyle = .default cell.accessoryType = name == selected ? .checkmark : .none return cell } open func reload() { names = names.sorted() tableView.reloadData() } override open func viewWillAppear(_ animated: Bool) { reload() if let row = names.index(of: selected) { let path = IndexPath(row:row,section:0) tableView.scrollToRow(at: path as IndexPath,at:.middle,animated:true) } super.viewWillAppear(animated) } var update: (() -> ()) = {} override open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { selected = names[indexPath.row] reload() update() } } // TODO: ADD FILTERING CAPABILITY + INTEGRATION WITH NAVIGATION CONTROLLER
mit
720f89a215329f7ddd4f99b525f398f7
22.19685
125
0.528174
5.336957
false
false
false
false
attheodo/NSNotificationCenterMock
Example/NSNotificationCenterMock/ViewController.swift
1
2415
// // ViewController.swift // NSNotificationCenterMock // // Created by Athanasios Theodoridis on 03/01/16. // Copyright © 2016 Athanasios Theodoridis. All rights reserved. // import UIKit class ViewController: UIViewController { let kNotificationsHello = "kNotificationsHello" let kNotificationsGoodbye = "kNotificationsGoodbye" // MARK: - IBOutlets @IBOutlet weak var helloButton: UIButton? @IBOutlet weak var goodbyeButton: UIButton? @IBOutlet weak var notificationLabel: UILabel? // MARK: - IBActions @IBAction func postHelloNotification() { NotificationCenter.postNotificationName(kNotificationsHello, object: "Foo", userInfo: nil) } @IBAction func postGoodbyeNotification() { NotificationCenter.postNotificationName(kNotificationsGoodbye, object: "Bar", userInfo: nil) } // MARK: - Controller Properties lazy var NotificationCenter = { return NSNotificationCenter.defaultCenter() }() // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() registerNotifications() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } deinit { unregisterNotifications() } // MARK: - NSNotifications func registerNotifications() { NotificationCenter.addObserver(self, selector: "updateLabelForHelloNotification:", name: kNotificationsHello, object: nil) NotificationCenter.addObserver(self, selector: "updateLabelForGoodbyeNotification:", name: kNotificationsGoodbye, object: nil) } func unregisterNotifications() { NotificationCenter.removeObserver(self, name: kNotificationsHello, object: nil) NotificationCenter.removeObserver(self, name: kNotificationsGoodbye, object: nil) } // MARK: NSNotification Selectors internal func updateLabelForHelloNotification(notification: NSNotification) { if let name = notification.object as? String { notificationLabel?.text = "Hello \(name)" } } internal func updateLabelForGoodbyeNotification(notification: NSNotification) { if let name = notification.object as? String { notificationLabel?.text = "Goodbye \(name)" } } }
mit
d91958560867859eacdb34a3ced0c8d7
29.175
134
0.678956
5.259259
false
false
false
false