repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
Onetaway/VPNOn
VPNOnWatchKitExtension/GlanceController.swift
2
2038
// // GlanceController.swift // VPN On WatchKit Extension // // Created by Lex Tang on 3/30/15. // Copyright (c) 2015 LexTang.com. All rights reserved. // import WatchKit import Foundation import VPNOnKit class GlanceController: VPNInterfaceController { @IBOutlet weak var tableView: WKInterfaceTable! override func willActivate() { super.willActivate() loadVPNs() } func loadVPNs() { if vpns.count > 0 { self.tableView.setNumberOfRows(vpns.count, withRowType: "VPNRow") for i in 0...vpns.count-1 { if let row = self.tableView.rowControllerAtIndex(i) as! VPNRowInGlance? { let vpn = vpns[i] if let countryCode = vpn.countryCode { row.flag.setImageNamed(countryCode) } row.titleLabel.setText(vpn.title) row.latency = LTPingQueue.sharedQueue.latencyForHostname(vpn.server) let connected = Bool(VPNManager.sharedManager.status == .Connected && vpn.ID == selectedID) let backgroundColor = connected ? UIColor(red:0, green:0.6, blue:1, alpha:1) : UIColor(white: 1.0, alpha: 0.2) row.group.setBackgroundColor(backgroundColor) } } } else { self.tableView.setNumberOfRows(1, withRowType: "HintRow") } } // MARK: - Notification func pingDidUpdate(notification: NSNotification) { loadVPNs() } func coreDataDidSave(notification: NSNotification) { VPNDataManager.sharedManager.managedObjectContext?.mergeChangesFromContextDidSaveNotification(notification) loadVPNs() } func VPNStatusDidChange(notification: NSNotification?) { loadVPNs() if VPNManager.sharedManager.status == .Disconnected { LTPingQueue.sharedQueue.restartPing() } } }
mit
679ab55a094ee8c51007b31ff902f17c
29.878788
130
0.581943
4.852381
false
false
false
false
aschwaighofer/swift
stdlib/public/core/CollectionAlgorithms.swift
2
23263
//===--- CollectionAlgorithms.swift ---------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// // last //===----------------------------------------------------------------------===// extension BidirectionalCollection { /// The last element of the collection. /// /// If the collection is empty, the value of this property is `nil`. /// /// let numbers = [10, 20, 30, 40, 50] /// if let lastNumber = numbers.last { /// print(lastNumber) /// } /// // Prints "50" /// /// - Complexity: O(1) @inlinable public var last: Element? { return isEmpty ? nil : self[index(before: endIndex)] } } //===----------------------------------------------------------------------===// // firstIndex(of:)/firstIndex(where:) //===----------------------------------------------------------------------===// extension Collection where Element: Equatable { /// Returns the first index where the specified value appears in the /// collection. /// /// After using `firstIndex(of:)` to find the position of a particular element /// in a collection, you can use it to access the element by subscripting. /// This example shows how you can modify one of the names in an array of /// students. /// /// var students = ["Ben", "Ivy", "Jordell", "Maxime"] /// if let i = students.firstIndex(of: "Maxime") { /// students[i] = "Max" /// } /// print(students) /// // Prints "["Ben", "Ivy", "Jordell", "Max"]" /// /// - Parameter element: An element to search for in the collection. /// - Returns: The first index where `element` is found. If `element` is not /// found in the collection, returns `nil`. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @inlinable public func firstIndex(of element: Element) -> Index? { if let result = _customIndexOfEquatableElement(element) { return result } var i = self.startIndex while i != self.endIndex { if self[i] == element { return i } self.formIndex(after: &i) } return nil } } extension Collection { /// Returns the first index in which an element of the collection satisfies /// the given predicate. /// /// You can use the predicate to find an element of a type that doesn't /// conform to the `Equatable` protocol or to find an element that matches /// particular criteria. Here's an example that finds a student name that /// begins with the letter "A": /// /// let students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"] /// if let i = students.firstIndex(where: { $0.hasPrefix("A") }) { /// print("\(students[i]) starts with 'A'!") /// } /// // Prints "Abena starts with 'A'!" /// /// - Parameter predicate: A closure that takes an element as its argument /// and returns a Boolean value that indicates whether the passed element /// represents a match. /// - Returns: The index of the first element for which `predicate` returns /// `true`. If no elements in the collection satisfy the given predicate, /// returns `nil`. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @inlinable public func firstIndex( where predicate: (Element) throws -> Bool ) rethrows -> Index? { var i = self.startIndex while i != self.endIndex { if try predicate(self[i]) { return i } self.formIndex(after: &i) } return nil } } //===----------------------------------------------------------------------===// // lastIndex(of:)/lastIndex(where:) //===----------------------------------------------------------------------===// extension BidirectionalCollection { /// Returns the last element of the sequence that satisfies the given /// predicate. /// /// This example uses the `last(where:)` method to find the last /// negative number in an array of integers: /// /// let numbers = [3, 7, 4, -2, 9, -6, 10, 1] /// if let lastNegative = numbers.last(where: { $0 < 0 }) { /// print("The last negative number is \(lastNegative).") /// } /// // Prints "The last negative number is -6." /// /// - Parameter predicate: A closure that takes an element of the sequence as /// its argument and returns a Boolean value indicating whether the /// element is a match. /// - Returns: The last element of the sequence that satisfies `predicate`, /// or `nil` if there is no element that satisfies `predicate`. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @inlinable public func last( where predicate: (Element) throws -> Bool ) rethrows -> Element? { return try lastIndex(where: predicate).map { self[$0] } } /// Returns the index of the last element in the collection that matches the /// given predicate. /// /// You can use the predicate to find an element of a type that doesn't /// conform to the `Equatable` protocol or to find an element that matches /// particular criteria. This example finds the index of the last name that /// begins with the letter *A:* /// /// let students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"] /// if let i = students.lastIndex(where: { $0.hasPrefix("A") }) { /// print("\(students[i]) starts with 'A'!") /// } /// // Prints "Akosua starts with 'A'!" /// /// - Parameter predicate: A closure that takes an element as its argument /// and returns a Boolean value that indicates whether the passed element /// represents a match. /// - Returns: The index of the last element in the collection that matches /// `predicate`, or `nil` if no elements match. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @inlinable public func lastIndex( where predicate: (Element) throws -> Bool ) rethrows -> Index? { var i = endIndex while i != startIndex { formIndex(before: &i) if try predicate(self[i]) { return i } } return nil } } extension BidirectionalCollection where Element: Equatable { /// Returns the last index where the specified value appears in the /// collection. /// /// After using `lastIndex(of:)` to find the position of the last instance of /// a particular element in a collection, you can use it to access the /// element by subscripting. This example shows how you can modify one of /// the names in an array of students. /// /// var students = ["Ben", "Ivy", "Jordell", "Ben", "Maxime"] /// if let i = students.lastIndex(of: "Ben") { /// students[i] = "Benjamin" /// } /// print(students) /// // Prints "["Ben", "Ivy", "Jordell", "Benjamin", "Max"]" /// /// - Parameter element: An element to search for in the collection. /// - Returns: The last index where `element` is found. If `element` is not /// found in the collection, this method returns `nil`. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @inlinable public func lastIndex(of element: Element) -> Index? { if let result = _customLastIndexOfEquatableElement(element) { return result } return lastIndex(where: { $0 == element }) } } //===----------------------------------------------------------------------===// // subranges(where:) / subranges(of:) //===----------------------------------------------------------------------===// extension Collection { /// Returns the indices of all the elements that match the given predicate. /// /// For example, you can use this method to find all the places that a /// vowel occurs in a string. /// /// let str = "Fresh cheese in a breeze" /// let vowels: Set<Character> = ["a", "e", "i", "o", "u"] /// let allTheVowels = str.subranges(where: { vowels.contains($0) }) /// // str[allTheVowels].count == 9 /// /// - Parameter predicate: A closure that takes an element as its argument /// and returns a Boolean value that indicates whether the passed element /// represents a match. /// - Returns: A set of the indices of the elements for which `predicate` /// returns `true`. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *) public func subranges(where predicate: (Element) throws -> Bool) rethrows -> RangeSet<Index> { if isEmpty { return RangeSet() } var result = RangeSet<Index>() var i = startIndex while i != endIndex { let next = index(after: i) if try predicate(self[i]) { result._append(i..<next) } i = next } return result } } extension Collection where Element: Equatable { /// Returns the indices of all the elements that are equal to the given /// element. /// /// For example, you can use this method to find all the places that a /// particular letter occurs in a string. /// /// let str = "Fresh cheese in a breeze" /// let allTheEs = str.subranges(of: "e") /// // str[allTheEs].count == 7 /// /// - Parameter element: An element to look for in the collection. /// - Returns: A set of the indices of the elements that are equal to /// `element`. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *) public func subranges(of element: Element) -> RangeSet<Index> { subranges(where: { $0 == element }) } } //===----------------------------------------------------------------------===// // partition(by:) //===----------------------------------------------------------------------===// extension MutableCollection { /// Reorders the elements of the collection such that all the elements /// that match the given predicate are after all the elements that don't /// match. /// /// After partitioning a collection, there is a pivot index `p` where /// no element before `p` satisfies the `belongsInSecondPartition` /// predicate and every element at or after `p` satisfies /// `belongsInSecondPartition`. /// /// In the following example, an array of numbers is partitioned by a /// predicate that matches elements greater than 30. /// /// var numbers = [30, 40, 20, 30, 30, 60, 10] /// let p = numbers.partition(by: { $0 > 30 }) /// // p == 5 /// // numbers == [30, 10, 20, 30, 30, 60, 40] /// /// The `numbers` array is now arranged in two partitions. The first /// partition, `numbers[..<p]`, is made up of the elements that /// are not greater than 30. The second partition, `numbers[p...]`, /// is made up of the elements that *are* greater than 30. /// /// let first = numbers[..<p] /// // first == [30, 10, 20, 30, 30] /// let second = numbers[p...] /// // second == [60, 40] /// /// - Parameter belongsInSecondPartition: A predicate used to partition /// the collection. All elements satisfying this predicate are ordered /// after all elements not satisfying it. /// - Returns: The index of the first element in the reordered collection /// that matches `belongsInSecondPartition`. If no elements in the /// collection match `belongsInSecondPartition`, the returned index is /// equal to the collection's `endIndex`. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @inlinable public mutating func partition( by belongsInSecondPartition: (Element) throws -> Bool ) rethrows -> Index { return try _halfStablePartition(isSuffixElement: belongsInSecondPartition) } /// Moves all elements satisfying `isSuffixElement` into a suffix of the /// collection, returning the start position of the resulting suffix. /// /// - Complexity: O(*n*) where n is the length of the collection. @inlinable internal mutating func _halfStablePartition( isSuffixElement: (Element) throws -> Bool ) rethrows -> Index { guard var i = try firstIndex(where: isSuffixElement) else { return endIndex } var j = index(after: i) while j != endIndex { if try !isSuffixElement(self[j]) { swapAt(i, j); formIndex(after: &i) } formIndex(after: &j) } return i } } extension MutableCollection where Self: BidirectionalCollection { /// Reorders the elements of the collection such that all the elements /// that match the given predicate are after all the elements that don't /// match. /// /// After partitioning a collection, there is a pivot index `p` where /// no element before `p` satisfies the `belongsInSecondPartition` /// predicate and every element at or after `p` satisfies /// `belongsInSecondPartition`. /// /// In the following example, an array of numbers is partitioned by a /// predicate that matches elements greater than 30. /// /// var numbers = [30, 40, 20, 30, 30, 60, 10] /// let p = numbers.partition(by: { $0 > 30 }) /// // p == 5 /// // numbers == [30, 10, 20, 30, 30, 60, 40] /// /// The `numbers` array is now arranged in two partitions. The first /// partition, `numbers[..<p]`, is made up of the elements that /// are not greater than 30. The second partition, `numbers[p...]`, /// is made up of the elements that *are* greater than 30. /// /// let first = numbers[..<p] /// // first == [30, 10, 20, 30, 30] /// let second = numbers[p...] /// // second == [60, 40] /// /// - Parameter belongsInSecondPartition: A predicate used to partition /// the collection. All elements satisfying this predicate are ordered /// after all elements not satisfying it. /// - Returns: The index of the first element in the reordered collection /// that matches `belongsInSecondPartition`. If no elements in the /// collection match `belongsInSecondPartition`, the returned index is /// equal to the collection's `endIndex`. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @inlinable public mutating func partition( by belongsInSecondPartition: (Element) throws -> Bool ) rethrows -> Index { let maybeOffset = try _withUnsafeMutableBufferPointerIfSupported { (bufferPointer) -> Int in let unsafeBufferPivot = try bufferPointer._partitionImpl( by: belongsInSecondPartition) return unsafeBufferPivot - bufferPointer.startIndex } if let offset = maybeOffset { return index(startIndex, offsetBy: offset) } else { return try _partitionImpl(by: belongsInSecondPartition) } } @usableFromInline internal mutating func _partitionImpl( by belongsInSecondPartition: (Element) throws -> Bool ) rethrows -> Index { var lo = startIndex var hi = endIndex // 'Loop' invariants (at start of Loop, all are true): // * lo < hi // * predicate(self[i]) == false, for i in startIndex ..< lo // * predicate(self[i]) == true, for i in hi ..< endIndex Loop: while true { FindLo: repeat { while lo < hi { if try belongsInSecondPartition(self[lo]) { break FindLo } formIndex(after: &lo) } break Loop } while false FindHi: repeat { formIndex(before: &hi) while lo < hi { if try !belongsInSecondPartition(self[hi]) { break FindHi } formIndex(before: &hi) } break Loop } while false swapAt(lo, hi) formIndex(after: &lo) } return lo } } //===----------------------------------------------------------------------===// // _indexedStablePartition / _partitioningIndex //===----------------------------------------------------------------------===// extension MutableCollection { /// Moves all elements at the indices satisfying `belongsInSecondPartition` /// into a suffix of the collection, preserving their relative order, and /// returns the start of the resulting suffix. /// /// - Complexity: O(*n* log *n*) where *n* is the number of elements. /// - Precondition: /// `n == distance(from: range.lowerBound, to: range.upperBound)` internal mutating func _indexedStablePartition( count n: Int, range: Range<Index>, by belongsInSecondPartition: (Index) throws-> Bool ) rethrows -> Index { if n == 0 { return range.lowerBound } if n == 1 { return try belongsInSecondPartition(range.lowerBound) ? range.lowerBound : range.upperBound } let h = n / 2, i = index(range.lowerBound, offsetBy: h) let j = try _indexedStablePartition( count: h, range: range.lowerBound..<i, by: belongsInSecondPartition) let k = try _indexedStablePartition( count: n - h, range: i..<range.upperBound, by: belongsInSecondPartition) return _rotate(in: j..<k, shiftingToStart: i) } } //===----------------------------------------------------------------------===// // _partitioningIndex(where:) //===----------------------------------------------------------------------===// extension Collection { /// Returns the index of the first element in the collection that matches /// the predicate. /// /// The collection must already be partitioned according to the predicate. /// That is, there should be an index `i` where for every element in /// `collection[..<i]` the predicate is `false`, and for every element /// in `collection[i...]` the predicate is `true`. /// /// - Parameter predicate: A predicate that partitions the collection. /// - Returns: The index of the first element in the collection for which /// `predicate` returns `true`. /// /// - Complexity: O(log *n*), where *n* is the length of this collection if /// the collection conforms to `RandomAccessCollection`, otherwise O(*n*). internal func _partitioningIndex( where predicate: (Element) throws -> Bool ) rethrows -> Index { var n = count var l = startIndex while n > 0 { let half = n / 2 let mid = index(l, offsetBy: half) if try predicate(self[mid]) { n = half } else { l = index(after: mid) n -= half + 1 } } return l } } //===----------------------------------------------------------------------===// // shuffled()/shuffle() //===----------------------------------------------------------------------===// extension Sequence { /// Returns the elements of the sequence, shuffled using the given generator /// as a source for randomness. /// /// You use this method to randomize the elements of a sequence when you are /// using a custom random number generator. For example, you can shuffle the /// numbers between `0` and `9` by calling the `shuffled(using:)` method on /// that range: /// /// let numbers = 0...9 /// let shuffledNumbers = numbers.shuffled(using: &myGenerator) /// // shuffledNumbers == [8, 9, 4, 3, 2, 6, 7, 0, 5, 1] /// /// - Parameter generator: The random number generator to use when shuffling /// the sequence. /// - Returns: An array of this sequence's elements in a shuffled order. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. /// - Note: The algorithm used to shuffle a sequence may change in a future /// version of Swift. If you're passing a generator that results in the /// same shuffled order each time you run your program, that sequence may /// change when your program is compiled using a different version of /// Swift. @inlinable public func shuffled<T: RandomNumberGenerator>( using generator: inout T ) -> [Element] { var result = ContiguousArray(self) result.shuffle(using: &generator) return Array(result) } /// Returns the elements of the sequence, shuffled. /// /// For example, you can shuffle the numbers between `0` and `9` by calling /// the `shuffled()` method on that range: /// /// let numbers = 0...9 /// let shuffledNumbers = numbers.shuffled() /// // shuffledNumbers == [1, 7, 6, 2, 8, 9, 4, 3, 5, 0] /// /// This method is equivalent to calling `shuffled(using:)`, passing in the /// system's default random generator. /// /// - Returns: A shuffled array of this sequence's elements. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public func shuffled() -> [Element] { var g = SystemRandomNumberGenerator() return shuffled(using: &g) } } extension MutableCollection where Self: RandomAccessCollection { /// Shuffles the collection in place, using the given generator as a source /// for randomness. /// /// You use this method to randomize the elements of a collection when you /// are using a custom random number generator. For example, you can use the /// `shuffle(using:)` method to randomly reorder the elements of an array. /// /// var names = ["Alejandro", "Camila", "Diego", "Luciana", "Luis", "Sofía"] /// names.shuffle(using: &myGenerator) /// // names == ["Sofía", "Alejandro", "Camila", "Luis", "Diego", "Luciana"] /// /// - Parameter generator: The random number generator to use when shuffling /// the collection. /// /// - Complexity: O(*n*), where *n* is the length of the collection. /// - Note: The algorithm used to shuffle a collection may change in a future /// version of Swift. If you're passing a generator that results in the /// same shuffled order each time you run your program, that sequence may /// change when your program is compiled using a different version of /// Swift. @inlinable public mutating func shuffle<T: RandomNumberGenerator>( using generator: inout T ) { guard count > 1 else { return } var amount = count var currentIndex = startIndex while amount > 1 { let random = Int.random(in: 0 ..< amount, using: &generator) amount -= 1 swapAt( currentIndex, index(currentIndex, offsetBy: random) ) formIndex(after: &currentIndex) } } /// Shuffles the collection in place. /// /// Use the `shuffle()` method to randomly reorder the elements of an array. /// /// var names = ["Alejandro", "Camila", "Diego", "Luciana", "Luis", "Sofía"] /// names.shuffle(using: myGenerator) /// // names == ["Luis", "Camila", "Luciana", "Sofía", "Alejandro", "Diego"] /// /// This method is equivalent to calling `shuffle(using:)`, passing in the /// system's default random generator. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @inlinable public mutating func shuffle() { var g = SystemRandomNumberGenerator() shuffle(using: &g) } }
apache-2.0
9ffad552d0a982af15ab75cf7eeba360
36.2144
82
0.594136
4.316815
false
false
false
false
ahoppen/swift
test/Frontend/debug-cycles.swift
13
562
// RUN: not %target-swift-frontend -typecheck -debug-cycles %s 2>&1 | %FileCheck %s --match-full-lines --strict-whitespace --color=false class Outer2: Outer2.Inner { class Inner {} } // CHECK:===CYCLE DETECTED=== // CHECK-NEXT: `--TypeCheckSourceFileRequest({{.*}}) // CHECK-NEXT: `--SuperclassDeclRequest({{.*}}) // CHECK-NEXT: `--InheritedDeclsReferencedRequest({{.*}}) // CHECK-NEXT: `--QualifiedLookupRequest({{.*}}) // CHECK-NEXT: `--SuperclassDeclRequest({{.*}}) (cyclic dependency)
apache-2.0
bbb89be63942b3fafada49c5f53d3564
45.833333
136
0.615658
3.579618
false
false
false
false
yuyedaidao/YQRefresh
Classes/YQRefreshHeader.swift
1
5718
// // YQRefreshHeader.swift // YQRefresh // // Created by 王叶庆 on 2017/2/10. // Copyright © 2017年 王叶庆. All rights reserved. // import UIKit open class YQRefreshHeader: UIView, Refresher { public var actor: YQRefreshActor? { didSet { guard let a = actor else { return } if let old = oldValue { old.removeFromSuperview() } addSubview(a) } } public var action: YQRefreshAction? public var refresherHeight: CGFloat = YQRefresherHeight public var originalInset: UIEdgeInsets = UIEdgeInsets.zero public var pullingPercentOffset: CGFloat = YQRefresherHeight / 2 public var yOffset: CGFloat = 0 private var isAnimated = false public var state: YQRefreshState = .default { didSet { guard oldValue != state else { return } switch state { case .default: if scrollView?.contentInset.top != originalInset.top { isAnimated = true isHidden = false UIView.animate(withDuration: YQRefresherAnimationDuration, animations: { let top = self.originalInset.top self.scrollView?.contentInset.top = top self.scrollView?.contentOffset.y = -top }) { (_) in self.isAnimated = false self.isHidden = true } } case .refreshing: UIView.animate(withDuration: YQRefresherAnimationDuration, animations: { let top = self.refresherHeight + self.originalInset.top self.scrollView?.contentInset.top = top self.scrollView?.contentOffset.y = -top }) case .pulling: guard let scrollView = scrollView, scrollView.isTracking else { break } if #available(iOS 10.0, *) { UIImpactFeedbackGenerator().impactOccurred() } default: break } actor?.state = state } } weak public var scrollView: UIScrollView? { didSet { if let scroll = scrollView { scroll.addObserver(self, forKeyPath: YQKVOContentOffset, options: .new, context: UnsafeMutableRawPointer(&YQKVOContentOffset)) } } } public var pullingPercent: Double = 0 { didSet { actor?.pullingPrecent = pullingPercent } } public func beginRefreshing() { pullingPercent = 1 state = .refreshing } public func endRefreshing() { state = .default pullingPercent = 0 } override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if let scroll = scrollView { let offsetY = scroll.contentOffset.y if !isAnimated { self.isHidden = (offsetY >= -originalInset.top) } guard state != .refreshing else { return } let triggerOffset = -originalInset.top - refresherHeight if scroll.isDragging { if state == .default && offsetY <= triggerOffset{ state = .pulling } else if state == .pulling && offsetY > triggerOffset { state = .default } } else { if state == .pulling { if offsetY <= triggerOffset + 10 { // 拉开一点距离,增大触发率 state = .refreshing if let action = self.action { NotificationCenter.default.post(name: NSNotification.Name(rawValue: YQNotificatonHeaderRefresh), object: self.scrollView) action() } } else { state = .default } } } guard offsetY < -originalInset.top else { return } let percent = (-originalInset.top - offsetY - pullingPercentOffset) / (refresherHeight - pullingPercentOffset) pullingPercent = max(min(Double(percent), 1), 0) } } public init (actor: YQRefreshActor? = YQRefreshActorProvider.shared.headerActor?() ?? PacmanActor(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: 45, height: 30))), action: @escaping YQRefreshAction) { self.actor = actor self.action = action super.init(frame: CGRect.zero) if let a = actor { addSubview(a) } } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open override func layoutSubviews() { super.layoutSubviews() guard let actor = actor else { return } actor.center = CGPoint(x: bounds.midX, y: bounds.midY) } open override func willMove(toSuperview newSuperview: UIView?) { func removeObservers(on view: UIView?) { view?.removeObserver(self, forKeyPath: YQKVOContentOffset, context: UnsafeMutableRawPointer(&YQKVOContentOffset)) } if let scroll = newSuperview as? UIScrollView { scrollView = scroll } else { removeObservers(on: superview) } } }
mit
728031acbd50ebfa73ad244354395819
34.055556
213
0.525445
5.342427
false
false
false
false
iworkinprogress/SBTimeLabel
SBTimeLabel/SBTimeLabel/SBTimeLabel.swift
1
3531
// // SBTimeLabel.swift // SBTimeLabel // // Created by Steven Baughman on 10/18/16. // Copyright © 2016 Steven Baughman. All rights reserved. // import UIKit enum TimerType { case stopwatch case countdown case clock } enum TimerAccurracy { case milliseconds case seconds } public protocol SBTimeLabelDelegate { func didUpdateText(_ label:SBTimeLabel) } open class SBTimeLabel: UILabel { var type:TimerType = .stopwatch var accurracy:TimerAccurracy = .seconds static var dateFormat = "HH:mm:ss" private var timer:Timer? private var pausedTime:TimeInterval = 0 open var startDate:Date? open var endDate:Date? open var delegate:SBTimeLabelDelegate? open lazy var dateFormatter:DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = dateFormat formatter.timeZone = TimeZone(secondsFromGMT: 0) return formatter }() private func updateText() { var string:String! switch type { case .stopwatch: string = dateFormatter.string(from: elapsedTimeAsDate) case .countdown: string = dateFormatter.string(from: elapsedTimeAsDate) case .clock: string = dateFormatter.string(from: Date()) } text = string // Notify Delegate delegate?.didUpdateText(self) } private func incrementTime() { DispatchQueue.main.async() { () -> Void in self.updateText() } } //MARK: - Computed Properties open var isRunning: Bool { get { if let timer = self.timer { return timer.isValid } else { return false } } } open var elapsedTimeAsDate: Date { get { return Date(timeIntervalSince1970: duration) } } open var duration:TimeInterval { get { if let startDate = self.startDate { let endDate = self.endDate ?? Date() return endDate.timeIntervalSince(startDate) - pausedTime } else { return 0 } } } private var timeInterval: TimeInterval { switch accurracy { case .seconds: return 1.0 case .milliseconds: return 0.01 } } //MARK: - Controls open func start() { timer?.invalidate() timer = Timer(timeInterval: self.timeInterval, repeats: true, block: { (timer) in self.incrementTime() }) // Add Timer RunLoop.main.add(timer!, forMode: .commonModes) // Set Tolerance to 10% of timer, as suggested by Apple Docs timer?.tolerance = self.timeInterval / 10.0 if startDate == nil { startDate = Date() } if let endDate = self.endDate { // was paused, add time to pausedTime pausedTime += Date().timeIntervalSince(endDate) self.endDate = nil } } open func pause() { if isRunning { timer?.invalidate() endDate = Date() } } // Is there a difference between pause and stop open func stop() { pause() } open func reset() { stop() startDate = nil endDate = nil self.updateText() } }
mit
5a035788b1339cbc2a1754ab8d1c8a61
23.178082
89
0.539377
4.950912
false
false
false
false
danielrcardenas/ac-course-2017
frameworks/SwarmChemistry-Swif/Demo/SwarmRenderer.swift
1
1619
// // SwarmRenderer.swift // SwarmChemistry // // Created by Yamazaki Mitsuyoshi on 2017/08/10. // Copyright © 2017 Mitsuyoshi Yamazaki. All rights reserved. // #if os(iOS) || os(watchOS) || os(tvOS) import UIKit #elseif os(macOS) import Cocoa #endif import SwarmChemistry protocol SwarmRenderer: class { weak var renderView: SwarmRenderView! { set get } var isRunning: Bool { set get } var steps: Int { get } var delay: Double { get } func setupRenderView(with population: Population) func step() func pause() func resume() func clear() func didStep(currentSteps: Int) } extension SwarmRenderer { var delay: Double { return 0.0 } func setupRenderView(with population: Population) { isRunning = false renderView.population = population } func step() { guard isRunning == true else { return } DispatchQueue.global(qos: .userInitiated).async { self.renderView.population.step(self.steps) DispatchQueue.main.asyncAfter(deadline: .now() + self.delay) { self.didStep(currentSteps: self.renderView.population.steps) guard self.isRunning == true else { return // Without this, setNeedsDisplay() maybe called one time after pause() call } self.renderView.setNeedsDisplay(self.renderView.bounds) self.step() } } } func pause() { isRunning = false } func resume() { isRunning = true step() } func clear() { pause() renderView.clear() } func didStep(currentSteps: Int) { // Default implementation: does nothing } }
apache-2.0
6858c1c53844a504a3889bdac0a14d47
20.012987
93
0.647713
4.075567
false
false
false
false
yariksmirnov/aerial
ios/Container.swift
1
2901
// // Container.swift // Aerial // // Created by Yaroslav Smirnov on 14/12/2016. // Copyright © 2016 Yaroslav Smirnov. All rights reserved. // import Foundation import ObjectMapper import KZFileWatchers final class Container { let service: ConnectionService var tree = [File]() var watcher: FileWatcher.Local? static var url: URL { let fm = FileManager.default let docUrl = fm.urls(for: .documentDirectory, in: .userDomainMask).first return docUrl!.deletingLastPathComponent() } init(device: Device) { self.service = device.service setupFileWatcher() installListeners() updateContainerTree() File.printTree(tree: tree) } func updateContainerTree() { tree = Container.currentTree() sendTree() } private func installListeners() { service.on(.containerTree) { data, _ in } service.on(.loadFile) { [weak self] data, _ in guard let json = data as? [String: Any] else { return } guard let file = Mapper<File>().map(JSON: json) else { return } self?.service.send(file: file) } } private func setupFileWatcher() { watcher = FileWatcher.Local(path: Container.url.path) try! watcher?.start { result in switch result { case .noChanges: break case .updated(_): break } } } private func sendTree() { let data = tree.toJSON() service.send(event: .containerTree, withData: data) } static func currentTree() -> [File] { return Container.tree(forDirectory: Container.url) } static func debugPrint() { File.printTree(tree: currentTree()) } static func tree(forDirectory directory: URL) -> [File] { let fm = FileManager.default var files = [File]() do { let keys: [URLResourceKey] = [.isDirectoryKey, .nameKey] let urls = try fm.contentsOfDirectory(at: directory, includingPropertiesForKeys: keys) for url in urls { let file = File(url: url) let resourceValues = try url.resourceValues(forKeys: Set(keys)) file.name = resourceValues.name ?? "" file.relativePath = url.absoluteString.replacingOccurrences(of: Container.url.absoluteString, with: "") if resourceValues.isDirectory == true { file.isLeaf = false file.children = tree(forDirectory: url) } files.append(file) } } catch (let error) { Log.error("Failed to get content of directory \(directory): \(error)") } return files } }
mit
66b29d3de2390b839b1f4f93df44d5fe
28.591837
119
0.553793
4.707792
false
false
false
false
mightydeveloper/swift
test/DebugInfo/inout.swift
7
2744
// RUN: %target-swift-frontend %s -emit-ir -g -module-name inout -o %t.ll // RUN: cat %t.ll | FileCheck %s // RUN: cat %t.ll | FileCheck %s --check-prefix=PROMO-CHECK // RUN: cat %t.ll | FileCheck %s --check-prefix=FOO-CHECK // LValues are direct values, too. They are reference types, though. func Close(fn: () -> Int64) { fn() } typealias MyFloat = Float // CHECK: define hidden void @_TF5inout13modifyFooHeap // CHECK: %[[ALLOCA:.*]] = alloca %Vs5Int64* // CHECK: %[[ALLOCB:.*]] = alloca %Sf // CHECK: call void @llvm.dbg.declare(metadata // CHECK-SAME: %[[ALLOCA]], metadata ![[A:[0-9]+]] // CHECK: call void @llvm.dbg.declare(metadata // CHECK-SAME: %[[ALLOCB]], metadata ![[B:[0-9]+]], metadata !{{[0-9]+}}) // Closure with promoted capture. // PROMO-CHECK: define {{.*}}@_TTSf2d_i___TFF5inout13modifyFooHeapFTRVs5Int64Sf_T_U_FT_S0_ // PROMO-CHECK: call void @llvm.dbg.declare(metadata {{(i32|i64)}}* % // PROMO-CHECK-SAME: metadata ![[A1:[0-9]+]], metadata ![[EMPTY_EXPR:[0-9]+]]) // PROMO-CHECK: ![[EMPTY_EXPR]] = !DIExpression() // PROMO-CHECK: ![[A1]] = !DILocalVariable(name: "a", arg: 1 // PROMO-CHECK-SAME: type: !"_TtVs5Int64" func modifyFooHeap(inout a: Int64, // CHECK: ![[A]] = !DILocalVariable(name: "a", arg: 1 // CHECK-SAME: line: [[@LINE-2]],{{.*}} type: !"_TtRVs5Int64" // CHECK: ![[B]] = !DILocalVariable(name: "b", scope: // CHECK-SAME: line: [[@LINE+5]],{{.*}} type: ![[MYFLOAT:[0-9]+]] // CHECK: ![[MYFLOAT]] = !DIDerivedType(tag: DW_TAG_typedef, // CHECK-SAME: name: "_Tta5inout7MyFloat",{{.*}} baseType: !"_TtSf" _ b: MyFloat) { var b = b if (b > 2.71) { a = a + 12// Set breakpoint here } // Close over the variable to disable promotion of the inout shadow. Close({ a }) } // Inout reference type. // FOO-CHECK: define {{.*}}@_TF5inout9modifyFooFTRVs5Int64Sf_T_ // FOO-CHECK: call void @llvm.dbg.declare(metadata %Vs5Int64** % // FOO-CHECK-SAME: metadata ![[U:[0-9]+]], metadata ![[EMPTY_EXPR:.*]]) // FOO-CHECK: ![[EMPTY_EXPR]] = !DIExpression() func modifyFoo(inout u: Int64, // FOO-CHECK-DAG: !DILocalVariable(name: "v", scope:{{.*}} line: [[@LINE+5]],{{.*}} type: ![[MYFLOAT:[0-9]+]] // FOO-CHECK-DAG: [[U]] = !DILocalVariable(name: "u", arg: 1{{.*}} line: [[@LINE-2]],{{.*}} type: !"_TtRVs5Int64" _ v: MyFloat) // FOO-CHECK-DAG: ![[MYFLOAT]] = !DIDerivedType(tag: DW_TAG_typedef, name: "_Tta5inout7MyFloat",{{.*}} baseType: !"_TtSf" { var v = v if (v > 2.71) { u = u - 41 } } func main() -> Int64 { var c = 11 as Int64 modifyFoo(&c, 3.14) var d = 64 as Int64 modifyFooHeap(&d, 1.41) return 0 } main()
apache-2.0
d814c74c66c0a6d5b93c144cc34e9d75
37.111111
121
0.573251
3.005476
false
false
false
false
ayvazj/BrundleflyiOS
Pod/Classes/BtfyJson.swift
1
14000
/* * Copyright (c) 2015 James Ayvaz * * 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. */ class BtfyJson { static let positionProps = BtfyPropertyParserKeyframePosition() static let rotationProps = BtfyPropertyParserKeyframeRotation() static let scaleProps = BtfyPropertyParserKeyframeScale(); static let opacityProps = BtfyPropertyParserKeyframeOpacity() static func parseSize(json: [String:AnyObject]) throws -> BtfySize { guard let width = json["width"] as? Int else { throw BtfyError.ParseError(msg: "Size missing width.") } guard let height = json["height"] as? Int else { throw BtfyError.ParseError(msg: "Size missing height.") } return BtfySize(width: Double(width), height: Double(height)); } static func parsePoint(json: [String:AnyObject]) throws -> BtfyPoint { guard let x = json["x"] as? Double else { throw BtfyError.ParseError(msg: "Point missing x.") } guard let y = json["y"] as? Double else { throw BtfyError.ParseError(msg: "Point missing y.") } return BtfyPoint(x: x, y: y); } static func parseScale(json: [String:AnyObject]) throws -> BtfyPoint { guard let sx = json["sx"] as? Double else { throw BtfyError.ParseError(msg: "Scale missing sx.") } guard let sy = json["sy"] as? Double else { throw BtfyError.ParseError(msg: "Scale missing sy.") } return BtfyPoint(x: sx, y: sy); } static func parseTypeface(str: String?) -> String { guard let typefaceStr = str else { return UIFont.systemFontOfSize(0).fontName } switch(typefaceStr) { case "italic": return UIFont.italicSystemFontOfSize(0).fontName case "bold": return UIFont.boldSystemFontOfSize(0).fontName case "bold-italic": return UIFont.italicSystemFontOfSize(0).fontName default: break } return UIFont.systemFontOfSize(0).fontName } static func parseTextAlignment(str: String?) -> NSTextAlignment { guard let textAlignStr = str else { return NSTextAlignment.Left } switch(textAlignStr) { case "center": return NSTextAlignment.Center case "right": return NSTextAlignment.Right case "right-center": return NSTextAlignment.Right case "left-center": return NSTextAlignment.Left default: break } return NSTextAlignment.Left } static func parseTimingFunction(json: [AnyObject]) -> CAMediaTimingFunction { guard json.count > 2 else { return CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) } let jsonTiming = json[2] guard let nameStr = jsonTiming["name"] as! String? else { return CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) } if nameStr == "cubic-bezier" || nameStr == "linear" { let x1 = jsonTiming["x1"] as! Float let y1 = jsonTiming["y1"] as! Float let x2 = jsonTiming["x2"] as! Float let y2 = jsonTiming["y2"] as! Float return CAMediaTimingFunction(controlPoints: x1, y1, x2, y2) } return CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) } static func parseAnimationGroup(json: [String: AnyObject]) throws -> BtfyAnimationGroup? { guard let typeStr = json["type"] as? String else { throw BtfyError.ParseError(msg: "Undefined animation group type") } guard let jsonId = json["id"] as? String else { throw BtfyError.ParseError(msg: "Animation missing id") } if typeStr != "animationGroup" { throw BtfyError.ParseError(msg: "Unexpected animation group type: \(typeStr)") } var parentId = json["parentId"] as! String? if ( parentId != nil && parentId!.isEmpty) { parentId = nil // we want it nil rather than empty } var shape = BtfyShape() if let shapeJSON = json["shape"] { let shapeStr = shapeJSON["name"] as! String? if (BtfyShape.Name.ellipse == shapeStr) { shape.name = BtfyShape.Name.ellipse } else { shape.name = BtfyShape.Name.rectangle } } let duration = (json["duration"] as! Double?)! var textStr = json["text"] as! String? if (textStr != nil && !(textStr!.isEmpty)) { textStr = textStr!.localized } var backgroundImageStr = json["backgroundImage"] as! String? if ( backgroundImageStr != nil && backgroundImageStr!.isEmpty ) { backgroundImageStr = nil } var animations : [BtfyAnimation] = [] if let animationsList = json["animations"] as? [[String:AnyObject]] { for animation in animationsList { let idStr = animation["id"] as! String? let animTypeStr = animation["type"] as! String? if "animation" != animTypeStr { throw BtfyError.ParseError(msg: "Unexpected animation type: \(animTypeStr)") } var delay = animation["delay"] as! Double? if delay == nil { delay = 0 } delay = delay! var animduration = animation["duration"] as! Double? if animduration == nil { animduration = 0 } animduration = animduration! let jsonKeyframesList = animation["keyframes"] as! [AnyObject]? let propertyValue = animation["property"] as! String? var animationObj : BtfyAnimation? if let propValue = propertyValue { switch(propValue) { case "opacity": var keyframes : [BtfyKeyframe] = [] do { keyframes = try opacityProps.parseKeyframes(jsonKeyframesList!) } catch let err as NSError { print(err) } animationObj = BtfyAnimation(id: idStr, property: BtfyAnimation.Property.Opacity, delay: delay!, duration: animduration!, list: keyframes) break case "rotation": var keyframes : [BtfyKeyframe] = [] do { keyframes = try rotationProps.parseKeyframes(jsonKeyframesList!) } catch let err as NSError { print(err) } animationObj = BtfyAnimation(id: idStr, property: BtfyAnimation.Property.Rotation, delay: delay!, duration: animduration!, list: keyframes) break case "scale": var keyframes : [BtfyKeyframe] = [] do { keyframes = try scaleProps.parseKeyframes(jsonKeyframesList!) } catch let err as NSError { print(err) } animationObj = BtfyAnimation(id: idStr, property: BtfyAnimation.Property.Scale, delay: delay!, duration: animduration!, list: keyframes) break case "position": var keyframes : [BtfyKeyframe] = [] do { keyframes = try positionProps.parseKeyframes(jsonKeyframesList!) } catch let err as NSError { print(err) } animationObj = BtfyAnimation(id: idStr, property: BtfyAnimation.Property.Position, delay: delay!, duration: animduration!, list: keyframes) break default: print("Unrecognised animation property value : \(propValue)") animationObj = nil } } else { print("Unrecognised animation property: \(propertyValue)") } if let animObj = animationObj { animations.append(animObj) } } } let intialValues = json["initialValues"] as! [String:AnyObject]? if intialValues == nil { throw BtfyError.ParseError(msg: "Animation group missing initial values.") } let jsonSize = intialValues!["size"] as! [String:AnyObject]? if jsonSize == nil { throw BtfyError.ParseError(msg: "Missing size in initial values.") } var anchorPointJson = intialValues!["anchorPoint"] as! [String:AnyObject]? if anchorPointJson == nil { anchorPointJson = ["anchorPoint": ["x": 0, "y":0]] } var anchorPoint : BtfyPoint? do { anchorPoint = try parsePoint(anchorPointJson!) } catch _ { throw BtfyError.ParseError(msg: "Unable to parse anchor point") } var backgroundColorJson = intialValues!["backgroundColor"] as! [String:AnyObject]? if backgroundColorJson == nil { backgroundColorJson = ["r": 0, "g":0, "b": 0, "a": 0] } let backgroundColor = BtfyColor.parseRGBA(backgroundColorJson!) var opacity = intialValues!["opacity"] as! Double? if opacity == nil { opacity = 1.0 } var positionJson = intialValues!["position"] as! [String:AnyObject]? if positionJson == nil { positionJson = ["position": ["x": 0, "y":0]] } var position : BtfyPoint? do { position = try parsePoint(positionJson!) } catch _ { throw BtfyError.ParseError(msg: "Unable to parse position") } var scaleJson = intialValues!["scale"] as! [String:AnyObject]? if scaleJson == nil { scaleJson = ["scale": ["sx": 1, "sy":1]] } var scale : BtfyPoint? do { scale = try parseScale(scaleJson!) } catch _ { throw BtfyError.ParseError(msg: "Unable to parse scale") } var rotation = intialValues!["rotation"] as! Double? if rotation == nil { rotation = 0.0 } let fontSize = intialValues!["fontSize"] as! Double? var textColorJson = intialValues!["textColor"] as! [String:AnyObject]? if textColorJson == nil { textColorJson = ["textColor": ["r": 1, "g":1, "b": 1, "a": 1]] } let textColor = BtfyColor.parseRGBA(textColorJson!) let textStyle = intialValues!["textStyle"] as! String? let textAlign = parseTextAlignment(intialValues!["textAlign"] as! String?) let sizeWidth = jsonSize!["width"] as! Double? let sizeHeight = jsonSize!["height"] as! Double? if (sizeWidth != nil && sizeHeight != nil) { return BtfyAnimationGroup( jsonId: jsonId, parentId: parentId, shape: shape, duration: duration, text: textStr, backgroundImageStr: backgroundImageStr, initialValues: BtfyInitialValues( size: BtfySize(width:sizeWidth!, height:sizeHeight!), anchorPoint: anchorPoint!, backgroundColor: backgroundColor, opacity: opacity!, position: position!, scale: scale!, rotation: rotation!, fontSize: fontSize, textColor: textColor, textStyle: textStyle, textAlign: textAlign ), animations: animations ) } else { throw BtfyError.ParseError(msg: "Size missing width or height.") } } }
mit
56aa193c9fbe4b607e9b827c4a703be9
37.251366
163
0.523
5.192878
false
false
false
false
SmallElephant/FEAlgorithm-Swift
11-GoldenInterview/11-GoldenInterview/main.swift
1
12662
// // main.swift // 11-GoldenInterview // // Created by keso on 2017/4/15. // Copyright © 2017年 FlyElephant. All rights reserved. // import Foundation var myString:MyString = MyString() var uniqueStr:String = "FlyElephant" var isUnique:Bool = myString.isUniqueChar(str: uniqueStr) print("\(uniqueStr)---是不是所有字符串唯一:\(isUnique)") var reverseTemp:String = "FlyElephant" var reverseStr:String = myString.reverseString(str: reverseTemp) print("反转字符串:\(reverseStr)---\(String(reverseTemp.characters.reversed()))") var strA:String = "student" var strB:String = "FlyElephant" var perResult:Bool = myString.permutation(strA: strA, strB: strB) print("\(strA)与\(strB)是不是变位词\(perResult)") var replaceStr:String = "I am FlyElephant" var replaceResult:String = myString.replaceSpaces(str: replaceStr) print("字符串空格替换:\(replaceResult)") var result2:String = myString.replaceSpaces1(str: replaceStr) print("字符串空格替换:\(result2)") var compressString:String = "abbcccdddd" var compressResult:String = myString.compressBetter(str: compressString) print("压缩结果:\(compressResult)") var rotateData:[[Int]] = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]] myString.rotate(data: &rotateData, n: 4) print("FlyElephant--数组旋转90度数据---\(rotateData)") var clearData:[[Int]] = [[1,2,3,4,0],[5,6,7,8,9],[9,10,11,12,1],[13,14,15,16,17]] myString.clearZero(data: &clearData) print("FlyElephant--数组清零--\(clearData)") var originalStr:String = "FlyElephant" var rotationStr:String = "antFlyEleph" var result:Bool = myString.isRotation(orginal: originalStr, rotation: rotationStr) print("\(rotationStr)是\(originalStr)的结果\(result)") var listNodeManger:ListNodeManger = ListNodeManger() for i in 0..<10 { listNodeManger.appendToTail(value: "\(i)") } for i in 0..<3 { listNodeManger.appendToTail(value: "\(i)") } listNodeManger.printListNode(headNode: listNodeManger.headNode!) listNodeManger.deleteDuplitation(node: listNodeManger.headNode!) print("删除重复结点") listNodeManger.printListNode(headNode: listNodeManger.headNode!) var nthNode:ListNode? = listNodeManger.nthToLastNode(node: listNodeManger.headNode!, k: 3) if nthNode != nil { print("FlyElephant--倒数的k个节点:\(nthNode!.value!)") } listNodeManger.headNode = nil listNodeManger.appendToTail(value: "\(1)") listNodeManger.appendToTail(value: "\(3)") listNodeManger.appendToTail(value: "\(5)") listNodeManger.appendToTail(value: "\(2)") listNodeManger.appendToTail(value: "\(4)") listNodeManger.appendToTail(value: "\(6)") listNodeManger.appendToTail(value: "\(8)") listNodeManger.appendToTail(value: "\(7)") listNodeManger.appendToTail(value: "\(9)") listNodeManger.printListNode(headNode: listNodeManger.headNode!) print("FlyElephant--链表切分1") var partitionHeadNode:ListNode = listNodeManger.partitionListNode(node: listNodeManger.headNode!, x: 5) listNodeManger.printListNode(headNode: partitionHeadNode) print("FlyElephant--链表切分2") partitionHeadNode = listNodeManger.partitionListNode2(node: listNodeManger.headNode!, x: 5) listNodeManger.printListNode(headNode: partitionHeadNode) listNodeManger.headNode = nil listNodeManger.appendToTail(value: "\(0)") listNodeManger.appendToTail(value: "\(5)") listNodeManger.appendToTail(value: "\(2)") listNodeManger.appendToTail(value: "\(7)") var addHeadNode1:ListNode = listNodeManger.headNode! listNodeManger.headNode = nil listNodeManger.appendToTail(value: "\(7)") listNodeManger.appendToTail(value: "\(8)") listNodeManger.appendToTail(value: "\(9)") var addHeadNode2:ListNode = listNodeManger.headNode! var addResultNode:ListNode = listNodeManger.addListNode(node1: addHeadNode1, node2: addHeadNode2) print("FlyElephant---链表原始数据") listNodeManger.printListNode(headNode: addHeadNode1) listNodeManger.printListNode(headNode: addHeadNode2) print("FlyElephant---相加之后结果") listNodeManger.printListNode(headNode: addResultNode) var addResultNode2:ListNode? = listNodeManger.addListNode1(node1: addHeadNode1, node2: addHeadNode2, carry: 0) print("FlyElephant---相加之后结果2") listNodeManger.printListNode(headNode: addResultNode2!) var listCount:Int = listNodeManger.listNodeCount(listNode: addHeadNode2) print("链表的长度---\(listCount)") var addHeadNode3:ListNode = listNodeManger.paddingListNode(node: addHeadNode2, padding: 2) listNodeManger.printListNode(headNode: addHeadNode3) listNodeManger.headNode = nil listNodeManger.appendToTail(value: "\(9)") listNodeManger.appendToTail(value: "\(5)") listNodeManger.appendToTail(value: "\(8)") var sequenceHeadNode1:ListNode! = listNodeManger.headNode listNodeManger.headNode = nil listNodeManger.appendToTail(value: "\(8)") listNodeManger.appendToTail(value: "\(7)") var sequenceHeadNode2:ListNode! = listNodeManger.headNode var sequenceHeadNode3:ListNode? = listNodeManger.addListNode3(node1: sequenceHeadNode1, node2: sequenceHeadNode2) print("FlyElephant---正向相加结果") listNodeManger.printListNode(headNode: sequenceHeadNode3!) var circleHead:ListNode = ListNode(value: "1") var circelNode1:ListNode = ListNode(value: "2") var circelNode2:ListNode = ListNode(value: "3") var circelNode3:ListNode = ListNode(value: "4") circleHead.next = circelNode1 circelNode1.next = circelNode2 circelNode2.next = circelNode3 circelNode3.next = circleHead var beginingNode:ListNode? = listNodeManger.findBeginingNode(headNode: circelNode1) print("FlyElephant---环路链表开始值---\(beginingNode!.value!)") listNodeManger.headNode = nil listNodeManger.appendToTail(value: "\(1)") listNodeManger.appendToTail(value: "\(2)") listNodeManger.appendToTail(value: "\(3)") listNodeManger.appendToTail(value: "\(2)") listNodeManger.appendToTail(value: "\(1)") var isRome:Bool = listNodeManger.isPalindrome(node: listNodeManger.headNode!) if isRome { print("FlyElephant---回文链表") } else { print("FlyElephant---非回文链表") } isRome = listNodeManger.isPalindrome1(node: listNodeManger.headNode!) if isRome { print("FlyElephant---回文链表") } else { print("FlyElephant---非回文链表") } var myStack:Stack = Stack() for i in 10..<25 { myStack.push(stackNum: 0, value: i) } for i in 30..<36 { myStack.push(stackNum: 1, value: i) } for i in 40..<48 { myStack.push(stackNum: 2, value: i) } for i in 0..<3 { for j in 0..<10 { var value:Int? = myStack.pop(stackNum: i) if value != nil { print("FlyElephant---栈号\(i)---\(j)---值:\(String(describing: value!))") } } } var minStack:MinStack = MinStack() var minData:[Int] = [6, 5, 7, 3, 3, 8, 1, 10] for i in 0..<minData.count { minStack.push(value: minData[i]) } for i in 0..<3 { minStack.pop() } print("FlyElephant---minStack的数组-----\(minStack.stack)---最小值--\(minStack.minStack)") var stacks:Stacks = Stacks() for i in 0..<13 { stacks.push(num: i) } print("\(stacks.bufferData)") for i in 0..<8 { var value:Int? = stacks.pop() if value != nil { print("FlyElephant--Pop---\(value!)") } } print("\(stacks.bufferData)") var hanoi:Hanoi = Hanoi() hanoi.move(diskCount: 3) hanoi.move2(diskCount: 3) var myQueue:MyQueue = MyQueue() for i in 0...3 { myQueue.push(value: i) } var topValue:Int? = myQueue.peek() if topValue != nil { print("FlyElephant---顶部数据:\(topValue!)") } for i in 10...15 { myQueue.push(value: i) } for i in 0...4 { var topValue:Int? = myQueue.peek() if topValue != nil { print("FlyElephant---顶部数据:\(topValue!)") } } var stackSort:StackSort = StackSort() var sortData:[Int] = stackSort.sort(data: [8,5,4,3,10,1,7,9,2,6]) print("FlyElephant---排序之后的数据---\(sortData)") var bitManager:BitManager = BitManager() var bitCount:Int = bitManager.bitSwapRequired(a: 10, b: 100) var bitCount2:Int = bitManager.bitSwapRequired2(a: 10, b: 100) print("FlyElephant--需要改变:\(bitCount)位---\(bitCount2)位") var bitBinary:String = bitManager.printBinary(num: 0.625) var bitBinary2:String = bitManager.printBinary2(num: 0.625) print("FlyElephant--二进制的表现形式:\(bitBinary)---\(bitBinary2)") var recursion:Recursion = Recursion() var steps:Int = recursion.countStepWays(n: 10) var map:[Int] = [Int].init(repeating: -1, count: 11) var steps2:Int = recursion.countStepWays2(n: 10, map: &map) print("FlyElephant--跳10级台阶的跳法---\(steps)-----\(steps2)") var tree:Tree = Tree() var preListData:[String] = ["1","2","4","#","#","5","7","#","#","#","3","#","6","#","#"] var preOrderRoot:TreeNode? tree.createTreeByPreOrder(root: &preOrderRoot, listData: preListData) tree.treeLevelOrder(root: preOrderRoot) print("FlyElephant") var binaryTree:BinaryTree = BinaryTree() var isBalanced:Bool = binaryTree.isBalanced(root: preOrderRoot) if isBalanced { print("FlyElephant---是二叉平衡树") } else { print("FlyElehant---不是二叉平衡树") } var isBalanced2:Bool = binaryTree.isBalanced2(root: preOrderRoot) if isBalanced2 { print("FlyElephant---是二叉平衡树") } else { print("FlyElehant---不是二叉平衡树") } var binarySearchTree:BinarySearchTree = BinarySearchTree() var searchData:[Int] = [1,2,3,4,5,6,7] var searchNode:TreeNode? = binarySearchTree.createMinBST(arr: searchData, start: 0, end: searchData.count - 1) tree.treeLevelOrder(root: searchNode) print("FlyElephant") var searchLevelData:[[String]]? = binarySearchTree.createLevelList(node: searchNode) if searchLevelData != nil { print("FlyElephant---层级链表数据---\(searchLevelData!)") } var isBST:Bool = binarySearchTree.isBST(root: searchNode) if isBST { print("FlyElephant---是二叉查找树") } else { print("FlyElephant---不是二叉查找树") } var isBST2:Bool = binarySearchTree.isBST2(root: searchNode) if isBST2 { print("FlyElephant---是二叉查找树") } else { print("FlyElephant---不是二叉查找树") } var isBST3:Bool = binarySearchTree.isBST3(root: searchNode) if isBST3 { print("FlyElephant---是二叉查找树") } else { print("FlyElephant---不是二叉查找树") } var sumListData:[String] = ["10","5","4","#","#","7","#","#","12","#","#"] var sumNode:TreeNode? tree.rootIndex = -1 tree.createTreeByPreOrder(root: &sumNode, listData: sumListData) binaryTree.findPath(root: sumNode, targetNum: 22) print("FlyElephant---和为22的路径----\(binaryTree.pathList)") var invertNode:TreeNode? var invertListData:[String] = ["4","2","1","#","#","3","#","#","7","6","#","#","9","#","#"] tree.rootIndex = -1 tree.createTreeByPreOrder(root: &invertNode, listData: invertListData) tree.treeLevelOrder(root: invertNode) binaryTree.invertTree(rootNode: invertNode) tree.treeLevelOrder(root: invertNode) print("FlyElephant") var updateResult:Int = bitManager.updateBits(n: 1024, m: 19, i: 2, j: 6) print("FlyElephant---最后的结果:\(updateResult)") var test1:Int = ((10 & 0xaaaaaaaa) >> 1 ) var test2:Int = ((10 & 0x55555555 ) << 1) var bitNumber:Int = bitManager.swapOddEvenBits(num: 10) print("FlyElephant---交换之后的数据---\(bitNumber)") var operatorNum:Operator = Operator() var minusNUm:Int = operatorNum.minus(a: 20, b: 10) print("FlyElephant---减法结果:\(minusNUm)") var multiNum:Int = operatorNum.multiply(a: 10, b: -4) print("FlyElephant---乘法结果:\(multiNum)") var divideNum:Int? = operatorNum.divide(a: 10, b: -3) print("FlyElephant---除法结果:\(divideNum!)") var factor:Factor = Factor() var factorNum:Int = factor.getKthFactorNumber(k: 10) print("FlyElephant---3,5,7因子数字:\(factorNum)") var factorNum2:Int = factor.getKthFactorNumber2(k: 10) print("FlyElephant---3,5,7因子数字:\(factorNum2)") var factorNum3:Int = factor.getKthFactorNumber3(k: 10) print("FlyElephant---3,5,7因子数字:\(factorNum3)") var magicArr:[Int] = [-40, -20, -1, 1, 2, 3, 5, 7, 9, 12, 13] var magicIndex:Int = recursion.magicFast(arr: &magicArr, start: 0, end: magicArr.count - 1) print("FlyElephant---\(magicArr)中间值:\(magicIndex)") magicArr = [-10, -5, 2, 2, 2, 3, 4, 7, 9, 12, 13] magicIndex = recursion.magicFast2(arr: &magicArr, start: 0, end: magicArr.count - 1) print("FlyElephant---\(magicArr)中间值:\(magicIndex)") var permutations:[String] = recursion.getPerms(str: "abc") print("FlyElephant---字符串排列:\(permutations)") var ways:Int = recursion.makeChange(n: 100, denom: 25) print("FlyElephant---100分的表示方式:\(ways)") var left:Int = 1 << 3 print("左移动之后的数据:\(left)") var checkData:[Int] = [1, 2, 24, 800 ,10, 20, 800, 2, 9] bitManager.checkDuplicates(arr: checkData)
mit
8cb654502eed6efff334f09c38dbc54c
27.796651
113
0.718701
2.984627
false
false
false
false
grpc/grpc-swift
Tests/GRPCTests/GRPCIdleTests.swift
1
2735
/* * Copyright 2020, gRPC Authors All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import EchoImplementation import EchoModel @testable import GRPC import NIOCore import NIOPosix import XCTest class GRPCIdleTests: GRPCTestCase { func testClientIdleTimeout() { XCTAssertNoThrow( try self .doTestIdleTimeout(serverIdle: .minutes(5), clientIdle: .milliseconds(100)) ) } func testServerIdleTimeout() throws { XCTAssertNoThrow( try self .doTestIdleTimeout(serverIdle: .milliseconds(100), clientIdle: .minutes(5)) ) } func doTestIdleTimeout(serverIdle: TimeAmount, clientIdle: TimeAmount) throws { let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) defer { XCTAssertNoThrow(try group.syncShutdownGracefully()) } // Setup a server. let server = try Server.insecure(group: group) .withServiceProviders([EchoProvider()]) .withConnectionIdleTimeout(serverIdle) .withLogger(self.serverLogger) .bind(host: "localhost", port: 0) .wait() defer { XCTAssertNoThrow(try server.close().wait()) } // Setup a state change recorder for the client. let stateRecorder = RecordingConnectivityDelegate() stateRecorder.expectChanges(3) { changes in XCTAssertEqual(changes, [ Change(from: .idle, to: .connecting), Change(from: .connecting, to: .ready), Change(from: .ready, to: .idle), ]) } // Setup a connection. let connection = ClientConnection.insecure(group: group) .withConnectivityStateDelegate(stateRecorder) .withConnectionIdleTimeout(clientIdle) .withBackgroundActivityLogger(self.clientLogger) .connect(host: "localhost", port: server.channel.localAddress!.port!) defer { XCTAssertNoThrow(try connection.close().wait()) } let client = Echo_EchoNIOClient(channel: connection) // Make a call; this will trigger channel creation. let get = client.get(.with { $0.text = "ignored" }) let status = try get.status.wait() XCTAssertEqual(status.code, .ok) // Now wait for the state changes. stateRecorder.waitForExpectedChanges(timeout: .seconds(10)) } }
apache-2.0
a49c2aebe52ed58ab45b25657fbe4ef7
31.176471
83
0.699452
4.266771
false
true
false
false
orucrob/Hoppla
Hoppla/HopplaSummaryBoard.swift
1
6333
/* The MIT License (MIT) Copyright (c) 2015 Rob Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation import UIKit class HopplaSummaryBoard: UIView { enum Mode{ case NORMAL, DETAIL } var titleLabel : UILabel?{ didSet{ oldValue?.removeFromSuperview() if let t = titleLabel{ addSubview(t) bringSubviewToFront(t) layoutTitle(skipSizing: false, forMode: mode) } } } /// duration for animation between modes @IBInspectable var animationDuration = 0.3 ///board var board: HopplaBoard?{ didSet{ oldValue?.removeFromSuperview() if let b = board{ addSubview(b) b.frame = bounds bringSubviewToFront(b) } } } ///title var title:String?{ get{ return titleLabel?.text } set(v){ if(v == nil){ titleLabel?.text = nil }else{ if( titleLabel == nil){ titleLabel = UILabel() } titleLabel?.text = v layoutTitle(skipSizing: false, forMode: mode) } } } ///background view var backgroundView:UIView?{ didSet{ oldValue?.removeFromSuperview() if let b = backgroundView{ addSubview(b) sendSubviewToBack(b) b.frame = bounds } } } ///display mode private var _mode:Mode = .NORMAL var mode:Mode { get{ return _mode } set(v){ setMode(v, animate:false) } } ///set mode with animate option func setMode(mode:Mode, animate:Bool=true){ if (mode == .DETAIL){ _transformToDetail(animate) }else if (mode == .NORMAL){ _transformToNormal(animate) } _mode = mode } // ///MARK: - copy properties from board // private var _levels = 0 // @IBInspectable var boardLevels: Int{ // get{ // return _levels // } // set(v){ // _levels = v // _board?.levels = _levels // } // } // private var _indexesInLevel = 0 // @IBInspectable var boardIndexesInLevel:Int{ // get{ // return _indexesInLevel // } // set(v){ // _indexesInLevel = v // _board?.indexesInLevel = _indexesInLevel // } // } // ///MARK: - layout private var _h:CGFloat = 0, _w:CGFloat = 0 override func layoutSubviews() { if(_h != bounds.height || _w != bounds.width){ _h = bounds.height; _w = bounds.width board?.frame = bounds layoutTitle(skipSizing: false, forMode: mode) backgroundView?.frame = bounds if(mode == .DETAIL){ _transformToDetail(false)//TODO double layout title } super.layoutSubviews() } } private func layoutTitle(skipSizing: Bool = false, forMode: Mode){ if let t = titleLabel{ if( !skipSizing){ t.sizeToFit() if (t.bounds.size.width > bounds.width){ t.adjustsFontSizeToFitWidth = true t.bounds.size.width = bounds.width } } if(forMode == .NORMAL){ t.frame.origin = CGPoint(x: 8 , y: bounds.height/2 - t.bounds.height/2) }else{ t.frame.origin = CGPoint(x: bounds.width/2 - t.bounds.width/2, y: 8) } } } ///MARK: - transformation between modes private func _transformToDetail(animate:Bool){ board?.setMode(HopplaBoard.Mode.DETAIL, animate: animate) if(animate){ UIView.animateWithDuration(animationDuration, animations: { () -> Void in if let bv = self.backgroundView{ bv.frame = CGRect(x: 0, y: 0, width: self.bounds.width, height: self.bounds.height/2) } self.layoutTitle(skipSizing: true, forMode: .DETAIL) }) }else{ if let bv = self.backgroundView{ bv.frame = CGRect(x: 0, y: 0, width: self.bounds.width, height: self.bounds.height/2) } layoutTitle(skipSizing: true, forMode: .DETAIL) } } private func _transformToNormal(animate:Bool){ board?.setMode(HopplaBoard.Mode.NORMAL, animate: animate) if(animate){ UIView.animateWithDuration(animationDuration, animations: { () -> Void in if let bv = self.backgroundView{ bv.frame = CGRect(x: 0, y: 0, width: self.bounds.width, height: self.bounds.height) } self.layoutTitle(skipSizing: true, forMode: .NORMAL) }) }else{ if let bv = self.backgroundView{ bv.frame = CGRect(x: 0, y: 0, width: self.bounds.width, height: self.bounds.height) } layoutTitle(skipSizing: true, forMode: .NORMAL) } } }
mit
34f15713c79b50f543544c826d262792
30.512438
109
0.540502
4.539785
false
false
false
false
zixun/ZXKit
Pod/Classes/controller/ZXNavigationController/ZXNavigationController.swift
1
3101
// // ZXNavigationController.swift // CocoaChinaPlus // // Created by 子循 on 15/8/4. // Copyright © 2015年 zixun. All rights reserved. // import UIKit public class ZXNavigationController: UINavigationController { public var enable = true override public func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.blackColor() // 获取系统自带滑动手势的target对象 let target = self.interactivePopGestureRecognizer!.delegate; // 创建全屏滑动手势,调用系统自带滑动手势的target的action方法 let pan = UIPanGestureRecognizer(target: target, action: Selector("handleNavigationTransition:")) // 设置手势代理,拦截手势触发 pan.delegate = self; // 给导航控制器的view添加全屏滑动手势 self.view.addGestureRecognizer(pan); // 禁止使用系统自带的滑动手势 self.interactivePopGestureRecognizer!.enabled = false; let image = UIImage.image(ZXColor(0x272626), size: CGSizeMake(ZXScreenWidth(), 0.5)) let imageView = UIImageView(image: image) self.navigationBar.addSubview(imageView) var rect = self.navigationBar.bounds rect.origin.y = rect.origin.y + rect.size.height - 0.5 rect.size.height = 0.5 imageView.frame = rect } override public func pushViewController(viewController: UIViewController, animated: Bool) { if self.viewControllers.count > 0 { viewController.hidesBottomBarWhenPushed = true } super.pushViewController(viewController, animated: animated) } } // MARK: UIGestureRecognizerDelegate extension ZXNavigationController: UIGestureRecognizerDelegate { public func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool { let translation: CGPoint = (gestureRecognizer as! UIPanGestureRecognizer).translationInView(self.view.superview) guard self.enable == true else { return false } if (translation.x < 0) { return false //往右滑返回,往左滑不做操作 } if (self.viewControllers.count <= 1) { return false } return true } } extension UIViewController { public func presentViewController(viewControllerToPresent: UIViewController) { self.presentViewController(viewControllerToPresent, animated: true, completion: nil) } public func presentViewController(viewControllerToPresent: UIViewController,withNavigation:Bool, animated flag: Bool, completion: (() -> Void)?) { if withNavigation == false { self.presentViewController(viewControllerToPresent, animated: flag, completion: completion) }else { let nav = ZXNavigationController(rootViewController: viewControllerToPresent) self.presentViewController(nav, animated: flag, completion: completion) } } }
mit
79fb9dad4f7fcb434016c853602aa583
32.113636
150
0.660261
5.157522
false
false
false
false
nRewik/swift-corelibs-foundation
TestFoundation/TestNSFileManager.swift
1
8681
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // #if DEPLOYMENT_RUNTIME_OBJC || os(Linux) import Foundation import XCTest #else import SwiftFoundation import SwiftXCTest #endif class TestNSFileManger : XCTestCase { var allTests : [(String, () -> Void)] { return [ ("test_createDirectory", test_createDirectory ), ("test_createFile", test_createFile ), ("test_fileSystemRepresentation", test_fileSystemRepresentation), ("test_fileAttributes", test_fileAttributes), ("test_directoryEnumerator", test_directoryEnumerator), ] } func ignoreError(@noescape block: () throws -> Void) { do { try block() } catch { } } func test_createDirectory() { let fm = NSFileManager.defaultManager() let path = "/tmp/testdir" ignoreError { try fm.removeItemAtPath(path) } do { try fm.createDirectoryAtPath(path, withIntermediateDirectories: false, attributes: nil) } catch _ { XCTFail() } var isDir = false let exists = fm.fileExistsAtPath(path, isDirectory: &isDir) XCTAssertTrue(exists) XCTAssertTrue(isDir) do { try fm.removeItemAtPath(path) } catch { XCTFail("Failed to clean up file") } } func test_createFile() { let fm = NSFileManager.defaultManager() let path = "/tmp/testfile" ignoreError { try fm.removeItemAtPath(path) } XCTAssertTrue(fm.createFileAtPath(path, contents: NSData(), attributes: nil)) var isDir = false let exists = fm.fileExistsAtPath(path, isDirectory: &isDir) XCTAssertTrue(exists) XCTAssertFalse(isDir) do { try fm.removeItemAtPath(path) } catch { XCTFail("Failed to clean up file") } } func test_fileSystemRepresentation() { let str = "☃" let result = NSFileManager.defaultManager().fileSystemRepresentationWithPath(str) XCTAssertNotNil(result) let uintResult = UnsafePointer<UInt8>(result) XCTAssertEqual(uintResult[0], 0xE2) XCTAssertEqual(uintResult[1], 0x98) XCTAssertEqual(uintResult[2], 0x83) } func test_fileAttributes() { let fm = NSFileManager.defaultManager() let path = "/tmp/testfile" ignoreError { try fm.removeItemAtPath(path) } XCTAssertTrue(fm.createFileAtPath(path, contents: NSData(), attributes: nil)) do { let attrs = try fm.attributesOfItemAtPath(path) XCTAssertTrue(attrs.count > 0) let fileSize = attrs[NSFileSize] as? NSNumber XCTAssertEqual(fileSize!.longLongValue, 0) let fileModificationDate = attrs[NSFileModificationDate] as? NSDate XCTAssertGreaterThan(NSDate().timeIntervalSince1970, fileModificationDate!.timeIntervalSince1970) let filePosixPermissions = attrs[NSFilePosixPermissions] as? NSNumber XCTAssertNotEqual(filePosixPermissions!.longLongValue, 0) let fileReferenceCount = attrs[NSFileReferenceCount] as? NSNumber XCTAssertEqual(fileReferenceCount!.longLongValue, 1) let fileSystemNumber = attrs[NSFileSystemNumber] as? NSNumber XCTAssertNotEqual(fileSystemNumber!.longLongValue, 0) let fileSystemFileNumber = attrs[NSFileSystemFileNumber] as? NSNumber XCTAssertNotEqual(fileSystemFileNumber!.longLongValue, 0) let fileType = attrs[NSFileType] as? String XCTAssertEqual(fileType!, NSFileTypeRegular) let fileOwnerAccountID = attrs[NSFileOwnerAccountID] as? NSNumber XCTAssertNotNil(fileOwnerAccountID) } catch let err { XCTFail("\(err)") } do { try fm.removeItemAtPath(path) } catch { XCTFail("Failed to clean up files") } } func test_directoryEnumerator() { let fm = NSFileManager.defaultManager() let path = "/tmp/testdir" let itemPath = "/tmp/testdir/item" ignoreError { try fm.removeItemAtPath(path) } do { try fm.createDirectoryAtPath(path, withIntermediateDirectories: false, attributes: nil) fm.createFileAtPath(itemPath, contents: NSData(), attributes: nil) } catch _ { XCTFail() } if let e = NSFileManager.defaultManager().enumeratorAtURL(NSURL(fileURLWithPath: path), includingPropertiesForKeys: nil, options: [], errorHandler: nil) { var foundItems = [String:Int]() while let item = e.nextObject() as? NSURL { if let p = item.path { foundItems[p] = e.level } } XCTAssertEqual(foundItems[itemPath], 1) } else { XCTFail() } let subDirPath = "/tmp/testdir/testdir2" let subDirItemPath = "/tmp/testdir/testdir2/item" do { try fm.createDirectoryAtPath(subDirPath, withIntermediateDirectories: false, attributes: nil) fm.createFileAtPath(subDirItemPath, contents: NSData(), attributes: nil) } catch _ { XCTFail() } if let e = NSFileManager.defaultManager().enumeratorAtURL(NSURL(fileURLWithPath: path), includingPropertiesForKeys: nil, options: [], errorHandler: nil) { var foundItems = [String:Int]() while let item = e.nextObject() as? NSURL { if let p = item.path { foundItems[p] = e.level } } XCTAssertEqual(foundItems[itemPath], 1) XCTAssertEqual(foundItems[subDirPath], 1) XCTAssertEqual(foundItems[subDirItemPath], 2) } else { XCTFail() } if let e = NSFileManager.defaultManager().enumeratorAtURL(NSURL(fileURLWithPath: path), includingPropertiesForKeys: nil, options: [.SkipsSubdirectoryDescendants], errorHandler: nil) { var foundItems = [String:Int]() while let item = e.nextObject() as? NSURL { if let p = item.path { foundItems[p] = e.level } } XCTAssertEqual(foundItems[itemPath], 1) XCTAssertEqual(foundItems[subDirPath], 1) } else { XCTFail() } if let e = NSFileManager.defaultManager().enumeratorAtURL(NSURL(fileURLWithPath: path), includingPropertiesForKeys: nil, options: [], errorHandler: nil) { var foundItems = [String:Int]() while let item = e.nextObject() as? NSURL { if let p = item.path { foundItems[p] = e.level } } XCTAssertEqual(foundItems[itemPath], 1) XCTAssertEqual(foundItems[subDirPath], 1) } else { XCTFail() } var didGetError = false let handler : (NSURL, NSError) -> Bool = { (NSURL, NSError) in didGetError = true return true } if let e = NSFileManager.defaultManager().enumeratorAtURL(NSURL(fileURLWithPath: "/nonexistant-path"), includingPropertiesForKeys: nil, options: [], errorHandler: handler) { XCTAssertNil(e.nextObject()) } else { XCTFail() } XCTAssertTrue(didGetError) do { let contents = try NSFileManager.defaultManager().contentsOfDirectoryAtURL(NSURL(fileURLWithPath: path), includingPropertiesForKeys: nil, options: []).map { return $0.path! } XCTAssertEqual(contents.count, 2) XCTAssertTrue(contents.contains(itemPath)) XCTAssertTrue(contents.contains(subDirPath)) } catch { XCTFail() } do { try fm.removeItemAtPath(path) } catch { XCTFail("Failed to clean up files") } } }
apache-2.0
a16ab0e722d9827f6319164fd9fbe111
34.867769
191
0.576218
5.301772
false
true
false
false
midoks/Swift-Learning
EampleApp/EampleApp/Framework/PictureSwitching/PictureSwitching.swift
1
6474
// // PictureSwitching.swift // // Created by midoks on 15/8/15. // Copyright © 2015年 midoks. All rights reserved. // import Foundation import UIKit class PictureSwitching: UIView, UIScrollViewDelegate { //滚动的View var contentScrollView: UIScrollView! var pageIndicator: UIPageControl! //页数指示器 var timer: Timer? //计时器 //图片列表 var imageArray: [UIImage?]! //当前的现实第几张图片 var indexOfCurrentImage: Int! var imageRollingDirection: Int! //代理 var delegate: PictureSwitchingDelegate? //MARK: - Start - override init(frame: CGRect) { super.init(frame: frame) } convenience init(frame: CGRect, imageArray: [UIImage?]? ) { self.init(frame: frame) //图片存放数组 self.imageArray = imageArray //当前显示的图片 self.indexOfCurrentImage = 0 //滚动方向 0:从右往左 self.imageRollingDirection = 0 //建立UI self.setUp() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: - Private - fileprivate func setUp(){ //print(imageArray.count) //循环 if(self.imageArray.count > 0){ self.contentScrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)) contentScrollView.contentSize = CGSize(width: self.frame.size.width * CGFloat(self.imageArray.count), height: 0) contentScrollView.delegate = self contentScrollView.bounces = false contentScrollView.isPagingEnabled = true contentScrollView.backgroundColor = UIColor.green contentScrollView.showsHorizontalScrollIndicator = false contentScrollView.isScrollEnabled = !(imageArray.count == 1) self.addSubview(contentScrollView) for i in 0 ..< self.imageArray.count { let imgView = UIImageView() imgView.frame = CGRect(x: self.frame.size.width * CGFloat(i), y: 0, width: self.frame.size.width, height: 200) imgView.isUserInteractionEnabled = true imgView.contentMode = UIViewContentMode.scaleAspectFill imgView.clipsToBounds = true contentScrollView.addSubview(imgView) imgView.image = self.imageArray[i] //添加点击事件 let imageTap = UITapGestureRecognizer(target: self, action: #selector(PictureSwitching.imageTapAction(_:))) imgView.addGestureRecognizer(imageTap) } } //设置分页指示器 //显示在右边 // self.pageIndicator = UIPageControl(frame: CGRectMake(self.frame.size.width - 20 * CGFloat(imageArray.count), // self.frame.size.height - 30, // 20 * CGFloat(imageArray.count), // 20)) self.pageIndicator = UIPageControl(frame: CGRect(x: 0, y: self.frame.size.height - 20, width: self.frame.size.width, height: 20)) pageIndicator.hidesForSinglePage = true pageIndicator.numberOfPages = imageArray.count pageIndicator.backgroundColor = UIColor.clear self.addSubview(pageIndicator) //设置计时器 self.timeStart() } //定时开始 func timeStart(){ if(self.timer == nil){ self.timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(PictureSwitching.timerAction), userInfo: nil, repeats: true) } } //取消定时 func timeStop(){ if(self.timer != nil){ self.timer!.invalidate() self.timer = nil } } //定时事件触发方法 func timerAction() { if(self.imageRollingDirection == 0){ //正方向 self.indexOfCurrentImage = self.indexOfCurrentImage + 1 if(self.indexOfCurrentImage >= self.imageArray.count){ self.indexOfCurrentImage = self.imageArray.count - 2 self.imageRollingDirection = 1 } }else{ self.indexOfCurrentImage = self.indexOfCurrentImage - 1 if(self.indexOfCurrentImage <= 0){//反反向 self.indexOfCurrentImage = 0 self.imageRollingDirection = 0 } } //print(self.indexOfCurrentImage) self.jumpImageIndex(CGFloat(self.indexOfCurrentImage)) } func jumpImageIndex(_ currentIndex:CGFloat){ pageIndicator.currentPage = self.indexOfCurrentImage contentScrollView.setContentOffset(CGPoint(x: self.frame.size.width * currentIndex, y: 0), animated: true) } //图片点击 func imageTapAction(_ tap:UIButton){ self.delegate!.PictureSwitchingTap!(indexOfCurrentImage) } //MARK: - UIScrollViewDelegate Methods - //拖拽开始 func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { //print("Dragging Start") self.timeStop() } //拖拽结束 func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { //print("Dragging End") //print(scrollView.contentOffset.x) //print(self.frame.width) //print(indexOfCurrentImage) //self.timeStart() } //滚动加速结束 func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { //print("EndDecelerating") let index = scrollView.contentOffset.x / self.frame.width self.indexOfCurrentImage = Int(index) self.pageIndicator.currentPage = self.indexOfCurrentImage self.timeStart() } //动画执行结束 func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { self.delegate?.PictureSwitchingEndScrolling!(self.indexOfCurrentImage) } } //MARK: - 代理 - @objc protocol PictureSwitchingDelegate{ //点击图片代理 @objc optional func PictureSwitchingTap(_ tapIndex: Int) //滚动动画结束代理 @objc optional func PictureSwitchingEndScrolling(_ currentIndex: Int) }
apache-2.0
1731af981ed415eb67be351057d749c6
30.140704
138
0.598354
4.864207
false
false
false
false
XiaHaozheJose/swift3_wb
sw3_wb/sw3_wb/Classes/View/Home/WB_HomeViewController.swift
1
1819
// // WB_HomeViewController.swift // sw3_wb // // Created by 浩哲 夏 on 2017/9/13. // Copyright © 2017年 浩哲 夏. All rights reserved. // import UIKit fileprivate let cellId = "homeCellId" class WB_HomeViewController: WB_BaseViewController { ///数据数组 fileprivate lazy var statusList = [String]() ///加载假数据 override func loadData() { for i in 0..<15{ statusList.insert(i.description, at: 0) } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } // MARK: - 监听 @objc fileprivate func addFriend(){ let vc = WB_DemoViewController(); navigationController?.pushViewController(vc, animated: true) } } // MARK: - UI extension WB_HomeViewController{ override func setUI(){ super.setUI() //左侧NaviItem navigationItem.leftBarButtonItem = UIBarButtonItem(title: "好友", fontSize: 16, normalColor: UIColor.black, highlightColor: UIColor.orange, target: self, action: #selector(addFriend)) ///注册原型cell tableView?.register(UITableViewCell.self, forCellReuseIdentifier: cellId) } } // MARK: - 数据源,具体的数据源方法,不需要super extension WB_HomeViewController{ override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return statusList.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) cell.textLabel?.text = statusList[indexPath.row] return cell } }
mit
dd47ec67c7a87e9fb976b702930ad5b4
22.173333
189
0.634638
4.585752
false
false
false
false
easyui/SwiftMan
SwiftMan/Extension/UIKit/UITabBar/UITabBar+Man.swift
1
1980
// // UITabBar+Man.swift // SwiftMan // // Created by yangjun zhu on 2017/1/11. // Copyright © 2017年 cactus. All rights reserved. // #if canImport(UIKit) && !os(watchOS) import UIKit extension UITabBar { /// Set tabBar colors. /// /// - Parameters: /// - background: background color. /// - selectedBackground: background color for selected tab. /// - item: icon tint color for items. /// - selectedItem: icon tint color for item. public func m_setColors(background: UIColor? = nil, selectedBackground: UIColor? = nil, item: UIColor? = nil, selectedItem: UIColor? = nil) { // background self.barTintColor = background ?? self.barTintColor // selectedItem self.tintColor = selectedItem ?? self.tintColor // self.shadowImage = UIImage() self.backgroundImage = UIImage() self.isTranslucent = false // selectedBackgoundColor if let selectedbg = selectedBackground { let rect = CGSize(width: self.frame.width/CGFloat(self.items!.count), height: self.frame.height) self.selectionIndicatorImage = UIImage.m_image(color: selectedbg, size: rect) } if let itemColor = item { for barItem in self.items! as [UITabBarItem] { // item if let image = barItem.image { barItem.image = (image.m_filled(withColor: itemColor) ?? image).withRenderingMode(.alwaysOriginal) barItem.setTitleTextAttributes([NSAttributedString.Key.foregroundColor : itemColor], for: .normal) if let selected = selectedItem { barItem.setTitleTextAttributes([NSAttributedString.Key.foregroundColor : selected], for: .selected) } } } } } } #endif
mit
2afb2dee307e219453d05274299eb347
33.684211
123
0.565503
4.930175
false
false
false
false
dobleuber/my-swift-exercises
Project15/Project15/ViewController.swift
1
2088
// // ViewController.swift // Project15 // // Created by Wbert Castro on 15/07/17. // Copyright © 2017 Wbert Castro. All rights reserved. // import UIKit class ViewController: UIViewController { var imageView: UIImageView! var currentAnimation = 0 @IBOutlet weak var tap: UIButton! override func viewDidLoad() { super.viewDidLoad() imageView = UIImageView(image: UIImage(named: "penguin")) imageView.center = CGPoint(x: 512, y: 384) view.addSubview(imageView) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func tapped(_ sender: UIButton) { tap.isHidden = true UIView.animate(withDuration: 1, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 5, options: [], animations: {[unowned self] in switch self.currentAnimation { case 0: self.imageView.transform = CGAffineTransform(scaleX: 2, y: 2) case 1: self.imageView.transform = CGAffineTransform.identity case 2: self.imageView.transform = CGAffineTransform(translationX: -256, y: -256) case 3: self.imageView.transform = CGAffineTransform.identity case 4: self.imageView.transform = CGAffineTransform(rotationAngle: CGFloat.pi) case 5: self.imageView.transform = CGAffineTransform.identity case 6: self.imageView.alpha = 0.1 self.imageView.backgroundColor = UIColor.green case 7: self.imageView.alpha = 1 self.imageView.backgroundColor = UIColor.clear default: break } }) { [unowned self] (finished: Bool) in self.tap.isHidden = false } currentAnimation += 1 if currentAnimation > 7 { currentAnimation = 0 } } }
mit
3a82d144bf45eb83f5fbcad0f131eabe
30.621212
148
0.578821
5.102689
false
false
false
false
natecook1000/swift
test/SILGen/addressors.swift
1
22658
// RUN: %target-swift-emit-sil -enable-sil-ownership -parse-stdlib %s | %FileCheck %s // RUN: %target-swift-emit-silgen -enable-sil-ownership -parse-stdlib %s | %FileCheck %s -check-prefix=SILGEN // RUN: %target-swift-emit-ir -enable-sil-ownership -parse-stdlib %s // This test includes some calls to transparent stdlib functions. // We pattern match for the absence of access markers in the inlined code. // REQUIRES: optimized_stdlib import Swift func someValidPointer<T>() -> UnsafePointer<T> { fatalError() } func someValidPointer<T>() -> UnsafeMutablePointer<T> { fatalError() } struct A { var base: UnsafeMutablePointer<Int32> = someValidPointer() subscript(index: Int32) -> Int32 { unsafeAddress { return UnsafePointer(base) } unsafeMutableAddress { return base } } static var staticProp: Int32 { unsafeAddress { // Just don't trip up the verifier. fatalError() } } } // CHECK-LABEL: sil hidden @$S10addressors1AVys5Int32VAEcilu : $@convention(method) (Int32, A) -> UnsafePointer<Int32> // CHECK: bb0([[INDEX:%.*]] : $Int32, [[SELF:%.*]] : $A): // CHECK: [[BASE:%.*]] = struct_extract [[SELF]] : $A, #A.base // CHECK: [[T0:%.*]] = struct_extract [[BASE]] : $UnsafeMutablePointer<Int32>, #UnsafeMutablePointer._rawValue // CHECK: [[T1:%.*]] = struct $UnsafePointer<Int32> ([[T0]] : $Builtin.RawPointer) // CHECK: return [[T1]] : $UnsafePointer<Int32> // CHECK-LABEL: sil hidden @$S10addressors1AVys5Int32VAEciau : $@convention(method) (Int32, @inout A) -> UnsafeMutablePointer<Int32> // CHECK: bb0([[INDEX:%.*]] : $Int32, [[SELF:%.*]] : $*A): // CHECK: [[READ:%.*]] = begin_access [read] [static] [[SELF]] : $*A // CHECK: [[T0:%.*]] = struct_element_addr [[READ]] : $*A, #A.base // CHECK: [[BASE:%.*]] = load [[T0]] : $*UnsafeMutablePointer<Int32> // CHECK: return [[BASE]] : $UnsafeMutablePointer<Int32> // CHECK-LABEL: sil hidden @$S10addressors5test0yyF : $@convention(thin) () -> () { func test0() { // CHECK: [[A:%.*]] = alloc_stack $A // CHECK: [[T1:%.*]] = metatype $@thin A.Type // CHECK: [[T0:%.*]] = function_ref @$S10addressors1AV{{[_0-9a-zA-Z]*}}fC // CHECK: [[AVAL:%.*]] = apply [[T0]]([[T1]]) // CHECK: store [[AVAL]] to [[A]] var a = A() // CHECK: [[T0:%.*]] = function_ref @$S10addressors1AVys5Int32VAEcilu : // CHECK: [[T1:%.*]] = apply [[T0]]({{%.*}}, [[AVAL]]) // CHECK: [[T2:%.*]] = struct_extract [[T1]] : $UnsafePointer<Int32>, #UnsafePointer._rawValue // CHECK: [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*Int32 // CHECK: [[ACCESS:%.*]] = begin_access [read] [unsafe] [[T3]] : $*Int32 // CHECK: [[Z:%.*]] = load [[ACCESS]] : $*Int32 let z = a[10] // CHECK: [[WRITE:%.*]] = begin_access [modify] [static] [[A]] : $*A // CHECK: [[T0:%.*]] = function_ref @$S10addressors1AVys5Int32VAEciau : // CHECK: [[T1:%.*]] = apply [[T0]]({{%.*}}, [[WRITE]]) // CHECK: [[T2:%.*]] = struct_extract [[T1]] : $UnsafeMutablePointer<Int32>, #UnsafeMutablePointer._rawValue // CHECK: [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*Int32 // CHECK: [[ACCESS:%.*]] = begin_access [modify] [unsafe] [[T3]] : $*Int32 // CHECK: load // CHECK: sadd_with_overflow_Int{{32|64}} // CHECK: store {{%.*}} to [[ACCESS]] a[5] += z // CHECK: [[WRITE:%.*]] = begin_access [modify] [static] [[A]] : $*A // CHECK: [[T0:%.*]] = function_ref @$S10addressors1AVys5Int32VAEciau : // CHECK: [[T1:%.*]] = apply [[T0]]({{%.*}}, [[WRITE]]) // CHECK: [[T2:%.*]] = struct_extract [[T1]] : $UnsafeMutablePointer<Int32>, #UnsafeMutablePointer._rawValue // CHECK: [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*Int32 // CHECK: [[ACCESS:%.*]] = begin_access [modify] [unsafe] [[T3]] : $*Int32 // CHECK: store {{%.*}} to [[ACCESS]] a[3] = 6 } // CHECK-LABEL: sil hidden @$S10addressors5test1s5Int32VyF : $@convention(thin) () -> Int32 func test1() -> Int32 { // CHECK: [[T0:%.*]] = metatype $@thin A.Type // CHECK: [[CTOR:%.*]] = function_ref @$S10addressors1AV{{[_0-9a-zA-Z]*}}fC // CHECK: [[A:%.*]] = apply [[CTOR]]([[T0]]) : $@convention(method) (@thin A.Type) -> A // CHECK: [[ACCESSOR:%.*]] = function_ref @$S10addressors1AVys5Int32VAEcilu : $@convention(method) (Int32, A) -> UnsafePointer<Int32> // CHECK: [[PTR:%.*]] = apply [[ACCESSOR]]({{%.*}}, [[A]]) : $@convention(method) (Int32, A) -> UnsafePointer<Int32> // CHECK: [[T0:%.*]] = struct_extract [[PTR]] : $UnsafePointer<Int32>, #UnsafePointer._rawValue // CHECK: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*Int32 // CHECK: [[ACCESS:%.*]] = begin_access [read] [unsafe] [[T1]] : $*Int32 // CHECK: [[T2:%.*]] = load [[ACCESS]] : $*Int32 // CHECK: return [[T2]] : $Int32 return A()[0] } let uninitAddr = UnsafeMutablePointer<Int32>.allocate(capacity: 1) var global: Int32 { unsafeAddress { return UnsafePointer(uninitAddr) } // CHECK: sil hidden @$S10addressors6globals5Int32Vvlu : $@convention(thin) () -> UnsafePointer<Int32> { // CHECK: [[T0:%.*]] = global_addr @$S10addressors10uninitAddrSpys5Int32VGvp : $*UnsafeMutablePointer<Int32> // CHECK: [[T1:%.*]] = load [[T0]] : $*UnsafeMutablePointer<Int32> // CHECK: [[T2:%.*]] = struct_extract [[T1]] : $UnsafeMutablePointer<Int32>, #UnsafeMutablePointer._rawValue // CHECK: [[T3:%.*]] = struct $UnsafePointer<Int32> ([[T2]] : $Builtin.RawPointer) // CHECK: return [[T3]] : $UnsafePointer<Int32> } func test_global() -> Int32 { return global } // CHECK-LABEL: sil hidden @$S10addressors11test_globals5Int32VyF : $@convention(thin) () -> Int32 { // CHECK: [[T0:%.*]] = function_ref @$S10addressors6globals5Int32Vvlu : $@convention(thin) () -> UnsafePointer<Int32> // CHECK: [[T1:%.*]] = apply [[T0]]() : $@convention(thin) () -> UnsafePointer<Int32> // CHECK: [[T2:%.*]] = struct_extract [[T1]] : $UnsafePointer<Int32>, #UnsafePointer._rawValue // CHECK: [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*Int32 // CHECK: [[ACCESS:%.*]] = begin_access [read] [unsafe] [[T3]] : $*Int32 // CHECK: [[T4:%.*]] = load [[ACCESS]] : $*Int32 // CHECK: return [[T4]] : $Int32 // Test that having generated trivial accessors for something because // of protocol conformance doesn't force us down inefficient access paths. protocol Subscriptable { subscript(i: Int32) -> Int32 { get set } } struct B : Subscriptable { subscript(i: Int32) -> Int32 { unsafeAddress { return someValidPointer() } unsafeMutableAddress { return someValidPointer() } } } // CHECK-LABEL: sil hidden @$S10addressors6test_ByyAA1BVzF : $@convention(thin) (@inout B) -> () { // CHECK: bb0([[B:%.*]] : $*B): // CHECK: [[T0:%.*]] = integer_literal $Builtin.Int32, 0 // CHECK: [[INDEX:%.*]] = struct $Int32 ([[T0]] : $Builtin.Int32) // CHECK: [[RHS:%.*]] = integer_literal $Builtin.Int32, 7 // CHECK: [[WRITE:%.*]] = begin_access [modify] [static] [[B]] : $*B // CHECK: [[T0:%.*]] = function_ref @$S10addressors1BVys5Int32VAEciau // CHECK: [[PTR:%.*]] = apply [[T0]]([[INDEX]], [[WRITE]]) // CHECK: [[T0:%.*]] = struct_extract [[PTR]] : $UnsafeMutablePointer<Int32>, // CHECK: [[ADDR:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*Int32 // CHECK: [[ACCESS:%.*]] = begin_access [modify] [unsafe] [[ADDR]] : $*Int32 // Accept either of struct_extract+load or load+struct_element_addr. // CHECK: load // CHECK: [[T1:%.*]] = builtin "or_Int32" // CHECK: [[T2:%.*]] = struct $Int32 ([[T1]] : $Builtin.Int32) // CHECK: store [[T2]] to [[ACCESS]] : $*Int32 func test_B(_ b: inout B) { b[0] |= 7 } // Test that we handle abstraction difference. struct CArray<T> { var storage: UnsafeMutablePointer<T> subscript(index: Int) -> T { unsafeAddress { return UnsafePointer(storage) + index } unsafeMutableAddress { return storage + index } } } func id_int(_ i: Int32) -> Int32 { return i } // CHECK-LABEL: sil hidden @$S10addressors11test_carrayys5Int32VAA6CArrayVyA2DcGzF : $@convention(thin) (@inout CArray<(Int32) -> Int32>) -> Int32 { // CHECK: bb0([[ARRAY:%.*]] : $*CArray<(Int32) -> Int32>): func test_carray(_ array: inout CArray<(Int32) -> Int32>) -> Int32 { // CHECK: [[WRITE:%.*]] = begin_access [modify] [static] [[ARRAY]] : $*CArray<(Int32) -> Int32> // CHECK: [[T0:%.*]] = function_ref @$S10addressors6CArrayVyxSiciau : // CHECK: [[T1:%.*]] = apply [[T0]]<(Int32) -> Int32>({{%.*}}, [[WRITE]]) // CHECK: [[T2:%.*]] = struct_extract [[T1]] : $UnsafeMutablePointer<(Int32) -> Int32>, #UnsafeMutablePointer._rawValue // CHECK: [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*@callee_guaranteed (@in_guaranteed Int32) -> @out Int32 // CHECK: [[ACCESS:%.*]] = begin_access [modify] [unsafe] [[T3]] : $*@callee_guaranteed (@in_guaranteed Int32) -> @out Int32 // CHECK: store {{%.*}} to [[ACCESS]] : array[0] = id_int // CHECK: [[READ:%.*]] = begin_access [read] [static] [[ARRAY]] : $*CArray<(Int32) -> Int32> // CHECK: [[T0:%.*]] = load [[READ]] // CHECK: [[T1:%.*]] = function_ref @$S10addressors6CArrayVyxSicilu : // CHECK: [[T2:%.*]] = apply [[T1]]<(Int32) -> Int32>({{%.*}}, [[T0]]) // CHECK: [[T3:%.*]] = struct_extract [[T2]] : $UnsafePointer<(Int32) -> Int32>, #UnsafePointer._rawValue // CHECK: [[T4:%.*]] = pointer_to_address [[T3]] : $Builtin.RawPointer to [strict] $*@callee_guaranteed (@in_guaranteed Int32) -> @out Int32 // CHECK: [[ACCESS:%.*]] = begin_access [read] [unsafe] [[T4]] : $*@callee_guaranteed (@in_guaranteed Int32) -> @out Int32 // CHECK: [[T5:%.*]] = load [[ACCESS]] return array[1](5) } // rdar://17270560, redux struct D : Subscriptable { subscript(i: Int32) -> Int32 { get { return i } unsafeMutableAddress { return someValidPointer() } } } // Setter. // SILGEN-LABEL: sil hidden [transparent] @$S10addressors1DVys5Int32VAEcis // SILGEN: bb0([[VALUE:%.*]] : @trivial $Int32, [[I:%.*]] : @trivial $Int32, [[SELF:%.*]] : @trivial $*D): // SILGEN: debug_value [[VALUE]] : $Int32 // SILGEN: debug_value [[I]] : $Int32 // SILGEN: debug_value_addr [[SELF]] // SILGEN: [[ACCESS:%.*]] = begin_access [modify] [unknown] [[SELF]] : $*D // SILGEN: [[T0:%.*]] = function_ref @$S10addressors1DVys5Int32VAEciau{{.*}} // SILGEN: [[PTR:%.*]] = apply [[T0]]([[I]], [[ACCESS]]) // SILGEN: [[T0:%.*]] = struct_extract [[PTR]] : $UnsafeMutablePointer<Int32>, // SILGEN: [[ADDR:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*Int32 // SILGEN: [[ACCESS:%.*]] = begin_access [modify] [unsafe] [[ADDR]] : $*Int32 // SILGEN: assign [[VALUE]] to [[ACCESS]] : $*Int32 // SILGEN-LABEL: sil hidden [transparent] @$S10addressors1DVys5Int32VAEciM // SILGEN: bb0([[I:%.*]] : @trivial $Int32, [[SELF:%.*]] : @trivial $*D): // SILGEN: [[SELF_ACCESS:%.*]] = begin_access [modify] [unknown] [[SELF]] // SILGEN: [[T0:%.*]] = function_ref @$S10addressors1DVys5Int32VAEciau // SILGEN: [[PTR:%.*]] = apply [[T0]]([[I]], [[SELF_ACCESS]]) // SILGEN: [[ADDR_TMP:%.*]] = struct_extract [[PTR]] : $UnsafeMutablePointer<Int32>, // SILGEN: [[ADDR:%.*]] = pointer_to_address [[ADDR_TMP]] // SILGEN: [[ACCESS:%.*]] = begin_access [modify] [unsafe] [[ADDR]] // SILGEN: yield [[ACCESS]] // SILGEN: end_access [[ACCESS]] func make_int() -> Int32 { return 0 } func take_int_inout(_ value: inout Int32) {} // CHECK-LABEL: sil hidden @$S10addressors6test_dys5Int32VAA1DVzF : $@convention(thin) (@inout D) -> Int32 // CHECK: bb0([[ARRAY:%.*]] : $*D): func test_d(_ array: inout D) -> Int32 { // CHECK: [[T0:%.*]] = function_ref @$S10addressors8make_ints5Int32VyF // CHECK: [[V:%.*]] = apply [[T0]]() // CHECK: [[WRITE:%.*]] = begin_access [modify] [static] [[ARRAY]] : $*D // CHECK: [[T0:%.*]] = function_ref @$S10addressors1DVys5Int32VAEciau // CHECK: [[T1:%.*]] = apply [[T0]]({{%.*}}, [[WRITE]]) // CHECK: [[T2:%.*]] = struct_extract [[T1]] : $UnsafeMutablePointer<Int32>, // CHECK: [[ADDR:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*Int32 // CHECK: [[ACCESS:%.*]] = begin_access [modify] [unsafe] [[ADDR]] : $*Int32 // CHECK: store [[V]] to [[ACCESS]] : $*Int32 array[0] = make_int() // CHECK: [[WRITE:%.*]] = begin_access [modify] [static] [[ARRAY]] : $*D // CHECK: [[T0:%.*]] = function_ref @$S10addressors1DVys5Int32VAEciau // CHECK: [[T1:%.*]] = apply [[T0]]({{%.*}}, [[WRITE]]) // CHECK: [[T2:%.*]] = struct_extract [[T1]] : $UnsafeMutablePointer<Int32>, // CHECK: [[ADDR:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*Int32 // CHECK: [[ACCESS:%.*]] = begin_access [modify] [unsafe] [[ADDR]] : $*Int32 // CHECK: [[FN:%.*]] = function_ref @$S10addressors14take_int_inoutyys5Int32VzF // CHECK: apply [[FN]]([[ACCESS]]) take_int_inout(&array[1]) // CHECK: [[READ:%.*]] = begin_access [read] [static] [[ARRAY]] : $*D // CHECK: [[T0:%.*]] = load [[READ]] // CHECK: [[T1:%.*]] = function_ref @$S10addressors1DVys5Int32VAEcig // CHECK: [[T2:%.*]] = apply [[T1]]({{%.*}}, [[T0]]) // CHECK: return [[T2]] return array[2] } struct E { var value: Int32 { unsafeAddress { return someValidPointer() } nonmutating unsafeMutableAddress { return someValidPointer() } } } // CHECK-LABEL: sil hidden @$S10addressors6test_eyyAA1EVF // CHECK: bb0([[E:%.*]] : $E): // CHECK: [[T0:%.*]] = function_ref @$S10addressors1EV5values5Int32Vvau // CHECK: [[T1:%.*]] = apply [[T0]]([[E]]) // CHECK: [[T2:%.*]] = struct_extract [[T1]] // CHECK: [[T3:%.*]] = pointer_to_address [[T2]] // CHECK: [[ACCESS:%.*]] = begin_access [modify] [unsafe] [[T3]] : $*Int32 // CHECK: store {{%.*}} to [[ACCESS]] : $*Int32 func test_e(_ e: E) { e.value = 0 } class F { var data: UnsafeMutablePointer<Int32> = UnsafeMutablePointer.allocate(capacity: 100) final var value: Int32 { addressWithNativeOwner { return (UnsafePointer(data), Builtin.castToNativeObject(self)) } mutableAddressWithNativeOwner { return (data, Builtin.castToNativeObject(self)) } } } // CHECK-LABEL: sil hidden @$S10addressors1FC5values5Int32Vvlo : $@convention(method) (@guaranteed F) -> (UnsafePointer<Int32>, @owned Builtin.NativeObject) { // CHECK-LABEL: sil hidden @$S10addressors1FC5values5Int32Vvao : $@convention(method) (@guaranteed F) -> (UnsafeMutablePointer<Int32>, @owned Builtin.NativeObject) { func test_f0(_ f: F) -> Int32 { return f.value } // CHECK-LABEL: sil hidden @$S10addressors7test_f0ys5Int32VAA1FCF : $@convention(thin) (@guaranteed F) -> Int32 { // CHECK: bb0([[SELF:%0]] : $F): // CHECK: [[ADDRESSOR:%.*]] = function_ref @$S10addressors1FC5values5Int32Vvlo : $@convention(method) (@guaranteed F) -> (UnsafePointer<Int32>, @owned Builtin.NativeObject) // CHECK: [[T0:%.*]] = apply [[ADDRESSOR]]([[SELF]]) // CHECK: [[PTR:%.*]] = tuple_extract [[T0]] : $(UnsafePointer<Int32>, Builtin.NativeObject), 0 // CHECK: [[OWNER:%.*]] = tuple_extract [[T0]] : $(UnsafePointer<Int32>, Builtin.NativeObject), 1 // CHECK: [[T0:%.*]] = struct_extract [[PTR]] // CHECK: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*Int32 // CHECK: [[T2:%.*]] = mark_dependence [[T1]] : $*Int32 on [[OWNER]] : $Builtin.NativeObject // CHECK: [[ACCESS:%.*]] = begin_access [read] [unsafe] [[T2]] : $*Int32 // CHECK: [[VALUE:%.*]] = load [[ACCESS]] : $*Int32 // CHECK: strong_release [[OWNER]] : $Builtin.NativeObject // CHECK-NOT: strong_release [[SELF]] : $F // CHECK: return [[VALUE]] : $Int32 func test_f1(_ f: F) { f.value = 14 } // CHECK-LABEL: sil hidden @$S10addressors7test_f1yyAA1FCF : $@convention(thin) (@guaranteed F) -> () { // CHECK: bb0([[SELF:%0]] : $F): // CHECK: [[T0:%.*]] = integer_literal $Builtin.Int32, 14 // CHECK: [[VALUE:%.*]] = struct $Int32 ([[T0]] : $Builtin.Int32) // CHECK: [[ADDRESSOR:%.*]] = function_ref @$S10addressors1FC5values5Int32Vvao : $@convention(method) (@guaranteed F) -> (UnsafeMutablePointer<Int32>, @owned Builtin.NativeObject) // CHECK: [[T0:%.*]] = apply [[ADDRESSOR]]([[SELF]]) // CHECK: [[PTR:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Builtin.NativeObject), 0 // CHECK: [[OWNER:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Builtin.NativeObject), 1 // CHECK: [[T0:%.*]] = struct_extract [[PTR]] // CHECK: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*Int32 // CHECK: [[T2:%.*]] = mark_dependence [[T1]] : $*Int32 on [[OWNER]] : $Builtin.NativeObject // CHECK: [[ACCESS:%.*]] = begin_access [modify] [unsafe] [[T2]] : $*Int32 // CHECK: store [[VALUE]] to [[ACCESS]] : $*Int32 // CHECK: strong_release [[OWNER]] : $Builtin.NativeObject // CHECK-NOT: strong_release [[SELF]] : $F class G { var data: UnsafeMutablePointer<Int32> = UnsafeMutablePointer.allocate(capacity: 100) var value: Int32 { addressWithNativeOwner { return (UnsafePointer(data), Builtin.castToNativeObject(self)) } mutableAddressWithNativeOwner { return (data, Builtin.castToNativeObject(self)) } } } // CHECK-LABEL: sil hidden [transparent] @$S10addressors1GC5values5Int32Vvg : $@convention(method) (@guaranteed G) -> Int32 { // CHECK: bb0([[SELF:%0]] : $G): // CHECK: [[ADDRESSOR:%.*]] = function_ref @$S10addressors1GC5values5Int32Vvlo : $@convention(method) (@guaranteed G) -> (UnsafePointer<Int32>, @owned Builtin.NativeObject) // CHECK: [[T0:%.*]] = apply [[ADDRESSOR]]([[SELF]]) // CHECK: [[PTR:%.*]] = tuple_extract [[T0]] : $(UnsafePointer<Int32>, Builtin.NativeObject), 0 // CHECK: [[OWNER:%.*]] = tuple_extract [[T0]] : $(UnsafePointer<Int32>, Builtin.NativeObject), 1 // CHECK: [[T0:%.*]] = struct_extract [[PTR]] // CHECK: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*Int32 // CHECK: [[T2:%.*]] = mark_dependence [[T1]] : $*Int32 on [[OWNER]] : $Builtin.NativeObject // CHECK: [[ACCESS:%.*]] = begin_access [read] [unsafe] [[T2]] : $*Int32 // CHECK: [[VALUE:%.*]] = load [[ACCESS]] : $*Int32 // CHECK: strong_release [[OWNER]] : $Builtin.NativeObject // CHECK: return [[VALUE]] : $Int32 // CHECK-LABEL: sil hidden [transparent] @$S10addressors1GC5values5Int32Vvs : $@convention(method) (Int32, @guaranteed G) -> () { // CHECK: bb0([[VALUE:%0]] : $Int32, [[SELF:%1]] : $G): // CHECK: [[ADDRESSOR:%.*]] = function_ref @$S10addressors1GC5values5Int32Vvao : $@convention(method) (@guaranteed G) -> (UnsafeMutablePointer<Int32>, @owned Builtin.NativeObject) // CHECK: [[T0:%.*]] = apply [[ADDRESSOR]]([[SELF]]) // CHECK: [[PTR:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Builtin.NativeObject), 0 // CHECK: [[OWNER:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Builtin.NativeObject), 1 // CHECK: [[T0:%.*]] = struct_extract [[PTR]] // CHECK: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*Int32 // CHECK: [[T2:%.*]] = mark_dependence [[T1]] : $*Int32 on [[OWNER]] : $Builtin.NativeObject // CHECK: [[ACCESS:%.*]] = begin_access [modify] [unsafe] [[T2]] : $*Int32 // CHECK: store [[VALUE]] to [[ACCESS]] : $*Int32 // CHECK: strong_release [[OWNER]] : $Builtin.NativeObject // CHECK-LABEL: sil hidden [transparent] @$S10addressors1GC5values5Int32VvM : $@yield_once @convention(method) (@guaranteed G) -> @yields @inout Int32 { // CHECK: bb0([[SELF:%0]] : $G): // Call the addressor. // CHECK: [[ADDRESSOR:%.*]] = function_ref @$S10addressors1GC5values5Int32Vvao : $@convention(method) (@guaranteed G) -> (UnsafeMutablePointer<Int32>, @owned Builtin.NativeObject) // CHECK: [[T0:%.*]] = apply [[ADDRESSOR]]([[SELF]]) // CHECK: [[T1:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Builtin.NativeObject), 0 // CHECK: [[OWNER:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Builtin.NativeObject), 1 // Get the address. // CHECK: [[PTR:%.*]] = struct_extract [[T1]] : $UnsafeMutablePointer<Int32>, #UnsafeMutablePointer._rawValue // CHECK: [[ADDR_TMP:%.*]] = pointer_to_address [[PTR]] // CHECK: [[ADDR:%.*]] = mark_dependence [[ADDR_TMP]] : $*Int32 on [[OWNER]] // Yield. // CHECK: [[ACCESS:%.*]] = begin_access [modify] [unsafe] [[ADDR]] : $*Int32 // CHECK: yield [[ACCESS]] : $*Int32, resume bb1, unwind bb2 // CHECK: end_access [[ACCESS]] // Clean up. // CHECK: strong_release [[OWNER]] : $Builtin.NativeObject class Base { var data: UnsafeMutablePointer<Int32> = UnsafeMutablePointer.allocate(capacity: 100) var value: Int32 { addressWithNativeOwner { return (UnsafePointer(data), Builtin.castToNativeObject(self)) } mutableAddressWithNativeOwner { return (data, Builtin.castToNativeObject(self)) } } } class Sub : Base { override var value: Int32 { addressWithNativeOwner { return (UnsafePointer(data), Builtin.castToNativeObject(self)) } mutableAddressWithNativeOwner { return (data, Builtin.castToNativeObject(self)) } } } // Make sure addressors don't get vtable entries. // CHECK-LABEL: sil_vtable Base { // CHECK-NEXT: #Base.data!getter.1: (Base) -> () -> UnsafeMutablePointer<Int32> : @$S10addressors4BaseC4dataSpys5Int32VGvg // CHECK-NEXT: #Base.data!setter.1: (Base) -> (UnsafeMutablePointer<Int32>) -> () : @$S10addressors4BaseC4dataSpys5Int32VGvs // CHECK-NEXT: #Base.data!modify.1: (Base) -> () -> () : @$S10addressors4BaseC4dataSpys5Int32VGvM // CHECK-NEXT: #Base.value!getter.1: (Base) -> () -> Int32 : @$S10addressors4BaseC5values5Int32Vvg // CHECK-NEXT: #Base.value!setter.1: (Base) -> (Int32) -> () : @$S10addressors4BaseC5values5Int32Vvs // CHECK-NEXT: #Base.value!modify.1: (Base) -> () -> () : @$S10addressors4BaseC5values5Int32VvM // CHECK-NEXT: #Base.init!initializer.1: (Base.Type) -> () -> Base : @$S10addressors4BaseCACycfc // CHECK-NEXT: #Base.deinit!deallocator.1: @$S10addressors4BaseCfD // CHECK-NEXT: } // CHECK-LABEL: sil_vtable Sub { // CHECK-NEXT: #Base.data!getter.1: (Base) -> () -> UnsafeMutablePointer<Int32> : @$S10addressors4BaseC4dataSpys5Int32VGvg // CHECK-NEXT: #Base.data!setter.1: (Base) -> (UnsafeMutablePointer<Int32>) -> () : @$S10addressors4BaseC4dataSpys5Int32VGvs // CHECK-NEXT: #Base.data!modify.1: (Base) -> () -> () : @$S10addressors4BaseC4dataSpys5Int32VGvM // CHECK-NEXT: #Base.value!getter.1: (Base) -> () -> Int32 : @$S10addressors3SubC5values5Int32Vvg // CHECK-NEXT: #Base.value!setter.1: (Base) -> (Int32) -> () : @$S10addressors3SubC5values5Int32Vvs // CHECK-NEXT: #Base.value!modify.1: (Base) -> () -> () : @$S10addressors3SubC5values5Int32VvM // CHECK-NEXT: #Base.init!initializer.1: (Base.Type) -> () -> Base : @$S10addressors3SubCACycfc // CHECK-NEXT: #Sub.deinit!deallocator.1: @$S10addressors3SubCfD // CHECK-NEXT: }
apache-2.0
89e8771a151e9723bab3dd79126e1528
51.087356
181
0.617839
3.241024
false
false
false
false
sishenyihuba/Weibo
Weibo/05-Tools/Global/Global.swift
1
386
// // Global.swift // Weibo // // Created by daixianglong on 2017/1/11. // Copyright © 2017年 Dale. All rights reserved. // let app_key = "2328961873" let secret_key = "0b8942f34d2bfc47cf2038c5156ebbae" let callback_url = "http://www.sina.com.cn" let picDidPickNoti = "picDidPickNoti" let picDidDeleteNoti = "picDidDeleteNoti" let picBrowserShowNoti = "picBrowserShowNoti"
mit
fe78a3276bfe6b16be2103a875a08a28
18.15
51
0.72846
2.623288
false
false
false
false
NordicSemiconductor/IOS-nRF-Toolbox
nRF Toolbox/Utilities/CharacteristicReader.swift
1
8979
/* * Copyright (c) 2020, 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 Foundation struct Nibble { var first : UInt8 var second : UInt8 } enum ReservedSFloatValues : Int16 { case positiveInfinity = 0x07FE case nan = 0x07FF case nres = 0x0800 case reserved = 0x0801 case negativeInfinity = 0x0802 static let firstReservedValue = ReservedSFloatValues.positiveInfinity } enum ReservedFloatValues : UInt32 { case positiveInfinity = 0x007FFFFE case nan = 0x007FFFFF case nres = 0x00800000 case reserved = 0x00800001 case negativeInfinity = 0x00800002 static let firstReservedValue = ReservedFloatValues.positiveInfinity } extension Double { static var reservedValues: [Double] { [.infinity, .nan, .nan, .nan, -.infinity] } } struct CharacteristicReader { static func readUInt8Value(ptr aPointer : inout UnsafeMutablePointer<UInt8>) -> UInt8 { let val = aPointer.pointee aPointer = aPointer.successor() return val } static func readSInt8Value(ptr aPointer : UnsafeMutablePointer<UInt8>) -> Int8 { Int8(aPointer.successor().pointee) } static func readUInt16Value(ptr aPointer : inout UnsafeMutablePointer<UInt8>) -> UInt16 { let anUInt16Pointer = UnsafeMutablePointer<UInt16>(OpaquePointer(aPointer)) let val = CFSwapInt16LittleToHost(anUInt16Pointer.pointee) aPointer = aPointer.advanced(by: 2) return val } static func readSInt16Value(ptr aPointer : inout UnsafeMutablePointer<UInt8>) -> Int16 { let anInt16Pointer = UnsafeMutablePointer<Int16>(OpaquePointer(aPointer)) let val = CFSwapInt16LittleToHost(UnsafeMutablePointer<UInt16>(OpaquePointer(anInt16Pointer)).pointee) aPointer = aPointer.advanced(by: 2) return Int16(val) } static func readUInt32Value(ptr aPointer : inout UnsafeMutablePointer<UInt8>) -> UInt32 { let anInt32Pointer = UnsafeMutablePointer<UInt32>(OpaquePointer(aPointer)) let val = CFSwapInt32LittleToHost(UnsafeMutablePointer<UInt32>(OpaquePointer(anInt32Pointer)).pointee) aPointer = aPointer.advanced(by: 4) return UInt32(val) } static func readSInt32Value(ptr aPointer : inout UnsafeMutablePointer<UInt8>) -> Int32 { let anInt32Pointer = UnsafeMutablePointer<UInt32>(OpaquePointer(aPointer)) let val = CFSwapInt32LittleToHost(UnsafeMutablePointer<UInt32>(OpaquePointer(anInt32Pointer)).pointee) aPointer = aPointer.advanced(by: 4) return Int32(val) } static func readSFloat(_ data: Data, offset: Int) throws -> Float32 { let tempData: UInt16 = try data.read(fromOffset: offset) var mantissa = Int16(tempData & 0x0FFF) var exponent = Int8(tempData >> 12) if exponent >= 0x0008 { exponent = -( (0x000F + 1) - exponent ) } var output : Float32 = 0 if mantissa >= ReservedSFloatValues.firstReservedValue.rawValue && mantissa <= ReservedSFloatValues.negativeInfinity.rawValue { output = Float32(Double.reservedValues[Int(mantissa - ReservedSFloatValues.firstReservedValue.rawValue)]) } else { if mantissa > 0x0800 { mantissa = -((0x0FFF + 1) - mantissa) } let magnitude = pow(10.0, Double(exponent)) output = Float32(mantissa) * Float32(magnitude) } return output } static func readSFloatValue(ptr aPointer : inout UnsafeMutablePointer<UInt8>) -> Float32 { let tempData = CFSwapInt16LittleToHost(UnsafeMutablePointer<UInt16>(OpaquePointer(aPointer)).pointee) var mantissa = Int16(tempData & 0x0FFF) var exponent = Int8(tempData >> 12) if exponent >= 0x0008 { exponent = -((0x000F + 1) - exponent) } var output : Float32 = 0 if mantissa >= ReservedSFloatValues.firstReservedValue.rawValue && mantissa <= ReservedSFloatValues.negativeInfinity.rawValue { output = Float32(Double.reservedValues[Int(mantissa - ReservedSFloatValues.firstReservedValue.rawValue)]) } else { if mantissa > 0x0800 { mantissa = -((0x0FFF + 1) - mantissa) } let magnitude = pow(10.0, Double(exponent)) output = Float32(mantissa) * Float32(magnitude) } aPointer = aPointer.advanced(by: 2) return output } static func readFloatValue(ptr aPointer : inout UnsafeMutablePointer<UInt8>) -> Float32 { let tempData = CFSwapInt32LittleToHost(UnsafeMutablePointer<UInt32>(OpaquePointer(aPointer)).pointee) var mantissa = Int32(tempData & 0x00FFFFFF) let exponent = Int8(bitPattern: UInt8(tempData >> 24)) var output : Float32 = 0 if mantissa >= Int32(ReservedFloatValues.firstReservedValue.rawValue) && mantissa <= Int32(ReservedFloatValues.negativeInfinity.rawValue) { output = Float32(Double.reservedValues[Int(mantissa - Int32(ReservedSFloatValues.firstReservedValue.rawValue))]) } else { if mantissa >= 0x800000 { mantissa = -((0xFFFFFF + 1) - mantissa) } let magnitude = pow(10.0, Double(exponent)) output = Float32(mantissa) * Float32(magnitude) } aPointer = aPointer.advanced(by: 4) return output } static func readDateTime(ptr aPointer : inout UnsafeMutablePointer<UInt8>) -> Date { let year = CharacteristicReader.readUInt16Value(ptr: &aPointer) let month = CharacteristicReader.readUInt8Value(ptr: &aPointer) let day = CharacteristicReader.readUInt8Value(ptr: &aPointer) var hour = CharacteristicReader.readUInt8Value(ptr: &aPointer) let min = CharacteristicReader.readUInt8Value(ptr: &aPointer) let sec = CharacteristicReader.readUInt8Value(ptr: &aPointer) let dateFormatter = DateFormatter() var dateString : String if using12hClockFormat() == true { var merediumString :String = "am" if (hour > 12) { hour = hour - 12; merediumString = "pm" } dateString = String(format: "%d %d %d %d %d %d %@", year, month, day, hour, min, sec, merediumString) dateFormatter.dateFormat = "yyyy MM dd HH mm ss a" }else{ dateString = String(format: "%d %d %d %d %d %d", year, month, day, hour, min, sec) dateFormatter.dateFormat = "yyyy MM dd HH mm ss" } return dateFormatter.date(from: dateString)! } static func readNibble(ptr aPointer : inout UnsafeMutablePointer<UInt8>) -> Nibble { let value = CharacteristicReader.readUInt8Value(ptr: &aPointer) let nibble = Nibble(first: value & 0xF, second: value >> 4) return nibble } static func using12hClockFormat() -> Bool { let formatter = DateFormatter() formatter.locale = Locale.current formatter.dateStyle = .none formatter.timeStyle = .short let dateString = formatter.string(from: Date()) let amRange = dateString.range(of: formatter.amSymbol) let pmRange = dateString.range(of: formatter.pmSymbol) return !(pmRange == nil && amRange == nil) } }
bsd-3-clause
a7e67bc4232d117f3d8574b19ab91f88
40
147
0.663994
4.350291
false
false
false
false
YauheniYarotski/APOD
APOD/ApodTitleView.swift
1
1996
// // ApodTitleView.swift // APOD // // Created by Yauheni Yarotski on 6/22/16. // Copyright © 2016 Yauheni_Yarotski. All rights reserved. // import UIKit @objc protocol ApodTitleViewDelegate: class { func apodTitlePressed(apodTitleView: ApodTitleView) @objc optional func apodTitlePan(apodTitleView: ApodTitleView, pan: UIPanGestureRecognizer) } class ApodTitleView: UIView { weak var delegate: ApodTitleViewDelegate? let title = UILabel() let likesView = LikesView() //TODO: left for blur effect in future // let blurEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .dark)) required override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setup() { setupTap() //only apply the blur if the user hasn't disabled transparency effects // if UIAccessibilityIsReduceTransparencyEnabled() { // backgroundColor = UIColor.black // } else { // backgroundColor = UIColor.clear // addSubview(blurEffectView) // blurEffectView.snp.makeConstraints({ (make) in // make.edges.equalToSuperview() // }) // } likesView.translatesAutoresizingMaskIntoConstraints = false addSubview(likesView) likesView.snp.makeConstraints { (make) in make.leading.equalToSuperview().offset(8) make.top.bottom.equalToSuperview() make.width.equalTo(46) } title.translatesAutoresizingMaskIntoConstraints = false title.textColor = UIColor.white title.textAlignment = .center title.numberOfLines = 2 addSubview(title) title.snp.makeConstraints { (make) in make.leading.equalTo(likesView.snp.trailing) make.top.bottom.equalToSuperview() make.trailing.equalToSuperview().offset(-3) } } } extension ApodTitleView: Gestureable { func wasTap() { delegate?.apodTitlePressed(apodTitleView: self) } func wasPan(_ pan: UIPanGestureRecognizer) { delegate?.apodTitlePan?(apodTitleView: self, pan: pan) } }
mit
f54cc400e8548b6f0b4cf182a1dabe83
24.576923
92
0.734336
3.601083
false
false
false
false
CreazyShadow/SimpleDemo
SimpleApp/SimpleApp/Swift/UserListViewController.swift
1
1085
// // UserListViewController.swift // SimpleApp // // Created by 邬勇鹏 on 2018/5/21. // Copyright © 2018年 wuyp. All rights reserved. // import UIKit import Then import SnapKit class UserListViewController: BaseViewController { lazy var table: UITableView = { let table = UITableView(frame: self.view.bounds, style: .grouped) table.delegate = self table.dataSource = self return table }() override func viewDidLoad() { super.viewDidLoad() } } extension UserListViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell: UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: "cell") if cell == nil { cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cell") } return cell! } }
apache-2.0
e26249b077d027466c154c988fc5bf0e
23.454545
100
0.642193
4.981481
false
false
false
false
huang303513/iOS-Study-Demo
[转]Swift版的FMDB和CoreData学习_转/SwiftFMDB/FMDBDemoViewController.swift
28
4007
// // FMDBDemoViewController.swift // SwiftFMDBDemo // // Created by Limin Du on 11/18/14. // Copyright (c) 2014 GoldenFire.Do. All rights reserved. // import Foundation import UIKit class FMDBDemoViewController : UITableViewController, UITableViewDataSource, UITableViewDelegate, GADInterstitialDelegate { let dal = EntryDAL() var data=[Entry]() var interstitial:GADInterstitial? override func viewDidLoad() { let addButton = UIBarButtonItem(title: "Add", style: .Plain, target: self, action: "addEntry") self.navigationItem.rightBarButtonItem = addButton self.tableView.delegate = self self.tableView.dataSource = self interstitial = createAndLoadInterstitial() NSNotificationCenter.defaultCenter().addObserver(self, selector: "displayInterstitial", name: "kDisplayInterstitialNotification", object: nil) } override func viewDidAppear(animated: Bool) { data = dal.getAllEntries() self.tableView.reloadData() } func addEntry() { println("in add Entry") let addVC = AddEntryViewController() let navVC = UINavigationController(rootViewController: addVC) let backButton = UIBarButtonItem(title: "Back", style: .Plain, target: self, action: "back") //backButton.tintColor = UIColor.redColor() addVC.navigationItem.setLeftBarButtonItem(backButton, animated: true) self.presentViewController(navVC, animated: true, completion: nil) } func back() { self.dismissViewControllerAnimated(true, completion: nil) } //table view data source override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return data.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let index = indexPath.row var cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: nil) cell.textLabel?.text = data[index].name cell.detailTextLabel?.text = data[index].description return cell } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { let e = data[indexPath.row] if dal.deleteEntry(e) { data.removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } } //Interstitial func func createAndLoadInterstitial()->GADInterstitial { var interstitial = GADInterstitial() interstitial.delegate = self interstitial.adUnitID = "ca-app-pub-6938332798224330/6206234808" interstitial.loadRequest(GADRequest()) return interstitial } //Interstitial delegate func interstitial(ad: GADInterstitial!, didFailToReceiveAdWithError error: GADRequestError!) { println("interstitialDidFailToReceiveAdWithError:\(error.localizedDescription)") interstitial = createAndLoadInterstitial() } func interstitialWillDismissScreen(ad: GADInterstitial!) { interstitial = createAndLoadInterstitial() } /*func interstitialDidDismissScreen(ad: GADInterstitial!) { println("interstitialDidDismissScreen") } func interstitialWillLeaveApplication(ad: GADInterstitial!) { println("interstitialWillLeaveApplication") } func interstitialWillPresentScreen(ad: GADInterstitial!) { println("interstitialWillPresentScreen") }*/ func displayInterstitial() { if let isReady = interstitial?.isReady { interstitial?.presentFromRootViewController(self) } } }
apache-2.0
d7f135fea1a5d9ba9f5208cf62f20f32
33.852174
157
0.680809
5.58078
false
false
false
false
Rahulclaritaz/rahul
ixprez/ixprez/XPHumburgerMenuViewController.swift
1
11866
// // XPHumburgerMenuViewController.swift // ixprez // // Created by Claritaz Techlabs on 12/06/17. // Copyright © 2017 Claritaz Techlabs. All rights reserved. // import UIKit class XPHumburgerMenuViewController: UIViewController { var customActivityView : UIActivityViewController? var shareTextField = UITextField () @IBOutlet weak var humburgerMenuTableView : UITableView? @IBOutlet weak var humburgerMenuUserProfile : UIImageView? @IBOutlet weak var humburgerMenuUserName : UILabel? let dashBoardCommonService = XPWebService() let userPrifileURL = URLDirectory.UserProfile() let getMenuHeartCountWebService = PrivateWebService() let menuHeartScreenCount = URLDirectory.Setting() var dashboardCountData = [String : AnyObject]() var heartButtonBadgeCount = Int() var userEmail = String () var imageGesture = UITapGestureRecognizer() var profileImageURL: String! override func awakeFromNib() { self.getUserProfile() } override func viewDidLoad() { super.viewDidLoad() imageGesture = UITapGestureRecognizer(target: self, action: #selector(gotoSettingView(gesture:))) userEmail = UserDefaults.standard.value(forKey: "emailAddress") as! String // humburgerMenuUserName?.text = UserDefaults.standard.value(forKey: "userName") as? String // self.menuXpressionCount() let imageLogo = UIImage (named: "DashboardTitleImage") let imageView = UIImageView(image : imageLogo) self.navigationItem.titleView = imageView navigationController?.navigationBar.barTintColor = UIColor(red: 103.0/255.0, green: 68.0/255.0, blue: 240.0/255.0, alpha: 1.0) navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white] humburgerMenuUserProfile?.layer.masksToBounds = true humburgerMenuUserProfile?.layer.cornerRadius = (self.humburgerMenuUserProfile?.frame.size.width)!/2 humburgerMenuUserProfile?.clipsToBounds = true humburgerMenuUserProfile?.isUserInteractionEnabled = true humburgerMenuUserProfile?.addGestureRecognizer(imageGesture) // Do any additional setup after loading the view. } func gotoSettingView(gesture:UIGestureRecognizer) { let settingView = storyboard?.instantiateViewController(withIdentifier: "XPSettingsViewController") as! XPSettingsViewController settingView.isFromMenu = true let navigation = UINavigationController.init(rootViewController: settingView) self.navigationController?.present(navigation, animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(_ animated: Bool) { // self.navigationItem.leftBarButtonItem?.badgeValue = String(self.heartButtonBadgeCount) self.getUserProfile() self.menuXpressionCount() // self.humburgerMenuTableView?.reloadData() } // This method will call when clik on the trending button func menuXpressionCount() { let parameter = ["user_email": UserDefaults.standard.value(forKey: "emailAddress"), "PreviousCount" : 0 ] getMenuHeartCountWebService.getPrivateData(urlString: menuHeartScreenCount.getPrivateData(), dicData: parameter) { (response, error) in DispatchQueue.main.async { print("the dashboard count is \(response)") self.dashboardCountData = response["data"] as! [String : AnyObject] self.heartButtonBadgeCount = self.dashboardCountData["TotalNumberofrecords"] as! Int self.navigationItem.leftBarButtonItem?.badgeValue = String(self.heartButtonBadgeCount) print("The dashboard heart menu expression count is \(self.heartButtonBadgeCount)") } } } // This method will logout the application @IBAction func signOutButton (sender : Any) { NSObject.cancelPreviousPerformRequests(withTarget: self) exit(0) // UserDefaults.standard.removeObject(forKey: "emailAddress") // UserDefaults.standard.synchronize() } // This method will navigate to the setting page @IBAction func settingButton (sender : Any) { let storyboard = self.storyboard?.instantiateViewController(withIdentifier: "XPSettingsViewController") as! XPSettingsViewController storyboard.isFromMenu = true let navigation = UINavigationController.init(rootViewController: storyboard) self.navigationController?.present(navigation, animated: true, completion: nil) } func getUserProfile() { let parameter = [ "email_id" : userEmail] dashBoardCommonService.getUserProfileWebService(urlString: userPrifileURL.url(), dicData: parameter as NSDictionary, callback: {(userprofiledata , error) in let imageUrl : String = userprofiledata.value(forKey: "profile_image") as! String self.profileImageURL = imageUrl print(self.profileImageURL) // self.humburgerMenuUserProfile?.getImageFromUrl(imageURL) // var urlString = imageURL.replacingOccurrences(of: "/root/cpanel3-skel/public_html/Xpress", with: "http://103.235.104.118:3000") // // let url = NSURL(string: urlString) // // let session = URLSession.shared // // let taskData = session.dataTask(with: url! as URL, completionHandler: {(data,response,error) -> Void in // // if (data != nil) // { // // DispatchQueue.main.async { // // self.humburgerMenuUserProfile?.image = UIImage(data: data!) // // } // } // }) // // // taskData.resume() }) } /* // 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. } */ } // MARK: UITableview datasource Method extension XPHumburgerMenuViewController : UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 5 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 60 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellIdentifier = "XPHumburgerMenuTableViewCell" let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! XPHumburgerMenuTableViewCell switch indexPath.row { case 0: cell.menuLabel?.text = "My Uploads" return cell case 1: cell.menuLabel?.text = "Contacts" return cell case 2: cell.menuLabel?.text = "Private Xpressions" return cell case 3: cell.menuLabel?.text = "Share ixprez" return cell case 4: cell.menuLabel?.text = "About" return cell default: return cell } } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 165 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let cellIdentifierDashboard = "XPMenuProfileHeaderTableViewCell" let cellMenu : XPMenuProfileHeaderTableViewCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifierDashboard) as! XPMenuProfileHeaderTableViewCell if (profileImageURL == nil) { cellMenu.profileImage?.backgroundColor = UIColor.purple } else { cellMenu.profileImage?.getImageFromUrl(profileImageURL) } cellMenu.userName?.text = UserDefaults.standard.value(forKey: "userName") as? String return cellMenu.contentView } } // MARK: UITableview delegate Method extension XPHumburgerMenuViewController : UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch (indexPath.row) { case 0: let storyboard = self.storyboard?.instantiateViewController(withIdentifier: "XPMyUploadViewController") as! XPMyUploadViewController storyboard.isFromMenu = true let navigation = UINavigationController.init(rootViewController: storyboard) self.navigationController?.present(navigation, animated: true, completion: nil) // revealViewController().rightViewRevealWidth = 375 // self.present(storyboard, animated: true, completion: nil) // self.navigationController?.pushViewController(storyboard, animated: true) return case 1: let storyboard = self.storyboard?.instantiateViewController(withIdentifier: "XPContactViewController") as! XPContactViewController storyboard.isFromMenu = true let navigation = UINavigationController.init(rootViewController: storyboard) self.navigationController?.present(navigation, animated: true, completion: nil) case 2: let storyboard = self.storyboard?.instantiateViewController(withIdentifier: "IXPrivateViewController") as! IXPrivateViewController storyboard.isFromMenu = true // storyboard.userID = let navigation = UINavigationController.init(rootViewController: storyboard) self.navigationController?.present(navigation, animated: true, completion: nil) // self.navigationController?.pushViewController(storyboard, animated: true) case 3: // This will open the default activity view customActivityView = UIActivityViewController(activityItems: [shareTextField.text as! NSString], applicationActivities: nil) present(customActivityView!, animated: true, completion: nil) // let storyboard = self.storyboard?.instantiateViewController(withIdentifier: "XPShareXprezViewController") as! XPShareXprezViewController // let navigation = UINavigationController.init(rootViewController: storyboard) // self.navigationController?.present(navigation, animated: true, completion: nil) case 4: let storyboard = self.storyboard?.instantiateViewController(withIdentifier: "XPAboutViewController") as! XPAboutViewController storyboard.isFromMenu = true let navigation = UINavigationController.init(rootViewController: storyboard) self.navigationController?.present(navigation, animated: true, completion: nil) // self.navigationController?.pushViewController(storyboard, animated: true) default: let storyboard = self.storyboard?.instantiateViewController(withIdentifier: "XPMyUploadViewController") as! XPMyUploadViewController self.navigationController?.pushViewController(storyboard, animated: true) } } }
mit
992b93765c18cd521f6b3dea3613ef5b
39.357143
165
0.655373
5.356659
false
false
false
false
quran/quran-ios
Sources/QueuePlayer/AudioPlaying.swift
1
3190
// // AudioPlaying.swift // QueuePlayer // // Created by Afifi, Mohamed on 4/27/19. // Copyright © 2019 Quran.com. All rights reserved. // import Foundation struct FramePlaying { var frameIndex: Int var framePlays: Int } struct FilePlaying { let fileIndex: Int init(fileIndex: Int) { self.fileIndex = fileIndex } } struct AudioPlaying { let request: AudioRequest private(set) var filePlaying: FilePlaying private(set) var framePlaying: FramePlaying var requestPlays: Int init(request: AudioRequest, fileIndex: Int, frameIndex: Int) { self.request = request filePlaying = FilePlaying(fileIndex: fileIndex) framePlaying = FramePlaying(frameIndex: frameIndex, framePlays: 0) requestPlays = 0 } mutating func setPlaying(fileIndex: Int, frameIndex: Int) { filePlaying = FilePlaying(fileIndex: fileIndex) framePlaying.frameIndex = frameIndex } var file: AudioFile { request.files[filePlaying.fileIndex] } var frame: AudioFrame { file.frames[framePlaying.frameIndex] } func isLastPlayForCurrentFrame() -> Bool { framePlaying.framePlays + 1 >= request.frameRuns.maxRuns } func isLastRun() -> Bool { requestPlays + 1 >= request.requestRuns.maxRuns } mutating func incrementRequestPlays() { guard request.requestRuns != .indefinite else { return } requestPlays += 1 } mutating func incrementFramePlays() { guard request.frameRuns != .indefinite else { return } framePlaying.framePlays += 1 } mutating func resetFramePlays() { framePlaying.framePlays = 0 } func previousFrame() -> (fileIndex: Int, frameIndex: Int)? { // same file if framePlaying.frameIndex > 0 { return (filePlaying.fileIndex, framePlaying.frameIndex - 1) } // previous file if filePlaying.fileIndex > 0 { let previousFileIndex = filePlaying.fileIndex - 1 return (previousFileIndex, request.files[previousFileIndex].frames.count - 1) } // first frame return nil } func nextFrame() -> (fileIndex: Int, frameIndex: Int)? { // same file if framePlaying.frameIndex < file.frames.count - 1 { return (filePlaying.fileIndex, framePlaying.frameIndex + 1) } // next file if filePlaying.fileIndex < request.files.count - 1 { return (filePlaying.fileIndex + 1, 0) } // last frame return nil } var frameEndTime: TimeInterval? { if let frameEndTime = request.files[filePlaying.fileIndex].frames[framePlaying.frameIndex].endTime { return frameEndTime } guard let nextFrame = nextFrame() else { // last frame return request.endTime } if nextFrame.fileIndex == filePlaying.fileIndex { // same file return request.files[nextFrame.fileIndex].frames[nextFrame.frameIndex].startTime } // different file return nil } }
apache-2.0
e755da7fabeaede12bf701b944f7518f
25.798319
108
0.614299
4.416898
false
false
false
false
smart23033/boostcamp_iOS_bipeople
Bipeople/Bipeople/AnimatedLabel.swift
1
1748
// // AnimatedLabel.swift // SampleAnimatedLabel // // Created by 김성준 on 2017. 8. 24.. // Copyright © 2017년 김성준. All rights reserved. // import UIKit enum DecimalPoints { case zero, one var format: String { switch self { case .zero: return "%.0f" case .one: return "%.1f" } } } class AnimatedLabel: UILabel { var lastUpdate: TimeInterval = 0 var progress: TimeInterval = 0 var destinationValue: Float = 0 var totalTime: TimeInterval = 0 var timer: CADisplayLink? var decimalPoints: DecimalPoints = .one var currentValue: Float { if progress >= totalTime { return destinationValue } return (Float(progress / totalTime) * (destinationValue)) } func count(to: Float, duration: TimeInterval = 2.0) { destinationValue = to lastUpdate = Date.timeIntervalSinceReferenceDate totalTime = duration progress = 0 timer?.invalidate() timer = nil addDisplayLink() } func addDisplayLink() { timer = CADisplayLink(target: self, selector: #selector(self.updateValue(timer:))) timer?.add(to: .main, forMode: .defaultRunLoopMode) } @objc func updateValue(timer: Timer) { let now: TimeInterval = Date.timeIntervalSinceReferenceDate progress += now - lastUpdate lastUpdate = now if progress >= totalTime { self.timer?.invalidate() self.timer = nil progress = totalTime } setTextValue(value: currentValue) } func setTextValue(value: Float) { text = String(format: "%.0f", value) } }
mit
27d324270ce9ebf268c8f42c562fa4bb
23.069444
90
0.585113
4.609043
false
false
false
false
Takanu/Pelican
Sources/Pelican/API/Types/Inline/InlineQuery.swift
1
862
// // InlineQuery.swift // Pelican // // Created by Takanu Kyriako on 19/12/2017. // import Foundation /** Represents an incoming inline query. When the user sends an empty query, your bot could return some default or trending results. */ public struct InlineQuery: UpdateModel, Codable { // Unique identifier for this query. public var id: String // The sender. public var from: User // Text of the query (up to 512 characters). public var query: String // Offset of the results to be returned, is bot-controllable. public var offset: String // Sender location, only for bots that request it. public var location: Location? public init(id: String, user: User, query: String, offset: String, location: Location? = nil) { self.id = id self.from = user self.query = query self.offset = offset self.location = location } }
mit
1f0242a46379d4912ae2a36409bce273
21.102564
128
0.705336
3.576763
false
false
false
false
MChainZhou/DesignPatterns
Memo/Memo/Simple_2_加强案例/Simple_3_优化变种/JsonBankAccountOriginator.swift
1
1197
// // JsonBankAccountOriginator.swift // Memo // // Created by apple on 2017/8/31. // Copyright © 2017年 apple. All rights reserved. // import UIKit class JsonBankAccountOriginator: OriginatorProtocol { var entries = [Int:BankAccount]() var total:Float = 0 var nextID:Int = 1 func addEntry(name:String,amount:Float,time:String) { let entry = BankAccount(id: nextID, name: name, amonut: amount, time: time) self.total += amount self.nextID += 1 self.entries[nextID] = entry } //更新-存档 func createMemo() -> MemoProtocol { return JsonBankAccountMemo(originator:self) } //更新-读档 func applyMemo(memo: MemoProtocol) { if let entry = memo as? JsonBankAccountMemo { entry.apply(originator:self) } } //输出 func printEntries() { for entry in self.entries.values.sorted(by: { (b1, b2) -> Bool in return b1.id < b2.id }) { print("id:\(entry.id) 姓名:\(entry.name) 金额:\(entry.amonut) 时间:\(entry.time)") } print("--------------------------") } }
mit
72bfb6ac1cacfcd63e3f4e074a687422
22.24
88
0.551635
3.724359
false
false
false
false
fsiu/SprityBirdInSwift
SprityBirdInSwift/src/Scenes/Nodes/SKScrollingNode.swift
1
2379
// // SKScrollingNode.swift // SprityBirdInSwift // // Created by Frederick Siu on 6/6/14. // Copyright (c) 2014 Frederick Siu. All rights reserved. // import Foundation import SpriteKit class SKScrollingNode: SKSpriteNode { var scrollingSpeed: CGFloat = 0.0; class func scrollingNode(_ imageNamed: String, containerSize: CGSize) -> SKScrollingNode { let image = UIImage(named: imageNamed); let result = SKScrollingNode(color: UIColor.clear, size: CGSize(width: CGFloat(containerSize.width), height: containerSize.height)); result.scrollingSpeed = 1.0; var total:CGFloat = 0.0; while(total < CGFloat(containerSize.width) + image!.size.width) { let child = SKSpriteNode(imageNamed: imageNamed); child.size = containerSize child.anchorPoint = CGPoint.zero; child.position = CGPoint(x: total, y: 0); result.addChild(child); total+=child.size.width; } return result; } class func scrollingNode(_ imageNamed: String, containerWidth: CGFloat) -> SKScrollingNode { let image = UIImage(named: imageNamed); let result = SKScrollingNode(color: UIColor.clear, size: CGSize(width: CGFloat(containerWidth), height: image!.size.height)); result.scrollingSpeed = 1.0; var total:CGFloat = 0.0; while(total < CGFloat(containerWidth) + image!.size.width) { let child = SKSpriteNode(imageNamed: imageNamed); child.anchorPoint = CGPoint.zero; child.position = CGPoint(x: total, y: 0); result.addChild(child); total+=child.size.width; } return result; } func update(_ currentTime: TimeInterval) { let runBlock: () -> Void = { for child in self.children as! [SKSpriteNode] { child.position = CGPoint(x: child.position.x-CGFloat(self.scrollingSpeed), y: child.position.y); if(child.position.x <= -child.size.width) { let delta = child.position.x + child.size.width; child.position = CGPoint(x: CGFloat(child.size.width * CGFloat(self.children.count-1)) + delta, y: child.position.y); } } } runBlock(); } }
apache-2.0
c305430536b4cc11f1e3dbe9f77efeb1
35.6
140
0.592686
4.325455
false
false
false
false
overtake/TelegramSwift
packages/TGUIKit/Sources/MergeLists.swift
1
11979
import Foundation public protocol Identifiable { associatedtype T: Hashable var stableId: T { get } } public func mergeListsStable<T>(leftList: [T], rightList: [T]) -> ([Int], [(Int, T, Int?)]) where T: Comparable, T: Equatable, T: Identifiable { var removeIndices: [Int] = [] var insertItems: [(Int, T, Int?)] = [] var currentList = leftList var i = 0 var j = 0 while true { let left: T? = i < currentList.count ? currentList[i] : nil let right: T? = j < rightList.count ? rightList[j] : nil if let left = left, let right = right { if left == right { i += 1 j += 1 } else if left < right { removeIndices.append(i) i += 1 } else { j += 1 } } else if let _ = left { removeIndices.append(i) i += 1 } else if let _ = right { j += 1 } else { break } } for index in removeIndices.reversed() { currentList.remove(at: index) } var previousIndices: [T.T: Int] = [:] i = 0 for left in leftList { previousIndices[left.stableId] = i i += 1 } i = 0 j = 0 while true { let left: T? = i < currentList.count ? currentList[i] : nil let right: T? = j < rightList.count ? rightList[j] : nil if let left = left, let right = right { if left == right { i += 1 j += 1 } else if left > right { let previousIndex = previousIndices[right.stableId] insertItems.append((i, right, previousIndex)) currentList.insert(right, at: i) i += 1 j += 1 } else { i += 1 } } else if let _ = left { i += 1 } else if let right = right { let previousIndex = previousIndices[right.stableId] insertItems.append((i, right, previousIndex)) currentList.insert(right, at: i) i += 1 j += 1 } else { break } } assert(currentList == rightList, "currentList == rightList") return (removeIndices, insertItems) } public func mergeListsStableWithUpdates<T>(leftList: [T], rightList: [T], allUpdated: Bool = false) -> ([Int], [(Int, T, Int?)], [(Int, T, Int)]) where T: Comparable, T: Identifiable { var removeIndices: [Int] = [] var insertItems: [(Int, T, Int?)] = [] var updatedIndices: [(Int, T, Int)] = [] var currentList = leftList var i = 0 var previousIndices: [T.T: Int] = [:] for left in leftList { previousIndices[left.stableId] = i i += 1 } i = 0 var j = 0 while true { let left: T? = i < currentList.count ? currentList[i] : nil let right: T? = j < rightList.count ? rightList[j] : nil if let left = left, let right = right { if left.stableId == right.stableId && (left != right || allUpdated) { updatedIndices.append((i, right, previousIndices[left.stableId]!)) i += 1 j += 1 } else { if left == right && !allUpdated { i += 1 j += 1 } else if left < right { removeIndices.append(i) i += 1 } else if !(left > right) { removeIndices.append(i) i += 1 } else { j += 1 } } } else if let _ = left { removeIndices.append(i) i += 1 } else if let _ = right { j += 1 } else { break } } //print("remove:\n\(removeIndices)") for index in removeIndices.reversed() { currentList.remove(at: index) for i in 0 ..< updatedIndices.count { if updatedIndices[i].0 >= index { updatedIndices[i].0 -= 1 } } } /*print("\n current after removes:\n") m = 0 for right in currentList { print("\(m): \(right.stableId)") m += 1 } print("update:\n\(updatedIndices.map({ "\($0.0), \($0.1.stableId) (was \($0.2)))" }))")*/ i = 0 j = 0 var k = 0 while true { let left: T? //print("i=\(i), j=\(j), k=\(k)") if k < updatedIndices.count && updatedIndices[k].0 < i { //print("updated[k=\(k)]=\(updatedIndices[k].0)<i=\(i), k++") k += 1 } if k < updatedIndices.count { if updatedIndices[k].0 == i { left = updatedIndices[k].1 //print("override left = \(updatedIndices[k].1.stableId)") } else { left = i < currentList.count ? currentList[i] : nil } } else { left = i < currentList.count ? currentList[i] : nil } let right: T? = j < rightList.count ? rightList[j] : nil if let left = left, let right = right { if left == right { //print("\(left.stableId)==\(right.stableId)") //print("i++, j++") i += 1 j += 1 } else if left > right { //print("\(left.stableId)>\(right.stableId)") //print("insert \(right.stableId) at \(i)") //print("i++, j++") let previousIndex = previousIndices[right.stableId] insertItems.append((i, right, previousIndex)) currentList.insert(right, at: i) if k < updatedIndices.count { for l in k ..< updatedIndices.count { updatedIndices[l] = (updatedIndices[l].0 + 1, updatedIndices[l].1, updatedIndices[l].2) } } i += 1 j += 1 } else { //print("\(left.stableId)<\(right.stableId)") //print("i++") i += 1 } } else if let _ = left { //print("\(left!.stableId)>nil") //print("i++") i += 1 } else if let right = right { //print("nil<\(right.stableId)") //print("insert \(right.stableId) at \(i)") //print("i++") //print("j++") let previousIndex = previousIndices[right.stableId] insertItems.append((i, right, previousIndex)) currentList.insert(right, at: i) if k < updatedIndices.count { for l in k ..< updatedIndices.count { updatedIndices[l] = (updatedIndices[l].0 + 1, updatedIndices[l].1, updatedIndices[l].2) } } i += 1 j += 1 } else { break } } for (index, item, _) in updatedIndices { currentList[index] = item } return (removeIndices, insertItems, updatedIndices) } public func mergeListsStableWithUpdatesReversed<T>(leftList: [T], rightList: [T], allUpdated: Bool = false) -> ([Int], [(Int, T, Int?)], [(Int, T, Int)]) where T: Comparable, T: Identifiable { var removeIndices: [Int] = [] var insertItems: [(Int, T, Int?)] = [] var updatedIndices: [(Int, T, Int)] = [] #if (arch(i386) || arch(x86_64)) && os(iOS) var existingStableIds: [T.T: T] = [:] for item in leftList { if let _ = existingStableIds[item.stableId] { assertionFailure() } else { existingStableIds[item.stableId] = item } } existingStableIds.removeAll() for item in rightList { if let other = existingStableIds[item.stableId] { print("\(other) has the same stableId as \(item): \(item.stableId)") assertionFailure() } else { existingStableIds[item.stableId] = item } } #endif var currentList = leftList var i = 0 var previousIndices: [T.T: Int] = [:] for left in leftList { previousIndices[left.stableId] = i i += 1 } i = 0 var j = 0 while true { let left: T? = i < currentList.count ? currentList[i] : nil let right: T? = j < rightList.count ? rightList[j] : nil if let left = left, let right = right { if left.stableId == right.stableId && (left != right || allUpdated) { updatedIndices.append((i, right, previousIndices[left.stableId]!)) i += 1 j += 1 } else { if left == right && !allUpdated { i += 1 j += 1 } else if left > right { removeIndices.append(i) i += 1 } else if !(left < right) { removeIndices.append(i) i += 1 } else { j += 1 } } } else if let _ = left { removeIndices.append(i) i += 1 } else if let _ = right { j += 1 } else { break } } //print("remove:\n\(removeIndices)") for index in removeIndices.reversed() { currentList.remove(at: index) for i in 0 ..< updatedIndices.count { if updatedIndices[i].0 >= index { updatedIndices[i].0 -= 1 } } } i = 0 j = 0 var k = 0 while true { let left: T? if k < updatedIndices.count && updatedIndices[k].0 < i { k += 1 } if k < updatedIndices.count { if updatedIndices[k].0 == i { left = updatedIndices[k].1 } else { left = i < currentList.count ? currentList[i] : nil } } else { left = i < currentList.count ? currentList[i] : nil } let right: T? = j < rightList.count ? rightList[j] : nil if let left = left, let right = right { if left == right { i += 1 j += 1 } else if left < right { let previousIndex = previousIndices[right.stableId] insertItems.append((i, right, previousIndex)) currentList.insert(right, at: i) if k < updatedIndices.count { for l in k ..< updatedIndices.count { updatedIndices[l] = (updatedIndices[l].0 + 1, updatedIndices[l].1, updatedIndices[l].2) } } i += 1 j += 1 } else { i += 1 } } else if let _ = left { i += 1 } else if let right = right { let previousIndex = previousIndices[right.stableId] insertItems.append((i, right, previousIndex)) currentList.insert(right, at: i) if k < updatedIndices.count { for l in k ..< updatedIndices.count { updatedIndices[l] = (updatedIndices[l].0 + 1, updatedIndices[l].1, updatedIndices[l].2) } } i += 1 j += 1 } else { break } } for (index, item, _) in updatedIndices { currentList[index] = item } assert(currentList == rightList, "currentList == rightList") return (removeIndices, insertItems, updatedIndices) }
gpl-2.0
54e177905c731942b53e1799bd812d87
29.173804
192
0.44386
4.316757
false
false
false
false
mleiv/MEGameTracker
MEGameTracker/Views/Common/MESearchManager.swift
1
4141
// // MESearchManager.swift // MEGameTracker // // Created by Emily Ivie on 5/8/16. // Copyright © 2016 Emily Ivie. All rights reserved. // import UIKit final public class MESearchManager: NSObject { // passed in private var controller: UIViewController private var tempSearchBar: UISearchBar? // - (optional) private var resultsController: UITableViewController? private var searchData: ((_ needle: String?) -> Void) = { _ in } private var closeSearch: (() -> Void) = { } // revealed public var searchController: UISearchController? public var showSearchData: Bool = false // interal use only private var lastSearch: String = "" public init( controller: UIViewController, tempSearchBar: UISearchBar? = nil, resultsController: UITableViewController? = nil, searchData: ((_ needle: String?) -> Void)? = nil, closeSearch: (() -> Void)? = nil ) { self.controller = controller self.tempSearchBar = tempSearchBar self.resultsController = resultsController super.init() self.searchData = searchData ?? self.searchData self.closeSearch = closeSearch ?? self.closeSearch setupSearchController() } public func reloadData() { (searchController?.searchResultsController as? UITableViewController)?.tableView?.reloadData() } public func styleSearchTable(_ closure: (UITableView?) -> Void ) { closure((searchController?.searchResultsController as? UITableViewController)?.tableView) } private func setupSearchController() { controller.definesPresentationContext = true // hold search to our current bounds // create search controller (no IB equivalent) let searchController = UISearchController(searchResultsController: resultsController) searchController.hidesNavigationBarDuringPresentation = false searchController.obscuresBackgroundDuringPresentation = false searchController.searchResultsUpdater = self searchController.searchBar.delegate = self searchController.searchBar.searchBarStyle = tempSearchBar?.searchBarStyle ?? searchController.searchBar.searchBarStyle searchController.searchBar.placeholder = tempSearchBar?.placeholder searchController.searchBar.barTintColor = tempSearchBar?.barTintColor searchController.searchBar.setNeedsLayout() searchController.searchBar.layoutIfNeeded() self.searchController = searchController // replace placeholder: if let tempParent = tempSearchBar?.superview { tempSearchBar?.removeFromSuperview() let searchBar = searchController.searchBar tempParent.addSubview(searchBar) searchBar.topAnchor.constraint(equalTo: tempParent.topAnchor).isActive = true searchBar.bottomAnchor.constraint(equalTo: tempParent.bottomAnchor).isActive = true searchBar.leadingAnchor.constraint(equalTo: tempParent.leadingAnchor).isActive = true searchBar.trailingAnchor.constraint(equalTo: tempParent.trailingAnchor).isActive = true } // TODO: fix the excess header between search bar and results. // Below is icky and doesn't work well on horizontal/ipad // if #available(iOS 10.0, *) { // resultsController?.automaticallyAdjustsScrollViewInsets = false // resultsController?.tableView.contentInset = UIEdgeInsetsMake(64, 0, 44, 0) // } } } // MARK: UISearchResultsUpdating protocol extension MESearchManager: UISearchResultsUpdating { public func updateSearchResults(for searchController: UISearchController) { let search = searchController.searchBar.text?.trim() ?? "" if search.isEmpty && !lastSearch.isEmpty { lastSearch = "" searchData(nil) } else if !search.isEmpty && search != lastSearch { lastSearch = search showSearchData = true searchData(search) // searchController.active = true } } } // MARK: UISearchBarDelegate protocol extension MESearchManager: UISearchBarDelegate { public func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { if searchController?.isActive == true { lastSearch = "" showSearchData = false searchController?.dismiss(animated: true) { () -> Void in } closeSearch() } } }
mit
049a87a548ca3954219efac2063e4680
34.689655
99
0.738406
4.715262
false
false
false
false
omarqazi/HearstKit
Example/HearstKit/AppDelegate.swift
1
5081
// // AppDelegate.swift // HearstKit // // Created by Omar Qazi on 02/02/2016. // Copyright (c) 2016 Omar Qazi. All rights reserved. // import UIKit import FBSDKCoreKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions) self.registerUserNotificationSettings(application) application.registerForRemoteNotifications() return true } func registerUserNotificationSettings(application: UIApplication) { let newMessageCategory = UIMutableUserNotificationCategory() newMessageCategory.identifier = "chat-message" let thumbsUpAction = UIMutableUserNotificationAction() thumbsUpAction.identifier = "thumbs-up" thumbsUpAction.title = "👍" thumbsUpAction.activationMode = UIUserNotificationActivationMode.Background thumbsUpAction.authenticationRequired = false let replyAction = UIMutableUserNotificationAction() replyAction.identifier = "reply-with-message" replyAction.title = "Reply" replyAction.activationMode = UIUserNotificationActivationMode.Background replyAction.authenticationRequired = false if #available(iOS 9.0, *) { replyAction.behavior = UIUserNotificationActionBehavior.TextInput replyAction.parameters = [UIUserNotificationTextInputActionButtonTitleKey : "Reply"] } else { // No text replies on older iOS versions } newMessageCategory.setActions([thumbsUpAction,replyAction], forContext: .Default) newMessageCategory.setActions([thumbsUpAction,replyAction], forContext: .Minimal) let notificationSettings = UIUserNotificationSettings(forTypes: [.Alert,.Sound,.Badge], categories: [newMessageCategory]) application.registerUserNotificationSettings(notificationSettings) } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. print("app will resign active") } 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. print("app did enter background") } 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. print("app will enter foreground") } func applicationWillTerminate(application: UIApplication) { print("application will terminate") // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) { print("did register user notification settings") } func application(application: UIApplication, handleActionWithIdentifier identifier: String?, forRemoteNotification userInfo: [NSObject : AnyObject], completionHandler: () -> Void) { print(userInfo) } func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) { print("failed to register for remote notifications",error) } func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) { print("Got notification",userInfo) } func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) { print(deviceToken) } func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool { return FBSDKApplicationDelegate.sharedInstance().application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation) } func applicationDidBecomeActive(application: UIApplication) { FBSDKAppEvents.activateApp() } }
gpl-3.0
822ee6c3fd5fd49cea8e178a5368f735
46.457944
285
0.738086
5.967098
false
false
false
false
CPC-Coder/CPCBannerView
Example/CPCBannerView/CPCBannerView/CPCBaseBannerView.swift
2
14273
// // CPCBaseBannerView.swift // bannerView // // Created by 鹏程 on 17/7/5. // Copyright © 2017年 pengcheng. All rights reserved. // /*-------- 温馨提示 --------*/ /* CPCBannerViewDefault --> collectionView上有lab (所有cell共享控件) CPCBannerViewCustom --> 每个cell上都有lab(cell都有独有控件) CPCBannerViewTextOnly --> 只有文字 */ /*-------- 温馨提示 --------*/ import UIKit enum CPCPageControlPosition{ case bottomCenter,bottomLeft,bottomRight,topCenter,topLeft,topRight } /// 如果需要设置可选协议方法 /// - 需要遵守 NSObjectProtocol 协议 /// - 协议需要是 @objc 的 /// - 方法需要 @objc optional //MARK: - *** 协议 *** @objc protocol CPCBannerViewDelegate:NSObjectProtocol { /** * 必须实现的代理方法, 返回总页数 * * @param bannerView bannerView * * @return 返回总页数 */ //func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int func c_numberOfPages(bannerView: CPCBaseBannerView) -> Int /** * 设置cell的数据 * * @param bannerView bannerView * @param cell cell的类型由注册的时候决定, 需要转换为相应的类型来使用 * @param index index */ //collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell func c_setUpPageCell(bannerView:CPCBaseBannerView, cell:UICollectionViewCell,index: Int) -> () /** 修改公共控件的数据 */ @objc optional func c_setUpLab(bannerView:CPCBaseBannerView,index:Int) -> String /** * 响应点击当前页 * * @param bannerView * @param index 被点击的index */ @objc optional func c_didSelectPage(bannerView:CPCBaseBannerView, index:Int) /** * 滚动到当前页 * * @param bannerView * @param currentIndex currentIndex */ @objc optional func c_didScrollToCurrentIndex(bannerView:CPCBaseBannerView, currentIndex:Int) } //MARK: - *** CPCBaseBannerView *** class CPCBaseBannerView: UIView { /** pageControl 的位置 默认为下面居中显示 */ var pageControlPositon:CPCPageControlPosition = .bottomCenter{ didSet{ setNeedsLayout() } } /** 滚动的时间间隔 默认为3s */ var scrollDuration:Float = 3 /** 滚动方向 水平或者竖直滚动 默认为水平方向滚动 */ var scrollDirection:UICollectionViewScrollDirection = .horizontal{ didSet{ layout.scrollDirection = scrollDirection } } //代理 weak var delegate:CPCBannerViewDelegate? fileprivate lazy var layout: UICollectionViewFlowLayout = { let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: 100, height: 100) layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.scrollDirection = .horizontal return layout }() /** collectionView */ fileprivate lazy var collectionView: UICollectionView = {[weak self] in guard let `self` = self else { return UICollectionView() } //collectionView let v = UICollectionView(frame: CGRect.zero, collectionViewLayout: self.layout) v.delegate = self v.dataSource = self v.isPagingEnabled = true v.showsVerticalScrollIndicator = false v.showsHorizontalScrollIndicator = false v.backgroundColor = UIColor.white return v }() /** pageControl */ lazy var pageControl: UIPageControl = { let pageC = UIPageControl() pageC.backgroundColor = UIColor.clear pageC.currentPageIndicatorTintColor = UIColor.black pageC.pageIndicatorTintColor = UIColor.lightGray return pageC }() /** 总共的页数 */ fileprivate var pages:Int = 0{ didSet{ pageControl.numberOfPages = pages } } /** 当前的页数 */ fileprivate var currentPage:Int = 0{ didSet{ delegate?.c_didScrollToCurrentIndex?(bannerView: self, currentIndex: currentPage) change(currentPage: currentPage) pageControl.currentPage = currentPage } } fileprivate var beginOffset: CGPoint = CGPoint.zero fileprivate var timer: Timer? init(delegate: CPCBannerViewDelegate) { super.init(frame: CGRect.zero) self.delegate = delegate change(currentPage: currentPage) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { stopTimer() } override func willMove(toSuperview newSuperview: UIView?) { if newSuperview == nil{ stopTimer() } } override func layoutSubviews() { super.layoutSubviews() let pageControlSize = pageControl.size(forNumberOfPages: pages) var pageControlFrame = CGRect(x: 0, y: 0, width: pageControlSize.width, height: pageControlSize.height) switch pageControlPositon { case .topCenter: pageControlFrame.origin = CGPoint(x: (bounds.width-pageControlFrame.width)*0.5, y: 0) case .topLeft: pageControlFrame.origin = CGPoint(x: 0, y: 0) case .topRight: pageControlFrame.origin = CGPoint(x: bounds.width-pageControlFrame.width, y: 0) case .bottomCenter: pageControlFrame.origin = CGPoint(x: (bounds.width-pageControlFrame.width)*0.5, y: bounds.height-pageControlFrame.height) case .bottomLeft: pageControlFrame.origin = CGPoint(x: 0, y: bounds.height-pageControlFrame.height) case .bottomRight: pageControlFrame.origin = CGPoint(x: bounds.width-pageControlFrame.width, y: bounds.height-pageControlFrame.height) } pageControl.frame = pageControlFrame; collectionView.frame = self.bounds; } //MARK: - *** 图片修改后 必须reload *** func reload(){ stopTimer() currentPage = 0 collectionView.reloadData() pages = delegate!.c_numberOfPages(bannerView: self) startTimer() // collectionView.reloadData() // collectionView.removeFromSuperview() // pageControl.removeFromSuperview() // // setupUI() } } //MARK: - *** 子类实现 *** extension CPCBaseBannerView { func registerCell(collectionView: UICollectionView) -> () { } func dequeueReusableCell(collectionView: UICollectionView,indexPath:IndexPath)->(UICollectionViewCell){ return UICollectionViewCell() } func change(currentPage:Int) -> () { } } fileprivate extension CPCBaseBannerView { func setupUI() -> () { guard let delegate = delegate else { assert(false, "必须实现代理方法 numberOfPagesForbannerView:") return } pages = delegate.c_numberOfPages(bannerView: self) // 添加控件 addSubview(collectionView) addSubview(pageControl) // 注册cell registerCell(collectionView: collectionView) // 开启timer startTimer() } } //MARK: - *** time *** fileprivate extension CPCBaseBannerView{ func startTimer(){ if timer == nil && pages>1{ timer = Timer(fireAt: Date()+TimeInterval(scrollDuration), interval: TimeInterval(scrollDuration), target: self, selector: #selector(timerHandler), userInfo: nil, repeats: true) RunLoop.main.add(timer!, forMode: .defaultRunLoopMode) } } func stopTimer() -> () { timer?.invalidate() timer = nil } @objc func timerHandler() -> () { let offset = collectionView.contentOffset if scrollDirection == .horizontal { collectionView.setContentOffset(CGPoint(x: offset.x+collectionView.bounds.width, y: 0), animated: true) } else { collectionView.setContentOffset(CGPoint(x: 0, y: offset.y+collectionView.bounds.height), animated: true) } } } extension CPCBaseBannerView{ // 开始拖拽 func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { beginOffset = scrollView.contentOffset stopTimer() } // 松开手 func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { startTimer() } func scrollViewDidScroll(_ scrollView: UIScrollView) { var offsetX = scrollView.contentOffset.x if scrollDirection == .horizontal { /*-------- --------*/ //向左滑 if offsetX>scrollView.contentSize.width-scrollView.bounds.width { // 重置滚动开始的偏移量 beginOffset.x = 0 offsetX = beginOffset.x // 设置滚动到第一页 scrollView.setContentOffset(CGPoint(x: beginOffset.x, y: 0), animated: false) if !scrollView.isDragging{ scrollView.setContentOffset(CGPoint(x: beginOffset.x+scrollView.bounds.width, y: 0), animated: true) } } // 向右滑 if offsetX<0 {// 滚动到第一页 beginOffset.x = scrollView.contentSize.width-scrollView.bounds.width offsetX = beginOffset.x // 设置滚动到最后一页 scrollView.setContentOffset(CGPoint(x: beginOffset.x, y: 0), animated: false) } var tempIndex = Int(offsetX/scrollView.bounds.width+0.5) if tempIndex >= pages{ tempIndex = 0 } if tempIndex != currentPage{ currentPage = tempIndex } /*-------- <#注释#> --------*/ } else { /*-------- <#注释#> --------*/ var offsetY = scrollView.contentOffset.y //向上滑 if offsetY>scrollView.contentSize.height-scrollView.bounds.height{ beginOffset.y = 0 offsetY = beginOffset.y scrollView.setContentOffset(CGPoint(x: 0, y: beginOffset.y), animated: false) // if !scrollView.isDragging{ // scrollView.setContentOffset(CGPoint(x: 0, y: beginOffset.y+scrollView.bounds.height), animated: true) // currentPage = 1 // } } // 向下滑 if offsetY<0{ print("向下滑") beginOffset.y = scrollView.contentSize.height-scrollView.bounds.height offsetY = beginOffset.y scrollView.setContentOffset(CGPoint(x: 0, y: beginOffset.y), animated: false) } var tempIndex:Int = Int(offsetY/scrollView.bounds.size.height+0.5) if tempIndex>=pages { tempIndex = 0 } if tempIndex != currentPage { currentPage = tempIndex } /*-------- <#注释#> --------*/ } } } //MARK: - *** UICollectionViewDelegate DataSource *** extension CPCBaseBannerView: UICollectionViewDelegate,UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return pages+1 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { var realIndexPath = indexPath if indexPath.row == pages{ realIndexPath = IndexPath(row: 0, section: indexPath.section) } let cell = dequeueReusableCell(collectionView: collectionView, indexPath: realIndexPath) delegate?.c_setUpPageCell(bannerView: self, cell: cell, index: realIndexPath.row) return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { var realIndexPath = indexPath if indexPath.row == pages{ realIndexPath = IndexPath(row: 0, section: indexPath.section) } delegate?.c_didSelectPage?(bannerView: self, index: realIndexPath.row) } } extension CPCBaseBannerView: UICollectionViewDelegateFlowLayout{ func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return self.collectionView.bounds.size } }
mit
8214c86a95558590722eca323ce0fe54
22.968531
192
0.538074
5.410418
false
false
false
false
LiLe2015/DouYuLive
DouYuLive/DouYuLive/Classes/Home/Controller/RecommendViewController.swift
1
5044
// // RecommendViewController.swift // DouYuLive // // Created by LiLe on 2016/11/15. // Copyright © 2016年 LiLe. All rights reserved. // import UIKit private let kItemMargin: CGFloat = 10 private let kItemW = (kScreenW - 3 * kItemMargin) / 2 private let kNormalItemH = kItemW * 3 / 4 private let kPrettyItemH = kItemW * 4 / 3 private let kHeaderViewH : CGFloat = 50 private let kNormalCellID = "kNormalCellID" private let kPrettyCellID = "kPrettyCellID" private let kHeaderViewID = "kHeaderViewID" class RecommendViewController: UIViewController { // MARK:- 懒加载属性 private lazy var recommendVM: RecommendViewModel = RecommendViewModel() private lazy var collectionView: UICollectionView = {[unowned self] in // 1.创建布局 let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: kItemW, height: kNormalItemH) layout.minimumLineSpacing = 0 // 行间距 layout.minimumInteritemSpacing = kItemMargin // item之间的间距 layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderViewH) // 设置section头部的尺寸 // 设置item的四周的间距 layout.sectionInset = UIEdgeInsets(top: 0, left: kItemMargin, bottom: 0, right: kItemMargin) // 2.创建UICollectionView let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout) collectionView.backgroundColor = UIColor.whiteColor() collectionView.dataSource = self collectionView.delegate = self // 设置collectionView的尺寸的大小随着父控件的变化而变化 collectionView.autoresizingMask = [.FlexibleHeight, .FlexibleWidth] // 注册cell //collectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: kNormalCellID) //collectionView.registerClass(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID) collectionView.registerNib(UINib(nibName: "CollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: kNormalCellID) collectionView.registerNib(UINib(nibName: "CollectionPrettyCell", bundle: nil), forCellWithReuseIdentifier: kPrettyCellID) collectionView.registerNib(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID) return collectionView }() override func viewDidLoad() { super.viewDidLoad() // 设置UI界面 setupUI() // 请求数据 loadData() } } // MARK:- 设置UI界面内容 extension RecommendViewController { private func setupUI() { // 1.将UICollectionView添加到控制器的view中 view.addSubview(collectionView) } } // MARK:- 请求数据 extension RecommendViewController { private func loadData() { recommendVM.requestData() { self.collectionView.reloadData() } } } // MARK:- 遵守UICollectionView的数据源协议 extension RecommendViewController : UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return recommendVM.anchorGroups.count } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let group = recommendVM.anchorGroups[section] return group.anchors.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { // 1.定义cell var cell: UICollectionViewCell! // 2.获取cell if indexPath.section == 1 { cell = collectionView.dequeueReusableCellWithReuseIdentifier(kPrettyCellID, forIndexPath: indexPath) } else { cell = collectionView.dequeueReusableCellWithReuseIdentifier(kNormalCellID, forIndexPath: indexPath) } return cell } func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { // 1.取出section的HeaderView let headerView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: kHeaderViewID, forIndexPath: indexPath) as! CollectionHeaderView // 2.取出模型 headerView.group = recommendVM.anchorGroups[indexPath.section] return headerView } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { if indexPath.section == 1 { return CGSize(width: kItemW, height: kPrettyItemH) } return CGSize(width: kItemW, height: kNormalItemH) } }
mit
3f3b70891cd3c848d79b9f7b985652e4
38.663934
189
0.712131
5.981459
false
false
false
false
getsenic/nuimo-websocket-server-osx
Pods/NuimoSwift/SDK/NuimoController.swift
1
3467
// // NuimoController.swift // Nuimo // // Created by Lars Blumberg on 10/9/15. // Copyright © 2015 Senic. All rights reserved. // // This software may be modified and distributed under the terms // of the MIT license. See the LICENSE file for details. @objc public protocol NuimoController { var uuid: String {get} var delegate: NuimoControllerDelegate? {get set} var connectionState: NuimoConnectionState {get} /// Display interval in seconds var defaultMatrixDisplayInterval: NSTimeInterval {get set} /// Brightness 0..1 (1=max) var matrixBrightness: Float {get set} func connect() -> Bool func disconnect() -> Bool /// Writes an LED matrix for an interval with options (options is of type Int for compatibility with Objective-C) func writeMatrix(matrix: NuimoLEDMatrix, interval: NSTimeInterval, options: Int) } public extension NuimoController { /// Writes an LED matrix with options defaulting to ResendsSameMatrix and WithWriteResponse func writeMatrix(matrix: NuimoLEDMatrix, interval: NSTimeInterval) { writeMatrix(matrix, interval: interval, options: 0) } /// Writes an LED matrix using the default display interval and with options defaulting to ResendsSameMatrix and WithWriteResponse public func writeMatrix(matrix: NuimoLEDMatrix) { writeMatrix(matrix, interval: defaultMatrixDisplayInterval) } /// Writes an LED matrix for an interval and with options public func writeMatrix(matrix: NuimoLEDMatrix, interval: NSTimeInterval, options: NuimoLEDMatrixWriteOptions) { writeMatrix(matrix, interval: interval, options: options.rawValue) } /// Writes an LED matrix using the default display interval and with options defaulting to ResendsSameMatrix and WithWriteResponse public func writeMatrix(matrix: NuimoLEDMatrix, options: NuimoLEDMatrixWriteOptions) { writeMatrix(matrix, interval: defaultMatrixDisplayInterval, options: options) } } @objc public enum NuimoLEDMatrixWriteOption: Int { case IgnoreDuplicates = 1 case WithFadeTransition = 2 case WithoutWriteResponse = 4 } public struct NuimoLEDMatrixWriteOptions: OptionSetType { public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } public static let IgnoreDuplicates = NuimoLEDMatrixWriteOptions(rawValue: NuimoLEDMatrixWriteOption.IgnoreDuplicates.rawValue) public static let WithFadeTransition = NuimoLEDMatrixWriteOptions(rawValue: NuimoLEDMatrixWriteOption.WithFadeTransition.rawValue) public static let WithoutWriteResponse = NuimoLEDMatrixWriteOptions(rawValue: NuimoLEDMatrixWriteOption.WithoutWriteResponse.rawValue) } @objc public enum NuimoConnectionState: Int { case Connecting, Connected, Disconnecting, Disconnected, Invalidated } @objc public protocol NuimoControllerDelegate { optional func nuimoController(controller: NuimoController, didChangeConnectionState state: NuimoConnectionState, withError error: NSError?) optional func nuimoController(controller: NuimoController, didReadFirmwareVersion firmwareVersion: String) optional func nuimoController(controller: NuimoController, didUpdateBatteryLevel batteryLevel: Int) optional func nuimoController(controller: NuimoController, didReceiveGestureEvent event: NuimoGestureEvent) optional func nuimoControllerDidDisplayLEDMatrix(controller: NuimoController) }
mit
51a0b77f2d36b7dc0e2ffa72301045a3
40.261905
143
0.768321
4.370744
false
false
false
false
PJayRushton/TeacherTools
TeacherTools/MainTabBarController.swift
1
1289
// // AddStudentsViewController.swift // TeacherTools // // Created by Parker Rushton on 12/31/16. // Copyright © 2016 AppsByPJ. All rights reserved. // import UIKit class MainTabBarController: UITabBarController, AutoStoryboardInitializable { enum Tab: Int, CaseIterable { case list case groups case drawName case settings } // MARK: - Properties var core = App.core // MARK: - Lifecycle overrides override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) core.add(subscriber: self) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) core.remove(subscriber: self) } } // MARK: - Subscriber extension MainTabBarController: Subscriber { func update(with state: AppState) { let currentTheme = state.theme tabBar.tintColor = currentTheme.tintColor tabBar.unselectedItemTintColor = currentTheme.textColor tabBar.barStyle = currentTheme.name == "Whiteboard" ? .default : .black } } // MARK: - Private functions private extension MainTabBarController { }
mit
8c037139e28b0a4a82581b89e6cd8633
19.774194
79
0.639752
4.860377
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/StartUI/StartUI/SearchResultsViewController.swift
1
16214
// // 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 Foundation import WireSyncEngine import UIKit enum SearchGroup: Int { case people case services } extension SearchGroup { var accessible: Bool { switch self { case .people: return true case .services: return SelfUser.current.canCreateService } } #if ADD_SERVICE_DISABLED // remove service from the tab static let all: [SearchGroup] = [.people] #else static var all: [SearchGroup] { return [.people, .services].filter { $0.accessible } } #endif var name: String { switch self { case .people: return "peoplepicker.header.people".localized case .services: return "peoplepicker.header.services".localized } } } protocol SearchResultsViewControllerDelegate: AnyObject { func searchResultsViewController(_ searchResultsViewController: SearchResultsViewController, didTapOnUser user: UserType, indexPath: IndexPath, section: SearchResultsViewControllerSection) func searchResultsViewController(_ searchResultsViewController: SearchResultsViewController, didDoubleTapOnUser user: UserType, indexPath: IndexPath) func searchResultsViewController(_ searchResultsViewController: SearchResultsViewController, didTapOnConversation conversation: ZMConversation) func searchResultsViewController(_ searchResultsViewController: SearchResultsViewController, didTapOnSeviceUser user: ServiceUser) func searchResultsViewController(_ searchResultsViewController: SearchResultsViewController, wantsToPerformAction action: SearchResultsViewControllerAction) } enum SearchResultsViewControllerAction: Int { case createGroup case createGuestRoom } enum SearchResultsViewControllerMode: Int { case search case selection case list } enum SearchResultsViewControllerSection: Int { case unknown case topPeople case contacts case teamMembers case conversations case directory case services case federation } extension UIViewController { class ControllerHierarchyIterator: IteratorProtocol { private var current: UIViewController init(controller: UIViewController) { current = controller } func next() -> UIViewController? { var candidate: UIViewController? = .none if let controller = current.navigationController { candidate = controller } else if let controller = current.presentingViewController { candidate = controller } else if let controller = current.parent { candidate = controller } if let candidate = candidate { current = candidate } return candidate } } func isContainedInPopover() -> Bool { var hierarchy = ControllerHierarchyIterator(controller: self) return hierarchy.any { if let arrowDirection = $0.popoverPresentationController?.arrowDirection, arrowDirection != .unknown { return true } else { return false } } } } final class SearchResultsViewController: UIViewController { lazy var searchResultsView: SearchResultsView = { let view = SearchResultsView() view.parentViewController = self return view }() private lazy var searchDirectory: SearchDirectory! = { guard let session = ZMUserSession.shared() else { return nil } return SearchDirectory(userSession: session) }() let userSelection: UserSelection let sectionController: SectionCollectionViewController = SectionCollectionViewController() let contactsSection: ContactsSectionController = ContactsSectionController() let teamMemberAndContactsSection: ContactsSectionController = ContactsSectionController() let directorySection = DirectorySectionController() let conversationsSection: GroupConversationsSectionController = GroupConversationsSectionController() let federationSection = FederationSectionController() lazy var topPeopleSection: TopPeopleSectionController = { return TopPeopleSectionController(topConversationsDirectory: ZMUserSession.shared()?.topConversationsDirectory) }() let servicesSection: SearchServicesSectionController let inviteTeamMemberSection: InviteTeamMemberSection let createGroupSection = CreateGroupSection() var pendingSearchTask: SearchTask? var isAddingParticipants: Bool let isFederationEnabled: Bool var searchGroup: SearchGroup = .people { didSet { updateVisibleSections() } } var filterConversation: ZMConversation? let shouldIncludeGuests: Bool weak var delegate: SearchResultsViewControllerDelegate? var mode: SearchResultsViewControllerMode = .search { didSet { updateVisibleSections() } } deinit { searchDirectory?.tearDown() } init(userSelection: UserSelection, isAddingParticipants: Bool = false, shouldIncludeGuests: Bool, isFederationEnabled: Bool) { self.userSelection = userSelection self.isAddingParticipants = isAddingParticipants self.mode = .list self.shouldIncludeGuests = shouldIncludeGuests self.isFederationEnabled = isFederationEnabled let team = ZMUser.selfUser().team let teamName = team?.name contactsSection.selection = userSelection contactsSection.title = "peoplepicker.header.contacts_personal".localized contactsSection.allowsSelection = isAddingParticipants teamMemberAndContactsSection.allowsSelection = isAddingParticipants teamMemberAndContactsSection.selection = userSelection teamMemberAndContactsSection.title = "peoplepicker.header.contacts".localized servicesSection = SearchServicesSectionController(canSelfUserManageTeam: ZMUser.selfUser().canManageTeam) conversationsSection.title = team != nil ? "peoplepicker.header.team_conversations".localized(args: teamName ?? "") : "peoplepicker.header.conversations".localized inviteTeamMemberSection = InviteTeamMemberSection(team: team) super.init(nibName: nil, bundle: nil) contactsSection.delegate = self teamMemberAndContactsSection.delegate = self directorySection.delegate = self topPeopleSection.delegate = self conversationsSection.delegate = self servicesSection.delegate = self createGroupSection.delegate = self inviteTeamMemberSection.delegate = self federationSection.delegate = self } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func loadView() { view = searchResultsView } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) sectionController.collectionView?.reloadData() sectionController.collectionView?.collectionViewLayout.invalidateLayout() } override func viewDidLoad() { super.viewDidLoad() sectionController.collectionView = searchResultsView.collectionView updateVisibleSections() searchResultsView.emptyResultContainer.isHidden = !isResultEmpty } @objc func cancelPreviousSearch() { pendingSearchTask?.cancel() pendingSearchTask = nil } private func performSearch(query: String, options: SearchOptions) { pendingSearchTask?.cancel() searchResultsView.emptyResultContainer.isHidden = true var options = options options.updateForSelfUserTeamRole(selfUser: ZMUser.selfUser()) let request = SearchRequest(query: query.trim(), searchOptions: options, team: ZMUser.selfUser().team) if let task = searchDirectory?.perform(request) { task.onResult({ [weak self] in self?.handleSearchResult(result: $0, isCompleted: $1)}) task.start() pendingSearchTask = task } } func searchForUsers(withQuery query: String) { var options: SearchOptions = [.conversations, .contacts, .teamMembers, .directory] if isFederationEnabled { options.formUnion(.federated) } self.performSearch(query: query, options: options) } func searchForLocalUsers(withQuery query: String) { self.performSearch(query: query, options: [.contacts, .teamMembers]) } func searchForServices(withQuery query: String) { self.performSearch(query: query, options: [.services]) } func searchContactList() { searchForLocalUsers(withQuery: "") } var isResultEmpty: Bool = true { didSet { searchResultsView.emptyResultContainer.isHidden = !isResultEmpty } } func handleSearchResult(result: SearchResult, isCompleted: Bool) { self.updateSections(withSearchResult: result) if isCompleted { isResultEmpty = sectionController.visibleSections.isEmpty } } func updateVisibleSections() { var sections: [CollectionViewSectionController] let team = ZMUser.selfUser().team switch(self.searchGroup, isAddingParticipants) { case (.services, _): sections = [servicesSection] case (.people, true): switch (mode, team != nil) { case (.search, false): sections = [contactsSection] case (.search, true): sections = [teamMemberAndContactsSection] case (.selection, false): sections = [contactsSection] case (.selection, true): sections = [teamMemberAndContactsSection] case (.list, false): sections = [contactsSection] case (.list, true): sections = [teamMemberAndContactsSection] } case (.people, false): switch (mode, team != nil) { case (.search, false): sections = [contactsSection, conversationsSection, directorySection, federationSection] case (.search, true): sections = [teamMemberAndContactsSection, conversationsSection, directorySection, federationSection] case (.selection, false): sections = [contactsSection] case (.selection, true): sections = [teamMemberAndContactsSection] case (.list, false): sections = [createGroupSection, topPeopleSection, contactsSection] case (.list, true): sections = [createGroupSection, inviteTeamMemberSection, teamMemberAndContactsSection] } } sectionController.sections = sections } func updateSections(withSearchResult searchResult: SearchResult) { var contacts = searchResult.contacts var teamContacts = searchResult.teamMembers if let filteredParticpants = filterConversation?.localParticipants { contacts = contacts.filter({ guard let user = $0.user else { return true } return !filteredParticpants.contains(user) }) teamContacts = teamContacts.filter({ guard let user = $0.user else { return true } return !filteredParticpants.contains(user) }) } contactsSection.contacts = contacts // Access mode is not set, or the guests are allowed. if shouldIncludeGuests { teamMemberAndContactsSection.contacts = Set(teamContacts + contacts).sorted { let name0 = $0.name ?? "" let name1 = $1.name ?? "" return name0.compare(name1) == .orderedAscending } } else { teamMemberAndContactsSection.contacts = teamContacts } directorySection.suggestions = searchResult.directory.filter { !$0.isFederated } conversationsSection.groupConversations = searchResult.conversations servicesSection.services = searchResult.services federationSection.users = searchResult.directory.filter { $0.isFederated } sectionController.collectionView?.reloadData() } func sectionFor(controller: CollectionViewSectionController) -> SearchResultsViewControllerSection { if controller === topPeopleSection { return .topPeople } else if controller === contactsSection { return .contacts } else if controller === teamMemberAndContactsSection { return .teamMembers } else if controller === conversationsSection { return .conversations } else if controller === directorySection { return .directory } else if controller === servicesSection { return .services } else if controller === federationSection { return .federation } else { return .unknown } } } extension SearchResultsViewController: SearchSectionControllerDelegate { func searchSectionController(_ searchSectionController: CollectionViewSectionController, didSelectUser user: UserType, at indexPath: IndexPath) { if let user = user as? ZMUser { delegate?.searchResultsViewController(self, didTapOnUser: user, indexPath: indexPath, section: sectionFor(controller: searchSectionController)) } else if let service = user as? ServiceUser, service.isServiceUser { delegate?.searchResultsViewController(self, didTapOnSeviceUser: service) } else if let searchUser = user as? ZMSearchUser { delegate?.searchResultsViewController(self, didTapOnUser: searchUser, indexPath: indexPath, section: sectionFor(controller: searchSectionController)) } } func searchSectionController(_ searchSectionController: CollectionViewSectionController, didSelectConversation conversation: ZMConversation, at indexPath: IndexPath) { delegate?.searchResultsViewController(self, didTapOnConversation: conversation) } func searchSectionController(_ searchSectionController: CollectionViewSectionController, didSelectRow row: CreateGroupSection.Row, at indexPath: IndexPath) { switch row { case .createGroup: delegate?.searchResultsViewController(self, wantsToPerformAction: .createGroup) case .createGuestRoom: delegate?.searchResultsViewController(self, wantsToPerformAction: .createGuestRoom) } } func searchSectionController(_ searchSectionController: CollectionViewSectionController, wantsToDisplayError error: LocalizedError) { presentLocalizedErrorAlert(error) } } extension SearchResultsViewController: InviteTeamMemberSectionDelegate { func inviteSectionDidRequestTeamManagement() { URL.manageTeam(source: .onboarding).openInApp(above: self) } } extension SearchResultsViewController: SearchServicesSectionDelegate { func addServicesSectionDidRequestOpenServicesAdmin() { URL.manageTeam(source: .settings).openInApp(above: self) } }
gpl-3.0
f3d0cf5ba2ee151424116a80a9c70ce5
34.557018
192
0.671087
5.571821
false
false
false
false
wupingzj/YangRepoApple
QiuTuiJian/QiuTuiJian/User.swift
1
820
// // Mobile.swift // QiuTuiJian // // Created by Ping on 27/07/2014. // Copyright (c) 2014 Yang Ltd. All rights reserved. // import Foundation import CoreData public class User: Person { @NSManaged public var anonymous: Bool @NSManaged public var reviews: [Review] public override func awakeFromInsert() { super.awakeFromInsert() self.uuid = NSUUID().UUIDString self.createdDate = NSDate() } public class func createEntity() -> User { let ctx: NSManagedObjectContext = DataService.sharedInstance.ctx let ed: NSEntityDescription = NSEntityDescription.entityForName("User", inManagedObjectContext: ctx)! let newEntity = User(entity: ed, insertIntoManagedObjectContext: ctx) return newEntity } }
gpl-2.0
c86b96b961229a03e6843ba2c4701955
23.878788
109
0.654878
4.852071
false
false
false
false
Pluto-tv/RxSwift
RxTests/RxSwiftTests/TestImplementations/Mocks/HotObservable.swift
1
1624
// // HotObservable.swift // Rx // // Created by Krunoslav Zaher on 2/14/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation import RxSwift class HotObservable<Element : Equatable> : ObservableType, ObservableConvertibleType { typealias E = Element typealias Events = Recorded<Element> typealias Observer = AnyObserver<Element> let testScheduler: TestScheduler var subscriptions: [Subscription] var recordedEvents: [Events] var observers: Bag<AnyObserver<Element>> init(testScheduler: TestScheduler, recordedEvents: [Events]) { self.testScheduler = testScheduler self.recordedEvents = recordedEvents self.subscriptions = [] self.observers = Bag() for recordedEvent in recordedEvents { testScheduler.schedule((), time: recordedEvent.time) { t in self.observers.forEach { $0.on(recordedEvent.event) } return NopDisposable.instance } } } func subscribe<O : ObserverType where O.E == E>(observer: O) -> Disposable { let key = observers.insert(AnyObserver(observer)) subscriptions.append(Subscription(self.testScheduler.now)) let i = self.subscriptions.count - 1 return AnonymousDisposable { let removed = self.observers.removeKey(key) assert(removed != nil) let existing = self.subscriptions[i] self.subscriptions[i] = Subscription(existing.subscribe, self.testScheduler.now) } } }
mit
e716d21d9c0b3008355a893ad1b0c3d0
29.074074
92
0.631158
4.93617
false
true
false
false
jesseXu/Charts
Source/Charts/Formatters/DefaultValueFormatter.swift
4
1910
// // DefaultValueFormatter.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation @objc(ChartDefaultValueFormatter) open class DefaultValueFormatter: NSObject, IValueFormatter { open var hasAutoDecimals: Bool = false fileprivate var _formatter: NumberFormatter? open var formatter: NumberFormatter? { get { return _formatter } set { hasAutoDecimals = false _formatter = newValue } } fileprivate var _decimals: Int? open var decimals: Int? { get { return _decimals } set { _decimals = newValue if let digits = newValue { self.formatter?.minimumFractionDigits = digits self.formatter?.maximumFractionDigits = digits self.formatter?.usesGroupingSeparator = true } } } public override init() { super.init() self.formatter = NumberFormatter() hasAutoDecimals = true } public init(formatter: NumberFormatter) { super.init() self.formatter = formatter } public init(decimals: Int) { super.init() self.formatter = NumberFormatter() self.formatter?.usesGroupingSeparator = true self.decimals = decimals hasAutoDecimals = true } open func stringForValue(_ value: Double, entry: ChartDataEntry, dataSetIndex: Int, viewPortHandler: ViewPortHandler?) -> String { return formatter?.string(from: NSNumber(floatLiteral: value)) ?? "" } }
apache-2.0
8790dec7949d40c8beedf05407ce7be3
22.580247
75
0.554974
5.457143
false
false
false
false
wuchun4/XCDownloadTool
XCDownloadToolExample/XCDownloadToolExample/ViewController.swift
1
1922
// // ViewController.swift // XCDownloadToolExample // // Created by Simon on 2017/2/24. // Copyright © 2017年 Simon. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var progressLabel:UILabel! @IBOutlet weak var imageView:UIImageView! var downloadTool:XCDownloadTool? override func viewDidLoad() { super.viewDidLoad() self.initData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func initData() -> Void { let url:URL = URL(string: "https://camo.githubusercontent.com/91481851b3130c22fdbb0d3dfb91869fa4bd2174/687474703a2f2f692e696d6775722e636f6d2f30684a384d7a572e676966")! let cacheDir:String = NSTemporaryDirectory() let folder = cacheDir.appending("simon") self.downloadTool = XCDownloadTool(url: url, fileIdentifier: nil, targetDirectory: folder, shouldResume: true) self.downloadTool?.shouldOverwrite = true self.downloadTool?.downloadProgress = {[weak self] (progress)-> Void in self?.progressLabel.text = "progress: \(progress)" } self.downloadTool?.downLoadCompletion = {[weak self] (finished:Bool ,targetPath:String?, error:Error?) -> Void in self?.progressLabel.text = "download finished" if let _ = targetPath{ let image:UIImage? = UIImage.init(contentsOfFile: targetPath!) self?.imageView.image = image } } } @IBAction func clickStart(sender:UIButton) -> Void { switch sender.tag { case 10: self.downloadTool?.startDownload() break case 11: self.downloadTool?.suspendDownload() break default: break } } }
mit
461bad7123fed555be1485f67b1cf734
27.220588
174
0.607087
4.515294
false
false
false
false
rockgarden/swift_language
Playground/Design-Patterns.playground/Design-Patterns.playground/section-18.swift
1
1114
typealias Memento = Dictionary<NSObject, AnyObject> let DPMementoKeyChapter = "com.valve.halflife.chapter" let DPMementoKeyWeapon = "com.valve.halflife.weapon" let DPMementoGameState = "com.valve.halflife.state" /** * Originator */ class GameState { var chapter: String = "" var weapon: String = "" func toMemento() -> Memento { return [ DPMementoKeyChapter:chapter, DPMementoKeyWeapon:weapon ] } func restoreFromMemento(memento: Memento) { chapter = memento[DPMementoKeyChapter] as? String ?? "n/a" weapon = memento[DPMementoKeyWeapon] as? String ?? "n/a" } } /** * Caretaker */ class CheckPoint { class func saveState(memento: Memento, keyName: String = DPMementoGameState) { let defaults = NSUserDefaults.standardUserDefaults() defaults.setObject(memento, forKey: keyName) defaults.synchronize() } class func restorePreviousState(keyName: String = DPMementoGameState) -> Memento { let defaults = NSUserDefaults.standardUserDefaults() return defaults.objectForKey(keyName) as? Memento ?? Memento() } }
mit
de81292fa8e4b18aa4aab9133b501ed2
27.589744
86
0.693896
3.922535
false
false
false
false
Draveness/NightNight
NightNight/Classes/NightNight.swift
1
950
// // NightNight.swift // Pods // // Created by Draveness on 6/30/16. // // import UIKit import ObjectiveC public let NightNightThemeChangeNotification = "NightNightThemeChangeNotification" private let NightNightThemeKey = "NightNightThemeKey" open class NightNight { fileprivate static var currentTheme = Theme(rawValue: UserDefaults.standard.integer(forKey: NightNightThemeKey)) ?? Theme.normal public enum Theme: Int { case normal case night } public static var theme: Theme { get { return currentTheme } set { currentTheme = newValue UserDefaults.standard.set(currentTheme.rawValue, forKey: NightNightThemeKey) NotificationCenter.default.post(name: Notification.Name(rawValue: NightNightThemeChangeNotification), object: nil) } } open class func toggleNightTheme() { theme = currentTheme == .night ? .normal : .night } }
mit
cb406f1c32a42cedfee3aabdfe864ec5
26.142857
132
0.686316
4.52381
false
false
false
false
kingcos/CS193P_2017
Smashtag/Smashtag/TweetTableViewCell.swift
1
1695
// // TweetTableViewCell.swift // Smashtag // // Created by 买明 on 19/03/2017. // Copyright © 2017 买明. All rights reserved. // import UIKit import Twitter class TweetTableViewCell: UITableViewCell { @IBOutlet weak var tweetProfileImageView: UIImageView! @IBOutlet weak var tweetCreatedLabel: UILabel! @IBOutlet weak var tweetUserLabel: UILabel! @IBOutlet weak var tweetTextLabel: UILabel! var tweet: Twitter.Tweet? { didSet { updateUI() } } private func updateUI() { tweetTextLabel?.text = tweet?.text tweetUserLabel?.text = tweet?.user.description if let profileImageURL = tweet?.user.profileImageURL { // Global 队列 // DispatchQueue.global(qos: .userInitiated).async { [weak self] in // if let imageData = try? Data(contentsOf: profileImageURL) { // self?.tweetProfileImageView?.image = UIImage(data: imageData) // } // } if let imageData = try? Data(contentsOf: profileImageURL) { tweetProfileImageView?.image = UIImage(data: imageData) } } else { tweetProfileImageView?.image = nil } if let created = tweet?.created { let formatter = DateFormatter() if Date().timeIntervalSince(created) > 24*60*60 { formatter.dateStyle = .short } else { formatter.dateStyle = .short } tweetCreatedLabel?.text = formatter.string(from: created) } else { tweetCreatedLabel?.text = nil } } }
mit
b331bf3edf853b184e54064fb804b933
28.508772
83
0.567776
4.991098
false
false
false
false
BalestraPatrick/Tweetometer
Carthage/Checkouts/Swifter/Sources/SwifterAppOnlyClient.swift
2
4537
// // AppOnlyClient.swift // Swifter // // Copyright (c) 2014 Matt Donnelly. // // 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 internal class AppOnlyClient: SwifterClientProtocol { var consumerKey: String var consumerSecret: String var credential: Credential? let dataEncoding: String.Encoding = .utf8 init(consumerKey: String, consumerSecret: String) { self.consumerKey = consumerKey self.consumerSecret = consumerSecret } func get(_ path: String, baseURL: TwitterURL, parameters: [String: Any], uploadProgress: HTTPRequest.UploadProgressHandler?, downloadProgress: HTTPRequest.DownloadProgressHandler?, success: HTTPRequest.SuccessHandler?, failure: HTTPRequest.FailureHandler?) -> HTTPRequest { let url = URL(string: path, relativeTo: baseURL.url) let request = HTTPRequest(url: url!, method: .GET, parameters: parameters) request.downloadProgressHandler = downloadProgress request.successHandler = success request.failureHandler = failure request.dataEncoding = self.dataEncoding if let bearerToken = self.credential?.accessToken?.key { request.headers = ["Authorization": "Bearer \(bearerToken)"]; } request.start() return request } func post(_ path: String, baseURL: TwitterURL, parameters: [String: Any], uploadProgress: HTTPRequest.UploadProgressHandler?, downloadProgress: HTTPRequest.DownloadProgressHandler?, success: HTTPRequest.SuccessHandler?, failure: HTTPRequest.FailureHandler?) -> HTTPRequest { let url = URL(string: path, relativeTo: baseURL.url) let request = HTTPRequest(url: url!, method: .POST, parameters: parameters) request.downloadProgressHandler = downloadProgress request.successHandler = success request.failureHandler = failure request.dataEncoding = self.dataEncoding if let bearerToken = self.credential?.accessToken?.key { request.headers = ["Authorization": "Bearer \(bearerToken)"]; } else { let basicCredentials = AppOnlyClient.base64EncodedCredentials(withKey: self.consumerKey, secret: self.consumerSecret) request.headers = ["Authorization": "Basic \(basicCredentials)"]; request.encodeParameters = true } request.start() return request } func delete(_ path: String, baseURL: TwitterURL, parameters: [String: Any], success: HTTPRequest.SuccessHandler?, failure: HTTPRequest.FailureHandler?) -> HTTPRequest { let url = URL(string: path, relativeTo: baseURL.url) let request = HTTPRequest(url: url!, method: .DELETE, parameters: parameters) request.successHandler = success request.failureHandler = failure request.dataEncoding = self.dataEncoding if let bearerToken = self.credential?.accessToken?.key { request.headers = ["Authorization": "Bearer \(bearerToken)"]; } request.start() return request } class func base64EncodedCredentials(withKey key: String, secret: String) -> String { let encodedKey = key.urlEncodedString() let encodedSecret = secret.urlEncodedString() let bearerTokenCredentials = "\(encodedKey):\(encodedSecret)" guard let data = bearerTokenCredentials.data(using: .utf8) else { return "" } return data.base64EncodedString(options: []) } }
mit
291929181cc25ea0ad2801ed904a97c8
36.188525
129
0.6987
4.821467
false
false
false
false
ahoppen/swift
test/Interpreter/protocol_initializers_class.swift
21
10933
// RUN: %target-run-simple-swift(-swift-version 4) // RUN: %target-run-simple-swift(-swift-version 5) // REQUIRES: executable_test import StdlibUnittest var ProtocolInitTestSuite = TestSuite("ProtocolInitClass") func mustThrow<T>(_ f: () throws -> T) { do { _ = try f() preconditionFailure("Didn't throw") } catch {} } func mustFail<T>(f: () -> T?) { if f() != nil { preconditionFailure("Didn't fail") } } enum E : Error { case X } // This is the same as the protocol_initializers.swift test, // but class-bound protocol TriviallyConstructible : class { init(x: LifetimeTracked) init(x: LifetimeTracked, throwsDuring: Bool) throws init?(x: LifetimeTracked, failsDuring: Bool) } extension TriviallyConstructible { init(x: LifetimeTracked, throwsBefore: Bool) throws { if throwsBefore { throw E.X } self.init(x: x) } init(x: LifetimeTracked, throwsAfter: Bool) throws { self.init(x: x) if throwsAfter { throw E.X } } init(x: LifetimeTracked, throwsBefore: Bool, throwsDuring: Bool) throws { if throwsBefore { throw E.X } try self.init(x: x, throwsDuring: throwsDuring) } init(x: LifetimeTracked, throwsBefore: Bool, throwsAfter: Bool) throws { if throwsBefore { throw E.X } self.init(x: x) if throwsAfter { throw E.X } } init(x: LifetimeTracked, throwsDuring: Bool, throwsAfter: Bool) throws { try self.init(x: x, throwsDuring: throwsDuring) if throwsAfter { throw E.X } } init(x: LifetimeTracked, throwsBefore: Bool, throwsDuring: Bool, throwsAfter: Bool) throws { if throwsBefore { throw E.X } try self.init(x: x, throwsDuring: throwsDuring) if throwsAfter { throw E.X } } init?(x: LifetimeTracked, failsBefore: Bool) { if failsBefore { return nil } self.init(x: x) } init?(x: LifetimeTracked, failsAfter: Bool) { self.init(x: x) if failsAfter { return nil } } init?(x: LifetimeTracked, failsBefore: Bool, failsDuring: Bool) { if failsBefore { return nil } self.init(x: x, failsDuring: failsDuring) } init?(x: LifetimeTracked, failsBefore: Bool, failsAfter: Bool) { if failsBefore { return nil } self.init(x: x) if failsAfter { return nil } } init?(x: LifetimeTracked, failsDuring: Bool, failsAfter: Bool) { self.init(x: x, failsDuring: failsDuring) if failsAfter { return nil } } init?(x: LifetimeTracked, failsBefore: Bool, failsDuring: Bool, failsAfter: Bool) { if failsBefore { return nil } self.init(x: x, failsDuring: failsDuring) if failsAfter { return nil } } } class TrivialClass : TriviallyConstructible { let tracker: LifetimeTracked // Protocol requirements required init(x: LifetimeTracked) { self.tracker = x } required convenience init(x: LifetimeTracked, throwsDuring: Bool) throws { self.init(x: x) if throwsDuring { throw E.X } } required convenience init?(x: LifetimeTracked, failsDuring: Bool) { self.init(x: x) if failsDuring { return nil } } // Class initializers delegating to protocol initializers convenience init(throwsBefore: Bool) throws { if throwsBefore { throw E.X } self.init(x: LifetimeTracked(0)) } convenience init(throwsAfter: Bool) throws { self.init(x: LifetimeTracked(0)) if throwsAfter { throw E.X } } convenience init(throwsBefore: Bool, throwsDuring: Bool) throws { if throwsBefore { throw E.X } try self.init(x: LifetimeTracked(0), throwsDuring: throwsDuring) } convenience init(throwsBefore: Bool, throwsAfter: Bool) throws { if throwsBefore { throw E.X } self.init(x: LifetimeTracked(0)) if throwsAfter { throw E.X } } convenience init(throwsDuring: Bool, throwsAfter: Bool) throws { try self.init(x: LifetimeTracked(0), throwsDuring: throwsDuring) if throwsAfter { throw E.X } } convenience init(throwsBefore: Bool, throwsDuring: Bool, throwsAfter: Bool) throws { if throwsBefore { throw E.X } try self.init(x: LifetimeTracked(0), throwsDuring: throwsDuring) if throwsAfter { throw E.X } } convenience init?(failsBefore: Bool) { if failsBefore { return nil } self.init(x: LifetimeTracked(0)) } convenience init?(failsAfter: Bool) { self.init(x: LifetimeTracked(0)) if failsAfter { return nil } } convenience init?(failsBefore: Bool, failsDuring: Bool) { if failsBefore { return nil } self.init(x: LifetimeTracked(0), failsDuring: failsDuring) } convenience init?(failsBefore: Bool, failsAfter: Bool) { if failsBefore { return nil } self.init(x: LifetimeTracked(0)) if failsAfter { return nil } } convenience init?(failsDuring: Bool, failsAfter: Bool) { self.init(x: LifetimeTracked(0), failsDuring: failsDuring) if failsAfter { return nil } } convenience init?(failsBefore: Bool, failsDuring: Bool, failsAfter: Bool) { if failsBefore { return nil } self.init(x: LifetimeTracked(0), failsDuring: failsDuring) if failsAfter { return nil } } } ProtocolInitTestSuite.test("ExtensionInit_Success") { _ = try! TrivialClass(x: LifetimeTracked(0), throwsBefore: false) _ = try! TrivialClass(x: LifetimeTracked(0), throwsAfter: false) _ = try! TrivialClass(x: LifetimeTracked(0), throwsBefore: false, throwsDuring: false) _ = try! TrivialClass(x: LifetimeTracked(0), throwsDuring: false, throwsAfter: false) _ = try! TrivialClass(x: LifetimeTracked(0), throwsBefore: false, throwsAfter: false) _ = try! TrivialClass(x: LifetimeTracked(0), throwsBefore: false, throwsDuring: false, throwsAfter: false) _ = TrivialClass(x: LifetimeTracked(0), failsBefore: false)! _ = TrivialClass(x: LifetimeTracked(0), failsAfter: false)! _ = TrivialClass(x: LifetimeTracked(0), failsBefore: false, failsDuring: false)! _ = TrivialClass(x: LifetimeTracked(0), failsDuring: false, failsAfter: false)! _ = TrivialClass(x: LifetimeTracked(0), failsBefore: false, failsAfter: false)! _ = TrivialClass(x: LifetimeTracked(0), failsBefore: false, failsDuring: false, failsAfter: false)! } ProtocolInitTestSuite.test("ClassInit_Success") { _ = try! TrivialClass(throwsBefore: false) _ = try! TrivialClass(throwsAfter: false) _ = try! TrivialClass(throwsBefore: false, throwsDuring: false) _ = try! TrivialClass(throwsDuring: false, throwsAfter: false) _ = try! TrivialClass(throwsBefore: false, throwsAfter: false) _ = try! TrivialClass(throwsBefore: false, throwsDuring: false, throwsAfter: false) _ = TrivialClass(failsBefore: false)! _ = TrivialClass(failsAfter: false)! _ = TrivialClass(failsBefore: false, failsDuring: false)! _ = TrivialClass(failsDuring: false, failsAfter: false)! _ = TrivialClass(failsBefore: false, failsAfter: false)! _ = TrivialClass(failsBefore: false, failsDuring: false, failsAfter: false)! } ProtocolInitTestSuite.test("ExtensionInit_Failure") { mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsBefore: true) } mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsAfter: true) } mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsBefore: true, throwsDuring: false) } mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsBefore: false, throwsDuring: true) } mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsDuring: true, throwsAfter: false) } mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsDuring: false, throwsAfter: true) } mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsBefore: true, throwsAfter: false) } mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsBefore: false, throwsAfter: true) } mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsBefore: true, throwsDuring: false, throwsAfter: false) } mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsBefore: false, throwsDuring: true, throwsAfter: false) } mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsBefore: false, throwsDuring: false, throwsAfter: true) } mustFail { TrivialClass(x: LifetimeTracked(0), failsBefore: true) } mustFail { TrivialClass(x: LifetimeTracked(0), failsAfter: true) } mustFail { TrivialClass(x: LifetimeTracked(0), failsBefore: true, failsDuring: false) } mustFail { TrivialClass(x: LifetimeTracked(0), failsBefore: false, failsDuring: true) } mustFail { TrivialClass(x: LifetimeTracked(0), failsDuring: true, failsAfter: false) } mustFail { TrivialClass(x: LifetimeTracked(0), failsDuring: false, failsAfter: true) } mustFail { TrivialClass(x: LifetimeTracked(0), failsBefore: true, failsAfter: false) } mustFail { TrivialClass(x: LifetimeTracked(0), failsBefore: false, failsAfter: true) } mustFail { TrivialClass(x: LifetimeTracked(0), failsBefore: true, failsDuring: false, failsAfter: false) } mustFail { TrivialClass(x: LifetimeTracked(0), failsBefore: false, failsDuring: true, failsAfter: false) } mustFail { TrivialClass(x: LifetimeTracked(0), failsBefore: false, failsDuring: false, failsAfter: true) } } ProtocolInitTestSuite.test("ClassInit_Failure") { mustThrow { try TrivialClass(throwsBefore: true) } mustThrow { try TrivialClass(throwsAfter: true) } mustThrow { try TrivialClass(throwsBefore: true, throwsDuring: false) } mustThrow { try TrivialClass(throwsBefore: false, throwsDuring: true) } mustThrow { try TrivialClass(throwsDuring: true, throwsAfter: false) } mustThrow { try TrivialClass(throwsDuring: false, throwsAfter: true) } mustThrow { try TrivialClass(throwsBefore: true, throwsAfter: false) } mustThrow { try TrivialClass(throwsBefore: false, throwsAfter: true) } mustThrow { try TrivialClass(throwsBefore: true, throwsDuring: false, throwsAfter: false) } mustThrow { try TrivialClass(throwsBefore: false, throwsDuring: true, throwsAfter: false) } mustThrow { try TrivialClass(throwsBefore: false, throwsDuring: false, throwsAfter: true) } mustFail { TrivialClass(failsBefore: true) } mustFail { TrivialClass(failsAfter: true) } mustFail { TrivialClass(failsBefore: true, failsDuring: false) } mustFail { TrivialClass(failsBefore: false, failsDuring: true) } mustFail { TrivialClass(failsDuring: true, failsAfter: false) } mustFail { TrivialClass(failsDuring: false, failsAfter: true) } mustFail { TrivialClass(failsBefore: true, failsAfter: false) } mustFail { TrivialClass(failsBefore: false, failsAfter: true) } mustFail { TrivialClass(failsBefore: true, failsDuring: false, failsAfter: false) } mustFail { TrivialClass(failsBefore: false, failsDuring: true, failsAfter: false) } mustFail { TrivialClass(failsBefore: false, failsDuring: false, failsAfter: true) } } runAllTests()
apache-2.0
5c9dd8cb262f38669ff6009d88425686
31.635821
116
0.696332
4.235955
false
false
false
false
vonox7/Kotlift
test-dest/4_stringInterpolation.swift
2
510
func x() -> String { return "return value" } func main(args: [String]) { let name = "Bob" var name2 = "Dan" print("Hello, \(name)!") print("true: \(true)") print("false: \(1 == 2)") print("function call: \(x())") print("my name is \(name) :)") print("multiple: \(name), \(name2) \(name2)") print("multiple2: \(name), \(name2) \(name2)") print("multiple3: \(name), \(name2) \(name2)") print("$123 is not a variable, $= and $ are also not a valid name") } main([])
apache-2.0
eb37a3fbfd092a6f2fff1884c6b6a69e
25.842105
71
0.535294
3.109756
false
false
false
false
velvetroom/columbus
Source/View/Basic/VGradient.swift
1
3001
import UIKit final class VGradient:UIView { class func diagonal( colourLeftBottom:UIColor, colourTopRight:UIColor) -> VGradient { let colours:[CGColor] = [ colourLeftBottom.cgColor, colourTopRight.cgColor] let locations:[NSNumber] = [ VGradient.Constants.locationStart, VGradient.Constants.locationEnd] let startPoint:CGPoint = CGPoint(x:0, y:1) let endPoint:CGPoint = CGPoint(x:1, y:0) let gradient:VGradient = VGradient( colours:colours, locations:locations, startPoint:startPoint, endPoint:endPoint) return gradient } class func horizontal( colourLeft:UIColor, colourRight:UIColor) -> VGradient { let colours:[CGColor] = [ colourLeft.cgColor, colourRight.cgColor] let locations:[NSNumber] = [ VGradient.Constants.locationStart, VGradient.Constants.locationEnd] let startPoint:CGPoint = CGPoint(x:0, y:0.5) let endPoint:CGPoint = CGPoint(x:1, y:0.5) let gradient:VGradient = VGradient( colours:colours, locations:locations, startPoint:startPoint, endPoint:endPoint) return gradient } class func vertical( colourTop:UIColor, colourBottom:UIColor) -> VGradient { let colours:[CGColor] = [ colourTop.cgColor, colourBottom.cgColor] let locations:[NSNumber] = [ VGradient.Constants.locationStart, VGradient.Constants.locationEnd] let startPoint:CGPoint = CGPoint(x:0.5, y:0) let endPoint:CGPoint = CGPoint(x:0.5, y:1) let gradient:VGradient = VGradient( colours:colours, locations:locations, startPoint:startPoint, endPoint:endPoint) return gradient } private init( colours:[CGColor], locations:[NSNumber], startPoint:CGPoint, endPoint:CGPoint) { super.init(frame:CGRect.zero) clipsToBounds = true backgroundColor = UIColor.clear translatesAutoresizingMaskIntoConstraints = false isUserInteractionEnabled = false guard let gradientLayer:CAGradientLayer = self.layer as? CAGradientLayer else { return } gradientLayer.startPoint = startPoint gradientLayer.endPoint = endPoint gradientLayer.locations = locations gradientLayer.colors = colours } required init?(coder:NSCoder) { return nil } override open class var layerClass:AnyClass { get { return CAGradientLayer.self } } }
mit
1c479b011063fd6fc285690abf780529
24.87069
78
0.552816
5.246503
false
false
false
false
DataArt/SmartSlides
PresentatorS/Extensions/AFDateExtension.swift
1
30480
// // AFDateExtension.swift // // Version 3.1.1 // // Created by Melvin Rivera on 7/15/14. // Copyright (c) 2014. All rights reserved. // import Foundation // DotNet: "/Date(1268123281843)/" let DefaultFormat = "EEE MMM dd HH:mm:ss Z yyyy" let RSSFormat = "EEE, d MMM yyyy HH:mm:ss ZZZ" // "Fri, 09 Sep 2011 15:26:08 +0200" let AltRSSFormat = "d MMM yyyy HH:mm:ss ZZZ" // "09 Sep 2011 15:26:08 +0200" public enum ISO8601Format: String { case Year = "yyyy" // 1997 case YearMonth = "yyyy-MM" // 1997-07 case Date = "yyyy-MM-dd" // 1997-07-16 case DateTime = "yyyy-MM-dd'T'HH:mmZ" // 1997-07-16T19:20+01:00 case DateTimeSec = "yyyy-MM-dd'T'HH:mm:ssZ" // 1997-07-16T19:20:30+01:00 case DateTimeMilliSec = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" // 1997-07-16T19:20:30.45+01:00 init(dateString:String) { switch dateString.characters.count { case 4: self = ISO8601Format(rawValue: ISO8601Format.Year.rawValue)! case 7: self = ISO8601Format(rawValue: ISO8601Format.YearMonth.rawValue)! case 10: self = ISO8601Format(rawValue: ISO8601Format.Date.rawValue)! case 22: self = ISO8601Format(rawValue: ISO8601Format.DateTime.rawValue)! case 25: self = ISO8601Format(rawValue: ISO8601Format.DateTimeSec.rawValue)! default:// 28: self = ISO8601Format(rawValue: ISO8601Format.DateTimeMilliSec.rawValue)! } } } public enum DateFormat { case ISO8601(ISO8601Format?), DotNet, RSS, AltRSS, Custom(String) } public extension NSDate { // MARK: Intervals In Seconds private class func minuteInSeconds() -> Double { return 60 } private class func hourInSeconds() -> Double { return 3600 } private class func dayInSeconds() -> Double { return 86400 } private class func weekInSeconds() -> Double { return 604800 } private class func yearInSeconds() -> Double { return 31556926 } // MARK: Components private class func componentFlags() -> NSCalendarUnit { return [NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day, NSCalendarUnit.WeekOfYear, NSCalendarUnit.Hour, NSCalendarUnit.Minute, NSCalendarUnit.Second, NSCalendarUnit.Weekday, NSCalendarUnit.WeekdayOrdinal, NSCalendarUnit.WeekOfYear] } private class func components(fromDate fromDate: NSDate) -> NSDateComponents! { return NSCalendar.currentCalendar().components(NSDate.componentFlags(), fromDate: fromDate) } private func components() -> NSDateComponents { return NSDate.components(fromDate: self)! } // MARK: Date From String /** Creates a date based on a string and a formatter type. You can ise .ISO8601(nil) to for deducting an ISO8601Format automatically. - Parameter fromString Date string i.e. "16 July 1972 6:12:00". - Parameter format The Date Formatter type can be .ISO8601(ISO8601Format?), .DotNet, .RSS, .AltRSS or Custom(String). - Returns A new date */ convenience init(fromString string: String, format:DateFormat) { if string.isEmpty { self.init() return } let string = string as NSString switch format { case .DotNet: let startIndex = string.rangeOfString("(").location + 1 let endIndex = string.rangeOfString(")").location let range = NSRange(location: startIndex, length: endIndex-startIndex) let milliseconds = (string.substringWithRange(range) as NSString).longLongValue let interval = NSTimeInterval(milliseconds / 1000) self.init(timeIntervalSince1970: interval) case .ISO8601(let isoFormat): let dateFormat = (isoFormat != nil) ? isoFormat! : ISO8601Format(dateString: string as String) let formatter = NSDate.formatter(format: dateFormat.rawValue) formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") formatter.timeZone = NSTimeZone.localTimeZone() formatter.dateFormat = dateFormat.rawValue if let date = formatter.dateFromString(string as String) { self.init(timeInterval:0, sinceDate:date) } else { self.init() } case .RSS: var s = string if string.hasSuffix("Z") { s = s.substringToIndex(s.length-1) + "GMT" } let formatter = NSDate.formatter(format: RSSFormat) if let date = formatter.dateFromString(string as String) { self.init(timeInterval:0, sinceDate:date) } else { self.init() } case .AltRSS: var s = string if string.hasSuffix("Z") { s = s.substringToIndex(s.length-1) + "GMT" } let formatter = NSDate.formatter(format: AltRSSFormat) if let date = formatter.dateFromString(string as String) { self.init(timeInterval:0, sinceDate:date) } else { self.init() } case .Custom(let dateFormat): let formatter = NSDate.formatter(format: dateFormat) if let date = formatter.dateFromString(string as String) { self.init(timeInterval:0, sinceDate:date) } else { self.init() } } } // MARK: Comparing Dates /** Returns true if dates are equal while ignoring time. - Parameter date: The Date to compare. */ func isEqualToDateIgnoringTime(date: NSDate) -> Bool { let comp1 = NSDate.components(fromDate: self) let comp2 = NSDate.components(fromDate: date) return ((comp1.year == comp2.year) && (comp1.month == comp2.month) && (comp1.day == comp2.day)) } /** Returns Returns true if date is today. */ func isToday() -> Bool { return self.isEqualToDateIgnoringTime(NSDate()) } /** Returns true if date is tomorrow. */ func isTomorrow() -> Bool { return self.isEqualToDateIgnoringTime(NSDate().dateByAddingDays(1)) } /** Returns true if date is yesterday. */ func isYesterday() -> Bool { return self.isEqualToDateIgnoringTime(NSDate().dateBySubtractingDays(1)) } /** Returns true if date are in the same week. - Parameter date: The date to compare. */ func isSameWeekAsDate(date: NSDate) -> Bool { let comp1 = NSDate.components(fromDate: self) let comp2 = NSDate.components(fromDate: date) // Must be same week. 12/31 and 1/1 will both be week "1" if they are in the same week if comp1.weekOfYear != comp2.weekOfYear { return false } // Must have a time interval under 1 week return abs(self.timeIntervalSinceDate(date)) < NSDate.weekInSeconds() } /** Returns true if date is this week. */ func isThisWeek() -> Bool { return self.isSameWeekAsDate(NSDate()) } /** Returns true if date is next week. */ func isNextWeek() -> Bool { let interval: NSTimeInterval = NSDate().timeIntervalSinceReferenceDate + NSDate.weekInSeconds() let date = NSDate(timeIntervalSinceReferenceDate: interval) return self.isSameWeekAsDate(date) } /** Returns true if date is last week. */ func isLastWeek() -> Bool { let interval: NSTimeInterval = NSDate().timeIntervalSinceReferenceDate - NSDate.weekInSeconds() let date = NSDate(timeIntervalSinceReferenceDate: interval) return self.isSameWeekAsDate(date) } /** Returns true if dates are in the same year. - Parameter date: The date to compare. */ func isSameYearAsDate(date: NSDate) -> Bool { let comp1 = NSDate.components(fromDate: self) let comp2 = NSDate.components(fromDate: date) return (comp1.year == comp2.year) } /** Returns true if date is this year. */ func isThisYear() -> Bool { return self.isSameYearAsDate(NSDate()) } /** Returns true if date is next year. */ func isNextYear() -> Bool { let comp1 = NSDate.components(fromDate: self) let comp2 = NSDate.components(fromDate: NSDate()) return (comp1.year == comp2.year + 1) } /** Returns true if date is last year. */ func isLastYear() -> Bool { let comp1 = NSDate.components(fromDate: self) let comp2 = NSDate.components(fromDate: NSDate()) return (comp1.year == comp2.year - 1) } /** Returns true if date is earlier than date. - Parameter date: The date to compare. */ func isEarlierThanDate(date: NSDate) -> Bool { return self.earlierDate(date) == self } /** Returns true if date is later than date. - Parameter date: The date to compare. */ func isLaterThanDate(date: NSDate) -> Bool { return self.laterDate(date) == self } /** Returns true if date is in future. */ func isInFuture() -> Bool { return self.isLaterThanDate(NSDate()) } /** Returns true if date is in past. */ func isInPast() -> Bool { return self.isEarlierThanDate(NSDate()) } // MARK: Adjusting Dates /** Creates a new date by a adding days. - Parameter days: The number of days to add. - Returns A new date object. */ func dateByAddingDays(days: Int) -> NSDate { let dateComp = NSDateComponents() dateComp.day = days return NSCalendar.currentCalendar().dateByAddingComponents(dateComp, toDate: self, options: NSCalendarOptions(rawValue: 0))! } /** Creates a new date by a substracting days. - Parameter days: The number of days to substract. - Returns A new date object. */ func dateBySubtractingDays(days: Int) -> NSDate { let dateComp = NSDateComponents() dateComp.day = (days * -1) return NSCalendar.currentCalendar().dateByAddingComponents(dateComp, toDate: self, options: NSCalendarOptions(rawValue: 0))! } /** Creates a new date by a adding hours. - Parameter days: The number of hours to add. - Returns A new date object. */ func dateByAddingHours(hours: Int) -> NSDate { let dateComp = NSDateComponents() dateComp.hour = hours return NSCalendar.currentCalendar().dateByAddingComponents(dateComp, toDate: self, options: NSCalendarOptions(rawValue: 0))! } /** Creates a new date by substracting hours. - Parameter days: The number of hours to substract. - Returns A new date object. */ func dateBySubtractingHours(hours: Int) -> NSDate { let dateComp = NSDateComponents() dateComp.hour = (hours * -1) return NSCalendar.currentCalendar().dateByAddingComponents(dateComp, toDate: self, options: NSCalendarOptions(rawValue: 0))! } /** Creates a new date by adding minutes. - Parameter days: The number of minutes to add. - Returns A new date object. */ func dateByAddingMinutes(minutes: Int) -> NSDate { let dateComp = NSDateComponents() dateComp.minute = minutes return NSCalendar.currentCalendar().dateByAddingComponents(dateComp, toDate: self, options: NSCalendarOptions(rawValue: 0))! } /** Creates a new date by substracting minutes. - Parameter days: The number of minutes to add. - Returns A new date object. */ func dateBySubtractingMinutes(minutes: Int) -> NSDate { let dateComp = NSDateComponents() dateComp.minute = (minutes * -1) return NSCalendar.currentCalendar().dateByAddingComponents(dateComp, toDate: self, options: NSCalendarOptions(rawValue: 0))! } /** Creates a new date by adding seconds. - Parameter seconds: The number of seconds to add. - Returns A new date object. */ func dateByAddingSeconds(seconds: Int) -> NSDate { let dateComp = NSDateComponents() dateComp.second = seconds return NSCalendar.currentCalendar().dateByAddingComponents(dateComp, toDate: self, options: NSCalendarOptions(rawValue: 0))! } /** Creates a new date by substracting seconds. - Parameter days: The number of seconds to substract. - Returns A new date object. */ func dateBySubtractingSeconds(seconds: Int) -> NSDate { let dateComp = NSDateComponents() dateComp.second = (seconds * -1) return NSCalendar.currentCalendar().dateByAddingComponents(dateComp, toDate: self, options: NSCalendarOptions(rawValue: 0))! } /** Creates a new date from the start of the day. - Returns A new date object. */ func dateAtStartOfDay() -> NSDate { let components = self.components() components.hour = 0 components.minute = 0 components.second = 0 return NSCalendar.currentCalendar().dateFromComponents(components)! } /** Creates a new date from the end of the day. - Returns A new date object. */ func dateAtEndOfDay() -> NSDate { let components = self.components() components.hour = 23 components.minute = 59 components.second = 59 return NSCalendar.currentCalendar().dateFromComponents(components)! } /** Creates a new date from the start of the week. - Returns A new date object. */ func dateAtStartOfWeek() -> NSDate { let flags :NSCalendarUnit = [NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.WeekOfYear, NSCalendarUnit.Weekday] let components = NSCalendar.currentCalendar().components(flags, fromDate: self) components.weekday = NSCalendar.currentCalendar().firstWeekday components.hour = 0 components.minute = 0 components.second = 0 return NSCalendar.currentCalendar().dateFromComponents(components)! } /** Creates a new date from the end of the week. - Returns A new date object. */ func dateAtEndOfWeek() -> NSDate { let flags :NSCalendarUnit = [NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.WeekOfYear, NSCalendarUnit.Weekday] let components = NSCalendar.currentCalendar().components(flags, fromDate: self) components.weekday = NSCalendar.currentCalendar().firstWeekday + 6 components.hour = 0 components.minute = 0 components.second = 0 return NSCalendar.currentCalendar().dateFromComponents(components)! } /** Creates a new date from the first day of the month - Returns A new date object. */ func dateAtTheStartOfMonth() -> NSDate { //Create the date components let components = self.components() components.day = 1 //Builds the first day of the month let firstDayOfMonthDate :NSDate = NSCalendar.currentCalendar().dateFromComponents(components)! return firstDayOfMonthDate } /** Creates a new date from the last day of the month - Returns A new date object. */ func dateAtTheEndOfMonth() -> NSDate { //Create the date components let components = self.components() //Set the last day of this month components.month += 1 components.day = 0 //Builds the first day of the month let lastDayOfMonth :NSDate = NSCalendar.currentCalendar().dateFromComponents(components)! return lastDayOfMonth } /** Creates a new date based on tomorrow. - Returns A new date object. */ class func tomorrow() -> NSDate { return NSDate().dateByAddingDays(1).dateAtStartOfDay() } /** Creates a new date based on yesterdat. - Returns A new date object. */ class func yesterday() -> NSDate { return NSDate().dateBySubtractingDays(1).dateAtStartOfDay() } // MARK: Retrieving Intervals /** Gets the number of seconds after a date. - Parameter date: the date to compare. - Returns The number of seconds */ func secondsAfterDate(date: NSDate) -> Int { return Int(self.timeIntervalSinceDate(date)) } /** Gets the number of seconds before a date. - Parameter date: The date to compare. - Returns The number of seconds */ func secondsBeforeDate(date: NSDate) -> Int { return Int(date.timeIntervalSinceDate(self)) } /** Gets the number of minutes after a date. - Parameter date: the date to compare. - Returns The number of minutes */ func minutesAfterDate(date: NSDate) -> Int { let interval = self.timeIntervalSinceDate(date) return Int(interval / NSDate.minuteInSeconds()) } /** Gets the number of minutes before a date. - Parameter date: The date to compare. - Returns The number of minutes */ func minutesBeforeDate(date: NSDate) -> Int { let interval = date.timeIntervalSinceDate(self) return Int(interval / NSDate.minuteInSeconds()) } /** Gets the number of hours after a date. - Parameter date: The date to compare. - Returns The number of hours */ func hoursAfterDate(date: NSDate) -> Int { let interval = self.timeIntervalSinceDate(date) return Int(interval / NSDate.hourInSeconds()) } /** Gets the number of hours before a date. - Parameter date: The date to compare. - Returns The number of hours */ func hoursBeforeDate(date: NSDate) -> Int { let interval = date.timeIntervalSinceDate(self) return Int(interval / NSDate.hourInSeconds()) } /** Gets the number of days after a date. - Parameter date: The date to compare. - Returns The number of days */ func daysAfterDate(date: NSDate) -> Int { let interval = self.timeIntervalSinceDate(date) return Int(interval / NSDate.dayInSeconds()) } /** Gets the number of days before a date. - Parameter date: The date to compare. - Returns The number of days */ func daysBeforeDate(date: NSDate) -> Int { let interval = date.timeIntervalSinceDate(self) return Int(interval / NSDate.dayInSeconds()) } // MARK: Decomposing Dates /** Returns the nearest hour. */ func nearestHour () -> Int { let halfHour = NSDate.minuteInSeconds() * 30 var interval = self.timeIntervalSinceReferenceDate if self.seconds() < 30 { interval -= halfHour } else { interval += halfHour } let date = NSDate(timeIntervalSinceReferenceDate: interval) return date.hour() } /** Returns the year component. */ func year () -> Int { return self.components().year } /** Returns the month component. */ func month () -> Int { return self.components().month } /** Returns the week of year component. */ func week () -> Int { return self.components().weekOfYear } /** Returns the day component. */ func day () -> Int { return self.components().day } /** Returns the hour component. */ func hour () -> Int { return self.components().hour } /** Returns the minute component. */ func minute () -> Int { return self.components().minute } /** Returns the seconds component. */ func seconds () -> Int { return self.components().second } /** Returns the weekday component. */ func weekday () -> Int { return self.components().weekday } /** Returns the nth days component. e.g. 2nd Tuesday of the month is 2. */ func nthWeekday () -> Int { return self.components().weekdayOrdinal } /** Returns the days of the month. */ func monthDays () -> Int { return NSCalendar.currentCalendar().rangeOfUnit(NSCalendarUnit.Day, inUnit: NSCalendarUnit.Month, forDate: self).length } /** Returns the first day of the week. */ func firstDayOfWeek () -> Int { let distanceToStartOfWeek = NSDate.dayInSeconds() * Double(self.components().weekday - 1) let interval: NSTimeInterval = self.timeIntervalSinceReferenceDate - distanceToStartOfWeek return NSDate(timeIntervalSinceReferenceDate: interval).day() } /** Returns the last day of the week. */ func lastDayOfWeek () -> Int { let distanceToStartOfWeek = NSDate.dayInSeconds() * Double(self.components().weekday - 1) let distanceToEndOfWeek = NSDate.dayInSeconds() * Double(7) let interval: NSTimeInterval = self.timeIntervalSinceReferenceDate - distanceToStartOfWeek + distanceToEndOfWeek return NSDate(timeIntervalSinceReferenceDate: interval).day() } /** Returns true if a weekday. */ func isWeekday() -> Bool { return !self.isWeekend() } /** Returns true if weekend. */ func isWeekend() -> Bool { let range = NSCalendar.currentCalendar().maximumRangeOfUnit(NSCalendarUnit.Weekday) return (self.weekday() == range.location || self.weekday() == range.length) } // MARK: To String /** A string representation using short date and time style. */ func toString() -> String { return self.toString(dateStyle: .ShortStyle, timeStyle: .ShortStyle, doesRelativeDateFormatting: false) } /** A string representation based on a format. - Parameter format: The format of date can be .ISO8601(.ISO8601Format?), .DotNet, .RSS, .AltRSS or Custom(FormatString). - Returns The date string representation */ func toString(format format: DateFormat) -> String { var dateFormat: String switch format { case .DotNet: let offset = NSTimeZone.defaultTimeZone().secondsFromGMT / 3600 let nowMillis = 1000 * self.timeIntervalSince1970 return "/Date(\(nowMillis)\(offset))/" case .ISO8601(let isoFormat): dateFormat = (isoFormat != nil) ? isoFormat!.rawValue : ISO8601Format.DateTimeMilliSec.rawValue case .RSS: dateFormat = RSSFormat case .AltRSS: dateFormat = AltRSSFormat case .Custom(let string): dateFormat = string } let formatter = NSDate.formatter(format: dateFormat) return formatter.stringFromDate(self) } /** A string representation based on custom style. - Parameter dateStyle: The date style to use. - Parameter timeStyle: The time style to use. - Parameter doesRelativeDateFormatting: Enables relative date formatting. - Returns A string representation of the date. */ func toString(dateStyle dateStyle: NSDateFormatterStyle, timeStyle: NSDateFormatterStyle, doesRelativeDateFormatting: Bool = false) -> String { let formatter = NSDate.formatter(dateStyle: dateStyle, timeStyle: timeStyle, doesRelativeDateFormatting: doesRelativeDateFormatting) return formatter.stringFromDate(self) } /** A string representation based on a relative time language. i.e. just now, 1 minute ago etc.. */ func relativeTimeToString() -> String { let time = self.timeIntervalSince1970 let now = NSDate().timeIntervalSince1970 let seconds = now - time let minutes = round(seconds/60) let hours = round(minutes/60) let days = round(hours/24) if seconds < 10 { return NSLocalizedString("just now", comment: "Show the relative time from a date") } else if seconds < 60 { let relativeTime = NSLocalizedString("%.f seconds ago", comment: "Show the relative time from a date") return String(format: relativeTime, seconds) } if minutes < 60 { if minutes == 1 { return NSLocalizedString("1 minute ago", comment: "Show the relative time from a date") } else { let relativeTime = NSLocalizedString("%.f minutes ago", comment: "Show the relative time from a date") return String(format: relativeTime, minutes) } } if hours < 24 { if hours == 1 { return NSLocalizedString("1 hour ago", comment: "Show the relative time from a date") } else { let relativeTime = NSLocalizedString("%.f hours ago", comment: "Show the relative time from a date") return String(format: relativeTime, hours) } } if days < 7 { if days == 1 { return NSLocalizedString("1 day ago", comment: "Show the relative time from a date") } else { let relativeTime = NSLocalizedString("%.f days ago", comment: "Show the relative time from a date") return String(format: relativeTime, days) } } return self.toString() } /** A string representation of the weekday. */ func weekdayToString() -> String { let formatter = NSDate.formatter() return formatter.weekdaySymbols[self.weekday()-1] as String } /** A short string representation of the weekday. */ func shortWeekdayToString() -> String { let formatter = NSDate.formatter() return formatter.shortWeekdaySymbols[self.weekday()-1] as String } /** A very short string representation of the weekday. - Returns String */ func veryShortWeekdayToString() -> String { let formatter = NSDate.formatter() return formatter.veryShortWeekdaySymbols[self.weekday()-1] as String } /** A string representation of the month. - Returns String */ func monthToString() -> String { let formatter = NSDate.formatter() return formatter.monthSymbols[self.month()-1] as String } /** A short string representation of the month. - Returns String */ func shortMonthToString() -> String { let formatter = NSDate.formatter() return formatter.shortMonthSymbols[self.month()-1] as String } /** A very short string representation of the month. - Returns String */ func veryShortMonthToString() -> String { let formatter = NSDate.formatter() return formatter.veryShortMonthSymbols[self.month()-1] as String } // MARK: Static Cached Formatters /** Returns a cached static array of NSDateFormatters so that thy are only created once. */ private class func sharedDateFormatters() -> [String: NSDateFormatter] { struct Static { static var formatters: [String: NSDateFormatter]? = nil static var once: dispatch_once_t = 0 } dispatch_once(&Static.once) { Static.formatters = [String: NSDateFormatter]() } return Static.formatters! } /** Returns a cached formatter based on the format, timeZone and locale. Formatters are cached in a singleton array using hashkeys generated by format, timeZone and locale. - Parameter format: The format to use. - Parameter timeZone: The time zone to use, defaults to the local time zone. - Parameter locale: The locale to use, defaults to the current locale - Returns The date formatter. */ private class func formatter(format format:String = DefaultFormat, timeZone: NSTimeZone = NSTimeZone.localTimeZone(), locale: NSLocale = NSLocale.currentLocale()) -> NSDateFormatter { let hashKey = "\(format.hashValue)\(timeZone.hashValue)\(locale.hashValue)" var formatters = NSDate.sharedDateFormatters() if let cachedDateFormatter = formatters[hashKey] { return cachedDateFormatter } else { let formatter = NSDateFormatter() formatter.dateFormat = format formatter.timeZone = timeZone formatter.locale = locale formatters[hashKey] = formatter return formatter } } /** Returns a cached formatter based on date style, time style and relative date. Formatters are cached in a singleton array using hashkeys generated by date style, time style, relative date, timeZone and locale. - Parameter dateStyle: The date style to use. - Parameter timeStyle: The time style to use. - Parameter doesRelativeDateFormatting: Enables relative date formatting. - Parameter timeZone: The time zone to use. - Parameter locale: The locale to use. - Returns The date formatter. */ private class func formatter(dateStyle dateStyle: NSDateFormatterStyle, timeStyle: NSDateFormatterStyle, doesRelativeDateFormatting: Bool, timeZone: NSTimeZone = NSTimeZone.localTimeZone(), locale: NSLocale = NSLocale.currentLocale()) -> NSDateFormatter { var formatters = NSDate.sharedDateFormatters() let hashKey = "\(dateStyle.hashValue)\(timeStyle.hashValue)\(doesRelativeDateFormatting.hashValue)\(timeZone.hashValue)\(locale.hashValue)" if let cachedDateFormatter = formatters[hashKey] { return cachedDateFormatter } else { let formatter = NSDateFormatter() formatter.dateStyle = dateStyle formatter.timeStyle = timeStyle formatter.doesRelativeDateFormatting = doesRelativeDateFormatting formatter.timeZone = timeZone formatter.locale = locale formatters[hashKey] = formatter return formatter } } }
mit
cb8e5878f9a345839d116809fe175eed
31.255026
308
0.614993
4.848871
false
false
false
false
iOS-mamu/SS
P/Pods/PSOperations/PSOperations/PushCapability-OSX.swift
1
2070
// // PushCapability-OSX.swift // PSOperations // // Created by Dev Team on 10/4/15. // Copyright © 2015 Pluralsight. All rights reserved. // #if os(OSX) import Cocoa public struct Push: CapabilityType { public static func didReceiveToken(token: NSData) { authorizer.completeAuthorization(token: token, error: nil) } public static func didFailRegistration(error: NSError) { authorizer.completeAuthorization(token: nil, error: error) } public static let name = "Push" private let types: NSRemoteNotificationType public init(types: NSRemoteNotificationType) { self.types = types } public func requestStatus(_ completion: @escaping (CapabilityStatus) -> Void) { if let _ = authorizer.token { completion(.authorized) } else { completion(.notDetermined) } } public func authorize(_ completion: @escaping (CapabilityStatus) -> Void) { authorizer.authorize(types: types, completion: completion) } } private let authorizer = PushAuthorizer() fileprivate class PushAuthorizer { var token: NSData? var completion: ((CapabilityStatus) -> Void)? func authorize(types: NSRemoteNotificationType, completion: @escaping (CapabilityStatus) -> Void) { guard self.completion == nil else { fatalError("Cannot request push authorization while a request is already in progress") } self.completion = completion NSApplication.shared().registerForRemoteNotifications(matching: types) } fileprivate func completeAuthorization(token: NSData?, error: NSError?) { self.token = token guard let completion = self.completion else { return } self.completion = nil if let _ = self.token { completion(.authorized) } else if let error = error { completion(.error(error)) } else { completion(.notDetermined) } } } #endif
mit
7d92d54396d7614d3a7ae8ec957c226f
25.525641
103
0.625423
4.879717
false
false
false
false
adrfer/swift
stdlib/public/core/ArrayBuffer.swift
2
16674
//===--- ArrayBuffer.swift - Dynamic storage for Swift Array --------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This is the class that implements the storage and object management for // Swift Array. // //===----------------------------------------------------------------------===// #if _runtime(_ObjC) import SwiftShims internal typealias _ArrayBridgeStorage = _BridgeStorage<_ContiguousArrayStorageBase, _NSArrayCoreType> public struct _ArrayBuffer<Element> : _ArrayBufferType { /// Create an empty buffer. public init() { _storage = _ArrayBridgeStorage(native: _emptyArrayStorage) } public init(nsArray: _NSArrayCoreType) { _sanityCheck(_isClassOrObjCExistential(Element.self)) _storage = _ArrayBridgeStorage(objC: nsArray) } /// Returns an `_ArrayBuffer<U>` containing the same elements. /// /// - Requires: The elements actually have dynamic type `U`, and `U` /// is a class or `@objc` existential. @warn_unused_result func castToBufferOf<U>(_: U.Type) -> _ArrayBuffer<U> { _sanityCheck(_isClassOrObjCExistential(Element.self)) _sanityCheck(_isClassOrObjCExistential(U.self)) return _ArrayBuffer<U>(storage: _storage) } /// The spare bits that are set when a native array needs deferred /// element type checking. var deferredTypeCheckMask : Int { return 1 } /// Returns an `_ArrayBuffer<U>` containing the same elements, /// deferring checking each element's `U`-ness until it is accessed. /// /// - Requires: `U` is a class or `@objc` existential derived from `Element`. @warn_unused_result func downcastToBufferWithDeferredTypeCheckOf<U>( _: U.Type ) -> _ArrayBuffer<U> { _sanityCheck(_isClassOrObjCExistential(Element.self)) _sanityCheck(_isClassOrObjCExistential(U.self)) // FIXME: can't check that U is derived from Element pending // <rdar://problem/19915280> generic metatype casting doesn't work // _sanityCheck(U.self is Element.Type) return _ArrayBuffer<U>( storage: _ArrayBridgeStorage( native: _native._storage, bits: deferredTypeCheckMask)) } var needsElementTypeCheck: Bool { // NSArray's need an element typecheck when the element type isn't AnyObject return !_isNativeTypeChecked && !(AnyObject.self is Element.Type) } //===--- private --------------------------------------------------------===// internal init(storage: _ArrayBridgeStorage) { _storage = storage } internal var _storage: _ArrayBridgeStorage } extension _ArrayBuffer { /// Adopt the storage of `source`. public init(_ source: NativeBuffer, shiftedToStartIndex: Int) { _sanityCheck(shiftedToStartIndex == 0, "shiftedToStartIndex must be 0") _storage = _ArrayBridgeStorage(native: source._storage) } /// `true`, if the array is native and does not need a deferred type check. var arrayPropertyIsNativeTypeChecked : Bool { return _isNativeTypeChecked } /// Returns `true` iff this buffer's storage is uniquely-referenced. @warn_unused_result mutating func isUniquelyReferenced() -> Bool { if !_isClassOrObjCExistential(Element.self) { return _storage.isUniquelyReferenced_native_noSpareBits() } return _storage.isUniquelyReferencedNative() && _isNative } /// Returns `true` iff this buffer's storage is either /// uniquely-referenced or pinned. @warn_unused_result mutating func isUniquelyReferencedOrPinned() -> Bool { if !_isClassOrObjCExistential(Element.self) { return _storage.isUniquelyReferencedOrPinned_native_noSpareBits() } return _storage.isUniquelyReferencedOrPinnedNative() && _isNative } /// Convert to an NSArray. /// /// - Precondition: `_isBridgedToObjectiveC(Element.self)`. /// O(1) if the element type is bridged verbatim, O(N) otherwise. @warn_unused_result public func _asCocoaArray() -> _NSArrayCoreType { _sanityCheck( _isBridgedToObjectiveC(Element.self), "Array element type is not bridged to Objective-C") return _fastPath(_isNative) ? _native._asCocoaArray() : _nonNative } /// If this buffer is backed by a uniquely-referenced mutable /// `_ContiguousArrayBuffer` that can be grown in-place to allow the self /// buffer store minimumCapacity elements, returns that buffer. /// Otherwise, returns `nil`. @warn_unused_result public mutating func requestUniqueMutableBackingBuffer(minimumCapacity: Int) -> NativeBuffer? { if _fastPath(isUniquelyReferenced()) { let b = _native if _fastPath(b.capacity >= minimumCapacity) { return b } } return nil } @warn_unused_result public mutating func isMutableAndUniquelyReferenced() -> Bool { return isUniquelyReferenced() } @warn_unused_result public mutating func isMutableAndUniquelyReferencedOrPinned() -> Bool { return isUniquelyReferencedOrPinned() } /// If this buffer is backed by a `_ContiguousArrayBuffer` /// containing the same number of elements as `self`, return it. /// Otherwise, return `nil`. @warn_unused_result public func requestNativeBuffer() -> NativeBuffer? { if !_isClassOrObjCExistential(Element.self) { return _native } return _fastPath(_storage.isNative) ? _native : nil } // We have two versions of type check: one that takes a range and the other // checks one element. The reason for this is that the ARC optimizer does not // handle loops atm. and so can get blocked by the presence of a loop (over // the range). This loop is not necessary for a single element access. @inline(never) internal func _typeCheckSlowPath(index: Int) { if _fastPath(_isNative) { let element: AnyObject = castToBufferOf(AnyObject.self)._native[index] _precondition( element is Element, "Down-casted Array element failed to match the target type") } else { let ns = _nonNative _precondition( ns.objectAtIndex(index) is Element, "NSArray element failed to match the Swift Array Element type") } } func _typeCheck(subRange: Range<Int>) { if !_isClassOrObjCExistential(Element.self) { return } if _slowPath(needsElementTypeCheck) { // Could be sped up, e.g. by using // enumerateObjectsAtIndexes:options:usingBlock: in the // non-native case. for i in subRange { _typeCheckSlowPath(i) } } } /// Copy the given subRange of this buffer into uninitialized memory /// starting at target. Return a pointer past-the-end of the /// just-initialized memory. public func _uninitializedCopy( subRange: Range<Int>, target: UnsafeMutablePointer<Element> ) -> UnsafeMutablePointer<Element> { _typeCheck(subRange) if _fastPath(_isNative) { return _native._uninitializedCopy(subRange, target: target) } let nonNative = _nonNative let nsSubRange = SwiftShims._SwiftNSRange( location:subRange.startIndex, length: subRange.endIndex - subRange.startIndex) let buffer = UnsafeMutablePointer<AnyObject>(target) // Copies the references out of the NSArray without retaining them nonNative.getObjects(buffer, range: nsSubRange) // Make another pass to retain the copied objects var result = target for _ in subRange { result.initialize(result.memory) result += 1 } return result } /// Return a `_SliceBuffer` containing the given `subRange` of values /// from this buffer. public subscript(subRange: Range<Int>) -> _SliceBuffer<Element> { get { _typeCheck(subRange) if _fastPath(_isNative) { return _native[subRange] } // Look for contiguous storage in the NSArray let nonNative = self._nonNative let cocoa = _CocoaArrayWrapper(nonNative) let cocoaStorageBaseAddress = cocoa.contiguousStorage(self.indices) if cocoaStorageBaseAddress != nil { return _SliceBuffer( owner: nonNative, subscriptBaseAddress: UnsafeMutablePointer(cocoaStorageBaseAddress), indices: subRange, hasNativeBuffer: false) } // No contiguous storage found; we must allocate let subRangeCount = subRange.count let result = _ContiguousArrayBuffer<Element>( count: subRangeCount, minimumCapacity: 0) // Tell Cocoa to copy the objects into our storage cocoa.buffer.getObjects( UnsafeMutablePointer(result.firstElementAddress), range: _SwiftNSRange( location: subRange.startIndex, length: subRangeCount)) return _SliceBuffer(result, shiftedToStartIndex: subRange.startIndex) } set { fatalError("not implemented") } } public var _unconditionalMutableSubscriptBaseAddress: UnsafeMutablePointer<Element> { _sanityCheck(_isNative, "must be a native buffer") return _native.firstElementAddress } /// If the elements are stored contiguously, a pointer to the first /// element. Otherwise, `nil`. public var firstElementAddress: UnsafeMutablePointer<Element> { if (_fastPath(_isNative)) { return _native.firstElementAddress } return nil } /// The number of elements the buffer stores. public var count: Int { @inline(__always) get { return _fastPath(_isNative) ? _native.count : _nonNative.count } set { _sanityCheck(_isNative, "attempting to update count of Cocoa array") _native.count = newValue } } /// Traps if an inout violation is detected or if the buffer is /// native and the subscript is out of range. /// /// wasNative == _isNative in the absence of inout violations. /// Because the optimizer can hoist the original check it might have /// been invalidated by illegal user code. internal func _checkInoutAndNativeBounds(index: Int, wasNative: Bool) { _precondition( _isNative == wasNative, "inout rules were violated: the array was overwritten") if _fastPath(wasNative) { _native._checkValidSubscript(index) } } // TODO: gyb this /// Traps if an inout violation is detected or if the buffer is /// native and typechecked and the subscript is out of range. /// /// wasNativeTypeChecked == _isNativeTypeChecked in the absence of /// inout violations. Because the optimizer can hoist the original /// check it might have been invalidated by illegal user code. internal func _checkInoutAndNativeTypeCheckedBounds( index: Int, wasNativeTypeChecked: Bool ) { _precondition( _isNativeTypeChecked == wasNativeTypeChecked, "inout rules were violated: the array was overwritten") if _fastPath(wasNativeTypeChecked) { _native._checkValidSubscript(index) } } /// The number of elements the buffer can store without reallocation. public var capacity: Int { return _fastPath(_isNative) ? _native.capacity : _nonNative.count } @inline(__always) @warn_unused_result func getElement(i: Int, wasNativeTypeChecked: Bool) -> Element { if _fastPath(wasNativeTypeChecked) { return _nativeTypeChecked[i] } return unsafeBitCast(_getElementSlowPath(i), Element.self) } @inline(never) @warn_unused_result func _getElementSlowPath(i: Int) -> AnyObject { _sanityCheck( _isClassOrObjCExistential(Element.self), "Only single reference elements can be indexed here.") let element: AnyObject if _isNative { // _checkInoutAndNativeTypeCheckedBounds does no subscript // checking for the native un-typechecked case. Therefore we // have to do it here. _native._checkValidSubscript(i) element = castToBufferOf(AnyObject.self)._native[i] _precondition( element is Element, "Down-casted Array element failed to match the target type") } else { // ObjC arrays do their own subscript checking. element = _nonNative.objectAtIndex(i) _precondition( element is Element, "NSArray element failed to match the Swift Array Element type") } return element } /// Get or set the value of the ith element. public subscript(i: Int) -> Element { get { return getElement(i, wasNativeTypeChecked: _isNativeTypeChecked) } nonmutating set { if _fastPath(_isNative) { _native[i] = newValue } else { var refCopy = self refCopy.replace( subRange: i...i, with: 1, elementsOf: CollectionOfOne(newValue)) } } } /// Call `body(p)`, where `p` is an `UnsafeBufferPointer` over the /// underlying contiguous storage. If no such storage exists, it is /// created on-demand. public func withUnsafeBufferPointer<R>( @noescape body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R { if _fastPath(_isNative) { defer { _fixLifetime(self) } return try body(UnsafeBufferPointer(start: firstElementAddress, count: count)) } return try ContiguousArray(self).withUnsafeBufferPointer(body) } /// Call `body(p)`, where `p` is an `UnsafeMutableBufferPointer` /// over the underlying contiguous storage. /// /// - Requires: Such contiguous storage exists or the buffer is empty. public mutating func withUnsafeMutableBufferPointer<R>( @noescape body: (UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R { _sanityCheck( firstElementAddress != nil || count == 0, "Array is bridging an opaque NSArray; can't get a pointer to the elements" ) defer { _fixLifetime(self) } return try body( UnsafeMutableBufferPointer(start: firstElementAddress, count: count)) } /// An object that keeps the elements stored in this buffer alive. public var owner: AnyObject { return _fastPath(_isNative) ? _native._storage : _nonNative } /// An object that keeps the elements stored in this buffer alive. /// /// - Requires: This buffer is backed by a `_ContiguousArrayBuffer`. public var nativeOwner: AnyObject { _sanityCheck(_isNative, "Expect a native array") return _native._storage } /// A value that identifies the storage used by the buffer. Two /// buffers address the same elements when they have the same /// identity and count. public var identity: UnsafePointer<Void> { if _isNative { return _native.identity } else { return unsafeAddressOf(_nonNative) } } //===--- CollectionType conformance -------------------------------------===// /// The position of the first element in a non-empty collection. /// /// In an empty collection, `startIndex == endIndex`. public var startIndex: Int { return 0 } /// The collection's "past the end" position. /// /// `endIndex` is not a valid argument to `subscript`, and is always /// reachable from `startIndex` by zero or more applications of /// `successor()`. public var endIndex: Int { return count } //===--- private --------------------------------------------------------===// typealias Storage = _ContiguousArrayStorage<Element> public typealias NativeBuffer = _ContiguousArrayBuffer<Element> var _isNative: Bool { if !_isClassOrObjCExistential(Element.self) { return true } else { return _storage.isNative } } /// `true`, if the array is native and does not need a deferred type check. var _isNativeTypeChecked: Bool { if !_isClassOrObjCExistential(Element.self) { return true } else { return _storage.isNativeWithClearedSpareBits(deferredTypeCheckMask) } } /// Our native representation. /// /// - Requires: `_isNative`. var _native: NativeBuffer { return NativeBuffer( _isClassOrObjCExistential(Element.self) ? _storage.nativeInstance : _storage.nativeInstance_noSpareBits) } /// Fast access to the native representation. /// /// - Requires: `_isNativeTypeChecked`. var _nativeTypeChecked: NativeBuffer { return NativeBuffer(_storage.nativeInstance_noSpareBits) } var _nonNative: _NSArrayCoreType { @inline(__always) get { _sanityCheck(_isClassOrObjCExistential(Element.self)) return _storage.objCInstance } } } #endif
apache-2.0
075a5e044d4f26f8d2dc109736552f16
31.376699
80
0.666427
4.785878
false
false
false
false
SaberVicky/LoveStory
LoveStory/Feature/Login/LSInviteViewController.swift
1
3588
// // LSInviteViewController.swift // LoveStory // // Created by songlong on 2017/1/20. // Copyright © 2017年 com.Saber. All rights reserved. // import UIKit class LSInviteViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() title = "匹配信息" setupUI() } private func setupUI() { view.backgroundColor = UIColor(red: 243 / 255.0, green: 239 / 255.0, blue: 230 / 255.0, alpha: 1) navigationItem.leftBarButtonItem = UIBarButtonItem(title: "退出", style: .plain, target: self, action: #selector(clickQuit)) let stepIcon = UIImageView(image: UIImage(named: "ln_reg_indicator_2")) view.addSubview(stepIcon) stepIcon.snp.makeConstraints { (make) in make.centerY.equalTo(35) make.centerX.equalTo(view) } let infoLabel = UILabel() infoLabel.text = "LoveStory是情侣两人玩的应用\n邀请你的另一半,以匹配开通" infoLabel.textAlignment = .center infoLabel.font = UIFont.systemFont(ofSize: 13) infoLabel.textColor = .lightGray infoLabel.numberOfLines = 2 view.addSubview(infoLabel) infoLabel.snp.makeConstraints { (make) in make.centerX.equalTo(view) make.top.equalTo(70) } let toInviteBtn = UIButton() toInviteBtn.addTarget(self, action: #selector(clickToInvite), for: .touchUpInside) toInviteBtn.setTitleColor(.white, for: .normal) toInviteBtn.layer.cornerRadius = 5 toInviteBtn.layer.masksToBounds = true toInviteBtn.setTitle("邀请另一半", for: .normal) toInviteBtn.backgroundColor = LSMainColor view.addSubview(toInviteBtn) toInviteBtn.snp.makeConstraints { (make) in make.centerX.equalTo(view) make.left.equalTo(20) make.top.equalTo(infoLabel.snp.bottom).offset(70) make.height.equalTo(50) } let beInvitedBtn = UIButton() beInvitedBtn.addTarget(self, action: #selector(clickBeInvited), for: .touchUpInside) beInvitedBtn.layer.cornerRadius = 5 beInvitedBtn.layer.masksToBounds = true beInvitedBtn.setTitleColor(.white, for: .normal) beInvitedBtn.setTitle("我已经被邀请", for: .normal) beInvitedBtn.backgroundColor = LSMainColor view.addSubview(beInvitedBtn) beInvitedBtn.snp.makeConstraints { (make) in make.centerX.equalTo(view) make.left.equalTo(20) make.top.equalTo(toInviteBtn.snp.bottom).offset(35) make.height.equalTo(50) } } func clickToInvite() { navigationController?.pushViewController(LSToInviteViewController(), animated: true) } func clickBeInvited() { navigationController?.pushViewController(LSBeInvitedViewController(), animated: true) } func clickQuit() { let alert = UIAlertController(title: "退出后您将断开该账号的连接!", message: nil, preferredStyle: .actionSheet) let action1 = UIAlertAction(title: "确定退出", style: .destructive, handler: { (action) in self.dismiss(animated: true, completion: nil) LSUser.currentUser()?.user_delete() }) let action2 = UIAlertAction(title: "取消", style: .cancel, handler: nil) alert.addAction(action1) alert.addAction(action2) present(alert, animated: true, completion: nil) } }
mit
09d60995927b7ccf26b2f17aac895493
35.494737
130
0.631382
4.142174
false
false
false
false
mmsaddam/ToDo
ToDo/ViewController.swift
1
16761
// // ViewController.swift // ToDo // // Created by Muzahidul Islam on 5/30/16. // Copyright © 2016 iMuzahid. All rights reserved. // import UIKit import AVFoundation class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, TableViewCellDelegate { @IBOutlet weak var tableView: UITableView! let kRowHeight: CGFloat = 50.0 var toDoItems :[ToDoItem] = []{ didSet{ self.loadItems() } } var today: [ToDoItem] = [] var tomorrow: [ToDoItem] = [] var upcoming: [ToDoItem] = [] var newItemType = ItemType.Today // default new item would be added let pinchRecognizer = UIPinchGestureRecognizer() var newItemPlayer : AVAudioPlayer? override func viewDidLoad() { super.viewDidLoad() if let contentPath = NSBundle.mainBundle().pathForResource("popup", ofType: "wav"), contentUrl = NSURL(string: contentPath){ do{ newItemPlayer = try AVAudioPlayer(contentsOfURL: contentUrl) //newItemPlayer.numberOfLoops = 1 newItemPlayer!.prepareToPlay() }catch let error as NSError { print(error) } }else{ print(" Audio File not found") } self.toDoItems = ToDoAPI.sharedInstance.getItems() loadItems() pinchRecognizer.addTarget(self, action: #selector(ViewController.handlePinch(_:))) // pinchRecognizer.addTarget(self, action: Selector("handlePinch:")) tableView.addGestureRecognizer(pinchRecognizer) tableView.dataSource = self tableView.delegate = self tableView.registerClass(TableViewCell.self, forCellReuseIdentifier: "cell") tableView.separatorStyle = .None tableView.backgroundColor = UIColor.whiteColor() tableView.rowHeight = kRowHeight playNewItemSound() } /// Show or hide the section header of tableView func hideAllHeader(isHide: Bool) { for itm in tableView.subviews { if itm.isKindOfClass(TableHeader) { itm.hidden = isHide } } } /// Load all items created, group by catagories func loadItems() { today = [] tomorrow = [] upcoming = [] for itm in self.toDoItems { switch itm.itemType { case .Today: today.append(itm) case .Tomorrow: tomorrow.append(itm) default: upcoming.append(itm) } } } /// Prepayere audio player to play new item created func playNewItemSound() { if !newItemPlayer!.playing { newItemPlayer!.play() } } // MARK: Button Action @IBAction func addAction(sender: AnyObject) { let addBtn = sender as! UIButton switch addBtn.tag { case 0: self.newItemType = ItemType.Today case 1: self.newItemType = ItemType.Tomorrow default: self.newItemType = ItemType.Upcoming } self.tableView.setContentOffset(CGPointMake(0, 0), animated: false) self.toDoItemAdded() // playNewItemSound() } // MARK: - Table view data source func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 3 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return today.count case 1: return tomorrow.count default: return upcoming.count } } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat{ return kRowHeight } func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let frame = CGRectMake(0, 0, CGRectGetWidth(tableView.frame), kRowHeight) let header = TableHeader(frame: frame) header.addBtn.addTarget(self, action: #selector(ViewController.addAction(_:)), forControlEvents: .TouchUpInside) header.addBtn.tag = section switch section { case 0: header.title.text = "TODAY" case 1: header.title.text = "TOMORROW" default: header.title.text = "UPCOMING" } return header } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! TableViewCell cell.selectionStyle = .None cell.textLabel?.backgroundColor = UIColor.clearColor() if indexPath.section == 0 { cell.toDoItem = today[indexPath.row] }else if indexPath.section == 1 { cell.toDoItem = tomorrow[indexPath.row] }else{ cell.toDoItem = upcoming[indexPath.row] } cell.delegate = self return cell } // MARK: TableViewCell Delegate func cellDidBeginEditing(editingCell: TableViewCell) { hideAllHeader(true) // hide header view let editingOffset = tableView.contentOffset.y - editingCell.frame.origin.y as CGFloat let visibleCells = tableView.visibleCells as! [TableViewCell] for cell in visibleCells { UIView.animateWithDuration(0.3, animations: {() in cell.transform = CGAffineTransformMakeTranslation(0, editingOffset) if cell !== editingCell { cell.alpha = 0.3 } }) } } func cellDidEndEditing(editingCell: TableViewCell) { hideAllHeader(false) // show header view let visibleCells = tableView.visibleCells as! [TableViewCell] for cell: TableViewCell in visibleCells { UIView.animateWithDuration(0.3, animations: {() in cell.transform = CGAffineTransformIdentity if cell !== editingCell { cell.alpha = 1.0 } }) } if editingCell.toDoItem!.text == "" { toDoItemDeleted(editingCell.toDoItem!) }else{ guard let item = editingCell.toDoItem else{ return } //toDoItemUpdated(item) for ( _ ,itm) in self.toDoItems.enumerate(){ if itm.createdAt == item.createdAt{ ToDoAPI.sharedInstance.updateItem(item, completion: { (isSuccess, error) -> Void in if isSuccess{ print("updated succssfully...") self.playNewItemSound() // self.adaptedAnyChanges() }else{ print("updating failed") } }) break } } } } // MARK: - Table view delegate func colorForIndex(index: Int) -> UIColor { return UIColor.whiteColor() } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return kRowHeight } func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { cell.backgroundColor = colorForIndex(indexPath.row) } // MARK: - pinch-to-add methods struct TouchPoints { var upper: CGPoint var lower: CGPoint } // the indices of the upper and lower cells that are being pinched var upperCellIndex = -100 var lowerCellIndex = -100 // the location of the touch points when the pinch began var initialTouchPoints: TouchPoints! // indicates that the pinch was big enough to cause a new item to be added var pinchExceededRequiredDistance = false // indicates that the pinch is in progress var pinchInProgress = false func handlePinch(recognizer: UIPinchGestureRecognizer) { if recognizer.state == .Began { pinchStarted(recognizer) } if recognizer.state == .Changed && pinchInProgress && recognizer.numberOfTouches() == 2 { pinchChanged(recognizer) } if recognizer.state == .Ended { pinchEnded(recognizer) } } func pinchStarted(recognizer: UIPinchGestureRecognizer) { // find the touch-points initialTouchPoints = getNormalizedTouchPoints(recognizer) // locate the cells that these points touch upperCellIndex = -100 lowerCellIndex = -100 let visibleCells = tableView.visibleCells as! [TableViewCell] for i in 0..<visibleCells.count { let cell = visibleCells[i] if viewContainsPoint(cell, point: initialTouchPoints.upper) { upperCellIndex = i } if viewContainsPoint(cell, point: initialTouchPoints.lower) { lowerCellIndex = i } } // check whether they are neighbors if abs(upperCellIndex - lowerCellIndex) == 1 { // initiate the pinch pinchInProgress = true // show placeholder cell let precedingCell = visibleCells[upperCellIndex] placeHolderCell.frame = CGRectOffset(precedingCell.frame, 0.0, kRowHeight / 2.0) placeHolderCell.backgroundColor = precedingCell.backgroundColor tableView.insertSubview(placeHolderCell, atIndex: 0) } } func pinchChanged(recognizer: UIPinchGestureRecognizer) { // find the touch points let currentTouchPoints = getNormalizedTouchPoints(recognizer) // determine by how much each touch point has changed, and take the minimum delta let upperDelta = currentTouchPoints.upper.y - initialTouchPoints.upper.y let lowerDelta = initialTouchPoints.lower.y - currentTouchPoints.lower.y let delta = -min(0, min(upperDelta, lowerDelta)) // offset the cells, negative for the cells above, positive for those below let visibleCells = tableView.visibleCells as! [TableViewCell] for i in 0..<visibleCells.count { let cell = visibleCells[i] if i <= upperCellIndex { cell.transform = CGAffineTransformMakeTranslation(0, -delta) } if i >= lowerCellIndex { cell.transform = CGAffineTransformMakeTranslation(0, delta) } } // scale the placeholder cell let gapSize = delta * 2 let cappedGapSize = min(gapSize, tableView.rowHeight) placeHolderCell.transform = CGAffineTransformMakeScale(1.0, cappedGapSize / tableView.rowHeight) placeHolderCell.label.text = gapSize > tableView.rowHeight ? "Release to add item" : "Pull apart to add item" placeHolderCell.alpha = min(1.0, gapSize / tableView.rowHeight) // has the user pinched far enough? pinchExceededRequiredDistance = gapSize > tableView.rowHeight } func pinchEnded(recognizer: UIPinchGestureRecognizer) { pinchInProgress = false // remove the placeholder cell placeHolderCell.transform = CGAffineTransformIdentity placeHolderCell.removeFromSuperview() if pinchExceededRequiredDistance { pinchExceededRequiredDistance = false // Set all the cells back to the transform identity let visibleCells = self.tableView.visibleCells as! [TableViewCell] for cell in visibleCells { cell.transform = CGAffineTransformIdentity } // add a new item let indexOffset = Int(floor(tableView.contentOffset.y / tableView.rowHeight)) toDoItemAddedAtIndex(lowerCellIndex + indexOffset) } else { // otherwise, animate back to position UIView.animateWithDuration(0.2, delay: 0.0, options: .CurveEaseInOut, animations: {() in let visibleCells = self.tableView.visibleCells as! [TableViewCell] for cell in visibleCells { cell.transform = CGAffineTransformIdentity } }, completion: nil) } } // returns the two touch points, ordering them to ensure that // upper and lower are correctly identified. func getNormalizedTouchPoints(recognizer: UIGestureRecognizer) -> TouchPoints { var pointOne = recognizer.locationOfTouch(0, inView: tableView) var pointTwo = recognizer.locationOfTouch(1, inView: tableView) // ensure pointOne is the top-most if pointOne.y > pointTwo.y { let temp = pointOne pointOne = pointTwo pointTwo = temp } return TouchPoints(upper: pointOne, lower: pointTwo) } func viewContainsPoint(view: UIView, point: CGPoint) -> Bool { let frame = view.frame return (frame.origin.y < point.y) && (frame.origin.y + (frame.size.height) > point.y) } // MARK: - UIScrollViewDelegate methods // contains scrollViewDidScroll, and you'll add two more, to keep track of dragging the scrollView // a cell that is rendered as a placeholder to indicate where a new item is added let placeHolderCell = TableViewCell(style: .Default, reuseIdentifier: "cell") // indicates the state of this behavior var pullDownInProgress = false func scrollViewWillBeginDragging(scrollView: UIScrollView) { // this behavior starts when a user pulls down while at the top of the table pullDownInProgress = scrollView.contentOffset.y <= 0.0 placeHolderCell.backgroundColor = UIColor.redColor() if pullDownInProgress { // add the placeholder tableView.insertSubview(placeHolderCell, atIndex: 0) } } func scrollViewDidScroll(scrollView: UIScrollView) { // non-scrollViewDelegate methods need this property value let scrollViewContentOffsetY = tableView.contentOffset.y if pullDownInProgress && scrollView.contentOffset.y <= 0.0 { // maintain the location of the placeholder placeHolderCell.frame = CGRect(x: 0, y: -tableView.rowHeight, width: tableView.frame.size.width, height: tableView.rowHeight) placeHolderCell.label.text = -scrollViewContentOffsetY > tableView.rowHeight ? "Release to add item" : "Pull to add item" placeHolderCell.alpha = min(1.0, -scrollViewContentOffsetY / tableView.rowHeight) } else { pullDownInProgress = false } } func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { // check whether the user pulled down far enough if pullDownInProgress && -scrollView.contentOffset.y > tableView.rowHeight { // toDoItemAdded() } pullDownInProgress = false placeHolderCell.removeFromSuperview() } // MARK: Update item func toDoItemUpdated(toDoItem: ToDoItem) { for ( _ , itm) in self.toDoItems.enumerate(){ if itm.createdAt == toDoItem.createdAt{ ToDoAPI.sharedInstance.updateItem(toDoItem, completion: { (isSuccess, error) -> Void in if isSuccess{ //self.toDoItems[index] = toDoItem // self.adaptedAnyChanges() }else{ print("updating failed") } }) break } } } // MARK: Delete Item func toDoItemDeleted(toDoItem: ToDoItem) { // could use this to get index when Swift Array indexOfObject works // let index = toDoItems.indexOfObject(toDoItem) // in the meantime, scan the array to find index of item to delete var index = 0 for i in 0..<toDoItems.count { if toDoItems[i].createdAt == toDoItem.createdAt { // note: === not == index = i break } } self.toDoItems.removeAtIndex(index) // could removeAtIndex in the loop but keep it here for when indexOfObject works // let path = NSIndexPath(forRow: self.findRowForItem(toDoItem), inSection: toDoItem.itemType.rawValue) // // use the UITableView to animate the removal of this row // self.tableView.beginUpdates() // self.tableView.deleteRowsAtIndexPaths([path], withRowAnimation: .Fade) // self.tableView.endUpdates() ToDoAPI.sharedInstance.deleteItem(toDoItem) { (isSuccess, error) in if isSuccess{ // loop over the visible cells to animate delete let visibleCells = self.tableView.visibleCells as! [TableViewCell] let lastView = visibleCells[visibleCells.count - 1] as TableViewCell var delay = 0.0 var startAnimating = false for i in 0..<visibleCells.count { let cell = visibleCells[i] if startAnimating { UIView.animateWithDuration(0.3, delay: delay, options: .CurveEaseInOut, animations: {() in cell.frame = CGRectOffset(cell.frame, 0.0, -cell.frame.size.height)}, completion: {(finished: Bool) in if (cell == lastView) { self.tableView.reloadData() } } ) delay += 0.03 } if cell.toDoItem === toDoItem { startAnimating = true cell.hidden = true } } }else{ } } } func toDoItemAdded() { toDoItemAddedAtIndex(0) } func toDoItemAddedAtIndex(index: Int) { let toDoItem = ToDoItem(text: "") toDoItem.itemType = newItemType // Insert New Item toDoItems.insert(toDoItem, atIndex: index) tableView.reloadData() let row: Int = 0 let indexPath = NSIndexPath(forRow: row, inSection: newItemType.rawValue) tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Top, animated: false) ToDoAPI.sharedInstance.addNewItem(toDoItem) { (isSuccess, error) in if isSuccess{ // enter edit mode var editCell: TableViewCell let visibleCells = self.tableView.visibleCells as! [TableViewCell] for cell in visibleCells { if (cell.toDoItem === toDoItem) { editCell = cell editCell.label.becomeFirstResponder() break } } }else{ print("fail to add ....") } } } func findRowForItem(item: ToDoItem) -> Int { var index = 0 if item.itemType == .Today { for i in 0..<today.count { if today[i].createdAt == item.createdAt { // note: === not == index = i break } } }else if item.itemType == .Tomorrow{ for i in 0..<tomorrow.count { if tomorrow[i].createdAt == item.createdAt { // note: === not == index = i break } } }else{ for i in 0..<upcoming.count { if upcoming[i].createdAt == item.createdAt { // note: === not == index = i break } } } return index } }
mit
1aa40ffc87187eb8535a5fd9eac1f591
26.656766
126
0.694212
3.967803
false
false
false
false
rpowelll/Lap-Timer-Swift
Lap Timer/Models/Time.swift
1
1001
// // Time.swift // Lap Timer // // Created by Rhys Powell on 5/08/2014. // Copyright (c) 2014 Rhys Powell. All rights reserved. // import UIKit class Time: NSObject, NSCoding { var time: NSTimeInterval! var dateRecorded: NSDate var comment: String? override init() { self.dateRecorded = NSDate.date() } required init(coder aDecoder: NSCoder) { time = aDecoder.decodeObjectForKey("time") as NSTimeInterval dateRecorded = aDecoder.decodeObjectForKey("dateRecorded") as NSDate comment = aDecoder.decodeObjectForKey("comment") as String? } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(time, forKey: "time") aCoder.encodeObject(dateRecorded, forKey: "dateRecorded") aCoder.encodeObject(comment!, forKey: "comment") } convenience init(time: NSTimeInterval, dateRecorded: NSDate) { self.init() self.time = time self.dateRecorded = dateRecorded } }
mit
7c443f83d4955fb15d5f2a6654209edd
26.054054
76
0.654346
4.314655
false
false
false
false
y-hryk/ViewPager
ViewPagerDemo/ViewController.swift
1
2169
// // ViewController.swift // ViewPagerDemo // // Created by yamaguchi on 2016/08/31. // Copyright © 2016年 h.yamaguchi. All rights reserved. // import UIKit class ViewController: UITableViewController { var datas = ["Normal Mode Demo","Segmented Mode Demo","Infinity Mode Demo"] override func viewDidLoad() { super.viewDidLoad() self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "reuseIdentifier") // self.datas = ["Normal Mode Demo","Segmented Mode Demo","Infinity Mode Demo"] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } 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 self.datas.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) // Configure the cell... cell.textLabel!.text = "\(self.datas[indexPath.row])" return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) if indexPath.row == 0 { let vc = Demo1ViewController() self.navigationController?.pushViewController(vc, animated: true) } if indexPath.row == 1 { let vc = Demo2ViewController() self.navigationController?.pushViewController(vc, animated: true) } if indexPath.row == 2 { let vc = Demo3ViewController() self.navigationController?.pushViewController(vc, animated: true) } } }
mit
e3169949a6261aa2a2ffaf51153f622c
29.942857
109
0.632964
5.401496
false
false
false
false
stasel/WWDC2015
StasSeldin/StasSeldin/ContactViewController.swift
1
4371
// // ContactViewController.swift // StasSeldin // // Created by Stas Seldin on 18/04/2015. // Copyright (c) 2015 Stas Seldin. All rights reserved. // import UIKit import Foundation import MapKit class ContactViewController: UIViewController { //outlets @IBOutlet weak var mapView: MKMapView! @IBOutlet weak var emailButton: UIButton! @IBOutlet weak var facetimeButton: UIButton! @IBOutlet weak var phoneButton: UIButton! override func viewDidLoad() { super.viewDidLoad() self.view.setBackgroundImage(named: "Background_Green") self.view.addBackgroundBlurEffect(style: .light) //set address in map view if let address = Profile.me.contact.address { self.setLocationForAddress(address: address) } self.setContactInfoUI() } func setLocationForAddress(address: Address) { let geoCoder = CLGeocoder() geoCoder.geocodeAddressString(address.description) { (placemarks, error) in if let placemarks = placemarks { if let firstResult = (placemarks as [CLPlacemark]).first { let placemark = MKPlacemark(placemark: firstResult) let addressRegion = MKCoordinateRegionMakeWithDistance(placemark.coordinate, 2000, 2000) self.mapView.setRegion(addressRegion, animated: true) let annotation = MKPointAnnotation() annotation.coordinate = placemark.coordinate annotation.title = "This is where I live" annotation.subtitle = address.description self.mapView.addAnnotation(annotation) self.mapView.selectAnnotation(annotation, animated: true) } } else if let error = error { print(error) } else { print("Unknown error finding geolocation") } } } func setContactInfoUI() { if let email = Profile.me.contact.email { self.emailButton.setTitle(email, for: .normal) } if let phone = Profile.me.contact.phoneNumber { self.phoneButton.setTitle(phone, for: .normal) } if let facetime = Profile.me.contact.faceTime { self.facetimeButton.setTitle(facetime, for: .normal) } } @IBAction func emailDidTouch(_ sender: AnyObject) { if let email = Profile.me.contact.email, let url = URL(string: "mailto:\(email)") { UIApplication.shared.openURL(url) } } @IBAction func phoneDidTouch(_ sender: AnyObject) { if let phone = Profile.me.contact.phoneNumber { let formattedPhone = phone.replacingOccurrences(of: " ", with: "") if let url = URL(string: "tel:\(formattedPhone)") { UIApplication.shared.openURL(url) } } } @IBAction func facetimeDidTouch(_ sender: AnyObject) { if let facetime = Profile.me.contact.faceTime { if let stringUrl = "facetime:/\(facetime)".addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed), let url = URL(string: stringUrl) { UIApplication.shared.openURL(url) } } } @IBAction func facebookDidTouch(_ sender: UIButton) { if let facebook = Profile.me.socialMedia.faceBook, let url = URL(string: facebook) { UIApplication.shared.openURL(url) } } @IBAction func linkedInDidTouch(_ sender: AnyObject) { if let linkedin = Profile.me.socialMedia.linkedIn, let url = URL(string: linkedin) { UIApplication.shared.openURL(url) } } @IBAction func stackDidTouch(_ sender: AnyObject) { if let stackOverflow = Profile.me.socialMedia.stackOverflow, let url = URL(string: stackOverflow) { UIApplication.shared.openURL(url) } } @IBAction func githubDidTouch(_ sender: AnyObject) { if let gitHub = Profile.me.socialMedia.gitHub { let url = URL(string: gitHub) UIApplication.shared.openURL(url!) } } }
mit
e33f0dc812c7f76d6a69ecabea2c746c
32.113636
132
0.583391
4.94457
false
false
false
false
kodlian/AlamofireXMLRPC
Sources/AlamofireXMLRPC/Value.swift
1
4000
// // Type.swift // AlamofireXMLRPC // // Created by Jeremy Marchand on 08/10/2015. // Copyright © 2015 kodlian. All rights reserved. // import Foundation public enum XMLRPCValueKind: String { // swiftlint:disable identifier_name case Integer = "int" case Double = "double" case Boolean = "boolean" case String = "string" case DateTime = "dateTime.iso8601" case Base64 = "base64" } public protocol XMLRPCRawValueRepresentable { static var xmlRpcKind: XMLRPCValueKind { get } var xmlRpcRawValue: String { get } init?(xmlRpcRawValue: String) } public extension XMLRPCRawValueRepresentable { static var xmlRpcKind: XMLRPCValueKind { return .String } var xmlRpcRawValue: String { return String(describing: self) } init?(xmlRpcRawValue: String) { return nil } } public extension RawRepresentable where RawValue == String, Self: XMLRPCRawValueRepresentable { init?(xmlRpcRawValue: String) { self.init(rawValue: xmlRpcRawValue) } var xmlRpcRawValue: String { return rawValue } } // MARK: String extension String: XMLRPCRawValueRepresentable { public static var xmlRpcKind: XMLRPCValueKind { return .String } public var xmlRpcRawValue: String { return self } public init?(xmlRpcRawValue: String) { self = xmlRpcRawValue } } // MARK: Bool extension Bool: XMLRPCRawValueRepresentable { public static var xmlRpcKind: XMLRPCValueKind { return .Boolean } public var xmlRpcRawValue: String { return self ? "1" : "0" } public init?(xmlRpcRawValue: String) { self.init(Int8(xmlRpcRawValue) == 1) } } // MARK: Integer extension XMLRPCRawValueRepresentable where Self: BinaryInteger { public static var xmlRpcKind: XMLRPCValueKind { return .Integer } } public protocol StringRadixParsable { init?(_ text: String, radix: Int) } extension XMLRPCRawValueRepresentable where Self: FixedWidthInteger { public init?(xmlRpcRawValue: String) { self.init(xmlRpcRawValue, radix: 10) } } extension Int: XMLRPCRawValueRepresentable { } extension Int32: XMLRPCRawValueRepresentable { } extension Int16: XMLRPCRawValueRepresentable { } extension Int8: XMLRPCRawValueRepresentable { } extension UInt16: XMLRPCRawValueRepresentable { } extension UInt8: XMLRPCRawValueRepresentable { } // MARK: Floating Point public extension XMLRPCRawValueRepresentable where Self: LosslessStringConvertible { init?(xmlRpcRawValue: String) { self.init(xmlRpcRawValue) } } public extension XMLRPCRawValueRepresentable where Self: FloatingPoint { static var xmlRpcKind: XMLRPCValueKind { return .Double } } extension Double: XMLRPCRawValueRepresentable { } extension Float: XMLRPCRawValueRepresentable { } // MARK: Date let iso8601DateFormatter: DateFormatter = { let dateFormatter = DateFormatter() dateFormatter.locale = Locale(identifier: "en_US_POSIX") dateFormatter.timeZone = TimeZone(abbreviation: "GMT") dateFormatter.dateFormat = "yyyyMMdd'T'HH:mm:ss" return dateFormatter }() extension Date { var iso8601String: String { return iso8601DateFormatter.string(from: self) } } extension Date: XMLRPCRawValueRepresentable { public static var xmlRpcKind: XMLRPCValueKind { return .DateTime } public var xmlRpcRawValue: String { return self.iso8601String } public init?(xmlRpcRawValue: String) { guard let date = iso8601DateFormatter.date(from: xmlRpcRawValue) else { return nil } self = date } } // MARK: Data extension Data: XMLRPCRawValueRepresentable { public static var xmlRpcKind: XMLRPCValueKind { return .Base64 } public var xmlRpcRawValue: String { return self.base64EncodedString(options: []) } public init?(xmlRpcRawValue: String) { guard let data = Data(base64Encoded: xmlRpcRawValue, options: .ignoreUnknownCharacters) else { return nil } self = data } }
mit
97fbbfe0c2529f6652f312af224601b2
28.622222
102
0.711428
4.144041
false
false
false
false
mparrish91/gifRecipes
framework/Model/Multireddit.swift
1
5393
// // Multireddit.swift // reddift // // Created by sonson on 2015/05/19. // Copyright (c) 2015年 sonson. All rights reserved. // import Foundation /** Type of Multireddit icon. */ public enum MultiredditIconName: String { case artAndDesign = "art and design" case ask = "ask" case books = "books" case business = "business" case cars = "cars" case comics = "comics" case cuteAnimals = "cute animals" case diy = "diy" case entertainment = "entertainment" case foodAndDrink = "food and drink" case funny = "funny" case games = "games" case grooming = "grooming" case health = "health" case lifeAdvice = "life advice" case military = "military" case modelsPinup = "models pinup" case music = "music" case news = "news" case philosophy = "philosophy" case picturesAndGifs = "pictures and gifs" case science = "science" case shopping = "shopping" case sports = "sports" case style = "style" case tech = "tech" case travel = "travel" case unusualStories = "unusual stories" case video = "video" case none = "None" init(_ name: String) { self = MultiredditIconName(rawValue:name) ?? .none } } /** Type of Multireddit visibility. */ public enum MultiredditVisibility: String { case `private` = "private" case `public` = "public" case hidden = "hidden" init(_ type: String) { self = MultiredditVisibility(rawValue:type) ?? .private } } /** Type of Multireddit weighting scheme. */ public enum MultiredditWeightingScheme: String { case classic = "classic" case fresh = "fresh" init(_ type: String) { self = MultiredditWeightingScheme(rawValue:type) ?? .classic } } /** Multireddit class. */ public struct Multireddit: SubredditURLPath, Created { public var descriptionMd: String public var displayName: String public var iconName: MultiredditIconName public var keyColor: String public var subreddits: [String] public var visibility: MultiredditVisibility public var weightingScheme: MultiredditWeightingScheme // can not update following attritubes public let descriptionHtml: String public let path: String public let name: String public let iconUrl: String public let canEdit: Bool public let copiedFrom: String public let created: Int public let createdUtc: Int public init(name: String) { self.descriptionMd = "" self.displayName = name self.iconName = MultiredditIconName("") self.visibility = MultiredditVisibility("") self.keyColor = "" self.subreddits = [] self.weightingScheme = MultiredditWeightingScheme("") self.descriptionHtml = "" self.path = name self.name = name self.iconUrl = "" self.canEdit = false self.copiedFrom = "" self.created = 0 self.createdUtc = 0 } public init(json: JSONDictionary) { descriptionMd = json["description_md"] as? String ?? "" displayName = json["display_name"] as? String ?? "" iconName = MultiredditIconName(json["icon_name"] as? String ?? "") visibility = MultiredditVisibility(json["visibility"] as? String ?? "") keyColor = json["key_color"] as? String ?? "" var buf: [String] = [] if let temp = json["subreddits"] as? [JSONDictionary] { for element in temp { if let element = element as? [String:String], let name = element["name"] { buf.append(name) } } } subreddits = buf weightingScheme = MultiredditWeightingScheme(json["weighting_scheme"] as? String ?? "") descriptionHtml = json["description_html"] as? String ?? "" path = json["path"] as? String ?? "" name = json["name"] as? String ?? "" iconUrl = json["icon_url"] as? String ?? "" canEdit = json["can_edit"] as? Bool ?? false copiedFrom = json["copied_from"] as? String ?? "" created = json["created"] as? Int ?? 0 createdUtc = json["created_utc"] as? Int ?? 0 } /** Create new multireddit path as String from "/user/sonson_twit/m/testmultireddit12" replacing its name with "newMultiredditName". For example, returns ""/user/sonson_twit/m/newmulti" when path is "/user/sonson_twit/m/testmultireddit12" and newMultiredditName is "newmulti". - parameter newMultiredditName: New display name for path. - returns: new path as String. */ public func multiredditPathReplacingNameWith(_ newMultiredditName: String) throws -> String { do { let regex = try NSRegularExpression(pattern:"^/user/(.+?)/m/", options: .caseInsensitive) if let match = regex.firstMatch(in: self.path, options: [], range: NSRange(location:0, length:self.path.characters.count)) { if match.numberOfRanges > 1 { let range = match.rangeAt(1) let userName = (self.path as NSString).substring(with: range) return "/user/\(userName)/m/\(newMultiredditName)" } } throw NSError(domain: "", code: 0, userInfo: nil) } catch { throw error } } }
mit
941d8d7762d8cfb11a8135abd677e60b
31.475904
277
0.608978
4.03518
false
false
false
false
weyert/Whisper
Demo/WhisperDemo/WhisperDemo/ViewController.swift
1
8237
import UIKit import Whisper class ViewController: UIViewController { lazy var scrollView: UIScrollView = UIScrollView() lazy var titleLabel: UILabel = { let label = UILabel() label.text = "Welcome to the magic of a tiny Whisper... 🍃" label.font = UIFont(name: "HelveticaNeue-Medium", size: 20)! label.textColor = UIColor(red:0.86, green:0.86, blue:0.86, alpha:1) label.textAlignment = .Center label.numberOfLines = 0 label.frame.size.width = UIScreen.mainScreen().bounds.width - 60 label.sizeToFit() return label }() lazy var presentButton: UIButton = { [unowned self] in let button = UIButton() button.addTarget(self, action: "presentButtonDidPress:", forControlEvents: .TouchUpInside) button.setTitle("Present and silent", forState: .Normal) return button }() lazy var showButton: UIButton = { [unowned self] in let button = UIButton() button.addTarget(self, action: "showButtonDidPress:", forControlEvents: .TouchUpInside) button.setTitle("Show", forState: .Normal) return button }() lazy var presentPermanentButton: UIButton = { [unowned self] in let button = UIButton() button.addTarget(self, action: "presentPermanentButtonDidPress:", forControlEvents: .TouchUpInside) button.setTitle("Present permanent Whisper", forState: .Normal) return button }() lazy var notificationButton: UIButton = { [unowned self] in let button = UIButton() button.addTarget(self, action: "presentNotificationDidPress:", forControlEvents: .TouchUpInside) button.setTitle("Notification", forState: .Normal) return button }() lazy var statusBarButton: UIButton = { [unowned self] in let button = UIButton() button.addTarget(self, action: "statusBarButtonDidPress:", forControlEvents: .TouchUpInside) button.setTitle("Status bar", forState: .Normal) return button }() lazy var containerView: UIView = { let view = UIView() view.backgroundColor = UIColor.grayColor() return view }() lazy var nextButton: UIBarButtonItem = { [unowned self] in let button = UIBarButtonItem() button.title = "Next" button.style = .Plain button.target = self button.action = "nextButtonDidPress" return button }() lazy var disclosureButton: UIButton = { [unowned self] in let button = UIButton() button.addTarget(self, action: "presentDisclosureButtonDidPress:", forControlEvents: .TouchUpInside) button.setTitle("Disclosure", forState: .Normal) return button }() lazy var modalViewButton: UIBarButtonItem = { [unowned self] in let button = UIBarButtonItem() button.title = "Modal view" button.style = .Plain button.target = self button.action = "modalViewButtonDidPress" return button }() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.whiteColor() title = "Whisper".uppercaseString navigationItem.rightBarButtonItem = nextButton navigationItem.leftBarButtonItem = modalViewButton view.addSubview(scrollView) [titleLabel, presentButton, showButton, presentPermanentButton, notificationButton, statusBarButton, disclosureButton].forEach { scrollView.addSubview($0) } [presentButton, showButton, presentPermanentButton, notificationButton, statusBarButton, disclosureButton].forEach { $0.setTitleColor(UIColor.grayColor(), forState: .Normal) $0.layer.borderColor = UIColor.grayColor().CGColor $0.layer.borderWidth = 1.5 $0.layer.cornerRadius = 7.5 } guard let navigationController = navigationController else { return } navigationController.navigationBar.addSubview(containerView) containerView.frame = CGRect(x: 0, y: navigationController.navigationBar.frame.maxY - UIApplication.sharedApplication().statusBarFrame.height, width: UIScreen.mainScreen().bounds.width, height: 0) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) setupFrames() } // MARK: - Orientation changes override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) { setupFrames() } // MARK: Action methods func presentButtonDidPress(button: UIButton) { guard let navigationController = navigationController else { return } let message = Message(title: "This message will silent in 3 seconds.", backgroundColor: UIColor(red:0.89, green:0.09, blue:0.44, alpha:1)) Whisper(message, to: navigationController, action: .Present) Silent(navigationController, after: 3) } func showButtonDidPress(button: UIButton) { guard let navigationController = navigationController else { return } let message = Message(title: "Showing all the things.", backgroundColor: UIColor.blackColor()) Whisper(message, to: navigationController) } func presentPermanentButtonDidPress(button: UIButton) { guard let navigationController = navigationController else { return } let message = Message(title: "This is a permanent Whisper.", textColor: UIColor(red:0.87, green:0.34, blue:0.05, alpha:1), backgroundColor: UIColor(red:1.000, green:0.973, blue:0.733, alpha: 1)) Whisper(message, to: navigationController, action: .Present) } func presentNotificationDidPress(button: UIButton) { let announcement = Announcement(title: "Ramon Gilabert", subtitle: "Vadym Markov just commented your post \"Getting started with Whisper\"", image: UIImage(named: "avatar")) Shout(announcement, to: self, completion: { print("The shout was silent.") }) } func nextButtonDidPress() { let controller = TableViewController() navigationController?.pushViewController(controller, animated: true) } func statusBarButtonDidPress(button: UIButton) { let murmur = Murmur(title: "This is a small whistle...", backgroundColor: UIColor(red: 0.975, green: 0.975, blue: 0.975, alpha: 1)) Whistle(murmur) } func presentDisclosureButtonDidPress(button: UIButton) { var secret = Secret(title: "This is a secret revealed!") secret.textColor = view.tintColor // It can also be used self instead of navigationController Disclosure(secret, to: navigationController!, completion: { print("The disclosure was silent") }) } func modalViewButtonDidPress() { let modalViewController = ModalViewController() let modelNavigationController = UINavigationController(rootViewController: modalViewController) let tabBarController = UITabBarController() tabBarController.viewControllers = [modelNavigationController] let tabBarItem = tabBarController.tabBar.items![0] tabBarItem.title = "Whisper" if let image = UIImage(named: "Whisper.png")?.imageWithRenderingMode(.AlwaysOriginal) { tabBarItem.image = image } navigationController?.presentViewController(tabBarController, animated: true, completion: nil) } // MARK - Configuration func setupFrames() { let totalSize = UIScreen.mainScreen().bounds scrollView.frame = CGRect(x: 0, y: 0, width: totalSize.width, height: totalSize.height) titleLabel.frame.origin = CGPoint(x: (totalSize.width - titleLabel.frame.width) / 2, y: 60) presentButton.frame = CGRect(x: 50, y: titleLabel.frame.maxY + 75, width: totalSize.width - 100, height: 50) showButton.frame = CGRect(x: 50, y: presentButton.frame.maxY + 15, width: totalSize.width - 100, height: 50) presentPermanentButton.frame = CGRect(x: 50, y: showButton.frame.maxY + 15, width: totalSize.width - 100, height: 50) notificationButton.frame = CGRect(x: 50, y: presentPermanentButton.frame.maxY + 15, width: totalSize.width - 100, height: 50) statusBarButton.frame = CGRect(x: 50, y: notificationButton.frame.maxY + 15, width: totalSize.width - 100, height: 50) disclosureButton.frame = CGRect(x: 50, y: statusBarButton.frame.maxY + 15, width: totalSize.width - 100, height: 50) let height = disclosureButton.frame.maxY >= totalSize.height ? disclosureButton.frame.maxY + 35 : totalSize.height scrollView.contentSize = CGSize(width: totalSize.width, height: height) } }
mit
8fd023b8c4ecc7bb8decf6741428a18e
35.273128
177
0.713384
4.556724
false
false
false
false
Roommate-App/roomy
roomy/Pods/IBAnimatable/Sources/ActivityIndicators/Animations/ActivityIndicatorAnimationBallClipRotateMultiple.swift
2
3238
// // Created by Tom Baranes on 23/08/16. // Copyright (c) 2016 IBAnimatable. All rights reserved. // import UIKit public class ActivityIndicatorAnimationBallClipRotateMultiple: ActivityIndicatorAnimating { // MARK: Properties fileprivate let duration: CFTimeInterval = 0.7 // MARK: ActivityIndicatorAnimating public func configureAnimation(in layer: CALayer, size: CGSize, color: UIColor) { let bigCircleSize: CGFloat = size.width let smallCircleSize: CGFloat = size.width / 2 let longDuration: CFTimeInterval = 1 let timingFunction: TimingFunctionType = .easeInOut let circleLayer1 = makeCircleLayerOf(shape: .ringTwoHalfHorizontal, duration: longDuration, timingFunction: timingFunction, layerSize: layer.frame.size, size: bigCircleSize, color: color, reverse: false) let circleLayer2 = makeCircleLayerOf(shape: .ringTwoHalfVertical, duration: longDuration, timingFunction: timingFunction, layerSize: layer.frame.size, size: smallCircleSize, color: color, reverse: true) layer.addSublayer(circleLayer1) layer.addSublayer(circleLayer2) } } // MARK: - Setup private extension ActivityIndicatorAnimationBallClipRotateMultiple { func makeAnimation(duration: CFTimeInterval, timingFunction: TimingFunctionType, reverse: Bool) -> CAAnimation { // Scale animation let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale") scaleAnimation.keyTimes = [0, 0.5, 1] scaleAnimation.timingFunctionsType = [timingFunction, timingFunction] scaleAnimation.values = [1, 0.6, 1] scaleAnimation.duration = duration // Rotate animation let rotateAnimation = CAKeyframeAnimation(keyPath:"transform.rotation.z") rotateAnimation.keyTimes = scaleAnimation.keyTimes rotateAnimation.timingFunctionsType = [timingFunction, timingFunction] if !reverse { rotateAnimation.values = [0, CGFloat.pi, 2 * CGFloat.pi] } else { rotateAnimation.values = [0, -CGFloat.pi, -2 * CGFloat.pi] } rotateAnimation.duration = duration // Animation let animation = CAAnimationGroup() animation.animations = [scaleAnimation, rotateAnimation] animation.duration = duration animation.repeatCount = .infinity animation.isRemovedOnCompletion = false return animation } // swiftlint:disable:next function_parameter_count func makeCircleLayerOf(shape: ActivityIndicatorShape, duration: CFTimeInterval, timingFunction: TimingFunctionType, layerSize: CGSize, size: CGFloat, color: UIColor, reverse: Bool) -> CALayer { let circleLayer = shape.makeLayer(size: CGSize(width: size, height: size), color: color) let frame = CGRect(x: (layerSize.width - size) / 2, y: (layerSize.height - size) / 2, width: size, height: size) let animation = makeAnimation(duration: duration, timingFunction: timingFunction, reverse: reverse) circleLayer.frame = frame circleLayer.add(animation, forKey: "animation") return circleLayer } }
mit
2e953cd6db2d7978a398ebc2bf32ef28
34.977778
114
0.685608
5.02795
false
false
false
false
pawanpoudel/SwiftNews
SwiftNews/ExternalDependencies/Server/ArticleBuilders/AppleNewsArticleBuilder.swift
1
1644
class AppleNewsArticleBuilder : AbstractArticleBuilder { // MARK: - Creating articles override func createArticleFromRssEntry(rssEntry: RssEntry) -> Article { let article = Article() article.uniqueId = (rssEntry.guid != nil) ? rssEntry.guid : rssEntry.link article.title = rssEntry.title; article.summary = rssEntry.summary; article.sourceUrl = rssEntry.link; article.publishedDate = NSDate(fromInternetDateTimeString: rssEntry.pubDate, formatHint: DateFormatHintRFC822) if let sourceUrl = article.sourceUrl { article.publisher = domainNameFromSourceUrl(sourceUrl) } return article } // MARK: - Extracting publisher info private func domainNameFromSourceUrl(sourceUrl: String) -> String? { if let urlComponents = NSURLComponents(string: sourceUrl), host = urlComponents.host { let hostWithoutWWW = removeWWWFromHost(host) return removeDotComFromHost(hostWithoutWWW) } return nil } private func removeWWWFromHost(host: String) -> String { let stringToRemove = "www." if let range = host.rangeOfString(stringToRemove) { return host.substringFromIndex(range.endIndex) } return host } private func removeDotComFromHost(host: String) -> String { let dotCom = ".com" if let range = host.rangeOfString(dotCom) { return host.substringToIndex(range.startIndex) } return host } }
mit
910d60f4adf71f37d12c8b64acd0484a
30.018868
118
0.613139
4.936937
false
false
false
false
jhaigler94/cs4720-iOS
Pensieve/Pensieve/GooglePlace.swift
1
2218
// // GooglePlace.swift // Feed Me // /* * Copyright (c) 2015 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit import Foundation import CoreLocation //import SwiftyJSON class GooglePlace { let name: String let address: String let coordinate: CLLocationCoordinate2D let placeType: String var photoReference: String? var photo: UIImage? init(dictionary:[String : AnyObject], acceptedTypes: [String]) { let json = JSON(dictionary) name = json["name"].stringValue address = json["vicinity"].stringValue let lat = json["geometry"]["location"]["lat"].doubleValue as CLLocationDegrees let lng = json["geometry"]["location"]["lng"].doubleValue as CLLocationDegrees coordinate = CLLocationCoordinate2DMake(lat, lng) photoReference = json["photos"][0]["photo_reference"].string var foundType = "restaurant" let possibleTypes = acceptedTypes.count > 0 ? acceptedTypes : ["bakery", "bar", "cafe", "grocery_or_supermarket", "restaurant"] for type in json["types"].arrayObject as! [String] { if possibleTypes.contains(type) { foundType = type break } } placeType = foundType } }
apache-2.0
445133d19b80cbefd400ba2a78a02f89
34.774194
131
0.725879
4.436
false
false
false
false
simeonpp/home-hunt
ios-client/HomeHunt/UIViewExtension.swift
1
3368
import Foundation import UIKit import CoreData var loading = UIActivityIndicatorView() extension UIViewController { var appDelegate: AppDelegate { get { return UIApplication.shared.delegate as! AppDelegate } } // Core data var managedObjectContext: NSManagedObjectContext { get { return self.appDelegate.persistentContainer.viewContext } } var apiAuthentication: ApiAuthentication? { get { do { let apiAuthentication = try self.managedObjectContext.fetch(ApiAuthentication.fetchRequest()) if (apiAuthentication.count == 0) { return nil } else { return apiAuthentication.last as? ApiAuthentication } } catch let error as NSError { print("\(error.userInfo)") return nil } } } var cookie: String { get { let apiAuthentication = self.apiAuthentication if (apiAuthentication != nil) { let cookie = apiAuthentication?.cookie return cookie! } else { return "" } } } func deleteApiAuthenticationRecords() { do { let recordsToDelete = try self.managedObjectContext.fetch(ApiAuthentication.fetchRequest()) for apiAuth in recordsToDelete { self.managedObjectContext.delete(apiAuth as! NSManagedObject) } self.appDelegate.saveContext() } catch let error as NSError { print("\(error.userInfo)") } } // Handle bad cookie func handleApiRequestError(error: ApiError) { let weakSelf = self // Delete ApiAuthentication records in CoreData self.deleteApiAuthenticationRecords() // Show user notification to go to the login screen self.showInformDialog(withTitle: error.message, andMessage: "Please log in", andHandler: { action in weakSelf.redirectTologin() }) } // Loading pop up func showLoading() { loading.frame = self.view.frame loading.activityIndicatorViewStyle = .whiteLarge loading.backgroundColor = UIColor(red: 0.95, green: 0.7, blue: 0.3, alpha: 0.7) self.view.addSubview(loading) loading.startAnimating() } func hideLoading() { loading.stopAnimating() loading.removeFromSuperview() } // Information pop up func showInformDialog(withTitle title: String, andMessage errorMessage: String, andHandler handler: @escaping ((UIAlertAction) -> Void)) -> Void { let alert = UIAlertController(title: title, message: errorMessage, preferredStyle: .alert) let okAction = UIAlertAction(title: "Ok", style: .default, handler: handler) alert.addAction(okAction) self.present(alert, animated: true, completion: nil) } // Redirect func redirectTologin() { let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) let loginVC = storyBoard.instantiateViewController(withIdentifier: "loginScreen") self.present(loginVC, animated: false, completion: nil) } }
mit
ce6a9bdc2cd3d5ffa236b5bb9b04e8a8
31.384615
150
0.591746
5.4061
false
false
false
false
cotkjaer/SilverbackFramework
SilverbackFramework/Operators.swift
1
1830
// // Operators.swift // SilverbackFramework // // Created by Christian Otkjær on 18/06/15. // Copyright (c) 2015 Christian Otkjær. All rights reserved. // import Foundation infix operator =?= { precedence 130 } /// compares two optional Equatables and returns true if they are equal or one or both are nil public func =?= <T:Equatable> (lhs: T?, rhs: T?) -> Bool { if lhs == nil { return true } if rhs == nil { return true } return lhs == rhs } infix operator =!= { precedence 130 } /// compares two optional Equatables and returns true if they are equal or both are nil public func =!= <T:Equatable> (lhs: T?, rhs: T?) -> Bool { if lhs == nil && rhs == nil { return true } if lhs == nil { return false } if rhs == nil { return false } return lhs! == rhs! } infix operator ** { associativity left precedence 160 } public func ** (left: Double, right: Double) -> Double { return pow(left, right) } infix operator **= { associativity right precedence 90 } public func **= (inout left: Double, right: Double) { left = left ** right } infix operator >?= { associativity right precedence 90 } ///Assign right to left only if right > left public func >?= <T:Comparable>(inout left: T, right: T) { if right > left { left = right } } ///Assign right to left only if check(left,right) is true public func conditionalAssign<T:Comparable>(inout left: T, right: T, check: ((T,T) -> Bool)) { if check(left,right) { left = right } } ///Wrap try catch log in one go public func tryCatchLog(call: (() throws ->())) { do { try call() } catch let e as NSError { debugPrint(e) } catch { debugPrint("caught unknown error") } } public func box<T : Comparable>(n: T, mi: T, ma: T) -> T { let realMin = min(mi, ma) let realMax = max(mi, ma) return min(realMax, max(realMin, n)) }
mit
4cfd32eef6fc9fd1c45bf6097f773c0b
28.015873
134
0.646061
3.508637
false
false
false
false
bsmith11/ScoreReporter
ScoreReporterCore/ScoreReporterCore/Interface/InfiniteScrollTableFooterView.swift
1
1468
// // InfiniteScrollTableFooterView.swift // ScoreReporterCore // // Created by Brad Smith on 2/9/17. // Copyright © 2017 Brad Smith. All rights reserved. // import UIKit import Anchorage class InfiniteScrollTableFooterView: UIView { fileprivate let spinner = UIActivityIndicatorView(activityIndicatorStyle: .gray) fileprivate let verticalMargin = CGFloat(16.0) var loading = false { didSet { if loading { spinner.startAnimating() } else { spinner.stopAnimating() } } } override init(frame: CGRect) { var size = spinner.intrinsicContentSize size.height += (2.0 * verticalMargin) super.init(frame: CGRect(origin: .zero, size: size)) configureViews() configureLayout() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func tintColorDidChange() { super.tintColorDidChange() spinner.color = tintColor } } // MARK: - Private private extension InfiniteScrollTableFooterView { func configureViews() { spinner.color = tintColor spinner.hidesWhenStopped = true addSubview(spinner) } func configureLayout() { spinner.verticalAnchors == verticalAnchors + verticalMargin spinner.centerXAnchor == centerXAnchor } }
mit
9361d7acebb5a6f0236cf9738bab4526
23.45
84
0.614179
5.296029
false
true
false
false
czechboy0/swift-package-crawler
Sources/AnalyzerLib/AllUniqueDependencies.swift
1
1397
// // AllUniqueDependencies.swift // swift-package-crawler // // Created by Honza Dvorsky on 5/10/16. // // //extracts all dependencies from all packages //and takes all the github ones and adds them to the list //of known packages. grow the web naturally. import PackageSearcherLib import Redbird struct AllUniqueDependencies: Analysis { let db: Redbird func analyze(packageIterator: PackageIterator) throws { print("Starting AllUniqueDependencies analyzer...") var allDependencies: Set<Dependency> = [] var it = packageIterator while let package = try it.next() { let deps = package .allDependencies //filter out local deps .filter { $0.url.lowercased().isRemoteGitURL() } allDependencies.formUnion(deps) } //add the github ones to redis! //TODO: handle case insensitivity let dependencyGitHubUrls = allDependencies .map { $0.url } .filter { $0.hasPrefix("https://github.com/") } .flatMap { $0.githubName() } let counts = try GoogleSearcher().insertIntoDb(db: db, newlyFetched: Array(dependencyGitHubUrls)) print("Added \(counts.added) new dependencies to our list") print("Overall found \(allDependencies.count) dependencies:") } }
mit
9f5f3fc8548b147e9fc3665ad27ec052
28.723404
105
0.617037
4.672241
false
false
false
false
apple/swift-package-manager
Sources/XCBuildSupport/XCBuildDelegate.swift
2
6434
//===----------------------------------------------------------------------===// // // This source file is part of the Swift open source project // // Copyright (c) 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Basics import Foundation import SPMBuildCore import TSCBasic import enum TSCUtility.Diagnostics import protocol TSCUtility.ProgressAnimationProtocol public class XCBuildDelegate { private let buildSystem: SPMBuildCore.BuildSystem private var parser: XCBuildOutputParser! private let observabilityScope: ObservabilityScope private let outputStream: ThreadSafeOutputByteStream private let progressAnimation: ProgressAnimationProtocol private var percentComplete: Int = 0 private let queue = DispatchQueue(label: "org.swift.swiftpm.xcbuild-delegate") /// The verbosity level to print out at private let logLevel: Basics.Diagnostic.Severity /// True if any progress output was emitted. fileprivate var didEmitProgressOutput: Bool = false /// True if any output was parsed. fileprivate(set) var didParseAnyOutput: Bool = false public init( buildSystem: SPMBuildCore.BuildSystem, outputStream: OutputByteStream, progressAnimation: ProgressAnimationProtocol, logLevel: Basics.Diagnostic.Severity, observabilityScope: ObservabilityScope ) { self.buildSystem = buildSystem // FIXME: Implement a class convenience initializer that does this once they are supported // https://forums.swift.org/t/allow-self-x-in-class-convenience-initializers/15924 self.outputStream = outputStream as? ThreadSafeOutputByteStream ?? ThreadSafeOutputByteStream(outputStream) self.progressAnimation = progressAnimation self.logLevel = logLevel self.observabilityScope = observabilityScope self.parser = XCBuildOutputParser(delegate: self) } public func parse(bytes: [UInt8]) { parser.parse(bytes: bytes) } } extension XCBuildDelegate: XCBuildOutputParserDelegate { public func xcBuildOutputParser(_ parser: XCBuildOutputParser, didParse message: XCBuildMessage) { self.didParseAnyOutput = true switch message { case .taskStarted(let info): queue.async { self.didEmitProgressOutput = true let text = self.logLevel.isVerbose ? [info.executionDescription, info.commandLineDisplayString].compactMap { $0 }.joined(separator: "\n") : info.executionDescription self.progressAnimation.update(step: self.percentComplete, total: 100, text: text) self.buildSystem.delegate?.buildSystem(self.buildSystem, willStartCommand: BuildSystemCommand(name: "\(info.taskID)", description: info.executionDescription, verboseDescription: info.commandLineDisplayString)) self.buildSystem.delegate?.buildSystem(self.buildSystem, didStartCommand: BuildSystemCommand(name: "\(info.taskID)", description: info.executionDescription, verboseDescription: info.commandLineDisplayString)) } case .taskOutput(let info): queue.async { self.progressAnimation.clear() self.outputStream <<< info.data self.outputStream <<< "\n" self.outputStream.flush() } case .taskComplete(let info): queue.async { self.buildSystem.delegate?.buildSystem(self.buildSystem, didStartCommand: BuildSystemCommand(name: "\(info.taskID)", description: info.result.rawValue)) } case .buildDiagnostic(let info): queue.async { self.progressAnimation.clear() self.outputStream <<< info.message self.outputStream <<< "\n" self.outputStream.flush() } case .buildOutput(let info): queue.async { self.progressAnimation.clear() self.outputStream <<< info.data self.outputStream <<< "\n" self.outputStream.flush() } case .didUpdateProgress(let info): queue.async { let percent = Int(info.percentComplete) self.percentComplete = percent > 0 ? percent : 0 self.buildSystem.delegate?.buildSystem(self.buildSystem, didUpdateTaskProgress: info.message) } case .buildCompleted(let info): queue.async { switch info.result { case .aborted, .cancelled, .failed: self.outputStream <<< "Build \(info.result)\n" self.outputStream.flush() self.buildSystem.delegate?.buildSystem(self.buildSystem, didFinishWithResult: false) case .ok: if self.didEmitProgressOutput { self.progressAnimation.update(step: 100, total: 100, text: "Build succeeded") } self.buildSystem.delegate?.buildSystem(self.buildSystem, didFinishWithResult: true) } } default: break } } public func xcBuildOutputParser(_ parser: XCBuildOutputParser, didFailWith error: Error) { self.didParseAnyOutput = true self.observabilityScope.emit(.xcbuildOutputParsingError(error)) } } private extension Basics.Diagnostic { static func xcbuildOutputParsingError(_ error: Error) -> Self { let message = (error as? LocalizedError)?.errorDescription ?? error.localizedDescription return .error("failed parsing XCBuild output: \(message)") } } // FIXME: Move to TSC. public final class VerboseProgressAnimation: ProgressAnimationProtocol { private let stream: OutputByteStream public init(stream: OutputByteStream) { self.stream = stream } public func update(step: Int, total: Int, text: String) { stream <<< text <<< "\n" stream.flush() } public func complete(success: Bool) { stream <<< "\n" stream.flush() } public func clear() { } }
apache-2.0
ca0334bc37768819b4fe22ea4e8639ab
39.721519
225
0.636152
5.180354
false
false
false
false
noxytrux/RescueKopter
RescueKopter/Utilities.swift
1
5174
// // Utilities.swift // RescueKopter // // Created by Marcin Pędzimąż on 15.11.2014. // Copyright (c) 2014 Marcin Pedzimaz. All rights reserved. // import UIKit import QuartzCore let kKPTDomain:String! = "KPTDomain" struct imageStruct { var width : Int = 0 var height : Int = 0 var bitsPerPixel : Int = 0 var hasAlpha : Bool = false var bitmapData : UnsafeMutablePointer<Void>? = nil } func createImageData(name: String!,inout texInfo: imageStruct) { let baseImage = UIImage(named: name) let image: CGImageRef? = baseImage?.CGImage if let image = image { texInfo.width = CGImageGetWidth(image) texInfo.height = CGImageGetHeight(image) texInfo.bitsPerPixel = CGImageGetBitsPerPixel(image) texInfo.hasAlpha = CGImageGetAlphaInfo(image) != .None let sizeInBytes = texInfo.width * texInfo.height * texInfo.bitsPerPixel / 8 let bytesPerRow = texInfo.width * texInfo.bitsPerPixel / 8 texInfo.bitmapData = malloc(Int(sizeInBytes)) let context: CGContextRef? = CGBitmapContextCreate( texInfo.bitmapData!, texInfo.width, texInfo.height, 8, bytesPerRow, CGImageGetColorSpace(image), CGImageGetBitmapInfo(image).rawValue) if let context = context { CGContextDrawImage( context, CGRectMake(0, 0, CGFloat(texInfo.width), CGFloat(texInfo.height)), image) } } } func convertToRGBA(inout texInfo: imageStruct) { assert(texInfo.bitsPerPixel == 24, "Wrong image format") let stride = texInfo.width * 4 let newPixels = malloc(stride * texInfo.height) var dstPixels = UnsafeMutablePointer<UInt32>(newPixels) var r: UInt8, g: UInt8, b: UInt8, a: UInt8 a = 255 let sourceStride = texInfo.width * texInfo.bitsPerPixel / 8 let pointer = texInfo.bitmapData! for var j : Int = 0; j < texInfo.height; j++ { for var i : Int = 0; i < sourceStride; i+=3 { let position : Int = Int(i + (sourceStride * j)) var srcPixel = UnsafeMutablePointer<UInt8>(pointer + position) r = srcPixel.memory srcPixel++ g = srcPixel.memory srcPixel++ b = srcPixel.memory srcPixel++ dstPixels.memory = (UInt32(a) << 24 | UInt32(b) << 16 | UInt32(g) << 8 | UInt32(r) ) dstPixels++ } } if let _ = texInfo.bitmapData { free(texInfo.bitmapData!) } texInfo.bitmapData = newPixels texInfo.bitsPerPixel = 32 texInfo.hasAlpha = true } struct mapDataStruct { var object: UInt32 //BGRA! var playerSpawn: UInt8 { return UInt8(object & 0x000000FF) } var ground: UInt8 { return UInt8((object & 0x0000FF00) >> 8) } var grass: UInt8 { return UInt8((object & 0x00FF0000) >> 16) } var wall: UInt8 { return UInt8((object & 0xFF000000) >> 24) } var desc : String { return "(\(self.ground),\(self.grass),\(self.wall),\(self.playerSpawn))" } } func makeNormal(x1:Float32, y1:Float32, z1:Float32, x2:Float32, y2:Float32, z2:Float32, x3:Float32, y3:Float32, z3:Float32, inout rx:Float32, inout ry:Float32, inout rz:Float32 ) { let ax:Float32 = x3-x1, ay:Float32 = y3-y1, az:Float32 = z3-z1, bx:Float32 = x2-x1, by:Float32 = y2-y1, bz:Float32 = z2-z1 rx = ay*bz - by*az ry = bx*az - ax*bz rz = ax*by - bx*ay } func createARGBBitmapContext(inImage: CGImage) -> CGContext! { var bitmapByteCount = 0 var bitmapBytesPerRow = 0 let pixelsWide = CGImageGetWidth(inImage) let pixelsHigh = CGImageGetHeight(inImage) bitmapBytesPerRow = Int(pixelsWide) * 4 bitmapByteCount = bitmapBytesPerRow * Int(pixelsHigh) let colorSpace = CGColorSpaceCreateDeviceRGB() let bitmapData = malloc(Int(bitmapByteCount)) let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedFirst.rawValue) let context = CGBitmapContextCreate(bitmapData, pixelsWide, pixelsHigh, Int(8), Int(bitmapBytesPerRow), colorSpace, bitmapInfo.rawValue) return context } func loadMapData(mapName: String) -> (data: UnsafeMutablePointer<Void>, width: Int, height: Int) { let image = UIImage(named: mapName) let inImage = image?.CGImage let cgContext = createARGBBitmapContext(inImage!) let imageWidth = CGImageGetWidth(inImage) let imageHeight = CGImageGetHeight(inImage) var rect = CGRectZero rect.size.width = CGFloat(imageWidth) rect.size.height = CGFloat(imageHeight) CGContextDrawImage(cgContext, rect, inImage) let dataPointer = CGBitmapContextGetData(cgContext) return (dataPointer, imageWidth, imageHeight) }
mit
566a6a76967c723c543c13fabc3a258d
24.726368
98
0.598143
4.03669
false
false
false
false
vapor/node
Sources/Node/Number/Number.swift
1
5040
extension Node { public typealias Number = StructuredData.Number } extension StructuredData { /// A more comprehensive Number encapsulation to allow /// more nuanced number information to be stored public enum Number { case int(Int) case uint(UInt) case double(Double) } } // MARK: Initializers extension StructuredData.Number { #if swift(>=4) public init<I: BinaryInteger>(_ value: I) { let max = Int64(value) let int = Int(max) self = .int(int) } #else public init<I: Integer>(_ value: I) { let max = value.toIntMax() let int = Int(max) self = .int(int) } #endif public init<U: UnsignedInteger>(_ value: U) { #if swift(>=4) let max = UInt64(value) #else let max = value.toUIntMax() #endif let uint = UInt(max) self = .uint(uint) } public init(_ value: Float) { let double = Double(value) self = .init(double) } public init(_ value: Double) { self = .double(value) } } extension String { fileprivate var number: StructuredData.Number? { if self.contains(".") { return Double(self).flatMap { StructuredData.Number($0) } } guard hasPrefix("-") else { return UInt(self).flatMap { StructuredData.Number($0) } } return Int(self).flatMap { StructuredData.Number($0) } } } // MARK: Accessors extension UInt { internal static var intMax = UInt(Int.max) } extension StructuredData.Number { public var int: Int { switch self { case let .int(i): return i case let .uint(u): guard u < UInt.intMax else { return Int.max } return Int(u) case let .double(d): guard d < Double(Int.max) else { return Int.max } guard d > Double(Int.min) else { return Int.min } return Int(d) } } public var uint: UInt { switch self { case let .int(i): guard i > 0 else { return 0 } return UInt(i) case let .uint(u): return u case let .double(d): guard d < Double(UInt.max) else { return UInt.max } return UInt(d) } } public var double: Double { switch self { case let .int(i): return Double(i) case let .uint(u): return Double(u) case let .double(d): return Double(d) } } } extension StructuredData.Number { public var bool: Bool? { switch self { case let .int(i): switch i { case 1: return true case 0: return false default: return nil } case let .uint(u): switch u { case 1: return true case 0: return false default: return nil } case let .double(d): switch d { case 1.0: return true case 0.0: return false default: return nil } } } } // MARK: Equatable extension StructuredData.Number: Equatable {} public func ==(lhs: StructuredData.Number, rhs: StructuredData.Number) -> Bool { switch (lhs, rhs) { case let (.int(l), .int(r)): return l == r case let (.int(l), .uint(r)): guard l >= 0 && r <= UInt(Int.max) else { return false } return l == Int(r) case let (.int(l), .double(r)): guard r.truncatingRemainder(dividingBy: 1) == 0.0 else { return false } return l == Int(r) case let (.uint(l), .int(r)): guard l <= UInt(Int.max) && r >= 0 else { return false } return Int(l) == r case let (.uint(l), .uint(r)): return l == r case let (.uint(l), .double(r)): guard r >= 0 && r.truncatingRemainder(dividingBy: 1) == 0.0 else { return false } return l == UInt(r) case let (.double(l), .int(r)): guard l.truncatingRemainder(dividingBy: 1) == 0.0 else { return false } return Int(l) == r case let (.double(l), .uint(r)): guard l.truncatingRemainder(dividingBy: 1) == 0.0 else { return false } return UInt(l) == r case let (.double(l), .double(r)): return l == r } } // MARK: Literals extension StructuredData.Number: ExpressibleByIntegerLiteral { public init(integerLiteral value: IntegerLiteralType) { self.init(value) } } extension StructuredData.Number: ExpressibleByFloatLiteral { public init(floatLiteral value: FloatLiteralType) { self.init(value) } } // MARK: String extension StructuredData.Number: CustomStringConvertible { public var description: String { switch self { case let .int(i): return i.description case let .uint(u): return u.description case let .double(d): return d.description } } }
mit
7fc473a0db3b8cc9bbc56f8133c18ffd
24.583756
93
0.534325
4.009547
false
false
false
false
Natoto/SWIFTMIAPP
swiftmi/Pods/Kingfisher/Kingfisher/String+MD5.swift
17
8284
// // String+MD5.swift // Kingfisher // // This file is stolen from HanekeSwift: https://github.com/Haneke/HanekeSwift/blob/master/Haneke/CryptoSwiftMD5.swift // which is a modified version of CryptoSwift: // // To date, adding CommonCrypto to a Swift framework is problematic. See: // http://stackoverflow.com/questions/25248598/importing-commoncrypto-in-a-swift-framework // We're using a subset of CryptoSwift as a (temporary?) alternative. // The following is an altered source version that only includes MD5. The original software can be found at: // https://github.com/krzyzanowskim/CryptoSwift // This is the original copyright notice: /* Copyright (C) 2014 Marcin Krzyżanowski <[email protected]> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. - This notice may not be removed or altered from any source or binary distribution. */ import Foundation extension String { func kf_MD5() -> String { if let data = dataUsingEncoding(NSUTF8StringEncoding) { let MD5Calculator = MD5(data) let MD5Data = MD5Calculator.calculate() let resultBytes = UnsafeMutablePointer<CUnsignedChar>(MD5Data.bytes) let resultEnumerator = UnsafeBufferPointer<CUnsignedChar>(start: resultBytes, count: MD5Data.length) var MD5String = "" for c in resultEnumerator { MD5String += String(format: "%02x", c) } return MD5String } else { return self } } } /** array of bytes, little-endian representation */ func arrayOfBytes<T>(value:T, length:Int? = nil) -> [UInt8] { let totalBytes = length ?? (sizeofValue(value) * 8) let valuePointer = UnsafeMutablePointer<T>.alloc(1) valuePointer.memory = value let bytesPointer = UnsafeMutablePointer<UInt8>(valuePointer) var bytes = [UInt8](count: totalBytes, repeatedValue: 0) for j in 0..<min(sizeof(T),totalBytes) { bytes[totalBytes - 1 - j] = (bytesPointer + j).memory } valuePointer.destroy() valuePointer.dealloc(1) return bytes } extension Int { /** Array of bytes with optional padding (little-endian) */ func bytes(totalBytes: Int = sizeof(Int)) -> [UInt8] { return arrayOfBytes(self, length: totalBytes) } } extension NSMutableData { /** Convenient way to append bytes */ func appendBytes(arrayOfBytes: [UInt8]) { appendBytes(arrayOfBytes, length: arrayOfBytes.count) } } class HashBase { var message: NSData init(_ message: NSData) { self.message = message } /** Common part for hash calculation. Prepare header data. */ func prepare(len:Int = 64) -> NSMutableData { let tmpMessage: NSMutableData = NSMutableData(data: self.message) // Step 1. Append Padding Bits tmpMessage.appendBytes([0x80]) // append one bit (UInt8 with one bit) to message // append "0" bit until message length in bits ≡ 448 (mod 512) var msgLength = tmpMessage.length; var counter = 0; while msgLength % len != (len - 8) { counter++ msgLength++ } let bufZeros = UnsafeMutablePointer<UInt8>(calloc(counter, sizeof(UInt8))) tmpMessage.appendBytes(bufZeros, length: counter) bufZeros.destroy() bufZeros.dealloc(1) return tmpMessage } } func rotateLeft(v:UInt32, n:UInt32) -> UInt32 { return ((v << n) & 0xFFFFFFFF) | (v >> (32 - n)) } class MD5 : HashBase { /** specifies the per-round shift amounts */ private let s: [UInt32] = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21] /** binary integer part of the sines of integers (Radians) */ private let k: [UInt32] = [0xd76aa478,0xe8c7b756,0x242070db,0xc1bdceee, 0xf57c0faf,0x4787c62a,0xa8304613,0xfd469501, 0x698098d8,0x8b44f7af,0xffff5bb1,0x895cd7be, 0x6b901122,0xfd987193,0xa679438e,0x49b40821, 0xf61e2562,0xc040b340,0x265e5a51,0xe9b6c7aa, 0xd62f105d,0x2441453,0xd8a1e681,0xe7d3fbc8, 0x21e1cde6,0xc33707d6,0xf4d50d87,0x455a14ed, 0xa9e3e905,0xfcefa3f8,0x676f02d9,0x8d2a4c8a, 0xfffa3942,0x8771f681,0x6d9d6122,0xfde5380c, 0xa4beea44,0x4bdecfa9,0xf6bb4b60,0xbebfbc70, 0x289b7ec6,0xeaa127fa,0xd4ef3085,0x4881d05, 0xd9d4d039,0xe6db99e5,0x1fa27cf8,0xc4ac5665, 0xf4292244,0x432aff97,0xab9423a7,0xfc93a039, 0x655b59c3,0x8f0ccc92,0xffeff47d,0x85845dd1, 0x6fa87e4f,0xfe2ce6e0,0xa3014314,0x4e0811a1, 0xf7537e82,0xbd3af235,0x2ad7d2bb,0xeb86d391] private let h:[UInt32] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476] func calculate() -> NSData { let tmpMessage = prepare() // hash values var hh = h // Step 2. Append Length a 64-bit representation of lengthInBits let lengthInBits = (message.length * 8) let lengthBytes = lengthInBits.bytes(64 / 8) tmpMessage.appendBytes(Array(lengthBytes.reverse())); // Process the message in successive 512-bit chunks: let chunkSizeBytes = 512 / 8 // 64 var leftMessageBytes = tmpMessage.length for (var i = 0; i < tmpMessage.length; i = i + chunkSizeBytes, leftMessageBytes -= chunkSizeBytes) { let chunk = tmpMessage.subdataWithRange(NSRange(location: i, length: min(chunkSizeBytes,leftMessageBytes))) // break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15 var M:[UInt32] = [UInt32](count: 16, repeatedValue: 0) let range = NSRange(location:0, length: M.count * sizeof(UInt32)) chunk.getBytes(UnsafeMutablePointer<Void>(M), range: range) // Initialize hash value for this chunk: var A:UInt32 = hh[0] var B:UInt32 = hh[1] var C:UInt32 = hh[2] var D:UInt32 = hh[3] var dTemp:UInt32 = 0 // Main loop for j in 0..<k.count { var g = 0 var F:UInt32 = 0 switch (j) { case 0...15: F = (B & C) | ((~B) & D) g = j break case 16...31: F = (D & B) | (~D & C) g = (5 * j + 1) % 16 break case 32...47: F = B ^ C ^ D g = (3 * j + 5) % 16 break case 48...63: F = C ^ (B | (~D)) g = (7 * j) % 16 break default: break } dTemp = D D = C C = B B = B &+ rotateLeft((A &+ F &+ k[j] &+ M[g]), n: s[j]) A = dTemp } hh[0] = hh[0] &+ A hh[1] = hh[1] &+ B hh[2] = hh[2] &+ C hh[3] = hh[3] &+ D } let buf: NSMutableData = NSMutableData(); hh.forEach({ (item) -> () in var i:UInt32 = item.littleEndian buf.appendBytes(&i, length: sizeofValue(i)) }) return buf.copy() as! NSData; } }
mit
4fe9e2843420885a80182b317bb82667
36.457014
213
0.581733
3.680302
false
false
false
false
steve-holmes/music-app-2
MusicApp/Modules/Singer/SingerService.swift
1
3089
// // SingerService.swift // MusicApp // // Created by Hưng Đỗ on 6/13/17. // Copyright © 2017 HungDo. All rights reserved. // import RxSwift protocol SingerService { var repository: SingerRepository { get } var category: CategoryRepository { get } var coordinator: SingerCoordinator { get } var categoryCoordinator: CategoryCoordinator { get } // MARK: Repository func getSingers(on category: String) -> Observable<ItemResponse<SingerInfo>> func resetSingers(on category: String) -> Observable<ItemResponse<SingerInfo>> func getNextSingers(on category: String) -> Observable<ItemResponse<SingerInfo>> // MARK: Category func getCategories() -> Observable<[CategoriesInfo]> // MARK: Coordinator func presentCategories(category: CategoryInfo, infos: [CategoriesInfo]) -> Observable<CategoryInfo?> func presentSingerDetail(_ singer: Singer, category: String, index: Int) -> Observable<Void> func registerSingerPreview(in view: UIView) -> Observable<Void> } class MASingerService: SingerService { let repository: SingerRepository let category: CategoryRepository let coordinator: SingerCoordinator let categoryCoordinator: CategoryCoordinator init(repository: SingerRepository, category: CategoryRepository, coordinator: SingerCoordinator, categoryCoordinator: CategoryCoordinator) { self.repository = repository self.category = category self.coordinator = coordinator self.categoryCoordinator = categoryCoordinator } // MARK: Repository func getSingers(on category: String) -> Observable<ItemResponse<SingerInfo>> { return repository.getSingers(on: category) } func resetSingers(on category: String) -> Observable<ItemResponse<SingerInfo>> { coordinator.removeSingerDetailInfos(category: category) return repository.resetSingers(on: category) } func getNextSingers(on category: String) -> Observable<ItemResponse<SingerInfo>> { return repository.getNextSingers(on: category) } // MARK: Category func getCategories() -> Observable<[CategoriesInfo]> { return category.getSingers() } // MARK: Coordinator func presentCategories(category: CategoryInfo, infos: [CategoriesInfo]) -> Observable<CategoryInfo?> { return Observable.create() { observer in self.categoryCoordinator.presentCategories(category: category, infos: infos) { categoryInfo in if let info = categoryInfo { observer.onNext(info) } observer.onCompleted() } return Disposables.create() } } func presentSingerDetail(_ singer: Singer, category: String, index: Int) -> Observable<Void> { return coordinator.presentSingerDetail(singer, category: category, index: index) } func registerSingerPreview(in view: UIView) -> Observable<Void> { return coordinator.registerSingerPreview(in: view) } }
mit
1e1c1afb03aced0f89e91d9a0a15bef7
32.521739
144
0.682879
4.623688
false
false
false
false
dnevera/ImageMetalling
ImageMetalling-16/ImageMetalling-16/Classes/Lut/SceneView.swift
2
7981
// // SceneView.swift // ImageMetalling-15 // // Created by denis svinarchuk on 24.05.2018. // Copyright © 2018 Dehancer. All rights reserved. // #if os(iOS) import UIKit #else import Cocoa #endif import SceneKit /// /// Базовый view сцены, всякая настроечная шняга и взаимодействие с тачпадом или мышкой. /// Покрутить и отзумить то что лежит в constraintNode. Ноду задаем в конкретной сцене. /// open class SceneView: NSView { // Стандартный угол обзора static var defaultFov:CGFloat = 35 // Просто отступы для сцены от рамок основного окна public var padding:CGFloat = 10 { didSet{ needsDisplay = true } } // Соотношение сторон сцены public var viewPortAspect:CGFloat = 0 { didSet{ needsDisplay = true } } public func reset(node:SCNNode) { updateFov(SceneView.defaultFov) node.pivot = SCNMatrix4Identity node.transform = SCNMatrix4Identity node.scale = SCNVector3(0.5, 0.5, 0.5) } public func resetView(animate:Bool = true, duration:CFTimeInterval = 0.15, complete: ((_ node:SCNNode)->Void)?=nil) { let node = constraintNode() SCNTransaction.begin() SCNTransaction.completionBlock = { complete?(node) } SCNTransaction.animationDuration = duration reset(node: node) SCNTransaction.commit() } open override func layout() { super.layout() _sceneView.frame = originalFrame } public var fov:CGFloat = defaultFov { didSet{ camera.fieldOfView = fov } } public var cameraNode:SCNNode { return _cameraNode } public var lightNode:SCNNode { return _lightNode } private lazy var camera:SCNCamera = { let c = SCNCamera() c.fieldOfView = self.fov c.automaticallyAdjustsZRange = true c.vignettingPower = 0.6 c.bloomIntensity = 1.4 c.bloomBlurRadius = 1.0 c.wantsDepthOfField = true c.focalBlurSampleCount = 30 c.focusDistance = 1.0 return c }() private var lastWidthRatio: CGFloat = 0 private var lastHeightRatio: CGFloat = 0 open func constraintNode() -> SCNNode { return _midNode } public var sceneView:SCNView { return _sceneView } public let scene = SCNScene() open func configure(frame: CGRect){ _sceneView.frame = originalFrame _sceneView.scene = scene addSubview(_sceneView) let pan = NSPanGestureRecognizer(target: self, action: #selector(panGesture(recognizer:))) pan.buttonMask = 1 _sceneView.addGestureRecognizer(pan) let press = NSPressGestureRecognizer(target: self, action: #selector(sceneTapped(recognizer:))) _sceneView.addGestureRecognizer(press) scene.rootNode.addChildNode(_cameraNode) scene.rootNode.addChildNode(_midNode) scene.rootNode.addChildNode(_lightNode) } public override init(frame frameRect: NSRect) { super.init(frame: frameRect) configure(frame: self.frame) } public required init?(coder: NSCoder) { super.init(coder: coder) configure(frame: self.frame) } var originalFrame:NSRect { let size = originalBounds.size let x = (frame.size.width - size.width)/2 let y = (frame.size.height - size.height)/2 return NSRect(x:x, y:y, width:size.width, height:size.height) } var originalBounds:NSRect { get{ let w = viewPortAspect != 0 ? bounds.height * viewPortAspect : bounds.width let h = bounds.height let scaleX = w / maxCanvasSize.width let scaleY = h / maxCanvasSize.height let scale = max(scaleX, scaleY) return NSRect(x:0, y:0, width: w / scale, height: h / scale) } } private var maxCanvasSize:NSSize { return NSSize(width:bounds.size.width - padding, height:bounds.size.height - padding) } private lazy var _midNode:SCNNode = { let node = SCNNode() node.position = SCNVector3(x: 0, y: 0, z: 0) return node }() private lazy var _cameraNode:SCNNode = { let n = SCNNode() //initial camera setup n.position = SCNVector3(x: 0, y: 0, z: 3.0) n.eulerAngles.y = -2 * CGFloat.pi * self.lastWidthRatio n.eulerAngles.x = -CGFloat.pi * self.lastHeightRatio n.camera = self.camera let constraint = SCNLookAtConstraint(target: self.constraintNode()) n.constraints = [constraint] return n }() private lazy var _lightNode:SCNNode = { let light = SCNLight() light.type = SCNLight.LightType.directional light.castsShadow = true light.color = NSColor.white let n = SCNNode() n.light = light n.position = SCNVector3(x: 1, y: 1, z: 1) let constraint = SCNLookAtConstraint(target: self.constraintNode()) n.constraints = [constraint] return n }() private lazy var _sceneView:SCNView = { let f = SCNView(frame: self.bounds, options: ["preferredRenderingAPI" : SCNRenderingAPI.metal]) f.backgroundColor = NSColor.clear f.allowsCameraControl = false f.antialiasingMode = .multisampling8X if let cam = f.pointOfView?.camera { cam.fieldOfView = 0 } return f }() private func updateFov(_ fv: CGFloat){ if fv < 5 { fov = 5 } else if fv > 75 { fov = 75 } else { fov = fv } } open override func scrollWheel(with event: NSEvent) { updateFov(fov - event.deltaY) } private var zoomValue:CGFloat = 1 open override func magnify(with event: NSEvent) { updateFov(fov - event.magnification * 10) } @objc private func panGesture(recognizer: NSPanGestureRecognizer){ let translation = recognizer.translation(in: recognizer.view!) let x = translation.x let y = -translation.y let anglePan = sqrt(pow(x,2)+pow(y,2))*CGFloat.pi/180.0 var rotationVector = SCNVector4() rotationVector.x = y rotationVector.y = x rotationVector.z = 0 rotationVector.w = anglePan constraintNode().rotation = rotationVector if(recognizer.state == .ended) { // let currentPivot = constraintNode().pivot let changePivot = SCNMatrix4Invert( constraintNode().transform) let pivot = SCNMatrix4Mult(changePivot, currentPivot) constraintNode().pivot = pivot constraintNode().transform = SCNMatrix4Identity } } @objc private func sceneTapped(recognizer: NSPressGestureRecognizer) { let location = recognizer.location(in: _sceneView) let hitResults = _sceneView.hitTest(location, options: nil) if hitResults.count > 1 { let result = hitResults[1] let node = result.node let fadeIn = SCNAction.fadeIn(duration: 0.1) let fadeOut = SCNAction.fadeOut(duration: 0.1) let pulse = SCNAction.repeat(SCNAction.sequence([fadeOut,fadeIn]), count: 2) node.runAction(pulse) } } }
mit
e8f24d21ec9dd7f5e765365d4d2be2ec
28.335849
121
0.576023
4.364964
false
false
false
false
tomasharkema/R.swift
Sources/RswiftCore/ResourceTypes/Image.swift
4
1397
// // Image.swift // R.swift // // Created by Mathijs Kadijk on 09-12-15. // From: https://github.com/mac-cain13/R.swift // License: MIT License // import Foundation struct Image: WhiteListedExtensionsResourceType { // See "Supported Image Formats" on https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIImage_Class/ static let supportedExtensions: Set<String> = ["tiff", "tif", "jpg", "jpeg", "gif", "png", "bmp", "bmpf", "ico", "cur", "xbm"] let name: String init(url: URL) throws { try Image.throwIfUnsupportedExtension(url.pathExtension) let filename = url.lastPathComponent let pathExtension = url.pathExtension guard filename.count > 0 && pathExtension.count > 0 else { throw ResourceParsingError.parsingFailed("Filename and/or extension could not be parsed from URL: \(url.absoluteString)") } let extensions = Image.supportedExtensions.joined(separator: "|") let regex = try! NSRegularExpression(pattern: "(~(ipad|iphone))?(@[2,3]x)?\\.(\(extensions))$", options: .caseInsensitive) let fullFileNameRange = NSRange(location: 0, length: filename.count) let pathExtensionToUse = (pathExtension == "png") ? "" : ".\(pathExtension)" name = regex.stringByReplacingMatches(in: filename, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: fullFileNameRange, withTemplate: pathExtensionToUse) } }
mit
09761a0bd5526d43a7f63cdec74b51d1
41.333333
174
0.712241
4.049275
false
false
false
false
tomasharkema/R.swift
Sources/RswiftCore/Util/Struct+InternalProperties.swift
1
5262
// // Struct+InternalProperties.swift // R.swift // // Created by Mathijs Kadijk on 06-10-16. // Copyright © 2016 Mathijs Kadijk. All rights reserved. // import Foundation extension Struct { func addingInternalProperties(forBundleIdentifier bundleIdentifier: String) -> Struct { let internalProperties = [ Let( comments: [], accessModifier: .filePrivate, isStatic: true, name: "hostingBundle", typeDefinition: .inferred(Type._Bundle), value: "Bundle(for: R.Class.self)"), Let( comments: [], accessModifier: .filePrivate, isStatic: true, name: "applicationLocale", typeDefinition: .inferred(Type._Locale), value: "hostingBundle.preferredLocalizations.first.flatMap { Locale(identifier: $0) } ?? Locale.current") ] let internalClasses = [ Class(accessModifier: .filePrivate, type: Type(module: .host, name: "Class")) ] let internalFunctions = [ Function( availables: [], comments: ["Load string from Info.plist file"], accessModifier: .filePrivate, isStatic: true, name: "infoPlistString", generics: nil, parameters: [ .init(name: "path", type: Type._Array.withGenericArgs([Type._String])), .init(name: "key", type: Type._String) ], doesThrow: false, returnType: Type._String.asOptional(), body: """ var dict = hostingBundle.infoDictionary for step in path { guard let obj = dict?[step] as? [String: Any] else { return nil } dict = obj } return dict?[key] as? String """, os: [] ), Function( availables: [], comments: ["Find first language and bundle for which the table exists"], accessModifier: .filePrivate, isStatic: true, name: "localeBundle", generics: nil, parameters: [ .init(name: "tableName", type: Type._String), .init(name: "preferredLanguages", type: Type._Array.withGenericArgs([Type._String])) ], doesThrow: false, returnType: Type._Tuple.withGenericArgs([Type._Locale, Type._Bundle]).asOptional(), body: """ // Filter preferredLanguages to localizations, use first locale var languages = preferredLanguages .map { Locale(identifier: $0) } .prefix(1) .flatMap { locale -> [String] in if hostingBundle.localizations.contains(locale.identifier) { if let language = locale.languageCode, hostingBundle.localizations.contains(language) { return [locale.identifier, language] } else { return [locale.identifier] } } else if let language = locale.languageCode, hostingBundle.localizations.contains(language) { return [language] } else { return [] } } // If there's no languages, use development language as backstop if languages.isEmpty { if let developmentLocalization = hostingBundle.developmentLocalization { languages = [developmentLocalization] } } else { // Insert Base as second item (between locale identifier and languageCode) languages.insert("Base", at: 1) // Add development language as backstop if let developmentLocalization = hostingBundle.developmentLocalization { languages.append(developmentLocalization) } } // Find first language for which table exists // Note: key might not exist in chosen language (in that case, key will be shown) for language in languages { if let lproj = hostingBundle.url(forResource: language, withExtension: "lproj"), let lbundle = Bundle(url: lproj) { let strings = lbundle.url(forResource: tableName, withExtension: "strings") let stringsdict = lbundle.url(forResource: tableName, withExtension: "stringsdict") if strings != nil || stringsdict != nil { return (Locale(identifier: language), lbundle) } } } // If table is available in main bundle, don't look for localized resources let strings = hostingBundle.url(forResource: tableName, withExtension: "strings", subdirectory: nil, localization: nil) let stringsdict = hostingBundle.url(forResource: tableName, withExtension: "stringsdict", subdirectory: nil, localization: nil) if strings != nil || stringsdict != nil { return (applicationLocale, hostingBundle) } // If table is not found for requested languages, key will be shown return nil """, os: [] ) ] var externalStruct = self externalStruct.properties.append(contentsOf: internalProperties) externalStruct.functions.append(contentsOf: internalFunctions) externalStruct.classes.append(contentsOf: internalClasses) return externalStruct } }
mit
ee14444339eff7eb19e15aeac3bcffcb
35.79021
137
0.592473
5.078185
false
false
false
false
bolshedvorsky/swift-corelibs-foundation
Foundation/URLSession/TaskRegistry.swift
6
4520
// Foundation/URLSession/TaskRegistry.swift - URLSession & libcurl // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // // ----------------------------------------------------------------------------- /// /// These are libcurl helpers for the URLSession API code. /// - SeeAlso: https://curl.haxx.se/libcurl/c/ /// - SeeAlso: URLSession.swift /// // ----------------------------------------------------------------------------- import CoreFoundation import Dispatch extension URLSession { /// This helper class keeps track of all tasks, and their behaviours. /// /// Each `URLSession` has a `TaskRegistry` for its running tasks. The /// *behaviour* defines what action is to be taken e.g. upon completion. /// The behaviour stores the completion handler for tasks that are /// completion handler based. /// /// - Note: This must **only** be accessed on the owning session's work queue. class _TaskRegistry { /// Completion handler for `URLSessionDataTask`, and `URLSessionUploadTask`. typealias DataTaskCompletion = (Data?, URLResponse?, Error?) -> Void /// Completion handler for `URLSessionDownloadTask`. typealias DownloadTaskCompletion = (URL?, URLResponse?, Error?) -> Void /// What to do upon events (such as completion) of a specific task. enum _Behaviour { /// Call the `URLSession`s delegate case callDelegate /// Default action for all events, except for completion. case dataCompletionHandler(DataTaskCompletion) /// Default action for all events, except for completion. case downloadCompletionHandler(DownloadTaskCompletion) } fileprivate var tasks: [Int: URLSessionTask] = [:] fileprivate var behaviours: [Int: _Behaviour] = [:] fileprivate var tasksFinishedCallback: (() -> Void)? } } extension URLSession._TaskRegistry { /// Add a task /// /// - Note: This must **only** be accessed on the owning session's work queue. func add(_ task: URLSessionTask, behaviour: _Behaviour) { let identifier = task.taskIdentifier guard identifier != 0 else { fatalError("Invalid task identifier") } guard tasks.index(forKey: identifier) == nil else { if tasks[identifier] === task { fatalError("Trying to re-insert a task that's already in the registry.") } else { fatalError("Trying to insert a task, but a different task with the same identifier is already in the registry.") } } tasks[identifier] = task behaviours[identifier] = behaviour } /// Remove a task /// /// - Note: This must **only** be accessed on the owning session's work queue. func remove(_ task: URLSessionTask) { let identifier = task.taskIdentifier guard identifier != 0 else { fatalError("Invalid task identifier") } guard let tasksIdx = tasks.index(forKey: identifier) else { fatalError("Trying to remove task, but it's not in the registry.") } tasks.remove(at: tasksIdx) guard let behaviourIdx = behaviours.index(forKey: identifier) else { fatalError("Trying to remove task's behaviour, but it's not in the registry.") } behaviours.remove(at: behaviourIdx) guard let allTasksFinished = tasksFinishedCallback else { return } if self.isEmpty { allTasksFinished() } } func notify(on tasksCompetion: @escaping () -> Void) { tasksFinishedCallback = tasksCompetion } var isEmpty: Bool { return tasks.isEmpty } } extension URLSession._TaskRegistry { /// The behaviour that's registered for the given task. /// /// - Note: It is a programming error to pass a task that isn't registered. /// - Note: This must **only** be accessed on the owning session's work queue. func behaviour(for task: URLSessionTask) -> _Behaviour { guard let b = behaviours[task.taskIdentifier] else { fatalError("Trying to access a behaviour for a task that in not in the registry.") } return b } }
apache-2.0
dd8619a701bc00e53ce7c8fe059d0493
40.46789
128
0.622124
4.886486
false
false
false
false
OneBusAway/onebusaway-iphone
Carthage/Checkouts/PromiseKit/Tests/CorePromise/01_PromiseTests.swift
3
2509
import PromiseKit import XCTest class PromiseTests: XCTestCase { override func setUp() { InjectedErrorUnhandler = { _ in } } func testPending() { XCTAssertTrue(Promise<Void>.pending().promise.isPending) XCTAssertFalse(Promise(value: ()).isPending) XCTAssertFalse(Promise<Void>(error: Error.dummy).isPending) } func testResolved() { XCTAssertFalse(Promise<Void>.pending().promise.isResolved) XCTAssertTrue(Promise(value: ()).isResolved) XCTAssertTrue(Promise<Void>(error: Error.dummy).isResolved) } func testFulfilled() { XCTAssertFalse(Promise<Void>.pending().promise.isFulfilled) XCTAssertTrue(Promise(value: ()).isFulfilled) XCTAssertFalse(Promise<Void>(error: Error.dummy).isFulfilled) } func testRejected() { XCTAssertFalse(Promise<Void>.pending().promise.isRejected) XCTAssertTrue(Promise<Void>(error: Error.dummy).isRejected) XCTAssertFalse(Promise(value: ()).isRejected) } func testDispatchQueueAsyncExtensionReturnsPromise() { let ex = expectation(description: "") DispatchQueue.global().promise { XCTAssertFalse(Thread.isMainThread) return 1 }.then { (one: Int) -> Void in XCTAssertEqual(one, 1) ex.fulfill() } waitForExpectations(timeout: 1) } func testDispatchQueueAsyncExtensionCanThrowInBody() { let ex = expectation(description: "") DispatchQueue.global().promise { () -> Int in throw Error.dummy }.then { _ -> Void in XCTFail() }.catch { _ in ex.fulfill() } waitForExpectations(timeout: 1) } func testCustomStringConvertible() { XCTAssert("\(Promise<Void>.pending().promise)".contains("Pending")) XCTAssert("\(Promise(value: ()))".contains("Fulfilled")) XCTAssert("\(Promise<Void>(error: Error.dummy))".contains("Rejected")) } func testCannotFulfillWithError() { let foo = Promise { fulfill, reject in fulfill(Error.dummy) } let bar = Promise<Error>.pending() let baz = Promise(value: Error.dummy) let bad = Promise(value: ()).then { Error.dummy } } #if swift(>=3.1) func testCanMakeVoidPromise() { let promise = Promise() XCTAssert(promise.value is Optional<Void>) } #endif } private enum Error: Swift.Error { case dummy }
apache-2.0
0c0c4f32533b2ef3a36c66a3747f5273
27.191011
78
0.615385
4.716165
false
true
false
false
7factory/mia-HeliumKit
HeliumKitTests/HashFunctions.swift
1
1171
import Foundation struct HashFunctions { private static func hash(data: NSData?) -> String? { guard let data = data else { return nil } let count = data.length / sizeof(UInt8) var input = [UInt8](count: count, repeatedValue: 0) data.getBytes(&input, length:count * sizeof(UInt8)) var hash = [UInt8](count: Int(CC_SHA256_DIGEST_LENGTH), repeatedValue: 0) CC_SHA256(input, CC_LONG(input.count), &hash) let hashData = NSData(bytes: hash, length: hash.count) let hashCount = hashData.length / sizeof(UInt8) var hashArray = [UInt8](count: hashCount, repeatedValue: 0) hashData.getBytes(&hashArray, length:hashCount * sizeof(UInt8)) let res = hashArray.reduce("") { $0 + String(format:"%02x", $1) } return res } static var sha256: String? -> String? = { input in guard let input = input?.lowercaseString, inputData = input.dataUsingEncoding(NSUTF8StringEncoding) else { return nil } return HashFunctions.hash(inputData)?.lowercaseString } }
mit
60fe5088592822aa12dd6d6cfb4629f8
33.441176
81
0.590948
4.21223
false
false
false
false
roambotics/swift
test/Generics/pack-shape-requirements.swift
1
2804
// RUN: %target-swift-frontend -typecheck -enable-experimental-variadic-generics %s -debug-generic-signatures 2>&1 | %FileCheck %s protocol P { associatedtype A } // CHECK-LABEL: inferSameShape(ts:us:) // CHECK-NEXT: Generic signature: <T..., U... where T.shape == U.shape> func inferSameShape<T..., U...>(ts t: T..., us u: U...) where ((T, U)...): Any { } // CHECK-LABEL: desugarSameShape(ts:us:) // CHECK-NEXT: Generic signature: <T..., U... where T : P, T.shape == U.shape, U : P> func desugarSameShape<T..., U...>(ts t: T..., us u: U...) where T: P, U: P, ((T.A, U.A)...): Any { } // CHECK-LABEL: multipleSameShape1(ts:us:vs:) // CHECK-NEXT: Generic signature: <T..., U..., V... where T.shape == U.shape, U.shape == V.shape> func multipleSameShape1<T..., U..., V...>(ts t: T..., us u: U..., vs v: V...) where ((T, U, V)...): Any { } // CHECK-LABEL: multipleSameShape2(ts:us:vs:) // CHECK-NEXT: Generic signature: <T..., U..., V... where T.shape == U.shape, U.shape == V.shape> func multipleSameShape2<T..., U..., V...>(ts t: T..., us u: U..., vs v: V...) where ((V, T, U)...): Any { } // CHECK-LABEL: multipleSameShape3(ts:us:vs:) // CHECK-NEXT: Generic signature: <T..., U..., V... where T.shape == U.shape, U.shape == V.shape> func multipleSameShape3<T..., U..., V...>(ts t: T..., us u: U..., vs v: V...) where ((U, V, T)...): Any { } // CHECK-LABEL: multipleSameShape4(ts:us:vs:) // CHECK-NEXT: Generic signature: <T..., U..., V... where T.shape == U.shape, U.shape == V.shape> func multipleSameShape4<T..., U..., V...>(ts t: T..., us u: U..., vs v: V...) where ((U, T, V)...): Any { } // CHECK-LABEL: multipleSameShape5(ts:us:vs:) // CHECK-NEXT: Generic signature: <T..., U..., V... where T.shape == U.shape, U.shape == V.shape> func multipleSameShape5<T..., U..., V...>(ts t: T..., us u: U..., vs v: V...) where ((T, V, U)...): Any { } // CHECK-LABEL: multipleSameShape6(ts:us:vs:) // CHECK-NEXT: Generic signature: <T..., U..., V... where T.shape == U.shape, U.shape == V.shape> func multipleSameShape6<T..., U..., V...>(ts t: T..., us u: U..., vs v: V...) where ((V, U, T)...): Any { } struct Ts<T...> { struct Us<U...> { // CHECK-LABEL: Ts.Us.packEquality() // CHECK-NEXT: Generic signature: <T..., U... where T == U> func packEquality() where T == U, ((T, U)...): Any { } struct Vs<V...> { // CHECK-LABEL: Ts.Us.Vs.packEquality() // CHECK-NEXT: Generic signature: <T..., U..., V... where T == U, T.shape == V.shape> func packEquality() where T == U, ((U, V)...): Any { } } } } // CHECK-LABEL: expandedParameters(_:transform:) // CHECK-NEXT: Generic signature: <T..., Result... where T.shape == Result.shape> func expandedParameters<T..., Result...>(_ t: T..., transform: ((T) -> Result)...) -> (Result...) { fatalError() }
apache-2.0
57773c39732a3139486a2df8e1e8a27f
40.850746
130
0.557775
2.858308
false
false
false
false
AmitaiB/MyPhotoViewer
MyPhotoViewer/Controllers/PhotoCollectionViewController.swift
1
4400
// // PhotoCollectionViewController.swift // MyPhotoViewer // // Created by Amitai Blickstein on 9/19/17. // Copyright © 2017 Amitai Blickstein. All rights reserved. // import UIKit private let reuseIdentifier = L10n.photoCellReuseID class PhotoCollectionViewController: UICollectionViewController { var photos = [PhotoData]() var images = [UIImage]() init() { super.init(collectionViewLayout: PhotoCollectionViewController.flowLayout) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() // Register cell classes collectionView?.register(PhotoCell.self, forCellWithReuseIdentifier: reuseIdentifier) collectionView?.backgroundColor = .white title = "YAPhotoViewer" setupPullToRefresh() do { try fetchPhotos() } catch { print(error.localizedDescription) } } func setupPullToRefresh() { let refresher = UIRefreshControl() let title = NSLocalizedString("PullToRefresh", comment: "Pull to refresh") refresher.attributedTitle = NSAttributedString(string: title) refresher.addTarget(self, action: #selector(fetchPhotos), for: .valueChanged) collectionView?.refreshControl = refresher } @objc func fetchPhotos() throws { let task = createPhotoDataTask() task.resume() } private func createPhotoDataTask() -> URLSessionTask { let handler = { (data: Data?, response: URLResponse?, error: Error?) in do { if let error = error { throw NetworkError.responseFailed(reason: "Received error: ↴\n\(error.localizedDescription)") } guard let data = data else { throw NetworkError.responseFailed(reason: "Can't find response data.") } let photosData = try JSONDecoder().decode([PhotoData].self, from: data) self.photos = photosData DispatchQueue.main.async { self.collectionView?.refreshControl?.endRefreshing() self.collectionView?.reloadData() } } catch { print(error.localizedDescription) } } let session = URLSession.shared guard let photoBankURL = URL(string: L10n.httpJsonplaceholderTypicodeComPhotos) else { fatalError("Flawed HTTPS address given.") } let photosRequest = URLRequest(url: photoBankURL) let task = session.dataTask(with: photosRequest, completionHandler: handler) return task } // MARK: UICollectionViewDataSource override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return photos.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) guard let photoCell = cell as? PhotoCell else { return cell } photoCell.photo = photos[indexPath.row] return photoCell } // MARK: UICollectionViewDelegate override func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool { return true } override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let photo = photos[indexPath.row] presentDetailView(for: photo) } fileprivate func presentDetailView(for photo: PhotoData) { let detailVC = PhotoDetailViewController() detailVC.modalPresentationStyle = .custom detailVC.transitioningDelegate = self detailVC.photo = photo present(detailVC, animated: true, completion: nil) } } // MARK: - UIViewControllerTransitioningDelegate extension PhotoCollectionViewController: UIViewControllerTransitioningDelegate { func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return PresentDetailTransition() } func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return DismissDetailTransition() } } extension PhotoCollectionViewController { static var flowLayout: UICollectionViewFlowLayout { let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: 106.0, height: 106.0) layout.minimumInteritemSpacing = 1.0 layout.minimumLineSpacing = 1.0 return layout } }
mit
97519c4552366801375afecd0fa16415
29.116438
167
0.742097
4.722879
false
false
false
false
apple/swift-format
Tests/SwiftFormatPrettyPrintTests/ClosureExprTests.swift
1
13469
import SwiftFormatConfiguration final class ClosureExprTests: PrettyPrintTestCase { func testBasicFunctionClosures_noPackArguments() { let input = """ funcCall(closure: <) funcCall(closure: { 4 }) funcCall(closure: { $0 < $1 }) funcCall(closure: { s1, s2 in s1 < s2 }) funcCall(closure: { s1, s2 in return s1 < s2}) funcCall(closure: { s1, s2, s3, s4, s5, s6 in return s1}) funcCall(closure: { s1, s2, s3, s4, s5, s6, s7, s8, s9, s10 in return s1 }) funcCall(param1: 123, closure: { s1, s2, s3 in return s1 }) funcCall(closure: { (s1: String, s2: String) -> Bool in return s1 > s2 }) funcCall(closure: { (s1: String, s2: String, s3: String, s4: String, s5: String) -> Bool in return s1 > s2 }) """ let expected = """ funcCall(closure: <) funcCall(closure: { 4 }) funcCall(closure: { $0 < $1 }) funcCall(closure: { s1, s2 in s1 < s2 }) funcCall(closure: { s1, s2 in return s1 < s2 }) funcCall(closure: { s1, s2, s3, s4, s5, s6 in return s1 }) funcCall(closure: { s1, s2, s3, s4, s5, s6, s7, s8, s9, s10 in return s1 }) funcCall( param1: 123, closure: { s1, s2, s3 in return s1 } ) funcCall(closure: { (s1: String, s2: String) -> Bool in return s1 > s2 }) funcCall(closure: { ( s1: String, s2: String, s3: String, s4: String, s5: String ) -> Bool in return s1 > s2 }) """ var config = Configuration() config.lineBreakBeforeEachArgument = true assertPrettyPrintEqual(input: input, expected: expected, linelength: 42, configuration: config) } func testBasicFunctionClosures_packArguments() { let input = """ funcCall(closure: <) funcCall(closure: { 4 }) funcCall(closure: { $0 < $1 }) funcCall(closure: { s1, s2 in s1 < s2 }) funcCall(closure: { s1, s2 in return s1 < s2}) funcCall(closure: { s1, s2, s3, s4, s5, s6 in return s1}) funcCall(closure: { s1, s2, s3, s4, s5, s6, s7, s8, s9, s10 in return s1 }) funcCall(param1: 123, closure: { s1, s2, s3 in return s1 }) funcCall(closure: { (s1: String, s2: String) -> Bool in return s1 > s2 }) funcCall(closure: { (s1: String, s2: String, s3: String, s4: String, s5: String) -> Bool in return s1 > s2 }) """ let expected = """ funcCall(closure: <) funcCall(closure: { 4 }) funcCall(closure: { $0 < $1 }) funcCall(closure: { s1, s2 in s1 < s2 }) funcCall(closure: { s1, s2 in return s1 < s2 }) funcCall(closure: { s1, s2, s3, s4, s5, s6 in return s1 }) funcCall(closure: { s1, s2, s3, s4, s5, s6, s7, s8, s9, s10 in return s1 }) funcCall( param1: 123, closure: { s1, s2, s3 in return s1 }) funcCall(closure: { (s1: String, s2: String) -> Bool in return s1 > s2 }) funcCall(closure: { ( s1: String, s2: String, s3: String, s4: String, s5: String ) -> Bool in return s1 > s2 }) """ var config = Configuration() config.lineBreakBeforeEachArgument = false assertPrettyPrintEqual(input: input, expected: expected, linelength: 42, configuration: config) } func testTrailingClosure() { let input = """ funcCall() { $1 < $2 } funcCall(param1: 2) { $1 < $2 } funcCall(param1: 2) { s1, s2, s3 in return s1} funcCall(param1: 2) { s1, s2, s3, s4, s5 in return s1} funcCall(param1: 2) { (s1: String, s2: String, s3: String, s4: String, s5: String) -> Bool in return s1 > s2 } """ let expected = """ funcCall() { $1 < $2 } funcCall(param1: 2) { $1 < $2 } funcCall(param1: 2) { s1, s2, s3 in return s1 } funcCall(param1: 2) { s1, s2, s3, s4, s5 in return s1 } funcCall(param1: 2) { ( s1: String, s2: String, s3: String, s4: String, s5: String ) -> Bool in return s1 > s2 } """ var config = Configuration() config.lineBreakBeforeEachArgument = false assertPrettyPrintEqual(input: input, expected: expected, linelength: 40, configuration: config) } func testClosureArgumentsWithTrailingClosure() { let input = """ someFunc({ return s0 }) { return s2 } someLongerFunc({ return s0 }) { input in return s2 } someLongerFunc({ firstInput in someUsefulFunc(firstInput) }) { secondInput in return s2 } someLongerFunc({ firstInput in someUsefulFunc(firstInput) }) { secondInput in return someLineBreakingCall(secondInput) } """ let expected = """ someFunc({ return s0 }) { return s2 } someLongerFunc({ return s0 }) { input in return s2 } someLongerFunc({ firstInput in someUsefulFunc(firstInput) }) { secondInput in return s2 } someLongerFunc({ firstInput in someUsefulFunc(firstInput) }) { secondInput in return someLineBreakingCall( secondInput) } """ assertPrettyPrintEqual(input: input, expected: expected, linelength: 40) } func testClosuresWithIfs() { let input = """ let a = afunc() { if condition1 { return true } return false } let a = afunc() { if condition1 { return true } if condition2 { return true } return false } """ let expected = """ let a = afunc() { if condition1 { return true } return false } let a = afunc() { if condition1 { return true } if condition2 { return true } return false } """ assertPrettyPrintEqual(input: input, expected: expected, linelength: 40) } func testClosureCapture() { let input = """ let a = funcCall() { [weak self] (a: Int) in return a + 1 } let a = funcCall() { [weak self, weak a = self.b] (a: Int) in return a + 1 } let b = funcCall() { [unowned self, weak delegate = self.delegate!] (a: Int, b: String) -> String in return String(a) + b } """ let expected = """ let a = funcCall() { [weak self] (a: Int) in return a + 1 } let a = funcCall() { [weak self, weak a = self.b] (a: Int) in return a + 1 } let b = funcCall() { [unowned self, weak delegate = self.delegate!] (a: Int, b: String) -> String in return String(a) + b } """ assertPrettyPrintEqual(input: input, expected: expected, linelength: 60) } func testClosureCaptureWithoutArguments() { let input = """ let a = { [weak self] in return foo } """ let expected = """ let a = { [weak self] in return foo } """ assertPrettyPrintEqual(input: input, expected: expected, linelength: 30) } func testBodilessClosure() { let input = """ let a = funcCall() { s1, s2 in // Move along, nothing here to see } let a = funcCall() { s1, s2 in } let a = funcCall() {} """ let expected = """ let a = funcCall() { s1, s2 in // Move along, nothing here to see } let a = funcCall() { s1, s2 in } let a = funcCall() {} """ assertPrettyPrintEqual(input: input, expected: expected, linelength: 60) } func testClosureVariables() { let input = """ var someClosure: (Int, Int, Int) -> Bool = { // a comment (a, b, c) in foo() return true } var someOtherClosure: (Int, Int, Int) -> Bool = { foo($0, $1, $2) return true } class Bar { private lazy var foo = { Foo() }() } class Foo { private lazy var bar = { // do some computations return Bar() }() } """ let expected = """ var someClosure: (Int, Int, Int) -> Bool = { // a comment (a, b, c) in foo() return true } var someOtherClosure: (Int, Int, Int) -> Bool = { foo($0, $1, $2) return true } class Bar { private lazy var foo = { Foo() }() } class Foo { private lazy var bar = { // do some computations return Bar() }() } """ assertPrettyPrintEqual(input: input, expected: expected, linelength: 100) } func testArrayClosures() { let input = """ let a = [ { a, b in someFunc(a, b) } ] """ let expected = """ let a = [{ a, b in someFunc(a, b) }] """ assertPrettyPrintEqual(input: input, expected: expected, linelength: 60) } func testClosureOutputGrouping() { let input = """ funcCall(closure: { (s1: String, s2: String, s3: String) throws -> Bool in return s1 > s2 }) funcCall(closure: { (s1: String, s2: String, s3: String) throws -> AVeryLongReturnTypeThatOverflowsFiftyColumns in return s1 > s2 }) funcCall(closure: { (s1: String, s2: String, n: Int) async throws -> AVeryLongReturnTypeThatOverflowsFiftyColumns in return s1 > s2 }) funcCall(closure: { (s1: String, s2: String, s3: String) async throws -> AVeryLongReturnTypeThatOverflowsFiftyColumns in return s1 > s2 }) funcCall(closure: { () throws -> Bool in return s1 > s2 }) funcCall(closure: { () throws -> AVeryLongReturnTypeThatOverflowsFiftyColumns in return s1 > s2 }) funcCall(closure: { () async throws -> AVeryLongReturnTypeThatOverflowsFiftyColumns in return s1 > s2 }) """ let expectedNotGroupingOutput = """ funcCall(closure: { (s1: String, s2: String, s3: String) throws -> Bool in return s1 > s2 }) funcCall(closure: { (s1: String, s2: String, s3: String) throws -> AVeryLongReturnTypeThatOverflowsFiftyColumns in return s1 > s2 }) funcCall(closure: { (s1: String, s2: String, n: Int) async throws -> AVeryLongReturnTypeThatOverflowsFiftyColumns in return s1 > s2 }) funcCall(closure: { (s1: String, s2: String, s3: String) async throws -> AVeryLongReturnTypeThatOverflowsFiftyColumns in return s1 > s2 }) funcCall(closure: { () throws -> Bool in return s1 > s2 }) funcCall(closure: { () throws -> AVeryLongReturnTypeThatOverflowsFiftyColumns in return s1 > s2 }) funcCall(closure: { () async throws -> AVeryLongReturnTypeThatOverflowsFiftyColumns in return s1 > s2 }) """ assertPrettyPrintEqual(input: input, expected: expectedNotGroupingOutput, linelength: 50) let expectedKeepingOutputTogether = """ funcCall(closure: { ( s1: String, s2: String, s3: String ) throws -> Bool in return s1 > s2 }) funcCall(closure: { ( s1: String, s2: String, s3: String ) throws -> AVeryLongReturnTypeThatOverflowsFiftyColumns in return s1 > s2 }) funcCall(closure: { ( s1: String, s2: String, n: Int ) async throws -> AVeryLongReturnTypeThatOverflowsFiftyColumns in return s1 > s2 }) funcCall(closure: { ( s1: String, s2: String, s3: String ) async throws -> AVeryLongReturnTypeThatOverflowsFiftyColumns in return s1 > s2 }) funcCall(closure: { () throws -> Bool in return s1 > s2 }) funcCall(closure: { () throws -> AVeryLongReturnTypeThatOverflowsFiftyColumns in return s1 > s2 }) funcCall(closure: { () async throws -> AVeryLongReturnTypeThatOverflowsFiftyColumns in return s1 > s2 }) """ var config = Configuration() config.prioritizeKeepingFunctionOutputTogether = true assertPrettyPrintEqual( input: input, expected: expectedKeepingOutputTogether, linelength: 50, configuration: config) } func testClosureSignatureAttributes() { let input = """ let a = { @MainActor in print("hi") } let b = { @MainActor in print("hello world") } let c = { @MainActor param in print("hi") } let d = { @MainActor (a: Int) async -> Int in print("hi") } let e = { @MainActor [weak self] in print("hi") } """ let expected = """ let a = { @MainActor in print("hi") } let b = { @MainActor in print("hello world") } let c = { @MainActor param in print("hi") } let d = { @MainActor (a: Int) async -> Int in print("hi") } let e = { @MainActor [weak self] in print("hi") } """ assertPrettyPrintEqual(input: input, expected: expected, linelength: 40) } }
apache-2.0
44c592c057d93b36695f6d97ab61da1b
24.95183
121
0.529883
3.674032
false
false
false
false
cafbuddy/cafbuddy-iOS
Caf Buddy/MealListingHeader.swift
1
1436
// // collectionViewHeader.swift // Caf Buddy // // Created by Jacob Forster on 3/1/15. // Copyright (c) 2015 St. Olaf Acm. All rights reserved. // import Foundation class MealListingHeader : UICollectionReusableView { var headerTitle = UILabel() var rightLine = UIView() var leftLine = UIView() func setTitle(title: String, sectionIndex : Int) { headerTitle.text = title headerTitle.font = UIFont.boldSystemFontOfSize(22) headerTitle.textColor = colorWithHexString(COLOR_DARKER_BLUE) headerTitle.textAlignment = NSTextAlignment.Center var offset : Int = 0 if (sectionIndex == 0) { offset = 5 } headerTitle.frame = CGRectMake(0, CGFloat(offset), self.frame.size.width, 40) offset = 0 if (sectionIndex == 1) { offset = 5 } rightLine.frame = CGRectMake(10, 25 - CGFloat(offset), (self.frame.size.width / 2) - 70, 2) rightLine.backgroundColor = colorWithHexString(COLOR_DARKER_BLUE) leftLine.frame = CGRectMake(self.frame.size.width - (self.frame.size.width / 2) + 60, 25 - CGFloat(offset), (self.frame.size.width / 2) - 70, 2) leftLine.backgroundColor = colorWithHexString(COLOR_DARKER_BLUE) self.addSubview(rightLine) self.addSubview(leftLine) self.addSubview(headerTitle) } }
mit
7097dacde2cfd6bf15dbc06cbc0d0971
28.9375
152
0.616992
4.312312
false
false
false
false
460467069/smzdm
什么值得买7.1.1版本/什么值得买(5月12日)/Classes/Share/Animations/ZZPopPresentAnimation.swift
1
2279
// // ZZPOPPresentAnimation.swift // 什么值得买 // // Created by Wang_ruzhou on 2016/12/17. // Copyright © 2016年 Wang_ruzhou. All rights reserved. // import UIKit class ZZPopPresentAnimation: NSObject { } extension ZZPopPresentAnimation: UIViewControllerAnimatedTransitioning{ func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.6 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let toVc = transitionContext.viewController(forKey: .to) let fromVc = transitionContext.viewController(forKey: .from) toVc?.view.top = kScreenHeight toVc?.view.height = 280 toVc?.view.width = kScreenWidth let maskBtn = UIButton() maskBtn.backgroundColor = UIColor.clear maskBtn.frame = CGRect.init(origin: CGPoint.zero, size: CGSize.init(width: kScreenWidth, height: kScreenHeight)) transitionContext.containerView.addSubview(maskBtn) maskBtn.addTarget(self, action: #selector(maskBtnDidClick), for: .touchUpInside) transitionContext.containerView.addSubview((toVc?.view)!) var t1 = CATransform3DIdentity t1.m34 = 1.0 / -900.0; t1 = CATransform3DScale(t1, 0.95, 0.95, 1) t1 = CATransform3DRotate(t1, 20.0 * .pi / 180.0, 1.0, 0, 0) var t2 = CATransform3DIdentity t2.m34 = 1.0 / -900.0 t2 = CATransform3DScale(t2, 0.95, 0.95, 1) UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseInOut, animations: { fromVc?.view.layer.transform = t1 }) { (finished: Bool) in UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseInOut, animations: { fromVc?.view.alpha = 0.5 fromVc?.view.layer.transform = t2 toVc?.view.bottom = kScreenHeight }, completion: { (finished: Bool) in transitionContext.completeTransition(true) }) } } @objc func maskBtnDidClick(){ NotificationCenter.default.post(name: NSNotification.Name(rawValue: "maskBtnDidClick"), object: self) } }
mit
102f65c456a803ddc3e077e5b88d84a6
33.333333
120
0.631509
4.26742
false
false
false
false
iSame7/Glassy
Glassy/Glassy/GlassyScrollView.swift
1
18003
// // GlassyScrollView.swift // Glassy // // Created by Sameh Mabrouk on 6/27/15. // Copyright (c) 2015 smapps. All rights reserved. // import UIKit //Default Blur Settings. let blurRadious:CGFloat = 14.0 let blurTintColor:UIColor = UIColor(white: 0, alpha: 0.3) let blurDeltaFactor:CGFloat = 1.4 //How much the background move when scrolling. let maxBackgroundMovementVerticle:CGFloat = 30 let maxBackgroundMovementHorizontal:CGFloat = 150 //the value of the fading space on the top between the view and navigation bar let topFadingHeightHalf:CGFloat = 10 @objc protocol GlassyScrollViewDelegate:NSObjectProtocol{ optional func floraView(floraView: AnyObject, numberOfRowsInSection section: Int) -> Int //use this to configure your foregroundView when the frame of the whole view changed optional func glassyScrollView(glassyScrollView: GlassyScrollView, didChangedToFrame fram: CGRect) //make custom blur without messing with default settings optional func glassyScrollView(glassyScrollView: GlassyScrollView, blurForImage image: UIImage) -> UIImage } class GlassyScrollView: UIView, UIScrollViewDelegate { private var backgroundImage: UIImage! //Default blurred is provided. private var blurredBackgroundImage: UIImage! //The view that will contain all the info private var foregroundView: UIView! //Shadow layers. private var topShadowLayer:CALayer! private var botShadowLayer:CALayer! //Masking private var foregroundContainerView:UIView! private var topMaskImageView:UIImageView! private var backgroundScrollView:UIScrollView! var foregroundScrollView:UIScrollView! //How much view is showed up from the bottom. var viewDistanceFromBottom:CGFloat! //set this only when using navigation bar of sorts. let topLayoutGuideLength:CGFloat = 0.0 var constraitView:UIView! var backgroundImageView:UIImageView! var blurredBackgroundImageView:UIImageView! //delegate. var delegate:GlassyScrollViewDelegate! // MARK: - Initialization override init(frame: CGRect) { super.init(frame: frame) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } init(frame: CGRect, backgroundImage:UIImage, blurredImage:UIImage?, viewDistanceFromBottom:CGFloat, foregroundView:UIView) { super.init(frame: frame) self.backgroundImage = backgroundImage if blurredImage != NSNull(){ // self.blurredBackgroundImage = blurredImage self.blurredBackgroundImage = backgroundImage.applyBlurWithRadius(blurRadious, tintColor: blurTintColor, saturationDeltaFactor: blurDeltaFactor, maskImage: nil) } else{ //Check if delegate conform to protocol or not. if self.delegate.respondsToSelector(Selector("glassyScrollView:blurForImage:")){ self.blurredBackgroundImage = self.delegate.glassyScrollView!(self, blurForImage: self.backgroundImage) } else{ //implement live blurring effect. self.blurredBackgroundImage = backgroundImage.applyBlurWithRadius(blurRadious, tintColor: blurTintColor, saturationDeltaFactor: blurDeltaFactor, maskImage: nil) } } self.viewDistanceFromBottom = viewDistanceFromBottom self.foregroundView = foregroundView //Autoresize self.autoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth //Create Views self.createBackgroundView() self.createForegroundView() // self.createTopShadow() self.createBottomShadow() } func initWithFrame(){ } // MARK: - Public Methods func scrollHorizontalRatio(ratio:CGFloat){ // when the view scroll horizontally, this works the parallax magic backgroundScrollView.contentOffset = CGPointMake(maxBackgroundMovementHorizontal+ratio*maxBackgroundMovementHorizontal, backgroundScrollView.contentOffset.y) } func scrollVerticallyToOffset(offsetY:CGFloat){ foregroundScrollView.contentOffset=CGPointMake(foregroundScrollView.contentOffset.x, offsetY) } // MARK: - Setters func setViewFrame(frame:CGRect){ super.frame = frame //work background let bounds:CGRect = CGRectOffset(frame, -frame.origin.x, -frame.origin.y) backgroundScrollView.frame=bounds backgroundScrollView.contentSize = CGSizeMake(bounds.size.width + 2*maxBackgroundMovementHorizontal, self.bounds.size.height+maxBackgroundMovementVerticle) backgroundScrollView.contentOffset=CGPointMake(maxBackgroundMovementHorizontal, 0) constraitView.frame = CGRectMake(0, 0, bounds.size.width + 2*maxBackgroundMovementHorizontal, bounds.size.height+maxBackgroundMovementVerticle) //foreground foregroundContainerView.frame = bounds foregroundScrollView.frame=bounds foregroundView.frame = CGRectOffset(foregroundView.bounds, (foregroundScrollView.frame.size.width - foregroundView.bounds.size.width)/2, foregroundScrollView.frame.size.height - foregroundScrollView.contentInset.top - viewDistanceFromBottom) foregroundScrollView.contentSize=CGSizeMake(bounds.size.width, foregroundView.frame.origin.y + foregroundView.bounds.size.height) //Shadows // topShadowLayer.frame=CGRectMake(0, 0, bounds.size.width, foregroundScrollView.contentInset.top + topFadingHeightHalf) botShadowLayer.frame=CGRectMake(0, bounds.size.height - viewDistanceFromBottom, bounds.size.width, bounds.size.height) // if self.delegate.respondsToSelector(Selector("glassyScrollView:didChangedToFrame:")){ // delegate.glassyScrollView!(self, didChangedToFrame: frame) // } } func setTopLayoutGuideLength(topLayoutGuideLength:CGFloat){ if topLayoutGuideLength==0 { return } //set inset foregroundScrollView.contentInset = UIEdgeInsetsMake(topLayoutGuideLength, 0, 0, 0) //reposition foregroundView.frame = CGRectOffset(foregroundView.bounds, (foregroundScrollView.frame.size.width - foregroundView.bounds.size.width)/2, foregroundScrollView.frame.size.height - foregroundScrollView.contentInset.top - viewDistanceFromBottom) //resize contentSize foregroundScrollView.contentSize = CGSizeMake(self.frame.size.width, foregroundView.frame.origin.y + foregroundView.frame.size.height) //reset the offset if foregroundScrollView.contentOffset.y == 0{ foregroundScrollView.contentOffset = CGPointMake(0, -foregroundScrollView.contentInset.top) } //adding new mask foregroundContainerView.layer.mask = createTopMaskWithSize(CGSizeMake(foregroundContainerView.frame.size.width, foregroundContainerView.frame.size.height), startFadAtTop: foregroundScrollView.contentInset.top - topFadingHeightHalf, endAtBottom: foregroundScrollView.contentInset.top + topFadingHeightHalf, topColor: UIColor(white: 1.0, alpha: 0.0), botColor: UIColor(white: 1.0, alpha: 1.0)) //recreate shadow createTopShadow() } func setViewDistanceFromBottom(vDistanceFromBottom:CGFloat){ viewDistanceFromBottom = vDistanceFromBottom foregroundView.frame = CGRectOffset(foregroundView.bounds, (foregroundScrollView.frame.size.width - foregroundView.bounds.size.width)/2, foregroundScrollView.frame.size.height - foregroundScrollView.contentInset.top - viewDistanceFromBottom) foregroundScrollView.contentSize = CGSizeMake(self.frame.size.width, foregroundView.frame.origin.y + foregroundView.frame.size.height) //shadows botShadowLayer.frame = CGRectOffset(botShadowLayer.bounds, 0, self.frame.size.height - viewDistanceFromBottom) } func setBackgroundImage(backgroundImg:UIImage, overWriteBlur:Bool, animated:Bool, interval:NSTimeInterval){ backgroundImage = backgroundImg if overWriteBlur{ blurredBackgroundImage = backgroundImg.applyBlurWithRadius(blurRadious, tintColor: blurTintColor, saturationDeltaFactor: blurDeltaFactor, maskImage: nil) } if animated{ let previousBackgroundImageView:UIImageView = backgroundImageView let previousBlurredBackgroundImageView:UIImageView = blurredBackgroundImageView createBackgroundImageView() backgroundImageView.alpha = 0 blurredBackgroundImageView.alpha=0 // blur needs to get animated first if the background is blurred if previousBlurredBackgroundImageView.alpha == 1{ UIView.animateWithDuration(interval, animations: { () -> Void in self.blurredBackgroundImageView.alpha=previousBlurredBackgroundImageView.alpha }, completion: { (Bool) -> Void in self.backgroundImageView.alpha=previousBackgroundImageView.alpha previousBackgroundImageView.removeFromSuperview() previousBlurredBackgroundImageView.removeFromSuperview() }) } else{ UIView.animateWithDuration(interval, animations: { () -> Void in self.backgroundImageView.alpha=self.backgroundImageView.alpha self.blurredBackgroundImageView.alpha=previousBlurredBackgroundImageView.alpha }, completion: { (Bool) -> Void in previousBackgroundImageView.removeFromSuperview() previousBlurredBackgroundImageView.removeFromSuperview() }) } } else{ backgroundImageView.image=backgroundImage blurredBackgroundImageView.image=blurredBackgroundImage } } func blurBackground(shouldBlur:Bool){ if shouldBlur{ blurredBackgroundImageView.alpha = 1 } else{ blurredBackgroundImageView.alpha = 0 } } // MARK: - Views creation // MARK: - ScrollViews func createBackgroundView(){ self.backgroundScrollView = UIScrollView(frame: self.frame) self.backgroundScrollView.userInteractionEnabled=true self.backgroundScrollView.contentSize = CGSize(width: self.frame.size.width + (2*maxBackgroundMovementHorizontal), height: self.frame.size.height+maxBackgroundMovementVerticle) self.backgroundScrollView.contentOffset = CGPointMake(maxBackgroundMovementHorizontal, 0) self.addSubview(self.backgroundScrollView) self.constraitView = UIView(frame: CGRectMake(0, 0, self.frame.size.width + (2*maxBackgroundMovementHorizontal), self.frame.size.height+maxBackgroundMovementVerticle)) self.backgroundScrollView.addSubview(self.constraitView) self.createBackgroundImageView() } func createBackgroundImageView(){ self.backgroundImageView = UIImageView(image: self.backgroundImage) self.backgroundImageView.setTranslatesAutoresizingMaskIntoConstraints(false) self.backgroundImageView.contentMode = UIViewContentMode.ScaleAspectFill self.constraitView.addSubview(self.backgroundImageView) self.blurredBackgroundImageView = UIImageView(image: self.blurredBackgroundImage) self.blurredBackgroundImageView.setTranslatesAutoresizingMaskIntoConstraints(false) self.blurredBackgroundImageView.contentMode = UIViewContentMode.ScaleAspectFill self.blurredBackgroundImageView.alpha=0 self.constraitView.addSubview(self.blurredBackgroundImageView) var viewBindingsDict: NSMutableDictionary = NSMutableDictionary() viewBindingsDict.setValue(backgroundImageView, forKey: "backgroundImageView") self.constraitView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[backgroundImageView]|", options: nil, metrics: nil, views: viewBindingsDict as [NSObject : AnyObject])) self.constraitView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[backgroundImageView]|", options: nil, metrics: nil, views: viewBindingsDict as [NSObject : AnyObject])) var blurredViewBindingsDict: NSMutableDictionary = NSMutableDictionary() blurredViewBindingsDict.setValue(blurredBackgroundImageView, forKey: "blurredBackgroundImageView") self.constraitView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[blurredBackgroundImageView]|", options: nil, metrics: nil, views: blurredViewBindingsDict as [NSObject : AnyObject])) self.constraitView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[blurredBackgroundImageView]|", options: nil, metrics: nil, views: blurredViewBindingsDict as [NSObject : AnyObject])) } func createForegroundView(){ self.foregroundContainerView = UIView(frame: self.frame) self.addSubview(self.foregroundContainerView) self.foregroundScrollView=UIScrollView(frame: self.frame) self.foregroundScrollView.delegate=self self.foregroundScrollView.showsVerticalScrollIndicator=false self.foregroundScrollView.showsHorizontalScrollIndicator=false self.foregroundContainerView.addSubview(self.foregroundScrollView) let tapRecognizer:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("foregroundTapped:")) foregroundScrollView.addGestureRecognizer(tapRecognizer) foregroundView.frame = CGRectOffset(foregroundView.bounds, (foregroundScrollView.frame.size.width - foregroundView.frame.size.width)/2, foregroundScrollView.frame.size.height - viewDistanceFromBottom) foregroundScrollView.addSubview(foregroundView) foregroundScrollView.contentSize = CGSizeMake(self.frame.size.width, foregroundView.frame.origin.y + foregroundView.frame.size.height) } // MARK: - Shadow and mask layer func createTopMaskWithSize(size:CGSize, startFadAtTop:CGFloat, endAtBottom:CGFloat, topColor:UIColor, botColor:UIColor) -> CALayer{ let top = startFadAtTop / size.height let bottom = endAtBottom / size.height let maskLayer:CAGradientLayer = CAGradientLayer() maskLayer.anchorPoint = CGPointZero maskLayer.startPoint = CGPointMake(0.5, 0.0) maskLayer.endPoint = CGPointMake(0.5, 1.0) maskLayer.colors = NSArray(arrayLiteral: topColor.CGColor, topColor.CGColor, botColor.CGColor, botColor.CGColor) as [AnyObject] maskLayer.locations = NSArray(arrayLiteral: 0.0, top, bottom, 1.0) as [AnyObject] maskLayer.frame = CGRectMake(0, 0, size.width, size.height) return maskLayer } func createTopShadow(){ topShadowLayer = self.createTopMaskWithSize(CGSizeMake(foregroundContainerView.frame.size.width, foregroundScrollView.contentInset.top + topFadingHeightHalf), startFadAtTop:foregroundScrollView.contentInset.top + topFadingHeightHalf , endAtBottom: foregroundScrollView.contentInset.top + topFadingHeightHalf, topColor: UIColor(white: 0, alpha: 0.15), botColor: UIColor(white: 0, alpha: 0)) self.layer.insertSublayer(topShadowLayer, below: foregroundContainerView.layer) } func createBottomShadow(){ botShadowLayer = self.createTopMaskWithSize(CGSizeMake(self.frame.size.width, viewDistanceFromBottom), startFadAtTop:0 , endAtBottom: viewDistanceFromBottom, topColor: UIColor(white: 0, alpha: 0), botColor: UIColor(white: 0, alpha: 0.8)) self.layer.insertSublayer(botShadowLayer, below: foregroundContainerView.layer) } // MARK: - foregroundScrollView Tap Action func foregroundTapped(tapRecognizer:UITapGestureRecognizer){ let tappedPoint:CGPoint = tapRecognizer.locationInView(foregroundScrollView) if tappedPoint.y < foregroundScrollView.frame.size.height{ var ratio:CGFloat! if foregroundScrollView.contentOffset.y == foregroundScrollView.contentInset.top{ ratio=1 } else{ ratio=0 } foregroundScrollView.setContentOffset(CGPointMake(0, ratio * foregroundView.frame.origin.y - foregroundScrollView.contentInset.top), animated: true) } } // MARK: - Delegate // MARK: - UIScrollView func scrollViewDidScroll(scrollView: UIScrollView) { //translate into ratio to height var ratio:CGFloat = (scrollView.contentOffset.y + foregroundScrollView.contentInset.top)/(foregroundScrollView.frame.size.height - foregroundScrollView.contentInset.top - viewDistanceFromBottom) if ratio < 0{ ratio = 0 } if ratio > 1{ ratio=1 } //set background scroll backgroundScrollView.contentOffset = CGPointMake(maxBackgroundMovementHorizontal, ratio * maxBackgroundMovementVerticle) //set alpha blurredBackgroundImageView.alpha = ratio } func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { var ratio = (targetContentOffset.memory.y + foregroundScrollView.contentInset.top) / (foregroundScrollView.frame.size.height - foregroundScrollView.contentInset.top - viewDistanceFromBottom) if ratio > 0 && ratio < 1{ if velocity.y == 0{ if ratio>0.5{ratio=1} else{ratio=0} } else if velocity.y > 0 { if ratio>0.1{ratio=1} else{ratio=0} } else { if ratio>0.9{ratio=1} else{ratio=0} } targetContentOffset.memory.y=ratio * foregroundView.frame.origin.y - foregroundScrollView.contentInset.top } } }
mit
77b70b9fa2e533d753da4ef8f2a09955
40.196796
399
0.716992
5.219774
false
false
false
false
huonw/swift
stdlib/public/SDK/Network/NWEndpoint.swift
1
25802
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Darwin import Foundation import _SwiftNetworkOverlayShims internal extension sockaddr_in { init(_ address:in_addr, _ port: in_port_t) { self.init(sin_len: UInt8(MemoryLayout<sockaddr_in>.size), sin_family: sa_family_t(AF_INET), sin_port: port, sin_addr: address, sin_zero: (0, 0, 0, 0, 0, 0, 0, 0)) } func withSockAddr<ReturnType>(_ body: (_ sa: UnsafePointer<sockaddr>) throws -> ReturnType) rethrows -> ReturnType { // We need to create a mutable copy of `self` so that we can pass it to `withUnsafePointer(to:_:)`. var sin = self return try withUnsafePointer(to: &sin) { try $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { try body($0) } } } } internal extension sockaddr_in6 { init(_ address:in6_addr, _ port: in_port_t, flow: UInt32 = 0, scope: UInt32 = 0) { self.init(sin6_len: UInt8(MemoryLayout<sockaddr_in6>.size), sin6_family: sa_family_t(AF_INET6), sin6_port: port, sin6_flowinfo: flow, sin6_addr: address, sin6_scope_id: scope) } func withSockAddr<ReturnType>(_ body: (_ sa: UnsafePointer<sockaddr>) throws -> ReturnType) rethrows -> ReturnType { // We need to create a mutable copy of `self` so that we can pass it to `withUnsafePointer(to:_:)`. var sin6 = self return try withUnsafePointer(to: &sin6) { try $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { try body($0) } } } } internal extension in_addr { init(address: UInt32) { self.init() self.s_addr = address.bigEndian } } @available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) private func getaddrinfo_numeric(_ string: String, family: Int32 = 0) -> NWEndpoint.Host? { // Determine if this string has an interface scope specified "127.0.0.1%lo0" or "fe80::1%lo0" var string = string var interface : NWInterface? = nil if let range = string.range(of: "%", options: String.CompareOptions.backwards) { interface = NWInterface(String(string[range.upperBound...])) if interface != nil { string.removeSubrange(range.lowerBound...) } } // call getaddrinfo var hints = addrinfo(ai_flags: AI_NUMERICHOST, ai_family: family, ai_socktype: SOCK_STREAM, ai_protocol: 0, ai_addrlen: 0, ai_canonname: nil, ai_addr: nil, ai_next: nil) var resolved : UnsafeMutablePointer<addrinfo>? = nil // After this point we must ensure we free addrinfo before we return guard getaddrinfo(string, nil, &hints, &resolved) == 0, let addrinfo = resolved else { return nil } var result: NWEndpoint.Host? = nil if let sa = addrinfo.pointee.ai_addr { if (sa.pointee.sa_family == AF_INET) { sa.withMemoryRebound(to: sockaddr_in.self, capacity: 1, { (sin) -> Void in result = NWEndpoint.Host.ipv4(IPv4Address(sin.pointee.sin_addr, interface)) }) } else if (sa.pointee.sa_family == AF_INET6) { sa.withMemoryRebound(to: sockaddr_in6.self, capacity: 1, { (sin6) -> Void in if (sin6.pointee.sin6_scope_id != 0) { interface = NWInterface(Int(sin6.pointee.sin6_scope_id)) } let ipv6 = IPv6Address(sin6.pointee.sin6_addr, interface); if ipv6.isIPv4Mapped && family == AF_UNSPEC, let ipv4 = ipv6.asIPv4 { // Treat IPv4 mapped as IPv4 result = NWEndpoint.Host.ipv4(ipv4) } else { result = NWEndpoint.Host.ipv6(ipv6) } }) } } freeaddrinfo(addrinfo) return result } private func getnameinfo_numeric(address: UnsafeRawPointer) -> String { let sa = address.assumingMemoryBound(to: sockaddr.self) var result : String? = nil let maxLen = socklen_t(100) let storage = UnsafeMutablePointer<Int8>.allocate(capacity: Int(maxLen)) if (getnameinfo(sa, socklen_t(sa.pointee.sa_len), storage, maxLen, nil, 0, NI_NUMERICHOST) == 0) { result = String(cString: storage) } storage.deallocate() return result ?? "?" } /// An IP address @available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) public protocol IPAddress { /// Fetch the raw address as data var rawValue: Data { get } /// Create an IP address from data. The length of the data must /// match the expected length of addresses in the address family /// (four bytes for IPv4, and sixteen bytes for IPv6) init?(_ rawValue: Data, _ interface: NWInterface?) /// Create an IP address from an address literal string. /// If the string contains '%' to indicate an interface, the interface will be /// associated with the address, such as "::1%lo0" being associated with the loopback /// interface. /// This function does not perform host name to address resolution. This is the same as calling getaddrinfo /// and using AI_NUMERICHOST. init?(_ string: String) /// The interface the address is scoped to, if any. var interface: NWInterface? { get } /// Indicates if this address is loopback var isLoopback : Bool { get } /// Indicates if this address is link-local var isLinkLocal : Bool { get } /// Indicates if this address is multicast var isMulticast : Bool { get } } /// IPv4Address /// Base type to hold an IPv4 address and convert between strings and raw bytes. /// Note that an IPv4 address may be scoped to an interface. @available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) public struct IPv4Address: IPAddress, Hashable, CustomDebugStringConvertible { /// The IPv4 any address used for listening public static let any = IPv4Address(in_addr(address: INADDR_ANY), nil) /// The IPv4 broadcast address used to broadcast to all hosts public static let broadcast = IPv4Address(in_addr(address: INADDR_BROADCAST), nil) /// The IPv4 loopback address public static let loopback = IPv4Address(in_addr(address: INADDR_LOOPBACK), nil) /// The IPv4 all hosts multicast group public static let allHostsGroup = IPv4Address(in_addr(address: INADDR_ALLHOSTS_GROUP), nil) /// The IPv4 all routers multicast group public static let allRoutersGroup = IPv4Address(in_addr(address: INADDR_ALLRTRS_GROUP), nil) /// The IPv4 all reports multicast group for ICMPv3 membership reports public static let allReportsGroup = IPv4Address(in_addr(address: INADDR_ALLRPTS_GROUP), nil) /// The IPv4 multicast DNS group. (Note: Use the dns_sd APIs instead of creating your own responder/resolver) public static let mdnsGroup = IPv4Address(in_addr(address: INADDR_ALLMDNS_GROUP), nil) /// Indicates if this IPv4 address is loopback (127.0.0.1) public var isLoopback : Bool { return self == IPv4Address.loopback } /// Indicates if this IPv4 address is link-local public var isLinkLocal : Bool { let linkLocalMask: UInt32 = IN_CLASSB_NET let linkLocalCompare: UInt32 = IN_LINKLOCALNETNUM return (self.address.s_addr & linkLocalMask.bigEndian) == linkLocalCompare.bigEndian } /// Indicates if this IPv4 address is multicast public var isMulticast : Bool { let multicastMask: UInt32 = IN_CLASSD_NET let multicastCompare: UInt32 = INADDR_UNSPEC_GROUP return (self.address.s_addr & multicastMask.bigEndian) == multicastCompare.bigEndian } /// Fetch the raw address (four bytes) public var rawValue: Data { var temporary = self.address return withUnsafeBytes(of: &temporary) { (bytes) -> Data in Data(bytes) } } internal init(_ address: in_addr, _ interface: NWInterface?) { self.address = address self.interface = interface } /// Create an IPv4 address from a 4-byte data. Optionally specify an interface. /// /// - Parameter rawValue: The raw bytes of the IPv4 address, must be exactly 4 bytes or init will fail. /// - Parameter interface: An optional network interface to scope the address to. Defaults to nil. /// - Returns: An IPv4Address or nil if the Data parameter did not contain an IPv4 address. public init?(_ rawValue: Data, _ interface: NWInterface? = nil) { if (rawValue.count != MemoryLayout<in_addr>.size) { return nil } let v4 = rawValue.withUnsafeBytes { (ptr: UnsafePointer<in_addr>) -> in_addr in return ptr.pointee } self.init(v4, interface) } /// Create an IPv4 address from an address literal string. /// /// This function does not perform host name to address resolution. This is the same as calling getaddrinfo /// and using AI_NUMERICHOST. /// /// - Parameter string: An IPv4 address literal string such as "127.0.0.1", "169.254.8.8%en0". /// - Returns: An IPv4Address or nil if the string parameter did not /// contain an IPv4 address literal. public init?(_ string: String) { guard let result = getaddrinfo_numeric(string, family: AF_INET) else { return nil } guard case .ipv4(let address) = result else { return nil } self = address } fileprivate let address : in_addr /// The interface the address is scoped to, if any. public let interface: NWInterface? // Hashable public static func == (lhs: IPv4Address, rhs: IPv4Address) -> Bool { return lhs.address.s_addr == rhs.address.s_addr && lhs.interface == rhs.interface } public func hash(into hasher: inout Hasher) { hasher.combine(self.address.s_addr) hasher.combine(self.interface) } // CustomDebugStringConvertible public var debugDescription: String { var sin = sockaddr_in(self.address, 0) let addressString = getnameinfo_numeric(address: &sin) if let interface = self.interface { return String("\(addressString)%\(interface)") } else { return addressString } } } /// IPv6Address /// Base type to hold an IPv6 address and convert between strings and raw bytes. /// Note that an IPv6 address may be scoped to an interface. @available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) public struct IPv6Address: IPAddress, Hashable, CustomDebugStringConvertible { /// IPv6 any address public static let any = IPv6Address(in6addr_any, nil) /// IPv6 broadcast address public static let broadcast = IPv6Address(in6addr_any, nil) /// IPv6 loopback address public static let loopback = IPv6Address(in6addr_loopback, nil) /// IPv6 all node local nodes multicast public static let nodeLocalNodes = IPv6Address(in6addr_nodelocal_allnodes, nil) /// IPv6 all link local nodes multicast public static let linkLocalNodes = IPv6Address(in6addr_linklocal_allnodes, nil) /// IPv6 all link local routers multicast public static let linkLocalRouters = IPv6Address(in6addr_linklocal_allrouters, nil) public enum Scope: UInt8 { case nodeLocal = 1 case linkLocal = 2 case siteLocal = 5 case organizationLocal = 8 case global = 0x0e } /// Is the Any address "::0" public var isAny : Bool { return self.address.__u6_addr.__u6_addr32.0 == 0 && self.address.__u6_addr.__u6_addr32.1 == 0 && self.address.__u6_addr.__u6_addr32.2 == 0 && self.address.__u6_addr.__u6_addr32.3 == 0 } /// Is the looback address "::1" public var isLoopback : Bool { return self.address.__u6_addr.__u6_addr32.0 == 0 && self.address.__u6_addr.__u6_addr32.1 == 0 && self.address.__u6_addr.__u6_addr32.2 == 0 && self.address.__u6_addr.__u6_addr32.3 != 0 && self.address.__u6_addr.__u6_addr32.3 == UInt32(1).bigEndian } /// Is an IPv4 compatible address public var isIPv4Compatabile : Bool { return self.address.__u6_addr.__u6_addr32.0 == 0 && self.address.__u6_addr.__u6_addr32.1 == 0 && self.address.__u6_addr.__u6_addr32.2 == 0 && self.address.__u6_addr.__u6_addr32.3 != 0 && self.address.__u6_addr.__u6_addr32.3 != UInt32(1).bigEndian } /// Is an IPv4 mapped address such as "::ffff:1.2.3.4" public var isIPv4Mapped : Bool { return self.address.__u6_addr.__u6_addr32.0 == 0 && self.address.__u6_addr.__u6_addr32.1 == 0 && self.address.__u6_addr.__u6_addr32.2 == UInt32(0x0000ffff).bigEndian } /// For IPv6 addresses that are IPv4 mapped, returns the IPv4 address /// /// - Returns: nil unless the IPv6 address was mapped or compatible, in which case the IPv4 address is /// returned. public var asIPv4 : IPv4Address? { guard self.isIPv4Mapped || self.isIPv4Compatabile else { return nil } return IPv4Address(in_addr(address: self.address.__u6_addr.__u6_addr32.3.bigEndian), self.interface) } /// Is a 6to4 IPv6 address public var is6to4 : Bool { return self.address.__u6_addr.__u6_addr16.0 == UInt16(0x2002).bigEndian } /// Is a link-local address public var isLinkLocal : Bool { return self.address.__u6_addr.__u6_addr8.0 == UInt8(0xfe) && (self.address.__u6_addr.__u6_addr8.1 & 0xc0) == 0x80 } /// Is multicast public var isMulticast : Bool { return self.address.__u6_addr.__u6_addr8.0 == 0xff } /// Returns the multicast scope public var multicastScope : IPv6Address.Scope? { if (self.isMulticast) { return IPv6Address.Scope(rawValue: self.address.__u6_addr.__u6_addr8.1 & 0x0f) } return nil } internal init(_ ip6: in6_addr, _ interface: NWInterface?) { self.address = ip6 self.interface = interface } /// Create an IPv6 from a raw 16 byte value and optional interface /// /// - Parameter rawValue: A 16 byte IPv6 address /// - Parameter interface: An optional interface the address is scoped to. Defaults to nil. /// - Returns: nil unless the raw data contained an IPv6 address public init?(_ rawValue: Data, _ interface: NWInterface? = nil) { if (rawValue.count != MemoryLayout<in6_addr>.size) { return nil } let v6 = rawValue.withUnsafeBytes { (ptr: UnsafePointer<in6_addr>) -> in6_addr in return ptr.pointee } self.init(v6, interface) } /// Create an IPv6 address from a string literal such as "fe80::1%lo0" or "2001:DB8::5" /// /// This function does not perform hostname resolution. This is similar to calling getaddrinfo with /// AI_NUMERICHOST. /// /// - Parameter string: An IPv6 address literal string. /// - Returns: nil unless the string contained an IPv6 literal public init?(_ string: String) { guard let result = getaddrinfo_numeric(string, family: AF_INET6) else { return nil } guard case .ipv6(let address) = result else { return nil } self = address } fileprivate let address: in6_addr /// The interface the address is scoped to, if any. public let interface: NWInterface? /// Fetch the raw address (sixteen bytes) public var rawValue: Data { var temporary = self.address return withUnsafeBytes(of: &temporary) { (bytes) -> Data in Data(bytes) } } // Hashable public static func ==(lhs: IPv6Address, rhs: IPv6Address) -> Bool { return lhs.address.__u6_addr.__u6_addr32.0 == rhs.address.__u6_addr.__u6_addr32.0 && lhs.address.__u6_addr.__u6_addr32.1 == rhs.address.__u6_addr.__u6_addr32.1 && lhs.address.__u6_addr.__u6_addr32.2 == rhs.address.__u6_addr.__u6_addr32.2 && lhs.address.__u6_addr.__u6_addr32.3 == rhs.address.__u6_addr.__u6_addr32.3 && lhs.interface == rhs.interface } public func hash(into hasher: inout Hasher) { hasher.combine(self.address.__u6_addr.__u6_addr32.0) hasher.combine(self.address.__u6_addr.__u6_addr32.1) hasher.combine(self.address.__u6_addr.__u6_addr32.2) hasher.combine(self.address.__u6_addr.__u6_addr32.3) hasher.combine(self.interface) } // CustomDebugStringConvertible public var debugDescription: String { var sin6 = sockaddr_in6(self.address, 0) let addressString = getnameinfo_numeric(address: &sin6) if let interface = self.interface { return String("\(addressString)%\(interface)") } else { return addressString } } } @available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) /// NWEndpoint represents something that can be connected to. public enum NWEndpoint: Hashable, CustomDebugStringConvertible { // Depends on non-exhaustive enum support for forward compatibility - in the event we need to add // a new case in the future // https://github.com/apple/swift-evolution/blob/master/proposals/0192-non-exhaustive-enums.md /// A host port endpoint represents an endpoint defined by the host and port. case hostPort(host: NWEndpoint.Host, port: NWEndpoint.Port) /// A service endpoint represents a Bonjour service case service(name: String, type: String, domain: String, interface: NWInterface?) /// A unix endpoint represnts a path that supports connections using AF_UNIX domain sockets. case unix(path: String) /// A Host is a name or address public enum Host: Hashable, CustomDebugStringConvertible, ExpressibleByStringLiteral { public typealias StringLiteralType = String public func hash(into hasher: inout Hasher) { switch self { case .name(let hostName, let hostInterface): hasher.combine(hostInterface) hasher.combine(hostName) case .ipv4(let v4Address): hasher.combine(v4Address) case .ipv6(let v6Address): hasher.combine(v6Address) } } /// A host specified as a name and optional interface scope case name(String, NWInterface?) /// A host specified as an IPv4 address case ipv4(IPv4Address) /// A host specified an an IPv6 address case ipv6(IPv6Address) public init(stringLiteral: StringLiteralType) { self.init(stringLiteral) } /// Create a host from a string. /// /// This is the preferred way to create a host. If the string is an IPv4 address literal ("198.51.100.2"), an /// IPv4 host will be created. If the string is an IPv6 address literal ("2001:DB8::2", "fe80::1%lo", etc), an IPv6 /// host will be created. If the string is an IPv4 mapped IPv6 address literal ("::ffff:198.51.100.2") an IPv4 /// host will be created. Otherwise, a named host will be created. /// /// - Parameter string: An IPv4 address literal, an IPv6 address literal, or a hostname. /// - Returns: A Host object public init(_ string: String) { if let result = getaddrinfo_numeric(string) { self = result } else { if let range = string.range(of: "%", options: String.CompareOptions.backwards), let interface = NWInterface(String(string[range.upperBound...])){ self = .name(String(string[..<range.lowerBound]), interface) } else { self = .name(string, nil) } } } /// Returns the interface the host is scoped to if any public var interface : NWInterface? { switch self { case .ipv4(let ip4): return ip4.interface case .ipv6(let ip6): return ip6.interface case .name(_, let interface): return interface } } public var debugDescription: String { switch self { case .ipv4(let ip4): return ip4.debugDescription case .ipv6(let ip6): return ip6.debugDescription case .name(let name, let interface): if let interface = interface { return String("\(name)%\(interface)") } else { return name } } } } /// A network port (TCP or UDP) public struct Port : Hashable, CustomDebugStringConvertible, ExpressibleByIntegerLiteral, RawRepresentable { public typealias IntegerLiteralType = UInt16 fileprivate let port: IntegerLiteralType public static let any : NWEndpoint.Port = 0 public static let ssh : NWEndpoint.Port = 22 public static let smtp : NWEndpoint.Port = 25 public static let http : NWEndpoint.Port = 80 public static let pop : NWEndpoint.Port = 110 public static let imap : NWEndpoint.Port = 143 public static let https : NWEndpoint.Port = 443 public static let imaps : NWEndpoint.Port = 993 public static let socks : NWEndpoint.Port = 1080 public var rawValue: UInt16 { return self.port } /// Create a port from a string. /// /// Supports common service names such as "http" as well as number strings such as "80". /// /// - Parameter service: A service string such as "http" or a number string such as "80" /// - Returns: A port if the string can be converted to a port, nil otherwise. public init?(_ service: String) { var hints = addrinfo(ai_flags: AI_DEFAULT, ai_family: AF_INET6, ai_socktype: SOCK_STREAM, ai_protocol: 0, ai_addrlen: 0, ai_canonname: nil, ai_addr: nil, ai_next: nil) var resolved : UnsafeMutablePointer<addrinfo>? = nil if (getaddrinfo(nil, service, &hints, &resolved) != 0) { return nil } // Check that it didn't return NULL. guard let addrinfo = resolved else { return nil } // After this point we must ensure we free addrinfo before we return guard let sa = addrinfo.pointee.ai_addr, sa.pointee.sa_family == AF_INET6 else { freeaddrinfo(addrinfo) return nil } self.port = sa.withMemoryRebound(to: sockaddr_in6.self, capacity: 1) {sin6 in return sin6.pointee.sin6_port.bigEndian } freeaddrinfo(addrinfo) } public init(integerLiteral value: IntegerLiteralType) { self.port = value } public init?(rawValue: UInt16) { self.port = rawValue } internal init(_ value: UInt16) { self.init(integerLiteral: value) } public var debugDescription: String { return String(port) } } /// Returns the interface the endpoint is scoped to if any public var interface : NWInterface? { switch self { case .hostPort(host: let host, port: _): return host.interface case .service(name: _, type: _, domain: _, interface: let interface): return interface case .unix(_): return nil } } internal init?(_ nw: nw_endpoint_t?) { guard let nw = nw else { return nil } var interface: NWInterface? = nil if let nwinterface = nw_endpoint_copy_interface(nw) { interface = NWInterface(nwinterface) } if (nw_endpoint_get_type(nw) == Network.nw_endpoint_type_host) { let host = NWEndpoint.Host.name(String(cString: nw_endpoint_get_hostname(nw)), interface) self = .hostPort(host: host, port: NWEndpoint.Port(nw_endpoint_get_port(nw))) } else if (nw_endpoint_get_type(nw) == Network.nw_endpoint_type_address) { let port = NWEndpoint.Port(nw_endpoint_get_port(nw)) let address = nw_endpoint_get_address(nw) if (address.pointee.sa_family == AF_INET && address.pointee.sa_len == MemoryLayout<sockaddr_in>.size) { let host = address.withMemoryRebound(to: sockaddr_in.self, capacity: 1) { (sin: UnsafePointer<sockaddr_in>) -> NWEndpoint.Host in return NWEndpoint.Host.ipv4(IPv4Address(sin.pointee.sin_addr, interface)) } self = .hostPort(host: host, port: port) } else if (address.pointee.sa_family == AF_INET6 && address.pointee.sa_len == MemoryLayout<sockaddr_in6>.size) { let host = address.withMemoryRebound(to: sockaddr_in6.self, capacity: 1) { (sin6) -> NWEndpoint.Host in if (interface == nil && sin6.pointee.sin6_scope_id != 0) { interface = NWInterface(Int(sin6.pointee.sin6_scope_id)) } return NWEndpoint.Host.ipv6(IPv6Address(sin6.pointee.sin6_addr, interface)) } self = .hostPort(host: host, port: port) } else if (address.pointee.sa_family == AF_UNIX) { // sockaddr_un is very difficult to deal with in swift. Fortunately, nw_endpoint_copy_address_string // already does exactly what we need. let path = nw_endpoint_copy_address_string(nw) self = .unix(path: String(cString: path)) path.deallocate() } else { return nil } } else if (nw_endpoint_get_type(nw) == Network.nw_endpoint_type_bonjour_service) { self = .service(name: String(cString: nw_endpoint_get_bonjour_service_name(nw)), type: String(cString: nw_endpoint_get_bonjour_service_type(nw)), domain: String(cString: nw_endpoint_get_bonjour_service_domain(nw)), interface: interface) } else { return nil } } public func hash(into hasher: inout Hasher) { switch self { case .hostPort(host: let host, port: let port): hasher.combine(host) hasher.combine(port) case .service(name: let name, type: let type, domain: let domain, interface: let interface): hasher.combine(name) hasher.combine(type) hasher.combine(domain) hasher.combine(interface) case .unix(let path): hasher.combine(path) } } public var debugDescription: String { switch self { case .hostPort(host: let host, port: let port): var separator = ":" if case .ipv6 = host { separator = "." } return String("\(host)\(separator)\(port)") case .service(name: let name, type: let type, domain: let domain, interface: let interface): if let interface = interface { return String("\(name).\(type).\(domain)%\(interface)") } return String("\(name).\(type).\(domain)") case .unix(let path): return path } } internal var nw: nw_endpoint_t? { var endpoint: nw_endpoint_t? = nil var interface: NWInterface? = nil switch self { case .hostPort(host: let host, port: let port): switch host { case .ipv4(let ipv4): let sin = sockaddr_in(ipv4.address, port.port.bigEndian) endpoint = sin.withSockAddr { (sa) -> nw_endpoint_t in nw_endpoint_create_address(sa) } interface = ipv4.interface case .ipv6(let ipv6): let sin6 = sockaddr_in6(ipv6.address, port.port.bigEndian) endpoint = sin6.withSockAddr { (sa) -> nw_endpoint_t? in nw_endpoint_create_address(sa) } interface = ipv6.interface case .name(let host, let hostInterface): endpoint = nw_endpoint_create_host(host, port.debugDescription) interface = hostInterface } case .service(name: let name, type: let type, domain: let domain, interface: let bonjourInterface): endpoint = nw_endpoint_create_bonjour_service(name, type, domain) interface = bonjourInterface case .unix(let path): endpoint = nw_endpoint_create_unix(path) } if interface != nil && endpoint != nil { nw_endpoint_set_interface(endpoint!, interface!.nw) } return endpoint } }
apache-2.0
de35d3ab0d2b7befbe5c64c4a6c17ac8
33.773585
117
0.685606
3.310071
false
false
false
false
lorentey/BigInt
Tests/BigIntTests/BigUIntTests.swift
2
60830
// // BigUIntTests.swift // BigInt // // Created by Károly Lőrentey on 2015-12-27. // Copyright © 2016-2017 Károly Lőrentey. // import XCTest import Foundation @testable import BigInt extension BigUInt.Kind: Equatable { public static func ==(left: BigUInt.Kind, right: BigUInt.Kind) -> Bool { switch (left, right) { case let (.inline(l0, l1), .inline(r0, r1)): return l0 == r0 && l1 == r1 case let (.slice(from: ls, to: le), .slice(from: rs, to: re)): return ls == rs && le == re case (.array, .array): return true default: return false } } } class BigUIntTests: XCTestCase { typealias Word = BigUInt.Word func check(_ value: BigUInt, _ kind: BigUInt.Kind?, _ words: [Word], file: StaticString = #file, line: UInt = #line) { if let kind = kind { XCTAssertEqual( value.kind, kind, "Mismatching kind: \(value.kind) vs. \(kind)", file: file, line: line) } XCTAssertEqual( Array(value.words), words, "Mismatching words: \(value.words) vs. \(words)", file: file, line: line) XCTAssertEqual( value.isZero, words.isEmpty, "Mismatching isZero: \(value.isZero) vs. \(words.isEmpty)", file: file, line: line) XCTAssertEqual( value.count, words.count, "Mismatching count: \(value.count) vs. \(words.count)", file: file, line: line) for i in 0 ..< words.count { XCTAssertEqual( value[i], words[i], "Mismatching word at index \(i): \(value[i]) vs. \(words[i])", file: file, line: line) } for i in words.count ..< words.count + 10 { XCTAssertEqual( value[i], 0, "Expected 0 word at index \(i), got \(value[i])", file: file, line: line) } } func check(_ value: BigUInt?, _ kind: BigUInt.Kind?, _ words: [Word], file: StaticString = #file, line: UInt = #line) { guard let value = value else { XCTFail("Expected non-nil BigUInt", file: file, line: line) return } check(value, kind, words, file: file, line: line) } func testInit_WordBased() { check(BigUInt(), .inline(0, 0), []) check(BigUInt(word: 0), .inline(0, 0), []) check(BigUInt(word: 1), .inline(1, 0), [1]) check(BigUInt(word: Word.max), .inline(Word.max, 0), [Word.max]) check(BigUInt(low: 0, high: 0), .inline(0, 0), []) check(BigUInt(low: 0, high: 1), .inline(0, 1), [0, 1]) check(BigUInt(low: 1, high: 0), .inline(1, 0), [1]) check(BigUInt(low: 1, high: 2), .inline(1, 2), [1, 2]) check(BigUInt(words: []), .array, []) check(BigUInt(words: [0, 0, 0, 0]), .array, []) check(BigUInt(words: [1]), .array, [1]) check(BigUInt(words: [1, 2, 3, 0, 0]), .array, [1, 2, 3]) check(BigUInt(words: [0, 1, 2, 3, 4]), .array, [0, 1, 2, 3, 4]) check(BigUInt(words: [], from: 0, to: 0), .inline(0, 0), []) check(BigUInt(words: [1, 2, 3, 4], from: 0, to: 4), .array, [1, 2, 3, 4]) check(BigUInt(words: [1, 2, 3, 4], from: 0, to: 3), .slice(from: 0, to: 3), [1, 2, 3]) check(BigUInt(words: [1, 2, 3, 4], from: 1, to: 4), .slice(from: 1, to: 4), [2, 3, 4]) check(BigUInt(words: [1, 2, 3, 4], from: 0, to: 2), .inline(1, 2), [1, 2]) check(BigUInt(words: [1, 2, 3, 4], from: 0, to: 1), .inline(1, 0), [1]) check(BigUInt(words: [1, 2, 3, 4], from: 1, to: 1), .inline(0, 0), []) check(BigUInt(words: [0, 0, 0, 1, 0, 0, 0, 2], from: 0, to: 4), .slice(from: 0, to: 4), [0, 0, 0, 1]) check(BigUInt(words: [0, 0, 0, 1, 0, 0, 0, 2], from: 0, to: 3), .inline(0, 0), []) check(BigUInt(words: [0, 0, 0, 1, 0, 0, 0, 2], from: 2, to: 6), .inline(0, 1), [0, 1]) check(BigUInt(words: [].lazy), .inline(0, 0), []) check(BigUInt(words: [1].lazy), .inline(1, 0), [1]) check(BigUInt(words: [1, 2].lazy), .inline(1, 2), [1, 2]) check(BigUInt(words: [1, 2, 3].lazy), .array, [1, 2, 3]) check(BigUInt(words: [1, 2, 3, 0, 0, 0, 0].lazy), .array, [1, 2, 3]) check(BigUInt(words: IteratorSequence([].makeIterator())), .inline(0, 0), []) check(BigUInt(words: IteratorSequence([1].makeIterator())), .inline(1, 0), [1]) check(BigUInt(words: IteratorSequence([1, 2].makeIterator())), .inline(1, 2), [1, 2]) check(BigUInt(words: IteratorSequence([1, 2, 3].makeIterator())), .array, [1, 2, 3]) check(BigUInt(words: IteratorSequence([1, 2, 3, 0, 0, 0, 0].makeIterator())), .array, [1, 2, 3]) } func testInit_BinaryInteger() { XCTAssertNil(BigUInt(exactly: -42)) check(BigUInt(exactly: 0 as Int), .inline(0, 0), []) check(BigUInt(exactly: 42 as Int), .inline(42, 0), [42]) check(BigUInt(exactly: 43 as UInt), .inline(43, 0), [43]) check(BigUInt(exactly: 44 as UInt8), .inline(44, 0), [44]) check(BigUInt(exactly: BigUInt(words: [])), .inline(0, 0), []) check(BigUInt(exactly: BigUInt(words: [1])), .inline(1, 0), [1]) check(BigUInt(exactly: BigUInt(words: [1, 2])), .inline(1, 2), [1, 2]) check(BigUInt(exactly: BigUInt(words: [1, 2, 3, 4])), .array, [1, 2, 3, 4]) } func testInit_FloatingPoint() { check(BigUInt(exactly: -0.0 as Float), nil, []) check(BigUInt(exactly: -0.0 as Double), nil, []) XCTAssertNil(BigUInt(exactly: -42.0 as Float)) XCTAssertNil(BigUInt(exactly: -42.0 as Double)) XCTAssertNil(BigUInt(exactly: 42.5 as Float)) XCTAssertNil(BigUInt(exactly: 42.5 as Double)) check(BigUInt(exactly: 100 as Float), nil, [100]) check(BigUInt(exactly: 100 as Double), nil, [100]) check(BigUInt(exactly: Float.greatestFiniteMagnitude), nil, convertWords([0, 0xFFFFFF0000000000])) check(BigUInt(exactly: Double.greatestFiniteMagnitude), nil, convertWords([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFFFFFFFFFFFFF800])) XCTAssertNil(BigUInt(exactly: Float.leastNormalMagnitude)) XCTAssertNil(BigUInt(exactly: Double.leastNormalMagnitude)) XCTAssertNil(BigUInt(exactly: Float.infinity)) XCTAssertNil(BigUInt(exactly: Double.infinity)) XCTAssertNil(BigUInt(exactly: Float.nan)) XCTAssertNil(BigUInt(exactly: Double.nan)) check(BigUInt(0 as Float), nil, []) check(BigUInt(Float.leastNonzeroMagnitude), nil, []) check(BigUInt(Float.leastNormalMagnitude), nil, []) check(BigUInt(0.5 as Float), nil, []) check(BigUInt(1.5 as Float), nil, [1]) check(BigUInt(42 as Float), nil, [42]) check(BigUInt(Double(sign: .plus, exponent: 2 * Word.bitWidth, significand: 1.0)), nil, [0, 0, 1]) } func testInit_Buffer() { func test(_ b: BigUInt, _ d: Array<UInt8>, file: StaticString = #file, line: UInt = #line) { d.withUnsafeBytes { buffer in let initialized = BigUInt(buffer) XCTAssertEqual(initialized, b, file: file, line: line) } } // Positive integers test(BigUInt(), []) test(BigUInt(1), [0x01]) test(BigUInt(2), [0x02]) test(BigUInt(0x0102030405060708), [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08]) test(BigUInt(0x01) << 64 + BigUInt(0x0203040506070809), [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 09]) } func testConversionToFloatingPoint() { func test<F: BinaryFloatingPoint>(_ a: BigUInt, _ b: F, file: StaticString = #file, line: UInt = #line) where F.RawExponent: FixedWidthInteger, F.RawSignificand: FixedWidthInteger { let f = F(a) XCTAssertEqual(f, b, file: file, line: line) } for i in 0 ..< 100 { test(BigUInt(i), Double(i)) } test(BigUInt(0x5A5A5A), 0x5A5A5A as Double) test(BigUInt(1) << 64, 0x1p64 as Double) test(BigUInt(0x5A5A5A) << 64, 0x5A5A5Ap64 as Double) test(BigUInt(1) << 1023, 0x1p1023 as Double) test(BigUInt(10) << 1020, 0xAp1020 as Double) test(BigUInt(1) << 1024, Double.infinity) test(BigUInt(words: convertWords([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFFFFFFFFFFFFF800])), Double.greatestFiniteMagnitude) test(BigUInt(UInt64.max), 0x1p64 as Double) for i in 0 ..< 100 { test(BigUInt(i), Float(i)) } test(BigUInt(0x5A5A5A), 0x5A5A5A as Float) test(BigUInt(1) << 64, 0x1p64 as Float) test(BigUInt(0x5A5A5A) << 64, 0x5A5A5Ap64 as Float) test(BigUInt(1) << 1023, 0x1p1023 as Float) test(BigUInt(10) << 1020, 0xAp1020 as Float) test(BigUInt(1) << 1024, Float.infinity) test(BigUInt(words: convertWords([0, 0xFFFFFF0000000000])), Float.greatestFiniteMagnitude) // Test rounding test(BigUInt(0xFFFFFF0000000000 as UInt64), 0xFFFFFFp40 as Float) test(BigUInt(0xFFFFFF7FFFFFFFFF as UInt64), 0xFFFFFFp40 as Float) test(BigUInt(0xFFFFFF8000000000 as UInt64), 0x1p64 as Float) test(BigUInt(0xFFFFFFFFFFFFFFFF as UInt64), 0x1p64 as Float) test(BigUInt(0xFFFFFE0000000000 as UInt64), 0xFFFFFEp40 as Float) test(BigUInt(0xFFFFFE7FFFFFFFFF as UInt64), 0xFFFFFEp40 as Float) test(BigUInt(0xFFFFFE8000000000 as UInt64), 0xFFFFFEp40 as Float) test(BigUInt(0xFFFFFEFFFFFFFFFF as UInt64), 0xFFFFFEp40 as Float) test(BigUInt(0x8000010000000000 as UInt64), 0x800001p40 as Float) test(BigUInt(0x8000017FFFFFFFFF as UInt64), 0x800001p40 as Float) test(BigUInt(0x8000018000000000 as UInt64), 0x800002p40 as Float) test(BigUInt(0x800001FFFFFFFFFF as UInt64), 0x800002p40 as Float) test(BigUInt(0x8000020000000000 as UInt64), 0x800002p40 as Float) test(BigUInt(0x8000027FFFFFFFFF as UInt64), 0x800002p40 as Float) test(BigUInt(0x8000028000000000 as UInt64), 0x800002p40 as Float) test(BigUInt(0x800002FFFFFFFFFF as UInt64), 0x800002p40 as Float) } func testInit_Misc() { check(BigUInt(0), .inline(0, 0), []) check(BigUInt(42), .inline(42, 0), [42]) check(BigUInt(BigUInt(words: [1, 2, 3])), .array, [1, 2, 3]) check(BigUInt(truncatingIfNeeded: 0 as Int8), .inline(0, 0), []) check(BigUInt(truncatingIfNeeded: 1 as Int8), .inline(1, 0), [1]) check(BigUInt(truncatingIfNeeded: -1 as Int8), .inline(Word.max, 0), [Word.max]) check(BigUInt(truncatingIfNeeded: BigUInt(words: [1, 2, 3])), .array, [1, 2, 3]) check(BigUInt(clamping: 0), .inline(0, 0), []) check(BigUInt(clamping: -100), .inline(0, 0), []) check(BigUInt(clamping: Word.max), .inline(Word.max, 0), [Word.max]) } func testEnsureArray() { var a = BigUInt() a.ensureArray() check(a, .array, []) a = BigUInt(word: 1) a.ensureArray() check(a, .array, [1]) a = BigUInt(low: 1, high: 2) a.ensureArray() check(a, .array, [1, 2]) a = BigUInt(words: [1, 2, 3, 4]) a.ensureArray() check(a, .array, [1, 2, 3, 4]) a = BigUInt(words: [1, 2, 3, 4, 5, 6], from: 1, to: 5) a.ensureArray() check(a, .array, [2, 3, 4, 5]) } func testCapacity() { XCTAssertEqual(BigUInt(low: 1, high: 2).capacity, 0) XCTAssertEqual(BigUInt(words: 1 ..< 10).extract(2 ..< 5).capacity, 0) var words: [Word] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] words.reserveCapacity(100) XCTAssertGreaterThanOrEqual(BigUInt(words: words).capacity, 100) } func testReserveCapacity() { var a = BigUInt() a.reserveCapacity(100) check(a, .array, []) XCTAssertGreaterThanOrEqual(a.capacity, 100) a = BigUInt(word: 1) a.reserveCapacity(100) check(a, .array, [1]) XCTAssertGreaterThanOrEqual(a.capacity, 100) a = BigUInt(low: 1, high: 2) a.reserveCapacity(100) check(a, .array, [1, 2]) XCTAssertGreaterThanOrEqual(a.capacity, 100) a = BigUInt(words: [1, 2, 3, 4]) a.reserveCapacity(100) check(a, .array, [1, 2, 3, 4]) XCTAssertGreaterThanOrEqual(a.capacity, 100) a = BigUInt(words: [1, 2, 3, 4, 5, 6], from: 1, to: 5) a.reserveCapacity(100) check(a, .array, [2, 3, 4, 5]) XCTAssertGreaterThanOrEqual(a.capacity, 100) } func testLoad() { var a: BigUInt = 0 a.reserveCapacity(100) a.load(BigUInt(low: 1, high: 2)) check(a, .array, [1, 2]) XCTAssertGreaterThanOrEqual(a.capacity, 100) a.load(BigUInt(words: [1, 2, 3, 4, 5, 6])) check(a, .array, [1, 2, 3, 4, 5, 6]) XCTAssertGreaterThanOrEqual(a.capacity, 100) a.clear() check(a, .array, []) XCTAssertGreaterThanOrEqual(a.capacity, 100) } func testInitFromLiterals() { check(0, .inline(0, 0), []) check(42, .inline(42, 0), [42]) check("42", .inline(42, 0), [42]) check("1512366075204170947332355369683137040", .inline(0xFEDCBA9876543210, 0x0123456789ABCDEF), [0xFEDCBA9876543210, 0x0123456789ABCDEF]) // I have no idea how to exercise these in the wild check(BigUInt(unicodeScalarLiteral: UnicodeScalar(52)), .inline(4, 0), [4]) check(BigUInt(extendedGraphemeClusterLiteral: "4"), .inline(4, 0), [4]) } func testSubscriptingGetter() { let a = BigUInt(words: [1, 2]) XCTAssertEqual(a[0], 1) XCTAssertEqual(a[1], 2) XCTAssertEqual(a[2], 0) XCTAssertEqual(a[3], 0) XCTAssertEqual(a[10000], 0) let b = BigUInt(low: 1, high: 2) XCTAssertEqual(b[0], 1) XCTAssertEqual(b[1], 2) XCTAssertEqual(b[2], 0) XCTAssertEqual(b[3], 0) XCTAssertEqual(b[10000], 0) } func testSubscriptingSetter() { var a = BigUInt() check(a, .inline(0, 0), []) a[10] = 0 check(a, .inline(0, 0), []) a[0] = 42 check(a, .inline(42, 0), [42]) a[10] = 23 check(a, .array, [42, 0, 0, 0, 0, 0, 0, 0, 0, 0, 23]) a[0] = 0 check(a, .array, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 23]) a[10] = 0 check(a, .array, []) a = BigUInt(words: [0, 1, 2, 3, 4, 5, 6], from: 1, to: 5) a[2] = 42 check(a, .array, [1, 2, 42, 4]) } func testSlice() { let a = BigUInt(words: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) check(a.extract(3 ..< 6), .slice(from: 3, to: 6), [3, 4, 5]) check(a.extract(3 ..< 5), .inline(3, 4), [3, 4]) check(a.extract(3 ..< 4), .inline(3, 0), [3]) check(a.extract(3 ..< 3), .inline(0, 0), []) check(a.extract(0 ..< 100), .array, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) check(a.extract(100 ..< 200), .inline(0, 0), []) let b = BigUInt(low: 1, high: 2) check(b.extract(0 ..< 2), .inline(1, 2), [1, 2]) check(b.extract(0 ..< 1), .inline(1, 0), [1]) check(b.extract(1 ..< 2), .inline(2, 0), [2]) check(b.extract(1 ..< 1), .inline(0, 0), []) check(b.extract(0 ..< 100), .inline(1, 2), [1, 2]) check(b.extract(100 ..< 200), .inline(0, 0), []) let c = BigUInt(words: [1, 0, 0, 0, 2, 0, 0, 0, 3, 4, 5, 0, 0, 6, 0, 0, 0, 7]) check(c.extract(0 ..< 4), .inline(1, 0), [1]) check(c.extract(1 ..< 5), .slice(from: 1, to: 5), [0, 0, 0, 2]) check(c.extract(1 ..< 8), .slice(from: 1, to: 5), [0, 0, 0, 2]) check(c.extract(6 ..< 12), .slice(from: 6, to: 11), [0, 0, 3, 4, 5]) check(c.extract(4 ..< 7), .inline(2, 0), [2]) let d = c.extract(3 ..< 14) // 0 1 2 3 4 5 6 7 8 9 10 check(d, .slice(from: 3, to: 14), [0, 2, 0, 0, 0, 3, 4, 5, 0, 0, 6]) check(d.extract(1 ..< 5), .inline(2, 0), [2]) check(d.extract(0 ..< 3), .inline(0, 2), [0, 2]) check(d.extract(1 ..< 6), .slice(from: 4, to: 9), [2, 0, 0, 0, 3]) check(d.extract(7 ..< 1000), .slice(from: 10, to: 14), [5, 0, 0, 6]) check(d.extract(10 ..< 1000), .inline(6, 0), [6]) check(d.extract(11 ..< 1000), .inline(0, 0), []) } func testSigns() { XCTAssertFalse(BigUInt.isSigned) XCTAssertEqual(BigUInt().signum(), 0) XCTAssertEqual(BigUInt(words: []).signum(), 0) XCTAssertEqual(BigUInt(words: [0, 1, 2]).signum(), 1) XCTAssertEqual(BigUInt(word: 42).signum(), 1) } func testBits() { let indices: Set<Int> = [0, 13, 59, 64, 79, 130] var value: BigUInt = 0 for i in indices { value[bitAt: i] = true } for i in 0 ..< 300 { XCTAssertEqual(value[bitAt: i], indices.contains(i)) } check(value, nil, convertWords([0x0800000000002001, 0x8001, 0x04])) for i in indices { value[bitAt: i] = false } check(value, nil, []) } func testStrideableRequirements() { XCTAssertEqual(BigUInt(10), BigUInt(4).advanced(by: BigInt(6))) XCTAssertEqual(BigUInt(4), BigUInt(10).advanced(by: BigInt(-6))) XCTAssertEqual(BigInt(6), BigUInt(4).distance(to: 10)) XCTAssertEqual(BigInt(-6), BigUInt(10).distance(to: 4)) } func testRightShift_ByWord() { var a = BigUInt() a.shiftRight(byWords: 1) check(a, .inline(0, 0), []) a = BigUInt(low: 1, high: 2) a.shiftRight(byWords: 0) check(a, .inline(1, 2), [1, 2]) a = BigUInt(low: 1, high: 2) a.shiftRight(byWords: 1) check(a, .inline(2, 0), [2]) a = BigUInt(low: 1, high: 2) a.shiftRight(byWords: 2) check(a, .inline(0, 0), []) a = BigUInt(low: 1, high: 2) a.shiftRight(byWords: 10) check(a, .inline(0, 0), []) a = BigUInt(words: [0, 1, 2, 3, 4]) a.shiftRight(byWords: 1) check(a, .array, [1, 2, 3, 4]) a = BigUInt(words: [0, 1, 2, 3, 4]) a.shiftRight(byWords: 2) check(a, .array, [2, 3, 4]) a = BigUInt(words: [0, 1, 2, 3, 4]) a.shiftRight(byWords: 5) check(a, .array, []) a = BigUInt(words: [0, 1, 2, 3, 4]) a.shiftRight(byWords: 100) check(a, .array, []) a = BigUInt(words: [0, 1, 2, 3, 4, 5, 6], from: 1, to: 6) check(a, .slice(from: 1, to: 6), [1, 2, 3, 4, 5]) a.shiftRight(byWords: 1) check(a, .slice(from: 2, to: 6), [2, 3, 4, 5]) a = BigUInt(words: [0, 1, 2, 3, 4, 5, 6], from: 1, to: 6) a.shiftRight(byWords: 2) check(a, .slice(from: 3, to: 6), [3, 4, 5]) a = BigUInt(words: [0, 1, 2, 3, 4, 5, 6], from: 1, to: 6) a.shiftRight(byWords: 3) check(a, .inline(4, 5), [4, 5]) a = BigUInt(words: [0, 1, 2, 3, 4, 5, 6], from: 1, to: 6) a.shiftRight(byWords: 4) check(a, .inline(5, 0), [5]) a = BigUInt(words: [0, 1, 2, 3, 4, 5, 6], from: 1, to: 6) a.shiftRight(byWords: 5) check(a, .inline(0, 0), []) a = BigUInt(words: [0, 1, 2, 3, 4, 5, 6], from: 1, to: 6) a.shiftRight(byWords: 10) check(a, .inline(0, 0), []) } func testLeftShift_ByWord() { var a = BigUInt() a.shiftLeft(byWords: 1) check(a, .inline(0, 0), []) a = BigUInt(word: 1) a.shiftLeft(byWords: 0) check(a, .inline(1, 0), [1]) a = BigUInt(word: 1) a.shiftLeft(byWords: 1) check(a, .inline(0, 1), [0, 1]) a = BigUInt(word: 1) a.shiftLeft(byWords: 2) check(a, .array, [0, 0, 1]) a = BigUInt(low: 1, high: 2) a.shiftLeft(byWords: 1) check(a, .array, [0, 1, 2]) a = BigUInt(low: 1, high: 2) a.shiftLeft(byWords: 2) check(a, .array, [0, 0, 1, 2]) a = BigUInt(words: [1, 2, 3, 4, 5, 6]) a.shiftLeft(byWords: 1) check(a, .array, [0, 1, 2, 3, 4, 5, 6]) a = BigUInt(words: [1, 2, 3, 4, 5, 6]) a.shiftLeft(byWords: 10) check(a, .array, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6]) a = BigUInt(words: [0, 1, 2, 3, 4, 5, 6], from: 2, to: 6) a.shiftLeft(byWords: 1) check(a, .array, [0, 2, 3, 4, 5]) a = BigUInt(words: [0, 1, 2, 3, 4, 5, 6], from: 2, to: 6) a.shiftLeft(byWords: 3) check(a, .array, [0, 0, 0, 2, 3, 4, 5]) } func testSplit() { let a = BigUInt(words: [0, 1, 2, 3]) XCTAssertEqual(a.split.low, BigUInt(words: [0, 1])) XCTAssertEqual(a.split.high, BigUInt(words: [2, 3])) } func testLowHigh() { let a = BigUInt(words: [0, 1, 2, 3]) check(a.low, .inline(0, 1), [0, 1]) check(a.high, .inline(2, 3), [2, 3]) check(a.low.low, .inline(0, 0), []) check(a.low.high, .inline(1, 0), [1]) check(a.high.low, .inline(2, 0), [2]) check(a.high.high, .inline(3, 0), [3]) let b = BigUInt(words: [0, 1, 2, 3, 4, 5]) let bl = b.low check(bl, .slice(from: 0, to: 3), [0, 1, 2]) let bh = b.high check(bh, .slice(from: 3, to: 6), [3, 4, 5]) let bll = bl.low check(bll, .inline(0, 1), [0, 1]) let blh = bl.high check(blh, .inline(2, 0), [2]) let bhl = bh.low check(bhl, .inline(3, 4), [3, 4]) let bhh = bh.high check(bhh, .inline(5, 0), [5]) let blhl = bll.low check(blhl, .inline(0, 0), []) let blhh = bll.high check(blhh, .inline(1, 0), [1]) let bhhl = bhl.low check(bhhl, .inline(3, 0), [3]) let bhhh = bhl.high check(bhhh, .inline(4, 0), [4]) } func testComparison() { XCTAssertEqual(BigUInt(words: [1, 2, 3]), BigUInt(words: [1, 2, 3])) XCTAssertNotEqual(BigUInt(words: [1, 2]), BigUInt(words: [1, 2, 3])) XCTAssertNotEqual(BigUInt(words: [1, 2, 3]), BigUInt(words: [1, 3, 3])) XCTAssertEqual(BigUInt(words: [1, 2, 3, 4, 5, 6]).low.high, BigUInt(words: [3])) XCTAssertTrue(BigUInt(words: [1, 2]) < BigUInt(words: [1, 2, 3])) XCTAssertTrue(BigUInt(words: [1, 2, 2]) < BigUInt(words: [1, 2, 3])) XCTAssertFalse(BigUInt(words: [1, 2, 3]) < BigUInt(words: [1, 2, 3])) XCTAssertTrue(BigUInt(words: [3, 3]) < BigUInt(words: [1, 2, 3, 4, 5, 6]).extract(2 ..< 4)) XCTAssertTrue(BigUInt(words: [1, 2, 3, 4, 5, 6]).low.high < BigUInt(words: [3, 5])) } func testHashing() { var hashes: [Int] = [] hashes.append(BigUInt(words: []).hashValue) hashes.append(BigUInt(words: [1]).hashValue) hashes.append(BigUInt(words: [2]).hashValue) hashes.append(BigUInt(words: [0, 1]).hashValue) hashes.append(BigUInt(words: [1, 1]).hashValue) hashes.append(BigUInt(words: [1, 2]).hashValue) hashes.append(BigUInt(words: [2, 1]).hashValue) hashes.append(BigUInt(words: [2, 2]).hashValue) hashes.append(BigUInt(words: [1, 2, 3, 4, 5]).hashValue) hashes.append(BigUInt(words: [5, 4, 3, 2, 1]).hashValue) hashes.append(BigUInt(words: [Word.max]).hashValue) hashes.append(BigUInt(words: [Word.max, Word.max]).hashValue) hashes.append(BigUInt(words: [Word.max, Word.max, Word.max]).hashValue) hashes.append(BigUInt(words: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]).hashValue) XCTAssertEqual(hashes.count, Set(hashes).count) } func checkData(_ bytes: [UInt8], _ value: BigUInt, file: StaticString = #file, line: UInt = #line) { XCTAssertEqual(BigUInt(Data(bytes)), value, file: file, line: line) XCTAssertEqual(bytes.withUnsafeBytes { buffer in BigUInt(buffer) }, value, file: file, line: line) } func testConversionFromBytes() { checkData([], 0) checkData([0], 0) checkData([0, 0, 0, 0, 0, 0, 0, 0], 0) checkData([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 0) checkData([1], 1) checkData([2], 2) checkData([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], 1) checkData([0x01, 0x02, 0x03, 0x04, 0x05], 0x0102030405) checkData([0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08], 0x0102030405060708) checkData([0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A], BigUInt(0x0102) << 64 + BigUInt(0x030405060708090A)) checkData([0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], BigUInt(1) << 80) checkData([0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10], BigUInt(0x0102030405060708) << 64 + BigUInt(0x090A0B0C0D0E0F10)) checkData([0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11], ((BigUInt(1) << 128) as BigUInt) + BigUInt(0x0203040506070809) << 64 + BigUInt(0x0A0B0C0D0E0F1011)) } func testConversionToData() { func test(_ b: BigUInt, _ d: Array<UInt8>, file: StaticString = #file, line: UInt = #line) { let expected = Data(d) let actual = b.serialize() XCTAssertEqual(actual, expected, file: file, line: line) XCTAssertEqual(BigUInt(actual), b, file: file, line: line) } test(BigUInt(), []) test(BigUInt(1), [0x01]) test(BigUInt(2), [0x02]) test(BigUInt(0x0102030405060708), [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08]) test(BigUInt(0x01) << 64 + BigUInt(0x0203040506070809), [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09]) } func testCodable() { func test(_ a: BigUInt, file: StaticString = #file, line: UInt = #line) { do { let json = try JSONEncoder().encode(a) print(String(data: json, encoding: .utf8)!) let b = try JSONDecoder().decode(BigUInt.self, from: json) XCTAssertEqual(a, b, file: file, line: line) } catch let error { XCTFail("Error thrown: \(error.localizedDescription)", file: file, line: line) } } test(0) test(1) test(0x0102030405060708) test(BigUInt(1) << 64) test(BigUInt(words: [1, 2, 3, 4, 5, 6, 7])) XCTAssertThrowsError(try JSONDecoder().decode(BigUInt.self, from: "[\"*\", 1]".data(using: .utf8)!)) { error in guard let error = error as? DecodingError else { XCTFail("Expected a decoding error"); return } guard case .dataCorrupted(let context) = error else { XCTFail("Expected a dataCorrupted error"); return } XCTAssertEqual(context.debugDescription, "Invalid big integer sign") } XCTAssertThrowsError(try JSONDecoder().decode(BigUInt.self, from: "[\"-\", 1]".data(using: .utf8)!)) { error in guard let error = error as? DecodingError else { XCTFail("Expected a decoding error"); return } guard case .dataCorrupted(let context) = error else { XCTFail("Expected a dataCorrupted error"); return } XCTAssertEqual(context.debugDescription, "BigUInt cannot hold a negative value") } } func testAddition() { XCTAssertEqual(BigUInt(0) + BigUInt(0), BigUInt(0)) XCTAssertEqual(BigUInt(0) + BigUInt(Word.max), BigUInt(Word.max)) XCTAssertEqual(BigUInt(Word.max) + BigUInt(1), BigUInt(words: [0, 1])) check(BigUInt(3) + BigUInt(42), .inline(45, 0), [45]) check(BigUInt(3) + BigUInt(42), .inline(45, 0), [45]) check(0 + BigUInt(Word.max), .inline(Word.max, 0), [Word.max]) check(1 + BigUInt(Word.max), .inline(0, 1), [0, 1]) check(BigUInt(low: 0, high: 1) + BigUInt(low: 3, high: 4), .inline(3, 5), [3, 5]) check(BigUInt(low: 3, high: 5) + BigUInt(low: 0, high: Word.max), .array, [3, 4, 1]) check(BigUInt(words: [3, 4, 1]) + BigUInt(low: 0, high: Word.max), .array, [3, 3, 2]) check(BigUInt(words: [3, 3, 2]) + 2, .array, [5, 3, 2]) check(BigUInt(words: [Word.max - 5, Word.max, 4, Word.max]).addingWord(6), .array, [0, 0, 5, Word.max]) var b = BigUInt(words: [Word.max, 2, Word.max]) b.increment() check(b, .array, [0, 3, Word.max]) } func testShiftedAddition() { var b = BigUInt() b.add(1, shiftedBy: 1) check(b, .inline(0, 1), [0, 1]) b.add(2, shiftedBy: 3) check(b, .array, [0, 1, 0, 2]) b.add(BigUInt(Word.max), shiftedBy: 1) check(b, .array, [0, 0, 1, 2]) } func testSubtraction() { var a1 = BigUInt(words: [1, 2, 3, 4]) XCTAssertEqual(false, a1.subtractWordReportingOverflow(3, shiftedBy: 1)) check(a1, .array, [1, Word.max, 2, 4]) let (diff, overflow) = BigUInt(words: [1, 2, 3, 4]).subtractingWordReportingOverflow(2) XCTAssertEqual(false, overflow) check(diff, .array, [Word.max, 1, 3, 4]) var a2 = BigUInt(words: [1, 2, 3, 4]) XCTAssertEqual(true, a2.subtractWordReportingOverflow(5, shiftedBy: 3)) check(a2, .array, [1, 2, 3, Word.max]) var a3 = BigUInt(words: [1, 2, 3, 4]) a3.subtractWord(4, shiftedBy: 3) check(a3, .array, [1, 2, 3]) var a4 = BigUInt(words: [1, 2, 3, 4]) a4.decrement() check(a4, .array, [0, 2, 3, 4]) a4.decrement() check(a4, .array, [Word.max, 1, 3, 4]) check(BigUInt(words: [1, 2, 3, 4]).subtractingWord(5), .array, [Word.max - 3, 1, 3, 4]) check(BigUInt(0) - BigUInt(0), .inline(0, 0), []) var b = BigUInt(words: [1, 2, 3, 4]) XCTAssertEqual(false, b.subtractReportingOverflow(BigUInt(words: [0, 1, 1, 1]))) check(b, .array, [1, 1, 2, 3]) let b1 = BigUInt(words: [1, 1, 2, 3]).subtractingReportingOverflow(BigUInt(words: [1, 1, 3, 3])) XCTAssertEqual(true, b1.overflow) check(b1.partialValue, .array, [0, 0, Word.max, Word.max]) let b2 = BigUInt(words: [0, 0, 1]) - BigUInt(words: [1]) check(b2, .array, [Word.max, Word.max]) var b3 = BigUInt(words: [1, 0, 0, 1]) b3 -= 2 check(b3, .array, [Word.max, Word.max, Word.max]) check(BigUInt(42) - BigUInt(23), .inline(19, 0), [19]) } func testMultiplyByWord() { check(BigUInt(words: [1, 2, 3, 4]).multiplied(byWord: 0), .inline(0, 0), []) check(BigUInt(words: [1, 2, 3, 4]).multiplied(byWord: 2), .array, [2, 4, 6, 8]) let full = Word.max check(BigUInt(words: [full, 0, full, 0, full]).multiplied(byWord: 2), .array, [full - 1, 1, full - 1, 1, full - 1, 1]) check(BigUInt(words: [full, full, full]).multiplied(byWord: 2), .array, [full - 1, full, full, 1]) check(BigUInt(words: [full, full, full]).multiplied(byWord: full), .array, [1, full, full, full - 1]) check(BigUInt("11111111111111111111111111111111", radix: 16)!.multiplied(byWord: 15), .array, convertWords([UInt64.max, UInt64.max])) check(BigUInt("11111111111111111111111111111112", radix: 16)!.multiplied(byWord: 15), .array, convertWords([0xE, 0, 0x1])) check(BigUInt(low: 1, high: 2).multiplied(byWord: 3), .inline(3, 6), [3, 6]) } func testMultiplication() { func test() { check(BigUInt(low: 1, high: 1) * BigUInt(word: 3), .inline(3, 3), [3, 3]) check(BigUInt(word: 4) * BigUInt(low: 1, high: 2), .inline(4, 8), [4, 8]) XCTAssertEqual( BigUInt(words: [1, 2, 3, 4]) * BigUInt(), BigUInt()) XCTAssertEqual( BigUInt() * BigUInt(words: [1, 2, 3, 4]), BigUInt()) XCTAssertEqual( BigUInt(words: [1, 2, 3, 4]) * BigUInt(words: [2]), BigUInt(words: [2, 4, 6, 8])) XCTAssertEqual( BigUInt(words: [1, 2, 3, 4]).multiplied(by: BigUInt(words: [2])), BigUInt(words: [2, 4, 6, 8])) XCTAssertEqual( BigUInt(words: [2]) * BigUInt(words: [1, 2, 3, 4]), BigUInt(words: [2, 4, 6, 8])) XCTAssertEqual( BigUInt(words: [1, 2, 3, 4]) * BigUInt(words: [0, 1]), BigUInt(words: [0, 1, 2, 3, 4])) XCTAssertEqual( BigUInt(words: [0, 1]) * BigUInt(words: [1, 2, 3, 4]), BigUInt(words: [0, 1, 2, 3, 4])) XCTAssertEqual( BigUInt(words: [4, 3, 2, 1]) * BigUInt(words: [1, 2, 3, 4]), BigUInt(words: [4, 11, 20, 30, 20, 11, 4])) // 999 * 99 = 98901 XCTAssertEqual( BigUInt(words: [Word.max, Word.max, Word.max]) * BigUInt(words: [Word.max, Word.max]), BigUInt(words: [1, 0, Word.max, Word.max - 1, Word.max])) XCTAssertEqual( BigUInt(words: [1, 2]) * BigUInt(words: [2, 1]), BigUInt(words: [2, 5, 2])) var b = BigUInt("2637AB28", radix: 16)! b *= BigUInt("164B", radix: 16)! XCTAssertEqual(b, BigUInt("353FB0494B8", radix: 16)) XCTAssertEqual(BigUInt("16B60", radix: 16)! * BigUInt("33E28", radix: 16)!, BigUInt("49A5A0700", radix: 16)!) } test() // Disable brute force multiplication. let limit = BigUInt.directMultiplicationLimit BigUInt.directMultiplicationLimit = 0 defer { BigUInt.directMultiplicationLimit = limit } test() } func testDivision() { func test(_ a: [Word], _ b: [Word], file: StaticString = #file, line: UInt = #line) { let x = BigUInt(words: a) let y = BigUInt(words: b) let (div, mod) = x.quotientAndRemainder(dividingBy: y) if mod >= y { XCTFail("x:\(x) = div:\(div) * y:\(y) + mod:\(mod)", file: file, line: line) } if div * y + mod != x { XCTFail("x:\(x) = div:\(div) * y:\(y) + mod:\(mod)", file: file, line: line) } let shift = y.leadingZeroBitCount let norm = y << shift var rem = x rem.formRemainder(dividingBy: norm, normalizedBy: shift) XCTAssertEqual(rem, mod, file: file, line: line) } // These cases exercise all code paths in the division when Word is UInt8 or UInt64. test([], [1]) test([1], [1]) test([1], [2]) test([2], [1]) test([], [0, 1]) test([1], [0, 1]) test([0, 1], [0, 1]) test([0, 0, 1], [0, 1]) test([0, 0, 1], [1, 1]) test([0, 0, 1], [3, 1]) test([0, 0, 1], [75, 1]) test([0, 0, 0, 1], [0, 1]) test([2, 4, 6, 8], [1, 2]) test([2, 3, 4, 5], [4, 5]) test([Word.max, Word.max - 1, Word.max], [Word.max, Word.max]) test([0, Word.max, Word.max - 1], [Word.max, Word.max]) test([0, 0, 0, 0, 0, Word.max / 2 + 1, Word.max / 2], [1, 0, 0, Word.max / 2 + 1]) test([0, Word.max - 1, Word.max / 2 + 1], [Word.max, Word.max / 2 + 1]) test([0, 0, 0x41 << Word(Word.bitWidth - 8)], [Word.max, 1 << Word(Word.bitWidth - 1)]) XCTAssertEqual(BigUInt(328) / BigUInt(21), BigUInt(15)) XCTAssertEqual(BigUInt(328) % BigUInt(21), BigUInt(13)) var a = BigUInt(328) a /= 21 XCTAssertEqual(a, 15) a %= 7 XCTAssertEqual(a, 1) #if false for x0 in (0 ... Int(Word.max)) { for x1 in (0 ... Int(Word.max)).reverse() { for y0 in (0 ... Int(Word.max)).reverse() { for y1 in (1 ... Int(Word.max)).reverse() { for x2 in (1 ... y1).reverse() { test( [Word(x0), Word(x1), Word(x2)], [Word(y0), Word(y1)]) } } } } } #endif } func testFactorial() { let power = 10 var forward = BigUInt(1) for i in 1 ..< (1 << power) { forward *= BigUInt(i) } print("\(1 << power - 1)! = \(forward) [\(forward.count)]") var backward = BigUInt(1) for i in (1 ..< (1 << power)).reversed() { backward *= BigUInt(i) } func balancedFactorial(level: Int, offset: Int) -> BigUInt { if level == 0 { return BigUInt(offset == 0 ? 1 : offset) } let a = balancedFactorial(level: level - 1, offset: 2 * offset) let b = balancedFactorial(level: level - 1, offset: 2 * offset + 1) return a * b } let balanced = balancedFactorial(level: power, offset: 0) XCTAssertEqual(backward, forward) XCTAssertEqual(balanced, forward) var remaining = balanced for i in 1 ..< (1 << power) { let (div, mod) = remaining.quotientAndRemainder(dividingBy: BigUInt(i)) XCTAssertEqual(mod, 0) remaining = div } XCTAssertEqual(remaining, 1) } func testExponentiation() { XCTAssertEqual(BigUInt(0).power(0), BigUInt(1)) XCTAssertEqual(BigUInt(0).power(1), BigUInt(0)) XCTAssertEqual(BigUInt(1).power(0), BigUInt(1)) XCTAssertEqual(BigUInt(1).power(1), BigUInt(1)) XCTAssertEqual(BigUInt(1).power(-1), BigUInt(1)) XCTAssertEqual(BigUInt(1).power(-2), BigUInt(1)) XCTAssertEqual(BigUInt(1).power(-3), BigUInt(1)) XCTAssertEqual(BigUInt(1).power(-4), BigUInt(1)) XCTAssertEqual(BigUInt(2).power(0), BigUInt(1)) XCTAssertEqual(BigUInt(2).power(1), BigUInt(2)) XCTAssertEqual(BigUInt(2).power(2), BigUInt(4)) XCTAssertEqual(BigUInt(2).power(3), BigUInt(8)) XCTAssertEqual(BigUInt(2).power(-1), BigUInt(0)) XCTAssertEqual(BigUInt(2).power(-2), BigUInt(0)) XCTAssertEqual(BigUInt(2).power(-3), BigUInt(0)) XCTAssertEqual(BigUInt(3).power(0), BigUInt(1)) XCTAssertEqual(BigUInt(3).power(1), BigUInt(3)) XCTAssertEqual(BigUInt(3).power(2), BigUInt(9)) XCTAssertEqual(BigUInt(3).power(3), BigUInt(27)) XCTAssertEqual(BigUInt(3).power(-1), BigUInt(0)) XCTAssertEqual(BigUInt(3).power(-2), BigUInt(0)) XCTAssertEqual((BigUInt(1) << 256).power(0), BigUInt(1)) XCTAssertEqual((BigUInt(1) << 256).power(1), BigUInt(1) << 256) XCTAssertEqual((BigUInt(1) << 256).power(2), BigUInt(1) << 512) XCTAssertEqual(BigUInt(0).power(577), BigUInt(0)) XCTAssertEqual(BigUInt(1).power(577), BigUInt(1)) XCTAssertEqual(BigUInt(2).power(577), BigUInt(1) << 577) } func testModularExponentiation() { XCTAssertEqual(BigUInt(2).power(11, modulus: 1), 0) XCTAssertEqual(BigUInt(2).power(11, modulus: 1000), 48) func test(a: BigUInt, p: BigUInt, file: StaticString = #file, line: UInt = #line) { // For all primes p and integers a, a % p == a^p % p. (Fermat's Little Theorem) let x = a % p let y = x.power(p, modulus: p) XCTAssertEqual(x, y, file: file, line: line) } // Here are some primes let m61 = (BigUInt(1) << 61) - BigUInt(1) let m127 = (BigUInt(1) << 127) - BigUInt(1) let m521 = (BigUInt(1) << 521) - BigUInt(1) test(a: 2, p: m127) test(a: BigUInt(1) << 42, p: m127) test(a: BigUInt(1) << 42 + BigUInt(1), p: m127) test(a: m61, p: m127) test(a: m61 + 1, p: m127) test(a: m61, p: m521) test(a: m61 + 1, p: m521) test(a: m127, p: m521) } func testBitWidth() { XCTAssertEqual(BigUInt(0).bitWidth, 0) XCTAssertEqual(BigUInt(1).bitWidth, 1) XCTAssertEqual(BigUInt(Word.max).bitWidth, Word.bitWidth) XCTAssertEqual(BigUInt(words: [Word.max, 1]).bitWidth, Word.bitWidth + 1) XCTAssertEqual(BigUInt(words: [2, 12]).bitWidth, Word.bitWidth + 4) XCTAssertEqual(BigUInt(words: [1, Word.max]).bitWidth, 2 * Word.bitWidth) XCTAssertEqual(BigUInt(0).leadingZeroBitCount, 0) XCTAssertEqual(BigUInt(1).leadingZeroBitCount, Word.bitWidth - 1) XCTAssertEqual(BigUInt(Word.max).leadingZeroBitCount, 0) XCTAssertEqual(BigUInt(words: [Word.max, 1]).leadingZeroBitCount, Word.bitWidth - 1) XCTAssertEqual(BigUInt(words: [14, Word.max]).leadingZeroBitCount, 0) XCTAssertEqual(BigUInt(0).trailingZeroBitCount, 0) XCTAssertEqual(BigUInt((1 as Word) << (Word.bitWidth - 1)).trailingZeroBitCount, Word.bitWidth - 1) XCTAssertEqual(BigUInt(Word.max).trailingZeroBitCount, 0) XCTAssertEqual(BigUInt(words: [0, 1]).trailingZeroBitCount, Word.bitWidth) XCTAssertEqual(BigUInt(words: [0, 1 << Word(Word.bitWidth - 1)]).trailingZeroBitCount, 2 * Word.bitWidth - 1) } func testBitwise() { let a = BigUInt("1234567890ABCDEF13579BDF2468ACE", radix: 16)! let b = BigUInt("ECA8642FDB97531FEDCBA0987654321", radix: 16)! // a = 01234567890ABCDEF13579BDF2468ACE // b = 0ECA8642FDB97531FEDCBA0987654321 XCTAssertEqual(String(~a, radix: 16), "fedcba9876f543210eca86420db97531") XCTAssertEqual(String(a | b, radix: 16), "febc767fdbbfdfffffdfbbdf767cbef") XCTAssertEqual(String(a & b, radix: 16), "2044289083410f014380982440200") XCTAssertEqual(String(a ^ b, radix: 16), "fe9c32574b3c9ef0fe9c3b47523c9ef") let ffff = BigUInt(words: Array(repeating: Word.max, count: 30)) let not = ~ffff let zero = BigUInt() XCTAssertEqual(not, zero) XCTAssertEqual(Array((~ffff).words), []) XCTAssertEqual(a | ffff, ffff) XCTAssertEqual(a | 0, a) XCTAssertEqual(a & a, a) XCTAssertEqual(a & 0, 0) XCTAssertEqual(a & ffff, a) XCTAssertEqual(~(a | b), (~a & ~b)) XCTAssertEqual(~(a & b), (~a | ~b).extract(..<(a&b).count)) XCTAssertEqual(a ^ a, 0) XCTAssertEqual((a ^ b) ^ b, a) XCTAssertEqual((a ^ b) ^ a, b) var z = a * b z |= a z &= b z ^= ffff XCTAssertEqual(z, (((a * b) | a) & b) ^ ffff) } func testLeftShifts() { let sample = BigUInt("123456789ABCDEF01234567891631832727633", radix: 16)! var a = sample a <<= 0 XCTAssertEqual(a, sample) a = sample a <<= 1 XCTAssertEqual(a, 2 * sample) a = sample a <<= Word.bitWidth XCTAssertEqual(a.count, sample.count + 1) XCTAssertEqual(a[0], 0) XCTAssertEqual(a.extract(1 ... sample.count + 1), sample) a = sample a <<= 100 * Word.bitWidth XCTAssertEqual(a.count, sample.count + 100) XCTAssertEqual(a.extract(0 ..< 100), 0) XCTAssertEqual(a.extract(100 ... sample.count + 100), sample) a = sample a <<= 100 * Word.bitWidth + 2 XCTAssertEqual(a.count, sample.count + 100) XCTAssertEqual(a.extract(0 ..< 100), 0) XCTAssertEqual(a.extract(100 ... sample.count + 100), sample << 2) a = sample a <<= Word.bitWidth - 1 XCTAssertEqual(a.count, sample.count + 1) XCTAssertEqual(a, BigUInt(words: [0] + sample.words) / 2) a = sample a <<= -4 XCTAssertEqual(a, sample / 16) XCTAssertEqual(sample << 0, sample) XCTAssertEqual(sample << 1, 2 * sample) XCTAssertEqual(sample << 2, 4 * sample) XCTAssertEqual(sample << 4, 16 * sample) XCTAssertEqual(sample << Word.bitWidth, BigUInt(words: [0 as Word] + sample.words)) XCTAssertEqual(sample << (Word.bitWidth - 1), BigUInt(words: [0] + sample.words) / 2) XCTAssertEqual(sample << (Word.bitWidth + 1), BigUInt(words: [0] + sample.words) * 2) XCTAssertEqual(sample << (Word.bitWidth + 2), BigUInt(words: [0] + sample.words) * 4) XCTAssertEqual(sample << (2 * Word.bitWidth), BigUInt(words: [0, 0] + sample.words)) XCTAssertEqual(sample << (2 * Word.bitWidth + 2), BigUInt(words: [0, 0] + (4 * sample).words)) XCTAssertEqual(sample << -1, sample / 2) XCTAssertEqual(sample << -4, sample / 16) } func testRightShifts() { let sample = BigUInt("123456789ABCDEF1234567891631832727633", radix: 16)! var a = sample a >>= BigUInt(0) XCTAssertEqual(a, sample) a >>= 0 XCTAssertEqual(a, sample) a = sample a >>= 1 XCTAssertEqual(a, sample / 2) a = sample a >>= Word.bitWidth XCTAssertEqual(a, sample.extract(1...)) a = sample a >>= Word.bitWidth + 2 XCTAssertEqual(a, sample.extract(1...) / 4) a = sample a >>= sample.count * Word.bitWidth XCTAssertEqual(a, 0) a = sample a >>= 1000 XCTAssertEqual(a, 0) a = sample a >>= 100 * Word.bitWidth XCTAssertEqual(a, 0) a = sample a >>= 100 * BigUInt(Word.max) XCTAssertEqual(a, 0) a = sample a >>= -1 XCTAssertEqual(a, sample * 2) a = sample a >>= -4 XCTAssertEqual(a, sample * 16) XCTAssertEqual(sample >> BigUInt(0), sample) XCTAssertEqual(sample >> 0, sample) XCTAssertEqual(sample >> 1, sample / 2) XCTAssertEqual(sample >> 3, sample / 8) XCTAssertEqual(sample >> Word.bitWidth, sample.extract(1 ..< sample.count)) XCTAssertEqual(sample >> (Word.bitWidth + 2), sample.extract(1...) / 4) XCTAssertEqual(sample >> (Word.bitWidth + 3), sample.extract(1...) / 8) XCTAssertEqual(sample >> (sample.count * Word.bitWidth), 0) XCTAssertEqual(sample >> (100 * Word.bitWidth), 0) XCTAssertEqual(sample >> (100 * BigUInt(Word.max)), 0) XCTAssertEqual(sample >> -1, sample * 2) XCTAssertEqual(sample >> -4, sample * 16) } func testSquareRoot() { let sample = BigUInt("123456789ABCDEF1234567891631832727633", radix: 16)! XCTAssertEqual(BigUInt(0).squareRoot(), 0) XCTAssertEqual(BigUInt(256).squareRoot(), 16) func checkSqrt(_ value: BigUInt, file: StaticString = #file, line: UInt = #line) { let root = value.squareRoot() XCTAssertLessThanOrEqual(root * root, value, "\(value)", file: file, line: line) XCTAssertGreaterThan((root + 1) * (root + 1), value, "\(value)", file: file, line: line) } for i in 0 ... 100 { checkSqrt(BigUInt(i)) checkSqrt(BigUInt(i) << 100) } checkSqrt(sample) checkSqrt(sample * sample) checkSqrt(sample * sample - 1) checkSqrt(sample * sample + 1) } func testGCD() { XCTAssertEqual(BigUInt(0).greatestCommonDivisor(with: 2982891), 2982891) XCTAssertEqual(BigUInt(2982891).greatestCommonDivisor(with: 0), 2982891) XCTAssertEqual(BigUInt(0).greatestCommonDivisor(with: 0), 0) XCTAssertEqual(BigUInt(4).greatestCommonDivisor(with: 6), 2) XCTAssertEqual(BigUInt(15).greatestCommonDivisor(with: 10), 5) XCTAssertEqual(BigUInt(8 * 3 * 25 * 7).greatestCommonDivisor(with: 2 * 9 * 5 * 49), 2 * 3 * 5 * 7) var fibo: [BigUInt] = [0, 1] for i in 0...10000 { fibo.append(fibo[i] + fibo[i + 1]) } XCTAssertEqual(BigUInt(fibo[100]).greatestCommonDivisor(with: fibo[101]), 1) XCTAssertEqual(BigUInt(fibo[1000]).greatestCommonDivisor(with: fibo[1001]), 1) XCTAssertEqual(BigUInt(fibo[10000]).greatestCommonDivisor(with: fibo[10001]), 1) XCTAssertEqual(BigUInt(3 * 5 * 7 * 9).greatestCommonDivisor(with: 5 * 7 * 7), 5 * 7) XCTAssertEqual(BigUInt(fibo[4]).greatestCommonDivisor(with: fibo[2]), fibo[2]) XCTAssertEqual(BigUInt(fibo[3 * 5 * 7 * 9]).greatestCommonDivisor(with: fibo[5 * 7 * 7 * 9]), fibo[5 * 7 * 9]) XCTAssertEqual(BigUInt(fibo[7 * 17 * 83]).greatestCommonDivisor(with: fibo[6 * 17 * 83]), fibo[17 * 83]) } func testInverse() { XCTAssertNil(BigUInt(4).inverse(2)) XCTAssertNil(BigUInt(4).inverse(8)) XCTAssertNil(BigUInt(12).inverse(15)) XCTAssertEqual(BigUInt(13).inverse(15), 7) XCTAssertEqual(BigUInt(251).inverse(1023), 269) XCTAssertNil(BigUInt(252).inverse(1023)) XCTAssertEqual(BigUInt(2).inverse(1023), 512) } func testStrongProbablePrimeTest() { let primes: [BigUInt.Word] = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 79, 83, 89, 97] let pseudoPrimes: [BigUInt] = [ /* 2 */ 2_047, /* 3 */ 1_373_653, /* 5 */ 25_326_001, /* 7 */ 3_215_031_751, /* 11 */ 2_152_302_898_747, /* 13 */ 3_474_749_660_383, /* 17 */ 341_550_071_728_321, /* 19 */ 341_550_071_728_321, /* 23 */ 3_825_123_056_546_413_051, /* 29 */ 3_825_123_056_546_413_051, /* 31 */ 3_825_123_056_546_413_051, /* 37 */ "318665857834031151167461", /* 41 */ "3317044064679887385961981", ] for i in 0..<pseudoPrimes.count { let candidate = pseudoPrimes[i] print(candidate) // SPPT should not rule out candidate's primality for primes less than prime[i + 1] for j in 0...i { XCTAssertTrue(candidate.isStrongProbablePrime(BigUInt(primes[j]))) } // But the pseudoprimes aren't prime, so there is a base that disproves them. let foo = (i + 1 ... i + 3).filter { !candidate.isStrongProbablePrime(BigUInt(primes[$0])) } XCTAssertNotEqual(foo, []) } // Try the SPPT for some Mersenne numbers. // Mersenne exponents from OEIS: https://oeis.org/A000043 XCTAssertFalse((BigUInt(1) << 606 - BigUInt(1)).isStrongProbablePrime(5)) XCTAssertTrue((BigUInt(1) << 607 - BigUInt(1)).isStrongProbablePrime(5)) // 2^607 - 1 is prime XCTAssertFalse((BigUInt(1) << 608 - BigUInt(1)).isStrongProbablePrime(5)) XCTAssertFalse((BigUInt(1) << 520 - BigUInt(1)).isStrongProbablePrime(7)) XCTAssertTrue((BigUInt(1) << 521 - BigUInt(1)).isStrongProbablePrime(7)) // 2^521 -1 is prime XCTAssertFalse((BigUInt(1) << 522 - BigUInt(1)).isStrongProbablePrime(7)) XCTAssertFalse((BigUInt(1) << 88 - BigUInt(1)).isStrongProbablePrime(128)) XCTAssertTrue((BigUInt(1) << 89 - BigUInt(1)).isStrongProbablePrime(128)) // 2^89 -1 is prime XCTAssertFalse((BigUInt(1) << 90 - BigUInt(1)).isStrongProbablePrime(128)) // One extra test to exercise an a^2 % modulus == 1 case XCTAssertFalse(BigUInt(217).isStrongProbablePrime(129)) } func testIsPrime() { XCTAssertFalse(BigUInt(0).isPrime()) XCTAssertFalse(BigUInt(1).isPrime()) XCTAssertTrue(BigUInt(2).isPrime()) XCTAssertTrue(BigUInt(3).isPrime()) XCTAssertFalse(BigUInt(4).isPrime()) XCTAssertTrue(BigUInt(5).isPrime()) // Try primality testing the first couple hundred Mersenne numbers comparing against the first few Mersenne exponents from OEIS: https://oeis.org/A000043 let mp: Set<Int> = [2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521] for exponent in 2..<200 { let m = BigUInt(1) << exponent - 1 XCTAssertEqual(m.isPrime(), mp.contains(exponent), "\(exponent)") } } func testConversionToString() { let sample = BigUInt("123456789ABCDEFEDCBA98765432123456789ABCDEF", radix: 16)! // Radix = 10 XCTAssertEqual(String(BigUInt()), "0") XCTAssertEqual(String(BigUInt(1)), "1") XCTAssertEqual(String(BigUInt(100)), "100") XCTAssertEqual(String(BigUInt(12345)), "12345") XCTAssertEqual(String(BigUInt(123456789)), "123456789") XCTAssertEqual(String(sample), "425693205796080237694414176550132631862392541400559") // Radix = 16 XCTAssertEqual(String(BigUInt(0x1001), radix: 16), "1001") XCTAssertEqual(String(BigUInt(0x0102030405060708), radix: 16), "102030405060708") XCTAssertEqual(String(sample, radix: 16), "123456789abcdefedcba98765432123456789abcdef") XCTAssertEqual(String(sample, radix: 16, uppercase: true), "123456789ABCDEFEDCBA98765432123456789ABCDEF") // Radix = 2 XCTAssertEqual(String(BigUInt(12), radix: 2), "1100") XCTAssertEqual(String(BigUInt(123), radix: 2), "1111011") XCTAssertEqual(String(BigUInt(1234), radix: 2), "10011010010") XCTAssertEqual(String(sample, radix: 2), "1001000110100010101100111100010011010101111001101111011111110110111001011101010011000011101100101010000110010000100100011010001010110011110001001101010111100110111101111") // Radix = 31 XCTAssertEqual(String(BigUInt(30), radix: 31), "u") XCTAssertEqual(String(BigUInt(31), radix: 31), "10") XCTAssertEqual(String(BigUInt("10000000000000000", radix: 16)!, radix: 31), "nd075ib45k86g") XCTAssertEqual(String(BigUInt("2908B5129F59DB6A41", radix: 16)!, radix: 31), "100000000000000") XCTAssertEqual(String(sample, radix: 31), "ptf96helfaqi7ogc3jbonmccrhmnc2b61s") let quickLook = BigUInt(513).playgroundDescription as? String if quickLook == "513 (10 bits)" { } else { XCTFail("Unexpected playground QuickLook representation: \(quickLook ?? "nil")") } } func testConversionFromString() { let sample = "123456789ABCDEFEDCBA98765432123456789ABCDEF" XCTAssertEqual(BigUInt("1"), 1) XCTAssertEqual(BigUInt("123456789ABCDEF", radix: 16)!, 0x123456789ABCDEF) XCTAssertEqual(BigUInt("1000000000000000000000"), BigUInt("3635C9ADC5DEA00000", radix: 16)) XCTAssertEqual(BigUInt("10000000000000000", radix: 16), BigUInt("18446744073709551616")) XCTAssertEqual(BigUInt(sample, radix: 16)!, BigUInt("425693205796080237694414176550132631862392541400559")) // We have to call BigUInt.init here because we don't want Literal initialization via coercion (SE-0213) XCTAssertNil(BigUInt.init("Not a number")) XCTAssertNil(BigUInt.init("X")) XCTAssertNil(BigUInt.init("12349A")) XCTAssertNil(BigUInt.init("000000000000000000000000A000")) XCTAssertNil(BigUInt.init("00A0000000000000000000000000")) XCTAssertNil(BigUInt.init("00 0000000000000000000000000")) XCTAssertNil(BigUInt.init("\u{4e00}\u{4e03}")) // Chinese numerals "1", "7" XCTAssertEqual(BigUInt("u", radix: 31)!, 30) XCTAssertEqual(BigUInt("10", radix: 31)!, 31) XCTAssertEqual(BigUInt("100000000000000", radix: 31)!, BigUInt("2908B5129F59DB6A41", radix: 16)!) XCTAssertEqual(BigUInt("nd075ib45k86g", radix: 31)!, BigUInt("10000000000000000", radix: 16)!) XCTAssertEqual(BigUInt("ptf96helfaqi7ogc3jbonmccrhmnc2b61s", radix: 31)!, BigUInt(sample, radix: 16)!) XCTAssertNotNil(BigUInt(sample.repeated(100), radix: 16)) } func testRandomIntegerWithMaximumWidth() { XCTAssertEqual(BigUInt.randomInteger(withMaximumWidth: 0), 0) let randomByte = BigUInt.randomInteger(withMaximumWidth: 8) XCTAssertLessThan(randomByte, 256) for _ in 0 ..< 100 { XCTAssertLessThanOrEqual(BigUInt.randomInteger(withMaximumWidth: 1024).bitWidth, 1024) } // Verify that all widths <= maximum are produced (with a tiny maximum) var widths: Set<Int> = [0, 1, 2, 3] var i = 0 while !widths.isEmpty { let random = BigUInt.randomInteger(withMaximumWidth: 3) XCTAssertLessThanOrEqual(random.bitWidth, 3) widths.remove(random.bitWidth) i += 1 if i > 4096 { XCTFail("randomIntegerWithMaximumWidth doesn't seem random") break } } // Verify that all bits are sometimes zero, sometimes one. var oneBits = Set<Int>(0..<1024) var zeroBits = Set<Int>(0..<1024) while !oneBits.isEmpty || !zeroBits.isEmpty { var random = BigUInt.randomInteger(withMaximumWidth: 1024) for i in 0..<1024 { if random[0] & 1 == 1 { oneBits.remove(i) } else { zeroBits.remove(i) } random >>= 1 } } } func testRandomIntegerWithExactWidth() { XCTAssertEqual(BigUInt.randomInteger(withExactWidth: 0), 0) XCTAssertEqual(BigUInt.randomInteger(withExactWidth: 1), 1) for _ in 0 ..< 1024 { let randomByte = BigUInt.randomInteger(withExactWidth: 8) XCTAssertEqual(randomByte.bitWidth, 8) XCTAssertLessThan(randomByte, 256) XCTAssertGreaterThanOrEqual(randomByte, 128) } for _ in 0 ..< 100 { XCTAssertEqual(BigUInt.randomInteger(withExactWidth: 1024).bitWidth, 1024) } // Verify that all bits except the top are sometimes zero, sometimes one. var oneBits = Set<Int>(0..<1023) var zeroBits = Set<Int>(0..<1023) while !oneBits.isEmpty || !zeroBits.isEmpty { var random = BigUInt.randomInteger(withExactWidth: 1024) for i in 0..<1023 { if random[0] & 1 == 1 { oneBits.remove(i) } else { zeroBits.remove(i) } random >>= 1 } } } func testRandomIntegerLessThan() { // Verify that all bits in random integers generated by `randomIntegerLessThan` are sometimes zero, sometimes one. // // The limit starts with "11" so that generated random integers may easily begin with all combos. // Also, 25% of the time the initial random int will be rejected as higher than the // limit -- this helps stabilize code coverage. let limit = BigUInt(3) << 1024 var oneBits = Set<Int>(0..<limit.bitWidth) var zeroBits = Set<Int>(0..<limit.bitWidth) for _ in 0..<100 { var random = BigUInt.randomInteger(lessThan: limit) XCTAssertLessThan(random, limit) for i in 0..<limit.bitWidth { if random[0] & 1 == 1 { oneBits.remove(i) } else { zeroBits.remove(i) } random >>= 1 } } XCTAssertEqual(oneBits, []) XCTAssertEqual(zeroBits, []) } func testRandomFunctionsUseProvidedGenerator() { // Here I verify that each of the randomInteger functions uses the provided RNG, and not SystemRandomNumberGenerator. // This is important because all but BigUInt.randomInteger(withMaximumWidth:using:) are built on that base function, and it is easy to forget to pass along the provided generator and get a default SystemRandomNumberGenerator instead. // Since SystemRandomNumberGenerator is seeded randomly, repeated uses should give varying results. // So here I pass the same deterministic RNG repeatedly and verify that I get the same result each time. struct CountingRNG: RandomNumberGenerator { var i: UInt64 = 12345 mutating func next() -> UInt64 { i += 1 return i } } func gen(_ body: (inout CountingRNG) -> BigUInt) -> BigUInt { var rng = CountingRNG() return body(&rng) } func check(_ body: (inout CountingRNG) -> BigUInt) { let expected = gen(body) for _ in 0 ..< 100 { let actual = gen(body) XCTAssertEqual(expected, actual) } } check { BigUInt.randomInteger(withMaximumWidth: 200, using: &$0) } check { BigUInt.randomInteger(withExactWidth: 200, using: &$0) } let limit = BigUInt(UInt64.max) * BigUInt(UInt64.max) * BigUInt(UInt64.max) check { BigUInt.randomInteger(lessThan: limit, using: &$0) } } }
mit
3d228e2bf982ab2eb8d8a166f23ad90e
40.070223
241
0.556136
3.433725
false
true
false
false
Miguel-Herrero/Swift
WhatsUp/WhatsUp/ViewController.swift
1
4737
// // ViewController.swift // WhatsUp // // Created by Miguel Herrero on 31/7/17. // Copyright © 2017 Miguel Herrero. All rights reserved. // import UIKit import SpriteKit import ARKit import CoreLocation import GameplayKit class ViewController: UIViewController, ARSKViewDelegate { @IBOutlet var sceneView: ARSKView! let locationManager = CLLocationManager() var userLocation = CLLocation() var sitesJSON = JSON() var userHeading = 0.0 var headingStep = 0 // Para saber cuántas veces se ha actualizado la dirección (esperaremos a la 3ª vez para que sea preciso) override func viewDidLoad() { super.viewDidLoad() // Assign delegate and obtain location locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestWhenInUseAuthorization() // Set the view's delegate sceneView.delegate = self // Show statistics such as fps and node count sceneView.showsFPS = true sceneView.showsNodeCount = true // Load the SKScene from 'Scene.sks' if let scene = SKScene(fileNamed: "Scene") { sceneView.presentScene(scene) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Create a session configuration let configuration = ARSessionConfiguration() // Run the view's session sceneView.session.run(configuration) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // Pause the view's session sceneView.session.pause() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } // MARK: - ARSKViewDelegate func view(_ view: ARSKView, nodeFor anchor: ARAnchor) -> SKNode? { return nil } func session(_ session: ARSession, didFailWithError error: Error) { // Present an error message to the user } func sessionWasInterrupted(_ session: ARSession) { // Inform the user that the session has been interrupted, for example, by presenting an overlay } func sessionInterruptionEnded(_ session: ARSession) { // Reset tracking and/or remove existing anchors if consistent tracking is required } // MARK: - My funcs func updateSites() { let urlString = "https://en.wikipedia.org/w/api.php?ggscoord=\(userLocation.coordinate.latitude)%7C\(userLocation.coordinate.longitude)&action=query&prop=coordinates%7Cpageimages%7Cpageterms&colimit=50&piprop=thumbnail&pithumbsize=500&pilimit=50&wbptterms=description&generator=geosearch&ggsradius=10000&ggslimit=50&format=json" guard let url = URL(string: urlString) else { return } if let data = try? Data(contentsOf: url) { sitesJSON = JSON(data) // Saber la direccióna dónde está apuntando el usuario locationManager.startUpdatingHeading() } } func createSites() { } } // MARK: - CLLocationManager extension ViewController: CLLocationManagerDelegate { func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print(error.localizedDescription) } func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { if status == .authorizedWhenInUse { locationManager.requestLocation() } } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { // Obtener la última posición del usuario guard let location = locations.last else { return } // Actualizar la posición del usuario userLocation = location // Actualizar los sitios en segundo plano DispatchQueue.global().async { self.updateSites() } } func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) { DispatchQueue.main.async { self.headingStep += 1 // Ignorar las dos primeras direcciones porque no son muy precisas if self.headingStep < 2 { return } // COoger la orientación magnética self.userHeading = newHeading.magneticHeading self.locationManager.stopUpdatingHeading() self.createSites() } } }
gpl-3.0
205f8648b4f98fbd6b09709cfcd71080
30.925676
336
0.637884
5.086114
false
false
false
false
Motsai/neblina-motiondemo-swift
ExerciseMotionTracker/iOS/ExerciseMotionTracker/AppDelegate.swift
2
3185
// // AppDelegate.swift // ExerciseMotionTracker // // Created by Hoan Hoang on 2015-11-24. // Copyright © 2015 Hoan Hoang. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. let splitViewController = self.window!.rootViewController as! UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem splitViewController.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 throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // MARK: - Split view func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController:UIViewController, onto primaryViewController:UIViewController) -> Bool { guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false } guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false } if topAsDetailController.nebdev == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } return false } }
mit
bfa7a29b1ec4aa27007f23f1b222b98a
51.196721
279
0.796168
5.595782
false
false
false
false
ArturAzarau/chatter
Chatter/Chatter/ToolbarVC.swift
1
5306
// // ToolbarVC.swift // Chatter // // Created by Artur Azarov on 08.09.17. // Copyright © 2017 Artur Azarov. All rights reserved. // import Cocoa enum ModalType { case logIn } final class ToolbarVC: NSViewController { // MARK: - Outlets @IBOutlet weak var loginImage: NSImageView! @IBOutlet weak var loginLabel: NSTextField! @IBOutlet weak var loginStack: NSStackView! // MARK: - Variables var modalBackgroundView: ClickBlockingView! var modalView: NSView! // MARK: - Life cycle override func viewWillAppear() { super.viewWillAppear() setUpView() } // MARK: - View methods private func setUpView() { // setup observer NotificationCenter.default.addObserver(self, selector: #selector(presentModal(_:)), name: Notifications.Names.notifPresentModal, object: nil) // setup main view view.wantsLayer = true view.layer?.backgroundColor = NSColor.chatGreen.cgColor // setup login stack view loginStack.gestureRecognizers.removeAll() let profilePage = NSClickGestureRecognizer(target: self, action: #selector(openProfilePage(_:))) loginStack.addGestureRecognizer(profilePage) } // MARK: - Helpers @objc private func openProfilePage(_ recognizer: NSClickGestureRecognizer) { let loginDict: [String: ModalType] = [Notifications.userInfoModal: ModalType.logIn] NotificationCenter.default.post(name: Notifications.Names.notifPresentModal, object: nil, userInfo: loginDict) } @objc private func presentModal(_ notification: Notification) { var modalWidth: CGFloat = 0 var modalHeight: CGFloat = 0 if modalBackgroundView == nil { modalBackgroundView = ClickBlockingView() modalBackgroundView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(modalBackgroundView, positioned: .above, relativeTo: loginStack) let topConstraint = NSLayoutConstraint(item: modalBackgroundView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: 50) let leftConstraint = NSLayoutConstraint(item: modalBackgroundView, attribute: .left, relatedBy: .equal, toItem: view, attribute: .left, multiplier: 1, constant: 0) let rightConstraint = NSLayoutConstraint(item: modalBackgroundView, attribute: .right, relatedBy: .equal, toItem: view, attribute: .right, multiplier: 1, constant: 0) let bottomConstraint = NSLayoutConstraint(item: modalBackgroundView, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0) view.addConstraints([topConstraint,bottomConstraint,leftConstraint,rightConstraint]) modalBackgroundView.layer?.backgroundColor = NSColor.black.cgColor modalBackgroundView.alphaValue = 0 let closeBackgroundClick = NSClickGestureRecognizer(target: self, action: #selector(closeModalClick(_:))) modalBackgroundView.addGestureRecognizer(closeBackgroundClick) // Instatiate XIB guard let modalType = notification.userInfo?[Notifications.userInfoModal] as? ModalType else { return } switch modalType { case .logIn: modalView = ModalLogin() modalWidth = 475 modalHeight = 300 } modalView.wantsLayer = true modalView.translatesAutoresizingMaskIntoConstraints = false modalView.alphaValue = 0 view.addSubview(modalView, positioned: .above, relativeTo: modalBackgroundView) let horizontalConstraint = modalView.centerXAnchor.constraint(equalTo: view.centerXAnchor) let verticalConstraint = modalView.centerYAnchor.constraint(equalTo: view.centerYAnchor) let widthConstraint = modalView.widthAnchor.constraint(equalToConstant: modalWidth) let heightConstraint = modalView.heightAnchor.constraint(equalToConstant: modalHeight) NSLayoutConstraint.activate([horizontalConstraint, verticalConstraint,widthConstraint,heightConstraint]) } NSAnimationContext.runAnimationGroup({ (context) in context.duration = 0.5 modalBackgroundView.animator().alphaValue = 0.6 modalView.animator().alphaValue = 1.0 self.view.layoutSubtreeIfNeeded() }, completionHandler: nil) } private func closeModal() { NSAnimationContext.runAnimationGroup({ (context) in context.duration = 0.5 modalView.animator().alphaValue = 0 modalBackgroundView.animator().alphaValue = 0 self.view.layoutSubtreeIfNeeded() }) { if self.modalBackgroundView != nil { self.modalBackgroundView.removeFromSuperview() self.modalBackgroundView = nil } self.modalView.removeFromSuperview() } } @objc private func closeModalClick(_ recognizer: NSGestureRecognizer) { closeModal() } }
mit
af4a16033018ae117cbcfdb2dee54cf4
39.807692
181
0.653157
5.491718
false
false
false
false
szehnder/AERecord
AERecord/AERecord.swift
1
26774
// // AERecord.swift // // Copyright (c) 2014 Marko Tadic - http://markotadic.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 CoreData let kAERecordPrintLog = true // MARK: - AERecord (facade for shared instance of AEStack) public class AERecord { // MARK: Properties public class var defaultContext: NSManagedObjectContext { return AEStack.sharedInstance.defaultContext } // context for current thread public class var mainContext: NSManagedObjectContext { return AEStack.sharedInstance.mainContext } // context for main thread public class var backgroundContext: NSManagedObjectContext { return AEStack.sharedInstance.backgroundContext } // context for background thread class var persistentStoreCoordinator: NSPersistentStoreCoordinator? { return AEStack.sharedInstance.persistentStoreCoordinator } // MARK: Setup Stack public class func storeURLForName(name: String) -> NSURL { return AEStack.storeURLForName(name) } public class func loadCoreDataStack(managedObjectModel: NSManagedObjectModel = AEStack.defaultModel, storeType: String = NSSQLiteStoreType, configuration: String? = nil, storeURL: NSURL = AEStack.defaultURL, options: [NSObject : AnyObject]? = nil) -> NSError? { return AEStack.sharedInstance.loadCoreDataStack(managedObjectModel, storeType: storeType, configuration: configuration, storeURL: storeURL, options: options) } public class func destroyCoreDataStack(storeURL: NSURL = AEStack.defaultURL) { AEStack.sharedInstance.destroyCoreDataStack(storeURL) } public class func truncateAllData(context: NSManagedObjectContext? = nil) { AEStack.sharedInstance.truncateAllData(context) } // MARK: Context Execute public class func executeFetchRequest(request: NSFetchRequest, context: NSManagedObjectContext? = nil) -> [NSManagedObject] { return AEStack.sharedInstance.executeFetchRequest(request, context: context) } // MARK: Context Save public class func saveContext(context: NSManagedObjectContext? = nil) { AEStack.sharedInstance.saveContext(context) } public class func saveContextAndWait(context: NSManagedObjectContext? = nil) { AEStack.sharedInstance.saveContextAndWait(context) } // MARK: Context Faulting Objects public class func refreshObjects(objectIDS: [NSManagedObjectID], mergeChanges: Bool, context: NSManagedObjectContext = AERecord.defaultContext) { AEStack.refreshObjects(objectIDS: objectIDS, mergeChanges: mergeChanges, context: context) } public class func refreshAllRegisteredObjects(mergeChanges: Bool, context: NSManagedObjectContext = AERecord.defaultContext) { AEStack.refreshAllRegisteredObjects(mergeChanges: mergeChanges, context: context) } } // MARK: - CoreData Stack (AERecord heart:) public class AEStack { // MARK: Shared Instance class var sharedInstance: AEStack { struct Singleton { static let instance = AEStack() } return Singleton.instance } // MARK: Default settings class var bundleIdentifier: String { return NSBundle.mainBundle().bundleIdentifier! } class var defaultURL: NSURL { return storeURLForName(bundleIdentifier) } class var defaultModel: NSManagedObjectModel { return NSManagedObjectModel.mergedModelFromBundles(nil)! } // MARK: Properties var managedObjectModel: NSManagedObjectModel? var persistentStoreCoordinator: NSPersistentStoreCoordinator? var mainContext: NSManagedObjectContext! var backgroundContext: NSManagedObjectContext! var defaultContext: NSManagedObjectContext { if NSThread.isMainThread() { return mainContext } else { return backgroundContext } } // MARK: Setup Stack public class func storeURLForName(name: String) -> NSURL { let applicationDocumentsDirectory = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).last! as NSURL let storeName = "\(name).sqlite" return applicationDocumentsDirectory.URLByAppendingPathComponent(storeName) } public func loadCoreDataStack(managedObjectModel: NSManagedObjectModel = defaultModel, storeType: String = NSSQLiteStoreType, configuration: String? = nil, storeURL: NSURL = defaultURL, options: [NSObject : AnyObject]? = nil) -> NSError? { self.managedObjectModel = managedObjectModel // setup main and background contexts mainContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) backgroundContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType) // create the coordinator and store persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel) if let coordinator = persistentStoreCoordinator { var error: NSError? do { try coordinator.addPersistentStoreWithType(storeType, configuration: configuration, URL: storeURL, options: options) // everything went ok mainContext.persistentStoreCoordinator = coordinator backgroundContext.persistentStoreCoordinator = coordinator startReceivingContextNotifications() return nil } catch let error1 as NSError { error = error1 var userInfoDictionary = [NSObject : AnyObject]() userInfoDictionary[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" userInfoDictionary[NSLocalizedFailureReasonErrorKey] = "There was an error creating or loading the application's saved data." userInfoDictionary[NSUnderlyingErrorKey] = error error = NSError(domain: AEStack.bundleIdentifier, code: 1, userInfo: userInfoDictionary) if let err = error { if kAERecordPrintLog { print("Error occured in \(NSStringFromClass(self.dynamicType)) - function: \(#function) | line: \(#line)\n\(err)") } } return error } } else { return NSError(domain: AEStack.bundleIdentifier, code: 2, userInfo: [NSLocalizedDescriptionKey : "Could not create NSPersistentStoreCoordinator from given NSManagedObjectModel."]) } } func destroyCoreDataStack(storeURL: NSURL = defaultURL) -> NSError? { // must load this core data stack first loadCoreDataStack(storeURL: storeURL) // because there is no persistentStoreCoordinator if destroyCoreDataStack is called before loadCoreDataStack // also if we're in other stack currently that persistentStoreCoordinator doesn't know about this storeURL stopReceivingContextNotifications() // stop receiving notifications for these contexts // reset contexts mainContext.reset() backgroundContext.reset() // finally, remove persistent store var error: NSError? if let coordinator = persistentStoreCoordinator { if let store = coordinator.persistentStoreForURL(storeURL) { do { try coordinator.removePersistentStore(store) do { try NSFileManager.defaultManager().removeItemAtURL(storeURL) } catch let error1 as NSError { error = error1 } } catch let error1 as NSError { error = error1 } } } // reset coordinator and model persistentStoreCoordinator = nil managedObjectModel = nil if let err = error { if kAERecordPrintLog { print("Error occured in \(NSStringFromClass(self.dynamicType)) - function: \(#function) | line: \(#line)\n\(err)") } } return error ?? nil } public func truncateAllData(context: NSManagedObjectContext? = nil) { let moc = context ?? defaultContext if let mom = managedObjectModel { for entity in mom.entities as [NSEntityDescription] { if let entityType = NSClassFromString(entity.managedObjectClassName) as? NSManagedObject.Type { entityType.deleteAll(moc) } } } } deinit { stopReceivingContextNotifications() if kAERecordPrintLog { print("\(NSStringFromClass(self.dynamicType)) deinitialized - function: \(#function) | line: \(#line)\n") } } // MARK: Context Execute func executeFetchRequest(request: NSFetchRequest, context: NSManagedObjectContext? = nil) -> [NSManagedObject] { var fetchedObjects = [NSManagedObject]() let moc = context ?? defaultContext moc.performBlockAndWait { () -> Void in var error: NSError? do { let result = try moc.executeFetchRequest(request) if let managedObjects = result as? [NSManagedObject] { fetchedObjects = managedObjects } } catch let error1 as NSError { error = error1 } catch { fatalError() } if let err = error { if kAERecordPrintLog { print("Error occured in \(NSStringFromClass(self.dynamicType)) - function: \(#function) | line: \(#line)\n\(err)") } } } return fetchedObjects } // MARK: Context Save func saveContext(context: NSManagedObjectContext? = nil) { let moc = context ?? defaultContext moc.performBlock { () -> Void in if (moc.hasChanges) { do { try moc.save() } catch let error as NSError { if kAERecordPrintLog { print("Error occured in \(NSStringFromClass(self.dynamicType)) - function: \(#function) | line: \(#line)\n\(error)") } } catch _ { // FIXME: do something with other exception } } } } func saveContextAndWait(context: NSManagedObjectContext? = nil) { let moc = context ?? defaultContext moc.performBlockAndWait { () -> Void in if moc.hasChanges { do { try moc.save() } catch let error as NSError { if kAERecordPrintLog { print("Error occured in \(NSStringFromClass(self.dynamicType)) - function: \(#function) | line: \(#line)\n\(error)") } } catch _ { // FIXME: do something with other exception } } } } // MARK: Context Sync func startReceivingContextNotifications() { NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AEStack.contextDidSave(_:)), name: NSManagedObjectContextDidSaveNotification, object: mainContext) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AEStack.contextDidSave(_:)), name: NSManagedObjectContextDidSaveNotification, object: backgroundContext) } func stopReceivingContextNotifications() { NSNotificationCenter.defaultCenter().removeObserver(self) } @objc func contextDidSave(notification: NSNotification) { if let context = notification.object as? NSManagedObjectContext { let contextToRefresh = context == mainContext ? backgroundContext : mainContext contextToRefresh.performBlock({ () -> Void in contextToRefresh.mergeChangesFromContextDidSaveNotification(notification) }) } } // MARK: Context Faulting Objects class func refreshObjects(objectIDS objectIDS: [NSManagedObjectID], mergeChanges: Bool, context: NSManagedObjectContext = AERecord.defaultContext) { for objectID in objectIDS { context.performBlockAndWait({ () -> Void in do { let object = try context.existingObjectWithID(objectID) if (object.fault == false) { // turn managed object into fault context.refreshObject(object, mergeChanges: mergeChanges) } } catch let error as NSError { if kAERecordPrintLog { print(error) //print("Error occured in \(NSStringFromClass(self.dynamicType)) - function: \(__FUNCTION__) | line: \(__LINE__)\n\(error)") } } catch _ { fatalError() } }) } } class func refreshAllRegisteredObjects(mergeChanges mergeChanges: Bool, context: NSManagedObjectContext = AERecord.defaultContext) { var registeredObjectIDS = [NSManagedObjectID]() for managedObject in context.registeredObjects { registeredObjectIDS.append(managedObject.objectID) } refreshObjects(objectIDS: registeredObjectIDS, mergeChanges: mergeChanges) } } // MARK: - NSManagedObject Extension public extension NSManagedObject { // MARK: General public class var entityName: String { var name = NSStringFromClass(self) name = name.componentsSeparatedByString(".").last! return name } public class var entity: NSEntityDescription? { return NSEntityDescription.entityForName(entityName, inManagedObjectContext: AERecord.defaultContext) } public class func createFetchRequest(predicate: NSPredicate? = nil, sortDescriptors: [NSSortDescriptor]? = nil, limit:Int? = nil) -> NSFetchRequest { // create request let request = NSFetchRequest(entityName: entityName) // set request parameters request.predicate = predicate request.sortDescriptors = sortDescriptors if (limit != nil) { request.fetchLimit = limit! } return request } // MARK: Creating public class func create(context: NSManagedObjectContext = AERecord.defaultContext) -> Self { let entityDescription = NSEntityDescription.entityForName(entityName, inManagedObjectContext: context) let object = self.init(entity: entityDescription!, insertIntoManagedObjectContext: context) return object } public class func createWithAttributes(attributes: [String : AnyObject], context: NSManagedObjectContext = AERecord.defaultContext) -> Self { let object = create(context) if attributes.count > 0 { object.setValuesForKeysWithDictionary(attributes) } return object } public class func firstOrCreateWithAttribute(attribute: String, value: AnyObject, context: NSManagedObjectContext = AERecord.defaultContext) -> NSManagedObject { let predicate = NSPredicate(format: "%K = %@", argumentArray: [attribute, value]) let request = createFetchRequest(predicate) request.fetchLimit = 1 let objects = AERecord.executeFetchRequest(request, context: context) return objects.first ?? createWithAttributes([attribute : value], context: context) } // MARK: Deleting // public func delete(context: NSManagedObjectContext = AERecord.defaultContext) { // context.deleteObject(self) // } public class func deleteAll(context: NSManagedObjectContext = AERecord.defaultContext) { if let objects = self.all(context: context) { for object in objects { context.deleteObject(object) } } } public class func deleteAllWithPredicate(predicate: NSPredicate, context: NSManagedObjectContext = AERecord.defaultContext) { if let objects = self.allWithPredicate(predicate, context: context) { for object in objects { context.deleteObject(object) } } } public class func deleteAllWithAttribute(attribute: String, value: AnyObject, context: NSManagedObjectContext = AERecord.defaultContext) { if let objects = self.allWithAttribute(attribute, value: value, context: context) { for object in objects { context.deleteObject(object) } } } // MARK: Finding First public class func first(sortDescriptors: [NSSortDescriptor]? = nil, context: NSManagedObjectContext = AERecord.defaultContext) -> NSManagedObject? { let request = createFetchRequest(sortDescriptors: sortDescriptors) request.fetchLimit = 1 let objects = AERecord.executeFetchRequest(request, context: context) return objects.first ?? nil } public class func firstWithPredicate(predicate: NSPredicate, sortDescriptors: [NSSortDescriptor]? = nil, context: NSManagedObjectContext = AERecord.defaultContext) -> NSManagedObject? { let request = createFetchRequest(predicate, sortDescriptors: sortDescriptors) request.fetchLimit = 1 let objects = AERecord.executeFetchRequest(request, context: context) return objects.first ?? nil } public class func firstWithAttribute(attribute: String, value: AnyObject, sortDescriptors: [NSSortDescriptor]? = nil, context: NSManagedObjectContext = AERecord.defaultContext) -> NSManagedObject? { let predicate = NSPredicate(format: "%K = %@", argumentArray: [attribute, value]) return firstWithPredicate(predicate, sortDescriptors: sortDescriptors, context: context) } public class func firstOrderedByAttribute(name: String, ascending: Bool = true, context: NSManagedObjectContext = AERecord.defaultContext) -> NSManagedObject? { let sortDescriptors = [NSSortDescriptor(key: name, ascending: ascending)] return first(sortDescriptors, context: context) } // MARK: Finding All public class func all(sortDescriptors: [NSSortDescriptor]? = nil, context: NSManagedObjectContext = AERecord.defaultContext) -> [NSManagedObject]? { let request = createFetchRequest(sortDescriptors: sortDescriptors) let objects = AERecord.executeFetchRequest(request, context: context) return objects.count > 0 ? objects : nil } public class func allWithPredicate(predicate: NSPredicate, sortDescriptors: [NSSortDescriptor]? = nil, context: NSManagedObjectContext = AERecord.defaultContext, limit:Int? = nil) -> [NSManagedObject]? { let request = createFetchRequest(predicate, sortDescriptors: sortDescriptors, limit: limit) let objects = AERecord.executeFetchRequest(request, context: context) return objects.count > 0 ? objects : nil } public class func allWithAttribute(attribute: String, value: AnyObject, sortDescriptors: [NSSortDescriptor]? = nil, context: NSManagedObjectContext = AERecord.defaultContext) -> [NSManagedObject]? { let predicate = NSPredicate(format: "%K = %@", argumentArray: [attribute, value]) return allWithPredicate(predicate, sortDescriptors: sortDescriptors, context: context) } // MARK: Count public class func count(context: NSManagedObjectContext = AERecord.defaultContext) -> Int { return countWithPredicate(context: context) } public class func countWithPredicate(predicate: NSPredicate? = nil, context: NSManagedObjectContext = AERecord.defaultContext) -> Int { let request = createFetchRequest(predicate) request.includesSubentities = false var error:NSError? let count = context.countForFetchRequest(request, error: &error) if (error != nil) { if kAERecordPrintLog { print(error) //print("Error occured in \(NSStringFromClass(self.dynamicType)) - function: \(__FUNCTION__) | line: \(__LINE__)\n\(error)") } } return count } public class func countWithAttribute(attribute: String, value: AnyObject, context: NSManagedObjectContext = AERecord.defaultContext) -> Int { let predicate = NSPredicate(format: "%K = %@", argumentArray: [attribute, value]) return countWithPredicate(predicate, context: context) } // MARK: Distinct public class func distinctValuesForAttribute(attribute: String, predicate: NSPredicate? = nil, sortDescriptors: [NSSortDescriptor]? = nil, context: NSManagedObjectContext = AERecord.defaultContext) -> [AnyObject]? { var distinctValues = [AnyObject]() if let distinctRecords = distinctRecordsForAttributes([attribute], predicate: predicate, sortDescriptors: sortDescriptors, context: context) { for record in distinctRecords { if let value: AnyObject = record[attribute] { distinctValues.append(value) } } } return distinctValues.count > 0 ? distinctValues : nil } public class func distinctRecordsForAttributes(attributes: [String], predicate: NSPredicate? = nil, sortDescriptors: [NSSortDescriptor]? = nil, context: NSManagedObjectContext = AERecord.defaultContext) -> [Dictionary<String, AnyObject>]? { let request = createFetchRequest(predicate, sortDescriptors: sortDescriptors) request.resultType = .DictionaryResultType request.returnsDistinctResults = true request.propertiesToFetch = attributes var distinctRecords: [Dictionary<String, AnyObject>]? do { if let distinctResult = try context.executeFetchRequest(request) as? [Dictionary<String, AnyObject>] { distinctRecords = distinctResult } } catch let error as NSError { if kAERecordPrintLog { print(error) //print("Error occured in \(NSStringFromClass(self.dynamicType)) - function: \(__FUNCTION__) | line: \(__LINE__)\n\(err)") } } catch _ { // FIXME: fatal error? } return distinctRecords } // MARK: Auto Increment public class func autoIncrementedIntegerAttribute(attribute: String, context: NSManagedObjectContext = AERecord.defaultContext) -> Int { let sortDescriptor = NSSortDescriptor(key: attribute, ascending: false) if let object = self.first([sortDescriptor], context: context) { if let max = object.valueForKey(attribute) as? Int { return max + 1 } else { return 0 } } else { return 0 } } // MARK: Turn Object Into Fault public func refresh(mergeChanges: Bool = true, context: NSManagedObjectContext = AERecord.defaultContext) { AERecord.refreshObjects([objectID], mergeChanges: mergeChanges, context: context) } // MARK: Batch Updating public class func batchUpdate(predicate: NSPredicate? = nil, properties: [NSObject : AnyObject]? = nil, resultType: NSBatchUpdateRequestResultType = .StatusOnlyResultType, context: NSManagedObjectContext = AERecord.defaultContext) -> NSBatchUpdateResult? { // create request let request = NSBatchUpdateRequest(entityName: entityName) // set request parameters request.predicate = predicate request.propertiesToUpdate = properties request.resultType = resultType // execute request var batchResult: NSBatchUpdateResult? = nil context.performBlockAndWait { () -> Void in do { if let result = try context.executeRequest(request) as? NSBatchUpdateResult { batchResult = result } } catch let error as NSError { if kAERecordPrintLog { print(error) // print("Error occured in \(NSStringFromClass(self.dynamicType)) - function: \(__FUNCTION__) | line: \(__LINE__)\n\(err)") } // } } catch _ { // FIXME: fatal? } } return batchResult } class func objectsCountForBatchUpdate(predicate: NSPredicate? = nil, properties: [NSObject : AnyObject]? = nil, context: NSManagedObjectContext = AERecord.defaultContext) -> Int { if let result = batchUpdate(predicate, properties: properties, resultType: .UpdatedObjectsCountResultType, context: context) { if let count = result.result as? Int { return count } else { return 0 } } else { return 0 } } class func batchUpdateAndRefreshObjects(predicate: NSPredicate? = nil, properties: [NSObject : AnyObject]? = nil, context: NSManagedObjectContext = AERecord.defaultContext) { if let result = batchUpdate(predicate, properties: properties, resultType: .UpdatedObjectIDsResultType, context: context) { if let objectIDS = result.result as? [NSManagedObjectID] { AERecord.refreshObjects(objectIDS, mergeChanges: true, context: context) } } } }
mit
acf9bd1e735019e7338d12e4b7350af8
43.183168
265
0.643348
5.741797
false
false
false
false
mihaicris/digi-cloud
Digi Cloud/Controller/Actions/ShareMountViewController.swift
1
23345
// // ShareMountViewController.swift // Digi Cloud // // Created by Mihai Cristescu on 02/03/2017. // Copyright © 2017 Mihai Cristescu. All rights reserved. // import UIKit final class ShareMountViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { // MARK: - Properties var onFinish: ((_ exitMount: Bool) -> Void)? private let location: Location var sharedNode: Node private var mappingProfileImages: [String: UIImage] = [:] private var users: [User] = [] private var isToolBarAlwaysHidden: Bool = false private var controllerShouldBeDismissed = false enum TableViewType: Int { case location = 0 case users } private lazy var tableViewForLocation: UITableView = { let tabelView = UITableView(frame: CGRect.zero, style: .grouped) tabelView.translatesAutoresizingMaskIntoConstraints = false tabelView.isUserInteractionEnabled = false tabelView.delegate = self tabelView.dataSource = self tabelView.rowHeight = AppSettings.textFieldRowHeight tabelView.tag = TableViewType.location.rawValue return tabelView }() private lazy var tableViewForUsers: UITableView = { let tableView = UITableView(frame: CGRect.zero, style: .plain) tableView.translatesAutoresizingMaskIntoConstraints = false tableView.alwaysBounceVertical = true tableView.delegate = self tableView.dataSource = self tableView.rowHeight = AppSettings.textFieldRowHeight tableView.tag = TableViewType.users.rawValue tableView.register(MountUserCell.self, forCellReuseIdentifier: String(describing: MountUserCell.self)) return tableView }() let usersLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.text = NSLocalizedString("MEMBERS", comment: "") label.font = UIFont(name: ".SFUIText", size: 12) ?? UIFont.fontHelveticaNeue(size: 12) label.textColor = UIColor(red: 0.43, green: 0.43, blue: 0.45, alpha: 1.0) return label }() private var errorMessageVerticalConstraint: NSLayoutConstraint? private lazy var waitingView: UIView = { let view = UIView() view.isHidden = false view.backgroundColor = .white view.translatesAutoresizingMaskIntoConstraints = false let spinner: UIActivityIndicatorView = { let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray) activityIndicator.translatesAutoresizingMaskIntoConstraints = false activityIndicator.hidesWhenStopped = true activityIndicator.tag = 55 activityIndicator.startAnimating() return activityIndicator }() let okButton: UIButton = { let button = UIButton(type: UIButtonType.system) button.translatesAutoresizingMaskIntoConstraints = false button.setTitle(NSLocalizedString("OK", comment: ""), for: UIControlState.normal) button.setTitleColor(.white, for: .normal) button.layer.cornerRadius = 10 button.contentEdgeInsets = UIEdgeInsets(top: 2, left: 40, bottom: 2, right: 40) button.sizeToFit() button.backgroundColor = UIColor(red: 0.7, green: 0.7, blue: 0.9, alpha: 1) button.tag = 11 button.isHidden = false button.addTarget(self, action: #selector(handleHideWaitingView), for: .touchUpInside) return button }() let label: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.textColor = .gray label.textAlignment = .center label.font = UIFont.systemFont(ofSize: 14) label.tag = 99 label.numberOfLines = 0 return label }() view.addSubview(spinner) view.addSubview(label) view.addSubview(okButton) self.errorMessageVerticalConstraint = label.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 40) NSLayoutConstraint.activate([ spinner.centerXAnchor.constraint(equalTo: view.centerXAnchor), spinner.centerYAnchor.constraint(equalTo: view.centerYAnchor), label.centerXAnchor.constraint(equalTo: view.centerXAnchor), label.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.8), self.errorMessageVerticalConstraint!, okButton.centerXAnchor.constraint(equalTo: view.centerXAnchor), okButton.topAnchor.constraint(equalTo: label.bottomAnchor, constant: 40) ]) return view }() // MARK: - Initializers and Deinitializers init(location: Location, sharedNode: Node, onFinish: @escaping (Bool) -> Void) { self.location = location self.sharedNode = sharedNode self.onFinish = onFinish super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Overridden Methods and Properties override func viewDidLoad() { super.viewDidLoad() setupViews() setupNavigationItems() setupToolBarItems() configureWaitingView(type: .started, message: NSLocalizedString("Please wait...", comment: "")) if let mount = sharedNode.mount { if mount.root == nil && sharedNode.mountPath != "/" { createMount() } else { refreshMount() } } else { createMount() } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.isToolbarHidden = false } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { var headerTitle: String? guard let type = TableViewType(rawValue: tableView.tag) else { return headerTitle } switch type { case .location: headerTitle = NSLocalizedString("LOCATION", comment: "") case .users: break } return headerTitle } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { guard let type = TableViewType(rawValue: tableView.tag) else { return 0 } switch type { case .location: return 35 case .users: return 0.01 } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let type = TableViewType(rawValue: tableView.tag) else { return 0 } switch type { case .location: return 1 case .users: return users.count } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let type = TableViewType(rawValue: tableView.tag) else { return UITableViewCell() } switch type { case .location: let cell = UITableViewCell() cell.isUserInteractionEnabled = false cell.selectionStyle = .none let mountNameLabel: UILabelWithPadding = { let label = UILabelWithPadding(paddingTop: 1, paddingLeft: 5, paddingBottom: 2, paddingRight: 5) label.font = UIFont.fontHelveticaNeue(size: 12) label.adjustsFontSizeToFitWidth = true label.textColor = .darkGray label.backgroundColor = UIColor(red: 240/255, green: 240/255, blue: 240/255, alpha: 1.0) label.text = location.mount.name label.layer.cornerRadius = 4 label.clipsToBounds = true label.translatesAutoresizingMaskIntoConstraints = false return label }() let locationPathLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.textColor = .darkGray label.text = String(location.path.dropLast()) label.numberOfLines = 2 label.font = UIFont.fontHelveticaNeue(size: 12) label.lineBreakMode = .byTruncatingMiddle return label }() cell.contentView.addSubview(mountNameLabel) cell.contentView.addSubview(locationPathLabel) NSLayoutConstraint.activate([ locationPathLabel.leftAnchor.constraint(equalTo: mountNameLabel.rightAnchor, constant: 2), locationPathLabel.rightAnchor.constraint(lessThanOrEqualTo: cell.contentView.layoutMarginsGuide.rightAnchor), locationPathLabel.centerYAnchor.constraint(equalTo: cell.contentView.centerYAnchor), mountNameLabel.leftAnchor.constraint(equalTo: cell.contentView.layoutMarginsGuide.leftAnchor), mountNameLabel.centerYAnchor.constraint(equalTo: cell.contentView.centerYAnchor) ]) return cell case .users: guard let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: MountUserCell.self), for: indexPath) as? MountUserCell else { return UITableViewCell() } let user = users[indexPath.row] cell.selectionStyle = .none if let owner = sharedNode.mount?.owner { if owner == user { cell.isUserInteractionEnabled = false cell.isOwner = true } else { if user.permissions.mount { cell.accessoryType = .disclosureIndicator } } } cell.user = user if let image = mappingProfileImages[users[indexPath.row].identifier] { cell.profileImageView.image = image } else { cell.profileImageView.image = #imageLiteral(resourceName: "account_icon") } return cell } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: false) guard let mount = sharedNode.mount else { print("No valid mount in node for editing.") return } let user = users[indexPath.row] // Only owner can change permissions or user has mount management permission. guard mount.permissions.owner || user.permissions.mount else { return } let controller = AddMountUserViewController(mount: mount, user: user) controller.onUpdatedUser = { [weak self] in self?.refreshMount() _ = self?.navigationController?.popViewController(animated: true) } navigationController?.pushViewController(controller, animated: true) } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { removeUser(at: indexPath) } } func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle { let user = users[indexPath.row] if user.permissions.owner { return .none } else { return .delete } } // MARK: - Helper Functions private func setupViews() { let headerView: UIImageView = { let imageView = UIImageView(frame: CGRect.zero) imageView.translatesAutoresizingMaskIntoConstraints = false imageView.image = #imageLiteral(resourceName: "share_digi_background") imageView.contentMode = .scaleAspectFill return imageView }() view.addSubview(headerView) view.addSubview(tableViewForLocation) view.addSubview(tableViewForUsers) view.addSubview(usersLabel) view.addSubview(waitingView) NSLayoutConstraint.activate([ waitingView.topAnchor.constraint(equalTo: view.topAnchor), waitingView.bottomAnchor.constraint(equalTo: view.bottomAnchor), waitingView.leftAnchor.constraint(equalTo: view.leftAnchor), waitingView.rightAnchor.constraint(equalTo: view.rightAnchor), headerView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), headerView.leftAnchor.constraint(equalTo: view.leftAnchor), headerView.rightAnchor.constraint(equalTo: view.rightAnchor), tableViewForLocation.topAnchor.constraint(equalTo: headerView.bottomAnchor), tableViewForLocation.heightAnchor.constraint(equalToConstant: 115), tableViewForLocation.leftAnchor.constraint(equalTo: view.leftAnchor), tableViewForLocation.rightAnchor.constraint(equalTo: view.rightAnchor), usersLabel.bottomAnchor.constraint(equalTo: tableViewForLocation.bottomAnchor, constant: -10), usersLabel.leftAnchor.constraint(equalTo: tableViewForLocation.layoutMarginsGuide.leftAnchor), tableViewForUsers.topAnchor.constraint(equalTo: tableViewForLocation.bottomAnchor), tableViewForUsers.bottomAnchor.constraint(equalTo: view.bottomAnchor), tableViewForUsers.leftAnchor.constraint(equalTo: view.leftAnchor), tableViewForUsers.rightAnchor.constraint(equalTo: view.rightAnchor) ]) } private func setupNavigationItems() { title = NSLocalizedString("Members", comment: "") navigationController?.navigationBar.topItem?.backBarButtonItem = UIBarButtonItem(title: NSLocalizedString("Back", comment: ""), style: .done, target: nil, action: nil) let doneButton = UIBarButtonItem(title: NSLocalizedString("Done", comment: ""), style: .done, target: self, action: #selector(handleDone)) navigationItem.setRightBarButton(doneButton, animated: false) } private func setupToolBarItems() { var toolBarItems: [UIBarButtonItem] = [] let flexibleButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil) let addUserButton: UIBarButtonItem = { let buttonView = UIButton(type: UIButtonType.system) buttonView.setTitle(NSLocalizedString("Add member", comment: ""), for: .normal) buttonView.addTarget(self, action: #selector(showAddUserView), for: .touchUpInside) buttonView.setTitleColor(UIColor(white: 0.8, alpha: 1), for: .disabled) buttonView.setTitleColor(UIColor.defaultColor, for: .normal) buttonView.titleLabel?.font = UIFont.systemFont(ofSize: 18) buttonView.sizeToFit() let button = UIBarButtonItem(customView: buttonView) return button }() let removeShareButton: UIBarButtonItem = { let buttonView = UIButton(type: UIButtonType.system) buttonView.setTitle(NSLocalizedString("Remove Share", comment: ""), for: .normal) buttonView.addTarget(self, action: #selector(handleRemoveMount), for: .touchUpInside) buttonView.setTitleColor(UIColor(white: 0.8, alpha: 1), for: .disabled) buttonView.setTitleColor(.red, for: .normal) buttonView.titleLabel?.font = UIFont.systemFont(ofSize: 18) buttonView.sizeToFit() let button = UIBarButtonItem(customView: buttonView) return button }() if let mount = sharedNode.mount { // if no management mount permission, then hide alwais the toolbar which // can contains remove share and / or add member buttons. if !mount.permissions.mount { isToolBarAlwaysHidden = true return } if mount.type == "import" || (mount.type == "device" && sharedNode.mountPath == "/") { toolBarItems.append(contentsOf: [flexibleButton, addUserButton]) } else { toolBarItems.append(contentsOf: [removeShareButton, flexibleButton, addUserButton]) } } else { toolBarItems.append(contentsOf: [removeShareButton, flexibleButton, addUserButton]) } setToolbarItems(toolBarItems, animated: false) } private func configureWaitingView(type: WaitingType, message: String) { switch type { case .hidden: waitingView.isHidden = true navigationController?.isToolbarHidden = isToolBarAlwaysHidden case .started, .stopped: waitingView.isHidden = false navigationController?.isToolbarHidden = true if let activityIndicator = waitingView.viewWithTag(55) as? UIActivityIndicatorView, let button = waitingView.viewWithTag(11) as? UIButton { if type == .started { activityIndicator.startAnimating() errorMessageVerticalConstraint?.constant = 40 button.isHidden = true } else { activityIndicator.stopAnimating() button.isHidden = false errorMessageVerticalConstraint?.constant = 0 } } if let label = waitingView.viewWithTag(99) as? UILabel { label.text = message } } } private func createMount() { DigiClient.shared.createSubmount(at: self.location, withName: sharedNode.name) { mount, error in guard error == nil else { let errorMessage = NSLocalizedString("There was an error at share creation.", comment: "") self.configureWaitingView(type: .stopped, message: errorMessage) return } if let mount = mount { self.processMount(mount) } } } private func refreshMount() { controllerShouldBeDismissed = false guard let mount = sharedNode.mount else { return } DigiClient.shared.getMountDetails(for: mount) { mount, error in guard error == nil else { self.controllerShouldBeDismissed = true let errorMessage = NSLocalizedString("There was an error at requesting share information.", comment: "") self.configureWaitingView(type: .stopped, message: errorMessage) return } if let mount = mount { self.processMount(mount) } } } private func processMount(_ mount: Mount) { self.sharedNode.mount = mount self.setupToolBarItems() self.getUserProfileImages(for: mount.users) } private func getUserProfileImages(for someUsers: [User]) { let dispatchGroup = DispatchGroup() for user in someUsers { // if profile image already available, skip network request if mappingProfileImages[user.identifier] != nil { continue } dispatchGroup.enter() DigiClient.shared.getUserProfileImage(for: user) { image, error in dispatchGroup.leave() guard error == nil else { return } if let image = image { self.mappingProfileImages[user.identifier] = image } } } dispatchGroup.notify(queue: .main) { self.updateUsersModel(someUsers) self.tableViewForUsers.reloadData() self.configureWaitingView(type: .hidden, message: "") } } private func updateUsersModel(_ someUsers: [User]) { // if the user already exists in the users array replace it (maybe it has new permissions) // otherwise add it to the array for user in someUsers { if let index = users.index(of: user) { users[index] = user } else { users.append(user) } } } private func removeUser(at indexPath: IndexPath) { guard let mount = sharedNode.mount else { print("No valid mount for user addition.") return } let user = users[indexPath.row] DigiClient.shared.updateMount(mount: mount, operation: .remove, user: user) { _, error in guard error == nil else { self.configureWaitingView(type: .stopped, message: "There was an error while removing the member.") self.tableViewForUsers.isEditing = false return } self.users.remove(at: indexPath.row) // Remove from tableView self.tableViewForUsers.deleteRows(at: [indexPath], with: .automatic) // if the user is not owner and it is the last user, it means user has left the share. if DigiClient.shared.loggedAccount.userID == user.identifier { self.dismiss(animated: true) { self.onFinish?(true) } } } } @objc private func showAddUserView() { guard let mount = sharedNode.mount else { print("No valid mount for user addition.") return } let controller = AddMountUserViewController(mount: mount) controller.onUpdatedUser = { [weak self] in self?.refreshMount() _ = self?.navigationController?.popViewController(animated: true) } navigationController?.pushViewController(controller, animated: true) } @objc private func handleRemoveMount() { guard let mount = sharedNode.mount else { print("No valid mount in node for deletion.") return } configureWaitingView(type: .started, message: NSLocalizedString("Removing share...", comment: "")) DigiClient.shared.deleteMount(mount) { error in guard error == nil else { self.configureWaitingView(type: .stopped, message: NSLocalizedString("There was an error while removing the share.", comment: "")) return } self.dismiss(animated: true) { if self.sharedNode.mountPath == "/" && self.sharedNode.mount?.type == "export" && self.sharedNode.name == "" { self.onFinish?(true) } else { self.onFinish?(false) } } } } @objc func handleHideWaitingView(_ sender: UIButton) { if controllerShouldBeDismissed { dismiss(animated: true, completion: nil) } else { self.configureWaitingView(type: .hidden, message: "") } } @objc private func handleDone() { dismiss(animated: true) { self.onFinish?(false) } } }
mit
e0f543bcba761a81ff0ad6c376a197ce
33.946108
175
0.609407
5.416241
false
false
false
false
sviatoslav/EndpointProcedure
Sources/Core/DataFlowProcedureBuilder.swift
1
4407
// // DataFlowProcedureBuilder.swift // EndpointProcedure // // Created by Sviatoslav Yakymiv on 2/23/19. // import Foundation #if canImport(ProcedureKit) import ProcedureKit #endif public struct DataFlowProcedureBuilder: ValidationProcedureBuilding { private let loading: Loading private var validation = AnyValidationProcedureFactory.empty.validationProcedure() private var deserialization = AnyDataDeserializationProcedureFactory.empty.dataDeserializationProcedure() private var interception = AnyInterceptionProcedureFactory.empty.interceptionProcedure() private init(loading: Loading) { self.loading = loading } public static func load<T: Procedure>(using procedure: T) -> DeserializationProcedureBuilding where T: OutputProcedure, T.Output == Data { return DataFlowProcedureBuilder(loading: .data(AnyOutputProcedure(procedure))) } public static func load<T: Procedure>(using procedure: T) -> ValidationProcedureBuilding where T: OutputProcedure, T.Output == HTTPResponseData { return DataFlowProcedureBuilder(loading: .httpData(AnyOutputProcedure(procedure))) } public func validate<T: Procedure>(using procedure: T) -> DeserializationProcedureBuilding where T: InputProcedure, T.Input == HTTPResponseData { return self.mutate(using: { $0.validation = AnyInputProcedure(procedure) }) } public func deserialize<T: Procedure>(using procedure: T) -> InterceptionProcedureBuilding where T: InputProcedure & OutputProcedure, T.Input == Data, T.Output == Any { return self.mutate(using: { $0.deserialization = AnyProcedure(procedure) }) } public func intercept<T: Procedure>(using procedure: T) -> MappingProcedureBuilding where T: InputProcedure & OutputProcedure, T.Input == Any, T.Output == Any { return self.mutate(using: { $0.interception = AnyProcedure(procedure) }) } public func map<T: Procedure>(using procedure: T) -> DataFlowProcedure<T.Output> where T: InputProcedure & OutputProcedure, T.Input == Any { switch self.loading { case .data(let loading): return DataFlowProcedure(dataLoadingProcedure: loading, deserializationProcedure: self.deserialization, interceptionProcedure: self.interception, resultMappingProcedure: procedure) case .httpData(let loading): return HTTPDataFlowProcedure(dataLoadingProcedure: loading, validationProcedure: self.validation, deserializationProcedure: self.deserialization, interceptionProcedure: self.interception, resultMappingProcedure: procedure) } } private func mutate(using mutator: (inout DataFlowProcedureBuilder) -> Void) -> DataFlowProcedureBuilder { var mutable = self mutator(&mutable) return mutable } } public protocol ValidationProcedureBuilding: DeserializationProcedureBuilding { func validate<T: Procedure>(using procedure: T) -> DeserializationProcedureBuilding where T: InputProcedure, T.Input == HTTPResponseData } public protocol DeserializationProcedureBuilding: InterceptionProcedureBuilding { func deserialize<T: Procedure>(using procedure: T) -> InterceptionProcedureBuilding where T: InputProcedure & OutputProcedure, T.Input == Data, T.Output == Any } public protocol InterceptionProcedureBuilding: MappingProcedureBuilding { func intercept<T: Procedure>(using procedure: T) -> MappingProcedureBuilding where T: InputProcedure & OutputProcedure, T.Input == Any, T.Output == Any } public protocol MappingProcedureBuilding { func map<T: Procedure>(using procedure: T) -> DataFlowProcedure<T.Output> where T: InputProcedure & OutputProcedure, T.Input == Any } extension DataFlowProcedureBuilder { fileprivate enum Loading { case data(AnyOutputProcedure<Data>) case httpData(AnyOutputProcedure<HTTPResponseData>) } }
mit
52686c517cf975771c6eee3b816744e0
47.428571
117
0.659859
5.628352
false
false
false
false
FsThatOne/OneSunChat
OneSunChat/OneSunChat/Util/PublicDefine.swift
1
1254
// // PublicDefine.swift // OneSunChat // // Created by 刘ToTo on 16/2/24. // Copyright © 2016年 刘ToTo. All rights reserved. // import UIKit // MARK: - App let App_Name = Bundle.main.infoDictionary?["CFBundleDisplayName"] ?? "" let App_Version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] ?? "" // MARK: - Screen /// 屏幕宽度 let kScreenWidth = UIScreen.main.bounds.size.width /// 屏幕高度 let kScreenHieght = UIScreen.main.bounds.size.height /// 屏幕大小 let kScreenBounds = UIScreen.main.bounds // MARK: - Color /// 三原色_alpha func RGB_A (r:CGFloat, g:CGFloat, b:CGFloat, a:CGFloat) ->UIColor { return UIColor (red: r/255.0, green: g/255.0, blue: b/255.0, alpha: a) } /// 三原色 func RGB (r:CGFloat, g:CGFloat, b:CGFloat) ->UIColor { return UIColor (red: r/255.0, green: g/255.0, blue: b/255.0, alpha: 1.0) } /// tab绿 let kTitleColor = RGB(r: 26,g: 178,b: 10) /// bar背景色 let kBarTintColor = UIColor(white: 10.0/255.0, alpha: 1.0) /// 黑色北京 let kBackGroundColor = UIColor(white: 30.0/255.0, alpha: 1.0) /// 微灰色背景 let kLightBackGroundColor = UIColor(white: 0.9, alpha: 1.0) let kWhiteColor = UIColor.white let kBlackColor = UIColor.black let kGreenColor = UIColor.green
mit
8012ab10d1467cc63da8617358b31614
25.333333
81
0.68692
2.862319
false
false
false
false
davidlivadaru/DLSuggestionsTextField
DLSuggestionsTextFieldDemo/DLSuggestionsTextFieldDemo/ViewController.swift
1
5625
// // ViewController.swift // DLSuggestionsTextFieldDemo // // Created by David Livadaru on 08/07/16. // Copyright © 2016 Community. All rights reserved. // import UIKit import DLSuggestionsTextField fileprivate extension Dictionary { typealias TransformClosure<NewKey, NewValue> = ((key: Key, value: Value)) -> (key: NewKey, value: NewValue) func map<NewKey, NewValue>(_ transform: TransformClosure<NewKey, NewValue>) -> [NewKey: NewValue] { var newDictionary: [NewKey: NewValue] = [:] for key in keys { if let value = self[key] { let mappedPair = transform((key, value)) newDictionary[mappedPair.key] = mappedPair.value } } return newDictionary } } class ViewController: UIViewController, PhonesSuggestionsHandlerObserver { @IBOutlet weak var suggestionsTextField: TextField! private let suggestionsHandler = PhonesSuggestionsHandler() private let suggestionsTableView = TableView() private let suggestionsLabel = UILabel() private var placeholderAttributes: [NSAttributedStringKey : Any] = [:] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. suggestionsHandler.observer = self view.addSubview(suggestionsTableView) suggestionsTableView.dataSource = suggestionsHandler suggestionsTableView.delegate = self suggestionsTableView.tableFooterView = UIView() placeholderAttributes[NSAttributedStringKey.font] = UIFont(name: "Arial", size: 14) placeholderAttributes[NSAttributedStringKey.foregroundColor] = UIColor.lightGray var textAttributes = placeholderAttributes textAttributes[NSAttributedStringKey.foregroundColor] = UIColor.darkText suggestionsTextField.defaultTextAttributes = textAttributes.map({ (key: $0.key.rawValue, value: $0.value) }) suggestionsTextField.attributedPlaceholder = NSAttributedString(string: "Search for a phone", attributes: placeholderAttributes) suggestionsTextField.suggestionTextSpacing = -3 suggestionsTextField.suggestionLabel = suggestionsLabel suggestionsTextField.suggestionsContentView = suggestionsTableView suggestionsHandler.filterPhonesWithText(from: suggestionsTextField) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) var tableViewFrame = CGRect.zero tableViewFrame.origin.x = suggestionsTextField.frame.minX tableViewFrame.origin.y = suggestionsTextField.frame.maxY tableViewFrame.size.width = suggestionsTextField.frame.width tableViewFrame.size.height = view.bounds.height - suggestionsTextField.frame.maxY suggestionsTableView.frame = tableViewFrame tableViewFrame.size.height = 0 suggestionsTableView.frame = tableViewFrame } @IBAction func controllerViewTapped(_ sender: UITapGestureRecognizer) { if sender.state == .recognized { view.endEditing(true) } } // MARK: PhonesSuggestionsHandlerObserver func handlerDidUpdatePhones(handler: PhonesSuggestionsHandler) { updateSuggestionLabel() suggestionsTableView.reloadData() } private func updateSuggestionLabel() { var suggestionText = "" if let phone = self.suggestionsHandler.phones.first, let text = self.suggestionsTextField.text, text.count > 0, phone.name.hasPrefix(text) { let substringIndex = phone.name.characters.index(phone.name.startIndex, offsetBy: text.characters.count) suggestionText = String(phone.name[substringIndex..<phone.name.endIndex]) } self.suggestionsLabel.attributedText = NSAttributedString(string: suggestionText, attributes: self.placeholderAttributes) } // MARK: Private fileprivate func selectPhone(atIndex index: Int) { guard index < suggestionsHandler.phones.count else { return } let phone = suggestionsHandler.phones[index] suggestionsTextField.text = phone.name } } extension ViewController : UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) selectPhone(atIndex: indexPath.row) suggestionsTextField.resignFirstResponder() } } extension ViewController : UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() if let text = textField.text, text.count > 0 { selectPhone(atIndex: 0) } return false } func textFieldDidEndEditing(_ textField: UITextField) { if let text = textField.text, text.count > 0 { selectPhone(atIndex: 0) } } } class TableView: UITableView { override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { let isPointInside = super.point(inside: point, with: event) if isPointInside { for cell in visibleCells where cell.frame.contains(point) { return true } } return false } }
mit
48950bc56e026434357b8c5903e68dce
37.258503
116
0.65096
5.423337
false
false
false
false
ReiVerdugo/uikit-fundamentals
step5.7-makeYourOwnAdventure-incomplete/MYOA/StoryNode.swift
1
1654
// // StoryNode.swift // MYOA // // Copyright (c) 2015 Udacity. All rights reserved. // import Foundation // MARK: - StoryNode struct StoryNode { // MARK: Properites var message: String private var adventure: Adventure private var connections: [Connection] var imageName: String? { return adventure.credits.imageName } // MARK: Initializer init(dictionary: [String : AnyObject], adventure: Adventure) { self.adventure = adventure message = dictionary["message"] as! String connections = [Connection]() message = message.stringByReplacingOccurrencesOfString("\\n", withString: "\n\n") if let connectionsArray = dictionary["connections"] as? [[String : String]] { for connectionDictionary: [String : String] in connectionsArray { connections.append(Connection(dictionary: connectionDictionary)) } } } // MARK: Prompts // The number of prompts for story choices func promptCount() -> Int { return connections.count } // The prompt string, these will be something like: "Open the door, and look inside" func promptForIndex(index: Int) -> String { return connections[index].prompt } // MARK: Story Nodes // The Story node that corresponds to the prompt with the same index. func storyNodeForIndex(index: Int) -> StoryNode { let storyNodeName = connections[index].connectedStoryNodeName let storyNode = adventure.storyNodes[storyNodeName] return storyNode! } }
mit
1ce05e8acf6fa6e16b4fac05b47d390b
26.114754
89
0.622733
4.822157
false
false
false
false
mxcl/PromiseKit
Tests/CorePromise/ZalgoTests.swift
1
1552
import XCTest import PromiseKit class ZalgoTests: XCTestCase { func test1() { var resolved = false Promise.value(1).done(on: nil) { _ in resolved = true }.silenceWarning() XCTAssertTrue(resolved) } func test2() { let p1 = Promise.value(1).map(on: nil) { x in return 2 } XCTAssertEqual(p1.value!, 2) var x = 0 let (p2, seal) = Promise<Int>.pending() p2.done(on: nil) { _ in x = 1 }.silenceWarning() XCTAssertEqual(x, 0) seal.fulfill(1) XCTAssertEqual(x, 1) } // returning a pending promise from its own zalgo’d then handler doesn’t hang func test3() { let ex = (expectation(description: ""), expectation(description: "")) var p1: Promise<Void>! p1 = after(.milliseconds(100)).then(on: nil) { _ -> Promise<Void> in ex.0.fulfill() return p1 } p1.catch { err in defer{ ex.1.fulfill() } guard case PMKError.returnedSelf = err else { return XCTFail() } } waitForExpectations(timeout: 1) } // return a sealed promise from its own zalgo’d then handler doesn’t hang func test4() { let ex = expectation(description: "") let p1 = Promise.value(1) p1.then(on: nil) { _ -> Promise<Int> in ex.fulfill() return p1 }.silenceWarning() waitForExpectations(timeout: 1) } }
mit
7d52b4e081e024b37c43fc2911dcd9a9
25.169492
81
0.525907
4.041885
false
true
false
false
aleph7/Upsurge
Sources/Upsurge/Exponential.swift
3
5717
// Copyright (c) 2014–2015 Mattt Thompson (http://mattt.me) // // 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 Accelerate // MARK: - Double /// Exponentiation public func exp<M: LinearType>(_ x: M) -> ValueArray<Double> where M.Element == Double { precondition(x.step == 1, "exp doesn't support step values other than 1") let results = ValueArray<Double>(count: x.count) withPointer(x) { xp in vvexp(results.mutablePointer, xp + x.startIndex, [Int32(x.count)]) } return results } /// Square Exponentiation public func exp2<M: LinearType>(_ x: M) -> ValueArray<Double> where M.Element == Double { precondition(x.step == 1, "exp2 doesn't support step values other than 1") let results = ValueArray<Double>(count: x.count) withPointer(x) { xp in vvexp2(results.mutablePointer, xp + x.startIndex, [Int32(x.count)]) } return results } /// Natural Logarithm public func log<M: LinearType>(_ x: M) -> ValueArray<Double> where M.Element == Double { precondition(x.step == 1, "log doesn't support step values other than 1") let results = ValueArray<Double>(count: x.count) withPointer(x) { xp in vvlog(results.mutablePointer, xp + x.startIndex, [Int32(x.count)]) } return results } /// Base-2 Logarithm public func log2<M: LinearType>(_ x: M) -> ValueArray<Double> where M.Element == Double { precondition(x.step == 1, "log2 doesn't support step values other than 1") let results = ValueArray<Double>(count: x.count) withPointer(x) { xp in vvlog2(results.mutablePointer, xp + x.startIndex, [Int32(x.count)]) } return results } /// Base-10 Logarithm public func log10<M: LinearType>(_ x: M) -> ValueArray<Double> where M.Element == Double { precondition(x.step == 1, "log10 doesn't support step values other than 1") let results = ValueArray<Double>(count: x.count) withPointer(x) { xp in vvlog10(results.mutablePointer, xp + x.startIndex, [Int32(x.count)]) } return results } /// Logarithmic Exponentiation public func logb<M: LinearType>(_ x: M) -> ValueArray<Double> where M.Element == Double { precondition(x.step == 1, "logb doesn't support step values other than 1") let results = ValueArray<Double>(count: x.count) withPointer(x) { xp in vvlogb(results.mutablePointer, xp + x.startIndex, [Int32(x.count)]) } return results } // MARK: - Float /// Exponentiation public func exp<M: LinearType>(_ x: M) -> ValueArray<Float> where M.Element == Float { precondition(x.step == 1, "exp doesn't support step values other than 1") let results = ValueArray<Float>(count: x.count) withPointer(x) { xp in vvexpf(results.mutablePointer, xp + x.startIndex, [Int32(x.count)]) } return results } /// Square Exponentiation public func exp2<M: LinearType>(_ x: M) -> ValueArray<Float> where M.Element == Float { precondition(x.step == 1, "exp2 doesn't support step values other than 1") let results = ValueArray<Float>(count: x.count) withPointer(x) { xp in vvexp2f(results.mutablePointer, xp + x.startIndex, [Int32(x.count)]) } return results } /// Natural Logarithm public func log<M: LinearType>(_ x: M) -> ValueArray<Float> where M.Element == Float { precondition(x.step == 1, "log doesn't support step values other than 1") let results = ValueArray<Float>(count: x.count) withPointer(x) { xp in vvlogf(results.mutablePointer, xp + x.startIndex, [Int32(x.count)]) } return results } /// Base-2 Logarithm public func log2<M: LinearType>(_ x: M) -> ValueArray<Float> where M.Element == Float { precondition(x.step == 1, "log2 doesn't support step values other than 1") let results = ValueArray<Float>(count: x.count) withPointer(x) { xp in vvlog2f(results.mutablePointer, xp + x.startIndex, [Int32(x.count)]) } return results } /// Base-10 Logarithm public func log10<M: LinearType>(_ x: M) -> ValueArray<Float> where M.Element == Float { precondition(x.step == 1, "log10 doesn't support step values other than 1") let results = ValueArray<Float>(count: x.count) withPointer(x) { xp in vvlog10f(results.mutablePointer, xp + x.startIndex, [Int32(x.count)]) } return results } /// Logarithmic Exponentiation public func logb<M: LinearType>(_ x: M) -> ValueArray<Float> where M.Element == Float { precondition(x.step == 1, "logb doesn't support step values other than 1") let results = ValueArray<Float>(count: x.count) withPointer(x) { xp in vvlogbf(results.mutablePointer, xp + x.startIndex, [Int32(x.count)]) } return results }
mit
28f29dfa42ff004cf37ac99d266a544f
32.816568
90
0.68259
3.640127
false
false
false
false
mitochrome/complex-gestures-demo
apps/GestureRecognizer/Carthage/Checkouts/RxSwift/Tests/RxSwiftTests/TestImplementations/Mocks/TestConnectableObservable.swift
15
642
// // TestConnectableObservable.swift // Tests // // Created by Krunoslav Zaher on 4/19/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import RxSwift final class TestConnectableObservable<S: SubjectType> : ConnectableObservableType where S.E == S.SubjectObserverType.E { typealias E = S.E let _o: ConnectableObservable<S.E> init(o: Observable<S.E>, s: S) { _o = o.multicast(s) } func connect() -> Disposable { return _o.connect() } func subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == E { return _o.subscribe(observer) } }
mit
99447ce1b7a948a80df6b97695591cc7
22.740741
120
0.630265
3.815476
false
true
false
false
jakub-tucek/fit-checker-2.0
fit-checker/networking/NetworkController.swift
1
4078
// // NetworkController.swift // fit-checker // // Created by Josef Dolezal on 13/01/2017. // Copyright © 2017 Josef Dolezal. All rights reserved. // import Foundation import Alamofire /// Represents networking layer, handles all remote requests. /// As Edux credentials are stored in cookies, you have to /// recycle (inject) instance to keep request authorized after login. class NetworkController { typealias Completion = (Void) -> () /// Network session manager, keeps cookies and shit private let sessionManager: SessionManager = { let configuration = URLSessionConfiguration.default return SessionManager(configuration: configuration) }() /// Network requests queue private let queue = OperationQueue() /// Database context manager private let contextManager: ContextManager init(contextManager: ContextManager) { self.contextManager = contextManager // This is safe because network controller is // weak property, so no reference cycle should occure let retrier = EduxRetrier(networkController: self) sessionManager.retrier = retrier } /// Allows to authorize user to Edux with username and password /// /// - Parameters: /// - username: User's faculty username /// - password: Password /// - Returns: User login promise @discardableResult func authorizeUser(with username: String, password: String) -> OperationPromise<Void> { let promise = OperationPromise<Void>() let loginOperation = EduxLoginOperation(username: username, password: password, sessionManager: sessionManager) loginOperation.promise = promise queue.addOperation(loginOperation) return promise } /// Loads latest classification results for given course /// /// - Parameters: /// - courseId: ID (name) of the course /// - student: Student username func loadCourseClassification(courseId: String, student: String) { let courseOperation = ReadCourseClassificationOperation(courseId: courseId, student: student, sessionManager: sessionManager, contextManager: contextManager) queue.addOperation(courseOperation) } /// Loads latest classification for all given courses, /// ideal for background refresh or initial app load /// /// - Parameters: /// - courses: Set of courses to be downloaded /// - student: Student username /// - Returns: Courses classification promise func loadCoursesClasification(courses: [Course], student: String) -> OperationPromise<Void>{ let operations = courses.map { course in return ReadCourseClassificationOperation(courseId: course.id, student: student, sessionManager: sessionManager, contextManager: contextManager) } let promise = OperationPromise<Void>() let completion = BlockOperation { // Check if all operations finished successfully let success = operations.reduce(true) { $0 && $1.error == nil } success ? promise.success() : promise.failure() } // Wait with completion until all operations are finished operations.forEach { completion.addDependency($0) } queue.addOperations(operations, waitUntilFinished: false) queue.addOperation(completion) return promise } /// Load current course list /// /// - Parameter completion: Completion callback func loadCourseList(completion: Completion? = nil) { let coursesList = ReadCourseListOperation( sessionManager: sessionManager, contextManager: contextManager) let completionOperation = BlockOperation() { completion?() } completionOperation.addDependency(coursesList) queue.addOperations([coursesList, completionOperation], waitUntilFinished: false) } }
mit
c1288930924a4645e39983bfc22e4aa9
32.146341
77
0.655139
5.487214
false
false
false
false
ProfileCreator/ProfileCreator
ProfileCreator/ProfileCreator/Profile Editor OutlineView/PropertyListEditor Source/Formatters/PropertyListDataFormatter.swift
1
5300
// swiftlint:disable:next file_header // PropertyListDataFormatter.swift // PropertyListEditor // // Created by Prachi Gauriar on 7/9/2015. // Copyright © 2015 Quantum Lens Cap. 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 /// `PropertyListDataFormatter` instances read/write `Data` instances in a way that looks like /// `Data`’s `description` method. class PropertyListDataFormatter: Formatter { /// Returns a `Data` instance by parsing the specified string. /// - parameter string: The string to parse. /// - returns: The `NSData` instance that was parsed or `nil` if parsing failed. func data(from string: String) -> Data? { var data: AnyObject? return getObjectValue(&data, for: string, errorDescription: nil) ? data as? Data : nil } override func string(for obj: Any?) -> String? { if let data = obj as? Data { return data.description } else { return nil } } override func getObjectValue(_ obj: AutoreleasingUnsafeMutablePointer<AnyObject?>?, for string: String, errorDescription error: AutoreleasingUnsafeMutablePointer<NSString?>?) -> Bool { // can use to iterate over each character var characterIterator = string.replacingOccurrences(of: " ", with: "").makeIterator() // If the string didn’t start with a <, it’s invalid guard let firstCharacter = characterIterator.next(), firstCharacter == "<" else { return false } // Otherwise, build up our data by continuously appending bytes until we reach a > var byteBuffer: [UInt8] = [] repeat { // Read the first character. If there wasn’t one, return false guard let char1 = characterIterator.next() else { return false } // If the first character was a >, we’re done parsing, so break out of the loop if char1 == ">" { break } // Otherwise, assume we got a hex character. Read a second hex character to form // a byte. If we can’t create a valid byte from the two hex characters, the string // was invalid, so we should return false guard let char2 = characterIterator.next(), let byte = UInt8("\(char1)\(char2)", radix: 16) else { return false } // Otherwise, everything went fine, so add our byte to our data object byteBuffer.append(byte) } while true obj?.pointee = Data(bytes: &byteBuffer, count: byteBuffer.count) as NSData return true } override func isPartialStringValid(_ partialStringPtr: AutoreleasingUnsafeMutablePointer<NSString>, proposedSelectedRange proposedSelRangePtr: NSRangePointer?, originalString origString: String, originalSelectedRange origSelRange: NSRange, errorDescription error: AutoreleasingUnsafeMutablePointer<NSString?>?) -> Bool { let partialString = partialStringPtr.pointee as String let scanner = Scanner(string: partialString) scanner.charactersToBeSkipped = CharacterSet(charactersIn: " ") if scanner.isAtEnd { // The string is empty return true } else if !scanner.scanString("<", into: nil) { // The string does not begin with a "<" return false } let hexadecimalDigitCharacterSet = CharacterSet(charactersIn: "0123456789abcdefABCDEF") // Scan hex digits until there are none left or we hit a ">". This is structured as a // repeat-while instead of a while so that we can handle the empty string case "<" and // "<>" in a single code path repeat { // If we hit a >, we’re done with our loop if scanner.scanString(">", into: nil) { break } } while scanner.scanCharacters(from: hexadecimalDigitCharacterSet, into: nil) return scanner.isAtEnd } }
mit
bb3306fb6b18bf844b143fbd2d4deb85
43.411765
119
0.632167
5
false
false
false
false