repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
saeta/penguin
Sources/PenguinStructures/FixedSizeArray.swift
1
10696
//****************************************************************************** // Copyright 2020 Penguin Authors // // 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 // // https://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. // /// Statically-sized nonempty collections of homogeneous elements. /// /// This protocol is mostly an implementation detail of `ArrayN`; it is not /// generally useful. Unless you're interested in generic application of /// `inserting`/`removing`, you probably want to use /// `RandomAccessCollection`/`MutableCollection` (either as constraints or /// conformances). /// /// The models of `FixedSizeArray` defined here efficiently support producing /// new instances by single-element insertion and deletion. public protocol FixedSizeArray: MutableCollection, RandomAccessCollection, SourceInitializableCollection, CustomStringConvertible where Index == Int { /// Creates an instance containing exactly the elements of `source`. /// /// Requires: `source.count == c`, where `c` is the capacity of instances. init<Source: Collection>(_ source: Source) where Source.Element == Element // Note: we don't have a generalization to `Sequence` because we couldn't // find an implementation optimizes nearly as well, and in practice // `Sequence`'s that are not `Collection`s are extremely rare. /// Creates an instance containing the elements of `source` except the one /// at `targetPosition`. /// /// Requires: `source.indices.contains(targetPosition)` init(_ source: ArrayN<Self>, removingAt targetPosition: Index) /// Returns a fixed-sized collection containing the same elements as `self`, /// with `newElement` inserted at `targetPosition`. func inserting(_ newElement: Element, at targetPosition: Index) -> ArrayN<Self> /// The number of elements in an instance. static var count: Int { get } } public extension FixedSizeArray { /// Default implementation of `CustomStringConvertible` conformance. var description: String { "\(Array(self))"} /// Returns the result of calling `body` on the elements of `self`. func withUnsafeBufferPointer<R>( _ body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R { return try withUnsafePointer(to: self) { [count] p in try body( UnsafeBufferPointer<Element>( start: UnsafeRawPointer(p) .assumingMemoryBound(to: Element.self), count: count)) } } /// Returns the result of calling `body` on the elements of `self`. mutating func withUnsafeMutableBufferPointer<R>( _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R { return try withUnsafeMutablePointer(to: &self) { [count] p in var b = UnsafeMutableBufferPointer<Element>( start: UnsafeMutableRawPointer(p) .assumingMemoryBound(to: Element.self), count: count) return try body(&b) } } /// Returns the result of calling `body` on the elements of `self`. func withContiguousStorageIfAvailable<R>( _ body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R? { return try withUnsafeBufferPointer(body) } /// Returns the result of calling `body` on the elements of `self`. mutating func withContiguousMutableStorageIfAvailable<R>( _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R? { return try withUnsafeMutableBufferPointer(body) } /// Returns a fixed-sized collection containing the same elements as `self`, /// with `newElement` inserted at the start. func prepending(_ newElement: Element) -> ArrayN<Self> { .init(head: newElement, tail: self) } } /// A fixed sized collection of 0 elements. public struct Array0<T> : FixedSizeArray { public init() { } /// Creates an instance containing exactly the elements of `source`. /// /// Requires: `source.isEmpty` @inline(__always) public init<Source: Collection>(_ source: Source) where Source.Element == Element { precondition(source.isEmpty, "Too many elements in source") } /// Creates an instance containing the elements of `source` except the one /// at `targetPosition`. /// /// Requires: `source.indices.contains(targetPosition)` public init(_ source: ArrayN<Self>, removingAt targetPosition: Index) { precondition(targetPosition == 0, "Index out of range.") self.init() } /// Returns a fixed-sized collection containing the same elements as `self`, /// with `newElement` inserted at `targetPosition`. public func inserting(_ newElement: Element, at i: Index) -> ArrayN<Self> { precondition(i == 0, "Index out of range.") return .init(head: newElement, tail: self) } /// The number of elements in an instance. public static var count: Int { 0 } // ======== Collection Requirements ============ public typealias Index = Int /// Accesses the element at `i`. public subscript(i: Index) -> T { get { fatalError("index out of range") } set { fatalError("index out of range") } } /// The position of the first element. public var startIndex: Index { 0 } /// The position just past the last element. public var endIndex: Index { 0 } } // ----- Standard conditional conformances. ------- extension Array0 : Equatable where T : Equatable {} extension Array0 : Hashable where T : Hashable {} extension Array0 : Comparable where Element : Comparable { public static func < (l: Self, r: Self) -> Bool { return false } } /// A fixed sized random access collection one element longer than `Tail`, /// supporting efficient creation of instances of related types via /// single-element insertion and deletion. public struct ArrayN<Tail: FixedSizeArray> : FixedSizeArray { private var head: Element private var tail: Tail public typealias Element = Tail.Element /// Creates an instance containing exactly the elements of `source`. /// /// Requires: `source.count == c`, where `c` is the capacity of instances. @inline(__always) public init<Source: Collection>(_ source: Source) where Source.Element == Element { head = source.first! tail = .init(source.dropFirst()) } /// Creates an instance containing `head` followed by the contents of /// `tail`. // Could be private, but for a test that is using it. internal init(head: Element, tail: Tail) { self.head = head self.tail = tail } /// Creates an instance containing the elements of `source` except the one at /// `targetPosition`. /// /// Requires: `source.indices.contains(targetPosition)` public init(_ source: ArrayN<Self>, removingAt targetPosition: Index) { self = targetPosition == 0 ? source.tail : Self( head: source.head, tail: .init(source.tail, removingAt: targetPosition &- 1)) } /// Returns a fixed-sized collection containing the same elements as `self`, /// with `newElement` inserted at `targetPosition`. public func inserting(_ newElement: Element, at i: Index) -> ArrayN<Self> { if i == 0 { return .init(head: newElement, tail: self) } return .init(head: head, tail: tail.inserting(newElement, at: i &- 1)) } /// Returns a fixed-sized collection containing the elements of self /// except the one at `targetPosition`. /// /// Requires: `indices.contains(targetPosition)` public func removing(at targetPosition: Index) -> Tail { .init(self, removingAt: targetPosition) } /// Traps with a suitable error message if `i` is not the position of an /// element in `self`. private func boundsCheck(_ i: Int) { precondition(i >= 0 && i < count, "index out of range") } /// The number of elements in an instance. public static var count: Int { Tail.count &+ 1 } // ======== Collection Requirements ============ /// Returns the element at `i`. public subscript(i: Int) -> Element { _read { boundsCheck(i) yield withUnsafeBufferPointer { $0.baseAddress.unsafelyUnwrapped[i] } } _modify { boundsCheck(i) defer { _fixLifetime(self) } yield &withUnsafeMutableBufferPointer { $0.baseAddress }.unsafelyUnwrapped[i] } } /// The position of the first element. public var startIndex: Int { 0 } /// The position just past the last element. public var endIndex: Int { tail.endIndex &+ 1 } } // ======== Conveniences ============ public typealias Array1<T> = ArrayN<Array0<T>> public typealias Array2<T> = ArrayN<Array1<T>> public typealias Array3<T> = ArrayN<Array2<T>> public typealias Array4<T> = ArrayN<Array3<T>> public typealias Array5<T> = ArrayN<Array4<T>> public typealias Array6<T> = ArrayN<Array5<T>> public typealias Array7<T> = ArrayN<Array6<T>> public extension ArrayN { /// Creates `Self([a0, a1])` efficiently. init<T>(_ a0: T, _ a1: T) where Tail == Array1<T> { head = a0; tail = Array1(CollectionOfOne(a1)) } /// Creates `Self([a0, a1, a2])` efficiently. init<T>(_ a0: T, _ a1: T, _ a2: T) where Tail == Array2<T> { head = a0; tail = Array2(a1, a2) } /// Creates `Self([a0, a1, a2, a3])` efficiently. init<T>(_ a0: T, _ a1: T, _ a2: T, _ a3: T) where Tail == Array3<T> { head = a0; tail = Tail(a1, a2, a3) } /// Creates `Self([a0, a1, a2, a3, a4])` efficiently. init<T>(_ a0: T, _ a1: T, _ a2: T, _ a3: T, _ a4: T) where Tail == Array4<T> { head = a0; tail = Tail(a1, a2, a3, a4) } /// Creates `Self([a0, a1, a2, a3, a4, a5])` efficiently. init<T>(_ a0: T, _ a1: T, _ a2: T, _ a3: T, _ a4: T, _ a5: T) where Tail == Array5<T> { head = a0; tail = Tail(a1, a2, a3, a4, a5) } /// Creates `Self([a0, a1, a2, a3, a4, a6])` efficiently. init<T>(_ a0: T, _ a1: T, _ a2: T, _ a3: T, _ a4: T, _ a5: T, _ a6: T) where Tail == Array6<T> { head = a0; tail = Tail(a1, a2, a3, a4, a5, a6) } } // ----- Standard conditional conformances. ------- extension ArrayN : Equatable where Element : Equatable, Tail : Equatable {} extension ArrayN : Hashable where Element : Hashable, Tail : Hashable {} extension ArrayN : Comparable where Element : Comparable, Tail : Comparable { public static func < (l: Self, r: Self) -> Bool { l.head < r.head || !(l.head > r.head) && l.tail < r.tail } }
apache-2.0
3978c81e17bbe869708013a12066a014
35.013468
83
0.658283
3.897959
false
false
false
false
dduan/swift
test/SILGen/struct_resilience.swift
1
8542
// RUN: %target-swift-frontend -I %S/../Inputs -enable-source-import -emit-silgen -enable-resilience %s | FileCheck %s import resilient_struct // Resilient structs are always address-only // CHECK-LABEL: sil hidden @_TF17struct_resilience26functionWithResilientTypesFTV16resilient_struct4Size1fFS1_S1__S1_ : $@convention(thin) (@in Size, @owned @callee_owned (@in Size) -> @out Size) -> @out Size // CHECK: bb0(%0 : $*Size, %1 : $*Size, %2 : $@callee_owned (@in Size) -> @out Size): func functionWithResilientTypes(s: Size, f: Size -> Size) -> Size { // Stored properties of resilient structs from outside our resilience // domain are accessed through accessors // CHECK: copy_addr %1 to [initialization] [[OTHER_SIZE_BOX:%[0-9]*]] : $*Size var s2 = s // CHECK: copy_addr %1 to [initialization] [[SIZE_BOX:%.*]] : $*Size // CHECK: [[FN:%.*]] = function_ref @_TFV16resilient_struct4Sizeg1wSi : $@convention(method) (@in_guaranteed Size) -> Int // CHECK: [[RESULT:%.*]] = apply [[FN]]([[SIZE_BOX]]) // CHECK: [[FN:%.*]] = function_ref @_TFV16resilient_struct4Sizes1wSi : $@convention(method) (Int, @inout Size) -> () // CHECK: apply [[FN]]([[RESULT]], [[OTHER_SIZE_BOX]]) s2.w = s.w // CHECK: copy_addr %1 to [initialization] [[SIZE_BOX:%.*]] : $*Size // CHECK: [[FN:%.*]] = function_ref @_TFV16resilient_struct4Sizeg1hSi : $@convention(method) (@in_guaranteed Size) -> Int // CHECK: [[RESULT:%.*]] = apply [[FN]]([[SIZE_BOX]]) _ = s.h // CHECK: copy_addr %1 to [initialization] [[SIZE_BOX:%.*]] : $*Size // CHECK: apply %2(%0, [[SIZE_BOX]]) // CHECK: return return f(s) } // Use materializeForSet for inout access of properties in resilient structs // from a different resilience domain func inoutFunc(x: inout Int) {} // CHECK-LABEL: sil hidden @_TF17struct_resilience18resilientInOutTestFRV16resilient_struct4SizeT_ : $@convention(thin) (@inout Size) -> () func resilientInOutTest(s: inout Size) { // CHECK: function_ref @_TF17struct_resilience9inoutFuncFRSiT_ // CHECK: function_ref @_TFV16resilient_struct4Sizem1wSi inoutFunc(&s.w) // CHECK: return } // Fixed-layout structs may be trivial or loadable // CHECK-LABEL: sil hidden @_TF17struct_resilience28functionWithFixedLayoutTypesFTV16resilient_struct5Point1fFS1_S1__S1_ : $@convention(thin) (Point, @owned @callee_owned (Point) -> Point) -> Point // CHECK: bb0(%0 : $Point, %1 : $@callee_owned (Point) -> Point): func functionWithFixedLayoutTypes(p: Point, f: Point -> Point) -> Point { // Stored properties of fixed layout structs are accessed directly var p2 = p // CHECK: [[RESULT:%.*]] = struct_extract %0 : $Point, #Point.x // CHECK: [[DEST:%.*]] = struct_element_addr [[POINT_BOX:%[0-9]*]] : $*Point, #Point.x // CHECK: assign [[RESULT]] to [[DEST]] : $*Int p2.x = p.x // CHECK: [[RESULT:%.*]] = struct_extract %0 : $Point, #Point.y _ = p.y // CHECK: [[NEW_POINT:%.*]] = apply %1(%0) // CHECK: return [[NEW_POINT]] return f(p) } // Fixed-layout struct with resilient stored properties is still address-only // CHECK-LABEL: sil hidden @_TF17struct_resilience39functionWithFixedLayoutOfResilientTypesFTV16resilient_struct9Rectangle1fFS1_S1__S1_ : $@convention(thin) (@in Rectangle, @owned @callee_owned (@in Rectangle) -> @out Rectangle) -> @out Rectangle // CHECK: bb0(%0 : $*Rectangle, %1 : $*Rectangle, %2 : $@callee_owned (@in Rectangle) -> @out Rectangle): func functionWithFixedLayoutOfResilientTypes(r: Rectangle, f: Rectangle -> Rectangle) -> Rectangle { return f(r) } // Make sure we generate getters and setters for stored properties of // resilient structs public struct MySize { // Static computed property // CHECK-LABEL: sil @_TZFV17struct_resilience6MySizeg10expirationSi : $@convention(thin) (@thin MySize.Type) -> Int // CHECK-LABEL: sil @_TZFV17struct_resilience6MySizes10expirationSi : $@convention(thin) (Int, @thin MySize.Type) -> () // CHECK-LABEL: sil @_TZFV17struct_resilience6MySizem10expirationSi : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @thin MySize.Type) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) public static var expiration: Int { get { return copyright + 70 } set { copyright = newValue - 70 } } // Instance computed property // CHECK-LABEL: sil @_TFV17struct_resilience6MySizeg1dSi : $@convention(method) (@in_guaranteed MySize) -> Int // CHECK-LABEL: sil @_TFV17struct_resilience6MySizes1dSi : $@convention(method) (Int, @inout MySize) -> () // CHECK-LABEL: sil @_TFV17struct_resilience6MySizem1dSi : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout MySize) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) public var d: Int { get { return 0 } set { } } // Instance stored property // CHECK-LABEL: sil @_TFV17struct_resilience6MySizeg1wSi : $@convention(method) (@in_guaranteed MySize) -> Int // CHECK-LABEL: sil @_TFV17struct_resilience6MySizes1wSi : $@convention(method) (Int, @inout MySize) -> () // CHECK-LABEL: sil @_TFV17struct_resilience6MySizem1wSi : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout MySize) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) public var w: Int // Read-only instance stored property // CHECK-LABEL: sil @_TFV17struct_resilience6MySizeg1hSi : $@convention(method) (@in_guaranteed MySize) -> Int public let h: Int // Static stored property // CHECK-LABEL: sil @_TZFV17struct_resilience6MySizeg9copyrightSi : $@convention(thin) (@thin MySize.Type) -> Int // CHECK-LABEL: sil @_TZFV17struct_resilience6MySizes9copyrightSi : $@convention(thin) (Int, @thin MySize.Type) -> () // CHECK-LABEL: sil @_TZFV17struct_resilience6MySizem9copyrightSi : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @thin MySize.Type) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) public static var copyright: Int = 0 } // CHECK-LABEL: sil @_TF17struct_resilience28functionWithMyResilientTypesFTVS_6MySize1fFS0_S0__S0_ : $@convention(thin) (@in MySize, @owned @callee_owned (@in MySize) -> @out MySize) -> @out MySize public func functionWithMyResilientTypes(s: MySize, f: MySize -> MySize) -> MySize { // Stored properties of resilient structs from inside our resilience // domain are accessed directly // CHECK: copy_addr %1 to [initialization] [[SIZE_BOX:%[0-9]*]] : $*MySize var s2 = s // CHECK: [[SRC_ADDR:%.*]] = struct_element_addr %1 : $*MySize, #MySize.w // CHECK: [[SRC:%.*]] = load [[SRC_ADDR]] : $*Int // CHECK: [[DEST_ADDR:%.*]] = struct_element_addr [[SIZE_BOX]] : $*MySize, #MySize.w // CHECK: assign [[SRC]] to [[DEST_ADDR]] : $*Int s2.w = s.w // CHECK: [[RESULT_ADDR:%.*]] = struct_element_addr %1 : $*MySize, #MySize.h // CHECK: [[RESULT:%.*]] = load [[RESULT_ADDR]] : $*Int _ = s.h // CHECK: copy_addr %1 to [initialization] [[SIZE_BOX:%.*]] : $*MySize // CHECK: apply %2(%0, [[SIZE_BOX]]) // CHECK: return return f(s) } // CHECK-LABEL: sil [transparent] [fragile] @_TF17struct_resilience25publicTransparentFunctionFVS_6MySizeSi : $@convention(thin) (@in MySize) -> Int @_transparent public func publicTransparentFunction(s: MySize) -> Int { // Since the body of a public transparent function might be inlined into // other resilience domains, we have to use accessors // CHECK: [[SELF:%.*]] = alloc_stack $MySize // CHECK-NEXT: copy_addr %0 to [initialization] [[SELF]] // CHECK: [[GETTER:%.*]] = function_ref @_TFV17struct_resilience6MySizeg1wSi // CHECK-NEXT: [[RESULT:%.*]] = apply [[GETTER]]([[SELF]]) // CHECK-NEXT: destroy_addr [[SELF]] // CHECK-NEXT: dealloc_stack [[SELF]] // CHECK-NEXT: destroy_addr %0 // CHECK-NEXT: return [[RESULT]] return s.w } // CHECK-LABEL: sil hidden [transparent] @_TF17struct_resilience27internalTransparentFunctionFVS_6MySizeSi : $@convention(thin) (@in MySize) -> Int @_transparent func internalTransparentFunction(s: MySize) -> Int { // The body of an internal transparent function will not be inlined into // other resilience domains, so we can access storage directly // CHECK: [[W_ADDR:%.*]] = struct_element_addr %0 : $*MySize, #MySize.w // CHECK-NEXT: [[RESULT:%.*]] = load [[W_ADDR]] : $*Int // CHECK-NEXT: destroy_addr %0 // CHECK-NEXT: return [[RESULT]] return s.w }
apache-2.0
7eaa2fd237296fb9b52c9ada62cbb3d0
46.19337
246
0.665886
3.525382
false
false
false
false
remlostime/one
one/one/AppDelegate.swift
1
4000
// // AppDelegate.swift // one // // Created by Kai Chen on 12/19/16. // Copyright © 2016 Kai Chen. All rights reserved. // import UIKit import Parse import CocoaLumberjack @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? let AppID = "one4ig_appid_1234567890" let ClientKey = "one4ig_masterkey_1234567890" let Server = "http://one4ig.herokuapp.com/parse" func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. // Configuration of using Parse code in Heroku let parseConfig = ParseClientConfiguration { (ParseMutableClientConfiguration) in // accessing Heroku App via id & keys ParseMutableClientConfiguration.applicationId = self.AppID ParseMutableClientConfiguration.clientKey = self.ClientKey ParseMutableClientConfiguration.server = self.Server } Parse.initialize(with: parseConfig) let username = UserDefaults.standard.string(forKey: User.id.rawValue) login(withUserName: username) DDLog.add(DDTTYLogger.sharedInstance()) // TTY = Xcode console DDLog.add(DDASLLogger.sharedInstance()) // ASL = Apple System Logs DDTTYLogger.sharedInstance().setForegroundColor(.red, backgroundColor: .black, for: .debug) let fileLogger: DDFileLogger = DDFileLogger() // File Logger fileLogger.rollingFrequency = TimeInterval(60*60*24) // 24 hours fileLogger.logFileManager.maximumNumberOfLogFiles = 7 DDLog.add(fileLogger) DDLogDebug("CK") return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // MARK: Helpers func login(withUserName username: String?) { if let _ = username { // Store logged user in userDefaults UserDefaults.standard.set(username, forKey: User.id.rawValue) UserDefaults.standard.synchronize() let storyboard = UIStoryboard(name: "Main", bundle: nil) let oneTabBarVC = storyboard.instantiateViewController(withIdentifier: "oneTabBar") as? UITabBarController window?.rootViewController = oneTabBarVC } } }
gpl-3.0
ba5b7320bfe900d4621a873d90798f7a
43.433333
285
0.711428
5.310757
false
true
false
false
sharath-cliqz/browser-ios
Client/Cliqz/Frontend/Browser/History/HistoryDataSource.swift
2
5564
// // HistoryDataSource.swift // Client // // Created by Mahmoud Adam on 10/17/17. // Copyright © 2017 Cliqz. All rights reserved. // import UIKit class HistoryDataSource: BubbleTableViewDataSource { //group details by their date. //order the dates. struct SortedHistoryEntry: Comparable { let date: String var details: [HistoryEntry] static func ==(x: SortedHistoryEntry, y: SortedHistoryEntry) -> Bool { return x.date == y.date } static func <(x: SortedHistoryEntry, y: SortedHistoryEntry) -> Bool { return x.date < y.date } } private let standardDateFormat = "dd.MM.yyyy" private let standardTimeFormat = "HH:mm" private let standardDateFormatter = DateFormatter() private let standardTimeFormatter = DateFormatter() var sortedDetails: [SortedHistoryEntry] = [] weak var delegate: HasDataSource? var profile: Profile! init(profile: Profile) { self.profile = profile standardDateFormatter.dateFormat = standardDateFormat standardTimeFormatter.dateFormat = standardTimeFormat } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func reloadHistory(completion: (() -> Void )?) { HistoryModule.getHistory(profile: profile) { [weak self] (historyEntries, error) in if error == nil, let orderedEntries = self?.groupByDate(historyEntries) { self?.sortedDetails = orderedEntries completion?() } } } func logo(indexPath: IndexPath, completionBlock: @escaping (_ url: URL, _ image: UIImage?, _ logoInfo: LogoInfo?) -> Void) { if let url = url(indexPath: indexPath) { LogoLoader.loadLogo(url.absoluteString) { (image, logoInfo, error) in completionBlock(url, image, logoInfo) } } } func url(indexPath: IndexPath) -> URL? { let historyEntry = detail(indexPath: indexPath) if let historyUrlEntry = historyEntry as? HistoryUrlEntry { return historyUrlEntry.url } return nil } func title(indexPath: IndexPath) -> String { return detail(indexPath: indexPath)?.title ?? "" } func titleSectionHeader(section: Int) -> String { guard sectionWithinBounds(section: section) else { return "" } return sortedDetails[section].date } func time(indexPath: IndexPath) -> String { if let date = detail(indexPath: indexPath)?.date { return standardTimeFormatter.string(from: date) } return "" } func accessibilityLabel(indexPath: IndexPath) -> String { if useRightCell(indexPath: indexPath) { return "query" } else { return "url" } } func numberOfSections() -> Int { return sortedDetails.count } func numberOfRows(section: Int) -> Int { return sortedDetails[section].details.count } func isNews() -> Bool { return false } func useRightCell(indexPath: IndexPath) -> Bool { if let _ = detail(indexPath: indexPath) as? HistoryQueryEntry { return true } return false } func useLeftExpandedCell() -> Bool { return false } func isEmpty() -> Bool { return !sectionWithinBounds(section: 0) } func detail(indexPath: IndexPath) -> HistoryEntry? { if indexWithinBounds(indexPath: indexPath) { return sortedDetails[indexPath.section].details[indexPath.row] } return nil } func sectionWithinBounds(section: Int) -> Bool { if section >= 0 && section < sortedDetails.count { return true } return false } func indexWithinBounds(indexPath: IndexPath) -> Bool { guard sectionWithinBounds(section: indexPath.section) else { return false } if indexPath.row >= 0 && indexPath.row < sortedDetails[indexPath.section].details.count { return true } return false } func groupByDate(_ historyEntries: [HistoryEntry]?) -> [SortedHistoryEntry] { var result = [SortedHistoryEntry]() guard let historyEntries = historyEntries else { return result } let ascendingHistoryEntries = historyEntries.reversed() for historyEntry in ascendingHistoryEntries { var date = "01-01-1970" if let entryDate = historyEntry.date { date = standardDateFormatter.string(from: entryDate) } if result.count > 0 && result[result.count - 1].date == date { result[result.count - 1].details.append(historyEntry) } else { let x = SortedHistoryEntry(date: date, details:[historyEntry]) result.append(x) } } return result } func deleteItem(at indexPath: IndexPath, completion: (() -> Void )?) { if let historyEntry = detail(indexPath: indexPath) { HistoryModule.removeHistoryEntries(profile: profile, ids: [historyEntry.id]) self.reloadHistory(completion: { DispatchQueue.main.async { [weak self] in self?.delegate?.dataSourceWasUpdated() } completion?() }) } } }
mpl-2.0
76364281a6436030deb50dccded35a95
30.078212
128
0.587273
4.828993
false
false
false
false
yonaskolb/XcodeGen
Tests/XcodeGenKitTests/SourceGeneratorTests.swift
1
61455
import PathKit import ProjectSpec import Spectre import XcodeGenKit import XcodeProj import XCTest import Yams import TestSupport class SourceGeneratorTests: XCTestCase { func testSourceGenerator() { describe { let directoryPath = Path("TestDirectory") let outOfRootPath = Path("OtherDirectory") func createDirectories(_ directories: String) throws { let yaml = try Yams.load(yaml: directories)! func getFiles(_ file: Any, path: Path) -> [Path] { if let array = file as? [Any] { return array.flatMap { getFiles($0, path: path) } } else if let string = file as? String { return [path + string] } else if let dictionary = file as? [String: Any] { var array: [Path] = [] for (key, value) in dictionary { array += getFiles(value, path: path + key) } return array } else { return [] } } let files = getFiles(yaml, path: directoryPath).filter { $0.extension != nil } for file in files { try file.parent().mkpath() try file.write("") } } func removeDirectories() { try? directoryPath.delete() try? outOfRootPath.delete() } $0.before { removeDirectories() } $0.after { removeDirectories() } $0.it("generates source groups") { let directories = """ Sources: A: - a.swift - B: - b.swift - C2.0: - c.swift """ try createDirectories(directories) let target = Target(name: "Test", type: .application, platform: .iOS, sources: ["Sources"]) let project = Project(basePath: directoryPath, name: "Test", targets: [target]) let pbxProj = try project.generatePbxProj() try pbxProj.expectFile(paths: ["Sources", "A", "a.swift"], buildPhase: .sources) try pbxProj.expectFile(paths: ["Sources", "A", "B", "b.swift"], buildPhase: .sources) try pbxProj.expectFile(paths: ["Sources", "A", "C2.0", "c.swift"], buildPhase: .sources) } $0.it("supports frameworks in sources") { let directories = """ Sources: - Foo.framework - Bar.swift """ try createDirectories(directories) let target = Target(name: "Test", type: .application, platform: .iOS, sources: ["Sources"]) let project = Project(basePath: directoryPath, name: "Test", targets: [target]) let pbxProj = try project.generatePbxProj() try pbxProj.expectFile(paths: ["Sources", "Bar.swift"], buildPhase: .sources) let buildPhase = pbxProj.copyFilesBuildPhases.first try expect(buildPhase?.dstSubfolderSpec) == .frameworks let fileReference = pbxProj.getFileReference( paths: ["Sources", "Foo.framework"], names: ["Sources", "Foo.framework"] ) let buildFile = try unwrap(pbxProj.buildFiles .first(where: { $0.file == fileReference })) try expect(buildPhase?.files?.count) == 1 try expect(buildPhase?.files?.contains(buildFile)) == true } $0.it("generates core data models") { let directories = """ Sources: model.xcdatamodeld: - .xccurrentversion - model.xcdatamodel - model1.xcdatamodel - model2.xcdatamodel """ try createDirectories(directories) let target = Target(name: "Test", type: .application, platform: .iOS, sources: ["Sources"]) let project = Project(basePath: directoryPath, name: "Test", targets: [target]) let pbxProj = try project.generatePbxProj() let fileReference = try unwrap(pbxProj.fileReferences.first(where: { $0.nameOrPath == "model2.xcdatamodel" })) let versionGroup = try unwrap(pbxProj.versionGroups.first) try expect(versionGroup.currentVersion) == fileReference try expect(versionGroup.children.count) == 3 try expect(versionGroup.path) == "model.xcdatamodeld" try expect(fileReference.path) == "model2.xcdatamodel" } $0.it("generates core data mapping models") { let directories = """ Sources: model.xcmappingmodel: - xcmapping.xml """ try createDirectories(directories) let target = Target(name: "Test", type: .application, platform: .iOS, sources: ["Sources"]) let project = Project(basePath: directoryPath, name: "Test", targets: [target]) let pbxProj = try project.generatePbxProj() try pbxProj.expectFile(paths: ["Sources", "model.xcmappingmodel"], buildPhase: .sources) } $0.it("generates variant groups") { let directories = """ Sources: Base.lproj: - LocalizedStoryboard.storyboard en.lproj: - LocalizedStoryboard.strings """ try createDirectories(directories) let target = Target(name: "Test", type: .application, platform: .iOS, sources: ["Sources"]) let project = Project(basePath: directoryPath, name: "Test", targets: [target]) let pbxProj = try project.generatePbxProj() func getFileReferences(_ path: String) -> [PBXFileReference] { pbxProj.fileReferences.filter { $0.path == path } } func getVariableGroups(_ name: String?) -> [PBXVariantGroup] { pbxProj.variantGroups.filter { $0.name == name } } let resourceName = "LocalizedStoryboard.storyboard" let baseResource = "Base.lproj/LocalizedStoryboard.storyboard" let localizedResource = "en.lproj/LocalizedStoryboard.strings" let variableGroup = try unwrap(getVariableGroups(resourceName).first) do { let refs = getFileReferences(baseResource) try expect(refs.count) == 1 try expect(variableGroup.children.filter { $0 == refs.first }.count) == 1 } do { let refs = getFileReferences(localizedResource) try expect(refs.count) == 1 try expect(variableGroup.children.filter { $0 == refs.first }.count) == 1 } } $0.it("handles localized resources") { let directories = """ App: Resources: en-CA.lproj: - empty.json - Localizable.strings en-US.lproj: - empty.json - Localizable.strings en.lproj: - empty.json - Localizable.strings fonts: SFUI: - SFUILight.ttf """ try createDirectories(directories) let target = Target(name: "Test", type: .application, platform: .iOS, sources: [TargetSource(path: "App/Resources")]) let options = SpecOptions(createIntermediateGroups: true) let project = Project(basePath: directoryPath, name: "Test", targets: [target], options: options) let outputXcodeProj = try project.generateXcodeProject() try outputXcodeProj.write(path: directoryPath) let inputXcodeProj = try XcodeProj(path: directoryPath) let pbxProj = inputXcodeProj.pbxproj func getFileReferences(_ path: String) -> [PBXFileReference] { pbxProj.fileReferences.filter { $0.path == path } } func getVariableGroups(_ name: String?) -> [PBXVariantGroup] { pbxProj.variantGroups.filter { $0.name == name } } let stringsResourceName = "Localizable.strings" let jsonResourceName = "empty.json" let stringsVariableGroup = try unwrap(getVariableGroups(stringsResourceName).first) let jsonVariableGroup = try unwrap(getVariableGroups(jsonResourceName).first) let stringsResource = "en.lproj/Localizable.strings" let jsonResource = "en-CA.lproj/empty.json" do { let refs = getFileReferences(stringsResource) try expect(refs.count) == 1 try expect(refs.first!.uuid.hasPrefix("TEMP")) == false try expect(stringsVariableGroup.children.filter { $0 == refs.first }.count) == 1 } do { let refs = getFileReferences(jsonResource) try expect(refs.count) == 1 try expect(refs.first!.uuid.hasPrefix("TEMP")) == false try expect(jsonVariableGroup.children.filter { $0 == refs.first }.count) == 1 } } $0.it("handles duplicate names") { let directories = """ Sources: - a.swift - a: - a.swift - a: - a.swift """ try createDirectories(directories) let target = Target(name: "Test", type: .application, platform: .iOS, sources: ["Sources"]) let project = Project( basePath: directoryPath, name: "Test", targets: [target], fileGroups: ["Sources"] ) let pbxProj = try project.generatePbxProj() try pbxProj.expectFile(paths: ["Sources", "a.swift"], buildPhase: .sources) try pbxProj.expectFile(paths: ["Sources", "a", "a.swift"], buildPhase: .sources) try pbxProj.expectFile(paths: ["Sources", "a", "a", "a.swift"], buildPhase: .sources) } $0.it("renames sources") { let directories = """ Sources: - a.swift OtherSource: - b.swift """ try createDirectories(directories) let target = Target(name: "Test", type: .application, platform: .iOS, sources: [ TargetSource(path: "Sources", name: "NewSource"), TargetSource(path: "OtherSource/b.swift", name: "c.swift"), ]) let project = Project(basePath: directoryPath, name: "Test", targets: [target]) let pbxProj = try project.generatePbxProj() try pbxProj.expectFile(paths: ["Sources", "a.swift"], names: ["NewSource", "a.swift"], buildPhase: .sources) try pbxProj.expectFile(paths: ["OtherSource", "b.swift"], names: ["OtherSource", "c.swift"], buildPhase: .sources) } $0.it("excludes sources") { let directories = """ Sources: - A: - a.swift - B: - b.swift - b.ignored - b.alsoIgnored - a.ignored - a.alsoIgnored - B: - b.swift - D: - d.h - d.m - E: - e.jpg - e.h - e.m - F: - f.swift - G: - H: - h.swift - types: - a.swift - a.m - a.h - a.x - numbers: - file1.a - file2.a - file3.a - file4.a - partial: - file_part - ignore.file - a.ignored - project.xcodeproj: - project.pbxproj - a.playground: - Sources: - a.swift - Resources """ try createDirectories(directories) let excludes = [ "B", "d.m", "E/F/*.swift", "G/H/", "types/*.[hx]", "numbers/file[2-3].a", "partial/*_part", "ignore.file", "*.ignored", "*.xcodeproj", "*.playground", "**/*.ignored", "A/B/**/*.alsoIgnored", ] let target = Target(name: "Test", type: .application, platform: .iOS, sources: [TargetSource(path: "Sources", excludes: excludes)]) func test(generateEmptyDirectories: Bool) throws { let options = SpecOptions(generateEmptyDirectories: generateEmptyDirectories) let project = Project(basePath: directoryPath, name: "Test", targets: [target], options: options) let pbxProj = try project.generatePbxProj() try pbxProj.expectFile(paths: ["Sources", "A", "a.swift"]) try pbxProj.expectFile(paths: ["Sources", "A", "a.alsoIgnored"]) try pbxProj.expectFile(paths: ["Sources", "D", "d.h"]) try pbxProj.expectFile(paths: ["Sources", "D", "d.m"]) try pbxProj.expectFile(paths: ["Sources", "E", "e.jpg"]) try pbxProj.expectFile(paths: ["Sources", "E", "e.m"]) try pbxProj.expectFile(paths: ["Sources", "E", "e.h"]) try pbxProj.expectFile(paths: ["Sources", "types", "a.swift"]) try pbxProj.expectFile(paths: ["Sources", "numbers", "file1.a"]) try pbxProj.expectFile(paths: ["Sources", "numbers", "file4.a"]) try pbxProj.expectFileMissing(paths: ["Sources", "B", "b.swift"]) try pbxProj.expectFileMissing(paths: ["Sources", "E", "F", "f.swift"]) try pbxProj.expectFileMissing(paths: ["Sources", "G", "H", "h.swift"]) try pbxProj.expectFileMissing(paths: ["Sources", "types", "a.h"]) try pbxProj.expectFileMissing(paths: ["Sources", "types", "a.x"]) try pbxProj.expectFileMissing(paths: ["Sources", "numbers", "file2.a"]) try pbxProj.expectFileMissing(paths: ["Sources", "numbers", "file3.a"]) try pbxProj.expectFileMissing(paths: ["Sources", "partial", "file_part"]) try pbxProj.expectFileMissing(paths: ["Sources", "a.ignored"]) try pbxProj.expectFileMissing(paths: ["Sources", "ignore.file"]) try pbxProj.expectFileMissing(paths: ["Sources", "project.xcodeproj"]) try pbxProj.expectFileMissing(paths: ["Sources", "a.playground"]) try pbxProj.expectFileMissing(paths: ["Sources", "A", "a.ignored"]) try pbxProj.expectFileMissing(paths: ["Sources", "A", "B", "b.ignored"]) try pbxProj.expectFileMissing(paths: ["Sources", "A", "B", "b.alsoIgnored"]) } try test(generateEmptyDirectories: false) try test(generateEmptyDirectories: true) } $0.it("excludes certain ignored files") { let directories = """ Sources: A: - a.swift - .DS_Store - a.swift.orig """ try createDirectories(directories) let target = Target(name: "Test", type: .application, platform: .iOS, sources: [TargetSource(path: "Sources")]) let project = Project(basePath: directoryPath, name: "Test", targets: [target]) let pbxProj = try project.generatePbxProj() try pbxProj.expectFile(paths: ["Sources", "A", "a.swift"]) try pbxProj.expectFileMissing(paths: ["Sources", "A", ".DS_Store"]) try pbxProj.expectFileMissing(paths: ["Sources", "A", "a.swift.orig"]) } $0.it("generates file sources") { let directories = """ Sources: A: - a.swift - Assets.xcassets - B: - b.swift - c.jpg - D2.0: - d.swift - E.bundle: - e.json """ try createDirectories(directories) let target = Target(name: "Test", type: .application, platform: .iOS, sources: [ "Sources/A/a.swift", "Sources/A/B/b.swift", "Sources/A/D2.0/d.swift", "Sources/A/Assets.xcassets", "Sources/A/E.bundle/e.json", "Sources/A/B/c.jpg", ]) let project = Project(basePath: directoryPath, name: "Test", targets: [target]) let pbxProj = try project.generatePbxProj() try pbxProj.expectFile(paths: ["Sources/A", "a.swift"], names: ["A", "a.swift"], buildPhase: .sources) try pbxProj.expectFile(paths: ["Sources/A/B", "b.swift"], names: ["B", "b.swift"], buildPhase: .sources) try pbxProj.expectFile(paths: ["Sources/A/D2.0", "d.swift"], names: ["D2.0", "d.swift"], buildPhase: .sources) try pbxProj.expectFile(paths: ["Sources/A/B", "c.jpg"], names: ["B", "c.jpg"], buildPhase: .resources) try pbxProj.expectFile(paths: ["Sources/A", "Assets.xcassets"], names: ["A", "Assets.xcassets"], buildPhase: .resources) try pbxProj.expectFile(paths: ["Sources/A/E.bundle", "e.json"], names: ["E.bundle", "e.json"], buildPhase: .resources) } $0.it("generates shared sources") { let directories = """ Sources: A: - a.swift - B: - b.swift - c.jpg """ try createDirectories(directories) let target1 = Target(name: "Test1", type: .framework, platform: .iOS, sources: ["Sources"]) let target2 = Target(name: "Test2", type: .framework, platform: .tvOS, sources: ["Sources"]) let project = Project(basePath: directoryPath, name: "Test", targets: [target1, target2]) _ = try project.generatePbxProj() // TODO: check there are build files for both targets } $0.it("generates intermediate groups") { let directories = """ Sources: A: - b.swift F: - G: - h.swift B: - b.swift """ try createDirectories(directories) let outOfSourceFile = outOfRootPath + "C/D/e.swift" try outOfSourceFile.parent().mkpath() try outOfSourceFile.write("") let target = Target(name: "Test", type: .application, platform: .iOS, sources: [ "Sources/A/b.swift", "Sources/F/G/h.swift", "../OtherDirectory/C/D/e.swift", TargetSource(path: "Sources/B", createIntermediateGroups: false), ]) let options = SpecOptions(createIntermediateGroups: true) let project = Project(basePath: directoryPath, name: "Test", targets: [target], options: options) let pbxProj = try project.generatePbxProj() try pbxProj.expectFile(paths: ["Sources", "A", "b.swift"], buildPhase: .sources) try pbxProj.expectFile(paths: ["Sources", "F", "G", "h.swift"], buildPhase: .sources) try pbxProj.expectFile(paths: ["..", "OtherDirectory", "C", "D", "e.swift"], names: [".", "OtherDirectory", "C", "D", "e.swift"], buildPhase: .sources) try pbxProj.expectFile(paths: ["Sources/B", "b.swift"], names: ["B", "b.swift"], buildPhase: .sources) } $0.it("generates custom groups") { let directories = """ - Sources: - a.swift - A: - b.swift - F: - G: - h.swift - i.swift - B: - b.swift - C: - c.swift """ try createDirectories(directories) let target = Target(name: "Test", type: .application, platform: .iOS, sources: [ TargetSource(path: "Sources/a.swift", group: "CustomGroup1"), TargetSource(path: "Sources/A/b.swift", group: "CustomGroup1"), TargetSource(path: "Sources/F/G/h.swift", group: "CustomGroup1"), TargetSource(path: "Sources/B", group: "CustomGroup2", createIntermediateGroups: false), TargetSource(path: "Sources/F/G/i.swift", group: "Sources/F/G/CustomGroup3"), ]) let options = SpecOptions(createIntermediateGroups: true) let project = Project(basePath: directoryPath, name: "Test", targets: [target], options: options) let pbxProj = try project.generatePbxProj() try pbxProj.expectFile(paths: ["CustomGroup1", "Sources/a.swift"], names: ["CustomGroup1", "a.swift"], buildPhase: .sources) try pbxProj.expectFile(paths: ["CustomGroup1", "Sources/A/b.swift"], names: ["CustomGroup1", "b.swift"], buildPhase: .sources) try pbxProj.expectFile(paths: ["CustomGroup1", "Sources/F/G/h.swift"], names: ["CustomGroup1", "h.swift"], buildPhase: .sources) try pbxProj.expectFile(paths: ["Sources", "F", "G", "CustomGroup3", "i.swift"], names: ["Sources", "F", "G", "CustomGroup3", "i.swift"], buildPhase: .sources) try pbxProj.expectFile(paths: ["CustomGroup2", "Sources/B", "b.swift"], names: ["CustomGroup2", "B", "b.swift"], buildPhase: .sources) try pbxProj.expectFile(paths: ["CustomGroup2", "Sources/B", "C", "c.swift"], names: ["CustomGroup2", "B", "C", "c.swift"], buildPhase: .sources) } $0.it("generates folder references") { let directories = """ Sources: A: - a.resource - b.resource """ try createDirectories(directories) let target = Target(name: "Test", type: .application, platform: .iOS, sources: [ TargetSource(path: "Sources/A", type: .folder), ]) let project = Project(basePath: directoryPath, name: "Test", targets: [target]) let pbxProj = try project.generatePbxProj() try pbxProj.expectFile(paths: ["Sources/A"], names: ["A"], buildPhase: .resources) try pbxProj.expectFileMissing(paths: ["Sources", "A", "a.swift"]) } $0.it("adds files to correct build phase") { let directories = """ A: - file.swift - file.xcassets - file.h - GoogleService-Info.plist - file.xcconfig B: - file.swift - file.xcassets - file.h - Sample.plist - file.xcconfig C: - file.swift - file.m - file.mm - file.cpp - file.c - file.S - file.h - file.hh - file.hpp - file.ipp - file.tpp - file.hxx - file.def - file.xcconfig - file.entitlements - file.gpx - file.apns - file.123 - file.xcassets - file.metal - file.mlmodel - file.mlmodelc - Info.plist - Intent.intentdefinition - Configuration.storekit - Settings.bundle: - en.lproj: - Root.strings - Root.plist - WithPeriod2.0: - file.swift - Documentation.docc """ try createDirectories(directories) let target = Target(name: "Test", type: .framework, platform: .iOS, sources: [ TargetSource(path: "A", buildPhase: .resources), TargetSource(path: "B", buildPhase: BuildPhaseSpec.none), TargetSource(path: "C", buildPhase: nil), ]) let project = Project(basePath: directoryPath, name: "Test", targets: [target]) let pbxProj = try project.generatePbxProj() try pbxProj.expectFile(paths: ["A", "file.swift"], buildPhase: .resources) try pbxProj.expectFile(paths: ["A", "file.xcassets"], buildPhase: .resources) try pbxProj.expectFile(paths: ["A", "file.h"], buildPhase: .resources) try pbxProj.expectFile(paths: ["A", "GoogleService-Info.plist"], buildPhase: .resources) try pbxProj.expectFile(paths: ["A", "file.xcconfig"], buildPhase: .resources) try pbxProj.expectFile(paths: ["B", "file.swift"], buildPhase: BuildPhaseSpec.none) try pbxProj.expectFile(paths: ["B", "file.xcassets"], buildPhase: BuildPhaseSpec.none) try pbxProj.expectFile(paths: ["B", "file.h"], buildPhase: BuildPhaseSpec.none) try pbxProj.expectFile(paths: ["B", "Sample.plist"], buildPhase: BuildPhaseSpec.none) try pbxProj.expectFile(paths: ["B", "file.xcconfig"], buildPhase: BuildPhaseSpec.none) try pbxProj.expectFile(paths: ["C", "file.swift"], buildPhase: .sources) try pbxProj.expectFile(paths: ["C", "file.m"], buildPhase: .sources) try pbxProj.expectFile(paths: ["C", "file.mm"], buildPhase: .sources) try pbxProj.expectFile(paths: ["C", "file.cpp"], buildPhase: .sources) try pbxProj.expectFile(paths: ["C", "file.c"], buildPhase: .sources) try pbxProj.expectFile(paths: ["C", "file.S"], buildPhase: .sources) try pbxProj.expectFile(paths: ["C", "file.h"], buildPhase: .headers) try pbxProj.expectFile(paths: ["C", "file.hh"], buildPhase: .headers) try pbxProj.expectFile(paths: ["C", "file.hpp"], buildPhase: .headers) try pbxProj.expectFile(paths: ["C", "file.ipp"], buildPhase: .headers) try pbxProj.expectFile(paths: ["C", "file.tpp"], buildPhase: .headers) try pbxProj.expectFile(paths: ["C", "file.hxx"], buildPhase: .headers) try pbxProj.expectFile(paths: ["C", "file.def"], buildPhase: .headers) try pbxProj.expectFile(paths: ["C", "file.xcconfig"], buildPhase: BuildPhaseSpec.none) try pbxProj.expectFile(paths: ["C", "file.entitlements"], buildPhase: BuildPhaseSpec.none) try pbxProj.expectFile(paths: ["C", "file.gpx"], buildPhase: BuildPhaseSpec.none) try pbxProj.expectFile(paths: ["C", "file.apns"], buildPhase: BuildPhaseSpec.none) try pbxProj.expectFile(paths: ["C", "file.xcconfig"], buildPhase: BuildPhaseSpec.none) try pbxProj.expectFile(paths: ["C", "file.xcconfig"], buildPhase: BuildPhaseSpec.none) try pbxProj.expectFile(paths: ["C", "file.xcconfig"], buildPhase: BuildPhaseSpec.none) try pbxProj.expectFile(paths: ["C", "file.xcassets"], buildPhase: .resources) try pbxProj.expectFile(paths: ["C", "file.123"], buildPhase: .resources) try pbxProj.expectFile(paths: ["C", "Info.plist"], buildPhase: BuildPhaseSpec.none) try pbxProj.expectFile(paths: ["C", "file.metal"], buildPhase: .sources) try pbxProj.expectFile(paths: ["C", "file.mlmodel"], buildPhase: .sources) try pbxProj.expectFile(paths: ["C", "file.mlmodelc"], buildPhase: .resources) try pbxProj.expectFile(paths: ["C", "Intent.intentdefinition"], buildPhase: .sources) try pbxProj.expectFile(paths: ["C", "Configuration.storekit"], buildPhase: .resources) try pbxProj.expectFile(paths: ["C", "Settings.bundle"], buildPhase: .resources) try pbxProj.expectFileMissing(paths: ["C", "Settings.bundle", "en.lproj"]) try pbxProj.expectFileMissing(paths: ["C", "Settings.bundle", "en.lproj", "Root.strings"]) try pbxProj.expectFileMissing(paths: ["C", "Settings.bundle", "Root.plist"]) try pbxProj.expectFileMissing(paths: ["C", "WithPeriod2.0"]) try pbxProj.expectFile(paths: ["C", "WithPeriod2.0", "file.swift"], buildPhase: .sources) try pbxProj.expectFile(paths: ["C", "Documentation.docc"], buildPhase: .sources) } $0.it("only omits the defined Info.plist from resource build phases but not other plists") { try createDirectories(""" A: - A-Info.plist B: - Info.plist - GoogleServices-Info.plist C: - Info.plist - Info-Production.plist D: - Info-Staging.plist - Info-Production.plist """) // Explicit plist.path value is respected let targetA = Target( name: "A", type: .application, platform: .iOS, sources: ["A"], info: Plist(path: "A/A-Info.plist") ) // Automatically picks first 'Info.plist' at the top-level let targetB = Target( name: "B", type: .application, platform: .iOS, sources: ["B"] ) // Also respects INFOPLIST_FILE, ignores other files named Info.plist let targetC = Target( name: "C", type: .application, platform: .iOS, settings: Settings(dictionary: [ "INFOPLIST_FILE": "C/Info-Production.plist" ]), sources: ["C"] ) // Does not support INFOPLIST_FILE value that requires expanding let targetD = Target( name: "D", type: .application, platform: .iOS, settings: Settings(dictionary: [ "ENVIRONMENT": "Production", "INFOPLIST_FILE": "D/Info-${ENVIRONMENT}.plist" ]), sources: ["D"] ) let project = Project(basePath: directoryPath.absolute(), name: "Test", targets: [targetA, targetB, targetC, targetD]) let pbxProj = try project.generatePbxProj() try pbxProj.expectFile(paths: ["A", "A-Info.plist"], buildPhase: BuildPhaseSpec.none) try pbxProj.expectFile(paths: ["B", "Info.plist"], buildPhase: BuildPhaseSpec.none) try pbxProj.expectFile(paths: ["B", "GoogleServices-Info.plist"], buildPhase: .resources) try pbxProj.expectFile(paths: ["C", "Info.plist"], buildPhase: .resources) try pbxProj.expectFile(paths: ["C", "Info-Production.plist"], buildPhase: BuildPhaseSpec.none) try pbxProj.expectFile(paths: ["D", "Info-Staging.plist"], buildPhase: .resources) try pbxProj.expectFile(paths: ["D", "Info-Production.plist"], buildPhase: .resources) } $0.it("sets file type properties") { let directories = """ A: - file.resource1 - file.source1 - file.abc: - file.a - file.exclude1 - file.unphased1 - ignored.swift """ try createDirectories(directories) let target = Target(name: "Test", type: .framework, platform: .iOS, sources: [ TargetSource(path: "A"), ]) let project = Project(basePath: directoryPath, name: "Test", targets: [target], options: .init(fileTypes: [ "abc": FileType(buildPhase: .sources), "source1": FileType(buildPhase: .sources, attributes: ["a1", "a2"], resourceTags: ["r1", "r2"], compilerFlags: ["-c1", "-c2"]), "resource1": FileType(buildPhase: .resources, attributes: ["a1", "a2"], resourceTags: ["r1", "r2"], compilerFlags: ["-c1", "-c2"]), "unphased1": FileType(buildPhase: BuildPhaseSpec.none), "swift": FileType(buildPhase: .resources), ])) let pbxProj = try project.generatePbxProj() try pbxProj.expectFile(paths: ["A", "file.abc"], buildPhase: .sources) try pbxProj.expectFile(paths: ["A", "file.source1"], buildPhase: .sources) try pbxProj.expectFile(paths: ["A", "file.resource1"], buildPhase: .resources) try pbxProj.expectFile(paths: ["A", "file.unphased1"], buildPhase: BuildPhaseSpec.none) try pbxProj.expectFile(paths: ["A", "ignored.swift"], buildPhase: .resources) do { let fileReference = try unwrap(pbxProj.getFileReference(paths: ["A", "file.resource1"], names: ["A", "file.resource1"])) let buildFile = try unwrap(pbxProj.buildFiles.first(where: { $0.file === fileReference })) let settings = NSDictionary(dictionary: buildFile.settings ?? [:]) try expect(settings) == [ "ATTRIBUTES": ["a1", "a2"], "ASSET_TAGS": ["r1", "r2"], ] } do { let fileReference = try unwrap(pbxProj.getFileReference(paths: ["A", "file.source1"], names: ["A", "file.source1"])) let buildFile = try unwrap(pbxProj.buildFiles.first(where: { $0.file === fileReference })) let settings = NSDictionary(dictionary: buildFile.settings ?? [:]) try expect(settings) == [ "ATTRIBUTES": ["a1", "a2"], "COMPILER_FLAGS": "-c1 -c2", ] } } $0.it("duplicate TargetSource is included once in sources build phase") { let directories = """ Sources: A: - a.swift """ try createDirectories(directories) let target = Target(name: "Test", type: .application, platform: .iOS, sources: [ "Sources/A/a.swift", "Sources/A/a.swift", ]) let project = Project(basePath: directoryPath, name: "Test", targets: [target]) let pbxProj = try project.generatePbxProj() try pbxProj.expectFile(paths: ["Sources/A", "a.swift"], names: ["A", "a.swift"], buildPhase: .sources) let sourcesBuildPhase = pbxProj.buildPhases.first(where: { $0.buildPhase == BuildPhase.sources })! try expect(sourcesBuildPhase.files?.count) == 1 } $0.it("add only carthage dependencies with same platform") { let directories = """ A: - file.swift """ try createDirectories(directories) let watchTarget = Target(name: "Watch", type: .watch2App, platform: .watchOS, sources: ["A"], dependencies: [Dependency(type: .carthage(findFrameworks: false, linkType: .dynamic), reference: "Alamofire_watch")]) let watchDependency = Dependency(type: .target, reference: "Watch") let target = Target(name: "Test", type: .application, platform: .iOS, sources: ["A"], dependencies: [Dependency(type: .carthage(findFrameworks: false, linkType: .dynamic), reference: "Alamofire"), watchDependency]) let project = Project(basePath: directoryPath, name: "Test", targets: [target, watchTarget]) let pbxProj = try project.generatePbxProj() let carthagePhase = pbxProj.nativeTargets.first(where: { $0.name == "Test" })?.buildPhases.first(where: { $0 is PBXShellScriptBuildPhase }) as? PBXShellScriptBuildPhase try expect(carthagePhase?.inputPaths) == ["$(SRCROOT)/Carthage/Build/iOS/Alamofire.framework"] } $0.it("derived directories are sorted last") { let directories = """ A: - file.swift P: - file.swift S: - file.swift """ try createDirectories(directories) let target = Target(name: "Test", type: .application, platform: .iOS, sources: ["A", "P", "S"], dependencies: [Dependency(type: .carthage(findFrameworks: false, linkType: .dynamic), reference: "Alamofire")]) let project = Project(basePath: directoryPath, name: "Test", targets: [target]) let pbxProj = try project.generatePbxProj() let groups = try pbxProj.getMainGroup().children.map { $0.nameOrPath } try expect(groups) == ["A", "P", "S", "Frameworks", "Products"] } $0.it("sorts files") { let directories = """ A: - A.swift Source: - file.swift Sources: - file3.swift - file.swift - 10file.a - 1file.a - file2.swift - group2: - file.swift - group: - file.swift Z: - A: - file.swift B: - file.swift """ try createDirectories(directories) let target = Target(name: "Test", type: .application, platform: .iOS, sources: [ "Sources", TargetSource(path: "Source", name: "S"), "A", TargetSource(path: "Z/A", name: "B"), "B", ], dependencies: [Dependency(type: .carthage(findFrameworks: false, linkType: .dynamic), reference: "Alamofire")]) let project = Project(basePath: directoryPath, name: "Test", targets: [target]) let pbxProj = try project.generatePbxProj() let mainGroup = try pbxProj.getMainGroup() let mainGroupNames = mainGroup.children.prefix(5).map { $0.name } try expect(mainGroupNames) == [ nil, nil, "B", "S", nil, ] let mainGroupPaths = mainGroup.children.prefix(5).map { $0.path } try expect(mainGroupPaths) == [ "A", "B", "Z/A", "Source", "Sources", ] let group = mainGroup.children.compactMap { $0 as? PBXGroup }.first { $0.path == "Sources" }! let names = group.children.map { $0.name } try expect(names) == [ nil, nil, nil, nil, nil, nil, nil, ] let paths = group.children.map { $0.path } try expect(paths) == [ "1file.a", "10file.a", "file.swift", "file2.swift", "file3.swift", "group", "group2", ] } $0.it("adds missing optional files and folders") { let target = Target(name: "Test", type: .application, platform: .iOS, sources: [ TargetSource(path: "File1.swift", optional: true), TargetSource(path: "File2.swift", type: .file, optional: true), TargetSource(path: "Group", type: .folder, optional: true), ]) let project = Project(basePath: directoryPath, name: "Test", targets: [target]) let pbxProj = try project.generatePbxProj() try pbxProj.expectFile(paths: ["File1.swift"]) try pbxProj.expectFile(paths: ["File2.swift"]) } $0.it("allows missing optional groups") { let target = Target(name: "Test", type: .application, platform: .iOS, sources: [ TargetSource(path: "Group1", optional: true), TargetSource(path: "Group2", type: .group, optional: true), TargetSource(path: "Group3", type: .group, optional: true), ]) let project = Project(basePath: directoryPath, name: "Test", targets: [target]) _ = try project.generatePbxProj() } $0.it("relative path items outside base path are grouped together") { let directories = """ Sources: - Inside: - a.swift - Inside2: - b.swift """ try createDirectories(directories) let outOfSourceFile1 = outOfRootPath + "Outside/a.swift" try outOfSourceFile1.parent().mkpath() try outOfSourceFile1.write("") let outOfSourceFile2 = outOfRootPath + "Outside/Outside2/b.swift" try outOfSourceFile2.parent().mkpath() try outOfSourceFile2.write("") let target = Target(name: "Test", type: .application, platform: .iOS, sources: [ "Sources", "../OtherDirectory", ]) let project = Project(basePath: directoryPath, name: "Test", targets: [target]) let pbxProj = try project.generatePbxProj() try pbxProj.expectFile(paths: ["Sources", "Inside", "a.swift"], buildPhase: .sources) try pbxProj.expectFile(paths: ["Sources", "Inside", "Inside2", "b.swift"], buildPhase: .sources) try pbxProj.expectFile(paths: ["../OtherDirectory", "Outside", "a.swift"], names: ["OtherDirectory", "Outside", "a.swift"], buildPhase: .sources) try pbxProj.expectFile(paths: ["../OtherDirectory", "Outside", "Outside2", "b.swift"], names: ["OtherDirectory", "Outside", "Outside2", "b.swift"], buildPhase: .sources) } $0.it("correctly adds target source attributes") { let directories = """ A: - Intent.intentdefinition """ try createDirectories(directories) let definition: String = "Intent.intentdefinition" let target = Target(name: "Test", type: .framework, platform: .iOS, sources: [ TargetSource(path: "A/\(definition)", buildPhase: .sources, attributes: ["no_codegen"]), ]) let project = Project(basePath: directoryPath, name: "Test", targets: [target]) let pbxProj = try project.generatePbxProj() let fileReference = pbxProj.getFileReference( paths: ["A", definition], names: ["A", definition] ) let buildFile = try unwrap(pbxProj.buildFiles.first(where: { $0.file == fileReference })) try pbxProj.expectFile(paths: ["A", definition], buildPhase: .sources) if (buildFile.settings! as NSDictionary) != (["ATTRIBUTES": ["no_codegen"]] as NSDictionary) { throw failure("File does not contain no_codegen attribute") } } $0.it("includes only the specified files when includes is present") { let directories = """ Sources: - file3.swift - file3Tests.swift - file2.swift - file2Tests.swift - group2: - file.swift - fileTests.swift - group: - file.swift - group3: - group4: - group5: - file.swift - file5Tests.swift - file6Tests.m - file6Tests.h """ try createDirectories(directories) let includes = [ "**/*Tests.*", ] let target = Target(name: "Test", type: .application, platform: .iOS, sources: [TargetSource(path: "Sources", includes: includes)]) let options = SpecOptions(createIntermediateGroups: true, generateEmptyDirectories: true) let project = Project(basePath: directoryPath, name: "Test", targets: [target], options: options) let pbxProj = try project.generatePbxProj() try pbxProj.expectFile(paths: ["Sources", "file2Tests.swift"]) try pbxProj.expectFile(paths: ["Sources", "file3Tests.swift"]) try pbxProj.expectFile(paths: ["Sources", "group2", "fileTests.swift"]) try pbxProj.expectFile(paths: ["Sources", "group3", "group4", "group5", "file5Tests.swift"]) try pbxProj.expectFile(paths: ["Sources", "group3", "group4", "group5", "file6Tests.h"]) try pbxProj.expectFile(paths: ["Sources", "group3", "group4", "group5", "file6Tests.m"]) try pbxProj.expectFileMissing(paths: ["Sources", "file2.swift"]) try pbxProj.expectFileMissing(paths: ["Sources", "file3.swift"]) try pbxProj.expectFileMissing(paths: ["Sources", "group2", "file.swift"]) try pbxProj.expectFileMissing(paths: ["Sources", "group", "file.swift"]) } $0.it("prioritizes excludes over includes when both are present") { let directories = """ Sources: - file3.swift - file3Tests.swift - file2.swift - file2Tests.swift - group2: - file.swift - fileTests.swift - group: - file.swift """ try createDirectories(directories) let includes = [ "**/*Tests.*", ] let excludes = [ "group2", ] let target = Target(name: "Test", type: .application, platform: .iOS, sources: [TargetSource(path: "Sources", excludes: excludes, includes: includes)]) let project = Project(basePath: directoryPath, name: "Test", targets: [target]) let pbxProj = try project.generatePbxProj() try pbxProj.expectFile(paths: ["Sources", "file2Tests.swift"]) try pbxProj.expectFile(paths: ["Sources", "file3Tests.swift"]) try pbxProj.expectFileMissing(paths: ["Sources", "group2", "fileTests.swift"]) try pbxProj.expectFileMissing(paths: ["Sources", "file2.swift"]) try pbxProj.expectFileMissing(paths: ["Sources", "file3.swift"]) try pbxProj.expectFileMissing(paths: ["Sources", "group2", "file.swift"]) try pbxProj.expectFileMissing(paths: ["Sources", "group", "file.swift"]) } $0.describe("Localized sources") { $0.context("With localized sources") { $0.it("*.intentdefinition should be added to source phase") { let directories = """ Sources: Base.lproj: - Intents.intentdefinition en.lproj: - Intents.strings ja.lproj: - Intents.strings """ try createDirectories(directories) let directoryPath = Path("TestDirectory") let target = Target(name: "IntentDefinitions", type: .application, platform: .iOS, sources: [TargetSource(path: "Sources")]) let project = Project(basePath: directoryPath, name: "IntendDefinitions", targets: [target]) let pbxProj = try project.generatePbxProj() let sourceBuildPhase = try unwrap(pbxProj.buildPhases.first { $0.buildPhase == .sources }) try expect(sourceBuildPhase.files?.compactMap { $0.file?.nameOrPath }) == ["Intents.intentdefinition"] } } $0.context("With localized sources with buildPhase") { $0.it("*.intentdefinition with buildPhase should be added to resource phase") { let directories = """ Sources: Base.lproj: - Intents.intentdefinition en.lproj: - Intents.strings ja.lproj: - Intents.strings """ try createDirectories(directories) let directoryPath = Path("TestDirectory") let target = Target(name: "IntentDefinitions", type: .application, platform: .iOS, sources: [TargetSource(path: "Sources", buildPhase: .resources)]) let project = Project(basePath: directoryPath, name: "IntendDefinitions", targets: [target]) let pbxProj = try project.generatePbxProj() let sourceBuildPhase = try unwrap(pbxProj.buildPhases.first { $0.buildPhase == .sources }) let resourcesBuildPhase = try unwrap(pbxProj.buildPhases.first { $0.buildPhase == .resources }) try expect(sourceBuildPhase.files) == [] try expect(resourcesBuildPhase.files?.compactMap { $0.file?.nameOrPath }) == ["Intents.intentdefinition"] } } $0.it("generates resource tags") { let directories = """ A: - resourceFile.mp4 - resourceFile2.mp4 - sourceFile.swift """ try createDirectories(directories) let target = Target( name: "Test", type: .application, platform: .iOS, sources: [ TargetSource(path: "A/resourceFile.mp4", buildPhase: .resources, resourceTags: ["tag1", "tag2"]), TargetSource(path: "A/resourceFile2.mp4", buildPhase: .resources, resourceTags: ["tag2", "tag3"]), TargetSource(path: "A/sourceFile.swift", buildPhase: .sources, resourceTags: ["tag1", "tag2"]), ] ) let project = Project(basePath: directoryPath, name: "Test", targets: [target]) let pbxProj = try project.generatePbxProj() let resourceFileReference = try unwrap(pbxProj.getFileReference( paths: ["A", "resourceFile.mp4"], names: ["A", "resourceFile.mp4"] )) let resourceFileReference2 = try unwrap(pbxProj.getFileReference( paths: ["A", "resourceFile2.mp4"], names: ["A", "resourceFile2.mp4"] )) let sourceFileReference = try unwrap(pbxProj.getFileReference( paths: ["A", "sourceFile.swift"], names: ["A", "sourceFile.swift"] )) try pbxProj.expectFile(paths: ["A", "resourceFile.mp4"], buildPhase: .resources) try pbxProj.expectFile(paths: ["A", "resourceFile2.mp4"], buildPhase: .resources) try pbxProj.expectFile(paths: ["A", "sourceFile.swift"], buildPhase: .sources) let resourceBuildFile = try unwrap(pbxProj.buildFiles.first(where: { $0.file == resourceFileReference })) let resourceBuildFile2 = try unwrap(pbxProj.buildFiles.first(where: { $0.file == resourceFileReference2 })) let sourceBuildFile = try unwrap(pbxProj.buildFiles.first(where: { $0.file == sourceFileReference })) if (resourceBuildFile.settings! as NSDictionary) != (["ASSET_TAGS": ["tag1", "tag2"]] as NSDictionary) { throw failure("File does not contain tag1 and tag2 ASSET_TAGS") } if (resourceBuildFile2.settings! as NSDictionary) != (["ASSET_TAGS": ["tag2", "tag3"]] as NSDictionary) { throw failure("File does not contain tag2 and tag3 ASSET_TAGS") } if sourceBuildFile.settings != nil { throw failure("File that buildPhase is source contain settings") } if !pbxProj.rootObject!.attributes.keys.contains("knownAssetTags") { throw failure("PBXProject does not contain knownAssetTags") } try expect(pbxProj.rootObject!.attributes["knownAssetTags"] as? [String]) == ["tag1", "tag2", "tag3"] } } } } } extension PBXProj { /// expect a file within groups of the paths, using optional different names func expectFile(paths: [String], names: [String]? = nil, buildPhase: BuildPhaseSpec? = nil, file: String = #file, line: Int = #line) throws { guard let fileReference = getFileReference(paths: paths, names: names ?? paths) else { var error = "Could not find file at path \(paths.joined(separator: "/").quoted)" if let names = names, names != paths { error += " and name \(names.joined(separator: "/").quoted)" } error += "\n\(self.printGroups())" throw failure(error, file: file, line: line) } if let buildPhase = buildPhase { let buildFile = buildFiles .first(where: { $0.file === fileReference }) let actualBuildPhase = buildFile .flatMap { buildFile in buildPhases.first { $0.files?.contains(buildFile) ?? false } }?.buildPhase var error: String? if let buildPhase = buildPhase.buildPhase { if actualBuildPhase != buildPhase { if let actualBuildPhase = actualBuildPhase { error = "is in the \(actualBuildPhase.rawValue) build phase instead of the expected \(buildPhase.rawValue.quoted)" } else { error = "isn't in a build phase when it's expected to be in \(buildPhase.rawValue.quoted)" } } } else if let actualBuildPhase = actualBuildPhase { error = "is in the \(actualBuildPhase.rawValue.quoted) build phase when it's expected to not be in any" } if let error = error { throw failure("File \(paths.joined(separator: "/").quoted) \(error)", file: file, line: line) } } } /// expect a missing file within groups of the paths, using optional different names func expectFileMissing(paths: [String], names: [String]? = nil, file: String = #file, line: Int = #line) throws { let names = names ?? paths if getFileReference(paths: paths, names: names) != nil { throw failure("Found unexpected file at path \(paths.joined(separator: "/").quoted) and name \(paths.joined(separator: "/").quoted)", file: file, line: line) } } func getFileReference(paths: [String], names: [String], file: String = #file, line: Int = #line) -> PBXFileReference? { guard let mainGroup = projects.first?.mainGroup else { return nil } return getFileReference(group: mainGroup, paths: paths, names: names) } private func getFileReference(group: PBXGroup, paths: [String], names: [String]) -> PBXFileReference? { guard !paths.isEmpty else { return nil } let path = paths.first! let name = names.first! let restOfPath = Array(paths.dropFirst()) let restOfName = Array(names.dropFirst()) if restOfPath.isEmpty { let fileReferences: [PBXFileReference] = group.children.compactMap { $0 as? PBXFileReference } return fileReferences.first { ($0.path == nil || $0.path == path) && $0.nameOrPath == name } } else { let groups = group.children.compactMap { $0 as? PBXGroup } guard let group = groups.first(where: { ($0.path == nil || $0.path == path) && $0.nameOrPath == name }) else { return nil } return getFileReference(group: group, paths: restOfPath, names: restOfName) } } }
mit
90c0d9baffc831ae3e8f4c7601e9199e
46.936817
230
0.482955
4.861562
false
true
false
false
benjaminsnorris/SharedHelpers
Sources/SegmentedLine.swift
1
3739
/* | _ ____ ____ _ | | |‾| ⚈ |-| ⚈ |‾| | | | | ‾‾‾‾| |‾‾‾‾ | | | ‾ ‾ ‾ */ import UIKit @IBDesignable open class SegmentedLine: CustomView { // MARK: - Inspectable properties @IBInspectable open var fillColorName: String? { didSet { updateColors() } } @IBInspectable open var fillBackgroundColorName: String? { didSet { updateColors() } } @IBInspectable open var fillColor: UIColor = #colorLiteral(red: 0, green: 0.4784313725, blue: 1, alpha: 1) { didSet { updateColors() } } @IBInspectable open var fillBackgroundColor: UIColor = .white { didSet { updateColors() } } @IBInspectable open var segments: Int = 3 { didSet { updateBar() } } @IBInspectable open var segmentSpacing: CGFloat = 2 { didSet { updateBar() } } @IBInspectable open var progress: Float = 0.5 { didSet { barLayer.strokeEnd = CGFloat(progress) } } // MARK: - Private properties fileprivate let backgroundLayer = CAShapeLayer() fileprivate let barLayer = CAShapeLayer() // MARK: - Initializers override public init(frame: CGRect) { super.init(frame: frame) setupViews() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupViews() } // MARK: - Lifecycle overrides override open func layoutSubviews() { super.layoutSubviews() updateBar() } // MARK: - Functions override func registerForNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(updateColors), name: Notification.Name.AppearanceColorsUpdated, object: nil) } override func updateColors() { super.updateColors() if let fillColorName = fillColorName, let color = UIColor(withName: fillColorName) { barLayer.strokeColor = color.cgColor } else { barLayer.strokeColor = fillColor.cgColor } if let fillBackgroundName = fillBackgroundColorName, let color = UIColor(withName: fillBackgroundName) { backgroundLayer.strokeColor = color.cgColor } else { backgroundLayer.strokeColor = fillBackgroundColor.cgColor } } } // MARK: - Private functions private extension SegmentedLine { func setupViews() { registerForNotifications() layoutIfNeeded() layer.addSublayer(backgroundLayer) layer.addSublayer(barLayer) barLayer.strokeStart = 0.0 barLayer.strokeEnd = CGFloat(progress) updateBar() updateColors() } func updateBar() { let start = CGPoint(x: bounds.minX, y: bounds.midY) let end = CGPoint(x: bounds.maxX, y: bounds.midY) let path = UIBezierPath() path.move(to: start) path.addLine(to: end) barLayer.path = path.cgPath backgroundLayer.path = path.cgPath let lineWidth = frame.height barLayer.lineWidth = lineWidth backgroundLayer.lineWidth = lineWidth let totalSpacing = segmentSpacing * CGFloat(segments - 1) let segmentLength = (frame.width - totalSpacing) / CGFloat(segments) let lineDashPattern = [NSNumber(value: Float(segmentLength)), NSNumber(value: Float(segmentSpacing))] backgroundLayer.lineDashPattern = lineDashPattern barLayer.lineDashPattern = lineDashPattern } }
mit
3b9536cf6f7b8c976d7ee62f2f72d204
25.304965
149
0.581019
4.958556
false
false
false
false
devedbox/AXBadgeView-Swift
Samples/ViewController.swift
1
4400
// // ViewController.swift // AXBadgeView-Swift // // Created by ai on 16/2/24. // Copyright © 2016年 devedbox. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var showsView: UIView! @IBOutlet weak var heightConstant: NSLayoutConstraint! @IBOutlet weak var widthConstant: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. showsView.showBadge(animated: true) showsView.badge.animator = .scale showsView.badge.masking = .roundingCorner([ .topLeft, .bottomRight, .topRight ] ) showsView.badge.strokeColor = .white DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(1.0 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { [unowned self]() -> Void in self.showsView.badge.offsets = .offsets(x: .exact(50.0), y: .exact(0.0)) self.showsView.badge.style = .new DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(2.5 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { [unowned self]() -> Void in self.heightConstant.constant += 50 self.widthConstant.constant -= 50 UIView.animate(withDuration: 0.5, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.7, options: UIView.AnimationOptions(rawValue: 7), animations: { [unowned self]() -> Void in self.view.layoutSubviews() }, completion: {[unowned self](finished: Bool) -> Void in DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(2.5 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { [unowned self]() -> Void in self.heightConstant.constant -= 100 self.widthConstant.constant += 100 UIView.animate(withDuration: 0.5, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.7, options: UIView.AnimationOptions(rawValue: 7), animations: { [unowned self]() -> Void in self.view.layoutSubviews() }, completion:{[unowned self](finished: Bool) -> Void in self.showsView.badge.offsets = .offsets(x: .greatest, y: .least) }) } }) } } navigationController?.navigationBar.setNeedsLayout() navigationController?.navigationBar.layoutIfNeeded() // MARK: - Left bar button item. navigationItem.leftBarButtonItem?.showBadge(animated: true) { // $0.animator = .breathing $0.style = .number(value: 2) $0.masking = .roundingCorner([ .topLeft, .bottomRight, .topRight ] ) } navigationItem.leftBarButtonItem?.badge.strokeColor = .white DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(2.5 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { [unowned self]() -> Void in self.navigationItem.leftBarButtonItem?.badge.style = .number(value: 3) DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(2.5 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { [unowned self]() -> Void in self.navigationItem.leftBarButtonItem?.badge.style = .text(value: "1000") } } // MARK: - Right bar button item. navigationItem.rightBarButtonItem?.showBadge(animated: true) // navigationItem.rightBarButtonItem?.badgeView.offsets = .offsets(x: .exact(30.0), y: .least) navigationItem.rightBarButtonItem?.badge.animator = .shaking // MARK: - Tab bar item. navigationController?.tabBarItem?.badge.style = .new // navigationController?.tabBarItem?.badgeView.offsets = .offsets(x: .exact(view.bounds.width/4+10), y: .exact(0.0)) navigationController?.tabBarItem?.badge.animator = .breathing navigationController?.tabBarItem?.showBadge(animated: true) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func badgeViewAction(_ sender: UIButton) { if showsView.badge.visible { showsView.clearBadge(animated: true) self.heightConstant.constant = 100 self.widthConstant.constant = 100 } else { showsView.showBadge(animated: true) } } }
mit
4c31f3a1c4553cccb5437430d4d595f1
41.278846
205
0.664771
4.132519
false
false
false
false
SASAbus/SASAbus-ios
SASAbus/Beacon/BeaconStorage.swift
1
5292
import Foundation import RealmSwift class BeaconStorage { private static var mCurrentTrip: CurrentTrip? private static var mCurrentBusStop: BusStopBeacon? private static var PREF_BEACON_CURRENT_TRIP = "pref_beacon_current_trip" private static var PREF_BEACON_CURRENT_BUS_STOP = "pref_beacon_current_bus_stop" private static var PREF_BUS_BEACON_MAP = "pref_bus_beacon_map" private static var PREF_BUS_BEACON_MAP_LAST = "pref_bus_beacon_map_last" private static var BEACON_MAP_TIMEOUT: Int64 = 240 * 1000 static func clear() { Log.error("Clearing beacon storage") UserDefaults.standard.removeObject(forKey: PREF_BEACON_CURRENT_TRIP) UserDefaults.standard.removeObject(forKey: PREF_BUS_BEACON_MAP) UserDefaults.standard.removeObject(forKey: PREF_BUS_BEACON_MAP_LAST) } // =================================== CURRENT TRIP ============================================ static var currentTrip: CurrentTrip? { get { if mCurrentTrip == nil { mCurrentTrip = readCurrentTrip() } return mCurrentTrip } set { mCurrentTrip = newValue } } static func saveCurrentTrip() { if mCurrentTrip == nil { Log.error("trip == null, cancelling notification") TripNotification.hide(trip: nil) UserDefaults.standard.removeObject(forKey: PREF_BEACON_CURRENT_TRIP) } else { let json = mCurrentTrip!.toJSONString(prettyPrint: false) UserDefaults.standard.set(json, forKey: PREF_BEACON_CURRENT_TRIP) } } private static func readCurrentTrip() -> CurrentTrip? { let json = UserDefaults.standard.string(forKey: PREF_BEACON_CURRENT_TRIP) if json == nil { return nil } if let trip = CurrentTrip(JSONString: json!) { trip.update() if trip.beacon.lastTrip == 0 { return nil } if trip.path.isEmpty || trip.times != nil && trip.times!.isEmpty { Log.error("Path or times empty for current trip, will reset...") trip.reset() } return trip } return nil } static func hasCurrentTrip() -> Bool { return currentTrip != nil } // ================================= CURRENT BUS STOP ========================================== static var currentBusStop: BusStopBeacon? { get { if mCurrentBusStop == nil { mCurrentBusStop = readCurrentBusStop() } return mCurrentBusStop } set { mCurrentBusStop = newValue } } static func saveCurrentBusStop() { if mCurrentBusStop == nil { UserDefaults.standard.removeObject(forKey: PREF_BEACON_CURRENT_BUS_STOP) } else { let json = mCurrentBusStop!.toJSONString(prettyPrint: false) Log.debug("Saving current bus stop: \(json)") UserDefaults.standard.set(json, forKey: PREF_BEACON_CURRENT_TRIP) } } private static func readCurrentBusStop() -> BusStopBeacon? { let json = UserDefaults.standard.string(forKey: PREF_BEACON_CURRENT_BUS_STOP) if json == nil { return nil } Log.debug("Reading current bus stop: \(json)") if let beacon = BusStopBeacon(JSONString: json!) { beacon.busStop = BusStopRealmHelper.getBusStop(id: beacon.id) return beacon } return nil } // ==================================== BEACON MAP ============================================= static func writeBeaconMap(map: [Int : BusBeacon]?) { if map == nil { UserDefaults.standard.removeObject(forKey: PREF_BUS_BEACON_MAP_LAST) } else { /*let returnDict = NSMutableDictionary() for (key, value) in map! { returnDict[String(key)] = value.toJsonString() }*/ UserDefaults.standard.set("", forKey: PREF_BUS_BEACON_MAP) UserDefaults.standard.set(Date().seconds(), forKey: PREF_BUS_BEACON_MAP_LAST) } } static func getBeaconMap() -> [Int : BusBeacon] { var lastMapSave: Int64 = 0 if UserDefaults.standard.integer(forKey: PREF_BUS_BEACON_MAP_LAST) != 0 { lastMapSave = Int64(UserDefaults.standard.integer(forKey: PREF_BUS_BEACON_MAP_LAST) * 1000) } if lastMapSave != 0 { let difference = Date().millis() - lastMapSave if difference < BEACON_MAP_TIMEOUT { let json = UserDefaults.standard.string(forKey: PREF_BUS_BEACON_MAP) if json == nil { return [:] } /*var oldDict = NSMutableDictionary(json: json!) as! [String : String] var newDict = [Int: BusBeacon]() for (key, value) in oldDict { newDict[Int(key)!] = BusBeacon(json: value) } return newDict*/ return [:] } else { saveCurrentTrip() } } return [:] } }
gpl-3.0
9bebf135bf5567d125e8618013410f64
28.564246
103
0.540627
4.566005
false
false
false
false
buyiyang/iosstar
iOSStar/Scenes/Market/CustomView/MarketFansCell.swift
3
1379
// // MarketFansCell.swift // iOSStar // // Created by J-bb on 17/5/18. // Copyright © 2017年 YunDian. All rights reserved. // import UIKit class MarketFansCell: UITableViewCell { @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var iconImaageView: UIImageView! @IBOutlet weak var topLabel: UILabel! @IBOutlet var price_lb: UILabel! override func awakeFromNib() { super.awakeFromNib() price_lb.textColor = UIColor.init(hexString: AppConst.Color.orange) // Initialization code } func setOrderFans(model:FansListModel,isBuy:Bool,index:Int) { let headerUrl = model.user?.headUrl ?? "" let name = model.user?.nickname ?? "" dateLabel.text = Date.yt_convertDateStrWithTimestempWithSecond(Int(model.trades!.positionTime), format: "MM-DD hh:mm:ss") iconImaageView.kf.setImage(with: URL(string: headerUrl),placeholder:UIImage.init(named: "\(index%8+1)") ) nameLabel.text = name topLabel.text = String.init(format: "%.2d", index + 1) price_lb.text = String(format: "%.2f元/秒", model.trades!.openPrice) } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
gpl-3.0
a221f2a1cad30e42a059f7f2282d9864
32.463415
129
0.657434
3.864789
false
false
false
false
jkolb/midnightbacon
MidnightBacon/Reddit/OAuth/OAuthAccessTokenMapper.swift
1
2383
// // OAuthAccessTokenMapper.swift // MidnightBacon // // Copyright (c) 2015 Justin Kolb - http://franticapparatus.net // // 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 Jasoom public class OAuthAccessTokenMapper { public init() { } public func map(json: JSON) throws -> OAuthAccessToken { return OAuthAccessToken( accessToken: json["access_token"].textValue ?? "", tokenType: json["token_type"].textValue ?? "", expiresIn: json["expires_in"].doubleValue ?? 0.0, scope: json["scope"].textValue ?? "", state: json["state"].textValue ?? "", refreshToken: json["refresh_token"].textValue ?? "", created: json["created"].dateValue ?? NSDate() ) } public func map(accessToken: OAuthAccessToken) throws -> NSData { var json = JSON.object() json["access_token"] = .String(accessToken.accessToken) json["token_type"] = .String(accessToken.tokenType) json["expires_in"] = .Number(accessToken.expiresIn) json["scope"] = .String(accessToken.scope) json["state"] = .String(accessToken.state) json["refresh_token"] = .String(accessToken.refreshToken) json["created"] = .Number(accessToken.created.timeIntervalSince1970) return try json.generateData() } }
mit
26d57f04e467b9ce2212534d4948193b
42.327273
80
0.683172
4.591522
false
false
false
false
mkaply/firefox-ios
content-blocker-lib-ios/src/ContentBlocker+Safelist.swift
7
3367
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import WebKit struct SafelistedDomains { var domainSet = Set<String>() { didSet { domainRegex = domainSet.compactMap { wildcardContentBlockerDomainToRegex(domain: "*" + $0) } } } private(set) var domainRegex = [String]() } extension ContentBlocker { func safelistFileURL() -> URL? { guard let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return nil } return dir.appendingPathComponent("safelist") } // Get the safelist domain array as a JSON fragment that can be inserted at the end of a blocklist. func safelistAsJSON() -> String { if safelistedDomains.domainSet.isEmpty { return "" } // Note that * is added to the front of domains, so foo.com becomes *foo.com let list = "'*" + safelistedDomains.domainSet.joined(separator: "','*") + "'" return ", {'action': { 'type': 'ignore-previous-rules' }, 'trigger': { 'url-filter': '.*', 'if-domain': [\(list)] }}".replacingOccurrences(of: "'", with: "\"") } func safelist(enable: Bool, url: URL, completion: (() -> Void)?) { guard let domain = safelistableDomain(fromUrl: url) else { return } if enable { safelistedDomains.domainSet.insert(domain) } else { safelistedDomains.domainSet.remove(domain) } updateSafelist(completion: completion) } func clearSafelist(completion: (() -> Void)?) { safelistedDomains.domainSet = Set<String>() updateSafelist(completion: completion) } private func updateSafelist(completion: (() -> Void)?) { removeAllRulesInStore { self.compileListsNotInStore { completion?() NotificationCenter.default.post(name: .contentBlockerTabSetupRequired, object: nil) } } guard let fileURL = safelistFileURL() else { return } if safelistedDomains.domainSet.isEmpty { try? FileManager.default.removeItem(at: fileURL) return } let list = safelistedDomains.domainSet.joined(separator: "\n") do { try list.write(to: fileURL, atomically: true, encoding: .utf8) } catch { print("Failed to save safelist file: \(error)") } } // Ensure domains used for safelisting are standardized by using this function. func safelistableDomain(fromUrl url: URL) -> String? { guard let domain = url.host, !domain.isEmpty else { return nil } return domain } func isSafelisted(url: URL) -> Bool { guard let domain = safelistableDomain(fromUrl: url) else { return false } return safelistedDomains.domainSet.contains(domain) } func readSafelistFile() -> [String]? { guard let fileURL = safelistFileURL() else { return nil } let text = try? String(contentsOf: fileURL, encoding: .utf8) if let text = text, !text.isEmpty { return text.components(separatedBy: .newlines) } return nil } }
mpl-2.0
c6b09fef6cbc7000595233586f1d99d5
33.010101
167
0.604693
4.267427
false
false
false
false
shaps80/Snaply
Snaply/Classes/Snap.swift
1
9869
// // Snap.swift // Pods // // Created by Shaps Mohsenin on 13/07/2016. // // import UIKit /* Snap can be used to provide 'paging' behaviour to a scrollView with arbitrarily sized content. This class also provides advanced snapping behaviour such as edge alignment. Snap is designed to completely plug-n-play. */ public final class Snap: NSObject, UIScrollViewDelegate { // MARK: Variables /// The scrollView this class should apply Snap to private weak var scrollView: UIScrollView! /// The original delegate to forward all delegate methods to so that existing behaviour is still handled private weak var originalDelegate: UIScrollViewDelegate? /// The supported direction private var snapDirection: SnapDirection /// The edge to snap to public private(set) var snapEdge: SnapEdge /// The current snap locations private var locations = [CGFloat]() // MARK: Lifecycle /** Initializes Snap with a scrollView - parameter scrollView: The scrollView to apply snapping to - parameter edge: The scrollView edge to snap to - parameter direction: The scrollView direction to apply snapping - parameter delegate: The original scrollView delegate. If nil, scrollView.delegate will be used - returns: A new instance of Snap */ public init(scrollView: UIScrollView, edge: SnapEdge = .min, direction: SnapDirection = .automatic, delegate: UIScrollViewDelegate? = nil) { self.scrollView = scrollView self.originalDelegate = delegate ?? scrollView.delegate self.snapDirection = direction self.snapEdge = edge super.init() scrollView.delegate = self } // MARK: Public functions /** Scrolls to the nearest snap point, relative to the specified offset - parameter offset: The content offset */ public func scrollToNearestSnapLocationForTargetContentOffset(offset: CGPoint) { let contentOffset = contentOffsetForTargetContentOffset(offset: offset) scrollView?.setContentOffset(contentOffset, animated: true) } /** Called when dragging stops inside the scrollView - parameter scrollView: The scrollView that was being dragged - parameter velocity: The velocity as dragging stopped - parameter targetContentOffset: The expected offset when the scrolling action decelerates to a stop */ public func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { guard locations.count > 0 else { return } let direction = supportedDirection() let offset = contentOffsetForTargetContentOffset(offset: targetContentOffset.pointee) let dragVelocity = (direction == .horizontal ? abs(velocity.x) : abs(velocity.y)) guard dragVelocity > 0 else { scrollView.setContentOffset(offset, animated: true) return } targetContentOffset.pointee = offset scrollView.setContentOffset(offset, animated: true) // fixes a flicker bug originalDelegate?.scrollViewWillEndDragging?(scrollView, withVelocity: velocity, targetContentOffset: targetContentOffset) } /** Returns the content offset for a target offset, taking into account the snap locations - parameter offset: The target offset (generally provided by the scrollView) - returns: The snap offset */ public func contentOffsetForTargetContentOffset(offset: CGPoint) -> CGPoint { let direction = supportedDirection() var next: CGFloat = 0 var prev: CGFloat = 0 var offsetValue = direction == .horizontal ? offset.x : offset.y let bounds = direction == .horizontal ? scrollView.bounds.width : scrollView.bounds.height guard offsetValue > 0 else { return CGPoint.zero } switch snapEdge { case .min: break case .mid: offsetValue += bounds / 2 case .max: offsetValue += bounds } if let location = locations.last, offsetValue > location { return direction == .horizontal ? CGPoint(x: location, y: 0) : CGPoint(x: 0, y: location) } for i in 0..<locations.count { next = locations[i] if next > offsetValue { let index = max(0, min(locations.count - 1, i - 1)) prev = locations[index] break } } next = min(next, maximumValue()) let spanValue = fabs(next - prev) let midValue = next - (spanValue / 2) if midValue <= 0 { return CGPoint.zero } var location: CGFloat = next if offsetValue < midValue { location = prev } switch snapEdge { case .min: break case .mid: location -= bounds / 2 case .max: location -= bounds } location = max(location, 0) // clamp our values return direction == .horizontal ? CGPoint(x: location, y: 0) : CGPoint(x: 0, y: location) } /** Returns the supported direction. When direction == .Automatic, and the scrollView is a collectionView using a flow layout, the direction property will be used to determine direction. If the scrollView is a tableView, then this will always return Vertical. In all other cases the direction will be determined by comparing the scrollView's contentSize and looking for the larger value. When no direction can be determined, this defaults to Vertical. - returns: The supported snap direction */ public func supportedDirection() -> SnapDirection { if scrollView is UITableView { return .vertical } guard snapDirection == .automatic else { return snapDirection } if let collectionView = scrollView as? UICollectionView, let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout { return layout.scrollDirection == .vertical ? .vertical : .horizontal } return scrollView.contentSize.width > scrollView.contentSize.height ? .horizontal : .vertical } // MARK: Public Setters /** Updates the snap locations - parameter locations: The new locations to apply - parameter realignImmediately: If true, the scrollView will automatically re-align to the nearest location based on its current offset. */ public func setSnapLocations(locations: [CGFloat], realignImmediately: Bool) { let offset = scrollView.contentOffset // Remove duplicates and sort the resulting values var locs = [CGFloat]() locs.append(0) locs.append(contentsOf: locations) self.locations = Set(locs).sorted() guard realignImmediately else { return } scrollToNearestSnapLocationForTargetContentOffset(offset: offset) } /** Updates the snap edge to use when snapping to a location - parameter edge: The edge to snap to - parameter realignImmediately: If true, the scrollView will automatically re-align to the nearest location based on its current offset. */ public func setSnapEdge(edge: SnapEdge, realignImmediately: Bool) { self.snapEdge = edge guard realignImmediately else { return } scrollToNearestSnapLocationForTargetContentOffset(offset: scrollView.contentOffset) } /** Updates the snap direction to apply snapping to - parameter direction: The direction to apply snapping behaviour - parameter realignImmediately: If true, the scrollView will automatically re-align to the nearest location based on its current offset. */ public func setSnapDirection(direction: SnapDirection, realignImmediately: Bool) { self.snapDirection = direction guard realignImmediately else { return } scrollToNearestSnapLocationForTargetContentOffset(offset: scrollView.contentOffset) } // MARK: Delegate forwarding public override func responds(to aSelector: Selector!) -> Bool { if super.responds(to: aSelector) { return true } if originalDelegate?.responds(to: aSelector) ?? false { return true } return false } public override func forwardingTarget(for aSelector: Selector!) -> Any? { if super.responds(to: aSelector) { return self } return originalDelegate } // MARK: Helpers private func maximumValue() -> CGFloat { switch snapEdge { case .min: return supportedDirection() == .horizontal ? scrollView.contentSize.width - scrollView.bounds.width : scrollView.contentSize.height - scrollView.bounds.height case .mid: return supportedDirection() == .horizontal ? scrollView.contentSize.width - scrollView.bounds.width / 2 : scrollView.contentSize.height - scrollView.bounds.height / 2 case .max: return supportedDirection() == .horizontal ? scrollView.contentSize.width : scrollView.contentSize.height } } // MARK: Debugging public override var description: String { return "\(super.description), Locations:\n\(locations)" } }
mit
5873a85ffb6aff22c3fe343c22ca4976
35.150183
452
0.629851
5.381134
false
false
false
false
ben-ng/swift
stdlib/public/core/Unmanaged.swift
2
8035
//===----------------------------------------------------------------------===// // // 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 https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A type for propagating an unmanaged object reference. /// /// When you use this type, you become partially responsible for /// keeping the object alive. @_fixed_layout public struct Unmanaged<Instance : AnyObject> { internal unowned(unsafe) var _value: Instance @_versioned @_transparent internal init(_private: Instance) { _value = _private } /// Unsafely turns an opaque C pointer into an unmanaged class reference. /// /// This operation does not change reference counts. /// /// let str: CFString = Unmanaged.fromOpaque(ptr).takeUnretainedValue() /// /// - Parameter value: An opaque C pointer. /// - Returns: An unmanaged class reference to `value`. @_transparent public static func fromOpaque(_ value: UnsafeRawPointer) -> Unmanaged { return Unmanaged(_private: unsafeBitCast(value, to: Instance.self)) } /// Unsafely converts an unmanaged class reference to a pointer. /// /// This operation does not change reference counts. /// /// let str0: CFString = "boxcar" /// let bits = Unmanaged.passUnretained(str0) /// let ptr = bits.toOpaque() /// /// - Returns: An opaque pointer to the value of this unmanaged reference. @_transparent public func toOpaque() -> UnsafeMutableRawPointer { return unsafeBitCast(_value, to: UnsafeMutableRawPointer.self) } /// Creates an unmanaged reference with an unbalanced retain. /// /// The instance passed as `value` will leak if nothing eventually balances /// the retain. /// /// This is useful when passing an object to an API which Swift does not know /// the ownership rules for, but you know that the API expects you to pass /// the object at +1. /// /// - Parameter value: A class instance. /// - Returns: An unmanaged reference to the object passed as `value`. @_transparent public static func passRetained(_ value: Instance) -> Unmanaged { return Unmanaged(_private: value).retain() } /// Creates an unmanaged reference without performing an unbalanced /// retain. /// /// This is useful when passing a reference to an API which Swift /// does not know the ownership rules for, but you know that the /// API expects you to pass the object at +0. /// /// CFArraySetValueAtIndex(.passUnretained(array), i, /// .passUnretained(object)) /// /// - Parameter value: A class instance. /// - Returns: An unmanaged reference to the object passed as `value`. @_transparent public static func passUnretained(_ value: Instance) -> Unmanaged { return Unmanaged(_private: value) } /// Gets the value of this unmanaged reference as a managed /// reference without consuming an unbalanced retain of it. /// /// This is useful when a function returns an unmanaged reference /// and you know that you're not responsible for releasing the result. /// /// - Returns: The object referenced by this `Unmanaged` instance. public func takeUnretainedValue() -> Instance { return _value } /// Gets the value of this unmanaged reference as a managed /// reference and consumes an unbalanced retain of it. /// /// This is useful when a function returns an unmanaged reference /// and you know that you're responsible for releasing the result. /// /// - Returns: The object referenced by this `Unmanaged` instance. public func takeRetainedValue() -> Instance { let result = _value release() return result } /// Gets the value of the unmanaged referenced as a managed reference without /// consuming an unbalanced retain of it and passes it to the closure. Asserts /// that there is some other reference ('the owning reference') to the /// instance referenced by the unmanaged reference that guarantees the /// lifetime of the instance for the duration of the /// '_withUnsafeGuaranteedRef' call. /// /// NOTE: You are responsible for ensuring this by making the owning /// reference's lifetime fixed for the duration of the /// '_withUnsafeGuaranteedRef' call. /// /// Violation of this will incur undefined behavior. /// /// A lifetime of a reference 'the instance' is fixed over a point in the /// programm if: /// /// * There exists a global variable that references 'the instance'. /// /// import Foundation /// var globalReference = Instance() /// func aFunction() { /// point() /// } /// /// Or if: /// /// * There is another managed reference to 'the instance' whose life time is /// fixed over the point in the program by means of 'withExtendedLifetime' /// dynamically closing over this point. /// /// var owningReference = Instance() /// ... /// withExtendedLifetime(owningReference) { /// point($0) /// } /// /// Or if: /// /// * There is a class, or struct instance ('owner') whose lifetime is fixed /// at the point and which has a stored property that references /// 'the instance' for the duration of the fixed lifetime of the 'owner'. /// /// class Owned { /// } /// /// class Owner { /// final var owned: Owned /// /// func foo() { /// withExtendedLifetime(self) { /// doSomething(...) /// } // Assuming: No stores to owned occur for the dynamic lifetime of /// // the withExtendedLifetime invocation. /// } /// /// func doSomething() { /// // both 'self' and 'owned''s lifetime is fixed over this point. /// point(self, owned) /// } /// } /// /// The last rule applies transitively through a chain of stored references /// and nested structs. /// /// Examples: /// /// var owningReference = Instance() /// ... /// withExtendedLifetime(owningReference) { /// let u = Unmanaged.passUnretained(owningReference) /// for i in 0 ..< 100 { /// u._withUnsafeGuaranteedRef { /// $0.doSomething() /// } /// } /// } /// /// class Owner { /// final var owned: Owned /// /// func foo() { /// withExtendedLifetime(self) { /// doSomething(Unmanaged.passUnretained(owned)) /// } /// } /// /// func doSomething(_ u : Unmanaged<Owned>) { /// u._withUnsafeGuaranteedRef { /// $0.doSomething() /// } /// } /// } public func _withUnsafeGuaranteedRef<Result>( _ body: (Instance) throws -> Result ) rethrows -> Result { let (guaranteedInstance, token) = Builtin.unsafeGuaranteed(_value) let result = try body(guaranteedInstance) Builtin.unsafeGuaranteedEnd(token) return result } /// Performs an unbalanced retain of the object. @_transparent public func retain() -> Unmanaged { Builtin.retain(_value) return self } /// Performs an unbalanced release of the object. @_transparent public func release() { Builtin.release(_value) } #if _runtime(_ObjC) /// Performs an unbalanced autorelease of the object. @_transparent public func autorelease() -> Unmanaged { Builtin.autorelease(_value) return self } #endif } extension Unmanaged { @available(*, unavailable, message:"use 'fromOpaque(_: UnsafeRawPointer)' instead") public static func fromOpaque(_ value: OpaquePointer) -> Unmanaged { Builtin.unreachable() } @available(*, unavailable, message:"use 'toOpaque() -> UnsafeRawPointer' instead") public func toOpaque() -> OpaquePointer { Builtin.unreachable() } }
apache-2.0
ec7a8ded5b1126f24351af28f7f3c9f9
31.795918
80
0.632607
4.620472
false
false
false
false
sigito/material-components-ios
components/TextFields/tests/unit/TextFieldControllerClassPropertiesTests.swift
1
21307
/* Copyright 2017-present the Material Components for iOS 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. */ // swiftlint:disable function_body_length // swiftlint:disable type_body_length import XCTest import MaterialComponents.MaterialPalettes import MaterialComponents.MaterialTextFields import MaterialComponents.MaterialTypography class TextFieldControllerClassPropertiesTests: XCTestCase { override func tearDown() { super.tearDown() MDCTextInputControllerUnderline.roundedCornersDefault = [] MDCTextInputControllerUnderline.errorColorDefault = nil MDCTextInputControllerUnderline.inlinePlaceholderColorDefault = nil MDCTextInputControllerUnderline.mdc_adjustsFontForContentSizeCategoryDefault = false MDCTextInputControllerUnderline.activeColorDefault = nil MDCTextInputControllerUnderline.normalColorDefault = nil MDCTextInputControllerUnderline.disabledColorDefault = nil MDCTextInputControllerUnderline.underlineViewModeDefault = .whileEditing MDCTextInputControllerUnderline.leadingUnderlineLabelTextColorDefault = nil MDCTextInputControllerUnderline.trailingUnderlineLabelTextColorDefault = nil MDCTextInputControllerUnderline.inlinePlaceholderFontDefault = nil MDCTextInputControllerUnderline.leadingUnderlineLabelFontDefault = nil MDCTextInputControllerUnderline.trailingUnderlineLabelFontDefault = nil MDCTextInputControllerUnderline.floatingPlaceholderNormalColorDefault = nil MDCTextInputControllerUnderline.floatingPlaceholderScaleDefault = 0.75 MDCTextInputControllerUnderline.isFloatingEnabledDefault = true MDCTextInputControllerFullWidth.errorColorDefault = nil MDCTextInputControllerFullWidth.inlinePlaceholderColorDefault = nil MDCTextInputControllerFullWidth.mdc_adjustsFontForContentSizeCategoryDefault = false MDCTextInputControllerFullWidth.activeColorDefault = nil MDCTextInputControllerFullWidth.normalColorDefault = nil MDCTextInputControllerFullWidth.disabledColorDefault = nil MDCTextInputControllerFullWidth.underlineViewModeDefault = .never MDCTextInputControllerFullWidth.leadingUnderlineLabelTextColorDefault = nil MDCTextInputControllerFullWidth.trailingUnderlineLabelTextColorDefault = nil MDCTextInputControllerFullWidth.inlinePlaceholderFontDefault = nil MDCTextInputControllerFullWidth.leadingUnderlineLabelFontDefault = nil MDCTextInputControllerFullWidth.trailingUnderlineLabelFontDefault = nil } func testUnderline() { // Test the values of the class properties. XCTAssertEqual(MDCTextInputControllerUnderline.errorColorDefault, MDCPalette.red.accent400) XCTAssertEqual(MDCTextInputControllerUnderline.inlinePlaceholderColorDefault, UIColor(white: 0, alpha: CGFloat(Float(0.54)))) XCTAssertEqual(MDCTextInputControllerUnderline.mdc_adjustsFontForContentSizeCategoryDefault, false) XCTAssertEqual(MDCTextInputControllerUnderline.activeColorDefault, MDCPalette.blue.accent700) XCTAssertEqual(MDCTextInputControllerUnderline.normalColorDefault, .lightGray) XCTAssertEqual(MDCTextInputControllerUnderline.underlineHeightActiveDefault, 2) XCTAssertEqual(MDCTextInputControllerUnderline.underlineHeightNormalDefault, 1) XCTAssertEqual(MDCTextInputControllerUnderline.underlineViewModeDefault, .whileEditing) XCTAssertEqual(MDCTextInputControllerUnderline.leadingUnderlineLabelTextColorDefault, UIColor(white: 0, alpha: CGFloat(Float(0.54)))) XCTAssertEqual(MDCTextInputControllerUnderline.trailingUnderlineLabelTextColorDefault, UIColor(white: 0, alpha: CGFloat(Float(0.54)))) XCTAssertEqual(MDCTextInputControllerUnderline.leadingUnderlineLabelTextColorDefault, MDCTextInputControllerUnderline.inlinePlaceholderColorDefault) XCTAssertEqual(MDCTextInputControllerUnderline.trailingUnderlineLabelTextColorDefault, MDCTextInputControllerUnderline.inlinePlaceholderColorDefault) XCTAssertEqual(MDCTextInputControllerUnderline.inlinePlaceholderFontDefault, UIFont.mdc_standardFont(forMaterialTextStyle: .body1)) XCTAssertEqual(MDCTextInputControllerUnderline.leadingUnderlineLabelFontDefault, MDCTextInputControllerUnderline.trailingUnderlineLabelFontDefault) XCTAssertEqual(MDCTextInputControllerUnderline.leadingUnderlineLabelFontDefault, UIFont.mdc_standardFont(forMaterialTextStyle: .caption)) // Default specific properties XCTAssertEqual(MDCTextInputControllerUnderline.floatingPlaceholderNormalColorDefault, UIColor(white: 0, alpha: CGFloat(Float(0.54)))) XCTAssertEqual(Float(MDCTextInputControllerUnderline.floatingPlaceholderScaleDefault), 0.75) XCTAssertEqual(MDCTextInputControllerUnderline.isFloatingEnabledDefault, true) XCTAssertEqual(MDCTextInputControllerUnderline.roundedCornersDefault, []) // Test the use of the class properties. let textField = MDCTextField() var controller = MDCTextInputControllerUnderline(textInput: textField) XCTAssertEqual(controller.errorColor, MDCTextInputControllerUnderline.errorColorDefault) XCTAssertEqual(controller.inlinePlaceholderColor, MDCTextInputControllerUnderline.inlinePlaceholderColorDefault) XCTAssertEqual(controller.mdc_adjustsFontForContentSizeCategory, MDCTextInputControllerUnderline.mdc_adjustsFontForContentSizeCategoryDefault) XCTAssertEqual(controller.activeColor, MDCTextInputControllerUnderline.activeColorDefault) XCTAssertEqual(controller.normalColor, MDCTextInputControllerUnderline.normalColorDefault) XCTAssertEqual(controller.underlineHeightActive, MDCTextInputControllerUnderline.underlineHeightActiveDefault) XCTAssertEqual(controller.underlineHeightNormal, MDCTextInputControllerUnderline.underlineHeightNormalDefault) XCTAssertEqual(controller.underlineViewMode, MDCTextInputControllerUnderline.underlineViewModeDefault) XCTAssertEqual(controller.leadingUnderlineLabelTextColor, MDCTextInputControllerUnderline.leadingUnderlineLabelTextColorDefault) XCTAssertEqual(controller.trailingUnderlineLabelTextColor, MDCTextInputControllerUnderline.trailingUnderlineLabelTextColorDefault) XCTAssertEqual(controller.inlinePlaceholderFont, MDCTextInputControllerUnderline.inlinePlaceholderFontDefault) XCTAssertEqual(controller.leadingUnderlineLabelFont, MDCTextInputControllerUnderline.leadingUnderlineLabelFontDefault) XCTAssertEqual(controller.trailingUnderlineLabelFont, MDCTextInputControllerUnderline.trailingUnderlineLabelFontDefault) // Default specific properties XCTAssertEqual(controller.floatingPlaceholderNormalColor, MDCTextInputControllerUnderline.floatingPlaceholderNormalColorDefault) XCTAssertEqual(controller.isFloatingEnabled, MDCTextInputControllerUnderline.isFloatingEnabledDefault) XCTAssertEqual(controller.roundedCorners, MDCTextInputControllerUnderline.roundedCornersDefault) // Test the changes to the class properties. MDCTextInputControllerUnderline.errorColorDefault = .green XCTAssertEqual(MDCTextInputControllerUnderline.errorColorDefault, .green) MDCTextInputControllerUnderline.inlinePlaceholderColorDefault = .orange XCTAssertEqual(MDCTextInputControllerUnderline.inlinePlaceholderColorDefault, .orange) MDCTextInputControllerUnderline.mdc_adjustsFontForContentSizeCategoryDefault = false XCTAssertEqual(MDCTextInputControllerUnderline.mdc_adjustsFontForContentSizeCategoryDefault, false) MDCTextInputControllerUnderline.activeColorDefault = .purple XCTAssertEqual(MDCTextInputControllerUnderline.activeColorDefault, .purple) MDCTextInputControllerUnderline.normalColorDefault = .white XCTAssertEqual(MDCTextInputControllerUnderline.normalColorDefault, .white) MDCTextInputControllerUnderline.underlineHeightActiveDefault = 11 XCTAssertEqual(MDCTextInputControllerUnderline.underlineHeightActiveDefault, 11) MDCTextInputControllerUnderline.underlineHeightNormalDefault = 5 XCTAssertEqual(MDCTextInputControllerUnderline.underlineHeightNormalDefault, 5) MDCTextInputControllerUnderline.underlineViewModeDefault = .unlessEditing XCTAssertEqual(MDCTextInputControllerUnderline.underlineViewModeDefault, .unlessEditing) MDCTextInputControllerUnderline.leadingUnderlineLabelTextColorDefault = .blue XCTAssertEqual(MDCTextInputControllerUnderline.leadingUnderlineLabelTextColorDefault, .blue) MDCTextInputControllerUnderline.trailingUnderlineLabelTextColorDefault = .white XCTAssertEqual(MDCTextInputControllerUnderline.trailingUnderlineLabelTextColorDefault, .white) MDCTextInputControllerUnderline.inlinePlaceholderFontDefault = UIFont.systemFont(ofSize: 4) XCTAssertEqual(MDCTextInputControllerUnderline.inlinePlaceholderFontDefault, UIFont.systemFont(ofSize: 4)) MDCTextInputControllerUnderline.inlinePlaceholderFontDefault = UIFont.systemFont(ofSize: 5) XCTAssertEqual(MDCTextInputControllerUnderline.inlinePlaceholderFontDefault, UIFont.systemFont(ofSize: 5)) MDCTextInputControllerUnderline.inlinePlaceholderFontDefault = UIFont.systemFont(ofSize: 6) XCTAssertEqual(MDCTextInputControllerUnderline.inlinePlaceholderFontDefault, UIFont.systemFont(ofSize: 6)) // Default specific properties MDCTextInputControllerUnderline.floatingPlaceholderNormalColorDefault = .red XCTAssertEqual(MDCTextInputControllerUnderline.floatingPlaceholderNormalColorDefault, .red) MDCTextInputControllerUnderline.floatingPlaceholderScaleDefault = 0.6 XCTAssertEqual(Float(MDCTextInputControllerUnderline.floatingPlaceholderScaleDefault), 0.6) MDCTextInputControllerUnderline.isFloatingEnabledDefault = false XCTAssertEqual(MDCTextInputControllerUnderline.isFloatingEnabledDefault, false) MDCTextInputControllerUnderline.roundedCornersDefault = [.bottomRight] XCTAssertEqual(MDCTextInputControllerUnderline.roundedCornersDefault, [.bottomRight]) // Test that the changes to the class properties can propogate to an instance. controller = MDCTextInputControllerUnderline(textInput: textField) XCTAssertEqual(controller.errorColor, MDCTextInputControllerUnderline.errorColorDefault) XCTAssertEqual(controller.inlinePlaceholderColor, MDCTextInputControllerUnderline.inlinePlaceholderColorDefault) XCTAssertEqual(controller.mdc_adjustsFontForContentSizeCategory, MDCTextInputControllerUnderline.mdc_adjustsFontForContentSizeCategoryDefault) XCTAssertEqual(controller.activeColor, MDCTextInputControllerUnderline.activeColorDefault) XCTAssertEqual(controller.normalColor, MDCTextInputControllerUnderline.normalColorDefault) XCTAssertEqual(controller.underlineHeightActive, MDCTextInputControllerUnderline.underlineHeightActiveDefault) XCTAssertEqual(controller.underlineHeightNormal, MDCTextInputControllerUnderline.underlineHeightNormalDefault) XCTAssertEqual(controller.underlineViewMode, MDCTextInputControllerUnderline.underlineViewModeDefault) XCTAssertEqual(controller.leadingUnderlineLabelTextColor, MDCTextInputControllerUnderline.leadingUnderlineLabelTextColorDefault) XCTAssertEqual(controller.trailingUnderlineLabelTextColor, MDCTextInputControllerUnderline.trailingUnderlineLabelTextColorDefault) XCTAssertEqual(controller.inlinePlaceholderFont, MDCTextInputControllerUnderline.inlinePlaceholderFontDefault) XCTAssertEqual(controller.leadingUnderlineLabelFont, MDCTextInputControllerUnderline.leadingUnderlineLabelFontDefault) XCTAssertEqual(controller.trailingUnderlineLabelFont, MDCTextInputControllerUnderline.trailingUnderlineLabelFontDefault) // Default specific properties XCTAssertEqual(controller.floatingPlaceholderNormalColor, MDCTextInputControllerUnderline.floatingPlaceholderNormalColorDefault) XCTAssertEqual(controller.isFloatingEnabled, MDCTextInputControllerUnderline.isFloatingEnabledDefault) XCTAssertEqual(controller.roundedCorners, MDCTextInputControllerUnderline.roundedCornersDefault) } func testFullWidth() { // Test the values of the class properties. XCTAssertEqual(MDCTextInputControllerFullWidth.disabledColorDefault, .clear) XCTAssertEqual(MDCTextInputControllerFullWidth.errorColorDefault, MDCPalette.red.accent400) XCTAssertEqual(MDCTextInputControllerFullWidth.inlinePlaceholderColorDefault, UIColor(white: 0, alpha: CGFloat(Float(0.54)))) XCTAssertEqual(MDCTextInputControllerFullWidth.mdc_adjustsFontForContentSizeCategoryDefault, false) XCTAssertEqual(MDCTextInputControllerFullWidth.activeColorDefault, .clear) XCTAssertEqual(MDCTextInputControllerFullWidth.normalColorDefault, .clear) XCTAssertEqual(MDCTextInputControllerFullWidth.underlineHeightActiveDefault, 0) XCTAssertEqual(MDCTextInputControllerFullWidth.underlineHeightNormalDefault, 0) XCTAssertEqual(MDCTextInputControllerFullWidth.underlineViewModeDefault, .never) XCTAssertEqual(MDCTextInputControllerFullWidth.leadingUnderlineLabelTextColorDefault, .clear) XCTAssertEqual(MDCTextInputControllerFullWidth.trailingUnderlineLabelTextColorDefault, UIColor(white: 0, alpha: CGFloat(Float(0.54)))) XCTAssertEqual(MDCTextInputControllerFullWidth.inlinePlaceholderFontDefault, UIFont.mdc_standardFont(forMaterialTextStyle: .body1)) XCTAssertEqual(MDCTextInputControllerFullWidth.leadingUnderlineLabelFontDefault, MDCTextInputControllerFullWidth.trailingUnderlineLabelFontDefault) XCTAssertEqual(MDCTextInputControllerFullWidth.leadingUnderlineLabelFontDefault, UIFont.mdc_standardFont(forMaterialTextStyle: .caption)) // Test the use of the class properties. let textField = MDCTextField() var controller = MDCTextInputControllerFullWidth(textInput: textField) XCTAssertEqual(controller.disabledColor, .clear) XCTAssertEqual(controller.errorColor, MDCTextInputControllerFullWidth.errorColorDefault) XCTAssertEqual(controller.inlinePlaceholderColor, MDCTextInputControllerFullWidth.inlinePlaceholderColorDefault) XCTAssertEqual(controller.mdc_adjustsFontForContentSizeCategory, MDCTextInputControllerFullWidth.mdc_adjustsFontForContentSizeCategoryDefault) XCTAssertEqual(controller.activeColor, MDCTextInputControllerFullWidth.activeColorDefault) XCTAssertEqual(controller.normalColor, MDCTextInputControllerFullWidth.normalColorDefault) XCTAssertEqual(controller.underlineHeightActive, MDCTextInputControllerFullWidth.underlineHeightActiveDefault) XCTAssertEqual(controller.underlineHeightNormal, MDCTextInputControllerFullWidth.underlineHeightNormalDefault) XCTAssertEqual(controller.underlineViewMode, MDCTextInputControllerFullWidth.underlineViewModeDefault) XCTAssertEqual(controller.leadingUnderlineLabelTextColor, MDCTextInputControllerFullWidth.leadingUnderlineLabelTextColorDefault) XCTAssertEqual(controller.trailingUnderlineLabelTextColor, MDCTextInputControllerFullWidth.trailingUnderlineLabelTextColorDefault) XCTAssertEqual(controller.inlinePlaceholderFont, MDCTextInputControllerFullWidth.inlinePlaceholderFontDefault) XCTAssertEqual(controller.leadingUnderlineLabelFont, MDCTextInputControllerFullWidth.leadingUnderlineLabelFontDefault) XCTAssertEqual(controller.trailingUnderlineLabelFont, MDCTextInputControllerFullWidth.trailingUnderlineLabelFontDefault) // Test the changes to the class properties. MDCTextInputControllerFullWidth.disabledColorDefault = .red XCTAssertNotEqual(MDCTextInputControllerFullWidth.disabledColorDefault, .red) MDCTextInputControllerFullWidth.errorColorDefault = .green XCTAssertEqual(MDCTextInputControllerFullWidth.errorColorDefault, .green) MDCTextInputControllerFullWidth.inlinePlaceholderColorDefault = .orange XCTAssertEqual(MDCTextInputControllerFullWidth.inlinePlaceholderColorDefault, .orange) MDCTextInputControllerFullWidth.mdc_adjustsFontForContentSizeCategoryDefault = false XCTAssertEqual(MDCTextInputControllerFullWidth.mdc_adjustsFontForContentSizeCategoryDefault, false) MDCTextInputControllerFullWidth.activeColorDefault = .purple XCTAssertEqual(MDCTextInputControllerFullWidth.activeColorDefault, .clear) MDCTextInputControllerFullWidth.normalColorDefault = .white XCTAssertEqual(MDCTextInputControllerFullWidth.normalColorDefault, .clear) MDCTextInputControllerFullWidth.underlineHeightActiveDefault = 9 XCTAssertEqual(MDCTextInputControllerFullWidth.underlineHeightActiveDefault, 0) MDCTextInputControllerFullWidth.underlineHeightNormalDefault = 17 XCTAssertEqual(MDCTextInputControllerFullWidth.underlineHeightNormalDefault, 0) MDCTextInputControllerFullWidth.underlineViewModeDefault = .unlessEditing XCTAssertEqual(MDCTextInputControllerFullWidth.underlineViewModeDefault, .never) MDCTextInputControllerFullWidth.leadingUnderlineLabelTextColorDefault = .brown XCTAssertEqual(MDCTextInputControllerFullWidth.leadingUnderlineLabelTextColorDefault, .clear) MDCTextInputControllerFullWidth.trailingUnderlineLabelTextColorDefault = .cyan XCTAssertEqual(MDCTextInputControllerFullWidth.trailingUnderlineLabelTextColorDefault, .cyan) MDCTextInputControllerFullWidth.inlinePlaceholderFontDefault = UIFont.systemFont(ofSize: 4) XCTAssertEqual(MDCTextInputControllerFullWidth.inlinePlaceholderFontDefault, UIFont.systemFont(ofSize: 4)) MDCTextInputControllerFullWidth.inlinePlaceholderFontDefault = UIFont.systemFont(ofSize: 5) XCTAssertEqual(MDCTextInputControllerFullWidth.inlinePlaceholderFontDefault, UIFont.systemFont(ofSize: 5)) MDCTextInputControllerFullWidth.inlinePlaceholderFontDefault = UIFont.systemFont(ofSize: 6) XCTAssertEqual(MDCTextInputControllerFullWidth.inlinePlaceholderFontDefault, UIFont.systemFont(ofSize: 6)) // Test the changes to the class properties can propogate to an instance. controller = MDCTextInputControllerFullWidth(textInput: textField) XCTAssertEqual(controller.disabledColor, .clear) XCTAssertEqual(controller.errorColor, MDCTextInputControllerFullWidth.errorColorDefault) XCTAssertEqual(controller.inlinePlaceholderColor, MDCTextInputControllerFullWidth.inlinePlaceholderColorDefault) XCTAssertEqual(controller.mdc_adjustsFontForContentSizeCategory, MDCTextInputControllerFullWidth.mdc_adjustsFontForContentSizeCategoryDefault) XCTAssertEqual(controller.activeColor, MDCTextInputControllerFullWidth.activeColorDefault) XCTAssertEqual(controller.normalColor, MDCTextInputControllerFullWidth.normalColorDefault) XCTAssertEqual(controller.underlineHeightActive, MDCTextInputControllerFullWidth.underlineHeightActiveDefault) XCTAssertEqual(controller.underlineHeightNormal, MDCTextInputControllerFullWidth.underlineHeightNormalDefault) XCTAssertEqual(controller.underlineViewMode, MDCTextInputControllerFullWidth.underlineViewModeDefault) XCTAssertEqual(controller.leadingUnderlineLabelTextColor, MDCTextInputControllerFullWidth.leadingUnderlineLabelTextColorDefault) XCTAssertEqual(controller.trailingUnderlineLabelTextColor, MDCTextInputControllerFullWidth.trailingUnderlineLabelTextColorDefault) XCTAssertEqual(controller.inlinePlaceholderFont, MDCTextInputControllerFullWidth.inlinePlaceholderFontDefault) XCTAssertEqual(controller.leadingUnderlineLabelFont, MDCTextInputControllerFullWidth.leadingUnderlineLabelFontDefault) XCTAssertEqual(controller.trailingUnderlineLabelFont, MDCTextInputControllerFullWidth.trailingUnderlineLabelFontDefault) } }
apache-2.0
df15fb304c1f5d18291a2e17fa348417
57.057221
103
0.810156
6.875444
false
false
false
false
josve05a/wikipedia-ios
WMF Framework/ReadingListsSyncOperation.swift
3
48510
internal enum ReadingListsOperationError: Error { case cancelled } internal class ReadingListsSyncOperation: ReadingListsOperation { var syncedReadingListsCount = 0 var syncedReadingListEntriesCount = 0 override func execute() { syncedReadingListsCount = 0 syncedReadingListEntriesCount = 0 DispatchQueue.main.async { self.dataStore.performBackgroundCoreDataOperation { (moc) in do { try self.executeSync(on: moc) } catch let error { DDLogError("error during sync operation: \(error)") do { if moc.hasChanges { try moc.save() } } catch let error { DDLogError("error during sync save: \(error)") } if let readingListError = error as? APIReadingListError, readingListError == .notSetup { DispatchQueue.main.async { self.readingListsController.setSyncEnabled(false, shouldDeleteLocalLists: false, shouldDeleteRemoteLists: false) self.finish() } } else if let readingListError = error as? APIReadingListError, readingListError == .needsFullSync { let readingListsController = self.readingListsController DispatchQueue.main.async { guard let oldState = readingListsController?.syncState else { return } var newState = oldState newState.insert(.needsSync) if newState != oldState { readingListsController?.syncState = newState } self.finish() DispatchQueue.main.async { readingListsController?.sync() } } } else if let readingListError = error as? ReadingListsOperationError, readingListError == .cancelled { self.apiController.cancelAllTasks() self.finish() } else { self.finish(with: error) } } } } } func executeSync(on moc: NSManagedObjectContext) throws { let syncEndpointsAreAvailable = moc.wmf_isSyncRemotelyEnabled let rawSyncState = moc.wmf_numberValue(forKey: WMFReadingListSyncStateKey)?.int64Value ?? 0 var syncState = ReadingListSyncState(rawValue: rawSyncState) let taskGroup = WMFTaskGroup() let hasValidLocalCredentials = apiController.session.hasValidCentralAuthCookies(for: Configuration.current.wikipediaCookieDomain) if syncEndpointsAreAvailable && syncState.contains(.needsRemoteDisable) && hasValidLocalCredentials { var disableReadingListsError: Error? = nil taskGroup.enter() apiController.teardownReadingLists(completion: { (error) in disableReadingListsError = error taskGroup.leave() }) taskGroup.wait() if let error = disableReadingListsError { try moc.save() self.finish(with: error) return } else { syncState.remove(.needsRemoteDisable) moc.wmf_setValue(NSNumber(value: syncState.rawValue), forKey: WMFReadingListSyncStateKey) try moc.save() } } if syncState.contains(.needsRandomLists) { try executeRandomListPopulation(in: moc) syncState.remove(.needsRandomLists) moc.wmf_setValue(NSNumber(value: syncState.rawValue), forKey: WMFReadingListSyncStateKey) try moc.save() } if syncState.contains(.needsRandomEntries) { try executeRandomArticlePopulation(in: moc) syncState.remove(.needsRandomEntries) moc.wmf_setValue(NSNumber(value: syncState.rawValue), forKey: WMFReadingListSyncStateKey) try moc.save() } if syncState.contains(.needsLocalReset) { try moc.wmf_batchProcessObjects(handler: { (readingListEntry: ReadingListEntry) in readingListEntry.readingListEntryID = nil readingListEntry.isUpdatedLocally = true readingListEntry.errorCode = nil guard !self.isCancelled else { throw ReadingListsOperationError.cancelled } }) try moc.wmf_batchProcessObjects(handler: { (readingList: ReadingList) in readingList.readingListID = nil readingList.isUpdatedLocally = true readingList.errorCode = nil guard !self.isCancelled else { throw ReadingListsOperationError.cancelled } }) syncState.remove(.needsLocalReset) moc.wmf_setValue(NSNumber(value: syncState.rawValue), forKey: WMFReadingListSyncStateKey) try moc.save() moc.reset() } if syncState.contains(.needsLocalListClear) { try moc.wmf_batchProcess(matchingPredicate: NSPredicate(format: "isDefault != YES"), handler: { (lists: [ReadingList]) in try self.readingListsController.markLocalDeletion(for: lists) guard !self.isCancelled else { throw ReadingListsOperationError.cancelled } }) syncState.remove(.needsLocalListClear) moc.wmf_setValue(NSNumber(value: syncState.rawValue), forKey: WMFReadingListSyncStateKey) try moc.save() } if syncState.contains(.needsLocalArticleClear) { try moc.wmf_batchProcess(matchingPredicate: NSPredicate(format: "savedDate != NULL"), handler: { (articles: [WMFArticle]) in self.readingListsController.unsave(articles, in: moc) guard !self.isCancelled else { throw ReadingListsOperationError.cancelled } }) syncState.remove(.needsLocalArticleClear) moc.wmf_setValue(NSNumber(value: syncState.rawValue), forKey: WMFReadingListSyncStateKey) try moc.save() } let localSyncOnly = { try self.executeLocalOnlySync(on: moc) try moc.save() self.finish() } guard hasValidLocalCredentials else { try localSyncOnly() return } // local only sync guard syncState != [] else { if syncEndpointsAreAvailable { // make an update call to see if the user has enabled sync on another device var updateError: Error? = nil taskGroup.enter() let iso8601String = DateFormatter.wmf_iso8601().string(from: Date()) apiController.updatedListsAndEntries(since: iso8601String, completion: { (lists, entries, since, error) in updateError = error taskGroup.leave() }) taskGroup.wait() if updateError == nil { DispatchQueue.main.async { self.readingListsController.setSyncEnabled(true, shouldDeleteLocalLists: false, shouldDeleteRemoteLists: false) self.readingListsController.postReadingListsServerDidConfirmSyncWasEnabledForAccountNotification(true) self.finish() } } else { if let apiError = updateError as? APIReadingListError, apiError == .notSetup { readingListsController.postReadingListsServerDidConfirmSyncWasEnabledForAccountNotification(false) } try localSyncOnly() } } else { readingListsController.postReadingListsServerDidConfirmSyncWasEnabledForAccountNotification(false) try localSyncOnly() } return } guard syncEndpointsAreAvailable else { self.finish() return } if syncState.contains(.needsRemoteEnable) { var enableReadingListsError: Error? = nil taskGroup.enter() apiController.setupReadingLists(completion: { (error) in enableReadingListsError = error taskGroup.leave() }) taskGroup.wait() if let error = enableReadingListsError { try moc.save() finish(with: error) return } else { syncState.remove(.needsRemoteEnable) moc.wmf_setValue(NSNumber(value: syncState.rawValue), forKey: WMFReadingListSyncStateKey) self.readingListsController.postReadingListsServerDidConfirmSyncWasEnabledForAccountNotification(true) try moc.save() } } if syncState.contains(.needsSync) { try executeFullSync(on: moc) syncState.remove(.needsSync) syncState.insert(.needsUpdate) } else if syncState.contains(.needsUpdate) { try executeUpdate(on: moc) } moc.wmf_setValue(NSNumber(value: syncState.rawValue), forKey: WMFReadingListSyncStateKey) if moc.hasChanges { try moc.save() } finish() } func executeLocalOnlySync(on moc: NSManagedObjectContext) throws { try moc.wmf_batchProcessObjects(matchingPredicate: NSPredicate(format: "isDeletedLocally == YES"), handler: { (list: ReadingList) in moc.delete(list) }) try moc.wmf_batchProcessObjects(matchingPredicate: NSPredicate(format: "isDeletedLocally == YES"), handler: { (entry: ReadingListEntry) in moc.delete(entry) }) } func executeFullSync(on moc: NSManagedObjectContext) throws { let taskGroup = WMFTaskGroup() var allAPIReadingLists: [APIReadingList] = [] var getAllAPIReadingListsError: Error? var nextSince: String? = nil taskGroup.enter() readingListsController.apiController.getAllReadingLists { (readingLists, since, error) in getAllAPIReadingListsError = error allAPIReadingLists = readingLists nextSince = since taskGroup.leave() } taskGroup.wait() guard !isCancelled else { throw ReadingListsOperationError.cancelled } if let getAllAPIReadingListsError = getAllAPIReadingListsError { throw getAllAPIReadingListsError } let group = WMFTaskGroup() syncedReadingListsCount += try createOrUpdate(remoteReadingLists: allAPIReadingLists, deleteMissingLocalLists: true, inManagedObjectContext: moc) // Get all entries var remoteEntriesByReadingListID: [Int64: [APIReadingListEntry]] = [:] for remoteReadingList in allAPIReadingLists { group.enter() apiController.getAllEntriesForReadingListWithID(readingListID: remoteReadingList.id, completion: { (entries, error) in if let error = error { DDLogError("Error fetching entries for reading list with ID \(remoteReadingList.id): \(error)") } else { remoteEntriesByReadingListID[remoteReadingList.id] = entries } group.leave() }) } group.wait() guard !isCancelled else { throw ReadingListsOperationError.cancelled } for (readingListID, remoteReadingListEntries) in remoteEntriesByReadingListID { syncedReadingListEntriesCount += try createOrUpdate(remoteReadingListEntries: remoteReadingListEntries, for: readingListID, deleteMissingLocalEntries: true, inManagedObjectContext: moc) } if let since = nextSince { moc.wmf_setValue(since as NSString, forKey: WMFReadingListUpdateKey) } if moc.hasChanges { try moc.save() } try processLocalUpdates(in: moc) guard moc.hasChanges else { return } try moc.save() } func executeUpdate(on moc: NSManagedObjectContext) throws { try processLocalUpdates(in: moc) if moc.hasChanges { try moc.save() } guard let since = moc.wmf_stringValue(forKey: WMFReadingListUpdateKey) else { return } var updatedLists: [APIReadingList] = [] var updatedEntries: [APIReadingListEntry] = [] var updateError: Error? var nextSince: String? let taskGroup = WMFTaskGroup() taskGroup.enter() apiController.updatedListsAndEntries(since: since, completion: { (lists, entries, since, error) in updateError = error updatedLists = lists updatedEntries = entries nextSince = since taskGroup.leave() }) taskGroup.wait() guard !isCancelled else { throw ReadingListsOperationError.cancelled } if let error = updateError { throw error } syncedReadingListsCount += try createOrUpdate(remoteReadingLists: updatedLists, inManagedObjectContext: moc) syncedReadingListEntriesCount += try createOrUpdate(remoteReadingListEntries: updatedEntries, inManagedObjectContext: moc) if let since = nextSince { moc.wmf_setValue(since as NSString, forKey: WMFReadingListUpdateKey) } guard moc.hasChanges else { return } try moc.save() } func executeRandomListPopulation(in moc: NSManagedObjectContext) throws { let countOfListsToCreate = moc.wmf_numberValue(forKey: "WMFCountOfListsToCreate")?.int64Value ?? 10 for i in 1...countOfListsToCreate { do { _ = try readingListsController.createReadingList(named: "\(i)", in: moc) } catch { _ = try readingListsController.createReadingList(named: "\(arc4random())", in: moc) } } try moc.save() } func executeRandomArticlePopulation(in moc: NSManagedObjectContext) throws { guard let siteURL = URL(string: "https://en.wikipedia.org") else { return } let countOfEntriesToCreate = moc.wmf_numberValue(forKey: "WMFCountOfEntriesToCreate")?.int64Value ?? 10 let randomArticleFetcher = RandomArticleFetcher() let taskGroup = WMFTaskGroup() try moc.wmf_batchProcessObjects { (list: ReadingList) in guard !list.isDefault else { return } do { var summaryResponses: [String: ArticleSummary] = [:] for i in 1...countOfEntriesToCreate { taskGroup.enter() randomArticleFetcher.fetchRandomArticle(withSiteURL: siteURL, completion: { (error, result, summary) in if let key = result?.wmf_databaseKey, let summary = summary { summaryResponses[key] = summary } taskGroup.leave() }) if i % 16 == 0 || i == countOfEntriesToCreate { taskGroup.wait() guard !isCancelled else { throw ReadingListsOperationError.cancelled } let articlesByKey = try moc.wmf_createOrUpdateArticleSummmaries(withSummaryResponses: summaryResponses) let articles = Array(articlesByKey.values) try readingListsController.add(articles: articles, to: list, in: moc) if let defaultReadingList = moc.wmf_fetchDefaultReadingList() { try readingListsController.add(articles: articles, to: defaultReadingList, in: moc) } try moc.save() summaryResponses.removeAll(keepingCapacity: true) } } } catch let error { DDLogError("error populating lists: \(error)") } } } private func split(readingList: ReadingList, intoReadingListsOfSize size: Int, in moc: NSManagedObjectContext) throws -> [ReadingList] { var newReadingLists: [ReadingList] = [] guard let readingListName = readingList.name else { assertionFailure("Missing reading list name") return newReadingLists } let entries = Array(readingList.entries ?? []) let entriesCount = Int(readingList.countOfEntries) let splitEntriesArrays = stride(from: size, to: entriesCount, by: size).map { Array(entries[$0..<min($0 + size, entriesCount)]) } for (index, splitEntries) in splitEntriesArrays.enumerated() { guard let newReadingList = NSEntityDescription.insertNewObject(forEntityName: "ReadingList", into: moc) as? ReadingList else { continue } let splitIndex = index + 1 var newReadingListName = "\(readingListName)_\(splitIndex)" while try readingListsController.listExists(with: newReadingListName, in: moc) { newReadingListName = "\(newReadingListName)_\(splitIndex)" } newReadingList.name = newReadingListName newReadingList.createdDate = NSDate() newReadingList.updatedDate = newReadingList.createdDate newReadingList.isUpdatedLocally = true for splitEntry in splitEntries { splitEntry.list = newReadingList splitEntry.isUpdatedLocally = true } readingList.isUpdatedLocally = true try readingList.updateArticlesAndEntries() try newReadingList.updateArticlesAndEntries() newReadingLists.append(newReadingList) } newReadingLists.append(readingList) if !newReadingLists.isEmpty { let userInfo = [ReadingListsController.readingListsWereSplitNotificationEntryLimitKey: size] NotificationCenter.default.post(name: ReadingListsController.readingListsWereSplitNotification, object: nil, userInfo: userInfo) UserDefaults.wmf.wmf_setDidSplitExistingReadingLists(true) } return newReadingLists } func processLocalUpdates(in moc: NSManagedObjectContext) throws { let taskGroup = WMFTaskGroup() let listsToCreateOrUpdateFetch: NSFetchRequest<ReadingList> = ReadingList.fetchRequest() listsToCreateOrUpdateFetch.sortDescriptors = [NSSortDescriptor(keyPath: \ReadingList.createdDate, ascending: false)] listsToCreateOrUpdateFetch.predicate = NSPredicate(format: "isUpdatedLocally == YES") let listsToUpdate = try moc.fetch(listsToCreateOrUpdateFetch) var createdReadingLists: [Int64: ReadingList] = [:] var failedReadingLists: [(ReadingList, APIReadingListError)] = [] var updatedReadingLists: [Int64: ReadingList] = [:] var deletedReadingLists: [Int64: ReadingList] = [:] var listsToCreate: [ReadingList] = [] var requestCount = 0 for localReadingList in listsToUpdate { autoreleasepool { guard let readingListName = localReadingList.name else { moc.delete(localReadingList) return } guard let readingListID = localReadingList.readingListID?.int64Value else { if localReadingList.isDeletedLocally || localReadingList.canonicalName == nil { // if it has no id and is deleted locally, it can just be deleted moc.delete(localReadingList) } else if !localReadingList.isDefault { let entryLimit = moc.wmf_readingListsConfigMaxListsPerUser if localReadingList.countOfEntries > entryLimit && !UserDefaults.wmf.wmf_didSplitExistingReadingLists() { if let splitReadingLists = try? split(readingList: localReadingList, intoReadingListsOfSize: entryLimit, in: moc) { listsToCreate.append(contentsOf: splitReadingLists) } } else { listsToCreate.append(localReadingList) } } return } if localReadingList.isDeletedLocally { requestCount += 1 taskGroup.enter() self.apiController.deleteList(withListID: readingListID, completion: { (deleteError) in defer { taskGroup.leave() } guard deleteError == nil else { DDLogError("Error deleting reading list: \(String(describing: deleteError))") return } deletedReadingLists[readingListID] = localReadingList }) } else if localReadingList.isUpdatedLocally { requestCount += 1 taskGroup.enter() self.apiController.updateList(withListID: readingListID, name: readingListName, description: localReadingList.readingListDescription, completion: { (updateError) in defer { taskGroup.leave() } guard updateError == nil else { DDLogError("Error updating reading list: \(String(describing: updateError))") return } updatedReadingLists[readingListID] = localReadingList }) } } } let listNamesAndDescriptionsToCreate: [(name: String, description: String?)] = listsToCreate.map { assert($0.canonicalName != nil) return (name: $0.canonicalName ?? "", description: $0.readingListDescription) } var start = 0 var end = 0 while end < listNamesAndDescriptionsToCreate.count { end = min(listNamesAndDescriptionsToCreate.count, start + WMFReadingListBatchSizePerRequestLimit) autoreleasepool { taskGroup.enter() let listsToCreateSubarray = Array(listsToCreate[start..<end]) let namesAndDescriptionsSubarray = Array(listNamesAndDescriptionsToCreate[start..<end]) self.apiController.createLists(namesAndDescriptionsSubarray, completion: { (readingListIDs, createError) in defer { taskGroup.leave() } guard let readingListIDs = readingListIDs else { DDLogError("Error creating reading list: \(String(describing: createError))") if let apiError = createError as? APIReadingListError { for list in listsToCreateSubarray { failedReadingLists.append((list, apiError)) } } return } for (index, readingList) in readingListIDs.enumerated() { guard index < listsToCreateSubarray.count else { break } let localReadingList = listsToCreateSubarray[index] guard let readingListID = readingList.0 else { if let apiError = readingList.1 as? APIReadingListError { failedReadingLists.append((localReadingList, apiError)) } continue } createdReadingLists[readingListID] = localReadingList } }) } start = end } taskGroup.wait() guard !isCancelled else { throw ReadingListsOperationError.cancelled } for (readingListID, localReadingList) in createdReadingLists { localReadingList.readingListID = NSNumber(value: readingListID) localReadingList.isUpdatedLocally = false } for (_, localReadingList) in updatedReadingLists { localReadingList.isUpdatedLocally = false } for (_, localReadingList) in deletedReadingLists { moc.delete(localReadingList) } for failed in failedReadingLists { failed.0.errorCode = failed.1.rawValue } let entriesToCreateOrUpdateFetch: NSFetchRequest<ReadingListEntry> = ReadingListEntry.fetchRequest() entriesToCreateOrUpdateFetch.predicate = NSPredicate(format: "isUpdatedLocally == YES") entriesToCreateOrUpdateFetch.sortDescriptors = [NSSortDescriptor(keyPath: \ReadingListEntry.createdDate, ascending: false)] let localReadingListEntriesToUpdate = try moc.fetch(entriesToCreateOrUpdateFetch) var deletedReadingListEntries: [Int64: ReadingListEntry] = [:] var entriesToAddByListID: [Int64: [(project: String, title: String, entry: ReadingListEntry)]] = [:] for localReadingListEntry in localReadingListEntriesToUpdate { try autoreleasepool { guard let articleKey = localReadingListEntry.articleKey, let articleURL = URL(string: articleKey), let project = articleURL.wmf_site?.absoluteString, let title = articleURL.wmf_title else { moc.delete(localReadingListEntry) return } guard let readingListID = localReadingListEntry.list?.readingListID?.int64Value else { return } guard let readingListEntryID = localReadingListEntry.readingListEntryID?.int64Value else { if localReadingListEntry.isDeletedLocally { // if it has no id and is deleted locally, it can just be deleted moc.delete(localReadingListEntry) } else { entriesToAddByListID[readingListID, default: []].append((project: project, title: title, entry: localReadingListEntry)) } return } if localReadingListEntry.isDeletedLocally { requestCount += 1 taskGroup.enter() self.apiController.removeEntry(withEntryID: readingListEntryID, fromListWithListID: readingListID, completion: { (deleteError) in defer { taskGroup.leave() } guard deleteError == nil else { DDLogError("Error deleting reading list entry: \(String(describing: deleteError))") return } deletedReadingListEntries[readingListEntryID] = localReadingListEntry }) if requestCount % WMFReadingListBatchSizePerRequestLimit == 0 { taskGroup.wait() for (_, localReadingListEntry) in deletedReadingListEntries { moc.delete(localReadingListEntry) } deletedReadingListEntries.removeAll(keepingCapacity: true) try moc.save() guard !isCancelled else { throw ReadingListsOperationError.cancelled } } } else { // there's no "updating" of an entry currently localReadingListEntry.isUpdatedLocally = false } } } taskGroup.wait() for (_, localReadingListEntry) in deletedReadingListEntries { moc.delete(localReadingListEntry) } try moc.save() guard !isCancelled else { throw ReadingListsOperationError.cancelled } for (readingListID, entries) in entriesToAddByListID { var start = 0 var end = 0 while end < entries.count { end = min(entries.count, start + WMFReadingListBatchSizePerRequestLimit) try autoreleasepool { var createdReadingListEntries: [Int64: ReadingListEntry] = [:] var failedReadingListEntries: [(ReadingListEntry, APIReadingListError)] = [] requestCount += 1 taskGroup.enter() let entrySubarray = Array(entries[start..<end]) let entryProjectAndTitles = entrySubarray.map { (project: $0.project, title: $0.title) } self.apiController.addEntriesToList(withListID: readingListID, entries: entryProjectAndTitles, completion: { (readingListEntryIDs, createError) in defer { taskGroup.leave() } guard let readingListEntryIDs = readingListEntryIDs else { DDLogError("Error creating reading list entry: \(String(describing: createError))") if let apiError = createError as? APIReadingListError { for entry in entrySubarray { failedReadingListEntries.append((entry.entry, apiError)) } } return } for (index, readingListEntryIDOrError) in readingListEntryIDs.enumerated() { guard index < entrySubarray.count else { break } let localReadingListEntry = entrySubarray[index].entry guard let readingListEntryID = readingListEntryIDOrError.0 else { if let apiError = readingListEntryIDOrError.1 as? APIReadingListError { failedReadingListEntries.append((localReadingListEntry, apiError)) } continue } createdReadingListEntries[readingListEntryID] = localReadingListEntry } }) taskGroup.wait() for (readingListEntryID, localReadingListEntry) in createdReadingListEntries { localReadingListEntry.readingListEntryID = NSNumber(value: readingListEntryID) localReadingListEntry.isUpdatedLocally = false } for failed in failedReadingListEntries { failed.0.errorCode = failed.1.rawValue } if moc.hasChanges { try moc.save() } guard !isCancelled else { throw ReadingListsOperationError.cancelled } } start = end } } } internal func locallyCreate(_ readingListEntries: [APIReadingListEntry], with readingListsByEntryID: [Int64: ReadingList]? = nil, in moc: NSManagedObjectContext) throws { guard !readingListEntries.isEmpty else { return } let summaryFetcher = ArticleSummaryFetcher(session: apiController.session, configuration: Configuration.current) let group = WMFTaskGroup() let semaphore = DispatchSemaphore(value: 1) var remoteEntriesToCreateLocallyByArticleKey: [String: APIReadingListEntry] = [:] var requestedArticleKeys: Set<String> = [] var articleSummariesByArticleKey: [String: ArticleSummary] = [:] var entryCount = 0 var articlesByKey: [String: WMFArticle] = [:] for remoteEntry in readingListEntries { autoreleasepool { let isDeleted = remoteEntry.deleted ?? false guard !isDeleted else { return } guard let articleURL = remoteEntry.articleURL, let articleKey = articleURL.wmf_databaseKey else { return } remoteEntriesToCreateLocallyByArticleKey[articleKey] = remoteEntry guard !requestedArticleKeys.contains(articleKey) else { return } requestedArticleKeys.insert(articleKey) if let article = dataStore.fetchArticle(withKey: articleKey, in: moc) { articlesByKey[articleKey] = article } else { group.enter() summaryFetcher.fetchSummaryForArticle(with: articleKey, completion: { (result, response, error) in guard let result = result else { group.leave() return } semaphore.wait() articleSummariesByArticleKey[articleKey] = result semaphore.signal() group.leave() }) entryCount += 1 } } } group.wait() guard !isCancelled else { throw ReadingListsOperationError.cancelled } let updatedArticlesByKey = try moc.wmf_createOrUpdateArticleSummmaries(withSummaryResponses: articleSummariesByArticleKey) articlesByKey.merge(updatedArticlesByKey, uniquingKeysWith: { (a, b) in return a }) var finalReadingListsByEntryID: [Int64: ReadingList] if let readingListsByEntryID = readingListsByEntryID { finalReadingListsByEntryID = readingListsByEntryID } else { finalReadingListsByEntryID = [:] var readingListsByReadingListID: [Int64: ReadingList] = [:] let localReadingListsFetch: NSFetchRequest<ReadingList> = ReadingList.fetchRequest() localReadingListsFetch.predicate = NSPredicate(format: "readingListID IN %@", readingListEntries.compactMap { $0.listId } ) let localReadingLists = try moc.fetch(localReadingListsFetch) for localReadingList in localReadingLists { guard let localReadingListID = localReadingList.readingListID?.int64Value else { continue } readingListsByReadingListID[localReadingListID] = localReadingList } for readingListEntry in readingListEntries { guard let listId = readingListEntry.listId, let readingList = readingListsByReadingListID[listId] else { DDLogError("Missing list for reading list entry: \(readingListEntry)") throw APIReadingListError.needsFullSync } finalReadingListsByEntryID[readingListEntry.id] = readingList } } var updatedLists: Set<ReadingList> = [] for (articleKey, remoteEntry) in remoteEntriesToCreateLocallyByArticleKey { autoreleasepool { guard let readingList = finalReadingListsByEntryID[remoteEntry.id] else { return } var fetchedArticle = articlesByKey[articleKey] if fetchedArticle == nil { if let newArticle = moc.wmf_fetchOrCreate(objectForEntityName: "WMFArticle", withValue: articleKey, forKey: "key") as? WMFArticle { if newArticle.displayTitleHTML == "" { newArticle.displayTitleHTML = remoteEntry.title } fetchedArticle = newArticle } } guard let article = fetchedArticle else { return } var entry = ReadingListEntry(context: moc) entry.update(with: remoteEntry) // if there's a key mismatch, locally delete the bad entry and create a new one with the correct key if remoteEntry.articleKey != article.key { entry.list = readingList entry.articleKey = remoteEntry.articleKey try? readingListsController.markLocalDeletion(for: [entry]) entry = ReadingListEntry(context: moc) entry.update(with: remoteEntry) entry.readingListEntryID = nil entry.isUpdatedLocally = true } if entry.createdDate == nil { entry.createdDate = NSDate() } if entry.updatedDate == nil { entry.updatedDate = entry.createdDate } entry.list = readingList entry.articleKey = article.key entry.displayTitle = article.displayTitle if article.savedDate == nil { article.savedDate = entry.createdDate as Date? } updatedLists.insert(readingList) } } for readingList in updatedLists { try autoreleasepool { try readingList.updateArticlesAndEntries() } } } internal func createOrUpdate(remoteReadingLists: [APIReadingList], deleteMissingLocalLists: Bool = false, inManagedObjectContext moc: NSManagedObjectContext) throws -> Int { guard !remoteReadingLists.isEmpty || deleteMissingLocalLists else { return 0 } var createdOrUpdatedReadingListsCount = 0 // Arrange remote lists by ID and name for merging with local lists var remoteReadingListsByID: [Int64: APIReadingList] = [:] var remoteReadingListsByName: [String: [Int64: APIReadingList]] = [:] // server still allows multiple lists with the same name var remoteDefaultReadingList: APIReadingList? = nil for remoteReadingList in remoteReadingLists { if remoteReadingList.isDefault { remoteDefaultReadingList = remoteReadingList } remoteReadingListsByID[remoteReadingList.id] = remoteReadingList remoteReadingListsByName[remoteReadingList.name.precomposedStringWithCanonicalMapping, default: [:]][remoteReadingList.id] = remoteReadingList } if let remoteDefaultReadingList = remoteDefaultReadingList { let defaultReadingList = moc.wmf_fetchDefaultReadingList() defaultReadingList?.readingListID = NSNumber(value: remoteDefaultReadingList.id) } let localReadingListsFetch: NSFetchRequest<ReadingList> = ReadingList.fetchRequest() let localReadingLists = try moc.fetch(localReadingListsFetch) var localListsMissingRemotely: [ReadingList] = [] for localReadingList in localReadingLists { var remoteReadingList: APIReadingList? if let localReadingListID = localReadingList.readingListID?.int64Value { // remove from the dictionary because we will create any lists left in the dictionary if let remoteReadingListByID = remoteReadingListsByID.removeValue(forKey: localReadingListID) { remoteReadingListsByName[remoteReadingListByID.name]?.removeValue(forKey: remoteReadingListByID.id) remoteReadingList = remoteReadingListByID } } if remoteReadingList == nil { if localReadingList.readingListID == nil, let localReadingListName = localReadingList.name?.precomposedStringWithCanonicalMapping { if let remoteReadingListByName = remoteReadingListsByName[localReadingListName]?.values.first { // remove from the dictionary because we will create any lists left in this dictionary remoteReadingListsByID.removeValue(forKey: remoteReadingListByName.id) remoteReadingList = remoteReadingListByName } } } guard let remoteReadingListForUpdate = remoteReadingList else { if localReadingList.readingListID != nil { localListsMissingRemotely.append(localReadingList) } continue } let isDeleted = remoteReadingListForUpdate.deleted ?? false if isDeleted { try readingListsController.markLocalDeletion(for: [localReadingList]) moc.delete(localReadingList) // object can be removed since we have the server-side update createdOrUpdatedReadingListsCount += 1 } else { localReadingList.update(with: remoteReadingListForUpdate) createdOrUpdatedReadingListsCount += 1 } } if deleteMissingLocalLists { // Delete missing reading lists try readingListsController.markLocalDeletion(for: localListsMissingRemotely) for readingList in localListsMissingRemotely { moc.delete(readingList) createdOrUpdatedReadingListsCount += 1 } } // create any list that wasn't matched by ID or name for (_, remoteReadingList) in remoteReadingListsByID { let isDeleted = remoteReadingList.deleted ?? false guard !isDeleted else { continue } guard let localList = NSEntityDescription.insertNewObject(forEntityName: "ReadingList", into: moc) as? ReadingList else { continue } localList.update(with: remoteReadingList) if localList.createdDate == nil { localList.createdDate = NSDate() } if localList.updatedDate == nil { localList.updatedDate = localList.createdDate } createdOrUpdatedReadingListsCount += 1 } return createdOrUpdatedReadingListsCount } internal func createOrUpdate(remoteReadingListEntries: [APIReadingListEntry], for readingListID: Int64? = nil, deleteMissingLocalEntries: Bool = false, inManagedObjectContext moc: NSManagedObjectContext) throws -> Int { guard !remoteReadingListEntries.isEmpty || deleteMissingLocalEntries else { return 0 } var createdOrUpdatedReadingListEntriesCount = 0 // Arrange remote list entries by ID and key for merging with local lists var remoteReadingListEntriesByReadingListID: [Int64: [String: APIReadingListEntry]] = [:] if let readingListID = readingListID { remoteReadingListEntriesByReadingListID[readingListID] = [:] } for remoteReadingListEntry in remoteReadingListEntries { guard let listID = remoteReadingListEntry.listId ?? readingListID, let articleKey = remoteReadingListEntry.articleKey else { DDLogError("missing id or article key for remote entry: \(remoteReadingListEntry)") assert(false) continue } remoteReadingListEntriesByReadingListID[listID, default: [:]][articleKey] = remoteReadingListEntry } var entriesToDelete: [ReadingListEntry] = [] for (readingListID, readingListEntriesByKey) in remoteReadingListEntriesByReadingListID { try autoreleasepool { let localReadingListsFetch: NSFetchRequest<ReadingList> = ReadingList.fetchRequest() localReadingListsFetch.predicate = NSPredicate(format: "readingListID == %@", NSNumber(value: readingListID)) let localReadingLists = try moc.fetch(localReadingListsFetch) let localReadingListEntries = localReadingLists.first?.entries?.filter { !$0.isDeletedLocally } ?? [] var localEntriesMissingRemotely: [ReadingListEntry] = [] var remoteEntriesMissingLocally: [String: APIReadingListEntry] = readingListEntriesByKey for localReadingListEntry in localReadingListEntries { guard let articleKey = localReadingListEntry.articleKey else { moc.delete(localReadingListEntry) createdOrUpdatedReadingListEntriesCount += 1 continue } guard let remoteReadingListEntryForUpdate: APIReadingListEntry = remoteEntriesMissingLocally.removeValue(forKey: articleKey) else { if localReadingListEntry.readingListEntryID != nil { localEntriesMissingRemotely.append(localReadingListEntry) } continue } let isDeleted = remoteReadingListEntryForUpdate.deleted ?? false if isDeleted { entriesToDelete.append(localReadingListEntry) createdOrUpdatedReadingListEntriesCount += 1 } else { localReadingListEntry.update(with: remoteReadingListEntryForUpdate) createdOrUpdatedReadingListEntriesCount += 1 } } if deleteMissingLocalEntries { entriesToDelete.append(contentsOf: localEntriesMissingRemotely) } try readingListsController.markLocalDeletion(for: entriesToDelete) for entry in entriesToDelete { moc.delete(entry) createdOrUpdatedReadingListEntriesCount += 1 } try moc.save() moc.reset() // create any entry that wasn't matched var start = 0 var end = 0 let entries = Array(remoteEntriesMissingLocally.values) while end < entries.count { end = min(entries.count, start + WMFReadingListCoreDataBatchSize) try locallyCreate(Array(entries[start..<end]), in: moc) start = end try moc.save() moc.reset() createdOrUpdatedReadingListEntriesCount += 1 } } } return createdOrUpdatedReadingListEntriesCount } }
mit
90e3f9b9490e3fa20c697532cfc999bd
46.005814
223
0.561534
6.086575
false
false
false
false
adevelopers/PeriodicTableView
PeriodicTable/PeriodicTable/MainScreen/Cells/ElementCell.swift
1
591
// // MainCell.swift // PeriodicTable // // Created by Kirill Khudyakov on 06.10.17. // Copyright © 2017 adeveloper. All rights reserved. // import UIKit class ElementCell: UITableViewCell { @IBOutlet weak var number: UILabel! @IBOutlet weak var name: UILabel! @IBOutlet weak var symbol: UILabel! override func awakeFromNib() { super.awakeFromNib() number.textColor = .white name.textColor = .white symbol.textColor = .white backgroundColor = .clear contentView.backgroundColor = .clear } }
mit
7fb64da91b9f86f351bd6951baf4e8ef
20.071429
53
0.630508
4.402985
false
false
false
false
Workpop/meteor-ios
Examples/Todos/Todos/TodosViewController.swift
1
6501
// Copyright (c) 2014-2015 Martijn Walraven // // 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 CoreData import Meteor class TodosViewController: FetchedResultsTableViewController, UITextFieldDelegate { @IBOutlet weak var listLockStatusBarButtonItem: UIBarButtonItem! // MARK: - Model var listID: NSManagedObjectID? { didSet { assert(managedObjectContext != nil) if listID != nil { if listID != oldValue { list = managedObjectContext!.existingObjectWithID(self.listID!, error: nil) as? List } } else { list = nil } } } private var listObserver: ManagedObjectObserver? private var list: List? { didSet { if list != oldValue { if list != nil { listObserver = ManagedObjectObserver(list!) { (changeType) -> Void in switch changeType { case .Deleted, .Invalidated: self.list = nil case .Updated, .Refreshed: self.listDidChange() default: break } } } else { listObserver = nil resetContent() } listDidChange() setNeedsLoadContent() } } } func listDidChange() { title = list?.name if isViewLoaded() { updateViewWithModel() } } // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() addTaskContainerView.preservesSuperviewLayoutMargins = true } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) updateViewWithModel() } // MARK: - Content Loading override func loadContent() { if list == nil { return } super.loadContent() } override func configureSubscriptionLoader(subscriptionLoader: SubscriptionLoader) { if list != nil { subscriptionLoader.addSubscriptionWithName("todos", parameters: list!) } } override func createFetchedResultsController() -> NSFetchedResultsController? { if list == nil { return nil } let fetchRequest = NSFetchRequest(entityName: "Todo") fetchRequest.predicate = NSPredicate(format: "list == %@", self.list!) fetchRequest.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] return NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedObjectContext, sectionNameKeyPath: nil, cacheName: nil) } // MARK: - Updating View func updateViewWithModel() { if list == nil { tableView.tableHeaderView = nil listLockStatusBarButtonItem.image = nil } else { tableView.tableHeaderView = addTaskContainerView if list!.user == nil { listLockStatusBarButtonItem.image = UIImage(named: "unlocked_icon") } else { listLockStatusBarButtonItem.image = UIImage(named: "locked_icon") } } } // MARK: - FetchedResultsTableViewDataSourceDelegate func dataSource(dataSource: FetchedResultsTableViewDataSource, configureCell cell: UITableViewCell, forObject object: NSManagedObject, atIndexPath indexPath: NSIndexPath) { if let todo = object as? Todo { cell.textLabel!.text = todo.text cell.accessoryType = todo.checked ? .Checkmark : .None } } func dataSource(dataSource: FetchedResultsTableViewDataSource, deleteObject object: NSManagedObject, atIndexPath indexPath: NSIndexPath) { if let todo = object as? Todo { managedObjectContext.deleteObject(todo) todo.list.incompleteCount-- saveManagedObjectContext() } } // MARK: - UITableViewDelegate override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? { if let todo = dataSource.objectAtIndexPath(indexPath) as? Todo { todo.checked = !todo.checked if (todo.checked) { todo.list.incompleteCount-- } else { todo.list.incompleteCount++ } saveManagedObjectContext() } return nil } // MARK: - UITextFieldDelegate @IBOutlet var addTaskContainerView: UIView! @IBOutlet weak var addTaskTextField: UITextField! func textFieldShouldReturn(textField: UITextField) -> Bool { let text = addTaskTextField.text addTaskTextField.text = nil if text.isEmpty { addTaskTextField.resignFirstResponder() return false } let todo = NSEntityDescription.insertNewObjectForEntityForName("Todo", inManagedObjectContext: managedObjectContext) as Todo todo.creationDate = NSDate() todo.text = text todo.list = list list?.incompleteCount++ saveManagedObjectContext() return true } // MARK: - Making Lists Private @IBAction func listLockStatusButtonPressed() { if list != nil { let currentUser = self.currentUser if currentUser == nil { let alertController = UIAlertController(title: nil, message: "Please sign in to make private lists.", preferredStyle: .Alert) let okAction = UIAlertAction(title: "OK", style: .Default, handler: nil) alertController.addAction(okAction) presentViewController(alertController, animated: true, completion: nil) return } if list!.user == nil { list!.user = currentUser } else { list!.user = nil } saveManagedObjectContext() } } }
mit
9fc43b6baa7d010d5d6f0f4a502453ab
29.097222
174
0.668974
5.098824
false
false
false
false
dabing1022/AlgorithmRocks
LeetCodeSwift/Playground/LeetCode.playground/Pages/110 Balanced Binary Tree.xcplaygroundpage/Contents.swift
1
1057
//: [Previous](@previous) /*: # [Balanced Binary Tree](https://leetcode.com/problems/balanced-binary-tree/) Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. Tags: Tree, Depth-first Search */ public class TreeNode { public var val: Int public var left: TreeNode? public var right: TreeNode? public init(_ val: Int) { self.val = val self.left = nil self.right = nil } } class Solution { func maxDepth(root: TreeNode?) -> Int { if (root == nil) { return 0 } return max(maxDepth(root!.left), maxDepth(root!.right)) + 1 } func isBalanced(root: TreeNode?) -> Bool { if (root == nil) { return false } return abs(maxDepth(root!.left) - maxDepth(root!.right)) < 1 && isBalanced(root!.left) && isBalanced(root!.right) } } //: [Next](@next)
mit
7e1c1afdc7f904be514edd4234e06be6
23.581395
157
0.598865
3.815884
false
false
false
false
ishiimizuki/textFieldSample
TextFieldSample/ViewController.swift
1
3879
// // ViewController.swift // TextFieldSample // // Created by 石井瑞城 on 2015/03/05. // Copyright (c) 2015年 石井瑞城. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! // UITextField改行対応させれなかったのでUITextViewにしてます // 3行くらいまで高さが自動で変わるようにしたいです @IBOutlet weak var inputTextView: UITextView! @IBOutlet weak var bottomLayoutConstraint: NSLayoutConstraint! var messages: Array<String> = ["なんか", "てきとうに", "いれてます"] override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // キーボードの表示/非表示の監視を開始 let center = NSNotificationCenter.defaultCenter() center.addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil) center.addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil) } override func viewWillDisappear(animated: Bool) { // キーボードの表示/非表示の監視を解除 let center = NSNotificationCenter.defaultCenter() center.addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil) center.addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil) super.viewWillDisappear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func keyboardWillShow(notif: NSNotification) { let info = notif.userInfo if let unwrappedInfo = info { let keyboardFrame = unwrappedInfo[UIKeyboardFrameEndUserInfoKey]!.CGRectValue() let duration = unwrappedInfo[UIKeyboardAnimationDurationUserInfoKey]!.doubleValue bottomLayoutConstraint.constant = keyboardFrame.height UIView.animateWithDuration(duration) { [unowned self] () -> Void in self.view.layoutIfNeeded() } } } func keyboardWillHide(notif: NSNotification) { let info = notif.userInfo if let unwrappedInfo = info { let duration = unwrappedInfo[UIKeyboardAnimationDurationUserInfoKey]!.doubleValue bottomLayoutConstraint.constant = 0 UIView.animateWithDuration(duration) { [unowned self] () -> Void in self.view.layoutIfNeeded() } } } // MARK: - UITableViewDataSource func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return messages.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell cell.textLabel?.text = messages[indexPath.row] return cell } // MARK: - UITableViewDelegate func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) // タッチイベントがとれなかったので、cellをタップしたらキーボード閉じるようにしてます inputTextView.resignFirstResponder() } // MARK: - IBActions @IBAction func sendButtonTapped(sender: UIButton) { messages.append(inputTextView.text) inputTextView.text = nil tableView.reloadData() } }
mit
1ea54b6f4f037d7e8165c73937837b40
35.07
114
0.671195
5.312224
false
false
false
false
almcintyre/PagingMenuController
Pod/Classes/PagingMenuController.swift
2
21838
// // PagingMenuController.swift // PagingMenuController // // Created by Yusuke Kita on 3/18/15. // Copyright (c) 2015 kitasuke. All rights reserved. // import UIKit @available(*, unavailable, message: "Please use `onMove` property instead") public protocol PagingMenuControllerDelegate: class {} public enum MenuMoveState { case willMoveController(to: UIViewController, from: UIViewController) case didMoveController(to: UIViewController, from: UIViewController) case willMoveItem(to: MenuItemView, from: MenuItemView) case didMoveItem(to: MenuItemView, from: MenuItemView) case didScrollStart case didScrollEnd } internal let MinimumSupportedViewCount = 1 internal let VisiblePagingViewNumber = 3 open class PagingMenuController: UIViewController { public fileprivate(set) var menuView: MenuView? { didSet { guard let menuView = menuView else { return } menuView.delegate = self menuView.onMove = onMove menuView.update(currentPage: options.defaultPage) view.addSubview(menuView) } } public fileprivate(set) var pagingViewController: PagingViewController? { didSet { guard let pagingViewController = pagingViewController else { return } pagingViewController.contentScrollView.delegate = self view.addSubview(pagingViewController.view) addChildViewController(pagingViewController) pagingViewController.didMove(toParentViewController: self) } } public var onMove: ((MenuMoveState) -> Void)? { didSet { guard let menuView = menuView else { return } menuView.onMove = onMove } } fileprivate var options: PagingMenuControllerCustomizable! { didSet { cleanup() validate(options) } } fileprivate var menuOptions: MenuViewCustomizable? // MARK: - Lifecycle public init(options: PagingMenuControllerCustomizable) { super.init(nibName: nil, bundle: nil) setup(options) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override open func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() // fix unnecessary inset for menu view when implemented by programmatically menuView?.contentInset.top = 0 } override open func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) if let menuView = menuView, let menuOptions = menuOptions { menuView.updateMenuViewConstraints(size) coordinator.animate(alongsideTransition: { [unowned self] (_) -> Void in self.view.setNeedsLayout() self.view.layoutIfNeeded() // reset selected menu item view position switch menuOptions.displayMode { case .standard, .infinite: self.move(toPage: menuView.currentPage) default: break } }, completion: nil) } } // MARK: - Public open func setup(_ options: PagingMenuControllerCustomizable) { self.options = options switch options.componentType { case .all(let menuOptions, _): self.menuOptions = menuOptions case .menuView(let menuOptions): self.menuOptions = menuOptions default: break } setupMenuView() setupMenuController() move(toPage: currentPage, animated: false) } fileprivate func setupMenuView() { switch options.componentType { case .pagingController: return default: break } constructMenuView() layoutMenuView() } fileprivate func setupMenuController() { switch options.componentType { case .menuView: return default: break } constructPagingViewController() layoutPagingViewController() } open func move(toPage page: Int, animated: Bool = true) { switch options.componentType { case .menuView, .all: // ignore an unexpected page number guard let menuView = menuView , page < menuView.menuItemCount else { return } let lastPage = menuView.currentPage guard page != lastPage else { // place views on appropriate position menuView.move(toPage: page, animated: animated) pagingViewController?.positionMenuController() return } switch options.componentType { case .all: break default: menuView.move(toPage: page, animated: animated) return } case .pagingController: guard let pagingViewController = pagingViewController , page < pagingViewController.controllers.count else { return } guard page != pagingViewController.currentPage else { return } } guard let pagingViewController = pagingViewController, let previousPagingViewController = pagingViewController.currentViewController else { return } // hide paging views if it's moving to far away hidePagingMenuControllers(page) let nextPage = page % pagingViewController.controllers.count let nextPagingViewController = pagingViewController.controllers[nextPage] onMove?(.willMoveController(to: nextPagingViewController, from: previousPagingViewController)) menuView?.move(toPage: page) pagingViewController.update(currentPage: nextPage) pagingViewController.currentViewController = nextPagingViewController let duration = animated ? options.animationDuration : 0 let animationClosure = { pagingViewController.positionMenuController() } let completionClosure = { [weak self] (_: Bool) -> Void in pagingViewController.relayoutPagingViewControllers() // show paging views self?.showPagingMenuControllers() self?.onMove?(.didMoveController(to: nextPagingViewController, from: previousPagingViewController)) } if duration > 0 { UIView.animate(withDuration: duration, animations: animationClosure, completion: completionClosure) } else { animationClosure() completionClosure(true) } } // MARK: - Constructor fileprivate func constructMenuView() { guard let menuOptions = self.menuOptions else { return } menuView = MenuView(menuOptions: menuOptions) addTapGestureHandler() addSwipeGestureHandler() } fileprivate func layoutMenuView() { guard let menuView = menuView else { return } let height: CGFloat switch options.componentType { case .all(let menuOptions, _): height = menuOptions.height switch menuOptions.menuPosition { case .top: // V:|[menuView] menuView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true case .bottom: // V:[menuView]| menuView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true } case .menuView(let menuOptions): height = menuOptions.height // V:|[menuView] menuView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true default: return } // H:|[menuView]| // V:[menuView(height)] NSLayoutConstraint.activate([ menuView.leadingAnchor.constraint(equalTo: view.leadingAnchor), menuView.trailingAnchor.constraint(equalTo: view.trailingAnchor), menuView.heightAnchor.constraint(equalToConstant: height) ]) menuView.setNeedsLayout() menuView.layoutIfNeeded() } fileprivate func constructPagingViewController() { let viewControllers: [UIViewController] switch options.componentType { case .pagingController(let pagingControllers): viewControllers = pagingControllers case .all(_, let pagingControllers): viewControllers = pagingControllers default: return } pagingViewController = PagingViewController(viewControllers: viewControllers, options: options) } fileprivate func layoutPagingViewController() { guard let pagingViewController = pagingViewController else { return } // H:|[pagingView]| NSLayoutConstraint.activate([ pagingViewController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor), pagingViewController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor), ]) switch options.componentType { case .pagingController: // V:|[pagingView]| NSLayoutConstraint.activate([ pagingViewController.view.topAnchor.constraint(equalTo: view.topAnchor), pagingViewController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor), ]) case .all(let menuOptions, _): guard let menuView = menuView else { return } switch menuOptions.menuPosition { case .top: // V:[menuView][pagingView]| NSLayoutConstraint.activate([ menuView.bottomAnchor.constraint(equalTo: pagingViewController.view.topAnchor, constant: 0), pagingViewController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor), ]) case .bottom: // V:|[pagingView][menuView] NSLayoutConstraint.activate([ pagingViewController.view.topAnchor.constraint(equalTo: view.topAnchor), pagingViewController.view.bottomAnchor.constraint(equalTo: menuView.topAnchor, constant: 0), ]) } default: return } } // MARK: - Private fileprivate func hidePagingMenuControllers(_ page: Int) { guard let menuOptions = menuOptions else { return } switch (options.lazyLoadingPage, menuOptions.displayMode, page) { case (.three, .infinite, menuView?.previousPage ?? previousPage), (.three, .infinite, menuView?.nextPage ?? nextPage): break case (.three, .infinite, _): pagingViewController?.visibleControllers.forEach { $0.view.alpha = 0 } default: break } } fileprivate func showPagingMenuControllers() { pagingViewController?.visibleControllers.forEach { $0.view.alpha = 1 } } } extension PagingMenuController: UIScrollViewDelegate { public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { onMove?(.didScrollEnd) let nextPage: Int switch (scrollView, pagingViewController, menuView) { case let (scrollView, pagingViewController?, _) where scrollView.isEqual(pagingViewController.contentScrollView): nextPage = nextPageFromCurrentPosition case let (scrollView, _, menuView?) where scrollView.isEqual(menuView): nextPage = nextPageFromCurrentPoint default: return } move(toPage: nextPage) } public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { onMove?(.didScrollStart) } public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { switch (scrollView, decelerate) { case (let scrollView, false) where scrollView.isEqual(menuView): break default: return } let nextPage = nextPageFromCurrentPoint move(toPage: nextPage) } } extension PagingMenuController: Pagable { public var currentPage: Int { switch (menuView, pagingViewController) { case (let menuView?, _): return menuView.currentPage case (_, let pagingViewController?): return pagingViewController.currentPage default: return 0 } } var previousPage: Int { guard let menuOptions = menuOptions, case .infinite = menuOptions.displayMode, let controllers = pagingViewController?.controllers else { return currentPage - 1 } return currentPage - 1 < 0 ? controllers.count - 1 : currentPage - 1 } var nextPage: Int { guard let menuOptions = menuOptions, case .infinite = menuOptions.displayMode, let controllers = pagingViewController?.controllers else { return currentPage + 1 } return currentPage + 1 > controllers.count - 1 ? 0 : currentPage + 1 } } // MARK: Page Control extension PagingMenuController { fileprivate enum PagingViewPosition { case left, center, right, unknown init(order: Int) { switch order { case 0: self = .left case 1: self = .center case 2: self = .right default: self = .unknown } } } fileprivate var currentPagingViewPosition: PagingViewPosition { guard let pagingViewController = pagingViewController else { return .unknown } let pageWidth = pagingViewController.contentScrollView.frame.width let order = Int(ceil((pagingViewController.contentScrollView.contentOffset.x - pageWidth / 2) / pageWidth)) if let menuOptions = menuOptions, case .infinite = menuOptions.displayMode { return PagingViewPosition(order: order) } // consider left edge menu as center position guard pagingViewController.currentPage == 0 && pagingViewController.contentScrollView.contentSize.width < (pageWidth * CGFloat(VisiblePagingViewNumber)) else { return PagingViewPosition(order: order) } return PagingViewPosition(order: order + 1) } fileprivate var nextPageFromCurrentPosition: Int { // set new page number according to current moving direction let page: Int switch options.lazyLoadingPage { case .all: guard let scrollView = pagingViewController?.contentScrollView else { return currentPage } page = Int(scrollView.contentOffset.x) / Int(scrollView.frame.width) default: switch (currentPagingViewPosition, options.componentType) { case (.left, .pagingController): page = previousPage case (.left, _): page = menuView?.previousPage ?? previousPage case (.right, .pagingController): page = nextPage case (.right, _): page = menuView?.nextPage ?? nextPage default: page = currentPage } } return page } fileprivate var nextPageFromCurrentPoint: Int { guard let menuView = menuView else { return 0 } let point = CGPoint(x: menuView.contentOffset.x + menuView.frame.width / 2, y: 0) for (index, menuItemView) in menuView.menuItemViews.enumerated() { guard menuItemView.frame.contains(point) else { continue } return index } return menuView.currentPage } } // MARK: - GestureRecognizer extension PagingMenuController { fileprivate var tapGestureRecognizer: UITapGestureRecognizer { let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture)) gestureRecognizer.numberOfTapsRequired = 1 return gestureRecognizer } fileprivate var leftSwipeGestureRecognizer: UISwipeGestureRecognizer { let gestureRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipeGesture)) gestureRecognizer.direction = .left return gestureRecognizer } fileprivate var rightSwipeGestureRecognizer: UISwipeGestureRecognizer { let gestureRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipeGesture)) gestureRecognizer.direction = .right return gestureRecognizer } fileprivate func addTapGestureHandler() { menuView?.menuItemViews.forEach { $0.addGestureRecognizer(tapGestureRecognizer) } } fileprivate func addSwipeGestureHandler() { guard let menuOptions = menuOptions else { return } switch menuOptions.displayMode { case .standard(_, _, .pagingEnabled): break case .infinite(_, .pagingEnabled): break default: return } menuView?.panGestureRecognizer.require(toFail: leftSwipeGestureRecognizer) menuView?.addGestureRecognizer(leftSwipeGestureRecognizer) menuView?.panGestureRecognizer.require(toFail: rightSwipeGestureRecognizer) menuView?.addGestureRecognizer(rightSwipeGestureRecognizer) } internal func handleTapGesture(_ recognizer: UITapGestureRecognizer) { guard let menuItemView = recognizer.view as? MenuItemView, let menuView = menuView, let page = menuView.menuItemViews.index(of: menuItemView), page != menuView.currentPage, let menuOptions = menuOptions else { return } let newPage: Int switch menuOptions.displayMode { case .standard(_, _, .pagingEnabled): newPage = page < currentPage ? menuView.currentPage - 1 : menuView.currentPage + 1 case .infinite(_, .pagingEnabled): if menuItemView.frame.midX > menuView.currentMenuItemView.frame.midX { newPage = menuView.nextPage } else { newPage = menuView.previousPage } case .infinite: fallthrough default: newPage = page } move(toPage: newPage) } internal func handleSwipeGesture(_ recognizer: UISwipeGestureRecognizer) { guard let menuView = recognizer.view as? MenuView, let menuOptions = menuOptions else { return } let newPage: Int switch (recognizer.direction, menuOptions.displayMode) { case (UISwipeGestureRecognizerDirection.left, .infinite): newPage = menuView.nextPage case (UISwipeGestureRecognizerDirection.left, _): newPage = min(nextPage, menuOptions.itemsOptions.count - 1) case (UISwipeGestureRecognizerDirection.right, .infinite): newPage = menuView.previousPage case (UISwipeGestureRecognizerDirection.right, _): newPage = max(previousPage, 0) default: return } move(toPage: newPage) } } extension PagingMenuController { func cleanup() { if let menuView = self.menuView { menuView.cleanup() menuView.removeFromSuperview() } if let pagingViewController = self.pagingViewController { pagingViewController.cleanup() pagingViewController.view.removeFromSuperview() pagingViewController.removeFromParentViewController() pagingViewController.willMove(toParentViewController: nil) } } } // MARK: Validator extension PagingMenuController { fileprivate func validate(_ options: PagingMenuControllerCustomizable) { validateDefaultPage(options) validateContentsCount(options) validateInfiniteMenuItemNumbers(options) } fileprivate func validateContentsCount(_ options: PagingMenuControllerCustomizable) { switch options.componentType { case .all(let menuOptions, let pagingControllers): guard menuOptions.itemsOptions.count == pagingControllers.count else { raise("number of menu items and view controllers doesn't match") return } default: break } } fileprivate func validateDefaultPage(_ options: PagingMenuControllerCustomizable) { let maxCount: Int switch options.componentType { case .pagingController(let pagingControllers): maxCount = pagingControllers.count case .all(_, let pagingControllers): maxCount = pagingControllers.count case .menuView(let menuOptions): maxCount = menuOptions.itemsOptions.count } guard options.defaultPage >= maxCount || options.defaultPage < 0 else { return } raise("default page is invalid") } fileprivate func validateInfiniteMenuItemNumbers(_ options: PagingMenuControllerCustomizable) { guard case .all(let menuOptions, _) = options.componentType, case .infinite = menuOptions.displayMode else { return } guard menuOptions.itemsOptions.count < VisiblePagingViewNumber else { return } raise("number of view controllers should be more than three with Infinite display mode") } fileprivate var exceptionName: String { return "PMCException" } fileprivate func raise(_ reason: String) { NSException(name: NSExceptionName(rawValue: exceptionName), reason: reason, userInfo: nil).raise() } }
mit
44021b02b5377f75887a2175cf1adb55
35.826307
209
0.627759
5.873588
false
false
false
false
WeltN24/Carlos
Sources/Carlos/CacheLevels/Composed.swift
1
1465
import Combine import Foundation extension CacheLevel { /** Composes two cache levels - parameter cache: The second cache level - returns: A new cache level that is the result of the composition of the two cache levels */ public func compose<A: CacheLevel>(_ cache: A) -> BasicCache<A.KeyType, A.OutputType> where A.KeyType == KeyType, A.OutputType == OutputType { BasicCache( getClosure: { key in self.get(key) .catch { _ -> AnyPublisher<OutputType, Error> in Logger.log("Composed| error on getting value for key \(key) on cache \(String(describing: self)).", .info) return cache.get(key) .flatMap { value -> AnyPublisher<(OutputType, Void), Error> in let get = Just(value).setFailureType(to: Error.self) let set = self.set(value, forKey: key) return Publishers.Zip(get, set) .eraseToAnyPublisher() } .map(\.0) .eraseToAnyPublisher() }.eraseToAnyPublisher() }, setClosure: { value, key in Publishers.Zip( self.set(value, forKey: key), cache.set(value, forKey: key) ) .map { _ in () } .eraseToAnyPublisher() }, clearClosure: { self.clear() cache.clear() }, memoryClosure: { self.onMemoryWarning() cache.onMemoryWarning() } ) } }
mit
57e0883d6523f13301d58050f8c95cb8
29.520833
144
0.56041
4.578125
false
false
false
false
XLabKC/Badger
Badger/Badger/StatusSliderCell.swift
1
1763
import UIKit class StatusSliderCell: BorderedCell, StatusSliderDelegate { private var user: User? private var currentStatus = UserStatus.Unknown private var hasAwakened = false private var timer: NSTimer? @IBOutlet weak var slider: StatusSlider! override func awakeFromNib() { self.hasAwakened = true self.updateView() } func setUser(user: User) { self.user = user self.currentStatus = user.status self.updateView() } func sliderChangedStatus(slider: StatusSlider, newStatus: UserStatus) { self.currentStatus = newStatus var oldStatus = UserStatus.Free.rawValue if let user = self.user { oldStatus = user.status.rawValue user.ref.childByAppendingPath("status").setValue(newStatus.rawValue as String!) } if let timer = self.timer { oldStatus = timer.userInfo as! String timer.invalidate() } self.timer = NSTimer.scheduledTimerWithTimeInterval(1.5, target: self, selector: "setForPush:", userInfo: oldStatus, repeats: false) } func setForPush(timer: NSTimer) { self.timer = nil let oldStatus = timer.userInfo as! String if self.currentStatus.rawValue != oldStatus { let uid = UserStore.sharedInstance().getAuthUid() let ref = Firebase(url: Global.FirebasePushStatusUpdatedUrl).childByAppendingPath(uid) ref.setValue(self.currentStatus.rawValue) } } private func updateView() { if self.hasAwakened { if let user = self.user { self.slider.setStatus(user.status, animated: false) self.slider.delegate = self } } } }
gpl-2.0
0408a834041ab55b68043e4fd09a299d
31.054545
140
0.62734
4.713904
false
false
false
false
x331275955/-
学习微博/学习微博/Classes/Tools/NetworkTools.swift
1
1682
// // NetworkTools.swift // 我的微博 // // Created by 刘凡 on 15/7/29. // Copyright © 2015年 itheima. All rights reserved. // import UIKit import AFNetworking /// 网络工具类 class NetworkTools: AFHTTPSessionManager { // 全局访问点 static let sharedNetworkTools: NetworkTools = { let instance = NetworkTools(baseURL: NSURL(string: "https://api.weibo.com/")!) instance.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json", "text/json", "text/javascript", "text/plain") as Set<NSObject> return instance }() // MARK: - OAuth 授权相关信息 private var clientId = "113773579" private var clientSecret = "a34f52ecaad5571bfed41e6df78299f6" var redirectUri = "http://www.baidu.com" /// 授权 URL var oauthURL: NSURL { return NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(clientId)&redirect_uri=\(redirectUri)")! } /// 使用 code 获取 accessToken /// /// - parameter code: 请求码 func loadAccessToken(code: String, finished: (result: [String: AnyObject]?, error: NSError?)->()) { let urlString = "https://api.weibo.com/oauth2/access_token" let parames = ["client_id": clientId, "client_secret": clientSecret, "grant_type": "authorization_code", "code": code, "redirect_uri": redirectUri] POST(urlString, parameters: parames, success: { (_, JSON) in finished(result: JSON as? [String: AnyObject], error: nil) }) { (_, error) in finished(result: nil, error: error) } } }
mit
86515e1279d4a1245c0980fc9b3dda01
31.34
158
0.612245
3.943902
false
false
false
false
ylovesy/CodeFun
mayu/Decode Ways.swift
1
1137
import Foundation /* A message containing letters from A-Z is being encoded to numbers using the following mapping: 'A' -> 1 'B' -> 2 ... 'Z' -> 26 Given an encoded message containing digits, determine the total number of ways to decode it. For example, Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12). The number of ways decoding "12" is 2. */ private class Solution { func numDecodings(_ s: String) -> Int { if s.characters.count == 0 { return 0 } var dp = [Int](repeating: 0, count: s.characters.count + 1) dp[s.characters.count] = 1 var chAry = [Character]() for ch in s.characters { chAry.append(ch) } dp[s.characters.count - 1] = chAry[chAry.count - 1] != "0" ? 1 : 0 for i in (0 ..< s.characters.count - 1).reversed() { if chAry[i] != "0" { let str = "\(chAry[i])" + "\(chAry[i + 1])" dp[i] = Int(str)! <= 26 ? dp[i + 1] + dp[i + 2] : dp[i + 1] } else { continue } } return dp[0] } }
apache-2.0
bda68989696e07f7d9956defe7868223
28.921053
95
0.513632
3.445455
false
false
false
false
Boilertalk/VaporFacebookBot
Sources/VaporFacebookBot/Webhooks/FacebookMessage.swift
1
1517
// // FacebookMessage.swift // VaporFacebookBot // // Created by Koray Koska on 24/05/2017. // // import Foundation import Vapor public final class FacebookMessage: JSONConvertible { public var mid: String public var text: String? public var attachments: [FacebookAttachment]? public var quickReply: FacebookQuickReply? public init(json: JSON) throws { mid = try json.get("mid") text = json["text"]?.string if let attachementsJson = json["attachments"]?.array { var attachmentsArray = [FacebookAttachment]() for a in attachementsJson { attachmentsArray.append(try FacebookAttachment(json: a)) } attachments = attachmentsArray } if let q = json["quick_reply"] { quickReply = try FacebookQuickReply(json: q) } } public func makeJSON() throws -> JSON { var json = JSON() try json.set("mid", mid) if let text = text { try json.set("text", text) } if let attachments = attachments { try json.set("attachments", JSON(attachments.jsonArray())) } return json } } public final class FacebookQuickReply: JSONConvertible { public var payload: String public init(json: JSON) throws { payload = try json.get("payload") } public func makeJSON() throws -> JSON { var json = JSON() try json.set("payload", payload) return json } }
mit
8dd5c24a7f33528c376a4f1d1d149467
23.467742
72
0.592617
4.474926
false
false
false
false
bigxodus/candlelight
candlelight/screen/main/model/community/Comment.swift
1
1096
// // Comment.swift // candlelight // // Created by Lawrence on 2017. 3. 6.. // Copyright © 2017년 Waynlaw. All rights reserved. // import Foundation class Comment { // 댓글 var content: String? // 작성자 var author: String? // 작성일 var regDate: Date? // 댓글 깊이 var depth: Int? public init() { } public init(author: String, content: String, regDate: Date, depth: Int) { self.content = content self.author = author self.regDate = regDate self.depth = depth } func toHtml() -> String { let res = "<div class='depth\(depth!) '> <p> <span class='author'>\(author!)</span> <span class='reg-date'>\(dateToString(regDate!))</span> </p> <span class='comment'> \(content!) </span> </div>" return res } func dateToString(_ date: Date) -> String { let formatter = DateFormatter() formatter.locale = Locale(identifier: "ko_KR") formatter.setLocalizedDateFormatFromTemplate("MM.dd HH:mm:ss") return formatter.string(from: date) } }
apache-2.0
7c3fedd86ca0c0db38806f7cf80b46f5
22.23913
203
0.5884
3.587248
false
false
false
false
Webtrekk/webtrekk-ios-sdk
Source/Public/Properties/GlobalProperties.swift
1
2313
public class GlobalProperties: BaseProperties { public var crossDeviceProperties: CrossDeviceProperties public var variables: [String: String] public init( actionProperties: ActionProperties = ActionProperties(), advertisementProperties: AdvertisementProperties = AdvertisementProperties(), crossDeviceProperties: CrossDeviceProperties = CrossDeviceProperties(), ecommerceProperties: EcommerceProperties = EcommerceProperties(), ipAddress: String? = nil, mediaProperties: MediaProperties = MediaProperties(), pageProperties: PageProperties = PageProperties(), sessionDetails: [Int: TrackingValue] = [:], userProperties: UserProperties = UserProperties(), variables: [String: String] = [:] ) { self.crossDeviceProperties = crossDeviceProperties self.variables = variables super.init(actionProperties: actionProperties, advertisementProperties: advertisementProperties, ecommerceProperties: ecommerceProperties, ipAddress: ipAddress, mediaProperties: mediaProperties, pageProperties: pageProperties, sessionDetails: sessionDetails, userProperties: userProperties) } internal func merged(over other: GlobalProperties) -> GlobalProperties { let global = GlobalProperties( actionProperties: actionProperties.merged(over: other.actionProperties), advertisementProperties: advertisementProperties.merged(over: other.advertisementProperties), crossDeviceProperties: crossDeviceProperties.merged(over: other.crossDeviceProperties), ecommerceProperties: ecommerceProperties.merged(over: other.ecommerceProperties), ipAddress: ipAddress ?? other.ipAddress, mediaProperties: mediaProperties.merged(over: other.mediaProperties), pageProperties: pageProperties.merged(over: other.pageProperties), sessionDetails: sessionDetails.merged(over: other.sessionDetails), userProperties: userProperties.merged(over: other.userProperties), variables: variables.merged(over: other.variables) ) global.trackingParameters = self.trackingParameters ?? other.trackingParameters return global } }
mit
e35ddd5a6b73068863c2146dd4cec179
52.790698
105
0.71725
5.796992
false
false
false
false
TonnyTao/HowSwift
how_to_update_view_in_mvvm.playground/Sources/RxSwift/RxSwift/Observables/ObserveOn.swift
8
7640
// // ObserveOn.swift // RxSwift // // Created by Krunoslav Zaher on 7/25/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // extension ObservableType { /** Wraps the source sequence in order to run its observer callbacks on the specified scheduler. This only invokes observer callbacks on a `scheduler`. In case the subscription and/or unsubscription actions have side-effects that require to be run on a scheduler, use `subscribeOn`. - seealso: [observeOn operator on reactivex.io](http://reactivex.io/documentation/operators/observeon.html) - parameter scheduler: Scheduler to notify observers on. - returns: The source sequence whose observations happen on the specified scheduler. */ public func observe(on scheduler: ImmediateSchedulerType) -> Observable<Element> { guard let serialScheduler = scheduler as? SerialDispatchQueueScheduler else { return ObserveOn(source: self.asObservable(), scheduler: scheduler) } return ObserveOnSerialDispatchQueue(source: self.asObservable(), scheduler: serialScheduler) } /** Wraps the source sequence in order to run its observer callbacks on the specified scheduler. This only invokes observer callbacks on a `scheduler`. In case the subscription and/or unsubscription actions have side-effects that require to be run on a scheduler, use `subscribeOn`. - seealso: [observeOn operator on reactivex.io](http://reactivex.io/documentation/operators/observeon.html) - parameter scheduler: Scheduler to notify observers on. - returns: The source sequence whose observations happen on the specified scheduler. */ @available(*, deprecated, renamed: "observe(on:)") public func observeOn(_ scheduler: ImmediateSchedulerType) -> Observable<Element> { observe(on: scheduler) } } final private class ObserveOn<Element>: Producer<Element> { let scheduler: ImmediateSchedulerType let source: Observable<Element> init(source: Observable<Element>, scheduler: ImmediateSchedulerType) { self.scheduler = scheduler self.source = source #if TRACE_RESOURCES _ = Resources.incrementTotal() #endif } override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { let sink = ObserveOnSink(scheduler: self.scheduler, observer: observer, cancel: cancel) let subscription = self.source.subscribe(sink) return (sink: sink, subscription: subscription) } #if TRACE_RESOURCES deinit { _ = Resources.decrementTotal() } #endif } enum ObserveOnState : Int32 { // pump is not running case stopped = 0 // pump is running case running = 1 } final private class ObserveOnSink<Observer: ObserverType>: ObserverBase<Observer.Element> { typealias Element = Observer.Element let scheduler: ImmediateSchedulerType var lock = SpinLock() let observer: Observer // state var state = ObserveOnState.stopped var queue = Queue<Event<Element>>(capacity: 10) let scheduleDisposable = SerialDisposable() let cancel: Cancelable init(scheduler: ImmediateSchedulerType, observer: Observer, cancel: Cancelable) { self.scheduler = scheduler self.observer = observer self.cancel = cancel } override func onCore(_ event: Event<Element>) { let shouldStart = self.lock.performLocked { () -> Bool in self.queue.enqueue(event) switch self.state { case .stopped: self.state = .running return true case .running: return false } } if shouldStart { self.scheduleDisposable.disposable = self.scheduler.scheduleRecursive((), action: self.run) } } func run(_ state: (), _ recurse: (()) -> Void) { let (nextEvent, observer) = self.lock.performLocked { () -> (Event<Element>?, Observer) in if !self.queue.isEmpty { return (self.queue.dequeue(), self.observer) } else { self.state = .stopped return (nil, self.observer) } } if let nextEvent = nextEvent, !self.cancel.isDisposed { observer.on(nextEvent) if nextEvent.isStopEvent { self.dispose() } } else { return } let shouldContinue = self.shouldContinue_synchronized() if shouldContinue { recurse(()) } } func shouldContinue_synchronized() -> Bool { self.lock.performLocked { let isEmpty = self.queue.isEmpty if isEmpty { self.state = .stopped } return !isEmpty } } override func dispose() { super.dispose() self.cancel.dispose() self.scheduleDisposable.dispose() } } #if TRACE_RESOURCES private let numberOfSerialDispatchObservables = AtomicInt(0) extension Resources { /** Counts number of `SerialDispatchQueueObservables`. Purposed for unit tests. */ public static var numberOfSerialDispatchQueueObservables: Int32 { return load(numberOfSerialDispatchObservables) } } #endif final private class ObserveOnSerialDispatchQueueSink<Observer: ObserverType>: ObserverBase<Observer.Element> { let scheduler: SerialDispatchQueueScheduler let observer: Observer let cancel: Cancelable var cachedScheduleLambda: (((sink: ObserveOnSerialDispatchQueueSink<Observer>, event: Event<Element>)) -> Disposable)! init(scheduler: SerialDispatchQueueScheduler, observer: Observer, cancel: Cancelable) { self.scheduler = scheduler self.observer = observer self.cancel = cancel super.init() self.cachedScheduleLambda = { pair in guard !cancel.isDisposed else { return Disposables.create() } pair.sink.observer.on(pair.event) if pair.event.isStopEvent { pair.sink.dispose() } return Disposables.create() } } override func onCore(_ event: Event<Element>) { _ = self.scheduler.schedule((self, event), action: self.cachedScheduleLambda!) } override func dispose() { super.dispose() self.cancel.dispose() } } final private class ObserveOnSerialDispatchQueue<Element>: Producer<Element> { let scheduler: SerialDispatchQueueScheduler let source: Observable<Element> init(source: Observable<Element>, scheduler: SerialDispatchQueueScheduler) { self.scheduler = scheduler self.source = source #if TRACE_RESOURCES _ = Resources.incrementTotal() _ = increment(numberOfSerialDispatchObservables) #endif } override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { let sink = ObserveOnSerialDispatchQueueSink(scheduler: self.scheduler, observer: observer, cancel: cancel) let subscription = self.source.subscribe(sink) return (sink: sink, subscription: subscription) } #if TRACE_RESOURCES deinit { _ = Resources.decrementTotal() _ = decrement(numberOfSerialDispatchObservables) } #endif }
mit
29849d078be70c441e1eabdc7625e9cb
30.436214
171
0.645634
4.99281
false
false
false
false
tom-wolters/TWLocalize
Pods/TWLocalize/TWLocalize/TWLocalize.swift
1
2148
// // Localize.swift // Tickee // // Created by Tom Wolters on 16-06-17. // Copyright © 2017 Tickee. All rights reserved. // import UIKit public typealias TWLocalizedText = [TWLanguageCode:String] public enum TWLanguageCode:String { case dutch = "nl" case english = "en" case spanish = "es" case french = "fr" case turkish = "tr" case german = "de" case portuguese = "pt" } /** ## Example usage: ``` extension TWLocalizedStrings { static let LoginHeader:TWLocalizedText = [.dutch: "Verstuur tickets naar je vrienden", .english: "Send tickets to your friends" ] } ``` */ public struct TWLocalizedStrings {} public final class TWLocalize { fileprivate static var defaultLanguage:String? { set { UserDefaults.standard.set(newValue, forKey: "TWLocalizedCustomLanguageIdentifier") UserDefaults.standard.synchronize() } get { return UserDefaults.standard.string(forKey: "TWLocalizedCustomLanguageIdentifier") } } fileprivate static var languageCode:TWLanguageCode? { if let languageCode = defaultLanguage { return TWLanguageCode(rawValue: languageCode) } else if let currentLanguageCode = NSLocale(localeIdentifier: Locale.current.identifier).object(forKey: NSLocale.Key.languageCode) as? String { return TWLanguageCode(rawValue: currentLanguageCode) } return nil } public class func setLanguage(to languageCode:TWLanguageCode?) { guard let code = languageCode else { defaultLanguage = nil ; return } let languageCodes = Locale.availableIdentifiers.map { NSLocale(localeIdentifier: $0).object(forKey: NSLocale.Key.languageCode) as! String } guard let _ = languageCodes.index(of: code.rawValue) else { Logger.log(.error("\(code.rawValue) is not a valid language code")) ; return } defaultLanguage = code.rawValue } public class func text(_ localizedText:TWLocalizedText) -> String? { return localizedText[languageCode!] ?? localizedText[.english] ?? localizedText.first?.value } }
mit
2cdf14552a146794d46f4057c7a1dc92
33.629032
152
0.673032
4.417695
false
false
false
false
xedin/swift
test/SILGen/existential_erasure.swift
12
4718
// RUN: %target-swift-emit-silgen -module-name existential_erasure %s | %FileCheck %s protocol P { func downgrade(_ m68k: Bool) -> Self func upgrade() throws -> Self } protocol Q {} struct X: P, Q { func downgrade(_ m68k: Bool) -> X { return self } func upgrade() throws -> X { return self } } func makePQ() -> P & Q { return X() } func useP(_ x: P) { } func throwingFunc() throws -> Bool { return true } // CHECK-LABEL: sil hidden [ossa] @$s19existential_erasure5PQtoPyyF : $@convention(thin) () -> () { func PQtoP() { // CHECK: [[PQ_PAYLOAD:%.*]] = open_existential_addr immutable_access [[PQ:%.*]] : $*P & Q to $*[[OPENED_TYPE:@opened(.*) P & Q]] // CHECK: [[P_PAYLOAD:%.*]] = init_existential_addr [[P:%.*]] : $*P, $[[OPENED_TYPE]] // CHECK: copy_addr [[PQ_PAYLOAD]] to [initialization] [[P_PAYLOAD]] // CHECK: destroy_addr [[PQ]] // CHECK-NOT: destroy_addr [[P]] // CHECK-NOT: destroy_addr [[P_PAYLOAD]] // CHECK-NOT: deinit_existential_addr [[PQ]] // CHECK-NOT: destroy_addr [[PQ_PAYLOAD]] useP(makePQ()) } // Make sure uninitialized existentials are properly deallocated when we // have an early return. // CHECK-LABEL: sil hidden [ossa] @$s19existential_erasure19openExistentialToP1yyAA1P_pKF func openExistentialToP1(_ p: P) throws { // CHECK: bb0(%0 : $*P): // CHECK: [[OPEN:%.*]] = open_existential_addr immutable_access %0 : $*P to $*[[OPEN_TYPE:@opened\(.*\) P]] // CHECK: [[RESULT:%.*]] = alloc_stack $P // CHECK: [[FUNC:%.*]] = function_ref @$s19existential_erasure12throwingFuncSbyKF // CHECK: try_apply [[FUNC]]() // // CHECK: bb1([[SUCCESS:%.*]] : $Bool): // CHECK: [[METHOD:%.*]] = witness_method $[[OPEN_TYPE]], #P.downgrade!1 : {{.*}}, [[OPEN]] // CHECK: [[RESULT_ADDR:%.*]] = init_existential_addr [[RESULT]] : $*P, $[[OPEN_TYPE]] // CHECK: apply [[METHOD]]<[[OPEN_TYPE]]>([[RESULT_ADDR]], [[SUCCESS]], [[OPEN]]) // CHECK: dealloc_stack [[RESULT]] // CHECK: return // // CHECK: bb2([[FAILURE:%.*]] : @owned $Error): // CHECK: dealloc_stack [[RESULT]] // CHECK: throw [[FAILURE]] // try useP(p.downgrade(throwingFunc())) } // CHECK-LABEL: sil hidden [ossa] @$s19existential_erasure19openExistentialToP2yyAA1P_pKF func openExistentialToP2(_ p: P) throws { // CHECK: bb0(%0 : $*P): // CHECK: [[OPEN:%.*]] = open_existential_addr immutable_access %0 : $*P to $*[[OPEN_TYPE:@opened\(.*\) P]] // CHECK: [[RESULT:%.*]] = alloc_stack $P // CHECK: [[METHOD:%.*]] = witness_method $[[OPEN_TYPE]], #P.upgrade!1 : {{.*}}, [[OPEN]] // CHECK: [[RESULT_ADDR:%.*]] = init_existential_addr [[RESULT]] : $*P, $[[OPEN_TYPE]] // CHECK: try_apply [[METHOD]]<[[OPEN_TYPE]]>([[RESULT_ADDR]], [[OPEN]]) // // CHECK: bb1 // CHECK: dealloc_stack [[RESULT]] // CHECK: return // // CHECK: bb2([[FAILURE:%.*]]: @owned $Error): // CHECK: deinit_existential_addr [[RESULT]] // CHECK: dealloc_stack [[RESULT]] // CHECK: throw [[FAILURE]] // try useP(p.upgrade()) } // Same as above but for boxed existentials extension Error { func returnOrThrowSelf() throws -> Self { throw self } } // CHECK-LABEL: sil hidden [ossa] @$s19existential_erasure12errorHandlerys5Error_psAC_pKF func errorHandler(_ e: Error) throws -> Error { // CHECK: bb0([[ARG:%.*]] : @guaranteed $Error): // CHECK: debug_value [[ARG]] : $Error // CHECK: [[OPEN:%.*]] = open_existential_box [[ARG]] : $Error to $*[[OPEN_TYPE:@opened\(.*\) Error]] // CHECK: [[FUNC:%.*]] = function_ref @$ss5ErrorP19existential_erasureE17returnOrThrowSelf{{[_0-9a-zA-Z]*}}F // CHECK: [[RESULT:%.*]] = alloc_existential_box $Error, $[[OPEN_TYPE]] // CHECK: [[ADDR:%.*]] = project_existential_box $[[OPEN_TYPE]] in [[RESULT]] : $Error // CHECK: store [[RESULT]] to [init] [[RESULT_BUF:%.*]] : // CHECK: try_apply [[FUNC]]<[[OPEN_TYPE]]>([[ADDR]], [[OPEN]]) // // CHECK: bb1 // CHECK: [[RESULT2:%.*]] = load [take] [[RESULT_BUF]] // CHECK: return [[RESULT2]] : $Error // // CHECK: bb2([[FAILURE:%.*]] : @owned $Error): // CHECK: [[RESULT3:%.*]] = load [take] [[RESULT_BUF]] // CHECK: dealloc_existential_box [[RESULT3]] // CHECK: throw [[FAILURE]] : $Error // return try e.returnOrThrowSelf() } // rdar://problem/22003864 -- SIL verifier crash when init_existential_addr // references dynamic Self type class EraseDynamicSelf { required init() {} // CHECK-LABEL: sil hidden [ossa] @$s19existential_erasure16EraseDynamicSelfC7factoryACXDyFZ : $@convention(method) (@thick EraseDynamicSelf.Type) -> @owned EraseDynamicSelf // CHECK: [[ANY:%.*]] = alloc_stack $Any // CHECK: init_existential_addr [[ANY]] : $*Any, $@dynamic_self EraseDynamicSelf // class func factory() -> Self { let instance = self.init() let _: Any = instance return instance } }
apache-2.0
a2acf82de0346f65feb00c7101bb169b
35.015267
173
0.613184
3.290098
false
false
false
false
tatey/Lighting
Main/LoggedOutViewController.swift
1
1505
// // Created by Tate Johnson on 21/07/2015. // Copyright (c) 2015 Tate Johnson. All rights reserved. // import Cocoa import LIFXHTTPKit protocol LoggedOutViewControllerDelegate: class { func loggedOutViewControllerDidLogin(_ controller: LoggedOutViewController, withToken token: String) } class LoggedOutViewController: NSViewController { @IBOutlet weak var tokenTextField: NSTextField? @IBOutlet weak var loginButton: NSButton? @IBOutlet weak var spinner: NSProgressIndicator? @IBOutlet weak var errorLabel: NSTextField? weak var delegate: LoggedOutViewControllerDelegate? override func awakeFromNib() { super.awakeFromNib() preferredContentSize = view.frame.size } override func viewDidAppear() { super.viewDidAppear() tokenTextField?.becomeFirstResponder() } @IBAction func loginButtonDidGetTapped(_ sender: AnyObject?) { if let newToken = tokenTextField?.stringValue { let client = Client(accessToken: newToken) tokenTextField?.isEnabled = false loginButton?.isEnabled = false spinner?.startAnimation(self) errorLabel?.isHidden = true client.fetch { (errors) in DispatchQueue.main.async { if errors.count > 0 { self.errorLabel?.isHidden = false } else { self.tokenTextField?.stringValue = "" self.delegate?.loggedOutViewControllerDidLogin(self, withToken: newToken) } self.spinner?.stopAnimation(self) self.tokenTextField?.isEnabled = true self.loginButton?.isEnabled = true } } } } }
gpl-3.0
ce2420c4656861ecf32b87fa1745a3ef
24.948276
101
0.73887
4.239437
false
false
false
false
vincentherrmann/multilinear-math
Sources/TensorOperationNodes.swift
1
6568
// // TensorOperationNodes.swift // MultilinearMath // // Created by Vincent Herrmann on 20.07.16. // Copyright © 2016 Vincent Herrmann. All rights reserved. // import Foundation import Accelerate public protocol TensorOperationNode { static var inputCount: Int {get} static var outputCount: Int {get} mutating func setup() func execute(_ input: [Tensor<Float>]) -> [Tensor<Float>] } protocol TensorFourierTransform { static var transformSetup: (vDSP_DFT_Setup?, vDSP_Length) -> OpaquePointer {get} static var transformFunction: (OpaquePointer, UnsafePointer<Float>, UnsafePointer<Float>, UnsafeMutablePointer<Float>, UnsafeMutablePointer<Float>) -> () {get} var modeSizes: [Int] {get} var transformSizes: [Int]! {get set} var dftSetups: [OpaquePointer] {get set} } extension TensorFourierTransform { mutating func setupTransform() { /// next biggest integer base 2 logarithms of the mode sizes let logSizes = modeSizes.map{Int(ceil(log2(Float($0))))} transformSizes = logSizes.map{Int(pow(2, Float($0)))} print("transform sizes: \(transformSizes)") //create dft setup for each mode dftSetups = [] var currentSetup: OpaquePointer? = nil for size in transformSizes { currentSetup = Self.transformSetup(currentSetup, UInt(size)) dftSetups.append(currentSetup!) } } func performFourierTransform(_ input: Tensor<Float>) -> Tensor<Float> { var inputTensor = input print("input tensor sizes: \(inputTensor.modeSizes)") var outputTensor = [Tensor<Float>(withPropertiesOf: inputTensor)] for mode in 0..<modeSizes.count { var outerModes = inputTensor.modeArray outerModes.removeFirst() outerModes.remove(at: mode) //let modeSize = transformSizes[mode] let vectorSize = transformSizes[mode] ///array of padding zeros for the fft // let paddingZeros = [Float](count: vectorSize - modeSizes[mode], repeatedValue: 0) print("mode \(mode), vectorSize: \(vectorSize)") inputTensor.performForOuterModes(outerModes, outputData: &outputTensor, calculate: { (currentIndex, outerIndex, sourceData) -> [Tensor<Float>] in let real = sourceData[slice: currentIndex][0...0, all].values let imag = sourceData[slice: currentIndex][1...1, all].values print("index \(currentIndex) real vector: \(real)") print("index \(currentIndex) imag vector: \(imag)") var realOutValues = [Float](repeating: 0, count: vectorSize) var imagOutValues = [Float](repeating: 0, count: vectorSize) Self.transformFunction(self.dftSetups[mode], real, imag, &realOutValues, &imagOutValues) let outputValues = realOutValues + imagOutValues let output = Tensor<Float>(modeSizes: [2, vectorSize], values: outputValues) // print("index \(currentIndex) real output: \(realOutValues)") // print("index \(currentIndex) imag output: \(imagOutValues)") return [output] }, writeOutput: { (currentIndex, outerIndex, inputData, outputData) in outputData[0][slice: currentIndex] = inputData[0] }) inputTensor = outputTensor[0] } return outputTensor[0] } } public struct FourierTransform: TensorFourierTransform, TensorOperationNode { public static var inputCount = 1 public static var outputCount = 1 static var transformSetup: (vDSP_DFT_Setup?, vDSP_Length) -> OpaquePointer = {(prevSetup, length) -> OpaquePointer in return vDSP_DFT_zop_CreateSetup(prevSetup, length, vDSP_DFT_Direction.FORWARD)! } static var transformFunction = {(setup, realIn, imagIn, realOut, imagOut) -> () in vDSP_DFT_Execute(setup, realIn, imagIn, realOut, imagOut) } var modeSizes: [Int] var transformSizes: [Int]! var dftSetups: [vDSP_DFT_Setup] = [] public init(modeSizes: [Int]) { self.modeSizes = modeSizes setup() } mutating public func setup() { setupTransform() } public func execute(_ input: [Tensor<Float>]) -> [Tensor<Float>] { print("transform sizes: \(transformSizes)") let paddedInput = changeModeSizes(input[0], targetSizes: [2] + transformSizes) print("padded input sizes: \(paddedInput.modeSizes)") let output = performFourierTransform(paddedInput) return [output] } } public struct InverseFourierTransform: TensorFourierTransform, TensorOperationNode { public static var inputCount = 1 public static var outputCount = 1 static var transformSetup: (vDSP_DFT_Setup?, vDSP_Length) -> OpaquePointer = {(prevSetup, length) -> OpaquePointer in return vDSP_DFT_zop_CreateSetup(prevSetup, length, vDSP_DFT_Direction.INVERSE)! } static var transformFunction = {(setup, realIn, imagIn, realOut, imagOut) -> () in vDSP_DFT_Execute(setup, realIn, imagIn, realOut, imagOut) } var modeSizes: [Int] var transformSizes: [Int]! var dftSetups: [vDSP_DFT_Setup] = [] public init(modeSizes: [Int]) { self.modeSizes = modeSizes setup() } mutating public func setup() { setupTransform() } public func execute(_ input: [Tensor<Float>]) -> [Tensor<Float>] { let factor = 1 / Float(transformSizes.reduce(1, {$0*$1})) let output = performFourierTransform(input[0]) * factor let scaledOutput = changeModeSizes(output, targetSizes: [2] + modeSizes) return [scaledOutput] } }
apache-2.0
990e2ff88dc0416bbf934e4441400caf
41.921569
163
0.56053
4.83223
false
false
false
false
onevcat/Kingfisher
Sources/General/ImageSource/Source.swift
2
4277
// // Source.swift // Kingfisher // // Created by onevcat on 2018/11/17. // // Copyright (c) 2019 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /// Represents an image setting source for Kingfisher methods. /// /// A `Source` value indicates the way how the target image can be retrieved and cached. /// /// - network: The target image should be got from network remotely. The associated `Resource` /// value defines detail information like image URL and cache key. /// - provider: The target image should be provided in a data format. Normally, it can be an image /// from local storage or in any other encoding format (like Base64). public enum Source { /// Represents the source task identifier when setting an image to a view with extension methods. public enum Identifier { /// The underlying value type of source identifier. public typealias Value = UInt static var current: Value = 0 static func next() -> Value { current += 1 return current } } // MARK: Member Cases /// The target image should be got from network remotely. The associated `Resource` /// value defines detail information like image URL and cache key. case network(Resource) /// The target image should be provided in a data format. Normally, it can be an image /// from local storage or in any other encoding format (like Base64). case provider(ImageDataProvider) // MARK: Getting Properties /// The cache key defined for this source value. public var cacheKey: String { switch self { case .network(let resource): return resource.cacheKey case .provider(let provider): return provider.cacheKey } } /// The URL defined for this source value. /// /// For a `.network` source, it is the `downloadURL` of associated `Resource` instance. /// For a `.provider` value, it is always `nil`. public var url: URL? { switch self { case .network(let resource): return resource.downloadURL case .provider(let provider): return provider.contentURL } } } extension Source: Hashable { public static func == (lhs: Source, rhs: Source) -> Bool { switch (lhs, rhs) { case (.network(let r1), .network(let r2)): return r1.cacheKey == r2.cacheKey && r1.downloadURL == r2.downloadURL case (.provider(let p1), .provider(let p2)): return p1.cacheKey == p2.cacheKey && p1.contentURL == p2.contentURL case (.provider(_), .network(_)): return false case (.network(_), .provider(_)): return false } } public func hash(into hasher: inout Hasher) { switch self { case .network(let r): hasher.combine(r.cacheKey) hasher.combine(r.downloadURL) case .provider(let p): hasher.combine(p.cacheKey) hasher.combine(p.contentURL) } } } extension Source { var asResource: Resource? { guard case .network(let resource) = self else { return nil } return resource } }
mit
cf89b55f2ced08f58e3e53d71f51b8dc
35.87069
101
0.656067
4.502105
false
false
false
false
Matzo/Edamame
Pod/Classes/Edamame.swift
1
21788
// // DataSource.swift // DataSource // // Created by 松尾 圭祐 on 2016/02/11. // Copyright © 2016年 松尾 圭祐. All rights reserved. // import UIKit open class Edamame: NSObject { enum UpdateType { case append(item: EdamameItem, section: Int) case insert(item: EdamameItem, indexPath: IndexPath) case delete(indexPaths: [IndexPath]) case appendSupplementary(item: EdamameSupplementaryItem, kind: String, section: Int) case deleteSupplementary(kind: String, section: Int) } // readonly internal var _collectionView: UICollectionView internal var _sections = [EdamameSection]() internal var _updates: [UpdateType] = [] // public override init() { fatalError("required collectionView") } public init(collectionView: UICollectionView) { self._collectionView = collectionView super.init() self.collectionView.delegate = self self.collectionView.dataSource = self self.registerClassFromClass(UICollectionViewCell.self) self.registerClassFromClass(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader) self.registerClassFromClass(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter) } } // MARK: Public Methods public extension Edamame { // accessor public var collectionView: UICollectionView { return _collectionView } public var sections: [EdamameSection] { return _sections } subscript(index: Int) -> EdamameSection { get { if sections.count > index { return self.sections[index] } else { var section = self.createSection() while self.sections.count <= index { section = self.createSection() } return section } } } subscript(index: IndexPath) -> Any { get { return self[index.section][index.item] } } func createSection(_ cellType: UICollectionViewCell.Type? = nil, atIndex index: Int? = nil) -> EdamameSection { let section = EdamameSection(cellType: cellType) if let index = index { self.insertSection(section, atIndex: index) } else { self.appendSection(section) } section.reloadData(animated: false) return section } func appendSection(_ section: EdamameSection) { section.dataSource = self self._sections.append(section) } func insertSection(_ section: EdamameSection, atIndex: Int) { section.dataSource = self self._sections.insert(section, at: atIndex) } func reloadSections(animated: Bool = true) { if self.sections.count > 0 { for section in 0..<self.sections.count { self.reloadSection(section: section, animated: animated) } } } func reloadSection(section: Int, animated: Bool = false) { if animated && !self[section].hidden { applyUpdates(section: section) self.collectionView.reloadSections([section]) } else { UIView.performWithoutAnimation { applyUpdates(section: section) self.collectionView.reloadData() } } } func setNeedsLayout(animated: Bool = false) { let block = { for section in self.sections { for item in section.items { item.needsLayout = true } for (_, supplementaryItem) in section.supplementaryItems { supplementaryItem.needsLayout = true } } self.collectionView.collectionViewLayout.invalidateLayout() } if animated { UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.5, options: .curveEaseOut, animations: { block() }) { (done) in } } else { block() } } func setNeedsLayout(_ indexPath: IndexPath, animated: Bool = false) { guard self.sections.count > indexPath.section else { return } guard self.sections[indexPath.section].items.count > indexPath.item else { return } let block = { self.sections[indexPath.section].items[indexPath.item].needsLayout = true self.collectionView.collectionViewLayout.invalidateLayout() } if animated { UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.5, options: .curveEaseOut, animations: { block() }) { (done) in } } else { block() } } func reloadData(animated: Bool = false) { self.reloadHiddenSections() if animated { self.collectionView.performBatchUpdates({ self.applyUpdatesAnimating() }, completion: { (done) in self.collectionView.reloadData() }) } else { applyUpdates() self.collectionView.reloadData() } } func reloadHiddenSections() { sections.forEach { (section) in guard section.hidden else { return } reloadSection(section: section.index, animated: false) } } func applyUpdates() { for update in self._updates { switch update { case .append(let item, let section): self[section].items.append(item) case .insert(let item, let indexPath): self[indexPath.section].items.insert(item, at: indexPath.item) case .delete(let indexPaths): var indexListPerSection: [[Int]] = [] for section in 0..<self.collectionView.numberOfSections { indexListPerSection.append(indexPaths.filter({ $0.section == section }).map({ $0.item })) } for (section, indexList) in indexListPerSection.enumerated() { let section = self[section] for removeIndex in indexList.sorted(by: >) { section.items.remove(at: removeIndex) } } case .appendSupplementary(let item, let kind, let section): self[section].supplementaryItems[kind] = item case .deleteSupplementary(let kind, let section): self[section].supplementaryItems[kind] = nil } } self._updates.removeAll() self.collectionView.collectionViewLayout.invalidateLayout() } func applyUpdates(section sectionIndex: Int) { for update in self._updates { switch update { case .append(let item, let section): guard section == sectionIndex else { continue } self[section].items.append(item) case .insert(let item, let indexPath): guard indexPath.section == sectionIndex else { continue } self[indexPath.section].items.insert(item, at: indexPath.item) case .delete(let indexPaths): var indexListPerSection: [[Int]] = [] for _section in 0..<self.collectionView.numberOfSections { indexListPerSection.append(indexPaths.filter({ $0.section == _section }).map({ $0.item })) } for (_section, indexList) in indexListPerSection.enumerated() { guard _section == sectionIndex else { continue } let section = self[_section] for removeIndex in indexList.sorted(by: >) { section.items.remove(at: removeIndex) } } case .appendSupplementary(let item, let kind, let section): guard section == sectionIndex else { continue } self[section].supplementaryItems[kind] = item case .deleteSupplementary(let kind, let section): guard section == sectionIndex else { continue } self[section].supplementaryItems[kind] = nil } } var remainedUpdates: [UpdateType] = [] for update in _updates { switch update { case .append(_, let section): if section != sectionIndex { remainedUpdates.append(update) } case .insert(_, let indexPath): if indexPath.section != sectionIndex { remainedUpdates.append(update) } case .delete(let indexPaths): let remainedDeleteIndexPaths: [IndexPath] = indexPaths.filter({ $0.section != sectionIndex }) if remainedDeleteIndexPaths.count > 0 { remainedUpdates.append(.delete(indexPaths: remainedDeleteIndexPaths)) } case .appendSupplementary(_, _, let section): if section != sectionIndex { remainedUpdates.append(update) } case .deleteSupplementary(_, let section): if section != sectionIndex { remainedUpdates.append(update) } } } self._updates = remainedUpdates self.collectionView.collectionViewLayout.invalidateLayout() } func applyUpdatesAnimating() { var adding: [IndexPath] = [] var deleting: [IndexPath] = [] for update in self._updates { switch update { case .append(let item, let section): let addingCount = itemsCount(indexPaths: adding, inSection: section) let deletingCount = itemsCount(indexPaths: deleting, inSection: section) let indexPath = IndexPath(item: max(self.collectionView.numberOfItems(inSection: section) - deletingCount + addingCount, 0), section: section) self[section].items.append(item) if deleting.contains(indexPath) { deleting = deleting.filter({ $0 != indexPath }) } else { adding.append(indexPath) } case .insert(let item, let indexPath): self[indexPath.section].items.insert(item, at: indexPath.item) if deleting.contains(indexPath) { deleting = deleting.filter({ $0 != indexPath }) } else { adding.append(indexPath) } case .delete(let indexPaths): var indexListPerSection: [[Int]] = [] var deleteIndexPaths: [IndexPath] = [] for section in 0..<self.collectionView.numberOfSections { indexListPerSection.append(indexPaths.filter({ $0.section == section }).map({ $0.item })) } for (section, indexList) in indexListPerSection.enumerated() { let section = self[section] for removeIndex in indexList.sorted(by: >) { section.items.remove(at: removeIndex) } } for indexPath in indexPaths { if adding.contains(indexPath) { adding = adding.filter({ $0 != indexPath }) } else { deleting.append(indexPath) deleteIndexPaths.append(indexPath) } } case .appendSupplementary(let item, let kind, let section): self[section].supplementaryItems[kind] = item case .deleteSupplementary(let kind, let section): self[section].supplementaryItems[kind] = nil } } self.collectionView.insertItems(at: adding) self.collectionView.deleteItems(at: deleting) self._updates.removeAll() self.collectionView.collectionViewLayout.invalidateLayout() } internal func itemsCount(indexPaths: [IndexPath], inSection section: Int) -> Int { return indexPaths.filter({ $0.section == section }).count } func removeItemAtIndexPath(_ indexPath: IndexPath) { self[indexPath.section].removeItemAtIndex(indexPath.item) } func removeAllItems() { self._sections.forEach({ $0.removeAllItems() }) } func removeSections(indexSet: IndexSet, animated: Bool = false) { guard indexSet.filter({ self._sections.count > $0 }).count == indexSet.count else { return } var filteredSections: [EdamameSection] = [] for (index, section) in self._sections.enumerated() { if !indexSet.contains(index) { filteredSections.append(section) } } if animated { self.collectionView.performBatchUpdates({ self._sections = filteredSections self.collectionView.deleteSections(indexSet) }, completion: { (done) in self.collectionView.reloadData() }) } else { self._sections = filteredSections self.collectionView.reloadData() } } func removeSection(index: Int, animated: Bool = false) { self.removeSections(indexSet: [index], animated: animated) } } // MARK: UICollectionViewDelegateFlowLayout extension Edamame: UICollectionViewDelegateFlowLayout { public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if sections.count > indexPath.section { let section = sections[indexPath.section] return section.collectionView(collectionView, layout: collectionViewLayout, sizeForItemAtIndexPath: indexPath) } else { return CGSize.zero } } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { if sections.count > section { let sectionItem = sections[section] return sectionItem.collectionView(collectionView, layout: collectionViewLayout, referenceSizeForHeaderInSection: section) } else { return CGSize.zero } } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize { if sections.count > section { let sectionItem = sections[section] return sectionItem.collectionView(collectionView, layout: collectionViewLayout, referenceSizeForFooterInSection: section) } else { return CGSize.zero } } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { if sections.count > section { let sectionItem = sections[section] return sectionItem.collectionView(collectionView, layout: collectionViewLayout, insetForSectionAtIndex: section) } else { return UIEdgeInsets.zero } } public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { sections[indexPath.section].items[indexPath.item].selectionHandler?(self[indexPath], indexPath) } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { if sections.count > section { return sections[section].collectionView(collectionView, layout: collectionViewLayout, minimumInteritemSpacingForSectionAtIndex: section) } else { return 0 } } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { if sections.count > section { return sections[section].collectionView(collectionView, layout: collectionViewLayout, minimumLineSpacingForSectionAtIndex: section) } else { return 0 } } } // MARK: UICollectionViewDataSource extension Edamame: UICollectionViewDataSource { public func numberOfSections(in collectionView: UICollectionView) -> Int { return sections.count } public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let section = sections[section] return section.numberOfItemsInCollectionView(collectionView) } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let section = sections[indexPath.section] return section.collectionView(collectionView, cellForItemAtIndexPath: indexPath) } public func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let section = sections[indexPath.section] return section.collectionView(collectionView, viewForSupplementaryElementOfKind: kind, atIndexPath: indexPath) } } // MARK: - Utils public extension Edamame { func registerNibFromClass<T: UICollectionViewCell>(_ type: T.Type) { let className = String(describing: type) let nib = UINib(nibName: className, bundle: nil) collectionView.register(nib, forCellWithReuseIdentifier: className) } func registerNibFromClass<T: UICollectionReusableView>(_ type: T.Type, forSupplementaryViewOfKind kind: String) { let className = String(describing: type) let nib = UINib(nibName: className, bundle: nil) collectionView.register(nib, forSupplementaryViewOfKind: kind, withReuseIdentifier: className) } func registerClassFromClass<T: UICollectionViewCell>(_ type: T.Type) { let className = String(describing: type) collectionView.register(T.self, forCellWithReuseIdentifier: className) } func registerClassFromClass<T: UICollectionReusableView>(_ type: T.Type, forSupplementaryViewOfKind kind: String) { let className = String(describing: type) collectionView.register(T.self, forSupplementaryViewOfKind: kind, withReuseIdentifier: className) } func dequeueReusableCell<T: UICollectionViewCell>(_ type: T.Type, forIndexPath indexPath: IndexPath) -> T { return collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: type), for: indexPath) as! T } func dequeueReusableCell<T: UICollectionReusableView>(_ kind: String, withReuseType type: T.Type, forIndexPath indexPath: IndexPath) -> T { return collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: String(describing: type), for: indexPath) as! T } } // MARK: - FlowLayoutProtocol @objc public protocol FlowLayoutProtocol { @objc optional func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize @objc optional func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets @objc optional func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat @objc optional func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat @objc optional func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize @objc optional func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize @objc optional func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: IndexPath) -> UICollectionReusableView @objc optional func collectionView(_ collectionView: UICollectionView, canMoveItemAtIndexPath indexPath: IndexPath) -> Bool @objc optional func collectionView(_ collectionView: UICollectionView, moveItemAtIndexPath sourceIndexPath: IndexPath, toIndexPath destinationIndexPath: IndexPath) @objc optional func collectionView(_ collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: IndexPath) } // MARK: - UICollectionView public extension UICollectionView { var edamame: Edamame? { return dataSource as? Edamame ?? delegate as? Edamame } func isFirstAppearing(_ indexPath: IndexPath) -> Bool { guard let sections = self.edamame?._sections, sections.count > indexPath.section else { return false } guard sections[indexPath.section].items.count > indexPath.item else { return false } return sections[indexPath.section].items[indexPath.item].isFirstAppearing } }
mit
01c34d67bb86e6330e617fad51b9a811
42.889113
193
0.629427
5.597583
false
false
false
false
SteveBarnegren/SwiftChess
SwiftChess/Source/PieceMovement.swift
1
15766
// // Piece.swift // Pods // // Created by Steve Barnegren on 04/09/2016. // // //swiftlint:disable file_length import Foundation // MARK: - PieceMovement (Base Class) let pawnMovement = PieceMovementPawn() let rookMovement = PieceMovementRook() let knightMovement = PieceMovementKnight() let bishopMovement = PieceMovementBishop() let queenMovement = PieceMovementQueen() let kingMovement = PieceMovementKing() open class PieceMovement { public class func pieceMovement(for pieceType: Piece.PieceType) -> PieceMovement { switch pieceType { case .pawn: return pawnMovement case .rook: return rookMovement case .knight: return knightMovement case .bishop: return bishopMovement case .queen: return queenMovement case .king: return kingMovement } } public init() { } func canPieceMove(from fromLocation: BoardLocation, to toLocation: BoardLocation, board: Board, accountForCheckState: Bool = false) -> Bool { if fromLocation == toLocation { return false } let canMove = isMovementPossible(from: fromLocation, to: toLocation, board: board) if canMove && accountForCheckState { let color = board.getPiece(at: fromLocation)!.color var boardCopy = board boardCopy.movePiece(from: fromLocation, to: toLocation) return boardCopy.isColorInCheck(color: color) ? false : true } else { return canMove } } func isMovementPossible(from fromLocation: BoardLocation, to toLocation: BoardLocation, board: Board) -> Bool { return false } // swiftlint:disable function_body_length func canPieceMove(from fromLocation: BoardLocation, to toLocation: BoardLocation, board: Board, stride: BoardStride) -> Bool { enum Direction: Int { case increasing case decresing case none } var strideDirectionX = Direction.none if stride.x < 0 { strideDirectionX = .decresing } if stride.x > 0 { strideDirectionX = .increasing } var locationDirectionX = Direction.none if toLocation.x - fromLocation.x < 0 { locationDirectionX = .decresing } if toLocation.x - fromLocation.x > 0 { locationDirectionX = .increasing } if strideDirectionX != locationDirectionX { return false } var strideDirectionY = Direction.none if stride.y < 0 { strideDirectionY = .decresing } if stride.y > 0 { strideDirectionY = .increasing } var locationDirectionY = Direction.none if toLocation.y - fromLocation.y < 0 { locationDirectionY = .decresing } if toLocation.y - fromLocation.y > 0 { locationDirectionY = .increasing } if strideDirectionY != locationDirectionY { return false } // Make sure cannot take king if let piece = board.getPiece(at: toLocation) { if piece.type == .king { return false } } // Get the moving piece guard let movingPiece = board.getPiece(at: fromLocation) else { print("Cannot from an index that does not contain a piece") return false } // Increment by stride if !fromLocation.canIncrement(by: stride) { return false } var testLocation = fromLocation.incremented(by: stride) while testLocation.isInBounds() { // If there is a piece on the square if let piece = board.getPiece(at: testLocation) { if piece.color == movingPiece.color { return false } if piece.color == movingPiece.color.opposite && testLocation == toLocation { return true } if piece.color == movingPiece.color.opposite && testLocation != toLocation { return false } } // if the square is empty if testLocation == toLocation { return true } // Increment by stride if !testLocation.canIncrement(by: stride) { return false } testLocation = testLocation.incremented(by: stride) } return false } func canPieceOccupySquare(pieceLocation: BoardLocation, xOffset: Int, yOffset: Int, board: Board) -> Bool { let targetLocation = pieceLocation.incrementedBy(x: xOffset, y: yOffset) // Check if in bounds guard targetLocation.isInBounds() else { return false } // Check if wrapped if targetLocation.x - pieceLocation.x != xOffset || targetLocation.y - pieceLocation.y != yOffset { return false } // Check if space is occupied guard let movingPiece = board.getPiece(at: pieceLocation) else { print("Cannot move from an index that does not contain a piece") return false } if let otherPiece = board.getPiece(at: targetLocation) { if otherPiece.color == movingPiece.color { return false } } return true } } // MARK: - PieceMovementStraightLine open class PieceMovementStraightLine: PieceMovement { let strides = [ BoardStride(x: 0, y: -1 ), // Down BoardStride(x: 0, y: 1 ), // Up BoardStride(x: -1, y: 0 ), // Left BoardStride(x: 1, y: 0 ) // Right ] override func isMovementPossible(from fromLocation: BoardLocation, to toLocation: BoardLocation, board: Board) -> Bool { let sameX = fromLocation.x == toLocation.x let sameY = fromLocation.y == toLocation.y if !(sameX || sameY) { return false } for stride in strides { if canPieceMove(from: fromLocation, to: toLocation, board: board, stride: stride) { return true } } return false } } // MARK: - PieceMovementDiagonal open class PieceMovementDiagonal: PieceMovement { let strides = [ BoardStride(x: 1, y: -1 ), // South East BoardStride(x: -1, y: -1 ), // South West BoardStride(x: 1, y: 1 ), // North East BoardStride(x: -1, y: 1 ) // North West ] override func isMovementPossible(from fromLocation: BoardLocation, to toLocation: BoardLocation, board: Board) -> Bool { if fromLocation.isDarkSquare != toLocation.isDarkSquare { return false } for stride in strides { if canPieceMove(from: fromLocation, to: toLocation, board: board, stride: stride) { return true } } return false } } // MARK: - PieceMovementQueen open class PieceMovementQueen: PieceMovement { let movements: [PieceMovement] = [PieceMovementStraightLine(), PieceMovementDiagonal()] override func isMovementPossible(from fromLocation: BoardLocation, to toLocation: BoardLocation, board: Board) -> Bool { for pieceMovement in movements { if pieceMovement.canPieceMove(from: fromLocation, to: toLocation, board: board) { return true } } return false } } // MARK: - PieceMovementRook open class PieceMovementRook: PieceMovement { let straightLineMovement = PieceMovementStraightLine() override func isMovementPossible(from fromLocation: BoardLocation, to toLocation: BoardLocation, board: Board) -> Bool { return straightLineMovement.canPieceMove(from: fromLocation, to: toLocation, board: board) } } // MARK: - PieceMovementBishop open class PieceMovementBishop: PieceMovement { let diagonalMovement = PieceMovementDiagonal() override func isMovementPossible(from fromLocation: BoardLocation, to toLocation: BoardLocation, board: Board) -> Bool { return diagonalMovement.canPieceMove(from: fromLocation, to: toLocation, board: board) } } // MARK: - PieceMovementKnight open class PieceMovementKnight: PieceMovement { let offsets: [(x: Int, y: Int)] = [ (1, 2), (2, 1), (2, -1), (-2, 1), (-1, -2), (-2, -1), (1, -2), (-1, 2) ] override func isMovementPossible(from fromLocation: BoardLocation, to toLocation: BoardLocation, board: Board) -> Bool { // Make sure cannot take king if let piece = board.getPiece(at: toLocation) { if piece.type == .king { return false } } for offset in offsets { let offsetLocation = fromLocation.incrementedBy(x: offset.x, y: offset.y) if toLocation == offsetLocation && canPieceOccupySquare(pieceLocation: fromLocation, xOffset: offset.x, yOffset: offset.y, board: board) { return true } } return false } } // MARK: - PieceMovementPawn // swiftlint:disable function_body_length open class PieceMovementPawn: PieceMovement { override func isMovementPossible(from fromLocation: BoardLocation, to toLocation: BoardLocation, board: Board) -> Bool { // Get the moving piece guard let movingPiece = board.getPiece(at: fromLocation) else { return false } if movingPiece.color == .white && toLocation.y == 0 { return false } if movingPiece.color == .black && toLocation.y == 7 { return false } // Make sure cannot take king if let piece = board.getPiece(at: toLocation) { if piece.type == .king { return false } } let color = movingPiece.color // ****** Test forward locations ****** // Test one ahead offset let oneAheadStride = (color == .white ? BoardStride(x: 0, y: 1) : BoardStride(x: 0, y: -1)) var canMoveOneAhead = true ONE_AHEAD: if fromLocation.canIncrement(by: oneAheadStride) { let location = fromLocation.incremented(by: oneAheadStride) if board.getPiece(at: location) != nil { canMoveOneAhead = false break ONE_AHEAD } if location == toLocation { return true } } // Test two ahead offset if canMoveOneAhead { var twoAheadStride: BoardStride? if color == .white && fromLocation.y == 1 { twoAheadStride = BoardStride(x: 0, y: 2) } else if color == .black && fromLocation.y == 6 { twoAheadStride = BoardStride(x: 0, y: -2) } TWO_AHEAD: if let twoAheadStride = twoAheadStride { let twoAheadLocation = fromLocation.incremented(by: twoAheadStride) if toLocation != twoAheadLocation { break TWO_AHEAD } if board.getPiece(at: twoAheadLocation) == nil { return true } } } // ****** Test Diagonal locations ****** var diagonalStrides = [BoardStride]() if color == .white { diagonalStrides.append( BoardStride(x: -1, y: 1) ) diagonalStrides.append( BoardStride(x: 1, y: 1) ) } else { diagonalStrides.append( BoardStride(x: -1, y: -1) ) diagonalStrides.append( BoardStride(x: 1, y: -1) ) } for stride in diagonalStrides { guard fromLocation.canIncrement(by: stride) else { continue } let location = fromLocation.incremented(by: stride) if location != toLocation { continue } // If the target square has an opponent piece if let piece = board.getPiece(at: location) { if piece.color == color.opposite { return true } } // If can make en passent move let enPassentStride = BoardStride(x: stride.x, y: 0) guard fromLocation.canIncrement(by: enPassentStride) else { break } let enPassentLocation = fromLocation.incremented(by: enPassentStride) guard let passingPiece = board.getPiece(at: enPassentLocation) else { break } if passingPiece.canBeTakenByEnPassant && passingPiece.color == color.opposite { return true } } return false } } // MARK: - PieceMovementKing open class PieceMovementKing: PieceMovement { let offsets: [(x: Int, y: Int)] = [ (0, 1), // North (1, 1), // North-East (1, 0), // East (1, -1), // South-East (0, -1), // South (-1, -1), // South-West (-1, 0), // West (-1, 1) // North- West ] override func isMovementPossible(from fromLocation: BoardLocation, to toLocation: BoardLocation, board: Board) -> Bool { // Make sure cannot take king if let piece = board.getPiece(at: toLocation) { if piece.type == .king { return false } } for offset in offsets { let offsetLocation = fromLocation.incrementedBy(x: offset.x, y: offset.y) if toLocation == offsetLocation && offsetLocation.isInBounds() && canPieceOccupySquare(pieceLocation: fromLocation, xOffset: offset.x, yOffset: offset.y, board: board) { return true } } return false } }
mit
986efa7130918cb0f7ffa0f987014ccc
29.145315
115
0.501776
5.179369
false
false
false
false
joelrorseth/AtMe
AtMe/DismissalAnimator.swift
1
1635
// // DismissalAnimator.swift // AtMe // // Created by Joel Rorseth on 2018-04-28. // Copyright © 2018 Joel Rorseth. All rights reserved. // import UIKit class DismissalAnimator: NSObject, UIViewControllerAnimatedTransitioning { var openingFrame: CGRect? func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.3 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let fromViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)! //let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)! let containerView = transitionContext.containerView let animationDuration = transitionDuration(using: transitionContext) guard let snapshotView = fromViewController.view.resizableSnapshotView( from: fromViewController.view.bounds, afterScreenUpdates: true, withCapInsets: UIEdgeInsets.zero) else { return } containerView.addSubview(snapshotView) fromViewController.view.alpha = 0.0 UIView.animate(withDuration: animationDuration, animations: { () -> Void in snapshotView.frame = self.openingFrame! snapshotView.alpha = 0.0 }) { (finished) -> Void in snapshotView.removeFromSuperview() fromViewController.view.removeFromSuperview() transitionContext.completeTransition(!transitionContext.transitionWasCancelled) } } }
apache-2.0
6a802e80b7402591403e849549a76a19
38.853659
125
0.71175
6.097015
false
false
false
false
ricardorauber/iOS-Swift
iOS-Swift.playground/Pages/REST Request.xcplaygroundpage/Contents.swift
1
1820
//: ## REST Request //: ---- //: [Previous](@previous) import Foundation import XCPlayground XCPSetExecutionShouldContinueIndefinitely(true) //: Creating a Manager class ServerManager { // Singleton static let sharedManager = ServerManager() private init() {} // Properties let baseUrl = "https://api.github.com/" var task: NSURLSessionDataTask? // Make Request func getReposInfo(query: String) { // URL let apiUrl = baseUrl + query // Request let request = NSMutableURLRequest(URL: NSURL(string: apiUrl)!) request.HTTPMethod = "GET" request.setValue("value", forHTTPHeaderField: "field") // Session let session = NSURLSession.sharedSession() // Cancel Previous Task if self.task != nil { self.task!.cancel() } // Task self.task = session.dataTaskWithRequest(request) { (data, response, error) -> Void in // Check error if error == nil { // Get Data do { let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! [String: AnyObject] print(json) } catch let error as NSError { print("A JSON parsing error occurred: \(error)") } } else { print("Error on Reuqest Task: \(error)") } } task!.resume() } } //: Executing and Canceling let query = "repos/ricardorauber/iOS-Swift" ServerManager.sharedManager.getReposInfo(query) // ServerManager.sharedManager.task!.cancel() // Cancel Task //: [Next](@next)
mit
caf1ee795a142dc0b9fe118fac27d058
25.376812
133
0.536264
5.155807
false
false
false
false
zhubofei/IGListKit
Examples/Examples-tvOS/IGListKitExamples/Views/LabelCell.swift
4
2491
/** Copyright (c) 2016-present, Facebook, Inc. All rights reserved. The examples provided by Facebook are for non-commercial testing and evaluation purposes only. Facebook reserves all rights not expressly granted. 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 FACEBOOK 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 final class LabelCell: UICollectionViewCell { fileprivate static let insets = UIEdgeInsets(top: 8, left: 15, bottom: 8, right: 15) fileprivate static let font = UIFont.systemFont(ofSize: 40) static var singleLineHeight: CGFloat { return font.lineHeight + insets.top + insets.bottom } static func textHeight(_ text: String, width: CGFloat) -> CGFloat { let constrainedSize = CGSize(width: width - insets.left - insets.right, height: CGFloat.greatestFiniteMagnitude) let attributes = [ NSAttributedStringKey.font: font ] let options: NSStringDrawingOptions = [.usesFontLeading, .usesLineFragmentOrigin] let bounds = (text as NSString).boundingRect(with: constrainedSize, options: options, attributes: attributes, context: nil) return ceil(bounds.height) + insets.top + insets.bottom } lazy var label: UILabel = { let label = UILabel() label.backgroundColor = .clear label.numberOfLines = 1 label.font = LabelCell.font self.contentView.addSubview(label) return label }() lazy var separator: CALayer = { let layer = CALayer() layer.backgroundColor = UIColor(red: 200 / 255.0, green: 199 / 255.0, blue: 204 / 255.0, alpha: 1).cgColor self.contentView.layer.addSublayer(layer) return layer }() override func layoutSubviews() { super.layoutSubviews() let bounds = contentView.bounds label.frame = UIEdgeInsetsInsetRect(bounds, LabelCell.insets) let height: CGFloat = 0.5 let left = LabelCell.insets.left separator.frame = CGRect(x: left, y: bounds.height - height, width: bounds.width - left, height: height) } override var canBecomeFocused: Bool { return false } }
mit
72b2a32e03daf67eb42cd5cd9e4b408d
38.539683
131
0.696106
4.691149
false
false
false
false
mrchenhao/VPNOn
VPNOn/LTVPNCertificateViewController.swift
2
7130
// // LTVPNCertificateViewController.swift // VPNOn // // Created by Lex on 1/23/15. // Copyright (c) 2015 LexTang.com. All rights reserved. // import UIKit import VPNOnKit @objc protocol LTVPNCertificateViewControllerDelegate { optional func didTapSaveCertificateWithData(data: NSData?, URLString andURLString: String) } class LTVPNCertificateViewController: UITableViewController, UITextFieldDelegate { weak var delegate: LTVPNCertificateViewControllerDelegate? var temporaryCertificateURL: String? var temporaryCertificateData: NSData? private let kDownloadingText = NSLocalizedString("Downloading...", comment: "Certifiate - Download Cell - Downloading") private let kDownloadText = NSLocalizedString("Download", comment: "Certifiate - Download Cell") @IBOutlet weak var saveButton: UIBarButtonItem! @IBOutlet weak var certificateURLField: UITextField! @IBOutlet weak var certificateSummaryCell: LTVPNTableViewCell! @IBOutlet weak var deleteCell: UITableViewCell! @IBOutlet weak var downloadCell: LTTableViewActionCell! lazy var vpn: VPN? = { if let ID = VPNDataManager.sharedManager.selectedVPNID { if let result = VPNDataManager.sharedManager.VPNByID(ID) { let vpn = result return vpn } } return Optional.None }() var downloading: Bool = false { didSet { self.downloadCell.textLabel!.text = self.downloading ? kDownloadingText : kDownloadText self.downloadCell.disabled = self.downloading } } var certificateData: NSData? { didSet { self.updateCertificateSummary() self.updateSaveButton() } } override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if let vpnObject = vpn { certificateURLField.text = vpnObject.certificateURL if let certificate = VPNKeychainWrapper.certificateForVPNID(vpnObject.ID) { certificateData = certificate } } else { if let url = temporaryCertificateURL { certificateURLField.text = url } if let data = temporaryCertificateData { certificateData = data } } } deinit { vpn = nil certificateData = nil delegate = nil } // MARK: - Save @IBAction func save(sender: AnyObject) { if let data = certificateData { if let vpnObject = vpn { VPNKeychainWrapper.setCertificate(data, forVPNID: vpnObject.ID) vpnObject.certificateURL = certificateURLField.text VPNDataManager.sharedManager.saveContext() } else if let d = delegate { d.didTapSaveCertificateWithData?(data, URLString: certificateURLField.text) } } popDetailViewController() } func updateSaveButton() { if certificateData == nil { saveButton.enabled = false } else { saveButton.enabled = true } } // MARK: - Download && Scan && Delete override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if let cell = tableView.cellForRowAtIndexPath(indexPath) { if cell == deleteCell { let deleteTitle = NSLocalizedString("Delete Certificate?", comment: "Certificate - Delete alert - Title") let deleteButtonTitle = NSLocalizedString("Delete", comment: "Certificate - Delete alert - Delete button") let cancelButtonTitle = NSLocalizedString("Cancel", comment: "Certificate - Delete alert - Cancel button") let alert = UIAlertController(title: deleteTitle, message: "", preferredStyle: .Alert) alert.addAction(UIAlertAction(title: deleteButtonTitle, style: .Destructive, handler: { _ -> Void in self.deleteCertificate() })) alert.addAction(UIAlertAction(title: cancelButtonTitle, style: .Cancel, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } else if cell == downloadCell { downloadURL() } } } func downloadURL() { downloading = true if let URL = NSURL(string: certificateURLField.text) { LTVPNDownloader().download(URL) { response, data, error in dispatch_async(dispatch_get_main_queue(), { if let err = error { self.certificateSummaryCell.textLabel!.text = error.localizedDescription } else { self.certificateData = data } self.downloading = false }) } } } func updateCertificateSummary() { if let data = certificateData { let bytesFormatter = NSByteCountFormatter() bytesFormatter.countStyle = NSByteCountFormatterCountStyle.File let bytesCount = bytesFormatter.stringFromByteCount(Int64(data.length)) let certificateFormat = NSLocalizedString("Certificate downloaded (%@)", comment: "Certificate - Status") let certificateText = String(format: certificateFormat, bytesCount) certificateSummaryCell.textLabel!.text = certificateText } else { let defaultCertificateStatus = NSLocalizedString("Certificate will be downloaded and stored in Keychain", comment: "Certificate - Default status") certificateSummaryCell.textLabel!.text = defaultCertificateStatus } } func deleteCertificate() { certificateData = nil if let vpnObject = vpn { VPNKeychainWrapper.setCertificate(nil, forVPNID: vpnObject.ID) vpnObject.certificateURL = "" VPNDataManager.sharedManager.saveContext() } else if let d = delegate { d.didTapSaveCertificateWithData?(nil, URLString: "") } popDetailViewController() } // MARK: - TextField delegate func textFieldDidBeginEditing(textField: UITextField) { updateCertificateSummary() } func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { updateCertificateSummary() return true } func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() downloadURL() return true } // MARK: - Navigation func popDetailViewController() { let topNavigationController = splitViewController!.viewControllers.last! as UINavigationController topNavigationController.popViewControllerAnimated(true) } }
mit
d4d77d503988733ffa8ee56e0a04f5fb
35.192893
158
0.617251
5.694888
false
false
false
false
stripe/stripe-ios
StripePaymentsUI/StripePaymentsUI/Internal/UI/Views/Inputs/STPGenericInputPickerField.swift
1
7622
// // STPGenericInputPickerField.swift // StripePaymentsUI // // Created by Mel Ludowise on 2/8/21. // Copyright © 2021 Stripe, Inc. All rights reserved. // @_spi(STP) import StripeUICore import UIKit @_spi(STP) public protocol STPGenericInputPickerFieldDataSource { func numberOfRows() -> Int func inputPickerField( _ pickerField: STPGenericInputPickerField, titleForRow row: Int ) -> String? func inputPickerField( _ pickerField: STPGenericInputPickerField, inputValueForRow row: Int ) -> String? } @_spi(STP) public class STPGenericInputPickerField: STPInputTextField { /// Basic validator that sets `validationState` to `.valid` if there's an inputValue class Validator: STPInputTextFieldValidator { override var inputValue: String? { didSet { validationState = (inputValue?.isEmpty != false) ? .incomplete(description: nil) : .valid(message: nil) } } } /// Formatter specific to `STPGenericInputPickerField`. /// /// Contains overrides to `UITextFieldDelegate` that ensure the textfield's text can't be /// selected and the placeholder text displays correctly for a dropdown/picker style input. /// /// For internal SDK use only @objc(STP_Internal_GenericInputPickerFieldFormatter) class Formatter: STPInputTextFieldFormatter { override func isAllowedInput(_ input: String, to string: String, at range: NSRange) -> Bool { return false // no typing allowed } // See extension for rest of implementation } internal let wrappedDataSource: DataSourceWrapper @_spi(STP) public let pickerView = UIPickerView() @_spi(STP) public var dataSource: STPGenericInputPickerFieldDataSource { return wrappedDataSource.inputDataSource } init( dataSource: STPGenericInputPickerFieldDataSource, formatter: STPGenericInputPickerField.Formatter = .init(), validator: STPInputTextFieldValidator = Validator() ) { self.wrappedDataSource = DataSourceWrapper(inputDataSource: dataSource) super.init(formatter: formatter, validator: validator) } @objc public override var accessibilityAttributedValue: NSAttributedString? { get { return nil } set {} } @objc public override var accessibilityAttributedLabel: NSAttributedString? { get { return nil } set {} } required init( formatter: STPInputTextFieldFormatter, validator: STPInputTextFieldValidator ) { fatalError("Use init(dataSource:formatter:validator:) instead") } required init?( coder: NSCoder ) { fatalError("init(coder:) has not been implemented") } override func setupSubviews() { super.setupSubviews() pickerView.delegate = self pickerView.dataSource = wrappedDataSource inputView = pickerView inputAccessoryView = DoneButtonToolbar(delegate: self) rightView = UIImageView(image: StripeUICore.Image.icon_chevron_down.makeImage()) rightViewMode = .always // Prevents selection from flashing if the user double-taps on a word tintColor = .clear // Prevents text from being highlighted red if the user double-taps a word the spell checker doesn't recognize autocorrectionType = .no } @_spi(STP) public override func resignFirstResponder() -> Bool { // Update value right before resigning first responder (dismissing input view) updateValue() return super.resignFirstResponder() } @_spi(STP) public override func caretRect(for position: UITextPosition) -> CGRect { // hide the caret return .zero } override func textDidChange() { // NOTE(mludowise): There's probably a more elegant solution than // overriding this method, but this fixes a transcient bug where the // validator's inputValue would temprorily get set to the display text // (e.g. "United States") instead of value (e.g. "US") causing the field // to display as invalid and postal code to sometimes not display when a // valid country was selected. // // Override this method from `STPInputTextField` because... // 1. We don't want to override validator.input with the display text. // 2. The logic in `STPInputTextField` handles validation and formatting // for cases when the user is typing in text into the text field, which // we don't allow in this case since the value is determined from our // data source. } @_spi(STP) public func updateValue() { let selectedRow = pickerView.selectedRow(inComponent: 0) text = dataSource.inputPickerField(self, titleForRow: selectedRow) validator.inputValue = dataSource.inputPickerField(self, inputValueForRow: selectedRow) // Hide the placeholder so it behaves as though the placeholder is // replaced with the selected value rather than displaying as a title // label above the text. placeholder = nil } } // MARK: - UIPickerViewDelegate /// :nodoc: extension STPGenericInputPickerField: UIPickerViewDelegate { @_spi(STP) public func pickerView( _ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int ) -> NSAttributedString? { guard let title = dataSource.inputPickerField(self, titleForRow: row) else { return nil } // Make sure the picker font matches our standard input font return NSAttributedString( string: title, attributes: [.font: font ?? UIFont.preferredFont(forTextStyle: .body)] ) } } // MARK: - Formatter extension STPGenericInputPickerField.Formatter { func textFieldDidBeginEditing(_ textField: UITextField) { guard let inputField = textField as? STPGenericInputPickerField else { return } // If this is the first time the picker displays, we need to display the // current selection by manually calling the update method inputField.updateValue() UIAccessibility.post(notification: .layoutChanged, argument: inputField.pickerView) } func textFieldDidChangeSelection(_ textField: UITextField) { // Disable text selection textField.selectedTextRange = textField.textRange( from: textField.beginningOfDocument, to: textField.beginningOfDocument ) } } // MARK: - DoneButtonToolbarDelegate /// :nodoc: extension STPGenericInputPickerField: DoneButtonToolbarDelegate { @_spi(STP) public func didTapDone(_ toolbar: DoneButtonToolbar) { _ = resignFirstResponder() } } /// Wraps `STPGenericInputPickerFieldDataSource` into `UIPickerViewDataSource` /// For internal SDK use only @objc(STP_Internal_DataSourceWrapper) internal class DataSourceWrapper: NSObject, UIPickerViewDataSource { let inputDataSource: STPGenericInputPickerFieldDataSource init( inputDataSource: STPGenericInputPickerFieldDataSource ) { self.inputDataSource = inputDataSource } func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return inputDataSource.numberOfRows() } }
mit
c5a4d12f5cfd1769a50086b07a0ea92c
32.279476
118
0.667366
5.084056
false
false
false
false
ello/ello-ios
Sources/Utilities/Tracker.swift
1
21896
//// /// Tracker.swift // import Analytics import Keys enum ContentType: String { case post = "Post" case comment = "Comment" case user = "User" } protocol AnalyticsAgent { func identify(_ userId: String?, traits: [String: Any]?) func track(_ event: String) func track(_ event: String, properties: [String: Any]?) func screen(_ screenTitle: String) func screen(_ screenTitle: String, properties: [String: Any]?) func reset() } struct NullAgent: AnalyticsAgent { func identify(_ userId: String?, traits: [String: Any]?) {} func track(_ event: String) {} func track(_ event: String, properties: [String: Any]?) {} func screen(_ screenTitle: String) {} func screen(_ screenTitle: String, properties: [String: Any]?) {} func reset() {} } struct ForwardingAgent: AnalyticsAgent { let agents: [AnalyticsAgent] func identify(_ userId: String?, traits: [String: Any]?) { for agent in agents { agent.identify(userId, traits: traits) } } func track(_ event: String) { for agent in agents { agent.track(event) } } func track(_ event: String, properties: [String: Any]?) { for agent in agents { agent.track(event, properties: properties) } } func screen(_ screenTitle: String) { for agent in agents { agent.screen(screenTitle) } } func screen(_ screenTitle: String, properties: [String: Any]?) { for agent in agents { agent.screen(screenTitle, properties: properties) } } func reset() { for agent in agents { agent.reset() } } } extension SEGAnalytics: AnalyticsAgent {} class Tracker { static let shared = Tracker() // the iOS app redefines this to include the Quantcast agent var defaultAgent: AnalyticsAgent = SEGAnalytics.shared() { didSet { currentAgent = nil } } // during testing and using the simulator we override the agent to NullAgent var overrideAgent: AnalyticsAgent? { didSet { currentAgent = nil } } private var currentAgent: AnalyticsAgent? private var shouldTrackUser = true { didSet { currentAgent = nil } } var settingChangedNotification: NotificationObserver? private var agent: AnalyticsAgent { if let overrideAgent = overrideAgent { return overrideAgent } if let currentAgent = currentAgent { return currentAgent } let agent: AnalyticsAgent if shouldTrackUser { agent = defaultAgent } else { agent = NullAgent() } currentAgent = agent return agent } static func setup() { let configuration = SEGAnalyticsConfiguration(writeKey: APIKeys.shared.segmentKey) SEGAnalytics.setup(with: configuration) } init() { settingChangedNotification = NotificationObserver(notification: SettingChangedNotification) { user in self.shouldTrackUser = user.profile?.allowsAnalytics ?? true } } } // MARK: Session Info extension Tracker { func identify(user: User?) { guard let user = user else { shouldTrackUser = true agent.reset() return } shouldTrackUser = user.profile?.allowsAnalytics ?? true if let analyticsId = user.profile?.gaUniqueId { let authToken = AuthToken() agent.identify( analyticsId, traits: [ // camelCase is correct, so we have parity w/ webapp "hasAccount": true, "agent": "ios", // leave these as snake_case since they are being used in reports "is_nabaroo": authToken.isNabaroo, "is_featured": user.isFeatured, "is_experimental": user.experimentalFeatures ?? false, "created_at": user.profile?.createdAt.toServerDateString() ?? "no-creation-date", ] ) } else { agent.reset() } } func track(_ event: String, properties customProps: [String: Any] = [:]) { let properties = customProps + ["agent": "ios"] agent.track(event, properties: properties) } func screen(_ name: String, properties customProps: [String: Any] = [:]) { let properties = customProps + ["agent": "ios"] agent.screen(name, properties: properties) } func sessionStarted() { track("Session Began") } func sessionEnded() { track("Session Ended") } } // MARK: Signup and Login extension Tracker { func enteredEmail() { track("entered email and pressed 'next'") } func enteredUsername() { track("entered username and pressed 'next'") } func enteredPassword() { track("entered password and pressed 'next'") } func tappedRequestPassword() { track("tapped request reset password") } func tappedReset() { track("tapped reset password") } func tappedJoin() { track("tapped join") } func tappedAbout() { track("tapped about") } func tappedLink(title: String) { track("tapped \(title)") } func requestPasswordValid() { track("reset password valid email") } func resetPasswordValid() { track("reset password sent") } func resetPasswordSuccessful() { track("reset password successful") } func resetPasswordFailed() { track("reset password failed") } func joinButtonTapped() { track("join button tapped") } func joinValid() { track("join valid") } func joinInvalid() { track("join invalid") } func joinSuccessful() { track("join successful") } func joinFailed() { track("join failed") } func tappedLogin() { track("tapped sign in") } func loginButtonTapped() { track("login button tapped") } func loginValid() { track("sign-in valid") } func loginInvalid() { track("sign-in invalid") } func loginSuccessful() { track("sign-in successful") } func loginFailed() { track("sign-in failed") } func tappedForgotPassword() { track("forgot password tapped") } func tappedLogout() { track("logout tapped") } func tappedDrawer(_ item: String) { track("tapped \(item) drawer") } } // MARK: Rate prompt extension Tracker { func ratePromptShown() { track("rate prompt shown") } } // MARK: Hire Me extension Tracker { func tappedCollaborate(_ user: User) { track("open collaborate dialog profile", properties: ["id": user.id]) } func collaboratedUser(_ user: User) { track("send collaborate dialog profile", properties: ["id": user.id]) } func tappedHire(_ user: User) { track("open hire dialog profile", properties: ["id": user.id]) } func hiredUser(_ user: User) { track("send hire dialog profile", properties: ["id": user.id]) } } // MARK: Share Extension extension Tracker { func shareSuccessful() { track("successfully shared from the share extension") } func shareFailed() { track("failed to share from the share extension") } } // MARK: Onboarding extension Tracker { func completedCategories() { track("completed categories in onboarding") } func onboardingCreatorTypeSelected(_ creatorType: Profile.CreatorType) { track( "completed creator type in onboarding", properties: ["creatorType": creatorType.trackerName] ) } func onboardingCategorySelected(_ category: Category) { track("onboarding category chosen", properties: ["category": category.name]) } func skippedCategories() { track("skipped categories in onboarding") } func skippedNameBio() { track("skipped name_bio") } func addedNameBio() { track("added name_bio") } func skippedContactImport() { track("skipped contact import") } func completedContactImport() { track("completed contact import") } func enteredOnboardName() { track("entered name during onboarding") } func enteredOnboardBio() { track("entered bio during onboarding") } func enteredOnboardLinks() { track("entered links during onboarding") } func uploadedOnboardAvatar() { track("uploaded avatar during onboarding") } func uploadedOnboardCoverImage() { track("uploaded coverImage during onboarding") } } extension UIViewController { // return 'nil' to disable tracking, e.g. in StreamViewController @objc func trackerName() -> String? { return readableClassName() } @objc func trackerProps() -> [String: Any]? { return nil } @objc func trackScreenAppeared() { Tracker.shared.screenAppeared(self) } } // MARK: View Appearance extension Tracker { func screenAppeared(_ viewController: UIViewController) { guard let name = viewController.trackerName() else { return } let props = viewController.trackerProps() screenAppeared(name, properties: props) } func loggedOutScreenAppeared(_ viewController: UIViewController) { guard let name = viewController.trackerName() else { return } track("logged out screen viewed", properties: ["screen": name]) } func screenAppeared(_ name: String, properties: [String: Any]? = nil) { if let properties = properties { screen("Screen \(name)", properties: properties) } else { screen("Screen \(name)") } } func webViewAppeared(_ url: String) { screen("Web View", properties: ["url": url]) } func allCategoriesTapped() { track("all categories tapped") } func editCategoriesTapped() { track("edit categories tapped") } func categoriesEdited() { track("subscribed categories edited") } func subscribedCategoryTapped() { track("subscribed category tapped") } func categoryFilterChanged(_ filterName: String, on selection: Category.Selection) { let selectionDesc: String switch selection { case .all: selectionDesc = "all" case .subscribed: selectionDesc = "subscribed" case let .category(slug): selectionDesc = "category \(slug)" } track( "category filter changed", properties: ["category": selectionDesc, "filter": filterName] ) } func categoryOpened(_ categorySlug: String) { track("category opened", properties: ["category": categorySlug]) } func categoryHeaderPostedBy(_ categoryTitle: String) { track("promoByline clicked", properties: ["category": categoryTitle]) } func categoryHeaderCallToAction(_ categoryTitle: String) { track("promoCTA clicked", properties: ["category": categoryTitle]) } func badgeOpened(_ badgeSlug: String) { track("badge opened", properties: ["badge": badgeSlug]) } func badgeLearnMore(_ badgeSlug: String) { track("badge learn more clicked", properties: ["badge": badgeSlug]) } func badgeScreenLink(_ badgeSlug: String) { track("badges screen link tapped", properties: ["badge": badgeSlug]) } func viewedImage(_ asset: Asset, post: Post) { track("Viewed Image", properties: ["asset_id": asset.id, "post_id": post.id]) } func postBarVisibilityChanged(_ visible: Bool) { let visibility = visible ? "shown" : "hidden" track("Post bar \(visibility)") } func commentBarVisibilityChanged(_ visible: Bool) { let visibility = visible ? "shown" : "hidden" track("Comment bar \(visibility)") } func drawerClosed() { track("Drawer closed") } func viewsButtonTapped(post: Post) { track("Views button tapped", properties: ["post_id": post.id]) } func buyButtonLinkVisited(_ path: String) { track("Buy Button Link Visited", properties: ["link": path]) } } // MARK: Content Actions extension Tracker { private func regionDetails(_ regions: [Regionable]?) -> [String: Any] { guard let regions = regions else { return [:] } var imageCount = 0 var textLength = 0 for region in regions { if region.kind == RegionKind.image { imageCount += 1 } else if let region = region as? TextRegion { textLength += region.content.count } } return [ "total_regions": regions.count, "image_regions": imageCount, "text_length": textLength ] } func relatedPostTapped(_ post: Post) { let properties = ["post_id": post.id] track("related post tapped", properties: properties) } func postIntoCommunityChosen(_ category: Category?) { if let category = category { track("Post into Community chosen", properties: ["category": category.id]) } else { track("Post into Community removed") } } func postCreated(_ post: Post, category: Category?) { var properties = regionDetails(post.content) if let category = category { properties["community"] = category.id } track("Post created", properties: properties) } func postEdited(_ post: Post, category: Category?) { var properties = regionDetails(post.content) if let category = category { properties["community"] = category.id } track("Post edited", properties: properties) } func postDeleted(_ post: Post) { let properties = regionDetails(post.content) track("Post deleted", properties: properties) } func commentCreated(_ comment: ElloComment) { let properties = regionDetails(comment.content) track("Comment created", properties: properties) } func commentEdited(_ comment: ElloComment) { let properties = regionDetails(comment.content) track("Comment edited", properties: properties) } func commentDeleted(_ comment: ElloComment) { let properties = regionDetails(comment.content) track("Comment deleted", properties: properties) } func contentCreationCanceled(_ type: ContentType) { track("\(type.rawValue) creation canceled") } func contentEditingCanceled(_ type: ContentType) { track("\(type.rawValue) editing canceled") } func contentCreationFailed(_ type: ContentType, message: String) { track("\(type.rawValue) creation failed", properties: ["message": message]) } func contentFlagged(_ type: ContentType, flag: UserFlag, contentId: String) { track( "\(type.rawValue) flagged", properties: ["content_id": contentId, "flag": flag.rawValue] ) } func contentFlaggingCanceled(_ type: ContentType, contentId: String) { track("\(type.rawValue) flagging canceled", properties: ["content_id": contentId]) } func contentFlaggingFailed(_ type: ContentType, message: String, contentId: String) { track( "\(type.rawValue) flagging failed", properties: ["content_id": contentId, "message": message] ) } func userShared(_ user: User) { track("User shared", properties: ["user_id": user.id]) } } extension Tracker { private func postProps(_ post: Post, additional: [String: Any] = [:]) -> [String: Any] { var props: [String: Any] = ["post_id": post.id] if let artistInviteId = post.artistInviteId { props["artistInviteId"] = artistInviteId } return props + additional } func postReposted(_ post: Post) { track("Post reposted", properties: postProps(post)) } func postShared(_ post: Post) { track("Post shared", properties: postProps(post)) } func postLoved(_ post: Post, via: String) { var props: [String: Any] = ["post_id": post.id, "via": via] if let artistInviteId = post.artistInviteId { props["artistInviteId"] = artistInviteId } track("Post loved", properties: postProps(post, additional: ["via": via])) } func postUnloved(_ post: Post) { track("Post unloved", properties: postProps(post)) } func postWatched(_ post: Post) { track("Post watched", properties: postProps(post)) } func postUnwatched(_ post: Post) { var props: [String: Any] = ["post_id": post.id] if let artistInviteId = post.artistInviteId { props["artistInviteId"] = artistInviteId } track("Post unwatched", properties: props) } } // MARK: User Actions extension Tracker { func userBlocked(_ userId: String) { track("User blocked", properties: ["blocked_user_id": userId]) } func userMuted(_ userId: String) { track("User muted", properties: ["muted_user_id": userId]) } func userUnblocked(_ userId: String) { track("User UN-blocked", properties: ["blocked_user_id": userId]) } func userUnmuted(_ userId: String) { track("User UN-muted", properties: ["muted_user_id": userId]) } func userBlockCanceled(_ userId: String) { track("User block canceled", properties: ["blocked_user_id": userId]) } func relationshipStatusUpdated(_ relationshipPriority: RelationshipPriority, userId: String) { track( "Relationship Priority changed", properties: ["new_value": relationshipPriority.rawValue, "user_id": userId] ) } func relationshipStatusUpdateFailed( _ relationshipPriority: RelationshipPriority, userId: String ) { track( "Relationship Priority failed", properties: ["new_value": relationshipPriority.rawValue, "user_id": userId] ) } func relationshipButtonTapped(_ relationshipPriority: RelationshipPriority, userId: String) { track( "Relationship button tapped", properties: ["button": relationshipPriority.buttonName, "user_id": userId] ) } func friendInvited() { track("User invited") } func onboardingFriendInvited() { track("Onboarding User invited") } func userDeletedAccount() { track("User deleted account") } } // MARK: Image Actions extension Tracker { func imageAddedFromCamera() { track("Image added from camera") } func imageAddedFromLibrary() { track("Image added from library") } func addImageCanceled() { track("Image addition canceled") } } // MARK: Import Friend Actions extension Tracker { func inviteFriendsTapped() { track("Invite Friends tapped") } func importContactsInitiated() { track("Import Contacts initiated") } func importContactsDenied() { track("Import Contacts denied") } func addressBookAccessed() { track("Address book accessed") } } // MARK: Preferences extension Tracker { func pushNotificationPreferenceChanged(_ granted: Bool) { let accessLevel = granted ? "granted" : "denied" track("Push notification access \(accessLevel)") } func contactAccessPreferenceChanged(_ granted: Bool) { let accessLevel = granted ? "granted" : "denied" track("Address book access \(accessLevel)") } } // MARK: Errors extension Tracker { func encounteredNetworkError(_ path: String, error: NSError, statusCode: Int?) { track( "Encountered network error", properties: ["path": path, "message": error.description, "statusCode": statusCode ?? 0] ) } } // MARK: Search extension Tracker { func searchFor(_ searchType: String, _ text: String) { track("Search", properties: ["for": searchType, "text": text]) } } // MARK: Announcements extension Tracker { func announcementViewed(_ announcement: Announcement) { track("Announcement Viewed", properties: ["announcement": announcement.id]) } func announcementOpened(_ announcement: Announcement) { track("Announcement Clicked", properties: ["announcement": announcement.id]) } func announcementDismissed(_ announcement: Announcement) { track("Announcement Closed", properties: ["announcement": announcement.id]) } } // MARK: ArtistInvites extension Tracker { func artistInvitesBrowsed() { track("Clocked Artist Invites") } func artistInviteOpened(slug: String) { track("Clicked Artist Invite", properties: ["artistInvite": slug]) } func artistInviteSubmitted(slug: String) { track("Submitted Artist Invite", properties: ["artistInvite": slug]) } func artistInviteShared(slug: String) { track("Artist Invite shared", properties: ["artistInvite": slug]) } } // MARK: LoggedOut extension Tracker { func loggedOutScreenViewed() { track("logged out screen viewed") } func loggedOutRelationshipAction() { track("logged out follow button") } func loggedOutPostTool() { track("logged out post tool") } func loggedOutArtistInviteSubmit() { track("logged out artist invite submit") } }
mit
03535b5aed29f7dae732c4c14b7c57ad
25.380723
99
0.603078
4.619409
false
false
false
false
maxim-pervushin/Overlap
Overlap/App/View Controllers/TimePicker/TimePickerViewController.swift
1
2441
// // Created by Maxim Pervushin on 29/04/16. // Copyright (c) 2016 Maxim Pervushin. All rights reserved. // import UIKit class TimePickerViewController: UIViewController { // MARK: @IB @IBOutlet weak var datePicker: UIDatePicker? @IBAction func cancelButtonAction(sender: AnyObject) { dismissViewControllerAnimated(true, completion: nil) } @IBAction func pickButtonAction(sender: AnyObject) { guard let _ = datePicker?.date else { dismissViewControllerAnimated(true, completion: nil) return } dismissViewControllerAnimated(true, completion: nil) finished?() } // MARK: public var hours: Int { set { _hoursSet = newValue reloadData() } get { guard let date = datePicker?.date else { return 0 } let components = NSCalendar.currentCalendar().components([.Hour], fromDate: date) return components.hour } } var minutes: Int { set { _minutesSet = newValue reloadData() } get { guard let date = datePicker?.date else { return 0 } let components = NSCalendar.currentCalendar().components([.Minute], fromDate: date) return components.minute } } var finished: (Void -> Void)? // MARK: override override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) reloadData() } override func viewDidLoad() { super.viewDidLoad() // TODO: workaround for UIDatePicker text color. http://stackoverflow.com/questions/20181225/customize-text-color-of-uidatepicker-for-ios7-just-like-mailbox-does datePicker?.setValue(UIColor.whiteColor(), forKeyPath: "textColor") } // MARK: private private func reloadData() { guard let datePicker = datePicker else { return } let calendar = NSCalendar.currentCalendar() let components = calendar.components([.Hour, .Minute], fromDate: datePicker.date) components.hour = _hoursSet components.minute = _minutesSet if let newDate = calendar.dateFromComponents(components) { datePicker.setDate(newDate, animated: false) } } private var _hoursSet = 0 private var _minutesSet = 0 }
mit
cf139352886f8647f6c6a816fecf8113
26.426966
169
0.598525
5.085417
false
false
false
false
nkskalyan/ganesh-yrg
EcoKitchen-iOS/EcoKitcheniOSHackathon/FeedbackViewController.swift
1
12884
// // FeedbackTableViewController.swift // EcoKitcheniOS // // Created by mh53653 on 11/12/16. // Copyright © 2016 madan. All rights reserved. // import UIKit class FeedbackViewController: UIViewController,UITableViewDataSource,UITableViewDelegate { var sectionHeader:NSMutableArray = NSMutableArray() var dict: NSMutableDictionary = NSMutableDictionary() var collapse:NSMutableArray = NSMutableArray() var collapseRows:NSMutableArray = NSMutableArray() var formData:NSMutableArray = NSMutableArray() var locationObject : Location? @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() let tap : UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ProfileViewController.dismissKeyboard)); tap.cancelsTouchesInView = false; view.addGestureRecognizer(tap); collapse = [false,false,false,false,false] collapseRows = [false,false,false,false,false] formData = ["","","","",""]; sectionHeader = ["Entrepeneur courtesy","Quality of Food","Quantity of Food","Food Taste","Cleanliness of Serving"] let tmp: NSArray = ["Excellent","Good","Average","Need To Improve"] let str = sectionHeader.object(at: 0) as! String dict.setValue(tmp, forKey: str) let str1 = sectionHeader.object(at: 1) as! String dict.setValue(tmp, forKey: str1) let tmp2: NSArray = ["Sufficient","Can be increased"] let str2 = sectionHeader.object(at: 2) as! String dict.setValue(tmp2, forKey: str2) let str3 = sectionHeader.object(at: 3) as! String dict.setValue(tmp, forKey: str3) let str4 = sectionHeader.object(at: 4) as! String dict.setValue(tmp, forKey: str4) tableView.tableFooterView = UIView() tableView.dataSource = self; tableView.delegate = self; tableView.backgroundView = UIImageView(image: UIImage(named: "gradient_searchbar")); } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning(); } func ratingCalc(rating : String) -> Int { if rating == "Excellent"{ return 5 } else if rating == "Good"{ return 4 } else if rating == "Average"{ return 3 } else if rating == "Need To Improve"{ return 2 } else { return 1 } } @IBAction func submitBtnPressed(_ sender: AnyObject) { print(formData) let serviceManager = ServiceManager() let feedback = Feedback() feedback.locationId = GLOBAL_USERID feedback.userId = GLOBAL_USERID feedback.courtesy = ratingCalc(rating: formData[0] as! String); feedback.qualityOfFood = ratingCalc(rating: formData[1] as! String); feedback.quantityOfFood = ratingCalc(rating: formData[2] as! String); feedback.foodTaste = ratingCalc(rating: formData[3] as! String); feedback.cleanliness = ratingCalc(rating: formData[4] as! String); feedback.content = "" if let locationObject = self.locationObject { serviceManager.updateFeedback(feedback: feedback) { (success) in if(success != -1) { print("Successfully feedback") DispatchQueue.main.async { let alertController = UIAlertController(title: "Feedback Success", message: "Thank You for your feedback.", preferredStyle: UIAlertControllerStyle.alert) let alertAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: { (action) in self.navigationController?.popViewController(animated: true) }) alertController.addAction(alertAction) self.present(alertController, animated: true, completion: nil) } } else { DispatchQueue.main.async { let alertController = UIAlertController(title: "Feedback Failure", message: "Server not available", preferredStyle: UIAlertControllerStyle.alert) let alertAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil) alertController.addAction(alertAction) self.present(alertController, animated: true, completion: nil) } } } }else{ let alertController = UIAlertController(title: "Feedback Failure", message: "You should select the location and give your feedback.", preferredStyle: UIAlertControllerStyle.alert) let alertAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil) alertController.addAction(alertAction) self.present(alertController, animated: true, completion: nil) } } // MARK: - Table view data source func numberOfSections(in tableView: UITableView) -> Int { return sectionHeader.count } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return ""; } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 1; } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let value = collapse.object(at: section) as! Bool if value == true { let sectionHeaderTitle = sectionHeader.object(at: section) as! String let arr = dict.value(forKey: sectionHeaderTitle) as! NSArray return arr.count } return 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let cell = tableView.dequeueReusableCell(withIdentifier: "FeedbackCell"){ cell.textLabel?.text = .none let country = sectionHeader.object(at: indexPath.section) as! String let arr = dict.value(forKey: country) as! NSArray cell.textLabel?.text = arr.object(at: indexPath.row) as? String cell.textLabel?.sizeToFit(); // cell.textLabel?.textColor = UIColor.white cell.textLabel?.font = UIFont(name: "Courier New", size: 18) cell.selectionStyle = UITableViewCellSelectionStyle.none; cell.viewWithTag(100)?.isHidden = true cell.backgroundView = UIImageView(image: UIImage(named: "gradient_searchbar")); return cell } return UITableViewCell() } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { let val = collapseRows.object(at: section) as! Bool if val == false { return 60 } return 80 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let value = collapse.object(at: indexPath.section) as! Bool if value == true { return UITableViewAutomaticDimension } return UITableViewAutomaticDimension } func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { return UITableViewAutomaticDimension } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 40)) headerView.tag = section let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 40)) let image = UIImage(named: "gradient_searchbar") imageView.image = image headerView.addSubview(imageView) let headerString = UILabel(frame: CGRect(x: 10, y: 10, width: tableView.frame.size.width-10, height: 30)) as UILabel headerString.text = sectionHeader[section] as? String headerString.font = UIFont(name: "Courier New", size: 21) headerString.textColor = UIColor.white let headerStringDetailLabel = UILabel(frame: CGRect(x: 10, y: 40, width: tableView.frame.size.width-10, height: 40)) as UILabel headerStringDetailLabel.text = formData[section] as? String headerStringDetailLabel.font = UIFont(name: "Courier", size: 16) let collapseRowsVal = collapseRows.object(at: section) as! Bool if collapseRowsVal == false { headerStringDetailLabel.isHidden = true } headerStringDetailLabel.tag = 200 + section let headerButton = UIButton() let val = collapse.object(at: section) as! Bool if val == false { headerButton.setTitle("+", for: .normal) } else { headerButton.setTitle("-", for: .normal) } headerButton.setTitleColor(UIColor.white, for: .normal) headerButton.tag = section headerButton.frame = CGRect(x:tableView.frame.size.width-40,y:5,width:30,height:40) headerButton.addTarget(self, action: #selector(FeedbackViewController.headerTapped), for: .touchUpInside) headerView.addSubview(headerString) headerView.addSubview(headerButton) headerView.addSubview(headerStringDetailLabel) return headerView } func headerTapped(sender: UIButton!) { setEditing(false, animated: true) print("Tapping") print(sender.tag) let indexPath : NSIndexPath = NSIndexPath(row: 0, section: sender.tag) var valCollapse = collapseRows.object(at: indexPath.section) as! Bool valCollapse = false collapseRows.replaceObject(at: indexPath.section, with: valCollapse) var val = collapse.object(at: indexPath.section) as! Bool val = !val collapse.replaceObject(at: indexPath.section, with: val) for i in 0..<collapse.count { if i != indexPath.section { collapse.replaceObject(at: i, with: false) } } tableView.reloadData(); } func dismissKeyboard(){ self.view.endEditing(true); } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // tableView.deselectRow(at: indexPath, animated: true) print("Selected row"); let country = sectionHeader.object(at: indexPath.section) as! String let arr = dict.value(forKey: country) as! NSArray let headerView = self.view.viewWithTag(0) let headerDetailLabel = headerView?.viewWithTag(200+indexPath.section) as? UILabel headerDetailLabel?.text = arr.object(at: indexPath.row) as? String; headerDetailLabel?.isHidden = false; formData[indexPath.section] = arr.object(at: indexPath.row) as? String; // let indexPath = tableView.indexPathForSelectedRow! // let cell = tableView.cellForRow(at: indexPath)! as UITableViewCell // cell.detailTextLabel?.text = arr.object(at: indexPath.row) as? String // cell.detailTextLabel?.sizeToFit(); // tableView.reloadData() var val = collapseRows.object(at: indexPath.section) as! Bool val = true collapseRows.replaceObject(at: indexPath.section, with: val) // for i in 0..<collapseRows.count // { // if i != indexPath.section // { // collapseRows.replaceObject(at: i, with: false) // // } // } var value = collapse.object(at: indexPath.section) as! Bool value = !value collapse.replaceObject(at: indexPath.section, with: value) for i in 0..<collapse.count { if i != indexPath.section { collapse.replaceObject(at: i, with: false) } } let range = NSMakeRange(indexPath.section,1) let sectionReload = NSIndexSet(indexesIn: range) tableView.reloadSections(sectionReload as IndexSet, with: UITableViewRowAnimation.fade) tableView.reloadSections(NSIndexSet(index: indexPath.section) as IndexSet, with: UITableViewRowAnimation.none) } @IBAction func exitSelectKiosk(segue: UIStoryboardSegue) { let controller = segue.source as? SelectKioskTableViewController let location = controller?.selectionLocation self.locationObject = location! navigationItem.title = location?.address } }
apache-2.0
8242684b50f4788f52999c1b851df82b
39.259375
192
0.617325
4.972212
false
false
false
false
liuchuo/LeetCode-practice
Swift/62. Unique Paths.swift
1
600
// 62. Unique Paths // 16 ms, 39.53% func uniquePaths(_ m: Int, _ n: Int) -> Int { pathMatrix = Array(repeating: Array(repeating: 0, count: n+1), count: m+1) return pathMatrix(m, n) } private var pathMatrix: [[Int]]! private func pathMatrix(_ m: Int, _ n: Int) -> Int { if m <= 0 || n <= 0 { return 0 } if m < 2 || n < 2 { pathMatrix[m][n] = 1; return 1 } if pathMatrix[m-1][n] == 0 { pathMatrix[m-1][n] = pathMatrix(m-1, n) } if pathMatrix[m][n-1] == 0 { pathMatrix[m][n-1] = pathMatrix(m, n-1) } return pathMatrix[m-1][n] + pathMatrix[m][n-1] }
gpl-3.0
20cfa8c812fb8472733ef4d5facf7757
29.05
78
0.546667
2.643172
false
false
false
false
cdtschange/SwiftMKit
SwiftMKitDemo/SwiftMKitDemo/Data/Api/NetworkDemo.swift
1
5735
// // NetworkDemo.swift // SwiftMKitDemo // // Created by wei.mao on 2018/7/3. // Copyright © 2018年 cdts. All rights reserved. // import Foundation import Alamofire import CocoaLumberjack import ReactiveSwift import SwiftMKit public struct NetworkDemo { } public struct LoginService { static var accessKey: String? static var token: String? static var username: String? static func refreshAccessKey(completion: @escaping (Bool) -> Void) -> SignalProducer<LoginTokenApi, NetError> { return LoginTokenApi(username: username ?? "", token: token ?? "").signal().on(failed: { (error) in print(error) completion(false) }) { api in accessKey = api.accessKey completion(true) } } } class DMRequestHandler: RequestHandler { private let lock = NSLock() private var requestsToRetry: [RequestRetryCompletion] = [] private var isRefreshingAccessKey = false func adapt(_ urlRequest: URLRequest) throws -> URLRequest { if let accessKey = LoginService.accessKey { var urlRequest = urlRequest urlRequest.addValue(accessKey, forHTTPHeaderField: "xxxxxx") return urlRequest } return urlRequest } func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) { lock.lock() ; defer { lock.unlock() } if let error = error as? NetError, error.statusCode == NetStatusCode.unAuthorized.rawValue { requestsToRetry.append(completion) DDLogInfo("[Api] Token过期") if !isRefreshingAccessKey { isRefreshingAccessKey = true DDLogInfo("[Api] Token续期") LoginService.refreshAccessKey { [weak self] succeeded in guard let strongSelf = self else { return } strongSelf.lock.lock() ; defer { strongSelf.lock.unlock() } strongSelf.isRefreshingAccessKey = false DDLogInfo("[Api] 开始重试") strongSelf.requestsToRetry.forEach { $0(succeeded, 0.0) } strongSelf.requestsToRetry.removeAll() }.start() } } else { completion(false, 0.0) } } } class DMRequestApi: NSObject, RequestApi { var sessionIdentifier: String { return "DMRequestApi" } var baseURLString: String { return "http://xxxxxx" } var baseHeader: [String : Any]? var timeoutIntervalForRequest: TimeInterval { return 15 } var timeoutIntervalForResource: TimeInterval { return 45 } var url: String { return "" } var method: HTTPMethod { return .get } var params: [String: Any]? { return nil } var headers: HTTPHeaders? { return nil } var responseData: Data? var error: NetError? var requestHandler: RequestHandler? { return DMRequestHandler() } weak var indicator: Indicator? func setIndicator(_ indicator: Indicator?, view: UIView? = UIViewController.topController?.view, text: String? = nil) -> Self { self.indicator = indicator self.indicator?.add(api: self, view: view, text: text) return self } var validate: DataRequest.Validation { return { request, response, data in if let data = data, let dict = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any], let map = dict { if let statusCode = (map["statusCode"] as? String)?.toInt(), let message = map["errorMessage"] as? String, statusCode != NetStatusCode.success.rawValue { let error = NetError(statusCode: statusCode, message: message) return DataRequest.ValidationResult.failure(error) } } return DataRequest.ValidationResult.success } } func adapt(_ result: Result<Any>) -> Result<Any> { if result.isSuccess, let map = result.value as? [String: Any], let statusCode = (map["statusCode"] as? String)?.toInt(), let message = map["errorMessage"] as? String { if statusCode == NetStatusCode.success.rawValue { if let value = (map["data"] as? [String: Any]) { return Result.success(value) } let value = (map["data"] as? String)?.toDictionary() ?? [:] return Result.success(value) } else { let error = NetError(statusCode: statusCode, message: message) return Result.failure(error) } } return result } func fill(map: [String: Any]) {} func fill(array: [Any]) {} public override init() { super.init() } public convenience init(error: NetError) { self.init() self.error = error } deinit { DDLogError("Deinit: \(NSStringFromClass(type(of: self)))") } } class LoginTokenApi: DMRequestApi { var username: String var token: String var result: [String: Any]? var accessKey: String? { return result?["access_key"] as? String } override var url: String { return "login/token" } override var method: HTTPMethod { return .post } override var params: [String : Any]? { return ["username": username, "token": token] } init(username: String, token: String) { self.username = username self.token = token } override func fill(map: [String : Any]) { result = map } }
mit
46521b256fdc8a54e8465d4c272578d4
33.853659
133
0.585899
4.751455
false
false
false
false
CD1212/Doughnut
Pods/GRDB.swift/GRDB/Record/Persistable.swift
1
39035
extension Database.ConflictResolution { var invalidatesLastInsertedRowID: Bool { switch self { case .abort, .fail, .rollback, .replace: return false case .ignore: // Statement may have succeeded without inserting any row return true } } } // MARK: - PersistenceError /// An error thrown by a type that adopts Persistable. public enum PersistenceError: Error { /// Thrown by MutablePersistable.update() when no matching row could be /// found in the database. case recordNotFound(MutablePersistable) } extension PersistenceError : CustomStringConvertible { public var description: String { switch self { case .recordNotFound(let persistable): return "Not found: \(persistable)" } } } // MARK: - PersistenceContainer /// Use persistence containers in the `encode(to:)` method of your /// persistable records: /// /// struct Player : MutablePersistable { /// var id: Int64? /// var name: String? /// /// func encode(to container: inout PersistenceContainer) { /// container["id"] = id /// container["name"] = name /// } /// } public struct PersistenceContainer { // fileprivate for Row(_:PersistenceContainer) fileprivate var storage: [String: DatabaseValueConvertible?] /// Accesses the value associated with the given column. /// /// It is undefined behavior to set different values for the same column. /// Column names are case insensitive, so defining both "name" and "NAME" /// is considered undefined behavior. public subscript(_ column: String) -> DatabaseValueConvertible? { get { return storage[column] ?? nil } set { storage.updateValue(newValue, forKey: column) } } /// Accesses the value associated with the given column. /// /// It is undefined behavior to set different values for the same column. /// Column names are case insensitive, so defining both "name" and "NAME" /// is considered undefined behavior. public subscript(_ column: Column) -> DatabaseValueConvertible? { get { return self[column.name] } set { self[column.name] = newValue } } init() { storage = [:] } /// Convenience initializer from a record /// /// // Sweet /// let container = PersistenceContainer(record) /// /// // Meh /// var container = PersistenceContainer() /// record.encode(to: container) init(_ record: MutablePersistable) { storage = [:] record.encode(to: &self) } /// Columns stored in the container, ordered like values. var columns: [String] { return Array(storage.keys) } /// Values stored in the container, ordered like columns. var values: [DatabaseValueConvertible?] { return Array(storage.values) } /// Accesses the value associated with the given column, in a /// case-insensitive fashion. subscript(caseInsensitive column: String) -> DatabaseValueConvertible? { get { if let value = storage[column] { return value } let lowercaseColumn = column.lowercased() for (key, value) in storage where key.lowercased() == lowercaseColumn { return value } return nil } set { if storage[column] != nil { storage[column] = newValue return } let lowercaseColumn = column.lowercased() for key in storage.keys where key.lowercased() == lowercaseColumn { storage[key] = newValue return } storage[column] = newValue } } var isEmpty: Bool { return storage.isEmpty } /// An iterator over the (column, value) pairs func makeIterator() -> DictionaryIterator<String, DatabaseValueConvertible?> { return storage.makeIterator() } } extension Row { convenience init(_ record: MutablePersistable) { self.init(PersistenceContainer(record)) } convenience init(_ container: PersistenceContainer) { self.init(container.storage) } } // MARK: - MutablePersistable /// The MutablePersistable protocol uses this type in order to handle SQLite /// conflicts when records are inserted or updated. /// /// See `MutablePersistable.persistenceConflictPolicy`. /// /// See https://www.sqlite.org/lang_conflict.html public struct PersistenceConflictPolicy { /// The conflict resolution algorithm for insertions public let conflictResolutionForInsert: Database.ConflictResolution /// The conflict resolution algorithm for updates public let conflictResolutionForUpdate: Database.ConflictResolution /// Creates a policy public init(insert: Database.ConflictResolution = .abort, update: Database.ConflictResolution = .abort) { self.conflictResolutionForInsert = insert self.conflictResolutionForUpdate = update } } /// Types that adopt MutablePersistable can be inserted, updated, and deleted. public protocol MutablePersistable : TableMapping { /// The policy that handles SQLite conflicts when records are inserted /// or updated. /// /// This property is optional: its default value uses the ABORT policy /// for both insertions and updates, and has GRDB generate regular /// INSERT and UPDATE queries. /// /// If insertions are resolved with .ignore policy, the /// `didInsert(with:for:)` method is not called upon successful insertion, /// even if a row was actually inserted without any conflict. /// /// See https://www.sqlite.org/lang_conflict.html static var persistenceConflictPolicy: PersistenceConflictPolicy { get } /// Defines the values persisted in the database. /// /// Store in the *container* argument all values that should be stored in /// the columns of the database table (see databaseTableName()). /// /// Primary key columns, if any, must be included. /// /// struct Player : MutablePersistable { /// var id: Int64? /// var name: String? /// /// func encode(to container: inout PersistenceContainer) { /// container["id"] = id /// container["name"] = name /// } /// } /// /// It is undefined behavior to set different values for the same column. /// Column names are case insensitive, so defining both "name" and "NAME" /// is considered undefined behavior. func encode(to container: inout PersistenceContainer) /// Notifies the record that it was succesfully inserted. /// /// Do not call this method directly: it is called for you, in a protected /// dispatch queue, with the inserted RowID and the eventual /// INTEGER PRIMARY KEY column name. /// /// This method is optional: the default implementation does nothing. /// /// struct Player : MutablePersistable { /// var id: Int64? /// var name: String? /// /// mutating func didInsert(with rowID: Int64, for column: String?) { /// self.id = rowID /// } /// } /// /// - parameters: /// - rowID: The inserted rowID. /// - column: The name of the eventual INTEGER PRIMARY KEY column. mutating func didInsert(with rowID: Int64, for column: String?) // MARK: - CRUD /// Executes an INSERT statement. /// /// This method is guaranteed to have inserted a row in the database if it /// returns without error. /// /// Upon successful insertion, the didInsert(with:for:) method /// is called with the inserted RowID and the eventual INTEGER PRIMARY KEY /// column name. /// /// This method has a default implementation, so your adopting types don't /// have to implement it. Yet your types can provide their own /// implementation of insert(). In their implementation, it is recommended /// that they invoke the performInsert() method. /// /// - parameter db: A database connection. /// - throws: A DatabaseError whenever an SQLite error occurs. mutating func insert(_ db: Database) throws /// Executes an UPDATE statement. /// /// This method is guaranteed to have updated a row in the database if it /// returns without error. /// /// This method has a default implementation, so your adopting types don't /// have to implement it. Yet your types can provide their own /// implementation of update(). In their implementation, it is recommended /// that they invoke the performUpdate() method. /// /// - parameter db: A database connection. /// - parameter columns: The columns to update. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. /// PersistenceError.recordNotFound is thrown if the primary key does not /// match any row in the database. func update(_ db: Database, columns: Set<String>) throws /// Executes an INSERT or an UPDATE statement so that `self` is saved in /// the database. /// /// If the receiver has a non-nil primary key and a matching row in the /// database, this method performs an update. /// /// Otherwise, performs an insert. /// /// This method is guaranteed to have inserted or updated a row in the /// database if it returns without error. /// /// This method has a default implementation, so your adopting types don't /// have to implement it. Yet your types can provide their own /// implementation of save(). In their implementation, it is recommended /// that they invoke the performSave() method. /// /// - parameter db: A database connection. /// - throws: A DatabaseError whenever an SQLite error occurs, or errors /// thrown by update(). mutating func save(_ db: Database) throws /// Executes a DELETE statement. /// /// This method has a default implementation, so your adopting types don't /// have to implement it. Yet your types can provide their own /// implementation of delete(). In their implementation, it is recommended /// that they invoke the performDelete() method. /// /// - parameter db: A database connection. /// - returns: Whether a database row was deleted. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. @discardableResult func delete(_ db: Database) throws -> Bool /// Returns true if and only if the primary key matches a row in /// the database. /// /// This method has a default implementation, so your adopting types don't /// have to implement it. Yet your types can provide their own /// implementation of exists(). In their implementation, it is recommended /// that they invoke the performExists() method. /// /// - parameter db: A database connection. /// - returns: Whether the primary key matches a row in the database. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. func exists(_ db: Database) throws -> Bool } extension MutablePersistable { /// A dictionary whose keys are the columns encoded in the `encode(to:)` method. public var databaseDictionary: [String: DatabaseValue] { return PersistenceContainer(self).storage.mapValues { $0?.databaseValue ?? .null } } } extension MutablePersistable { /// Describes the conflict policy for insertions and updates. /// /// The default value specifies ABORT policy for both insertions and /// updates, which has GRDB generate regular INSERT and UPDATE queries. public static var persistenceConflictPolicy: PersistenceConflictPolicy { return PersistenceConflictPolicy(insert: .abort, update: .abort) } /// Notifies the record that it was succesfully inserted. /// /// The default implementation does nothing. public mutating func didInsert(with rowID: Int64, for column: String?) { } // MARK: - CRUD /// Executes an INSERT statement. /// /// The default implementation for insert() invokes performInsert(). public mutating func insert(_ db: Database) throws { try performInsert(db) } /// Executes an UPDATE statement. /// /// - parameter db: A database connection. /// - parameter columns: The columns to update. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. /// PersistenceError.recordNotFound is thrown if the primary key does not /// match any row in the database. public func update(_ db: Database, columns: Set<String>) throws { try performUpdate(db, columns: columns) } /// Executes an UPDATE statement. /// /// - parameter db: A database connection. /// - parameter columns: The columns to update. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. /// PersistenceError.recordNotFound is thrown if the primary key does not /// match any row in the database. public func update<Sequence: Swift.Sequence>(_ db: Database, columns: Sequence) throws where Sequence.Element == Column { try update(db, columns: Set(columns.map { $0.name })) } /// Executes an UPDATE statement. /// /// - parameter db: A database connection. /// - parameter columns: The columns to update. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. /// PersistenceError.recordNotFound is thrown if the primary key does not /// match any row in the database. public func update<Sequence: Swift.Sequence>(_ db: Database, columns: Sequence) throws where Sequence.Element == String { try update(db, columns: Set(columns)) } /// Executes an UPDATE statement that updates all table columns. /// /// - parameter db: A database connection. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. /// PersistenceError.recordNotFound is thrown if the primary key does not /// match any row in the database. public func update(_ db: Database) throws { let databaseTableName = type(of: self).databaseTableName let columns = try db.columns(in: databaseTableName) try update(db, columns: Set(columns.map { $0.name })) } /// Executes an INSERT or an UPDATE statement so that `self` is saved in /// the database. /// /// The default implementation for save() invokes performSave(). public mutating func save(_ db: Database) throws { try performSave(db) } /// Executes a DELETE statement. /// /// The default implementation for delete() invokes performDelete(). @discardableResult public func delete(_ db: Database) throws -> Bool { return try performDelete(db) } /// Returns true if and only if the primary key matches a row in /// the database. /// /// The default implementation for exists() invokes performExists(). public func exists(_ db: Database) throws -> Bool { return try performExists(db) } // MARK: - CRUD Internals /// Return true if record has a non-null primary key fileprivate func canUpdate(_ db: Database) throws -> Bool { let databaseTableName = type(of: self).databaseTableName let primaryKey = try db.primaryKey(databaseTableName) let container = PersistenceContainer(self) for column in primaryKey.columns { if let value = container[caseInsensitive: column], !value.databaseValue.isNull { return true } } return false } /// Don't invoke this method directly: it is an internal method for types /// that adopt MutablePersistable. /// /// performInsert() provides the default implementation for insert(). Types /// that adopt MutablePersistable can invoke performInsert() in their /// implementation of insert(). They should not provide their own /// implementation of performInsert(). public mutating func performInsert(_ db: Database) throws { let conflictResolutionForInsert = type(of: self).persistenceConflictPolicy.conflictResolutionForInsert let dao = try DAO(db, self) try dao.insertStatement(onConflict: conflictResolutionForInsert).execute() if !conflictResolutionForInsert.invalidatesLastInsertedRowID { didInsert(with: db.lastInsertedRowID, for: dao.primaryKey.rowIDColumn) } } /// Don't invoke this method directly: it is an internal method for types /// that adopt MutablePersistable. /// /// performUpdate() provides the default implementation for update(). Types /// that adopt MutablePersistable can invoke performUpdate() in their /// implementation of update(). They should not provide their own /// implementation of performUpdate(). /// /// - parameter db: A database connection. /// - parameter columns: The columns to update. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. /// PersistenceError.recordNotFound is thrown if the primary key does not /// match any row in the database. public func performUpdate(_ db: Database, columns: Set<String>) throws { guard let statement = try DAO(db, self).updateStatement(columns: columns, onConflict: type(of: self).persistenceConflictPolicy.conflictResolutionForUpdate) else { // Nil primary key throw PersistenceError.recordNotFound(self) } try statement.execute() if db.changesCount == 0 { throw PersistenceError.recordNotFound(self) } } /// Don't invoke this method directly: it is an internal method for types /// that adopt MutablePersistable. /// /// performSave() provides the default implementation for save(). Types /// that adopt MutablePersistable can invoke performSave() in their /// implementation of save(). They should not provide their own /// implementation of performSave(). /// /// This default implementation forwards the job to `update` or `insert`. public mutating func performSave(_ db: Database) throws { // Make sure we call self.insert and self.update so that classes // that override insert or save have opportunity to perform their // custom job. if try canUpdate(db) { do { try update(db) } catch PersistenceError.recordNotFound { // TODO: check that the not persisted objet is self // // Why? Adopting types could override update() and update // another object which may be the one throwing this error. try insert(db) } } else { try insert(db) } } /// Don't invoke this method directly: it is an internal method for types /// that adopt MutablePersistable. /// /// performDelete() provides the default implementation for deelte(). Types /// that adopt MutablePersistable can invoke performDelete() in /// their implementation of delete(). They should not provide their own /// implementation of performDelete(). public func performDelete(_ db: Database) throws -> Bool { guard let statement = try DAO(db, self).deleteStatement() else { // Nil primary key return false } try statement.execute() return db.changesCount > 0 } /// Don't invoke this method directly: it is an internal method for types /// that adopt MutablePersistable. /// /// performExists() provides the default implementation for exists(). Types /// that adopt MutablePersistable can invoke performExists() in /// their implementation of exists(). They should not provide their own /// implementation of performExists(). public func performExists(_ db: Database) throws -> Bool { guard let statement = try DAO(db, self).existsStatement() else { // Nil primary key return false } return try Row.fetchOne(statement) != nil } } extension MutablePersistable { // MARK: - Deleting All /// Deletes all records; returns the number of deleted rows. /// /// - parameter db: A database connection. /// - returns: The number of deleted rows /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. @discardableResult public static func deleteAll(_ db: Database) throws -> Int { return try all().deleteAll(db) } } extension MutablePersistable { // MARK: - Deleting by Single-Column Primary Key /// Delete records identified by their primary keys; returns the number of /// deleted rows. /// /// // DELETE FROM players WHERE id IN (1, 2, 3) /// try Player.deleteAll(db, keys: [1, 2, 3]) /// /// // DELETE FROM countries WHERE code IN ('FR', 'US', 'DE') /// try Country.deleteAll(db, keys: ["FR", "US", "DE"]) /// /// When the table has no explicit primary key, GRDB uses the hidden /// "rowid" column: /// /// // DELETE FROM documents WHERE rowid IN (1, 2, 3) /// try Document.deleteAll(db, keys: [1, 2, 3]) /// /// - parameters: /// - db: A database connection. /// - keys: A sequence of primary keys. /// - returns: The number of deleted rows @discardableResult public static func deleteAll<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> Int where Sequence.Element: DatabaseValueConvertible { let keys = Array(keys) if keys.isEmpty { // Avoid hitting the database return 0 } return try filter(keys: keys).deleteAll(db) } /// Delete a record, identified by its primary key; returns whether a /// database row was deleted. /// /// // DELETE FROM players WHERE id = 123 /// try Player.deleteOne(db, key: 123) /// /// // DELETE FROM countries WHERE code = 'FR' /// try Country.deleteOne(db, key: "FR") /// /// When the table has no explicit primary key, GRDB uses the hidden /// "rowid" column: /// /// // DELETE FROM documents WHERE rowid = 1 /// try Document.deleteOne(db, key: 1) /// /// - parameters: /// - db: A database connection. /// - key: A primary key value. /// - returns: Whether a database row was deleted. @discardableResult public static func deleteOne<PrimaryKeyType: DatabaseValueConvertible>(_ db: Database, key: PrimaryKeyType?) throws -> Bool { guard let key = key else { // Avoid hitting the database return false } return try deleteAll(db, keys: [key]) > 0 } } extension MutablePersistable { // MARK: - Deleting by Key /// Delete records identified by the provided unique keys (primary key or /// any key with a unique index on it); returns the number of deleted rows. /// /// try Player.deleteAll(db, keys: [["email": "[email protected]"], ["email": "[email protected]"]]) /// /// - parameters: /// - db: A database connection. /// - keys: An array of key dictionaries. /// - returns: The number of deleted rows @discardableResult public static func deleteAll(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> Int { if keys.isEmpty { // Avoid hitting the database return 0 } return try filter(keys: keys).deleteAll(db) } /// Delete a record, identified by a unique key (the primary key or any key /// with a unique index on it); returns whether a database row was deleted. /// /// Player.deleteOne(db, key: ["name": Arthur"]) /// /// - parameters: /// - db: A database connection. /// - key: A dictionary of values. /// - returns: Whether a database row was deleted. @discardableResult public static func deleteOne(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Bool { return try deleteAll(db, keys: [key]) > 0 } } // MARK: - Persistable /// Types that adopt Persistable can be inserted, updated, and deleted. /// /// This protocol is intented for types that don't have an INTEGER PRIMARY KEY. /// /// Unlike MutablePersistable, the insert() and save() methods are not /// mutating methods. public protocol Persistable : MutablePersistable { /// Notifies the record that it was succesfully inserted. /// /// Do not call this method directly: it is called for you, in a protected /// dispatch queue, with the inserted RowID and the eventual /// INTEGER PRIMARY KEY column name. /// /// This method is optional: the default implementation does nothing. /// /// If you need a mutating variant of this method, adopt the /// MutablePersistable protocol instead. /// /// - parameters: /// - rowID: The inserted rowID. /// - column: The name of the eventual INTEGER PRIMARY KEY column. func didInsert(with rowID: Int64, for column: String?) /// Executes an INSERT statement. /// /// This method is guaranteed to have inserted a row in the database if it /// returns without error. /// /// Upon successful insertion, the didInsert(with:for:) method /// is called with the inserted RowID and the eventual INTEGER PRIMARY KEY /// column name. /// /// This method has a default implementation, so your adopting types don't /// have to implement it. Yet your types can provide their own /// implementation of insert(). In their implementation, it is recommended /// that they invoke the performInsert() method. /// /// - parameter db: A database connection. /// - throws: A DatabaseError whenever an SQLite error occurs. func insert(_ db: Database) throws /// Executes an INSERT or an UPDATE statement so that `self` is saved in /// the database. /// /// If the receiver has a non-nil primary key and a matching row in the /// database, this method performs an update. /// /// Otherwise, performs an insert. /// /// This method is guaranteed to have inserted or updated a row in the /// database if it returns without error. /// /// This method has a default implementation, so your adopting types don't /// have to implement it. Yet your types can provide their own /// implementation of save(). In their implementation, it is recommended /// that they invoke the performSave() method. /// /// - parameter db: A database connection. /// - throws: A DatabaseError whenever an SQLite error occurs, or errors /// thrown by update(). func save(_ db: Database) throws } extension Persistable { /// Notifies the record that it was succesfully inserted. /// /// The default implementation does nothing. public func didInsert(with rowID: Int64, for column: String?) { } // MARK: - Immutable CRUD /// Executes an INSERT statement. /// /// The default implementation for insert() invokes performInsert(). public func insert(_ db: Database) throws { try performInsert(db) } /// Executes an INSERT or an UPDATE statement so that `self` is saved in /// the database. /// /// The default implementation for save() invokes performSave(). public func save(_ db: Database) throws { try performSave(db) } // MARK: - Immutable CRUD Internals /// Don't invoke this method directly: it is an internal method for types /// that adopt Persistable. /// /// performInsert() provides the default implementation for insert(). Types /// that adopt Persistable can invoke performInsert() in their /// implementation of insert(). They should not provide their own /// implementation of performInsert(). public func performInsert(_ db: Database) throws { let conflictResolutionForInsert = type(of: self).persistenceConflictPolicy.conflictResolutionForInsert let dao = try DAO(db, self) try dao.insertStatement(onConflict: conflictResolutionForInsert).execute() if !conflictResolutionForInsert.invalidatesLastInsertedRowID { didInsert(with: db.lastInsertedRowID, for: dao.primaryKey.rowIDColumn) } } /// Don't invoke this method directly: it is an internal method for types /// that adopt Persistable. /// /// performSave() provides the default implementation for save(). Types /// that adopt Persistable can invoke performSave() in their /// implementation of save(). They should not provide their own /// implementation of performSave(). /// /// This default implementation forwards the job to `update` or `insert`. public func performSave(_ db: Database) throws { // Make sure we call self.insert and self.update so that classes that // override insert or save have opportunity to perform their custom job. if try canUpdate(db) { do { try update(db) } catch PersistenceError.recordNotFound { // TODO: check that the not persisted objet is self // // Why? Adopting types could override update() and update another // object which may be the one throwing this error. try insert(db) } } else { try insert(db) } } } // MARK: - DAO /// DAO takes care of Persistable CRUD final class DAO { /// The database let db: Database /// The record let record: MutablePersistable /// DAO keeps a copy the record's persistenceContainer, so that this /// dictionary is built once whatever the database operation. It is /// guaranteed to have at least one (key, value) pair. let persistenceContainer: PersistenceContainer /// The table name let databaseTableName: String /// The table primary key let primaryKey: PrimaryKeyInfo init(_ db: Database, _ record: MutablePersistable) throws { let databaseTableName = type(of: record).databaseTableName let primaryKey = try db.primaryKey(databaseTableName) let persistenceContainer = PersistenceContainer(record) GRDBPrecondition(!persistenceContainer.isEmpty, "\(type(of: record)): invalid empty persistence container") self.db = db self.record = record self.persistenceContainer = persistenceContainer self.databaseTableName = databaseTableName self.primaryKey = primaryKey } func insertStatement(onConflict: Database.ConflictResolution) throws -> UpdateStatement { let query = InsertQuery( onConflict: onConflict, tableName: databaseTableName, insertedColumns: persistenceContainer.columns) let statement = try db.internalCachedUpdateStatement(query.sql) statement.unsafeSetArguments(StatementArguments(persistenceContainer.values)) return statement } /// Returns nil if and only if primary key is nil func updateStatement(columns: Set<String>, onConflict: Database.ConflictResolution) throws -> UpdateStatement? { // Fail early if primary key does not resolve to a database row. let primaryKeyColumns = primaryKey.columns let primaryKeyValues = primaryKeyColumns.map { persistenceContainer[caseInsensitive: $0]?.databaseValue ?? .null } guard primaryKeyValues.contains(where: { !$0.isNull }) else { return nil } let lowercasePersistentColumns = Set(persistenceContainer.columns.map { $0.lowercased() }) let lowercasePrimaryKeyColumns = Set(primaryKeyColumns.map { $0.lowercased() }) var updatedColumns: [String] = [] for column in columns { let lowercaseColumn = column.lowercased() // Don't update columns that are not present in the persistenceContainer guard lowercasePersistentColumns.contains(lowercaseColumn) else { continue } // Don't update primary key columns guard !lowercasePrimaryKeyColumns.contains(lowercaseColumn) else { continue } updatedColumns.append(column) } if updatedColumns.isEmpty { // IMPLEMENTATION NOTE // // It is important to update something, so that // TransactionObserver can observe a change even though this // change is useless. // // The goal is to be able to write tests with minimal tables, // including tables made of a single primary key column. updatedColumns = primaryKeyColumns } let updatedValues = updatedColumns.map { persistenceContainer[caseInsensitive: $0]?.databaseValue ?? .null } let query = UpdateQuery( onConflict: onConflict, tableName: databaseTableName, updatedColumns: updatedColumns, conditionColumns: primaryKeyColumns) let statement = try db.internalCachedUpdateStatement(query.sql) statement.unsafeSetArguments(StatementArguments(updatedValues + primaryKeyValues)) return statement } /// Returns nil if and only if primary key is nil func deleteStatement() throws -> UpdateStatement? { // Fail early if primary key does not resolve to a database row. let primaryKeyColumns = primaryKey.columns let primaryKeyValues = primaryKeyColumns.map { persistenceContainer[caseInsensitive: $0]?.databaseValue ?? .null } guard primaryKeyValues.contains(where: { !$0.isNull }) else { return nil } let query = DeleteQuery( tableName: databaseTableName, conditionColumns: primaryKeyColumns) let statement = try db.internalCachedUpdateStatement(query.sql) statement.unsafeSetArguments(StatementArguments(primaryKeyValues)) return statement } /// Returns nil if and only if primary key is nil func existsStatement() throws -> SelectStatement? { // Fail early if primary key does not resolve to a database row. let primaryKeyColumns = primaryKey.columns let primaryKeyValues = primaryKeyColumns.map { persistenceContainer[caseInsensitive: $0]?.databaseValue ?? .null } guard primaryKeyValues.contains(where: { !$0.isNull }) else { return nil } let query = ExistsQuery( tableName: databaseTableName, conditionColumns: primaryKeyColumns) let statement = try db.internalCachedSelectStatement(query.sql) statement.unsafeSetArguments(StatementArguments(primaryKeyValues)) return statement } } // MARK: - InsertQuery private struct InsertQuery { let onConflict: Database.ConflictResolution let tableName: String let insertedColumns: [String] } extension InsertQuery : Hashable { var hashValue: Int { return tableName.hashValue } static func == (lhs: InsertQuery, rhs: InsertQuery) -> Bool { if lhs.tableName != rhs.tableName { return false } if lhs.onConflict != rhs.onConflict { return false } return lhs.insertedColumns == rhs.insertedColumns } } extension InsertQuery { static let sqlCache = ReadWriteBox([InsertQuery: String]()) var sql: String { if let sql = InsertQuery.sqlCache.read({ $0[self] }) { return sql } let columnsSQL = insertedColumns.map { $0.quotedDatabaseIdentifier }.joined(separator: ", ") let valuesSQL = databaseQuestionMarks(count: insertedColumns.count) let sql: String switch onConflict { case .abort: sql = "INSERT INTO \(tableName.quotedDatabaseIdentifier) (\(columnsSQL)) VALUES (\(valuesSQL))" default: sql = "INSERT OR \(onConflict.rawValue) INTO \(tableName.quotedDatabaseIdentifier) (\(columnsSQL)) VALUES (\(valuesSQL))" } InsertQuery.sqlCache.write { $0[self] = sql } return sql } } // MARK: - UpdateQuery private struct UpdateQuery { let onConflict: Database.ConflictResolution let tableName: String let updatedColumns: [String] let conditionColumns: [String] } extension UpdateQuery : Hashable { var hashValue: Int { return tableName.hashValue } static func == (lhs: UpdateQuery, rhs: UpdateQuery) -> Bool { if lhs.tableName != rhs.tableName { return false } if lhs.onConflict != rhs.onConflict { return false } if lhs.updatedColumns != rhs.updatedColumns { return false } return lhs.conditionColumns == rhs.conditionColumns } } extension UpdateQuery { static let sqlCache = ReadWriteBox([UpdateQuery: String]()) var sql: String { if let sql = UpdateQuery.sqlCache.read({ $0[self] }) { return sql } let updateSQL = updatedColumns.map { "\($0.quotedDatabaseIdentifier)=?" }.joined(separator: ", ") let whereSQL = conditionColumns.map { "\($0.quotedDatabaseIdentifier)=?" }.joined(separator: " AND ") let sql: String switch onConflict { case .abort: sql = "UPDATE \(tableName.quotedDatabaseIdentifier) SET \(updateSQL) WHERE \(whereSQL)" default: sql = "UPDATE OR \(onConflict.rawValue) \(tableName.quotedDatabaseIdentifier) SET \(updateSQL) WHERE \(whereSQL)" } UpdateQuery.sqlCache.write { $0[self] = sql } return sql } } // MARK: - DeleteQuery private struct DeleteQuery { let tableName: String let conditionColumns: [String] } extension DeleteQuery { var sql: String { let whereSQL = conditionColumns.map { "\($0.quotedDatabaseIdentifier)=?" }.joined(separator: " AND ") return "DELETE FROM \(tableName.quotedDatabaseIdentifier) WHERE \(whereSQL)" } } // MARK: - ExistsQuery private struct ExistsQuery { let tableName: String let conditionColumns: [String] } extension ExistsQuery { var sql: String { let whereSQL = conditionColumns.map { "\($0.quotedDatabaseIdentifier)=?" }.joined(separator: " AND ") return "SELECT 1 FROM \(tableName.quotedDatabaseIdentifier) WHERE \(whereSQL)" } }
gpl-3.0
5ea01e4a8ad7537ad70843aaca282757
37.269608
170
0.638888
4.921826
false
false
false
false
debugsquad/nubecero
nubecero/View/Home/VHomeCellDiskCircleMemory.swift
1
1254
import UIKit class VHomeCellDiskCircleMemory:VHomeCellDiskCircle { private weak var timer:Timer? private var maxCircleEndAngle:CGFloat private let kTimeInterval:TimeInterval = 0.01 private let kAngleDelta:CGFloat = 0.06 override init(frame:CGRect) { maxCircleEndAngle = 0 super.init(frame:frame, color:UIColor.black) } override init(frame:CGRect, color:UIColor) { fatalError() } required init?(coder:NSCoder) { fatalError() } func tick(sender timer:Timer) { circleEndAngle += kAngleDelta if circleEndAngle > maxCircleEndAngle { circleEndAngle = maxCircleEndAngle timer.invalidate() } setNeedsDisplay() } //MARK: public func maxRadius(maxCircleEndAngle:CGFloat) { timer?.invalidate() self.maxCircleEndAngle = maxCircleEndAngle + kCircleStartAngle circleEndAngle = kCircleStartAngle timer = Timer.scheduledTimer( timeInterval:kTimeInterval, target:self, selector:#selector(tick(sender:)), userInfo:nil, repeats:true) } }
mit
7949741d49c6d86aae1d3719fcbf7bbc
21.8
70
0.590909
4.956522
false
false
false
false
debugsquad/nubecero
nubecero/View/Store/VStoreCellNew.swift
1
2890
import UIKit class VStoreCellNew:VStoreCell { private weak var labelPrice:UILabel! private let kButtonPurchaseWidth:CGFloat = 100 private let kLabelPriceWidth:CGFloat = 200 override init(frame:CGRect) { super.init(frame:frame) let buttonPurchase:UIButton = UIButton() buttonPurchase.translatesAutoresizingMaskIntoConstraints = false buttonPurchase.backgroundColor = UIColor.complement buttonPurchase.setTitleColor( UIColor.white, for:UIControlState.normal) buttonPurchase.setTitleColor( UIColor.black, for:UIControlState.highlighted) buttonPurchase.setTitle( NSLocalizedString("VStoreCellNew_buttonPurchase", comment:""), for:UIControlState.normal) buttonPurchase.titleLabel!.font = UIFont.medium(size:15) buttonPurchase.addTarget( self, action:#selector(actionPurchase(sender:)), for:UIControlEvents.touchUpInside) let labelPrice:UILabel = UILabel() labelPrice.isUserInteractionEnabled = false labelPrice.translatesAutoresizingMaskIntoConstraints = false labelPrice.backgroundColor = UIColor.clear labelPrice.font = UIFont.medium(size:16) labelPrice.textColor = UIColor.black labelPrice.textAlignment = NSTextAlignment.right self.labelPrice = labelPrice addSubview(buttonPurchase) addSubview(labelPrice) let views:[String:UIView] = [ "buttonPurchase":buttonPurchase, "labelPrice":labelPrice] let metrics:[String:CGFloat] = [ "buttonPurchaseWidth":kButtonPurchaseWidth, "labelPriceWidth":kLabelPriceWidth] addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"H:[labelPrice(labelPriceWidth)]-10-[buttonPurchase(buttonPurchaseWidth)]-0-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"V:|-0-[buttonPurchase]-0-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"V:|-0-[labelPrice]-0-|", options:[], metrics:metrics, views:views)) } required init?(coder:NSCoder) { fatalError() } override func config(controller:CStore, model:MStoreItem) { super.config(controller:controller, model:model) labelPrice.text = model.price } //MARK: actions func actionPurchase(sender button:UIButton) { FMain.sharedInstance.analytics?.purchaseBuy() controller?.purchase(skProduct:model?.skProduct) } }
mit
5a907f1979d3e9ddead186bb8d1c27bb
32.604651
108
0.630796
5.391791
false
false
false
false
codefellows/sea-b19-ios
Projects/ClassRosterB19/ClassRosterB19/ViewController.swift
1
1176
// // ViewController.swift // ClassRosterB19 // // Created by John Clem on 7/21/14. // Copyright (c) 2014 Learn Swift. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDataSource { var people : Array<Person>! @IBOutlet var tableView : UITableView? override func viewDidLoad() { super.viewDidLoad() people = Person.defaultPeopleArray() tableView!.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // UITableViewDataSource func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int { return people.count } func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell let personForRow = people[indexPath.row] cell.textLabel.text = personForRow.firstName cell.detailTextLabel.text = personForRow.lastName return cell } }
gpl-2.0
e0cbe9532bd106913b0e5b4774608b9e
27
112
0.67517
5.25
false
false
false
false
KosyanMedia/Aviasales-iOS-SDK
AviasalesSDKTemplate/Source/HotelsSource/Filters/VariantsSorter.swift
1
6887
import Foundation typealias ComparisonFunc = (HLResultVariant, HLResultVariant) -> ComparisonResult @objcMembers class VariantsSorter: NSObject { class func sortVariants(_ variants: [HLResultVariant], withType type: SortType, searchInfo: HLSearchInfo) -> [HLResultVariant] { switch type { case .price: return sortVariantsByPrice(variants) case .distance: return sortVariantsByDistance(variants) case .rating: return sortVariantsByRating(variants) case .popularity: return sortVariantsByPopularity(variants, searchInfo: searchInfo) case .discount: return sortVariantsByDiscount(variants) case .bookingsCount: return sortVariantsByBookingsCount(variants) } } internal class func sortVariants(_ variants: [HLResultVariant], withComparisonFunc comparisonFunc: @escaping ComparisonFunc) -> [HLResultVariant] { let variantsNSArray: NSArray = variants as NSArray let comparator: Comparator = {(obj1, obj2) -> ComparisonResult in if let variant1 = obj1 as? HLResultVariant, let variant2 = obj2 as? HLResultVariant { return comparisonFunc(variant1, variant2) } return .orderedSame } return variantsNSArray.sortedArray(options: [.stable, .concurrent], usingComparator: comparator) as! [HLResultVariant] } class func sortVariantsByDiscount(_ variants: [HLResultVariant]) -> [HLResultVariant] { return sortVariants(variants, withComparisonFunc: addCheckRoomsCondition(getDiscountComparator())) } class func sortVariantsByPopularity(_ variants: [HLResultVariant], searchInfo: HLSearchInfo) -> [HLResultVariant] { let sortFunc = getPopularityComparator() return sortVariants(variants, withComparisonFunc: sortFunc) } class func sortVariantsByRating(_ variants: [HLResultVariant]) -> [HLResultVariant] { return sortVariants(variants, withComparisonFunc: addCheckRoomsCondition(addRatingCondition(getPriceComparator()))) } class func sortVariantsByPrice(_ variants: [HLResultVariant]) -> [HLResultVariant] { return sortVariants(variants, withComparisonFunc: addCheckRoomsCondition(getPriceComparator())) } class func sortVariantsByDistance(_ variants: [HLResultVariant]) -> [HLResultVariant] { return sortVariants(variants, withComparisonFunc: addCheckRoomsCondition(getDistanceComparator())) } class func sortVariantsByBookingsCount(_ variants: [HLResultVariant]) -> [HLResultVariant] { return sortVariants(variants, withComparisonFunc: addCheckRoomsCondition(getBookingsCountComparator())) } class func localizedNameForSortType(_ sortType: SortType) -> String { switch sortType { case .popularity: return NSLS("HL_LOC_SORT_TYPE_POPULARITY") case .price: return NSLS("HL_LOC_SORT_TYPE_PRICE") case .rating: return NSLS("HL_LOC_SORT_TYPE_RATING") case .distance: return NSLS("HL_LOC_SORT_TYPE_DISTANCE") case .discount: return NSLS("HL_LOC_SORT_TYPE_DISCOUNT") case .bookingsCount: return "Bookings count" } } // MARK: Private internal class func getPopularityComparator() -> ComparisonFunc { return { $0.hotel.popularity.compare($1.hotel.popularity) } } fileprivate class func getDiscountComparator() -> ComparisonFunc { return { (variant1: HLResultVariant, variant2: HLResultVariant) -> ComparisonResult in let discount1 = variant1.highlightType == .discount ? normalizeDiscountValue(variant1.discount) : 0 let discount2 = variant2.highlightType == .discount ? normalizeDiscountValue(variant2.discount) : 0 let discountComparisonResult = discount1.compare(discount2) if discountComparisonResult != .orderedSame { return discountComparisonResult } let offer1 = variant1.highlightType == .mobile || variant1.highlightType == .private let offer2 = variant2.highlightType == .mobile || variant2.highlightType == .private if offer1 && offer2 { return variant1.minPrice.compare(variant2.minPrice) } if offer1 { return .orderedAscending } if offer2 { return .orderedDescending } return variant1.hotel.popularity.compare(variant2.hotel.popularity) } } fileprivate class func normalizeDiscountValue(_ rawDiscount: Int) -> Int { if rawDiscount < HDKRoom.kDiscountHighCutoff || rawDiscount > HDKRoom.kDiscountLowCutoff { return 0 } return -rawDiscount } fileprivate class func getPriceComparator() -> ComparisonFunc { return { $1.minPrice.compare($0.minPrice) } } fileprivate class func getRatingComparator() -> ComparisonFunc { return { $0.hotel.rating.compare($1.hotel.rating) } } fileprivate class func getDistanceComparator() -> ComparisonFunc { return { $1.distanceToCurrentLocationPoint.compare($0.distanceToCurrentLocationPoint)} } fileprivate class func getBookingsCountComparator() -> ComparisonFunc { return { $0.hotel.popularity2.compare($1.hotel.popularity2)} } fileprivate class func addRatingCondition(_ origFunc: @escaping ComparisonFunc) -> ComparisonFunc { let ratingComparator = getRatingComparator() let decorator: ComparisonFunc = { (variant1, variant2) in let comparisonResult = ratingComparator(variant1, variant2) if comparisonResult != .orderedSame { return comparisonResult } return origFunc(variant1, variant2) } return decorator } internal class func addCheckRoomsCondition(_ origFunc: @escaping ComparisonFunc) -> ComparisonFunc { let decorator: ComparisonFunc = { (variant1, variant2) in let roomsAvailability1 = variant1.roomsAvailability() let roomsAvailability2 = variant2.roomsAvailability() if roomsAvailability1 == .hasRooms && roomsAvailability2 != .hasRooms { return .orderedAscending } if roomsAvailability1 == .sold && roomsAvailability2 == .noRooms { return .orderedAscending } if roomsAvailability2 == .hasRooms && roomsAvailability1 != .hasRooms { return .orderedDescending } if roomsAvailability2 == .sold && roomsAvailability1 == .noRooms { return .orderedDescending } return origFunc(variant1, variant2) } return decorator } }
mit
1d7591d3b2cf1bf6b08c8138081d43be
37.049724
151
0.65689
4.843179
false
false
false
false
tardieu/swift
test/stdlib/Inputs/DictionaryKeyValueTypes.swift
28
8119
import Swift import StdlibUnittest func acceptsAnySet<T : Hashable>(_ s: Set<T>) {} func acceptsAnyDictionary<KeyTy : Hashable, ValueTy>( _ d: Dictionary<KeyTy, ValueTy>) { } // Compare two arrays as sets. func equalsUnordered<T : Comparable>( _ lhs: Array<(T, T)>, _ rhs: Array<(T, T)> ) -> Bool { func areInAscendingOrder(_ lhs: (T, T), _ rhs: (T, T)) -> Bool { return [ lhs.0, lhs.1 ].lexicographicallyPrecedes([ rhs.0, rhs.1 ]) } return lhs.sorted(by: areInAscendingOrder) .elementsEqual(rhs.sorted(by: areInAscendingOrder)) { (lhs: (T, T), rhs: (T, T)) -> Bool in lhs.0 == rhs.0 && lhs.1 == rhs.1 } } func equalsUnordered<T : Comparable>(_ lhs: [T], _ rhs: [T]) -> Bool { return lhs.sorted().elementsEqual(rhs.sorted()) } var _keyCount = _stdlib_AtomicInt(0) var _keySerial = _stdlib_AtomicInt(0) // A wrapper class that can help us track allocations and find issues with // object lifetime. final class TestKeyTy : Equatable, Hashable, CustomStringConvertible, ExpressibleByIntegerLiteral { class var objectCount: Int { get { return _keyCount.load() } set { _keyCount.store(newValue) } } init(_ value: Int) { _keyCount.fetchAndAdd(1) serial = _keySerial.addAndFetch(1) self.value = value self._hashValue = value } convenience init(integerLiteral value: Int) { self.init(value) } convenience init(value: Int, hashValue: Int) { self.init(value) self._hashValue = hashValue } deinit { assert(serial > 0, "double destruction") _keyCount.fetchAndAdd(-1) serial = -serial } var description: String { assert(serial > 0, "dead TestKeyTy") return value.description } var hashValue: Int { return _hashValue } var value: Int var _hashValue: Int var serial: Int } func == (lhs: TestKeyTy, rhs: TestKeyTy) -> Bool { return lhs.value == rhs.value } var _valueCount = _stdlib_AtomicInt(0) var _valueSerial = _stdlib_AtomicInt(0) class TestValueTy : CustomStringConvertible { class var objectCount: Int { get { return _valueCount.load() } set { _valueCount.store(newValue) } } init(_ value: Int) { _valueCount.fetchAndAdd(1) serial = _valueSerial.addAndFetch(1) self.value = value } deinit { assert(serial > 0, "double destruction") _valueCount.fetchAndAdd(-1) serial = -serial } var description: String { assert(serial > 0, "dead TestValueTy") return value.description } var value: Int var serial: Int } var _equatableValueCount = _stdlib_AtomicInt(0) var _equatableValueSerial = _stdlib_AtomicInt(0) class TestEquatableValueTy : Equatable, CustomStringConvertible { class var objectCount: Int { get { return _equatableValueCount.load() } set { _equatableValueCount.store(newValue) } } init(_ value: Int) { _equatableValueCount.fetchAndAdd(1) serial = _equatableValueSerial.addAndFetch(1) self.value = value } deinit { assert(serial > 0, "double destruction") _equatableValueCount.fetchAndAdd(-1) serial = -serial } var description: String { assert(serial > 0, "dead TestEquatableValueTy") return value.description } var value: Int var serial: Int } func == (lhs: TestEquatableValueTy, rhs: TestEquatableValueTy) -> Bool { return lhs.value == rhs.value } func resetLeaksOfDictionaryKeysValues() { TestKeyTy.objectCount = 0 TestValueTy.objectCount = 0 TestEquatableValueTy.objectCount = 0 } func expectNoLeaksOfDictionaryKeysValues() { expectEqual(0, TestKeyTy.objectCount, "TestKeyTy leak") expectEqual(0, TestValueTy.objectCount, "TestValueTy leak") expectEqual(0, TestEquatableValueTy.objectCount, "TestEquatableValueTy leak") } struct ExpectedArrayElement : Comparable, CustomStringConvertible { var value: Int var valueIdentity: UInt init(value: Int, valueIdentity: UInt = 0) { self.value = value self.valueIdentity = valueIdentity } var description: String { return "(\(value), \(valueIdentity))" } } func == ( lhs: ExpectedArrayElement, rhs: ExpectedArrayElement ) -> Bool { return lhs.value == rhs.value && lhs.valueIdentity == rhs.valueIdentity } func < ( lhs: ExpectedArrayElement, rhs: ExpectedArrayElement ) -> Bool { let lhsElements = [ lhs.value, Int(bitPattern: lhs.valueIdentity) ] let rhsElements = [ rhs.value, Int(bitPattern: rhs.valueIdentity) ] return lhsElements.lexicographicallyPrecedes(rhsElements) } func _equalsWithoutElementIdentity( _ lhs: [ExpectedArrayElement], _ rhs: [ExpectedArrayElement] ) -> Bool { func stripIdentity( _ list: [ExpectedArrayElement] ) -> [ExpectedArrayElement] { return list.map { ExpectedArrayElement(value: $0.value) } } return stripIdentity(lhs).elementsEqual(stripIdentity(rhs)) } func _makeExpectedArrayContents( _ expected: [Int] ) -> [ExpectedArrayElement] { var result = [ExpectedArrayElement]() for value in expected { result.append(ExpectedArrayElement(value: value)) } return result } struct ExpectedSetElement : Comparable, CustomStringConvertible { var value: Int var valueIdentity: UInt init(value: Int, valueIdentity: UInt = 0) { self.value = value self.valueIdentity = valueIdentity } var description: String { return "(\(value), \(valueIdentity))" } } func == ( lhs: ExpectedSetElement, rhs: ExpectedSetElement ) -> Bool { return lhs.value == rhs.value && lhs.valueIdentity == rhs.valueIdentity } func < ( lhs: ExpectedSetElement, rhs: ExpectedSetElement ) -> Bool { let lhsElements = [ lhs.value, Int(bitPattern: lhs.valueIdentity) ] let rhsElements = [ rhs.value, Int(bitPattern: rhs.valueIdentity) ] return lhsElements.lexicographicallyPrecedes(rhsElements) } func _makeExpectedSetContents( _ expected: [Int] ) -> [ExpectedSetElement] { var result = [ExpectedSetElement]() for value in expected { result.append(ExpectedSetElement(value: value)) } return result } func _equalsUnorderedWithoutElementIdentity( _ lhs: [ExpectedSetElement], _ rhs: [ExpectedSetElement] ) -> Bool { func stripIdentity( _ list: [ExpectedSetElement] ) -> [ExpectedSetElement] { return list.map { ExpectedSetElement(value: $0.value) } } return equalsUnordered(stripIdentity(lhs), stripIdentity(rhs)) } struct ExpectedDictionaryElement : Comparable, CustomStringConvertible { var key: Int var value: Int var keyIdentity: UInt var valueIdentity: UInt init(key: Int, value: Int, keyIdentity: UInt = 0, valueIdentity: UInt = 0) { self.key = key self.value = value self.keyIdentity = keyIdentity self.valueIdentity = valueIdentity } var description: String { return "(\(key), \(value), \(keyIdentity), \(valueIdentity))" } } func == ( lhs: ExpectedDictionaryElement, rhs: ExpectedDictionaryElement ) -> Bool { return lhs.key == rhs.key && lhs.value == rhs.value && lhs.keyIdentity == rhs.keyIdentity && lhs.valueIdentity == rhs.valueIdentity } func < ( lhs: ExpectedDictionaryElement, rhs: ExpectedDictionaryElement ) -> Bool { let lhsElements = [ lhs.key, lhs.value, Int(bitPattern: lhs.keyIdentity), Int(bitPattern: lhs.valueIdentity) ] let rhsElements = [ rhs.key, rhs.value, Int(bitPattern: rhs.keyIdentity), Int(bitPattern: rhs.valueIdentity) ] return lhsElements.lexicographicallyPrecedes(rhsElements) } func _equalsUnorderedWithoutElementIdentity( _ lhs: [ExpectedDictionaryElement], _ rhs: [ExpectedDictionaryElement] ) -> Bool { func stripIdentity( _ list: [ExpectedDictionaryElement] ) -> [ExpectedDictionaryElement] { return list.map { ExpectedDictionaryElement(key: $0.key, value: $0.value) } } return equalsUnordered(stripIdentity(lhs), stripIdentity(rhs)) } func _makeExpectedDictionaryContents( _ expected: [(Int, Int)] ) -> [ExpectedDictionaryElement] { var result = [ExpectedDictionaryElement]() for (key, value) in expected { result.append(ExpectedDictionaryElement(key: key, value: value)) } return result }
apache-2.0
a2910a13a8e4bf59fbbb8b67a17ff6c5
22.809384
79
0.687893
3.831524
false
true
false
false
tardieu/swift
test/Driver/filelists.swift
15
3137
// RUN: rm -rf %t && mkdir -p %t // RUN: touch %t/a.swift %t/b.swift %t/c.swift // RUN: (cd %t && %swiftc_driver_plain -driver-use-frontend-path %S/Inputs/filelists/check-filelist-abc.py -emit-module ./a.swift ./b.swift ./c.swift -module-name main -target x86_64-apple-macosx10.9 -driver-use-filelists -output-file-map=%S/Inputs/filelists/output.json 2>&1 | %FileCheck %s) // CHECK-NOT: Handled // CHECK: Handled a.swift // CHECK-NEXT: Handled b.swift // CHECK-NEXT: Handled c.swift // CHECK-NEXT: Handled modules // CHECK-NOT: Handled // RUN: %swiftc_driver_plain -driver-use-frontend-path %S/Inputs/filelists/check-filelist-abc.py -c %t/a.swift %t/b.swift %t/c.swift -module-name main -target x86_64-apple-macosx10.9 -driver-use-filelists -force-single-frontend-invocation 2>&1 | %FileCheck -check-prefix=CHECK-WMO %s // CHECK-WMO-NOT: Handled // CHECK-WMO: Handled all // CHECK-WMO-NOT: output // CHECK-WMO-NOT: Handled // RUN: mkdir -p %t/bin // RUN: ln -s %S/Inputs/filelists/fake-ld.py %t/bin/ld // RUN: (cd %t && %swiftc_driver_plain -driver-use-frontend-path %S/Inputs/filelists/check-filelist-abc.py -c ./a.swift ./b.swift ./c.swift -module-name main -target x86_64-apple-macosx10.9 -driver-use-filelists -output-file-map=%S/Inputs/filelists/output.json -force-single-frontend-invocation -num-threads 1 2>&1 | %FileCheck -check-prefix=CHECK-WMO-THREADED %s) // RUN: (cd %t && %swiftc_driver_plain -driver-use-frontend-path %S/Inputs/filelists/check-filelist-abc.py -c ./a.swift ./b.swift ./c.swift -module-name main -target x86_64-apple-macosx10.9 -driver-use-filelists -output-file-map=%S/Inputs/filelists/output.json -force-single-frontend-invocation -num-threads 1 -embed-bitcode 2>&1 | %FileCheck -check-prefix=CHECK-WMO-THREADED %s) // RUN: mkdir -p %t/tmp/ // RUN: (cd %t && env TMPDIR="%t/tmp/" %swiftc_driver_plain -driver-use-frontend-path %S/Inputs/filelists/check-filelist-abc.py -c ./a.swift ./b.swift ./c.swift -module-name main -target x86_64-apple-macosx10.9 -driver-use-filelists -output-file-map=%S/Inputs/filelists/output.json -force-single-frontend-invocation -num-threads 1 -save-temps 2>&1 | %FileCheck -check-prefix=CHECK-WMO-THREADED %s) // RUN: ls %t/tmp/sources-* %t/tmp/outputs-* // CHECK-WMO-THREADED-NOT: Handled // CHECK-WMO-THREADED: Handled all // CHECK-WMO-THREADED-NEXT: ...with output! // CHECK-WMO-THREADED-NOT: Handled // RUN: (cd %t && env PATH=%t/bin/:$PATH %swiftc_driver_plain -driver-use-frontend-path %S/Inputs/filelists/check-filelist-abc.py -emit-library ./a.swift ./b.swift ./c.swift -module-name main -target x86_64-apple-macosx10.9 -driver-use-filelists -output-file-map=%S/Inputs/filelists/output.json 2>&1 | %FileCheck -check-prefix=CHECK-LINK %s) // RUN: (cd %t && env PATH=%t/bin/:$PATH %swiftc_driver_plain -driver-use-frontend-path %S/Inputs/filelists/check-filelist-abc.py -emit-library ./a.swift ./b.swift ./c.swift -module-name main -target x86_64-apple-macosx10.9 -driver-use-filelists -output-file-map=%S/Inputs/filelists/output.json -force-single-frontend-invocation -num-threads 1 2>&1 | %FileCheck -check-prefix=CHECK-LINK %s) // CHECK-LINK: Handled link
apache-2.0
612c71f66210423a31957e97d2e1e169
77.425
397
0.722027
2.798394
false
false
true
false
niunaruto/DeDaoAppSwift
testSwift/Pods/RealmSwift/RealmSwift/Results.swift
6
17098
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // 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 Foundation import Realm // MARK: MinMaxType /** Types of properties which can be used with the minimum and maximum value APIs. - see: `min(ofProperty:)`, `max(ofProperty:)` */ public protocol MinMaxType {} extension NSNumber: MinMaxType {} extension Double: MinMaxType {} extension Float: MinMaxType {} extension Int: MinMaxType {} extension Int8: MinMaxType {} extension Int16: MinMaxType {} extension Int32: MinMaxType {} extension Int64: MinMaxType {} extension Date: MinMaxType {} extension NSDate: MinMaxType {} // MARK: AddableType /** Types of properties which can be used with the sum and average value APIs. - see: `sum(ofProperty:)`, `average(ofProperty:)` */ public protocol AddableType { /// :nodoc: init() } extension NSNumber: AddableType {} extension Double: AddableType {} extension Float: AddableType {} extension Int: AddableType {} extension Int8: AddableType {} extension Int16: AddableType {} extension Int32: AddableType {} extension Int64: AddableType {} /** `Results` is an auto-updating container type in Realm returned from object queries. `Results` can be queried with the same predicates as `List<Element>`, and you can chain queries to further filter query results. `Results` always reflect the current state of the Realm on the current thread, including during write transactions on the current thread. The one exception to this is when using `for...in` enumeration, which will always enumerate over the objects which matched the query when the enumeration is begun, even if some of them are deleted or modified to be excluded by the filter during the enumeration. `Results` are lazily evaluated the first time they are accessed; they only run queries when the result of the query is requested. This means that chaining several temporary `Results` to sort and filter your data does not perform any unnecessary work processing the intermediate state. Once the results have been evaluated or a notification block has been added, the results are eagerly kept up-to-date, with the work done to keep them up-to-date done on a background thread whenever possible. Results instances cannot be directly instantiated. */ public final class Results<Element: RealmCollectionValue>: NSObject, NSFastEnumeration { internal let rlmResults: RLMResults<AnyObject> /// A human-readable description of the objects represented by the results. public override var description: String { return RLMDescriptionWithMaxDepth("Results", rlmResults, RLMDescriptionMaxDepth) } // MARK: Fast Enumeration /// :nodoc: public func countByEnumerating(with state: UnsafeMutablePointer<NSFastEnumerationState>, objects buffer: AutoreleasingUnsafeMutablePointer<AnyObject?>, count len: Int) -> Int { return Int(rlmResults.countByEnumerating(with: state, objects: buffer, count: UInt(len))) } /// The type of the objects described by the results. public typealias ElementType = Element // MARK: Properties /// The Realm which manages this results. Note that this property will never return `nil`. public var realm: Realm? { return Realm(rlmResults.realm) } /** Indicates if the results are no longer valid. The results becomes invalid if `invalidate()` is called on the containing `realm`. An invalidated results can be accessed, but will always be empty. */ public var isInvalidated: Bool { return rlmResults.isInvalidated } /// The number of objects in the results. public var count: Int { return Int(rlmResults.count) } // MARK: Initializers internal init(_ rlmResults: RLMResults<AnyObject>) { self.rlmResults = rlmResults } // MARK: Index Retrieval /** Returns the index of the given object in the results, or `nil` if the object is not present. */ public func index(of object: Element) -> Int? { return notFoundToNil(index: rlmResults.index(of: object as AnyObject)) } /** Returns the index of the first object matching the predicate, or `nil` if no objects match. - parameter predicate: The predicate with which to filter the objects. */ public func index(matching predicate: NSPredicate) -> Int? { return notFoundToNil(index: rlmResults.indexOfObject(with: predicate)) } /** Returns the index of the first object matching the predicate, or `nil` if no objects match. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments. */ public func index(matching predicateFormat: String, _ args: Any...) -> Int? { return notFoundToNil(index: rlmResults.indexOfObject(with: NSPredicate(format: predicateFormat, argumentArray: unwrapOptionals(in: args)))) } // MARK: Object Retrieval /** Returns the object at the given `index`. - parameter index: The index. */ public subscript(position: Int) -> Element { throwForNegativeIndex(position) return dynamicBridgeCast(fromObjectiveC: rlmResults.object(at: UInt(position))) } /// Returns the first object in the results, or `nil` if the results are empty. public var first: Element? { return rlmResults.firstObject().map(dynamicBridgeCast) } /// Returns the last object in the results, or `nil` if the results are empty. public var last: Element? { return rlmResults.lastObject().map(dynamicBridgeCast) } // MARK: KVC /** Returns an `Array` containing the results of invoking `valueForKey(_:)` with `key` on each of the results. - parameter key: The name of the property whose values are desired. */ public override func value(forKey key: String) -> Any? { return value(forKeyPath: key) } /** Returns an `Array` containing the results of invoking `valueForKeyPath(_:)` with `keyPath` on each of the results. - parameter keyPath: The key path to the property whose values are desired. */ public override func value(forKeyPath keyPath: String) -> Any? { return rlmResults.value(forKeyPath: keyPath) } /** Invokes `setValue(_:forKey:)` on each of the objects represented by the results using the specified `value` and `key`. - warning: This method may only be called during a write transaction. - parameter value: The object value. - parameter key: The name of the property whose value should be set on each object. */ public override func setValue(_ value: Any?, forKey key: String) { return rlmResults.setValue(value, forKeyPath: key) } // MARK: Filtering /** Returns a `Results` containing all objects matching the given predicate in the collection. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments. */ public func filter(_ predicateFormat: String, _ args: Any...) -> Results<Element> { return Results<Element>(rlmResults.objects(with: NSPredicate(format: predicateFormat, argumentArray: unwrapOptionals(in: args)))) } /** Returns a `Results` containing all objects matching the given predicate in the collection. - parameter predicate: The predicate with which to filter the objects. */ public func filter(_ predicate: NSPredicate) -> Results<Element> { return Results<Element>(rlmResults.objects(with: predicate)) } // MARK: Sorting /** Returns a `Results` containing the objects represented by the results, but sorted. Objects are sorted based on the values of the given key path. For example, to sort a collection of `Student`s from youngest to oldest based on their `age` property, you might call `students.sorted(byKeyPath: "age", ascending: true)`. - warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision floating point, integer, and string types. - parameter keyPath: The key path to sort by. - parameter ascending: The direction to sort in. */ public func sorted(byKeyPath keyPath: String, ascending: Bool = true) -> Results<Element> { return sorted(by: [SortDescriptor(keyPath: keyPath, ascending: ascending)]) } /** Returns a `Results` containing the objects represented by the results, but sorted. - warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision floating point, integer, and string types. - see: `sorted(byKeyPath:ascending:)` - parameter sortDescriptors: A sequence of `SortDescriptor`s to sort by. */ public func sorted<S: Sequence>(by sortDescriptors: S) -> Results<Element> where S.Iterator.Element == SortDescriptor { return Results<Element>(rlmResults.sortedResults(using: sortDescriptors.map { $0.rlmSortDescriptorValue })) } /** Returns a `Results` containing distinct objects based on the specified key paths - parameter keyPaths: The key paths used produce distinct results */ public func distinct<S: Sequence>(by keyPaths: S) -> Results<Element> where S.Iterator.Element == String { return Results<Element>(rlmResults.distinctResults(usingKeyPaths: Array(keyPaths))) } // MARK: Aggregate Operations /** Returns the minimum (lowest) value of the given property among all the results, or `nil` if the results are empty. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified. - parameter property: The name of a property whose minimum value is desired. */ public func min<T: MinMaxType>(ofProperty property: String) -> T? { return rlmResults.min(ofProperty: property).map(dynamicBridgeCast) } /** Returns the maximum (highest) value of the given property among all the results, or `nil` if the results are empty. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified. - parameter property: The name of a property whose minimum value is desired. */ public func max<T: MinMaxType>(ofProperty property: String) -> T? { return rlmResults.max(ofProperty: property).map(dynamicBridgeCast) } /** Returns the sum of the values of a given property over all the results. - warning: Only a property whose type conforms to the `AddableType` protocol can be specified. - parameter property: The name of a property whose values should be summed. */ public func sum<T: AddableType>(ofProperty property: String) -> T { return dynamicBridgeCast(fromObjectiveC: rlmResults.sum(ofProperty: property)) } /** Returns the average value of a given property over all the results, or `nil` if the results are empty. - warning: Only the name of a property whose type conforms to the `AddableType` protocol can be specified. - parameter property: The name of a property whose average value should be calculated. */ public func average<T: AddableType>(ofProperty property: String) -> T? { return rlmResults.average(ofProperty: property).map(dynamicBridgeCast) } // MARK: Notifications /** Registers a block to be called each time the collection changes. The block will be asynchronously called with the initial results, and then called again after each write transaction which changes either any of the objects in the collection, or which objects are in the collection. The `change` parameter that is passed to the block reports, in the form of indices within the collection, which of the objects were added, removed, or modified during each write transaction. See the `RealmCollectionChange` documentation for more information on the change information supplied and an example of how to use it to update a `UITableView`. At the time when the block is called, the collection will be fully evaluated and up-to-date, and as long as you do not perform a write transaction on the same thread or explicitly call `realm.refresh()`, accessing it will never perform blocking work. Notifications are delivered via the standard run loop, and so can't be delivered while the run loop is blocked by other activity. When notifications can't be delivered instantly, multiple notifications may be coalesced into a single notification. This can include the notification with the initial collection. For example, the following code performs a write transaction immediately after adding the notification block, so there is no opportunity for the initial notification to be delivered first. As a result, the initial notification will reflect the state of the Realm after the write transaction. ```swift let dogs = realm.objects(Dog.self) print("dogs.count: \(dogs?.count)") // => 0 let token = dogs.observe { changes in switch changes { case .initial(let dogs): // Will print "dogs.count: 1" print("dogs.count: \(dogs.count)") break case .update: // Will not be hit in this example break case .error: break } } try! realm.write { let dog = Dog() dog.name = "Rex" person.dogs.append(dog) } // end of run loop execution context ``` You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving updates, call `invalidate()` on the token. - warning: This method cannot be called during a write transaction, or when the containing Realm is read-only. - parameter block: The block to be called whenever a change occurs. - returns: A token which must be held for as long as you want updates to be delivered. */ public func observe(_ block: @escaping (RealmCollectionChange<Results>) -> Void) -> NotificationToken { return rlmResults.addNotificationBlock { _, change, error in block(RealmCollectionChange.fromObjc(value: self, change: change, error: error)) } } } extension Results: RealmCollection { // MARK: Sequence Support /// Returns a `RLMIterator` that yields successive elements in the results. public func makeIterator() -> RLMIterator<Element> { return RLMIterator(collection: rlmResults) } // MARK: Collection Support /// The position of the first element in a non-empty collection. /// Identical to endIndex in an empty collection. 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 } public func index(after i: Int) -> Int { return i + 1 } public func index(before i: Int) -> Int { return i - 1 } /// :nodoc: public func _observe(_ block: @escaping (RealmCollectionChange<AnyRealmCollection<Element>>) -> Void) -> NotificationToken { let anyCollection = AnyRealmCollection(self) return rlmResults.addNotificationBlock { _, change, error in block(RealmCollectionChange.fromObjc(value: anyCollection, change: change, error: error)) } } } // MARK: AssistedObjectiveCBridgeable extension Results: AssistedObjectiveCBridgeable { static func bridging(from objectiveCValue: Any, with metadata: Any?) -> Results { return Results(objectiveCValue as! RLMResults) } var bridged: (objectiveCValue: Any, metadata: Any?) { return (objectiveCValue: rlmResults, metadata: nil) } } // MARK: - Codable #if swift(>=4.1) extension Results: Encodable where Element: Encodable { public func encode(to encoder: Encoder) throws { var container = encoder.unkeyedContainer() for value in self { try container.encode(value) } } } #endif
mit
92e8f11fba3125755fa89d2f4c99b111
38.487298
122
0.684583
4.930219
false
false
false
false
gogunskiy/The-Name
NameMe/Classes/Logic/Entities/NMNameItem.swift
1
964
// // NameEntity.swift // NameMe // // Created by Vladimir Gogunsky on 1/9/15. // Copyright (c) 2015 Volodymyr Hohunskyi. All rights reserved. // import Foundation import CoreData class NMNameItem : NSObject { var id : NSInteger? var name : NSString? var origin : NSString? var meaning : NSString? var notes : NSString? var rating : NSString? var recommended : NSString? var sex : NSString? init(item: NSManagedObject) { self.id = item.valueForKey("id")?.integerValue self.name = item.valueForKey("name") as? NSString self.origin = item.valueForKey("origin") as? NSString self.notes = item.valueForKey("notes") as? NSString self.rating = item.valueForKey("rating") as? NSString self.meaning = item.valueForKey("meaning") as? NSString self.recommended = item.valueForKey("recommended") as? NSString self.sex = item.valueForKey("sex") as? NSString } }
mit
43a0061ae5bb1421db9efa605176eaa4
28.242424
71
0.655602
4.05042
false
false
false
false
csujedihy/Flicks
MoviesViewer/AppDelegate.swift
1
3743
// // AppDelegate.swift // MoviesViewer // // Created by YiHuang on 1/22/16. // Copyright © 2016 c2fun. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. UITabBar.appearance().barTintColor = UIColor.blackColor() UITabBar.appearance().alpha = 0.8 UITabBar.appearance().translucent = true UIActivityIndicatorView.appearance().color = UIColor.whiteColor() window = UIWindow(frame: UIScreen.mainScreen().bounds) let storyboard = UIStoryboard(name: "Main", bundle: nil) let nowPlayingNavigationController = storyboard.instantiateViewControllerWithIdentifier("MoviesNavController") as! UINavigationController let nowPlayingViewController = nowPlayingNavigationController.topViewController as! MoviesViewController nowPlayingViewController.endpoint = "now_playing" nowPlayingNavigationController.tabBarItem.title = "Now Playing" nowPlayingNavigationController.tabBarItem.image = UIImage(named: "nowplaying") let topRatedNavigationController = storyboard.instantiateViewControllerWithIdentifier("MoviesNavController") as! UINavigationController let topRatedViewController = topRatedNavigationController.topViewController as! MoviesViewController topRatedViewController.endpoint = "top_rated" topRatedNavigationController.tabBarItem.title = "Top Rated" topRatedNavigationController.tabBarItem.image = UIImage(named: "toprated") let tabBarController = UITabBarController() tabBarController.viewControllers = [nowPlayingNavigationController, topRatedNavigationController] window?.rootViewController = tabBarController window?.makeKeyAndVisible() return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and 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:. } }
gpl-3.0
f858ceaa723da5e34ff72924e17dd43f
48.893333
285
0.747194
6.06483
false
false
false
false
mobgeek/swift
Swift em 4 Semanas/Playgrounds/Semana 3/4-Herança.playground/Contents.swift
2
2125
// Playground - noun: a place where people can play import UIKit // Herança class Veículo { var númeroRodas: Int var maxPassageiros: Int init() { númeroRodas = 0 maxPassageiros = 1 } func descrição() -> String { return "\(númeroRodas) rodas; até \(maxPassageiros) passageiros" } } let umVeículo = Veículo() class Bicicleta: Veículo { override init() { super.init() //A superClasse deve ser inicializada primeiro númeroRodas = 2 } } let bicicleta = Bicicleta() bicicleta.númeroRodas bicicleta.descrição() class Tandem: Bicicleta { override init() { super.init() maxPassageiros = 2 } } let tandem = Tandem() tandem.descrição() // Exemplo 5: class Carro: Veículo { var velocidade: Double = 0.0 override init() { super.init() maxPassageiros = 5 númeroRodas = 4 } override func descrição() -> String { return super.descrição() + ";" + "dirigindo a \(velocidade) km/h" } } let carro = Carro() carro.descrição() carro.velocidade = 80 carro.descrição() class CarroVelocidadeLimitada: Carro { override var velocidade: Double { get { return super.velocidade } set { super.velocidade = min(newValue, 80.0) } } } let carroLimitado = CarroVelocidadeLimitada() carroLimitado.velocidade = 120 carroLimitado.descrição() class CarroAutomático: Carro { var marcha = 1 override var velocidade: Double { didSet{ marcha = Int(velocidade / 16.0) + 1 } } override func descrição() -> String { return super.descrição() + " na marcha \(marcha)" } } let autoCar = CarroAutomático() autoCar.velocidade = 70 //Mude algum método de alguma superClasse acima para final, e veja como as subClasses dela não vão conseguir sobreescrever seus final method.
mit
8d5b5134abb6936da21837df64d9ddd4
12.640523
141
0.574509
3.235659
false
false
false
false
mobgeek/swift
Swift em 4 Semanas/App Lista/ListaData Solução 1/Lista/ListaTableViewController.swift
2
3962
// // ListaTableViewController.swift // Lista // // Created by Fabio Santos on 11/3/14. // Copyright (c) 2014 Fabio Santos. All rights reserved. // import UIKit class ListaTableViewController: UITableViewController,UITableViewDelegate, UITableViewDataSource { // MARK - Propriedades var itens: [ItemLista] = [] lazy var dateFormatter: NSDateFormatter = { let dateFormatter = NSDateFormatter() // Configure o estilo dateFormatter.dateStyle = .ShortStyle // Outros: NoStyle, ShortStyle, MediumStyle, FullStyle // Eventualmente: // dateFormatter.timeStyle = .ShortStyle // Cool Stuff: Hoje, Amanhã, etc.. // dateFormatter.doesRelativeDateFormatting = true // Alternativa: Há também a opção de criar formatos customizados...Para uma lista de especificadores consulte a documentação Data Formatting Guide: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html#//apple_ref/doc/uid/TP40002369-SW1 // dateFormatter.dateFormat = "'Criado em' dd/MM/yyyy 'às' HH:mm" // dateFormatter.dateFormat = "EEE, MMM d" // Estabeleça o Português como preferência. NSLocale dateFormatter.locale = NSLocale(localeIdentifier:"pt_BR") return dateFormatter } () // MARK - Helper Methods func carregarDadosIniciais() { var item1 = ItemLista(nome: "Comprar Maças") itens.append(item1) var item2 = ItemLista(nome: "Estudar Swift") itens.append(item2) var item3 = ItemLista(nome: "Ligar para o Banco") itens.append(item3) } // MARK: - View Controller Lifecycle override func viewDidLoad() { super.viewDidLoad() carregarDadosIniciais() } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return itens.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("ListaPrototypeCell", forIndexPath: indexPath)as! UITableViewCell // Configure the cell... var itemDaLista = itens[indexPath.row] cell.textLabel!.text = itemDaLista.nome cell.accessoryType = itemDaLista.concluido ? UITableViewCellAccessoryType.Checkmark :UITableViewCellAccessoryType.None cell.detailTextLabel?.text = dateFormatter.stringFromDate(itemDaLista.dataCriacao) // Passo 04 return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: false) var itemTocado = itens[indexPath.row] itemTocado.concluido = !itemTocado.concluido tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .None) } // MARK: - Navigation @IBAction func voltaParaLista(segue: UIStoryboardSegue!) { var sourceVC = segue.sourceViewController as! AdicionarItemViewController if let item = sourceVC.novoItemDaLista { itens.append(item) tableView.reloadData() } } }
mit
1e4700e5fef54447f9e54d30866c9229
28.259259
311
0.627848
5.143229
false
false
false
false
netgfx/BayesClassifier
Classifier.swift
1
6837
// // Classifier.swift import Foundation import SwiftyJSON class Classifier { var tokenizer: String = "" var vocabulary: Dictionary<String, Bool> = [:] var vocabularySize: Int = 0 var totalDocuments: Int = 0 var docCount: Dictionary<String, Int> = [:] var wordCount: Dictionary<String, Int> = [:] var wordFrequencyCount: Dictionary<String, Dictionary<String, Int>> = [:] var categories: Dictionary<String, Bool> = [:] var machineSuggestions<String, Array<String>> let STATE_KEYS = ["categories", "docCount", "totalDocuments", "vocabulary", "vocabularySize", "wordCount", "wordFrequencyCount", "options" ] internal init() {} func loadFromCache(_ theList: String) -> Void { let list = theList let data = list.base64Decoded().data(using: String.Encoding.utf8)! let values = JSON(data: data) self.categories = values["categories"].dictionaryObject as! Dictionary<String, Bool> self.docCount = values["docCount"].dictionaryObject as! Dictionary<String, Int> self.totalDocuments = values["totalDocuments"].intValue self.vocabulary = values["vocabulary"].dictionaryObject as! Dictionary<String, Bool> self.vocabularySize = values["vocabularySize"].intValue self.wordCount = values["wordCount"].dictionaryObject as! Dictionary<String, Int> self.wordFrequencyCount = values["wordFrequencyCount"].dictionaryObject as! Dictionary<String, Dictionary<String, Int>> if values["machineSuggestions"] != nil { self.machineSuggestions = values["machineSuggestions"].dictionaryObject as! Dictionary<String, Array<String>> } } func defaultTokenizer(_ text: String) -> Array<String> { let okayChars: Set<Character> = Set("abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLKMNOPQRSTUVWXYZ1234567890+-*=(),.:!_".characters) let str = String(text.characters.filter { okayChars.contains($0) }) let charset = CharacterSet.whitespaces let splitted = str.characters.split(whereSeparator: { [",", "[", "]", "\n", "\r", ".", "!", ":", "?", ":", "@", "#"].contains($0) }) let trimmed = splitted.map { String($0).trimmingCharacters(in: charset) } return trimmed } func Naivebayes(_ options: Dictionary<String, String>) { if options.count == 0 { print("error no options") } } func initializeCategory(_ categoryName: String) { if self.categories[categoryName] == nil { self.docCount[categoryName] = 0 self.wordCount[categoryName] = 0 self.wordFrequencyCount[categoryName] = [:] categories[categoryName] = true } } func learn(_ text: String, category: String) { self.initializeCategory(category) self.docCount[category] = self.docCount[category]! + 1 self.totalDocuments += 1 let tokens = self.defaultTokenizer(text) let frequencyTable = self.frequencyTable(tokens) for (item, _) in frequencyTable { if self.vocabulary[item] == nil { self.vocabulary[item] = true self.vocabularySize = self.vocabularySize + 1 } let frequencyInText: Int = frequencyTable[item]! if self.wordFrequencyCount[category]![item] == nil { self.wordFrequencyCount[category]![item] = frequencyInText } else { self.wordFrequencyCount[category]![item] = self.wordFrequencyCount[category]![item]! + frequencyInText } self.wordCount[category] = self.wordCount[category]! + frequencyInText } self.machineSuggestions[category] = tokens } /** teach the machine a series of names and criteria, and categorize them by alphabetical hash of the names (strings) - parameter text, the stringified names and criteria - parameter category, the alphabetically sorted hash (md5) to categorize the text with - return Void, nothing */ func learnHash(_ text: String, category: Array<String>) -> Void { var hash = "" hash = Utils.sortAndHash(category) self.learn(text, category: hash) } func categorize(_ text: String) -> String { var maxProbability = -Float.infinity var chosenCategory = "" let tokens = self.defaultTokenizer(text) var _frequencyTable = self.frequencyTable(tokens) for (item, _) in self.categories { let firstPart: Float = Float(self.docCount[item]!) let secondPart: Float = Float(self.totalDocuments) let categoryProbability: Float = Float(firstPart / secondPart) var logProbability = log(categoryProbability) for (token, _) in _frequencyTable { let frequencyInText: Float = Float(_frequencyTable[token]!) let tokenProbability: Float = self.tokenProbability(token, category: item) logProbability = logProbability + (frequencyInText * log(tokenProbability)) } if logProbability > maxProbability { maxProbability = logProbability chosenCategory = item } } return chosenCategory } func tokenProbability(_ token: String, category: String) -> Float { var wordFrequencyCount: Int! if let test = self.wordFrequencyCount[category]![token] { } if self.wordFrequencyCount[category]![token] != nil { wordFrequencyCount = self.wordFrequencyCount[category]![token]! } else { wordFrequencyCount = 0 } let wordCount = self.wordCount[category] let firstPart: Float = Float(wordFrequencyCount + 1) let secondPart: Float = Float(wordCount! + self.vocabularySize) let test2: Float = Float(firstPart / secondPart) if (wordCount! + self.vocabularySize) != 0 { print(wordFrequencyCount!, wordCount!, self.vocabularySize, (wordFrequencyCount! + 1) / (wordCount! + self.vocabularySize)) } return test2 } func frequencyTable(_ tokens: Array<String>) -> Dictionary<String, Int> { var frequencyTable: Dictionary<String, Int> = [:] for key in tokens { if frequencyTable[key] == nil { frequencyTable[key] = 1 } else { frequencyTable[key] = frequencyTable[key]! + 1 } } return frequencyTable } func excludeKeysFromResults(_ key:String, arr:Array<String>) -> Array<String> { var results:Array<String> = arr let keysArr = key.components(separatedBy: ",") for item in keysArr { let index = results.index(of: item) if index != nil { results.remove(at: index!) } } return results } func saveTokens() -> String { let _json: JSON = JSON([ "categories": self.categories, "docCount": self.docCount, "totalDocuments": self.totalDocuments, "vocabulary": self.vocabulary, "vocabularySize": self.vocabularySize, "wordCount": self.wordCount, "wordFrequencyCount": self.wordFrequencyCount, "machineSuggestions": DataStorage.machineSuggestions ]) return (_json.rawString(String.Encoding(rawValue: String.Encoding.utf8.rawValue), options: JSONSerialization.WritingOptions(rawValue: 0))?.base64Encoded())! } /** Return the results */ public func getMachineSuggestions() -> Dictionary<String, Array<String>> { return self.machineSuggestions } }
mit
c155a933ac3bc8ad174432769a92a631
31.870192
158
0.697674
3.769019
false
false
false
false
yyny1789/KrMediumKit
Source/Utils/Extensions/UIImage+Extension.swift
1
3463
import UIKit public extension UIImage { public convenience init(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) { let rect = CGRect(origin: CGPoint.zero, size: size) UIGraphicsBeginImageContextWithOptions(size, true, 1) color.setFill() UIRectFill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() self.init(cgImage: (image?.cgImage)!) } public var hasContent: Bool { return cgImage != nil || ciImage != nil } public func fixOrientation() -> UIImage? { if imageOrientation == UIImageOrientation.up { return self } var transform = CGAffineTransform.identity switch imageOrientation { case UIImageOrientation.down: fallthrough case UIImageOrientation.downMirrored: transform = transform.translatedBy(x: size.width, y: size.height) transform = transform.rotated(by: CGFloat(Double.pi)) case UIImageOrientation.left: fallthrough case UIImageOrientation.leftMirrored: transform = transform.translatedBy(x: size.width, y: 0) transform = transform.rotated(by: CGFloat(Double.pi / 2)) case UIImageOrientation.right: fallthrough case UIImageOrientation.rightMirrored: transform = transform.translatedBy(x: 0, y: size.height) transform = transform.rotated(by: CGFloat(-Double.pi / 2)) case UIImageOrientation.up: fallthrough case UIImageOrientation.upMirrored: fallthrough default: () } switch imageOrientation { case UIImageOrientation.upMirrored: fallthrough case UIImageOrientation.downMirrored: transform = transform.translatedBy(x: size.width, y: 0) transform = transform.scaledBy(x: -1, y: 1) case UIImageOrientation.leftMirrored: fallthrough case UIImageOrientation.rightMirrored: transform = transform.translatedBy(x: size.height, y: 0) transform = transform.scaledBy(x: -1, y: 1) case UIImageOrientation.up: fallthrough case UIImageOrientation.down: fallthrough case UIImageOrientation.left: fallthrough case UIImageOrientation.right: fallthrough default: () } let ctx = CGContext(data: nil, width: Int(size.width), height: Int(size.height), bitsPerComponent: ((self.cgImage)?.bitsPerComponent)!, bytesPerRow: 0, space: ((self.cgImage)?.colorSpace)!, bitmapInfo: ((self.cgImage)?.bitmapInfo.rawValue)!) ctx?.concatenate(transform) switch imageOrientation { case UIImageOrientation.left: fallthrough case UIImageOrientation.leftMirrored: fallthrough case UIImageOrientation.right: fallthrough case UIImageOrientation.rightMirrored: ctx?.draw(self.cgImage!, in: CGRect(x: 0, y: 0, width: size.height, height: size.width)) default: ctx?.draw(self.cgImage!, in: CGRect(x: 0, y: 0, width: size.width, height: size.height)) } if let cgImage = ctx?.makeImage() { return UIImage(cgImage: cgImage) } return nil } }
mit
bd593eaf4b2c9098259731c637f252b4
35.452632
249
0.606699
5.368992
false
false
false
false
NickAger/elm-slider
ServerSlider/WebSocketServer/Packages/Axis-0.14.0/Tests/AxisTests/Map/MapTests.swift
3
36632
import XCTest @testable import Axis public class MapTests : XCTestCase { func testCreation() { let nullValue: Bool? = nil let null = Map(nullValue) XCTAssertEqual(null, nil) XCTAssertEqual(null, .null) XCTAssert(null.isNull) XCTAssertFalse(null.isBool) XCTAssertFalse(null.isDouble) XCTAssertFalse(null.isInt) XCTAssertFalse(null.isString) XCTAssertFalse(null.isBuffer) XCTAssertFalse(null.isArray) XCTAssertFalse(null.isDictionary) XCTAssertNil(null.bool) XCTAssertNil(null.double) XCTAssertNil(null.int) XCTAssertNil(null.string) XCTAssertNil(null.buffer) XCTAssertNil(null.array) XCTAssertNil(null.dictionary) XCTAssertThrowsError(try null.asBool()) XCTAssertThrowsError(try null.asDouble()) XCTAssertThrowsError(try null.asInt()) XCTAssertThrowsError(try null.asString()) XCTAssertThrowsError(try null.asBuffer()) XCTAssertThrowsError(try null.asArray()) XCTAssertThrowsError(try null.asDictionary()) let nullArrayValue: [Bool]? = nil let nullArray = Map(nullArrayValue) XCTAssertEqual(nullArray, nil) XCTAssertEqual(nullArray, .null) XCTAssert(nullArray.isNull) XCTAssertFalse(nullArray.isBool) XCTAssertFalse(nullArray.isDouble) XCTAssertFalse(nullArray.isInt) XCTAssertFalse(nullArray.isString) XCTAssertFalse(nullArray.isBuffer) XCTAssertFalse(nullArray.isArray) XCTAssertFalse(nullArray.isDictionary) XCTAssertNil(nullArray.bool) XCTAssertNil(nullArray.double) XCTAssertNil(nullArray.int) XCTAssertNil(nullArray.string) XCTAssertNil(nullArray.buffer) XCTAssertNil(nullArray.array) XCTAssertNil(nullArray.dictionary) XCTAssertThrowsError(try null.asBool()) XCTAssertThrowsError(try null.asDouble()) XCTAssertThrowsError(try null.asInt()) XCTAssertThrowsError(try null.asString()) XCTAssertThrowsError(try null.asBuffer()) XCTAssertThrowsError(try null.asArray()) XCTAssertThrowsError(try null.asDictionary()) let nullArrayOfNullValue: [Bool?]? = nil let nullArrayOfNull = Map(nullArrayOfNullValue) XCTAssertEqual(nullArrayOfNull, nil) XCTAssertEqual(nullArrayOfNull, .null) XCTAssert(nullArrayOfNull.isNull) XCTAssertFalse(nullArrayOfNull.isBool) XCTAssertFalse(nullArrayOfNull.isDouble) XCTAssertFalse(nullArrayOfNull.isInt) XCTAssertFalse(nullArrayOfNull.isString) XCTAssertFalse(nullArrayOfNull.isBuffer) XCTAssertFalse(nullArrayOfNull.isArray) XCTAssertFalse(nullArrayOfNull.isDictionary) XCTAssertNil(nullArrayOfNull.bool) XCTAssertNil(nullArrayOfNull.double) XCTAssertNil(nullArrayOfNull.int) XCTAssertNil(nullArrayOfNull.string) XCTAssertNil(nullArrayOfNull.buffer) XCTAssertNil(nullArrayOfNull.array) XCTAssertNil(nullArrayOfNull.dictionary) XCTAssertThrowsError(try null.asBool()) XCTAssertThrowsError(try null.asDouble()) XCTAssertThrowsError(try null.asInt()) XCTAssertThrowsError(try null.asString()) XCTAssertThrowsError(try null.asBuffer()) XCTAssertThrowsError(try null.asArray()) XCTAssertThrowsError(try null.asDictionary()) let nullDictionaryValue: [String: Bool]? = nil let nullDictionary = Map(nullDictionaryValue) XCTAssertEqual(nullDictionary, nil) XCTAssertEqual(nullDictionary, .null) XCTAssert(nullDictionary.isNull) XCTAssertFalse(nullDictionary.isBool) XCTAssertFalse(nullDictionary.isDouble) XCTAssertFalse(nullDictionary.isInt) XCTAssertFalse(nullDictionary.isString) XCTAssertFalse(nullDictionary.isBuffer) XCTAssertFalse(nullDictionary.isArray) XCTAssertFalse(nullDictionary.isDictionary) XCTAssertNil(nullDictionary.bool) XCTAssertNil(nullDictionary.double) XCTAssertNil(nullDictionary.int) XCTAssertNil(nullDictionary.string) XCTAssertNil(nullDictionary.buffer) XCTAssertNil(nullDictionary.array) XCTAssertNil(nullDictionary.dictionary) XCTAssertThrowsError(try null.asBool()) XCTAssertThrowsError(try null.asDouble()) XCTAssertThrowsError(try null.asInt()) XCTAssertThrowsError(try null.asString()) XCTAssertThrowsError(try null.asBuffer()) XCTAssertThrowsError(try null.asArray()) XCTAssertThrowsError(try null.asDictionary()) let nullDictionaryOfNullValue: [String: Bool?]? = nil let nullDictionaryOfNull = Map(nullDictionaryOfNullValue) XCTAssertEqual(nullDictionaryOfNull, nil) XCTAssertEqual(nullDictionaryOfNull, .null) XCTAssert(nullDictionaryOfNull.isNull) XCTAssertFalse(nullDictionaryOfNull.isBool) XCTAssertFalse(nullDictionaryOfNull.isDouble) XCTAssertFalse(nullDictionaryOfNull.isInt) XCTAssertFalse(nullDictionaryOfNull.isString) XCTAssertFalse(nullDictionaryOfNull.isBuffer) XCTAssertFalse(nullDictionaryOfNull.isArray) XCTAssertFalse(nullDictionaryOfNull.isDictionary) XCTAssertNil(nullDictionaryOfNull.bool) XCTAssertNil(nullDictionaryOfNull.double) XCTAssertNil(nullDictionaryOfNull.int) XCTAssertNil(nullDictionaryOfNull.string) XCTAssertNil(nullDictionaryOfNull.buffer) XCTAssertNil(nullDictionaryOfNull.array) XCTAssertNil(nullDictionaryOfNull.dictionary) XCTAssertThrowsError(try null.asBool()) XCTAssertThrowsError(try null.asDouble()) XCTAssertThrowsError(try null.asInt()) XCTAssertThrowsError(try null.asString()) XCTAssertThrowsError(try null.asBuffer()) XCTAssertThrowsError(try null.asArray()) XCTAssertThrowsError(try null.asDictionary()) let boolValue = true let bool = Map(boolValue) XCTAssertEqual(bool, true) XCTAssertEqual(bool, .bool(boolValue)) XCTAssertFalse(bool.isNull) XCTAssert(bool.isBool) XCTAssertFalse(bool.isDouble) XCTAssertFalse(bool.isInt) XCTAssertFalse(bool.isString) XCTAssertFalse(bool.isBuffer) XCTAssertFalse(bool.isArray) XCTAssertFalse(bool.isDictionary) XCTAssertEqual(bool.bool, boolValue) XCTAssertNil(bool.double) XCTAssertNil(bool.int) XCTAssertNil(bool.string) XCTAssertNil(bool.buffer) XCTAssertNil(bool.array) XCTAssertNil(bool.dictionary) XCTAssertEqual(try bool.asBool(), boolValue) XCTAssertThrowsError(try bool.asDouble()) XCTAssertThrowsError(try bool.asInt()) XCTAssertThrowsError(try bool.asString()) XCTAssertThrowsError(try bool.asBuffer()) XCTAssertThrowsError(try bool.asArray()) XCTAssertThrowsError(try bool.asDictionary()) let doubleValue = 4.20 let double = Map(doubleValue) XCTAssertEqual(double, 4.20) XCTAssertEqual(double, .double(doubleValue)) XCTAssertFalse(double.isNull) XCTAssertFalse(double.isBool) XCTAssert(double.isDouble) XCTAssertFalse(double.isInt) XCTAssertFalse(double.isString) XCTAssertFalse(double.isBuffer) XCTAssertFalse(double.isArray) XCTAssertFalse(double.isDictionary) XCTAssertNil(double.bool) XCTAssertEqual(double.double, doubleValue) XCTAssertNil(double.int) XCTAssertNil(double.string) XCTAssertNil(double.buffer) XCTAssertNil(double.array) XCTAssertNil(double.dictionary) XCTAssertThrowsError(try double.asBool()) XCTAssertEqual(try double.asDouble(), doubleValue) XCTAssertThrowsError(try double.asInt()) XCTAssertThrowsError(try double.asString()) XCTAssertThrowsError(try double.asBuffer()) XCTAssertThrowsError(try double.asArray()) XCTAssertThrowsError(try double.asDictionary()) let intValue = 1969 let int = Map(intValue) XCTAssertEqual(int, 1969) XCTAssertEqual(int, .int(intValue)) XCTAssertFalse(int.isNull) XCTAssertFalse(int.isBool) XCTAssertFalse(int.isDouble) XCTAssert(int.isInt) XCTAssertFalse(int.isString) XCTAssertFalse(int.isBuffer) XCTAssertFalse(int.isArray) XCTAssertFalse(int.isDictionary) XCTAssertNil(int.bool) XCTAssertNil(int.double) XCTAssertEqual(int.int, intValue) XCTAssertNil(int.string) XCTAssertNil(int.buffer) XCTAssertNil(int.array) XCTAssertNil(int.dictionary) XCTAssertThrowsError(try null.asBool()) XCTAssertThrowsError(try null.asDouble()) XCTAssertEqual(try int.asInt(), intValue) XCTAssertThrowsError(try null.asString()) XCTAssertThrowsError(try null.asBuffer()) XCTAssertThrowsError(try null.asArray()) XCTAssertThrowsError(try null.asDictionary()) let stringValue = "foo" let string = Map(stringValue) XCTAssertEqual(string, "foo") XCTAssertEqual(string, .string(stringValue)) XCTAssertFalse(string.isNull) XCTAssertFalse(string.isBool) XCTAssertFalse(string.isDouble) XCTAssertFalse(string.isInt) XCTAssert(string.isString) XCTAssertFalse(string.isBuffer) XCTAssertFalse(string.isArray) XCTAssertFalse(string.isDictionary) XCTAssertNil(string.bool) XCTAssertNil(string.double) XCTAssertNil(string.int) XCTAssertEqual(string.string, stringValue) XCTAssertNil(string.buffer) XCTAssertNil(string.array) XCTAssertNil(string.dictionary) XCTAssertThrowsError(try string.asBool()) XCTAssertThrowsError(try string.asDouble()) XCTAssertThrowsError(try string.asInt()) XCTAssertEqual(try string.asString(), stringValue) XCTAssertThrowsError(try string.asBuffer()) XCTAssertThrowsError(try string.asArray()) XCTAssertThrowsError(try string.asDictionary()) let bufferValue = Buffer("foo") let buffer = Map(bufferValue) XCTAssertEqual(buffer, .buffer(bufferValue)) XCTAssertFalse(buffer.isNull) XCTAssertFalse(buffer.isBool) XCTAssertFalse(buffer.isDouble) XCTAssertFalse(buffer.isInt) XCTAssertFalse(buffer.isString) XCTAssert(buffer.isBuffer) XCTAssertFalse(buffer.isArray) XCTAssertFalse(buffer.isDictionary) XCTAssertNil(buffer.bool) XCTAssertNil(buffer.double) XCTAssertNil(buffer.int) XCTAssertNil(buffer.string) XCTAssertEqual(buffer.buffer, bufferValue) XCTAssertNil(buffer.array) XCTAssertNil(buffer.dictionary) XCTAssertThrowsError(try buffer.asBool()) XCTAssertThrowsError(try buffer.asDouble()) XCTAssertThrowsError(try buffer.asInt()) XCTAssertThrowsError(try buffer.asString()) XCTAssertEqual(try buffer.asBuffer(), bufferValue) XCTAssertThrowsError(try buffer.asArray()) XCTAssertThrowsError(try buffer.asDictionary()) let arrayValue = 1969 let array = Map([arrayValue]) XCTAssertEqual(array, [1969]) XCTAssertEqual(array, .array([.int(arrayValue)])) XCTAssertFalse(array.isNull) XCTAssertFalse(array.isBool) XCTAssertFalse(array.isDouble) XCTAssertFalse(array.isInt) XCTAssertFalse(array.isString) XCTAssertFalse(array.isBuffer) XCTAssert(array.isArray) XCTAssertFalse(array.isDictionary) XCTAssertNil(array.bool) XCTAssertNil(array.double) XCTAssertNil(array.int) XCTAssertNil(array.string) XCTAssertNil(array.buffer) if let a = array.array { XCTAssertEqual(a, [.int(arrayValue)]) } else { XCTAssertNotNil(array.array) } XCTAssertNil(array.dictionary) XCTAssertThrowsError(try array.asBool()) XCTAssertThrowsError(try array.asDouble()) XCTAssertThrowsError(try array.asInt()) XCTAssertThrowsError(try array.asString()) XCTAssertThrowsError(try array.asBuffer()) XCTAssertEqual(try array.asArray(), [.int(arrayValue)]) XCTAssertThrowsError(try array.asDictionary()) let arrayOfOptionalValue: Int? = arrayValue let arrayOfOptional = Map([arrayOfOptionalValue]) XCTAssertEqual(arrayOfOptional, [1969]) XCTAssertEqual(arrayOfOptional, .array([.int(arrayValue)])) XCTAssertFalse(arrayOfOptional.isNull) XCTAssertFalse(arrayOfOptional.isBool) XCTAssertFalse(arrayOfOptional.isDouble) XCTAssertFalse(arrayOfOptional.isInt) XCTAssertFalse(arrayOfOptional.isString) XCTAssertFalse(arrayOfOptional.isBuffer) XCTAssert(arrayOfOptional.isArray) XCTAssertFalse(arrayOfOptional.isDictionary) XCTAssertNil(arrayOfOptional.bool) XCTAssertNil(arrayOfOptional.double) XCTAssertNil(arrayOfOptional.int) XCTAssertNil(arrayOfOptional.string) XCTAssertNil(arrayOfOptional.buffer) if let a = arrayOfOptional.array { XCTAssertEqual(a, [.int(arrayValue)]) } else { XCTAssertNotNil(arrayOfOptional.array) } XCTAssertNil(arrayOfOptional.dictionary) XCTAssertThrowsError(try arrayOfOptional.asBool()) XCTAssertThrowsError(try arrayOfOptional.asDouble()) XCTAssertThrowsError(try arrayOfOptional.asInt()) XCTAssertThrowsError(try arrayOfOptional.asString()) XCTAssertThrowsError(try arrayOfOptional.asBuffer()) XCTAssertEqual(try arrayOfOptional.asArray(), [.int(arrayValue)]) XCTAssertThrowsError(try arrayOfOptional.asDictionary()) let arrayOfNullValue: Int? = nil let arrayOfNull = Map([arrayOfNullValue]) XCTAssertEqual(arrayOfNull, [nil]) XCTAssertEqual(arrayOfNull, .array([.null])) XCTAssertFalse(arrayOfNull.isNull) XCTAssertFalse(arrayOfNull.isBool) XCTAssertFalse(arrayOfNull.isDouble) XCTAssertFalse(arrayOfNull.isInt) XCTAssertFalse(arrayOfNull.isString) XCTAssertFalse(arrayOfNull.isBuffer) XCTAssert(arrayOfNull.isArray) XCTAssertFalse(arrayOfNull.isDictionary) XCTAssertNil(arrayOfNull.bool) XCTAssertNil(arrayOfNull.double) XCTAssertNil(arrayOfNull.int) XCTAssertNil(arrayOfNull.string) XCTAssertNil(arrayOfNull.buffer) if let a = arrayOfNull.array { XCTAssertEqual(a, [.null]) } else { XCTAssertNotNil(arrayOfNull.array) } XCTAssertNil(arrayOfNull.dictionary) XCTAssertThrowsError(try arrayOfNull.asBool()) XCTAssertThrowsError(try arrayOfNull.asDouble()) XCTAssertThrowsError(try arrayOfNull.asInt()) XCTAssertThrowsError(try arrayOfNull.asString()) XCTAssertThrowsError(try arrayOfNull.asBuffer()) XCTAssertEqual(try arrayOfNull.asArray(), [.null]) XCTAssertThrowsError(try arrayOfNull.asDictionary()) let dictionaryValue = 1969 let dictionary = Map(["foo": dictionaryValue]) XCTAssertEqual(dictionary, ["foo": 1969]) XCTAssertEqual(dictionary, .dictionary(["foo": .int(dictionaryValue)])) XCTAssertFalse(dictionary.isNull) XCTAssertFalse(dictionary.isBool) XCTAssertFalse(dictionary.isDouble) XCTAssertFalse(dictionary.isInt) XCTAssertFalse(dictionary.isString) XCTAssertFalse(dictionary.isBuffer) XCTAssertFalse(dictionary.isArray) XCTAssert(dictionary.isDictionary) XCTAssertNil(dictionary.bool) XCTAssertNil(dictionary.double) XCTAssertNil(dictionary.int) XCTAssertNil(dictionary.string) XCTAssertNil(dictionary.buffer) XCTAssertNil(dictionary.array) if let d = dictionary.dictionary { XCTAssertEqual(d, ["foo": .int(dictionaryValue)]) } else { XCTAssertNotNil(dictionary.dictionary) } XCTAssertThrowsError(try dictionary.asBool()) XCTAssertThrowsError(try dictionary.asDouble()) XCTAssertThrowsError(try dictionary.asInt()) XCTAssertThrowsError(try dictionary.asString()) XCTAssertThrowsError(try dictionary.asBuffer()) XCTAssertThrowsError(try dictionary.asArray()) XCTAssertEqual(try dictionary.asDictionary(), ["foo": .int(dictionaryValue)]) let dictionaryOfOptionalValue: Int? = dictionaryValue let dictionaryOfOptional = Map(["foo": dictionaryOfOptionalValue]) XCTAssertEqual(dictionaryOfOptional, ["foo": 1969]) XCTAssertEqual(dictionaryOfOptional, .dictionary(["foo": .int(dictionaryValue)])) XCTAssertFalse(dictionaryOfOptional.isNull) XCTAssertFalse(dictionaryOfOptional.isBool) XCTAssertFalse(dictionaryOfOptional.isDouble) XCTAssertFalse(dictionaryOfOptional.isInt) XCTAssertFalse(dictionaryOfOptional.isString) XCTAssertFalse(dictionaryOfOptional.isBuffer) XCTAssertFalse(dictionaryOfOptional.isArray) XCTAssert(dictionaryOfOptional.isDictionary) XCTAssertNil(dictionaryOfOptional.bool) XCTAssertNil(dictionaryOfOptional.double) XCTAssertNil(dictionaryOfOptional.int) XCTAssertNil(dictionaryOfOptional.string) XCTAssertNil(dictionaryOfOptional.buffer) XCTAssertNil(dictionaryOfOptional.array) if let d = dictionaryOfOptional.dictionary { XCTAssertEqual(d, ["foo": .int(dictionaryValue)]) } else { XCTAssertNotNil(dictionaryOfOptional.dictionary) } XCTAssertThrowsError(try dictionaryOfOptional.asBool()) XCTAssertThrowsError(try dictionaryOfOptional.asDouble()) XCTAssertThrowsError(try dictionaryOfOptional.asInt()) XCTAssertThrowsError(try dictionaryOfOptional.asString()) XCTAssertThrowsError(try dictionaryOfOptional.asBuffer()) XCTAssertThrowsError(try dictionaryOfOptional.asArray()) XCTAssertEqual(try dictionaryOfOptional.asDictionary(), ["foo": .int(dictionaryValue)]) let dictionaryOfNullValue: Int? = nil let dictionaryOfNull = Map(["foo": dictionaryOfNullValue]) XCTAssertEqual(dictionaryOfNull, ["foo": nil]) XCTAssertEqual(dictionaryOfNull, .dictionary(["foo": .null])) XCTAssertFalse(dictionaryOfNull.isNull) XCTAssertFalse(dictionaryOfNull.isBool) XCTAssertFalse(dictionaryOfNull.isDouble) XCTAssertFalse(dictionaryOfNull.isInt) XCTAssertFalse(dictionaryOfNull.isString) XCTAssertFalse(dictionaryOfNull.isBuffer) XCTAssertFalse(dictionaryOfNull.isArray) XCTAssert(dictionaryOfNull.isDictionary) XCTAssertNil(dictionaryOfNull.bool) XCTAssertNil(dictionaryOfNull.double) XCTAssertNil(dictionaryOfNull.int) XCTAssertNil(dictionaryOfNull.string) XCTAssertNil(dictionaryOfNull.buffer) XCTAssertNil(dictionaryOfNull.array) if let d = dictionaryOfNull.dictionary { XCTAssertEqual(d, ["foo": .null]) } else { XCTAssertNotNil(dictionaryOfNull.dictionary) } XCTAssertThrowsError(try dictionaryOfNull.asBool()) XCTAssertThrowsError(try dictionaryOfNull.asDouble()) XCTAssertThrowsError(try dictionaryOfNull.asInt()) XCTAssertThrowsError(try dictionaryOfNull.asString()) XCTAssertThrowsError(try dictionaryOfNull.asBuffer()) XCTAssertThrowsError(try dictionaryOfNull.asArray()) XCTAssertEqual(try dictionaryOfNull.asDictionary(), ["foo": .null]) } func testConversion() { let null: Map = nil XCTAssertEqual(try null.asBool(converting: true), false) XCTAssertEqual(try null.asDouble(converting: true), 0) XCTAssertEqual(try null.asInt(converting: true), 0) XCTAssertEqual(try null.asString(converting: true), "null") XCTAssertEqual(try null.asBuffer(converting: true), Buffer()) XCTAssertEqual(try null.asArray(converting: true), []) XCTAssertEqual(try null.asDictionary(converting: true), [:]) let `true`: Map = true XCTAssertEqual(try `true`.asBool(converting: true), true) XCTAssertEqual(try `true`.asDouble(converting: true), 1.0) XCTAssertEqual(try `true`.asInt(converting: true), 1) XCTAssertEqual(try `true`.asString(converting: true), "true") XCTAssertEqual(try `true`.asBuffer(converting: true), Buffer([0xff])) XCTAssertThrowsError(try `true`.asArray(converting: true)) XCTAssertThrowsError(try `true`.asDictionary(converting: true)) let `false`: Map = false XCTAssertEqual(try `false`.asBool(converting: true), false) XCTAssertEqual(try `false`.asDouble(converting: true), 0.0) XCTAssertEqual(try `false`.asInt(converting: true), 0) XCTAssertEqual(try `false`.asString(converting: true), "false") XCTAssertEqual(try `false`.asBuffer(converting: true), Buffer([0x00])) XCTAssertThrowsError(try `false`.asArray(converting: true)) XCTAssertThrowsError(try `false`.asDictionary(converting: true)) let double: Map = 4.20 XCTAssertEqual(try double.asBool(converting: true), true) XCTAssertEqual(try double.asDouble(converting: true), 4.20) XCTAssertEqual(try double.asInt(converting: true), 4) XCTAssertEqual(try double.asString(converting: true), "4.2") XCTAssertThrowsError(try double.asBuffer(converting: true)) XCTAssertThrowsError(try double.asArray(converting: true)) XCTAssertThrowsError(try double.asDictionary(converting: true)) let doubleZero: Map = 0.0 XCTAssertEqual(try doubleZero.asBool(converting: true), false) XCTAssertEqual(try doubleZero.asDouble(converting: true), 0.0) XCTAssertEqual(try doubleZero.asInt(converting: true), 0) XCTAssertEqual(try doubleZero.asString(converting: true), "0.0") XCTAssertThrowsError(try doubleZero.asBuffer(converting: true)) XCTAssertThrowsError(try doubleZero.asArray(converting: true)) XCTAssertThrowsError(try doubleZero.asDictionary(converting: true)) let int: Map = 1969 XCTAssertEqual(try int.asBool(converting: true), true) XCTAssertEqual(try int.asDouble(converting: true), 1969.0) XCTAssertEqual(try int.asInt(converting: true), 1969) XCTAssertEqual(try int.asString(converting: true), "1969") XCTAssertThrowsError(try int.asBuffer(converting: true)) XCTAssertThrowsError(try int.asArray(converting: true)) XCTAssertThrowsError(try int.asDictionary(converting: true)) let intZero: Map = 0 XCTAssertEqual(try intZero.asBool(converting: true), false) XCTAssertEqual(try intZero.asDouble(converting: true), 0.0) XCTAssertEqual(try intZero.asInt(converting: true), 0) XCTAssertEqual(try intZero.asString(converting: true), "0") XCTAssertThrowsError(try intZero.asBuffer(converting: true)) XCTAssertThrowsError(try intZero.asArray(converting: true)) XCTAssertThrowsError(try intZero.asDictionary(converting: true)) let string: Map = "foo" XCTAssertThrowsError(try string.asBool(converting: true)) XCTAssertThrowsError(try string.asDouble(converting: true)) XCTAssertThrowsError(try string.asInt(converting: true)) XCTAssertEqual(try string.asString(converting: true), "foo") XCTAssertEqual(try string.asBuffer(converting: true), Buffer("foo")) XCTAssertThrowsError(try string.asArray(converting: true)) XCTAssertThrowsError(try string.asDictionary(converting: true)) let stringTrue: Map = "TRUE" XCTAssertEqual(try stringTrue.asBool(converting: true), true) XCTAssertThrowsError(try stringTrue.asDouble(converting: true)) XCTAssertThrowsError(try stringTrue.asInt(converting: true)) XCTAssertEqual(try stringTrue.asString(converting: true), "TRUE") XCTAssertEqual(try stringTrue.asBuffer(converting: true), Buffer("TRUE")) XCTAssertThrowsError(try stringTrue.asArray(converting: true)) XCTAssertThrowsError(try stringTrue.asDictionary(converting: true)) let stringFalse: Map = "FALSE" XCTAssertEqual(try stringFalse.asBool(converting: true), false) XCTAssertThrowsError(try stringFalse.asDouble(converting: true)) XCTAssertThrowsError(try stringFalse.asInt(converting: true)) XCTAssertEqual(try stringFalse.asString(converting: true), "FALSE") XCTAssertEqual(try stringFalse.asBuffer(converting: true), Buffer("FALSE")) XCTAssertThrowsError(try stringFalse.asArray(converting: true)) XCTAssertThrowsError(try stringFalse.asDictionary(converting: true)) let stringDouble: Map = "4.20" XCTAssertThrowsError(try stringDouble.asBool(converting: true)) XCTAssertEqual(try stringDouble.asDouble(converting: true), 4.20) XCTAssertThrowsError(try stringDouble.asInt(converting: true)) XCTAssertEqual(try stringDouble.asString(converting: true), "4.20") XCTAssertEqual(try stringDouble.asBuffer(converting: true), Buffer("4.20")) XCTAssertThrowsError(try stringDouble.asArray(converting: true)) XCTAssertThrowsError(try stringDouble.asDictionary(converting: true)) let stringInt: Map = "1969" XCTAssertThrowsError(try stringInt.asBool(converting: true)) XCTAssertEqual(try stringInt.asDouble(converting: true), 1969.0) XCTAssertEqual(try stringInt.asInt(converting: true), 1969) XCTAssertEqual(try stringInt.asString(converting: true), "1969") XCTAssertEqual(try stringInt.asBuffer(converting: true), Buffer("1969")) XCTAssertThrowsError(try stringInt.asArray(converting: true)) XCTAssertThrowsError(try stringInt.asDictionary(converting: true)) let buffer: Map = .buffer(Buffer("foo")) XCTAssertEqual(try buffer.asBool(converting: true), true) XCTAssertThrowsError(try buffer.asDouble(converting: true)) XCTAssertThrowsError(try buffer.asInt(converting: true)) XCTAssertEqual(try buffer.asString(converting: true), "foo") XCTAssertEqual(try buffer.asBuffer(converting: true), Buffer("foo")) XCTAssertThrowsError(try buffer.asArray(converting: true)) XCTAssertThrowsError(try buffer.asDictionary(converting: true)) let bufferEmpty: Map = .buffer(Buffer()) XCTAssertEqual(try bufferEmpty.asBool(converting: true), false) XCTAssertThrowsError(try bufferEmpty.asDouble(converting: true)) XCTAssertThrowsError(try bufferEmpty.asInt(converting: true)) XCTAssertEqual(try bufferEmpty.asString(converting: true), "") XCTAssertEqual(try bufferEmpty.asBuffer(converting: true), Buffer()) XCTAssertThrowsError(try bufferEmpty.asArray(converting: true)) XCTAssertThrowsError(try bufferEmpty.asDictionary(converting: true)) let array: Map = [1969] XCTAssertEqual(try array.asBool(converting: true), true) XCTAssertThrowsError(try array.asDouble(converting: true)) XCTAssertThrowsError(try array.asInt(converting: true)) XCTAssertThrowsError(try array.asString(converting: true)) XCTAssertThrowsError(try array.asBuffer(converting: true)) XCTAssertEqual(try array.asArray(converting: true), [1969]) XCTAssertThrowsError(try array.asDictionary(converting: true)) let arrayEmpty: Map = [] XCTAssertEqual(try arrayEmpty.asBool(converting: true), false) XCTAssertThrowsError(try arrayEmpty.asDouble(converting: true)) XCTAssertThrowsError(try arrayEmpty.asInt(converting: true)) XCTAssertThrowsError(try arrayEmpty.asString(converting: true)) XCTAssertThrowsError(try arrayEmpty.asBuffer(converting: true)) XCTAssertEqual(try arrayEmpty.asArray(converting: true), []) XCTAssertThrowsError(try arrayEmpty.asDictionary(converting: true)) let dictionary: Map = ["foo": "bar"] XCTAssertEqual(try dictionary.asBool(converting: true), true) XCTAssertThrowsError(try dictionary.asDouble(converting: true)) XCTAssertThrowsError(try dictionary.asInt(converting: true)) XCTAssertThrowsError(try dictionary.asString(converting: true)) XCTAssertThrowsError(try dictionary.asBuffer(converting: true)) XCTAssertThrowsError(try dictionary.asArray(converting: true)) XCTAssertEqual(try dictionary.asDictionary(converting: true), ["foo": "bar"]) let dictionaryEmpty: Map = [:] XCTAssertEqual(try dictionaryEmpty.asBool(converting: true), false) XCTAssertThrowsError(try dictionaryEmpty.asDouble(converting: true)) XCTAssertThrowsError(try dictionaryEmpty.asInt(converting: true)) XCTAssertThrowsError(try dictionaryEmpty.asString(converting: true)) XCTAssertThrowsError(try dictionaryEmpty.asBuffer(converting: true)) XCTAssertThrowsError(try dictionaryEmpty.asArray(converting: true)) XCTAssertEqual(try dictionaryEmpty.asDictionary(converting: true), [:]) } func testDescription() { let buffer: Map = [ "array": [ [], true, .buffer(Buffer("bar")), [:], 4.20, 1969, nil, "foo\nbar", ], "bool": true, "buffer": .buffer(Buffer("bar")), "dictionary": [ "array": [], "bool": true, "buffer": .buffer(Buffer("bar")), "dictionary": [:], "double": 4.20, "int": 1969, "null": nil, "string": "foo\nbar", ], "double": 4.20, "int": 1969, "null": nil, "string": "foo\nbar", ] let description = "{\"array\":[[],true,0x626172,{},4.2,1969,null,\"foo\\nbar\"],\"bool\":true,\"buffer\":0x626172,\"dictionary\":{\"array\":[],\"bool\":true,\"buffer\":0x626172,\"dictionary\":{},\"double\":4.2,\"int\":1969,\"null\":null,\"string\":\"foo\\nbar\"},\"double\":4.2,\"int\":1969,\"null\":null,\"string\":\"foo\\nbar\"}" XCTAssertEqual(buffer.description, description) } func testEquality() { let a: Map = "foo" let b: Map = 1968 XCTAssertNotEqual(a, b) } func testIndexPath() throws { var buffer: Map buffer = [["foo"]] XCTAssertEqual(try buffer.get(0, 0), "foo") try buffer.set("bar", for: 0, 0) XCTAssertEqual(try buffer.get(0, 0), "bar") buffer = [["foo": "bar"]] XCTAssertEqual(try buffer.get(0, "foo"), "bar") try buffer.set("baz", for: 0, "foo") XCTAssertEqual(try buffer.get(0, "foo"), "baz") buffer = ["foo": ["bar"]] XCTAssertEqual(try buffer.get("foo", 0), "bar") try buffer.set("baz", for: "foo", 0) XCTAssertEqual(try buffer.get("foo", 0), "baz") buffer = ["foo": ["bar": "baz"]] XCTAssertEqual(try buffer.get("foo", "bar"), "baz") try buffer.set("buh", for: "foo", "bar") XCTAssertEqual(try buffer.get("foo", "bar"), "buh") try buffer.set("uhu", for: "foo", "yoo") XCTAssertEqual(try buffer.get("foo", "bar"), "buh") XCTAssertEqual(try buffer.get("foo", "yoo"), "uhu") try buffer.remove("foo", "bar") XCTAssertEqual(buffer, ["foo": ["yoo": "uhu"]]) } func testMapInitializable() throws { struct Bar : MapInitializable { let bar: String } struct Foo : MapInitializable { let foo: Bar } struct Baz { let baz: String } struct Fuu : MapInitializable { let fuu: Baz } struct Fou : MapInitializable { let fou: String? } XCTAssertEqual(try Bar(map: ["bar": "bar"]).bar, "bar") XCTAssertThrowsError(try Bar(map: "bar")) XCTAssertThrowsError(try Bar(map: ["bar": nil])) XCTAssertEqual(try Foo(map: ["foo": ["bar": "bar"]]).foo.bar, "bar") XCTAssertThrowsError(try Fuu(map: ["fuu": ["baz": "baz"]])) XCTAssertEqual(try Fou(map: [:]).fou, nil) XCTAssertEqual(try Map(map: nil), nil) XCTAssertEqual(try Bool(map: true), true) XCTAssertThrowsError(try Bool(map: nil)) XCTAssertEqual(try Double(map: 4.2), 4.2) XCTAssertThrowsError(try Double(map: nil)) XCTAssertEqual(try Int(map: 4), 4) XCTAssertThrowsError(try Int(map: nil)) XCTAssertEqual(try String(map: "foo"), "foo") XCTAssertThrowsError(try String(map: nil)) XCTAssertEqual(try Buffer(map: .buffer(Buffer("foo"))), Buffer("foo")) XCTAssertThrowsError(try Buffer(map: nil)) XCTAssertEqual(try Optional<Int>(map: nil), nil) XCTAssertEqual(try Optional<Int>(map: 1969), 1969) XCTAssertThrowsError(try Optional<Baz>(map: nil)) XCTAssertEqual(try Array<Int>(map: [1969]), [1969]) XCTAssertThrowsError(try Array<Int>(map: nil)) XCTAssertThrowsError(try Array<Baz>(map: [])) XCTAssertEqual(try Dictionary<String, Int>(map: ["foo": 1969]), ["foo": 1969]) XCTAssertThrowsError(try Dictionary<String, Int>(map: nil)) XCTAssertThrowsError(try Dictionary<Int, Int>(map: [:])) XCTAssertThrowsError(try Dictionary<String, Baz>(map: [:])) let map: Map = [ "fey": [ "foo": "bar", "fuu": "baz" ] ] struct Fey : MapInitializable { let foo: String let fuu: String } let fey: Fey = try map.get("fey") XCTAssertEqual(fey.foo, "bar") XCTAssertEqual(fey.fuu, "baz") } func testMapRepresentable() throws { struct Bar : MapFallibleRepresentable { let bar: String } struct Foo : MapFallibleRepresentable { let foo: Bar } struct Baz { let baz: String } struct Fuu : MapFallibleRepresentable { let fuu: Baz } XCTAssertEqual(try Foo(foo: Bar(bar: "bar")).asMap(), ["foo": ["bar": "bar"]]) XCTAssertThrowsError(try Fuu(fuu: Baz(baz: "baz")).asMap()) XCTAssertEqual(Map(1969).map, 1969) XCTAssertEqual(true.map, true) XCTAssertEqual(4.2.map, 4.2) XCTAssertEqual(1969.map, 1969) XCTAssertEqual("foo".map, "foo") XCTAssertEqual(Buffer("foo").map, .buffer(Buffer("foo"))) let optional: Int? = nil XCTAssertEqual(optional.map, nil) XCTAssertEqual(Int?(1969).map, 1969) XCTAssertEqual([1969].map, [1969]) XCTAssertEqual([1969].mapArray, [.int(1969)]) XCTAssertEqual(["foo": 1969].map, ["foo": 1969]) XCTAssertEqual(["foo": 1969].mapDictionary, ["foo": .int(1969)]) XCTAssertEqual(try optional.asMap(), nil) XCTAssertEqual(try Int?(1969).asMap(), 1969) let fuuOptional: Baz? = nil XCTAssertThrowsError(try fuuOptional.asMap()) XCTAssertEqual(try [1969].asMap(), [1969]) let fuuArray: [Baz] = [] XCTAssertEqual(try fuuArray.asMap(), []) XCTAssertEqual(try ["foo": 1969].asMap(), ["foo": 1969]) let fuuDictionaryA: [Int: Foo] = [:] XCTAssertThrowsError(try fuuDictionaryA.asMap()) let fuuDictionaryB: [String: Baz] = [:] XCTAssertEqual(try fuuDictionaryB.asMap(), [:]) } } extension MapTests { public static var allTests: [(String, (MapTests) -> () throws -> Void)] { return [ ("testCreation", testCreation), ("testConversion", testConversion), ("testDescription", testDescription), ("testEquality", testEquality), ("testIndexPath", testIndexPath), ("testMapInitializable", testMapInitializable), ("testMapRepresentable", testMapRepresentable), ] } }
mit
561ea40b65f9ca5adf89de0140d4faf4
43.837209
339
0.669087
5.019457
false
false
false
false
sivu22/AnyTracker
AnyTracker/ItemSum.swift
1
6573
// // ItemSum.swift // AnyTracker // // Created by Cristian Sava on 10/07/16. // Copyright © 2016 Cristian Sava. All rights reserved. // import Foundation class ItemSum: Item, ItemTypeSum { var version: String = App.version var name: String = "" var ID: String = "" var description: String = "" fileprivate(set) var type: ItemType = ItemType.sum var useDate: Bool = false var startDate: Date var endDate: Date fileprivate(set) var sum: Double = 0 fileprivate(set) var elements: [Element] = [] required init() { self.startDate = Date() self.endDate = self.startDate } convenience init(withName name: String, ID: String, description: String, useDate: Bool, startDate: Date, endDate: Date, sum: Double = 0, elements: [Element] = []) { self.init() initItem(withName: name, ID: ID, description: description, useDate: useDate, startDate: startDate, endDate: endDate) self.sum = sum self.elements = elements } func isEmpty() -> Bool { return elements.count == 0 } func toString() -> String? { return toJSONString() } func insert(element: Element, completionHandler: @escaping (Status?) -> Void) { elements.append(element) sum += element.value DispatchQueue.global().async { var completionError: Status? do { try self.saveToFile() } catch { self.elements.removeLast() self.sum -= element.value if let statusError = error as? Status { completionError = statusError } else { completionError = Status.errorDefault } } DispatchQueue.main.async { completionHandler(completionError) } } } func remove(atIndex index: Int, completionHandler: @escaping (Status?) -> Void) { if index < 0 || index >= elements.count { completionHandler(Status.errorIndex) return } let deleted = Element(name: elements[index].name, value: elements[index].value) sum -= elements[index].value elements.remove(at: index) DispatchQueue.global().async { var completionError: Status? do { try self.saveToFile() } catch { self.elements.append(deleted) self.sum += deleted.value if let statusError = error as? Status { completionError = statusError } else { completionError = Status.errorDefault } } DispatchQueue.main.async { completionHandler(completionError) } } } func updateElement(atIndex index: Int, newName name: String, newValue value: Double, completionHandler: @escaping (Status?) -> Void) { if index < 0 || index >= elements.count { completionHandler(Status.errorIndex) return } if elements[index].name == name && elements[index].value == value { return } let old = Element(name: elements[index].name, value: elements[index].value) let new = Element(name: name, value: value) sum -= old.value sum += new.value elements[index] = new DispatchQueue.global().async { var completionError: Status? do { try self.saveToFile() } catch { self.elements[index] = old self.sum -= new.value self.sum += old.value if let statusError = error as? Status { completionError = statusError } } DispatchQueue.main.async { completionHandler(completionError) } } } func exchangeElement(fromIndex src: Int, toIndex dst: Int) { if src < 0 || dst < 0 || src >= elements.count || dst >= elements.count { return } elements.swapAt(src, dst) } // MARK: - } extension ItemSum: JSON { // MARK: JSON Protocol func toJSONString() -> String? { var dict: JSONDictionary = getItemAsJSONDictionary() dict["sum"] = sum as JSONObject? var arrayElements: JSONArray = [] for element in elements { var dictElement: JSONDictionary = [:] dictElement["name"] = element.name as JSONObject? dictElement["value"] = element.value as JSONObject? arrayElements.append(dictElement as JSONObject) } dict["elements"] = arrayElements as JSONObject? let jsonString = Utils.getJSONFromObject(dict as JSONObject?) Utils.debugLog("Serialized sum item to JSON string \(String(describing: jsonString))") return jsonString } static func fromJSONString(_ input: String?) -> ItemSum? { guard let (dict, version, name, ID, description, type, useDate, startDate, endDate) = getItemFromJSONDictionary(input) else { return nil } Utils.debugLog(input!) if type != ItemType.sum.rawValue { Utils.debugLog("Item is not of type sum") return nil } guard let sum = dict["sum"] as? Double else { Utils.debugLog("Item sum invalid") return nil } guard let elementsArray = dict["elements"] as? [AnyObject] else { Utils.debugLog("Item elements are invalid") return nil } var elements: [Element] = [] for elementObject in elementsArray { if let name = elementObject["name"] as? String, let value = elementObject["value"] as? Double { let element = Element(name: name, value: value) elements.append(element) Utils.debugLog(element.name + " " + String(element.value)) } } let itemSum = ItemSum(withName: name, ID: ID, description: description, useDate: useDate, startDate: startDate, endDate: endDate, sum: sum, elements: elements) if !itemSum.setVersion(version) { return nil } return itemSum } }
mit
4f6b6939e2b5912b7dd7f41cd47bb70c
31.215686
168
0.537127
4.956259
false
false
false
false
zdima/LMZGaugeView
LMZGaugeView/LMZGaugeView.swift
1
16008
// // LMZGaugeView.swift // LMZGaugeView // // Created by Dmitriy Zakharkin on 9/4/15. // Copyright (c) 2015 ZDima. All rights reserved. // import Foundation import Cocoa @objc public protocol LMGaugeViewDelegate { /// Return ring stroke color from the specified value. optional func gaugeViewRingColor(gaugeView: LMZGaugeView) -> NSColor?; optional func gaugeViewLabel1Color(gaugeView: LMZGaugeView) -> NSColor?; optional func gaugeViewLabel2Color(gaugeView: LMZGaugeView) -> NSColor?; optional func gaugeViewLabel1String(gaugeView: LMZGaugeView) -> String?; optional func gaugeViewLabel2String(gaugeView: LMZGaugeView) -> String?; } public class LMZGaugeView : NSView { /// Current value. public var doubleValue: Double = 0 { didSet { if oldValue != doubleValue { var value = max( self.minValue, doubleValue) doubleValue = min( self.maxValue, value) } if oldValue != doubleValue { self.updateValueAndColor() } } } override public func value() -> AnyObject? { return NSNumber(double: doubleValue) } override public func setValue(value: AnyObject?) { doubleValue = doubleFromAnyObject(value) } /// Minimum value. @IBInspectable public var minValue: Double = 0 { didSet { if oldValue != minValue { self.invalidateMath = true self.needsDisplay = true } } } /// Maximum value. @IBInspectable public var maxValue: Double = 100 { didSet { if oldValue != maxValue { self.invalidateMath = true self.needsDisplay = true } } } /// Limit value. @IBInspectable public var limitValue: Double = 50 { didSet { if oldValue != limitValue { self.label2.stringValue = self.stringForLabel2() } } } /// The number of divisions. @IBInspectable public var numOfDivisions: Int = 10 { didSet { if oldValue != numOfDivisions { self.invalidateMath = true self.needsDisplay = true } } } /// The number of subdivisions. @IBInspectable public var numOfSubDivisions: Int = 1 { didSet { if oldValue != numOfSubDivisions { self.invalidateMath = true self.needsDisplay = true } } } /// The thickness of the ring. @IBInspectable public var ringThickness: CGFloat = 15 { didSet { if oldValue != ringThickness { self.invalidateMath = true self.needsDisplay = true } } } /// The background color of the ring. @IBInspectable public var ringBackgroundColor: NSColor = NSColor(white: 0.9, alpha: 1.0) { didSet { if oldValue != ringBackgroundColor { self.needsDisplay = true } } } /// The divisions radius. @IBInspectable public var divisionsRadius: CGFloat = 1.25 { didSet { if oldValue != divisionsRadius { self.invalidateMath = true self.needsDisplay = true } } } /// The divisions color. @IBInspectable public var divisionsColor: NSColor = NSColor(white: 0.5, alpha: 1.0) { didSet { if oldValue != divisionsColor { self.needsDisplay = true } } } /// The padding between ring and divisions. @IBInspectable public var divisionsPadding: CGFloat = 12 { didSet { if oldValue != divisionsPadding { self.invalidateMath = true self.needsDisplay = true } } } /// The subdivisions radius. @IBInspectable public var subDivisionsRadius: CGFloat = 0.75 { didSet { if oldValue != subDivisionsRadius { self.invalidateMath = true self.needsDisplay = true } } } /// The subdivisions color. @IBInspectable public var subDivisionsColor: NSColor = NSColor(white: 0.5, alpha: 0.5) { didSet { if oldValue != subDivisionsColor { self.needsDisplay = true } } } /// A boolean indicates whether to show limit dot. @IBInspectable public var showLimitDot: Bool = true { didSet { if oldValue != showLimitDot { self.needsDisplay = true } } } /// The radius of limit dot. @IBInspectable public var limitDotRadius: CGFloat = 2 { didSet { if oldValue != limitDotRadius { self.needsDisplay = true } } } /// The color of limit dot. @IBInspectable public var limitDotColor: NSColor = NSColor.redColor() { didSet { if oldValue != limitDotColor { self.needsDisplay = true } } } /// Font of value label. @IBInspectable public var valueFont: NSFont? = NSFont(name: "HelveticaNeue-CondensedBold", size: 19) { didSet { if oldValue != valueFont { self.label1.font = valueFont } } } /// Font of limit value label. @IBInspectable public var limitValueFont: NSFont? = NSFont(name: "HelveticaNeue-Condensed", size: 17) { didSet { if oldValue != limitValueFont { self.label2.font = limitValueFont } } } /// Text color of value label. @IBInspectable public var valueTextColor: NSColor = NSColor(white: 0.1, alpha: 1.0) { didSet { if oldValue != valueTextColor { if !self.useGaugeColor { label1.textColor = valueTextColor } } } } /// Use gauge color to show the value @IBInspectable public var useGaugeColor: Bool = true{ didSet { if useGaugeColor { label1.textColor = self.currentRingColor } else { label1.textColor = valueTextColor } } } /// The unit of measurement. @IBOutlet public var unitFormatter: NSFormatter? { didSet { if oldValue != unitFormatter { self.label1.stringValue = self.stringForLabel1() self.label2.stringValue = self.stringForLabel2() } } } /// The receiver of all gauge view delegate callbacks. @IBOutlet public var delegate: LMGaugeViewDelegate? { didSet { updateValueAndColor() } } func updateValueAndColor() { self.label1.stringValue = self.stringForLabel1() self.label2.stringValue = self.stringForLabel2() if self.delegate != nil, let valuecolor = self.delegate!.gaugeViewRingColor?(self) { self.currentRingColor = valuecolor } else { self.currentRingColor = kDefaultRingColor } if self.delegate != nil, let valuecolor = self.delegate!.gaugeViewLabel1Color?(self) { self.currentLabel1Color = valuecolor } else { if useGaugeColor { self.currentLabel1Color = self.currentRingColor } else { self.currentLabel1Color = kDefaultRingColor } } if self.delegate != nil, let valuecolor = self.delegate!.gaugeViewLabel2Color?(self) { self.currentLabel2Color = valuecolor } else { if useGaugeColor { self.currentLabel2Color = self.currentRingColor } else { self.currentLabel2Color = kDefaultRingColor } } self.invalidateMath = true self.valueChanged = true self.needsDisplay = true } func getValueColor() -> NSColor { if useGaugeColor { return self.currentRingColor } else { return self.valueTextColor } } func stringForLabel1() -> String { if self.delegate != nil, let valueString = self.delegate!.gaugeViewLabel1String?(self) { return valueString } if let formatter = self.unitFormatter { return formatter.stringForObjectValue(self.doubleValue)! } else { return NSString(format:"%0.f", locale:nil, self.doubleValue) as String } } func stringForLabel2() -> String { if self.delegate != nil, let valueString = self.delegate!.gaugeViewLabel2String?(self) { return valueString } let valueString: String! if let formatter = self.unitFormatter { valueString = formatter.stringForObjectValue(self.limitValue)! } else { valueString = NSString(format:"%0.f", locale:nil, self.limitValue) as String } return String(format: NSLocalizedString("Limit %@", comment: ""), valueString) } let kDefaultRingColor = NSColor(red: 76.0/255, green: 217.0/255, blue: 100.0/255, alpha: 1.0) var startAngle: Double = 0 var endAngle: Double = M_PI var divisionUnitAngle: Double = 1 var divisionUnitValue: Double = 1 var invalidateMath: Bool = true var valueChanged: Bool = true var currentRingColor: NSColor = NSColor(red: 76.0/255, green: 217.0/255, blue: 100.0/255, alpha: 1.0) { didSet { if oldValue != currentRingColor { self.progressLayer.fillColor = currentRingColor.CGColor self.progressLayer.strokeColor = currentRingColor.CGColor if useGaugeColor { self.label1.textColor = currentRingColor } } } } var currentLabel1Color: NSColor = NSColor(red: 76.0/255, green: 217.0/255, blue: 100.0/255, alpha: 1.0) { didSet { if oldValue != currentLabel1Color { self.label1.textColor = currentLabel1Color } } } var currentLabel2Color: NSColor = NSColor(red: 76.0/255, green: 217.0/255, blue: 100.0/255, alpha: 1.0) { didSet { if oldValue != currentLabel1Color { self.label2.textColor = currentLabel1Color } } } lazy var progressLayer: CAShapeLayer! = { self.wantsLayer = true let player = CAShapeLayer() player.lineCap = kCALineJoinBevel self.layer!.addSublayer(player) return player }() lazy var label1: NSTextField! = { let label = NSTextField() label.bezeled = false label.drawsBackground = false label.editable = false label.selectable = false label.alignment = NSTextAlignment.CenterTextAlignment label.stringValue = self.stringForLabel1() label.font = self.valueFont; label.textColor = self.getValueColor() self.addSubview(label) return label }() lazy var label2: NSTextField! = { let label = NSTextField() label.bezeled = false label.drawsBackground = false label.editable = false label.selectable = false label.alignment = NSTextAlignment.CenterTextAlignment label.stringValue = self.stringForLabel2() label.font = self.limitValueFont; label.textColor = self.valueTextColor; self.addSubview(label) return label }() func doubleFromAnyObject( any:AnyObject? ) -> Double { if let theValue: AnyObject = any { if let dValue = theValue as? Double { return dValue } else if let fValue = theValue as? CGFloat { return Double(fValue) } else if let iValue = theValue as? Int { return Double(iValue) } else if let nmValue = theValue as? NSNumber { return nmValue.doubleValue } } return 0.0 } func angleFromValue( value: Double) -> CGFloat { let level = (value - minValue) if divisionUnitValue != 0 { let angle = level * divisionUnitAngle / divisionUnitValue + startAngle return CGFloat(angle) } return CGFloat(startAngle) } func drawDotAtContext(context: CGContextRef, center: CGPoint, radius: CGFloat, fillColor: CGColorRef ) { CGContextBeginPath(context) CGContextAddArc(context, center.x, center.y, radius, 0, CGFloat(M_PI*2), 0) CGContextSetFillColorWithColor(context, fillColor); CGContextFillPath(context); } var center: CGPoint = CGPoint(x: 0, y: 0) var ringRadius: CGFloat = 0 var dotRadius: CGFloat = 0 var divisionCenter: [CGPoint] = [] var subdivisionCenter: [CGPoint] = [] var progressFrame: CGRect = CGRectZero var progressBounds: CGRect = CGRectZero override public func resizeSubviewsWithOldSize(oldSize: NSSize) { super.resizeSubviewsWithOldSize(oldSize) prepareMath() } func prepareMath() { self.invalidateMath = false divisionUnitValue = (maxValue - minValue)/Double(numOfDivisions) divisionUnitAngle = (M_PI * 2 - fabs(endAngle - startAngle))/Double(numOfDivisions) center = CGPoint(x: CGRectGetWidth(bounds)/2, y: 0) ringRadius = (min(CGRectGetWidth(bounds)/2, CGRectGetHeight(bounds)) - ringThickness/2) dotRadius = ringRadius - ringThickness/2 - divisionsPadding - divisionsRadius/2 let fx: CGFloat = center.x - ringRadius - ringThickness/2 let fy: CGFloat = 0 let fh: CGFloat = (ringRadius + ringThickness/2) let fw: CGFloat = fh * 2 progressFrame = CGRect(x:fx, y:fy , width:fw, height:fh) progressBounds = CGRect(x:0, y:fh, width:fw, height:fh) CATransaction.setDisableActions(true) if progressLayer.frame != progressFrame || progressLayer.bounds != progressBounds { valueChanged = true progressLayer.frame = progressFrame progressLayer.bounds = progressBounds } if valueChanged { valueChanged = false let smoothedPath = NSBezierPath() let a1 = 180-(startAngle).toDegree let a2 = 180-((endAngle - startAngle) * doubleValue / self.maxValue).toDegree let w = CGRectGetWidth(progressLayer.bounds)/2 smoothedPath.appendBezierPathWithArcWithCenter(CGPoint(x:w,y:w), radius: w, startAngle: a1, endAngle: a2, clockwise:true) smoothedPath.appendBezierPathWithArcWithCenter(CGPoint(x:w,y:w), radius: w-ringThickness, startAngle: a2, endAngle: a1, clockwise:false) progressLayer.path = BezierPath(smoothedPath) } CATransaction.setDisableActions(false) divisionCenter = [] subdivisionCenter = [] for i in 0...self.numOfDivisions { if i != numOfDivisions && numOfSubDivisions>1 { for j in 0..<numOfSubDivisions { // Subdivisions let value: Double = divisionUnitValue * Double(i) + (divisionUnitValue * Double(j)) / Double(numOfSubDivisions) let angle = angleFromValue(value) let dotCenter = CGPoint(x: dotRadius * CGFloat(cos(angle)) + center.x, y:dotRadius * CGFloat(sin(angle)) + center.y) subdivisionCenter.append(dotCenter) } } // Divisions let value = Double(i) * divisionUnitValue let angle = angleFromValue(value) let dotCenter = CGPoint(x:dotRadius * CGFloat(cos(angle)) + center.x, y:dotRadius * CGFloat(sin(angle)) + center.y) divisionCenter.append(dotCenter) } var lblFrame = CGRect(origin: CGPointZero, size: label1.intrinsicContentSize) lblFrame.origin.y = (progressLayer.frame.height-lblFrame.height)/2 lblFrame.size.width = self.frame.width self.label1.frame = lblFrame let origin = CGPoint(x:label1.frame.origin.x, y: label1.frame.origin.y-label2.intrinsicContentSize.height) let size = CGSize(width: CGRectGetWidth(self.label1.frame), height:label2.intrinsicContentSize.height) self.label2.frame = CGRect(origin: origin, size: size) } override public func drawRect(dirtyRect: NSRect) { if invalidateMath { prepareMath() } let context: CGContext = NSGraphicsContext.currentContext()!.CGContext // Draw the ring progress background CGContextSetLineWidth(context, ringThickness); CGContextBeginPath(context); CGContextAddArc(context, center.x, center.y, CGFloat(ringRadius), CGFloat(startAngle), CGFloat(endAngle), 0); CGContextSetStrokeColorWithColor(context, ringBackgroundColor.CGColor); CGContextStrokePath(context); // Draw divisions and subdivisions for center in divisionCenter { drawDotAtContext(context, center: center, radius: divisionsRadius, fillColor: divisionsColor.CGColor) } for center in subdivisionCenter { drawDotAtContext(context, center: center, radius: subDivisionsRadius, fillColor: subDivisionsColor.CGColor) } // Draw the limit dot if showLimitDot { let angle = angleFromValue(limitValue) let dotCenter = CGPoint(x:center.x - dotRadius * CGFloat(cos(angle)), y: dotRadius * CGFloat(sin(angle)) + center.y) drawDotAtContext(context, center: dotCenter, radius: limitDotRadius, fillColor: limitDotColor.CGColor) } } } extension Int { var toRadians : CGFloat { return CGFloat(self) * CGFloat(M_PI) / 180.0 } var toDegree: CGFloat { return CGFloat(self)*180.0/CGFloat(M_PI) } } extension Double { var toRadians : CGFloat { return CGFloat(self) * CGFloat(M_PI) / 180.0 } var toDegree: CGFloat { return CGFloat(self)*180.0/CGFloat(M_PI) } } func BezierPath(bezier: NSBezierPath) -> CGPath { var path: CGMutablePath = CGPathCreateMutable() var points: [NSPoint] = [NSPoint(),NSPoint(),NSPoint()] var didClosePath: Bool = false for idx in 0..<bezier.elementCount { let elementType = bezier.elementAtIndex(idx, associatedPoints: &points) switch(elementType) { case .MoveToBezierPathElement: CGPathMoveToPoint(path, nil, points[0].x, points[0].y) case .CurveToBezierPathElement: CGPathAddCurveToPoint(path, nil, points[0].x, points[0].y, points[1].x, points[1].y, points[2].x, points[2].y) case .LineToBezierPathElement: CGPathAddLineToPoint(path, nil, points[0].x, points[0].y) case .ClosePathBezierPathElement: CGPathCloseSubpath(path) didClosePath = true } } if didClosePath == false { CGPathCloseSubpath(path) } return CGPathCreateCopy(path) }
mit
107cbf3869833cbad06bcb1d553833c4
28.15847
139
0.70927
3.491385
false
false
false
false
richardpiazza/SOSwift
Sources/SOSwift/LoanOrCreditOrPaymentMethod.swift
1
2144
import Foundation import CodablePlus public enum LoanOrCreditOrPaymentMethod: Codable { case loanOrCredit(value: LoanOrCredit) case paymentMethod(value: PaymentMethod) public init(_ value: LoanOrCredit) { self = .loanOrCredit(value: value) } public init(_ value: PaymentMethod) { self = .paymentMethod(value: value) } public init(from decoder: Decoder) throws { var dictionary: [String : Any]? do { let jsonContainer = try decoder.container(keyedBy: DictionaryKeys.self) dictionary = try jsonContainer.decode(Dictionary<String, Any>.self) } catch { } guard let jsonDictionary = dictionary else { let container = try decoder.singleValueContainer() let value = try container.decode(PaymentMethod.self) self = .paymentMethod(value: value) return } guard let type = jsonDictionary[SchemaKeys.type.rawValue] as? String else { throw SchemaError.typeDecodingError } let container = try decoder.singleValueContainer() switch type { case LoanOrCredit.schemaName: let value = try container.decode(LoanOrCredit.self) self = .loanOrCredit(value: value) default: throw SchemaError.typeDecodingError } } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() switch self { case .loanOrCredit(let value): try container.encode(value) case .paymentMethod(let value): try container.encode(value) } } public var loanOrCredit: LoanOrCredit? { switch self { case .loanOrCredit(let value): return value default: return nil } } public var paymentMethod: PaymentMethod? { switch self { case .paymentMethod(let value): return value default: return nil } } }
mit
76a415d8bc8ec90b027ade5ed7ef3954
27.210526
83
0.576959
5.021077
false
false
false
false
neonichu/Roark
Sources/Roark/Xcode.swift
1
1581
import Chores import Foundation private func load_xcode_framework(path: String) { let result = >["xcode-select", "-p"] if let xcodePath = result.stdout.lines.first { let path = "\(xcodePath)/../\(path)" if !NSFileManager.defaultManager().fileExistsAtPath(path) { return } if dlopen(path, RTLD_NOW) == nil { fatalError(String.fromCString(dlerror()) ?? "dlopen() failed") } } } public func InitializeXcode() { load_xcode_framework("SharedFrameworks/DVTFoundation.framework/DVTFoundation") load_xcode_framework("SharedFrameworks/DVTServices.framework/DVTServices") load_xcode_framework("SharedFrameworks/DVTPortal.framework/DVTPortal") load_xcode_framework("SharedFrameworks/DVTSourceControl.framework/DVTSourceControl") //load_xcode_framework("SharedFrameworks/CSServiceClient.framework/CSServiceClient") load_xcode_framework("Frameworks/IBFoundation.framework/IBFoundation") load_xcode_framework("Frameworks/IBAutolayoutFoundation.framework/IBAutolayoutFoundation") load_xcode_framework("Frameworks/IDEFoundation.framework/IDEFoundation") load_xcode_framework("PlugIns/Xcode3Core.ideplugin/Contents/MacOS/Xcode3Core") silence_stderr { typealias IDEInitializeType = @convention(c) (Int, UnsafePointer<Void>) -> () let IDEInitialize = CFunction("IDEInitialize", IDEInitializeType.self) IDEInitialize(1, nil) typealias XCInitializeCoreIfNeededType = @convention(c) (Int) -> () let XCInitializeCoreIfNeeded = CFunction("XCInitializeCoreIfNeeded", XCInitializeCoreIfNeededType.self) XCInitializeCoreIfNeeded(0) } }
mit
f7a393ba83b7b916ff9148ef4230e2dd
44.171429
106
0.772296
3.913366
false
false
false
false
natecook1000/swift
stdlib/private/StdlibUnittest/StringConvertible.swift
4
5289
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A type that has different `CustomStringConvertible` and /// `CustomDebugStringConvertible` representations. /// /// This type also conforms to other protocols, to make it /// usable in constrained contexts. It is not intended to be a /// minimal type that only conforms to certain protocols. /// /// This type can be used to check that code uses the correct /// kind of string representation. public struct CustomPrintableValue : Equatable, Comparable, Hashable, Strideable { public static var timesDescriptionWasCalled = ResettableValue(0) public static var timesDebugDescriptionWasCalled = ResettableValue(0) public static var descriptionImpl = ResettableValue<(_ value: Int, _ identity: Int) -> String>({ (value: Int, identity: Int) -> String in if identity == 0 { return "(value: \(value)).description" } else { return "(value: \(value), identity: \(identity)).description" } }) public static var debugDescriptionImpl = ResettableValue<(_ value: Int, _ identity: Int) -> String>({ (value: Int, identity: Int) -> String in CustomPrintableValue.timesDescriptionWasCalled.value += 1 if identity == 0 { return "(value: \(value)).debugDescription" } else { return "(value: \(value), identity: \(identity)).debugDescription" } }) public var value: Int public var identity: Int public init(_ value: Int) { self.value = value self.identity = 0 } public init(_ value: Int, identity: Int) { self.value = value self.identity = identity } public var hashValue: Int { return value.hashValue } public typealias Stride = Int public func distance(to other: CustomPrintableValue) -> Stride { return other.value - self.value } public func advanced(by n: Stride) -> CustomPrintableValue { return CustomPrintableValue(self.value + n, identity: self.identity) } } public func == ( lhs: CustomPrintableValue, rhs: CustomPrintableValue ) -> Bool { return lhs.value == rhs.value } public func < ( lhs: CustomPrintableValue, rhs: CustomPrintableValue ) -> Bool { return lhs.value < rhs.value } extension CustomPrintableValue : CustomStringConvertible { public var description: String { CustomPrintableValue.timesDescriptionWasCalled.value += 1 return CustomPrintableValue.descriptionImpl.value( value, identity) } } extension CustomPrintableValue : CustomDebugStringConvertible { public var debugDescription: String { CustomPrintableValue.timesDebugDescriptionWasCalled.value += 1 return CustomPrintableValue.debugDescriptionImpl.value( value, identity) } } public func expectPrinted<T>( expectedOneOf patterns: [String], _ object: T, _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line ) { let actual = String(describing: object) if !patterns.contains(actual) { expectationFailure( "expected: any of \(String(reflecting: patterns))\n" + "actual: \(String(reflecting: actual))", trace: message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) } } public func expectPrinted<T>( _ expected: String, _ object: T, _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line ) { expectPrinted(expectedOneOf: [expected], object, message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) } public func expectDebugPrinted<T>( expectedOneOf patterns: [String], _ object: T, _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line ) { expectPrinted(expectedOneOf: patterns, String(reflecting: object), message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) } public func expectDebugPrinted<T>( _ expected: String, _ object: T, _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line ) { expectDebugPrinted(expectedOneOf: [expected], object, message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) } public func expectDumped<T>( _ expected: String, _ object: T, _ message: @autoclosure () -> String = "", stackTrace: SourceLocStack = SourceLocStack(), showFrame: Bool = true, file: String = #file, line: UInt = #line ) { var actual = "" dump(object, to: &actual) expectEqual(expected, actual, message(), stackTrace: stackTrace.pushIf(showFrame, file: file, line: line)) }
apache-2.0
e7bb5774f14dd9808bc695f22e8eadf8
30.111765
80
0.669503
4.324612
false
false
false
false
Fig-leaves/curation
RSSReader/ChannelViewController.swift
1
8340
// // ChannelViewController.swift // RSSReader // // Created by 伊藤総一郎 on 9/8/15. // Copyright (c) 2015 susieyy. All rights reserved. // import UIKit class ChannelViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, AdstirMraidViewDelegate{ @IBOutlet weak var table: UITableView! var items = NSMutableArray() var refresh: UIRefreshControl! final let API_KEY = Constants.youtube.API_KEY final let CHANNEL_ID:String = Constants.youtube.CHANNEL var loading = false var nextPageToken:NSString! var inter: AdstirInterstitial? = nil var click_count = 0; var adView: AdstirMraidView? = nil deinit { // デリゲートを解放します。解放を忘れるとクラッシュする可能性があります。 self.adView?.delegate = nil // 広告ビューを解放します。 self.adView = nil } override func viewDidLoad() { super.viewDidLoad() self.title = "内さま" self.inter = AdstirInterstitial() self.inter!.media = Constants.inter_ad.id self.inter!.spot = Constants.inter_ad.spot self.inter!.load() // 広告表示位置: タブバーの下でセンタリング、広告サイズ: 320,50 の場合 let originY = self.view.frame.height let originX = (self.view.frame.size.width - kAdstirAdSize320x50.size.width) / 2 let adView = AdstirMraidView(adSize: kAdstirAdSize320x50, origin: CGPointMake(originX, originY - 100), media: Constants.ad.id, spot:Constants.ad.spot) // リフレッシュ秒数を設定します。 adView.intervalTime = 5 // デリゲートを設定します。 adView.delegate = self // 広告ビューを親ビューに追加します。 self.view.addSubview(adView) self.adView = adView // NavigationControllerのタイトルバー(NavigationBar)の色の変更 self.navigationController?.navigationBar.barTintColor = UIColor.blackColor() // NavigationConrtollerの文字カラーの変更 self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()] // NavigationControllerのNavigationItemの色 self.navigationController?.navigationBar.tintColor = UIColor.whiteColor() items = NSMutableArray() let nibName = UINib(nibName: "YoutubeTableViewCell", bundle:nil) table.registerNib(nibName, forCellReuseIdentifier: "Cell") table.delegate = self table.dataSource = self self.refresh = UIRefreshControl() self.refresh.attributedTitle = NSAttributedString(string: Constants.message.UPDATING) self.refresh.addTarget(self, action: "viewWillAppear:", forControlEvents: UIControlEvents.ValueChanged) self.table.addSubview(refresh) // // NADViewクラスを生成 // nadView = NADView(frame: CGRect(x: Constants.frame.X, // y: Constants.frame.Y, // width: Constants.frame.WIDTH, // height: Constants.frame.HEIGHT)) // // 広告枠のapikey/spotidを設定(必須) // nadView.setNendID(Constants.nend_id.API_ID, spotID: Constants.nend_id.SPOT_ID) // // nendSDKログ出力の設定(任意) // nadView.isOutputLog = true // // delegateを受けるオブジェクトを指定(必須) // nadView.delegate = self // 読み込み開始(必須) // nadView.load() // self.view.addSubview(nadView) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) items = NSMutableArray() request(false) self.refresh?.endRefreshing() } func request(next: Bool) { var urlString:String if(next) { urlString = "https://www.googleapis.com/youtube/v3/search?key=\(API_KEY)&part=snippet&channelId=\(self.CHANNEL_ID)&pageToken=\(self.nextPageToken)&maxResults=30" } else { urlString = "https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UCd8GWuNu4-b0q6Bu0dHysGg&maxResults=30&key=\(API_KEY)" } let url:NSURL! = NSURL(string:urlString) let urlRequest:NSURLRequest = NSURLRequest(URL:url) var data:NSData var dic: NSDictionary = NSDictionary() do { data = try NSURLConnection.sendSynchronousRequest(urlRequest, returningResponse: nil) dic = try NSJSONSerialization.JSONObjectWithData( data, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary } catch { print("ERROR") } if(dic.objectForKey("nextPageToken") != nil) { self.nextPageToken = dic.objectForKey("nextPageToken") as! String } else { self.nextPageToken = nil } let itemsArray: NSArray = dic.objectForKey("items") as! NSArray var content: Dictionary<String, String> = ["" : ""] itemsArray.enumerateObjectsUsingBlock({ object, index, stop in let snippet: NSDictionary = object.objectForKey("snippet") as! NSDictionary let ids: NSDictionary = object.objectForKey("id") as! NSDictionary let thumbnails: NSDictionary = snippet.objectForKey("thumbnails") as! NSDictionary let resolution: NSDictionary = thumbnails.objectForKey("high") as! NSDictionary let imageUrl: NSString = resolution.objectForKey("url") as! String if(ids["kind"] as! String == "youtube#video") { content[Constants.article_data.VIDEO_ID] = ids[Constants.article_data.VIDEO_ID] as? String content[Constants.article_data.TITLE] = snippet.objectForKey(Constants.article_data.TITLE) as? String content[Constants.article_data.IMAGE_URL] = imageUrl as String content[Constants.article_data.PUBLISH_AT] = snippet.objectForKey("publishedAt") as? String self.items.addObject(content) } }) self.table.reloadData() self.loading = false } func scrollViewDidScroll(scrollView: UIScrollView) { if(self.table.contentOffset.y >= (self.table.contentSize.height - self.table.bounds.size.height) && self.nextPageToken != nil && loading == false) { loading = true SVProgressHUD.showWithStatus(Constants.message.LOADING) dispatch_async(dispatch_get_main_queue(), { () -> Void in if(self.nextPageToken == nil) { } else { self.request(true) SVProgressHUD.dismiss() } }) } } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 100 } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.items.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = self.table.dequeueReusableCellWithIdentifier("Cell") as! YoutubeTableViewCell let item = self.items[indexPath.row] as! NSDictionary return CellPreference.setValueToYoutubeViewCell(cell, item: item) } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let item = self.items[indexPath.row] as! NSDictionary let con = KINWebBrowserViewController() let youtube_url = "https://www.youtube.com/watch?v=" + (item[Constants.article_data.VIDEO_ID] as! String) let URL = NSURL(string: youtube_url) con.loadURL(URL) if click_count % Constants.inter_ad.click_count == 3 { self.inter!.showTypeB(self) } click_count++; self.navigationController?.pushViewController(con, animated: true) } }
mit
e478d411f2ae26476945335167f126a1
38.326733
173
0.631546
4.48307
false
false
false
false
jxxcarlson/exploring_swift
stackMachine.playground/Contents.swift
1
489
//: Playground - noun: a place where people can play // http://airspeedvelocity.net/2014/06/06/an-accumulator-in-swift-part-2/ // var foo = ["1", "2", "3.1"].map{ $0.doubleValue } import Foundation let prog = "1 2 add 3 mul 1 sub 2 div" let m = StackMachine(program: prog) m.stringValue() m.run() m.stringValue() ///////// // let s = Stack<Int>() let s = Stack(data:[2,4,6]) s.top s[0] s.count s.items // s[0] = 0 s.items s.push(17) s.pop() s.items s.shift() s.items
mit
d04e141822f5fcfb7674303b76c6d92d
9.866667
73
0.609407
2.469697
false
false
false
false
kdbertel/Swiftground
enums.swift
2
1364
import UIKit var buffer = "" enum Barcode { case UPCA(Int, Int, Int) case QRCode(String) } var productBarcode = Barcode.UPCA(8, 85909_51226, 3) productBarcode = .QRCode("ABCDEFGHIJKLMNOP") switch productBarcode { case .UPCA(let numberSystem, let identifier, let check): buffer = "UPC-A with value of \(numberSystem), \(identifier), \(check)." case .QRCode(let productCode): buffer = "QR code with value of \(productCode)." } buffer let someCharacter: Character = "e" switch someCharacter { case "a", "e", "i", "o", "u": buffer = "\(someCharacter) is a vowel" case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z": buffer = "\(someCharacter) is a consonant" default: buffer = "\(someCharacter) is not a vowel or a consonant" } buffer //let count = 3_000_000_000_000 let count = 3 //let countedThings = "stars in the Milky Way" let countedThings = "empty chairs" var naturalCount: String switch count { case 0: naturalCount = "no" case 1...3: naturalCount = "a few" case 4...9: naturalCount = "several" case 10...99: naturalCount = "tens of" case 100...999: naturalCount = "hundreds of" case 1000...999_999: naturalCount = "thousands of" default: naturalCount = "millions and millions of" } buffer = "There are \(naturalCount) \(countedThings)."
unlicense
63174dc22cd02be370584a6b48187c99
22.929825
76
0.638563
3.135632
false
false
false
false
tryolabs/TLMetaResolver
Pod/Classes/TLNativeAppActivity.swift
1
4744
// // TLNativeAppActivity.swift // TLMetaResolver // // Created by Bruno Berisso on 2/13/15. // Copyright (c) 2015 Bruno Berisso. All rights reserved. // import UIKit /** This is a subclass of UIActivity that open a native app using the supported custom scheme. The icon is showed in grayscale with the sice adjusted to the running devices. */ public class TLNativeAppActivity: UIActivity { var url: NSURL var name: String var icon : UIImage? /** Create a new TLNativeAppActivity with the given parameters. :param: appUrl The url used to open the native app. When this activity is permormed a call to 'UIApplication.sharedApplication().openURL()' is performed with this value. :param: appName The name of the app used, mostly, to show the activity title in a UIActivityViewController :param: appIcon The image to use as the activity icon. This image should be a square image of any size, preferible of 76 points of bigger because it will be scaled to that size on iPad (and to 60 points on iPhone) :returns: A new instance of TLNativeAppActivity that can be shown in a UIActivityViewController */ @objc public init(nativeAppInfo: TLNativeAppInfo) { url = nativeAppInfo.url name = nativeAppInfo.name //Scale the image to the correct size for an activity icon, according to the documentation let scale: CGFloat = UIDevice.currentDevice().userInterfaceIdiom == .Phone ? 60 : 76 let scaledImage = nativeAppInfo.icon.imageByScaleToSize(CGSizeMake(scale, scale)) //Transform it to grayscale let scaledGrayImage = scaledImage.convertToGrayscale() //Mask it so it has the correct shape let iconMask = UIImage(named: "iconMask", inBundle: NSBundle.metaResolverBundle(), compatibleWithTraitCollection: nil)! icon = scaledGrayImage.imageByApplyingMask(iconMask) } func _activityImage() -> UIImage? { return icon } override public func activityType() -> String? { return NSBundle.mainBundle().bundleIdentifier! + "open.\(name)" } override public func activityTitle() -> String? { return "Open in \(name)" } override public func canPerformWithActivityItems(activityItems: [AnyObject]) -> Bool { return true } override public func performActivity() { #if arch(i386) || arch(x86_64) NSLog("App URL: \(url)") #else UIApplication.sharedApplication().openURL(url) #endif activityDidFinish(true) } } private extension UIImage { func imageByApplyingMask (maskImage: UIImage) -> UIImage? { let maskRef = maskImage.CGImage let mask = CGImageMaskCreate( CGImageGetWidth(maskRef), CGImageGetHeight(maskRef), CGImageGetBitsPerComponent(maskRef), CGImageGetBitsPerPixel(maskRef), CGImageGetBytesPerRow(maskRef), CGImageGetDataProvider(maskRef), nil, false) return CGImageCreateWithMask(CGImage, mask).map { maskedImageRef in let scale = UIScreen.mainScreen().scale return UIImage(CGImage: maskedImageRef, scale: scale, orientation: .Up) } } func imageByScaleToSize (newSize: CGSize) -> UIImage { //UIGraphicsBeginImageContext(newSize); // In next line, pass 0.0 to use the current device's pixel scaling factor (and thus account for Retina resolution). // Pass 1.0 to force exact pixel size. UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0); drawInRect(CGRectMake(0, 0, newSize.width, newSize.height)) let newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return newImage; } func convertToGrayscale () -> UIImage { UIGraphicsBeginImageContextWithOptions(size, false, scale); let imageRect = CGRectMake(0, 0, size.width, size.height); let ctx = UIGraphicsGetCurrentContext(); // Draw a white background CGContextSetRGBFillColor(ctx, 1.0, 1.0, 1.0, 1.0); CGContextFillRect(ctx, imageRect); // Draw the luminosity on top of the white background to get grayscale drawInRect(imageRect, blendMode: .Luminosity, alpha: 1.0) // Apply the source image's alpha drawInRect(imageRect, blendMode: .DestinationIn, alpha: 1.0) let grayscaleImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return grayscaleImage; } }
mit
1917420401cfbfc83f54ecf99b8221bb
36.362205
221
0.654511
5.009504
false
false
false
false
noppoMan/aws-sdk-swift
scripts/generate-package.swift
1
2668
#!/usr/bin/env swift sh //===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import Files // JohnSundell/Files import Stencil // soto-project/Stencil struct GeneratePackage { let environment: Environment let fsLoader: FileSystemLoader struct Target { let name: String let hasExtension: Bool let dependencies: [String] } init() { self.fsLoader = FileSystemLoader(paths: ["./scripts/templates/generate-package"]) self.environment = Environment(loader: self.fsLoader) } func run() throws { let servicesFolder = try Folder(path: "./Sources/Soto/Services") let extensionsFolder = try Folder(path: "./Sources/Soto/Extensions") let testFolder = try Folder(path: "./Tests/SotoTests/Services") let currentFolder = try Folder(path: ".") let extensionSubfolders = extensionsFolder.subfolders // construct list of services along with a flag to say if they have an extension let srcFolders = servicesFolder.subfolders.map { (folder) -> Target in let hasExtension = extensionSubfolders.first { $0.name == folder.name } != nil let dependencies: [String] if folder.name == "S3" { dependencies = [#".product(name: "SotoCore", package: "soto-core")"#, #".byName(name: "CSotoZlib")"#] } else { dependencies = [#".product(name: "SotoCore", package: "soto-core")"#] } return Target(name: folder.name, hasExtension: hasExtension, dependencies: dependencies) } // construct list of tests, plus the ones used in AWSRequestTests.swift var testFolders = Set<String>(testFolder.subfolders.map { $0.name }) ["ACM", "CloudFront", "EC2", "IAM", "Route53", "S3", "SES", "SNS"].forEach { testFolders.insert($0) } let context: [String: Any] = [ "targets": srcFolders, "testTargets": testFolders.map { $0 }.sorted(), ] let package = try environment.renderTemplate(name: "Package.stencil", context: context) let packageFile = try currentFolder.createFile(named: "Package.swift") try packageFile.write(package) } } try GeneratePackage().run()
apache-2.0
faa9fa80aab42c47980cb0e672ce8b85
39.424242
117
0.60045
4.352365
false
true
false
false
SiddharthNarsimhan/DecorUI
DecorMainUI/DecorMainUI/ViewController.swift
1
1523
// // ViewController.swift // DecorMainUI // // Created by Siddharth Narsimhan on 12/28/16. // Copyright © 2016 Siddharth Narsimhan. All rights reserved. // import UIKit class FeaturedProductsController : UICollectionViewController, UICollectionViewDelegateFlowLayout { fileprivate let cellId = "cellId" override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. navigationItem.title = "Avastavik AR" collectionView?.backgroundColor = UIColor.white collectionView?.register(FeaturedCell.self, forCellWithReuseIdentifier: cellId) } // func showProductList() // { // let productlistcontroller = productList() // navigationController?.pushViewController(productlistcontroller, animated: true) // } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! FeaturedCell return cell } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 4 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: view.frame.width, height: 200) } }
apache-2.0
4c71c330c68a61cc7d3a9698561b63fd
36.121951
160
0.71025
5.266436
false
false
false
false
netguru/inbbbox-ios
Inbbbox/Source Files/ViewModels/ShotBucketsViewModel.swift
1
6334
// // ShotBucketsViewModel.swift // Inbbbox // // Created by Peter Bruz on 24/02/16. // Copyright © 2016 Netguru Sp. z o.o. All rights reserved. // import Foundation import PromiseKit class ShotBucketsViewModel { var itemsCount: Int { var counter = Int(0) counter += buckets.count if didDownloadBuckets { counter += 2 // for action buttons and gap before } return counter } var attributedShotTitleForHeader: NSAttributedString { return ShotDetailsFormatter.attributedStringForHeaderWithLinkRangeFromShot(shot).attributedString } var userLinkRange: NSRange { return ShotDetailsFormatter.attributedStringForHeaderWithLinkRangeFromShot(shot).userLinkRange ?? NSRange(location: 0, length: 0) } var teamLinkRange: NSRange { return ShotDetailsFormatter.attributedStringForHeaderWithLinkRangeFromShot(shot).teamLinkRange ?? NSRange(location: 0, length: 0) } var titleForHeader: String { switch shotBucketsViewControllerMode { case .addToBucket: return Localized("ShotBucketsViewModel.AddToBucket", comment: "Allows user to add shot to bucket") case .removeFromBucket: return Localized("ShotBucketsViewModel.RemoveFromBucket", comment: "Allows user to remove shot from bucket") } } var titleForActionItem: String { switch shotBucketsViewControllerMode { case .addToBucket: return Localized("ShotBucketsViewModel.NewBucket", comment: "Allows user to create new bucket") case .removeFromBucket: return Localized("ShotBucketsViewModel.RemoveFromSelectedBuckets", comment: "Allows user to remove from multiple backets") } } let shot: ShotType let shotBucketsViewControllerMode: ShotBucketsViewControllerMode var userProvider = APIUsersProvider() var bucketsProvider = BucketsProvider() var bucketsRequester = BucketsRequester() var shotsRequester = APIShotsRequester() fileprivate(set) var buckets = [BucketType]() fileprivate(set) var selectedBucketsIndexes = [Int]() fileprivate var didDownloadBuckets = false init(shot: ShotType, mode: ShotBucketsViewControllerMode) { self.shot = shot shotBucketsViewControllerMode = mode } func loadBuckets() -> Promise<Void> { return Promise<Void> { fulfill, reject in switch shotBucketsViewControllerMode { case .addToBucket: firstly { bucketsProvider.provideMyBuckets() }.then { buckets in self.buckets = buckets ?? [] }.then { self.didDownloadBuckets = true }.then(execute: fulfill).catch(execute: reject) case .removeFromBucket: firstly { shotsRequester.userBucketsForShot(shot) }.then { buckets in self.buckets = buckets ?? [] }.then { _ in self.didDownloadBuckets = true }.then(execute: fulfill).catch(execute: reject) } } } func createBucket(_ name: String, description: NSAttributedString? = nil) -> Promise<Void> { return Promise<Void> { fulfill, reject in firstly { bucketsRequester.postBucket(name, description: description) }.then { bucket in self.buckets.append(bucket) }.then(execute: fulfill).catch(execute: reject) } } func addShotToBucketAtIndex(_ index: Int) -> Promise<Void> { return Promise<Void> { fulfill, reject in firstly { bucketsRequester.addShot(shot, toBucket: buckets[index]) }.then(execute: fulfill).catch(execute: reject) } } func removeShotFromSelectedBuckets() -> Promise<Void> { return Promise<Void> { fulfill, reject in var bucketsToRemoveShot = [BucketType]() selectedBucketsIndexes.forEach { bucketsToRemoveShot.append(buckets[$0]) } when(fulfilled: bucketsToRemoveShot.map { bucketsRequester.removeShot(shot, fromBucket: $0) }).then(execute: fulfill).catch(execute: reject) } } func selectBucketAtIndex(_ index: Int) -> Bool { toggleBucketSelectionAtIndex(index) return selectedBucketsIndexes.contains(index) } func bucketShouldBeSelectedAtIndex(_ index: Int) -> Bool { return selectedBucketsIndexes.contains(index) } func showBottomSeparatorForBucketAtIndex(_ index: Int) -> Bool { return index != buckets.count - 1 } func isSeparatorAtIndex(_ index: Int) -> Bool { return index == itemsCount - 2 } func isActionItemAtIndex(_ index: Int) -> Bool { return index == itemsCount - 1 } func indexForRemoveFromSelectedBucketsActionItem() -> Int { return itemsCount - 1 } func displayableDataForBucketAtIndex(_ index: Int) -> (bucketName: String, shotsCountText: String) { let bucket = buckets[index] let localizedString = Localized("%d shots", comment: "How many shots in collection?") let shotsCountText = String.localizedStringWithFormat(localizedString, bucket.shotsCount) return (bucketName: bucket.name, shotsCountText: shotsCountText) } } // MARK: URL - User handling extension ShotBucketsViewModel: URLToUserProvider, UserToURLProvider { func userForURL(_ url: URL) -> UserType? { return shot.user.identifier == url.absoluteString ? shot.user : nil } func userForId(_ identifier: String) -> Promise<UserType> { return userProvider.provideUser(identifier) } } private extension ShotBucketsViewModel { func toggleBucketSelectionAtIndex(_ index: Int) { if let elementIndex = selectedBucketsIndexes.index(of: index) { selectedBucketsIndexes.remove(at: elementIndex) } else { selectedBucketsIndexes.append(index) } } }
gpl-3.0
82d845ffac556a1cac086555312ba430
30.665
105
0.620085
4.95928
false
false
false
false
seltzered/SVGKit
Source/Unsorted/SVGKit+SwiftAdditions.swift
1
3472
// // SVGKit+SwiftAdditions.swift // SVGKit // // Created by C.W. Betts on 10/14/14. // Copyright (c) 2014 C.W. Betts. All rights reserved. // import Foundation import CoreGraphics import SVGKit.SVGKStyleSheetList extension SVGKNodeList: SequenceType { public func generate() -> IndexingGenerator<[SVGKNode]> { return (internalArray as NSArray as! [SVGKNode]).generate() } } extension SVGKImage { public class var cacheEnabled: Bool { get { return isCacheEnabled() } set { if cacheEnabled == newValue { return } if newValue { enableCache() } else { disableCache() } } } } extension SVGKCSSRuleList: SequenceType { public func generate() -> IndexingGenerator<[SVGKCSSRule]> { return (internalArray as NSArray as! [SVGKCSSRule]).generate() } } extension SVGKStyleSheetList: SequenceType { public func generate() -> GeneratorOf<SVGKStyleSheet> { var index = 0 return GeneratorOf { if index < Int(self.length) { return self[index++] } return nil } } } extension SVGCurve: Equatable { public static let zeroCurve = SVGCurveMake(0,0,0,0,0,0) public init(cx1: Int, cy1: Int, cx2: Int, cy2: Int, px: Int, py: Int) { self = SVGCurveMake(CGFloat(cx1), CGFloat(cy1), CGFloat(cx2), CGFloat(cy2), CGFloat(px), CGFloat(py)) } public init(cx1: Float, cy1: Float, cx2: Float, cy2: Float, px: Float, py: Float) { self = SVGCurveMake(CGFloat(cx1), CGFloat(cy1), CGFloat(cx2), CGFloat(cy2), CGFloat(px), CGFloat(py)) } public init(cx1: CGFloat, cy1: CGFloat, cx2: CGFloat, cy2: CGFloat, px: CGFloat, py: CGFloat) { self = SVGCurveMake(cx1, cy1, cx2, cy2, px, py) } } extension SVGRect: Equatable { /// Returns a new uninitialized SVGRect public static func new() -> SVGRect { return SVGRectUninitialized() } public var initialized: Bool { return SVGRectIsInitialized(self) } /// Convenience variable to convert to ObjectiveC's kind of rect public var cgRect: CGRect { return CGRectFromSVGRect(self) } /// Convenience variable to convert to ObjectiveC's kind of size - <b>Only</b> the width and height of this rect. public var cgSize: CGSize { return CGSizeFromSVGRect(self) } } extension SVGColor: Hashable, Printable, DebugPrintable { public init(string: String) { self = SVGColorFromString(string) } public init(red: UInt8, green: UInt8, blue: UInt8, alpha: UInt8 = 255) { r = red; g = green; b = blue; a = alpha } public var cgColor: CGColor { return CGColorWithSVGColor(self) } public var description: String { return "Red: \(r), Green: \(g), Blue: \(b), alpha: \(a)" } public var debugDescription: String { return "Red: \(r), Green: \(g), Blue: \(b), alpha: \(a)" } public var hashValue: Int { return Int(r) | Int(g) << 8 | Int(b) << 16 | Int(a) << 24 } } #if os(OSX) extension SVGKImageRep { } #endif public func ==(lhs: SVGRect, rhs: SVGRect) -> Bool { if lhs.x != rhs.x { return false } else if lhs.y != rhs.y { return false } else if lhs.height != rhs.height { return false } else if lhs.width != rhs.width { return false } else { return true } } public func ==(lhs: SVGColor, rhs: SVGColor) -> Bool { if lhs.r != rhs.r { return false } else if lhs.g != rhs.g { return false } else if lhs.b != rhs.b { return false } else if lhs.a != rhs.a { return false } else { return true } } public func ==(lhs: SVGCurve, rhs: SVGCurve) -> Bool { return SVGCurveEqualToCurve(lhs, rhs) }
mit
ff81756d3fb49293d88a7e3cd440cd00
21.69281
114
0.662154
3.01913
false
false
false
false
mozilla-mobile/firefox-ios
Providers/Pocket/PocketProvider.swift
2
5398
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0 import Foundation import Shared import Storage protocol PocketStoriesProviding { typealias StoryResult = Swift.Result<[PocketFeedStory], Error> func fetchStories(items: Int, completion: @escaping (StoryResult) -> Void) func fetchStories(items: Int) async throws -> [PocketFeedStory] } extension PocketStoriesProviding { func fetchStories(items: Int) async throws -> [PocketFeedStory] { return try await withCheckedThrowingContinuation { continuation in fetchStories(items: items) { result in continuation.resume(with: result) } } } } class PocketProvider: PocketStoriesProviding, FeatureFlaggable, URLCaching { private class PocketError: MaybeErrorType { var description = "Failed to load from API" } private let pocketEnvAPIKey = "PocketEnvironmentAPIKey" private static let SupportedLocales = ["en_CA", "en_US", "en_GB", "en_ZA", "de_DE", "de_AT", "de_CH"] private let pocketGlobalFeed: String static let GlobalFeed = "https://getpocket.cdn.mozilla.net/v3/firefox/global-recs" static let MoreStoriesURL = URL(string: "https://getpocket.com/explore?src=ff_ios&cdn=0")! // Allow endPoint to be overriden for testing init(endPoint: String = PocketProvider.GlobalFeed) { self.pocketGlobalFeed = endPoint } var urlCache: URLCache { return URLCache.shared } lazy private var urlSession = makeURLSession(userAgent: UserAgent.defaultClientUserAgent, configuration: URLSessionConfiguration.default) private lazy var pocketKey: String? = { return Bundle.main.object(forInfoDictionaryKey: pocketEnvAPIKey) as? String }() enum Error: Swift.Error { case failure } // Fetch items from the global pocket feed func fetchStories(items: Int, completion: @escaping (StoryResult) -> Void) { if shouldUseMockData { return getMockDataFeed(count: items, completion: completion) } else { return getGlobalFeed(items: items, completion: completion) } } private func getGlobalFeed(items: Int, completion: @escaping (StoryResult) -> Void) { guard let request = createGlobalFeedRequest(items: items) else { return completion(.failure(Error.failure)) } if let cachedResponse = findCachedResponse(for: request), let items = cachedResponse["recommendations"] as? [[String: Any]] { return completion(.success(PocketFeedStory.parseJSON(list: items))) } urlSession.dataTask(with: request) { (data, response, error) in guard let response = validatedHTTPResponse(response, contentType: "application/json"), let data = data else { return completion(.failure(Error.failure)) } self.cache(response: response, for: request, with: data) let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] guard let items = json?["recommendations"] as? [[String: Any]] else { return completion(.failure(Error.failure)) } return completion(.success(PocketFeedStory.parseJSON(list: items))) }.resume() } // Returns nil if the locale is not supported static func islocaleSupported(_ locale: String) -> Bool { return PocketProvider.SupportedLocales.contains(locale) } // Create the URL request to query the Pocket API. The max items that the query can return is 20 private func createGlobalFeedRequest(items: Int = 2) -> URLRequest? { guard items > 0 && items <= 20 else { return nil } let locale = Locale.current.identifier let pocketLocale = locale.replacingOccurrences(of: "_", with: "-") var params = [URLQueryItem(name: "count", value: String(items)), URLQueryItem(name: "locale_lang", value: pocketLocale), URLQueryItem(name: "version", value: "3")] if let pocketKey = pocketKey { params.append(URLQueryItem(name: "consumer_key", value: pocketKey)) } guard let feedURL = URL(string: pocketGlobalFeed)?.withQueryParams(params) else { return nil } return URLRequest(url: feedURL, cachePolicy: .reloadIgnoringCacheData, timeoutInterval: 5) } private var shouldUseMockData: Bool { guard let pocketKey = pocketKey else { return featureFlags.isCoreFeatureEnabled(.useMockData) ? true : false } return featureFlags.isCoreFeatureEnabled(.useMockData) && pocketKey.isEmpty } private func getMockDataFeed(count: Int = 2, completion: (StoryResult) -> Void) { let path = Bundle(for: type(of: self)).path(forResource: "pocketglobalfeed", ofType: "json") let data = try! Data(contentsOf: URL(fileURLWithPath: path!)) let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] guard let items = json?["recommendations"] as? [[String: Any]] else { return completion(.failure(Error.failure)) } return completion(.success(Array(PocketFeedStory.parseJSON(list: items).prefix(count)))) } }
mpl-2.0
34659a53a888e76356c2c03902709f27
39.283582
171
0.670248
4.468543
false
false
false
false
gewill/Feeyue
Feeyue/Main/Weibo/Views/StatusOnePhotoCell.swift
1
2289
// // StatusOnePhotoCell.swift // Feeyue // // Created by Will on 1/14/16. // Copyright © 2016 gewill.org. All rights reserved. // import UIKit protocol StatusOnePhotoCellDelegate { func didClickOnePhotoCell(_ cell: StatusOnePhotoCell) } class StatusOnePhotoCell: UITableViewCell { @IBOutlet var oneImageView: UIImageView! var statusId: Int = 0 var delegate: StatusOnePhotoCellDelegate? override func awakeFromNib() { super.awakeFromNib() oneImageView.isUserInteractionEnabled = true oneImageView.clipsToBounds = true let tapGesture = UITapGestureRecognizer(target: self, action: #selector(StatusOnePhotoCell.tapping(_:))) tapGesture.numberOfTapsRequired = 1 oneImageView.addGestureRecognizer(tapGesture) } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func setupImageWith(urlArray array: [String]) { if array.count == 1 { var string = array[0] if array[0].hasSuffix(".gif") == true { let playImageView = UIImageView() playImageView.image = UIImage(named: "MMVideoPreviewPlayHL") self.oneImageView.addSubview(playImageView) playImageView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ playImageView.heightAnchor.constraint(equalToConstant: 60), playImageView.widthAnchor.constraint(equalToConstant: 60), playImageView.centerXAnchor.constraint(equalTo: self.oneImageView.centerXAnchor), playImageView.centerYAnchor.constraint(equalTo: self.oneImageView.centerYAnchor) ]) string = string.replacingOccurrences(of: "/bmiddle/", with: "/or480/") } if let url = URL(string: string) { self.oneImageView.kf.setImage(with: url, placeholder: Placeholder) } } } // MARK: - StatuesOnePhotoCellDelegate @objc func tapping(_ recognizer: UIGestureRecognizer) { self.delegate?.didClickOnePhotoCell(self) } }
mit
68f63f3f089baffae55dd0214796db31
32.15942
112
0.641608
5.118568
false
false
false
false
IvoPaunov/selfie-apocalypse
Selfie apocalypse/Selfie apocalypse/SetSelfieController.swift
1
6244
// // SetSelfieController.swift // Selfie apocalypse // // Created by Ivko on 2/5/16. // Copyright © 2016 Ivo Paounov. All rights reserved. // import UIKit import Parse class SetSelfieController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate { @IBOutlet weak var inageView: UIImageView! @IBOutlet weak var slayerNameTextBox: DCBorderedTextField! let transitionManager = TransitionManager() let defaults = NSUserDefaults.standardUserDefaults() var imagePicker = UIImagePickerController() let utils = Utils() let parseService = ParseService() override func viewDidLoad() { super.viewDidLoad() imagePicker.delegate = self setupUmageView() setSlayerName() } override func viewWillDisappear(animated: Bool) { self.updateSlayerName() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func selectSelfieFromLibrary(sender: UIButton) { self.imagePicker.allowsEditing = true self.imagePicker.sourceType = .PhotoLibrary self.imagePicker.modalPresentationStyle = .FullScreen presentViewController(self.imagePicker, animated: true, completion: nil) } @IBAction func selectSelfieFromCamera(sender: UIButton) { if UIImagePickerController.availableCaptureModesForCameraDevice(.Front) != nil { self.imagePicker.allowsEditing = true self.imagePicker.sourceType = UIImagePickerControllerSourceType.Camera self.imagePicker.cameraCaptureMode = .Photo self.imagePicker.modalPresentationStyle = .FullScreen presentViewController(self.imagePicker, animated: true, completion: nil) } else { self.missingCameraMessage() } } func imagePickerController( picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { let imageURL = info[UIImagePickerControllerReferenceURL] as! NSURL let imageName = "selfie-" + String(NSDate()) + imageURL.lastPathComponent! let documentDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! as NSString let imagePath = documentDirectory.stringByAppendingPathComponent(imageName) let edditedImage = info[UIImagePickerControllerEditedImage] as! UIImage let resizedImage = utils.ResizeImage(edditedImage, targetSize: CGSizeMake(250.0, 250.0)) let data = UIImagePNGRepresentation(resizedImage) let writeOK = data!.writeToFile(imagePath, atomically: true) // TODO: Add some error handling if write is not OK! let takenFeomPathImage = UIImage(contentsOfFile: imagePath) self.inageView.image = takenFeomPathImage self.setCitcularImageView() self.saveSelectedImagePath(imagePath) picker.dismissViewControllerAnimated(true, completion: nil) } func saveSelectedImagePath(imagePath: String){ self.defaults.setValue(imagePath, forKey: DefaultKeys.Selected_Selfie_Path.rawValue) self.defaults.synchronize() } func missingCameraMessage(){ let alertVC = UIAlertController( title: "No Selfie Camera", message: "Ooops, you device has no selfie camera. Choose from library, wisely!", preferredStyle: .Alert) let okAction = UIAlertAction( title: "OK", style:.Default, handler: nil) alertVC.addAction(okAction) presentViewController( alertVC, animated: true, completion: nil) } func setupUmageView(){ var currentSelfie: UIImage? let path = defaults.stringForKey(DefaultKeys.Selected_Selfie_Path.rawValue) if path != nil{ let selfieImage = UIImage(contentsOfFile: path!) currentSelfie = selfieImage } if(currentSelfie != nil){ self.inageView.image = currentSelfie! } else{ let defaultImage = UIImage(named: "Selfie") self.inageView.image = defaultImage } self.setCitcularImageView() } func updateSlayerName(){ var nameInBox = self.slayerNameTextBox.text if nameInBox != nil { nameInBox = nameInBox?.trim() let currentSlayerName = defaults.stringForKey(DefaultKeys.Slayer_Name.rawValue) if currentSlayerName == nameInBox{ return } else { let parseService = ParseService() defaults.setValue(nameInBox, forKey: DefaultKeys.Slayer_Name.rawValue) parseService.addOrUpdeteSlayerInfo(nameInBox, supremeScore: nil) } } } func setSlayerName(){ let currentSlayerName = defaults.stringForKey(DefaultKeys.Slayer_Name.rawValue) if currentSlayerName != nil { self.slayerNameTextBox.text = currentSlayerName } } func setCitcularImageView(){ self.inageView.contentMode = .ScaleAspectFit self.inageView.layer.cornerRadius = self.inageView.layer.frame.height / 2 self.inageView.clipsToBounds = true; self.inageView.layer.borderWidth = 5 self.inageView.layer.borderColor = UIColor.init(red: 214.0/255.0, green: 255.0/255.0, blue: 104/255.0, alpha: 1.0).CGColor } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let toViewController = segue.destinationViewController as UIViewController self.transitionManager.toLeft = false toViewController.transitioningDelegate = self.transitionManager } }
mit
0097ce09d2c0ecfff22f3a792dd89f6c
32.745946
130
0.623899
5.368014
false
false
false
false
PureSwift/Bluetooth
Sources/BluetoothHCI/HCILEWriteRfPathCompensation.swift
1
3179
// // HCILEWriteRfPathCompensation.swift // Bluetooth // // Created by Alsey Coleman Miller on 6/14/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation // MARK: - Method public extension BluetoothHostControllerInterface { /// LE Write RF Path Compensation Command /// /// The command is used to indicate the RF path gain or loss between the RF transceiver and /// the antenna contributed by intermediate components. func lowEnergyWriteRfPathCompensation(rfTxPathCompensationValue: LowEnergyRfTxPathCompensationValue, rfRxPathCompensationValue: LowEnergyRfTxPathCompensationValue, timeout: HCICommandTimeout = .default) async throws { let parameters = HCILEWriteRfPathCompensation(rfTxPathCompensationValue: rfTxPathCompensationValue, rfRxPathCompensationValue: rfRxPathCompensationValue) try await deviceRequest(parameters, timeout: timeout) } } // MARK: - Command /// LE Write RF Path Compensation Command /// /// The command is used to indicate the RF path gain or loss between the RF transceiver and /// the antenna contributed by intermediate components. A positive value means a net RF path gain /// and a negative value means a net RF path loss. The RF Tx Path Compensation Value parameter /// shall be used by the Controller to calculate radiative Tx Power Level used in the TxPower field /// in the Extended Header using the following equation: /// /// Radiative Tx Power Level = Tx Power Level at RF transceiver output + RF Tx Path Compensation Value /// /// For example, if the Tx Power Level is +4 (dBm) at RF transceiver output and the RF /// Path Compensation Value is -1.5 (dB), the radiative Tx Power Level is +4+(-1.5) = 2.5 (dBm). /// /// The RF Rx Path Compensation Value parameter shall be used by the Controller to calculate /// the RSSI value reported to the Host. @frozen public struct HCILEWriteRfPathCompensation: HCICommandParameter { public static let command = HCILowEnergyCommand.writeRFPathCompensation // 0x004D public var rfTxPathCompensationValue: LowEnergyRfTxPathCompensationValue public var rfRxPathCompensationValue: LowEnergyRfTxPathCompensationValue public init(rfTxPathCompensationValue: LowEnergyRfTxPathCompensationValue, rfRxPathCompensationValue: LowEnergyRfTxPathCompensationValue) { self.rfTxPathCompensationValue = rfTxPathCompensationValue self.rfRxPathCompensationValue = rfRxPathCompensationValue } public var data: Data { let rfTxPathCompensationValueBytes = UInt16.init(bitPattern: rfTxPathCompensationValue.rawValue).littleEndian.bytes let rfRxPathCompensationValueBytes = UInt16.init(bitPattern: rfRxPathCompensationValue.rawValue).littleEndian.bytes return Data([rfTxPathCompensationValueBytes.0, rfTxPathCompensationValueBytes.1, rfRxPathCompensationValueBytes.0, rfRxPathCompensationValueBytes.1]) } }
mit
fc495e1e66d2debda1ad46821acecf60
43.760563
123
0.715859
4.265772
false
false
false
false
Syerram/asphalos
asphalos/FormTextareaCell.swift
1
2032
// // FormTextViewCell.swift // Taskffiency // // Created by Saikiran Yerram on 11/25/14. // Copyright (c) 2014 Blackhorn. All rights reserved. // import Foundation import UIKit class FormTextareaCell: FormBaseCell, UITextViewDelegate { let textView = UITextView(frame: CGRectMake(11, 0, 320 - 11 - 11, 174)) override func configure() { super.configure() selectionStyle = .None textView.setTranslatesAutoresizingMaskIntoConstraints(false) textView.font = UIFont(name: Globals.Theme.RegularFont, size: 16) textView.backgroundColor = UIColor.clearColor(); textView.delegate = self textView.text = rowDescriptor.placeholder textView.textColor = UIColor.lightGrayColor() contentView.addSubview(textView) } override class func formRowCellHeight() -> CGFloat { return 200 } override func update() { super.update() self.textView.text = self.rowDescriptor.value as? String if !self.textView.text.isEmpty { textView.textColor = UIColor.blackColor() } else { textView.text = rowDescriptor.placeholder } } func textViewShouldBeginEditing(textView: UITextView) -> Bool { if self.textView.text.isEmpty || self.textView.text == rowDescriptor.placeholder { textView.text = "" textView.textColor = UIColor.blackColor(); } return true } func textViewDidEndEditing(textView: UITextView) { if self.textView.text.isEmpty { textView.text = rowDescriptor.placeholder textView.textColor = UIColor.lightGrayColor() } textView.resignFirstResponder() } func textViewDidChange(textView: UITextView) { let trimmedText = textView.text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) rowDescriptor.value = count(trimmedText) > 0 ? textView.text : nil } }
mit
edf10a24572caff9d59c6334d023cc9c
29.80303
122
0.646161
5.144304
false
false
false
false
yarshure/Surf
Surf/HostsTableViewController.swift
1
5701
// // HostsTableViewController.swift // // // Created by networkextension on 16/5/14. // // import UIKit import SFSocket import XRuler class HostsTableViewController: SFTableViewController ,HostEditDelegate{ var config:SFConfig! override func viewDidLoad() { super.viewDidLoad() self.title = "DNS Map" //self.tableView.allowsSelectionDuringEditing = true let edit = UIBarButtonItem.init(barButtonSystemItem: .add, target: self, action: #selector(HostsTableViewController.addEditHost(_:))) navigationItem.rightBarButtonItem = edit tableView.delegate = self // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } @objc func addEditHost(_ object:AnyObject){ self.performSegue(withIdentifier:"AddEditHost", sender: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return config.hosts.count } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String { return "Function like /etc/hosts" } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath){ if editingStyle == .delete { // Delete the row from the data source if indexPath.row < config.hosts.count{ config.hosts.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath as IndexPath], with: .fade) }else { tableView.reloadData() } } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "hosts", for: indexPath as IndexPath) // Configure the cell... let x :DNSRecord = config.hosts[indexPath.row] cell.textLabel?.text = x.name if let ip = x.ip() { cell.detailTextLabel?.text = ip } return cell } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. if segue.identifier == "AddEditHost"{ guard let vc = segue.destination as? HostEditTableViewController else{return} //barCodeController.useCamera = self.useCamera if let s = sender{ guard let indexPath = self.tableView.indexPath(for: s as! UITableViewCell) else {return } vc.record = config.hosts[indexPath.row] vc.title = "Record" }else { vc.title = "New Record" vc.new = true } vc.delegate = self } } func hostDidChange(controller: HostEditTableViewController,new:Bool){ if new{ config.hosts.insert(controller.record, at: 0) } tableView.reloadData() } }
bsd-3-clause
e3536dd3e2ce59a57bfdd5dee17be659
34.63125
157
0.636029
5.353052
false
true
false
false
gali8/G8MaterialKitTextField
MKTextField/MKLabel.swift
1
2989
// // MKLabel.swift // MaterialKit // // Created by Le Van Nghia on 11/29/14. // Copyright (c) 2014 Le Van Nghia. All rights reserved. // import UIKit class MKLabel: UILabel { @IBInspectable var maskEnabled: Bool = true { didSet { mkLayer.enableMask(maskEnabled) } } @IBInspectable var rippleLocation: MKRippleLocation = .TapLocation { didSet { mkLayer.rippleLocation = rippleLocation } } @IBInspectable var aniDuration: Float = 0.65 @IBInspectable var circleAniTimingFunction: MKTimingFunction = .Linear @IBInspectable var backgroundAniTimingFunction: MKTimingFunction = .Linear @IBInspectable var backgroundAniEnabled: Bool = true { didSet { if !backgroundAniEnabled { mkLayer.enableOnlyCircleLayer() } } } @IBInspectable var circleGrowRatioMax: Float = 0.9 { didSet { mkLayer.circleGrowRatioMax = circleGrowRatioMax } } @IBInspectable var cornerRadius: CGFloat = 2.5 { didSet { layer.cornerRadius = cornerRadius mkLayer.setMaskLayerCornerRadius(cornerRadius) } } // color @IBInspectable var circleLayerColor: UIColor = UIColor(white: 0.45, alpha: 0.5) { didSet { mkLayer.setCircleLayerColor(circleLayerColor) } } @IBInspectable var backgroundLayerColor: UIColor = UIColor(white: 0.75, alpha: 0.25) { didSet { mkLayer.setBackgroundLayerColor(backgroundLayerColor) } } override var bounds: CGRect { didSet { mkLayer.superLayerDidResize() } } private lazy var mkLayer: MKLayer = MKLayer(superLayer: self.layer) required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } override init(frame: CGRect) { super.init(frame: frame) setup() } private func setup() { mkLayer.setCircleLayerColor(circleLayerColor) mkLayer.setBackgroundLayerColor(backgroundLayerColor) mkLayer.setMaskLayerCornerRadius(cornerRadius) } func animateRipple(location: CGPoint? = nil) { if let point = location { mkLayer.didChangeTapLocation(point) } else if rippleLocation == .TapLocation { rippleLocation = .Center } mkLayer.animateScaleForCircleLayer(0.65, toScale: 1.0, timingFunction: circleAniTimingFunction, duration: CFTimeInterval(aniDuration)) mkLayer.animateAlphaForBackgroundLayer(backgroundAniTimingFunction, duration: CFTimeInterval(aniDuration)) } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { super.touchesBegan(touches, withEvent: event) if let firstTouch = touches.first { let location = firstTouch.locationInView(self) animateRipple(location) } } }
mit
588024032e7cfdb223ca4a55678a743f
30.135417
142
0.632653
5.074703
false
false
false
false
nathawes/swift
test/Generics/conditional_conformances_literals.swift
5
5822
// RUN: %target-typecheck-verify-swift // rdar://problem/38461036 , https://bugs.swift.org/browse/SR-7192 and highlights the real problem in https://bugs.swift.org/browse/SR-6941 protocol SameType {} protocol Conforms {} struct Works: Hashable, Conforms {} struct Fails: Hashable {} extension Array: SameType where Element == Works {} // expected-note@-1 3 {{requirement from conditional conformance of '[Fails]' to 'SameType'}} extension Dictionary: SameType where Value == Works {} // expected-note@-1 3 {{requirement from conditional conformance of '[Int : Fails]' to 'SameType'}} extension Array: Conforms where Element: Conforms {} // expected-note@-1 7 {{requirement from conditional conformance of '[Fails]' to 'Conforms'}} extension Dictionary: Conforms where Value: Conforms {} // expected-note@-1 5 {{requirement from conditional conformance of '[Int : Fails]' to 'Conforms'}} // expected-note@-2 2 {{requirement from conditional conformance of '[Int : Conforms]' to 'Conforms'}} let works = Works() let fails = Fails() func arraySameType() { let arrayWorks = [works] let arrayFails = [fails] let _: SameType = [works] let _: SameType = [fails] // expected-error@-1 {{cannot convert value of type 'Fails' to expected element type 'Works'}} let _: SameType = arrayWorks let _: SameType = arrayFails // expected-error@-1 {{protocol 'SameType' requires the types 'Fails' and 'Works' be equivalent}} let _: SameType = [works] as [Works] let _: SameType = [fails] as [Fails] // expected-error@-1 {{protocol 'SameType' requires the types 'Fails' and 'Works' be equivalent}} let _: SameType = [works] as SameType let _: SameType = [fails] as SameType // expected-error@-1 {{cannot convert value of type 'Fails' to expected element type 'Works'}} let _: SameType = arrayWorks as SameType let _: SameType = arrayFails as SameType // expected-error@-1 {{protocol 'SameType' requires the types 'Fails' and 'Works' be equivalent}} } func dictionarySameType() { let dictWorks: [Int : Works] = [0 : works] let dictFails: [Int : Fails] = [0 : fails] let _: SameType = [0 : works] let _: SameType = [0 : fails] // expected-error@-1 {{cannot convert value of type 'Fails' to expected dictionary value type 'Works'}} let _: SameType = dictWorks let _: SameType = dictFails // expected-error@-1 {{protocol 'SameType' requires the types 'Fails' and 'Works' be equivalent}} let _: SameType = [0 : works] as [Int : Works] let _: SameType = [0 : fails] as [Int : Fails] // expected-error@-1 {{protocol 'SameType' requires the types 'Fails' and 'Works' be equivalent}} let _: SameType = [0 : works] as SameType let _: SameType = [0 : fails] as SameType // expected-error@-1 {{cannot convert value of type 'Fails' to expected dictionary value type 'Works'}} let _: SameType = dictWorks as SameType let _: SameType = dictFails as SameType // expected-error@-1 {{protocol 'SameType' requires the types 'Fails' and 'Works' be equivalent}} } func arrayConforms() { let arrayWorks = [works] let arrayFails = [fails] let _: Conforms = [works] let _: Conforms = [fails] // expected-error@-1 {{protocol 'Conforms' requires that 'Fails' conform to 'Conforms'}} let _: Conforms = arrayWorks let _: Conforms = arrayFails // expected-error@-1 {{protocol 'Conforms' requires that 'Fails' conform to 'Conforms'}} let _: Conforms = [works] as [Works] let _: Conforms = [fails] as [Fails] // expected-error@-1 {{protocol 'Conforms' requires that 'Fails' conform to 'Conforms'}} let _: Conforms = [works] as Conforms let _: Conforms = [fails] as Conforms // expected-error@-1 {{protocol 'Conforms' requires that 'Fails' conform to 'Conforms'}} let _: Conforms = arrayWorks as Conforms let _: Conforms = arrayFails as Conforms // expected-error@-1 {{protocol 'Conforms' requires that 'Fails' conform to 'Conforms'}} } func dictionaryConforms() { let dictWorks: [Int : Works] = [0 : works] let dictFails: [Int : Fails] = [0 : fails] let _: Conforms = [0 : works] let _: Conforms = [0 : fails] // expected-error@-1 {{protocol 'Conforms' requires that 'Fails' conform to 'Conforms'}} let _: Conforms = dictWorks let _: Conforms = dictFails // expected-error@-1 {{protocol 'Conforms' requires that 'Fails' conform to 'Conforms'}} let _: Conforms = [0 : works] as [Int : Works] let _: Conforms = [0 : fails] as [Int : Fails] // expected-error@-1 {{protocol 'Conforms' requires that 'Fails' conform to 'Conforms'}} let _: Conforms = [0 : works] as Conforms let _: Conforms = [0 : fails] as Conforms // expected-error@-1 {{protocol 'Conforms' requires that 'Fails' conform to 'Conforms'}} let _: Conforms = dictWorks as Conforms let _: Conforms = dictFails as Conforms // expected-error@-1 {{protocol 'Conforms' requires that 'Fails' conform to 'Conforms'}} } func combined() { let _: Conforms = [[0: [1 : [works]]]] let _: Conforms = [[0: [1 : [fails]]]] // expected-error@-1 {{protocol 'Conforms' requires that 'Fails' conform to 'Conforms'}} // Needs self conforming protocols: let _: Conforms = [[0: [1 : [works]] as Conforms]] // expected-error@-1 {{protocol 'Conforms' as a type cannot conform to the protocol itself; only concrete types such as structs, enums and classes can conform to protocols}} let _: Conforms = [[0: [1 : [fails]] as Conforms]] // expected-error@-1 {{protocol 'Conforms' requires that 'Fails' conform to 'Conforms'}} // expected-error@-2 {{protocol 'Conforms' as a type cannot conform to the protocol itself; only concrete types such as structs, enums and classes can conform to protocols}} }
apache-2.0
add866499290ec20180c0cc8157f9cd3
41.808824
177
0.6618
3.96594
false
false
false
false
xedin/swift
test/IRGen/subclass.swift
2
2969
// RUN: %target-swift-frontend -enable-objc-interop -primary-file %s -emit-ir | %FileCheck %s -check-prefix CHECK -check-prefix CHECK-%target-import-type // REQUIRES: CPU=x86_64 // CHECK-DAG: %swift.refcounted = type { // CHECK-DAG: [[TYPE:%swift.type]] = type // CHECK-DAG: [[OBJC_CLASS:%objc_class]] = type { // CHECK-DAG: [[OPAQUE:%swift.opaque]] = type // CHECK-DAG: [[A:%T8subclass1AC]] = type <{ [[REF:%swift.refcounted]], %TSi, %TSi }> // CHECK-DAG: [[INT:%TSi]] = type <{ i64 }> // CHECK-DAG: [[B:%T8subclass1BC]] = type <{ [[REF]], [[INT]], [[INT]], [[INT]] }> // CHECK: @_DATA__TtC8subclass1A = private constant {{.* } }}{ // CHECK: @"$s8subclass1ACMf" = internal global [[A_METADATA:<{.* }>]] <{ // CHECK-SAME: void ([[A]]*)* @"$s8subclass1ACfD", // CHECK-DIRECT-SAME: i8** @"$sBoWV", // CHECK-INDIRECT-SAME: i8** null, // CHECK-SAME: i64 ptrtoint ([[OBJC_CLASS]]* @"$s8subclass1ACMm" to i64), // CHECK-DIRECT-SAME: [[OBJC_CLASS]]* @"OBJC_CLASS_$_{{(_TtCs12_)?}}SwiftObject", // CHECK-INDIRECT-SAME: [[TYPE]]* null, // CHECK-SAME: [[OPAQUE]]* @_objc_empty_cache, // CHECK-SAME: [[OPAQUE]]* null, // CHECK-SAME: i64 add (i64 ptrtoint ({ {{.*}} }* @_DATA__TtC8subclass1A to i64), i64 [[IS_SWIFT_BIT:1|2]]), // CHECK-SAME: i64 ([[A]]*)* @"$s8subclass1AC1fSiyF", // CHECK-SAME: [[A]]* ([[TYPE]]*)* @"$s8subclass1AC1gACyFZ" // CHECK-SAME: }> // CHECK: @_DATA__TtC8subclass1B = private constant {{.* } }}{ // CHECK: @"$s8subclass1BCMf" = internal global <{ {{.*}} }> <{ // CHECK-SAME: void ([[B]]*)* @"$s8subclass1BCfD", // CHECK-DIRECT-SAME: i8** @"$sBoWV", // CHECK-INDIRECT-SAME: i8** null, // CHECK-SAME: i64 ptrtoint ([[OBJC_CLASS]]* @"$s8subclass1BCMm" to i64), // CHECK-DIRECT-SAME: [[TYPE]]* {{.*}} @"$s8subclass1ACMf", // CHECK-INDIRECT-SAME: [[TYPE]]* null, // CHECK-SAME: [[OPAQUE]]* @_objc_empty_cache, // CHECK-SAME: [[OPAQUE]]* null, // CHECK-SAME: i64 add (i64 ptrtoint ({ {{.*}} }* @_DATA__TtC8subclass1B to i64), i64 [[IS_SWIFT_BIT]]), // CHECK-SAME: i64 ([[B]]*)* @"$s8subclass1BC1fSiyF", // CHECK-SAME: [[A]]* ([[TYPE]]*)* @"$s8subclass1AC1gACyFZ" // CHECK-SAME: }> // CHECK-DIRECT: @objc_classes = internal global [2 x i8*] [i8* {{.*}} @"$s8subclass1ACN" {{.*}}, i8* {{.*}} @"$s8subclass1BCN" {{.*}}] class A { var x = 0 var y = 0 func f() -> Int { return x } class func g() -> A { return A() } init() { } } class B : A { var z : Int = 10 override func f() -> Int { return z } } class G<T> : A { } // Ensure that downcasts to generic types instantiate generic metadata instead // of trying to reference global metadata. <rdar://problem/14265663> // CHECK: define hidden swiftcc %T8subclass1GCySiG* @"$s8subclass9a_to_gint1aAA1GCySiGAA1AC_tF"(%T8subclass1AC*) {{.*}} { func a_to_gint(a: A) -> G<Int> { // CHECK: call swiftcc %swift.metadata_response @"$s8subclass1GCySiGMa"(i64 0) // CHECK: call i8* @swift_dynamicCastClassUnconditional return a as! G<Int> } // CHECK: }
apache-2.0
af13e3b2bcef7b171f732936438dda87
41.414286
153
0.598181
2.86583
false
false
false
false
IngmarStein/swift
test/Generics/function_defs.swift
1
10952
// RUN: %target-parse-verify-swift //===----------------------------------------------------------------------===// // Type-check function definitions //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// // Basic type checking //===----------------------------------------------------------------------===// protocol EqualComparable { func isEqual(_ other: Self) -> Bool } func doCompare<T : EqualComparable, U : EqualComparable>(_ t1: T, t2: T, u: U) -> Bool { var b1 = t1.isEqual(t2) if b1 { return true } return t1.isEqual(u) // expected-error {{cannot invoke 'isEqual' with an argument list of type '(U)'}} expected-note {{expected an argument list of type '(T)'}} } protocol MethodLessComparable { func isLess(_ other: Self) -> Bool } func min<T : MethodLessComparable>(_ x: T, y: T) -> T { if (y.isLess(x)) { return y } return x } //===----------------------------------------------------------------------===// // Interaction with existential types //===----------------------------------------------------------------------===// func existential<T : EqualComparable, U : EqualComparable>(_ t1: T, t2: T, u: U) { var eqComp : EqualComparable = t1 // expected-error{{protocol 'EqualComparable' can only be used as a generic constraint}} eqComp = u if t1.isEqual(eqComp) {} // expected-error{{cannot invoke 'isEqual' with an argument list of type '(EqualComparable)'}} // expected-note @-1 {{expected an argument list of type '(T)'}} if eqComp.isEqual(t2) {} // expected-error{{member 'isEqual' cannot be used on value of protocol type 'EqualComparable'; use a generic constraint instead}} } protocol OtherEqualComparable { func isEqual(_ other: Self) -> Bool } func otherExistential<T : EqualComparable>(_ t1: T) { var otherEqComp : OtherEqualComparable = t1 // expected-error{{value of type 'T' does not conform to specified type 'OtherEqualComparable'}} expected-error{{protocol 'OtherEqualComparable' can only be used as a generic constraint}} otherEqComp = t1 // expected-error{{value of type 'T' does not conform to 'OtherEqualComparable' in assignment}} _ = otherEqComp var otherEqComp2 : OtherEqualComparable // expected-error{{protocol 'OtherEqualComparable' can only be used as a generic constraint}} otherEqComp2 = t1 // expected-error{{value of type 'T' does not conform to 'OtherEqualComparable' in assignment}} _ = otherEqComp2 _ = t1 as EqualComparable & OtherEqualComparable // expected-error{{'T' is not convertible to 'EqualComparable & OtherEqualComparable'; did you mean to use 'as!' to force downcast?}} {{10-12=as!}} expected-error{{protocol 'OtherEqualComparable' can only be used as a generic constraint}} expected-error{{protocol 'EqualComparable' can only be used as a generic constraint}} } protocol Runcible { func runce<A>(_ x: A) func spoon(_ x: Self) } func testRuncible(_ x: Runcible) { // expected-error{{protocol 'Runcible' can only be used as a generic constraint}} x.runce(5) } //===----------------------------------------------------------------------===// // Overloading //===----------------------------------------------------------------------===// protocol Overload { associatedtype A associatedtype B func getA() -> A func getB() -> B func f1(_: A) -> A func f1(_: B) -> B func f2(_: Int) -> A // expected-note{{found this candidate}} func f2(_: Int) -> B // expected-note{{found this candidate}} func f3(_: Int) -> Int // expected-note {{found this candidate}} func f3(_: Float) -> Float // expected-note {{found this candidate}} func f3(_: Self) -> Self // expected-note {{found this candidate}} var prop : Self { get } } func testOverload<Ovl : Overload, OtherOvl : Overload>(_ ovl: Ovl, ovl2: Ovl, other: OtherOvl) { var a = ovl.getA() var b = ovl.getB() // Overloading based on arguments _ = ovl.f1(a) a = ovl.f1(a) _ = ovl.f1(b) b = ovl.f1(b) // Overloading based on return type a = ovl.f2(17) b = ovl.f2(17) ovl.f2(17) // expected-error{{ambiguous use of 'f2'}} // Check associated types from different objects/different types. a = ovl2.f2(17) a = ovl2.f1(a) other.f1(a) // expected-error{{cannot invoke 'f1' with an argument list of type '(Ovl.A)'}} // expected-note @-1 {{overloads for 'f1' exist with these partially matching parameter lists: (Self.A), (Self.B)}} // Overloading based on context var f3i : (Int) -> Int = ovl.f3 var f3f : (Float) -> Float = ovl.f3 var f3ovl_1 : (Ovl) -> Ovl = ovl.f3 var f3ovl_2 : (Ovl) -> Ovl = ovl2.f3 var f3ovl_3 : (Ovl) -> Ovl = other.f3 // expected-error{{ambiguous reference to member 'f3'}} var f3i_unbound : (Ovl) -> (Int) -> Int = Ovl.f3 var f3f_unbound : (Ovl) -> (Float) -> Float = Ovl.f3 var f3f_unbound2 : (OtherOvl) -> (Float) -> Float = OtherOvl.f3 var f3ovl_unbound_1 : (Ovl) -> (Ovl) -> Ovl = Ovl.f3 var f3ovl_unbound_2 : (OtherOvl) -> (OtherOvl) -> OtherOvl = OtherOvl.f3 } //===----------------------------------------------------------------------===// // Subscripting //===----------------------------------------------------------------------===// protocol Subscriptable { associatedtype Index associatedtype Value func getIndex() -> Index func getValue() -> Value subscript (index : Index) -> Value { get set } } protocol IntSubscriptable { associatedtype ElementType func getElement() -> ElementType subscript (index : Int) -> ElementType { get } } func subscripting<T : Subscriptable & IntSubscriptable>(_ t: T) { var index = t.getIndex() var value = t.getValue() var element = t.getElement() value = t[index] t[index] = value // expected-error{{cannot assign through subscript: 't' is a 'let' constant}} element = t[17] t[42] = element // expected-error{{cannot assign through subscript: subscript is get-only}} // Suggests the Int form because we prefer concrete matches to generic matches in diagnosis. t[value] = 17 // expected-error{{cannot convert value of type 'T.Value' to expected argument type 'Int'}} } //===----------------------------------------------------------------------===// // Static functions //===----------------------------------------------------------------------===// protocol StaticEq { static func isEqual(_ x: Self, y: Self) -> Bool } func staticEqCheck<T : StaticEq, U : StaticEq>(_ t: T, u: U) { if t.isEqual(t, t) { return } // expected-error{{static member 'isEqual' cannot be used on instance of type 'T'}} if T.isEqual(t, y: t) { return } if U.isEqual(u, y: u) { return } T.isEqual(t, y: u) // expected-error{{cannot invoke 'isEqual' with an argument list of type '(T, y: U)'}} expected-note {{expected an argument list of type '(T, y: T)'}} } //===----------------------------------------------------------------------===// // Operators //===----------------------------------------------------------------------===// protocol Ordered { static func <(lhs: Self, rhs: Self) -> Bool } func testOrdered<T : Ordered>(_ x: T, y: Int) { if y < 100 || 500 < y { return } if x < x { return } } //===----------------------------------------------------------------------===// // Requires clauses //===----------------------------------------------------------------------===// func conformanceViaRequires<T>(_ t1: T, t2: T) -> Bool where T : EqualComparable, T : MethodLessComparable { let b1 = t1.isEqual(t2) if b1 || t1.isLess(t2) { return true } } protocol GeneratesAnElement { associatedtype Element : EqualComparable func makeIterator() -> Element } protocol AcceptsAnElement { associatedtype Element : MethodLessComparable func accept(_ e : Element) } func impliedSameType<T : GeneratesAnElement>(_ t: T) where T : AcceptsAnElement { t.accept(t.makeIterator()) let e = t.makeIterator(), e2 = t.makeIterator() if e.isEqual(e2) || e.isLess(e2) { return } } protocol GeneratesAssoc1 { associatedtype Assoc1 : EqualComparable func get() -> Assoc1 } protocol GeneratesAssoc2 { associatedtype Assoc2 : MethodLessComparable func get() -> Assoc2 } func simpleSameType<T : GeneratesAssoc1, U : GeneratesAssoc2> (_ t: T, u: U) -> Bool where T.Assoc1 == U.Assoc2 { return t.get().isEqual(u.get()) || u.get().isLess(t.get()) } protocol GeneratesMetaAssoc1 { associatedtype MetaAssoc1 : GeneratesAnElement func get() -> MetaAssoc1 } protocol GeneratesMetaAssoc2 { associatedtype MetaAssoc2 : AcceptsAnElement func get() -> MetaAssoc2 } func recursiveSameType <T : GeneratesMetaAssoc1, U : GeneratesMetaAssoc2, V : GeneratesAssoc1> (_ t: T, u: U) where T.MetaAssoc1 == V.Assoc1, V.Assoc1 == U.MetaAssoc2 { t.get().accept(t.get().makeIterator()) let e = t.get().makeIterator(), e2 = t.get().makeIterator() if e.isEqual(e2) || e.isLess(e2) { return } } // <rdar://problem/13985164> protocol P1 { associatedtype Element } protocol P2 { associatedtype AssocP1 : P1 func getAssocP1() -> AssocP1 } func beginsWith2<E0: P1, E1: P1>(_ e0: E0, _ e1: E1) -> Bool where E0.Element == E1.Element, E0.Element : EqualComparable { } func beginsWith3<S0: P2, S1: P2>(_ seq1: S0, _ seq2: S1) -> Bool where S0.AssocP1.Element == S1.AssocP1.Element, S1.AssocP1.Element : EqualComparable { return beginsWith2(seq1.getAssocP1(), seq2.getAssocP1()) } // FIXME: Test same-type constraints that try to equate things we // don't want to equate, e.g., T == U. //===----------------------------------------------------------------------===// // Bogus requirements //===----------------------------------------------------------------------===// func nonTypeReq<T>(_: T) where T : Wibble {} // expected-error{{use of undeclared type 'Wibble'}} func badProtocolReq<T>(_: T) where T : Int {} // expected-error{{type 'T' constrained to non-protocol type 'Int'}} func nonTypeSameType<T>(_: T) where T == Wibble {} // expected-error{{use of undeclared type 'Wibble'}} func nonTypeSameType2<T>(_: T) where Wibble == T {} // expected-error{{use of undeclared type 'Wibble'}} func sameTypeEq<T>(_: T) where T = T {} // expected-error{{use '==' for same-type requirements rather than '='}} {{34-35===}} func badTypeConformance1<T>(_: T) where Int : EqualComparable {} // expected-error{{type 'Int' in conformance requirement does not refer to a generic parameter or associated type}} func badTypeConformance2<T>(_: T) where T.Blarg : EqualComparable { } // expected-error{{'Blarg' is not a member type of 'T'}} func badSameType<T, U : GeneratesAnElement, V>(_ : T) // expected-error{{generic parameter 'V' is not used in function signature}} where T == U.Element, U.Element == V {} // expected-error{{same-type requirement makes generic parameters 'T' and 'V' equivalent}}
apache-2.0
6d06996ed4e72b65b3110ec3b5277b21
35.751678
375
0.579529
4.005852
false
false
false
false
xcodeswift/xcproj
Tests/XcodeProjTests/Objects/BuildPhase/PBXShellScriptBuildPhaseTests.swift
1
3471
import Foundation import XCTest @testable import XcodeProj final class PBXShellScriptBuildPhaseTests: XCTestCase { func test_returnsTheCorrectIsa() { XCTAssertEqual(PBXShellScriptBuildPhase.isa, "PBXShellScriptBuildPhase") } func test_write_showEnvVarsInLog() throws { let show = PBXShellScriptBuildPhase(showEnvVarsInLog: true) let doNotShow = PBXShellScriptBuildPhase(showEnvVarsInLog: false) let proj = PBXProj.fixture() let (_, showPlistValue) = try show.plistKeyAndValue(proj: proj, reference: "ref") let (_, doNotShowPlistValue) = try doNotShow.plistKeyAndValue(proj: proj, reference: "ref") if case let PlistValue.dictionary(showDictionary) = showPlistValue, case let PlistValue.dictionary(doNotShowDictionary) = doNotShowPlistValue { XCTAssertNil(showDictionary["showEnvVarsInLog"]) XCTAssertEqual(doNotShowDictionary["showEnvVarsInLog"]?.string, "0") } else { XCTAssert(false) } } func test_write_alwaysOutOfDate() throws { // Given let alwaysOutOfDateNotPresent = PBXShellScriptBuildPhase() let alwaysOutOfDateFalse = PBXShellScriptBuildPhase(alwaysOutOfDate: false) let alwaysOutOfDateTrue = PBXShellScriptBuildPhase(alwaysOutOfDate: true) let proj = PBXProj.fixture() // When guard case let .dictionary(valuesWhenNotPresent) = try alwaysOutOfDateNotPresent.plistKeyAndValue(proj: proj, reference: "ref").value, case let .dictionary(valuesWhenFalse) = try alwaysOutOfDateFalse.plistKeyAndValue(proj: proj, reference: "ref").value, case let .dictionary(valuesWhenTrue) = try alwaysOutOfDateTrue.plistKeyAndValue(proj: proj, reference: "ref").value else { XCTFail("Plist should contain dictionary") return } // Then XCTAssertFalse(valuesWhenNotPresent.keys.contains("alwaysOutOfDate")) XCTAssertFalse(valuesWhenFalse.keys.contains("alwaysOutOfDate")) XCTAssertEqual(valuesWhenTrue["alwaysOutOfDate"], "1") } func test_write_dependencyFile() throws { let discoveryPath = "$(DERIVED_FILE_DIR)/target.d" let discovery = PBXShellScriptBuildPhase(dependencyFile: discoveryPath) let proj = PBXProj.fixture() let (_, discoveryPlistValue) = try discovery.plistKeyAndValue(proj: proj, reference: "ref") XCTAssertEqual(discoveryPlistValue.dictionary?["dependencyFile"]?.string, CommentedString(discoveryPath)) } func test_skips_nilDependencyFile() throws { let noDiscovery = PBXShellScriptBuildPhase(dependencyFile: nil) let proj = PBXProj.fixture() let (_, noDiscoveryPlistValue) = try noDiscovery.plistKeyAndValue(proj: proj, reference: "ref") XCTAssertNil(noDiscoveryPlistValue.dictionary?["dependencyFile"]) } func test_notequal_differentDependencyFile() throws { let noDiscovery = PBXShellScriptBuildPhase(dependencyFile: nil) let discovery = PBXShellScriptBuildPhase(dependencyFile: "$(DERIVED_FILE_DIR)/target.d") XCTAssertNotEqual(noDiscovery, discovery) } private func testDictionary() -> [String: Any] { [ "files": ["files"], "inputPaths": ["input"], "outputPaths": ["output"], "shellPath": "shellPath", "shellScript": "shellScript", ] } }
mit
4426475447f67ec4a462e8b5fe3550e2
40.321429
140
0.681648
4.646586
false
true
false
false
joltguy/SwiftStructures
Source/Structures/extensions.swift
1
2804
// // extensions.swift // SwiftStructures // // Created by Wayne Bishop on 8/20/14. // Copyright (c) 2014 Arbutus Software Inc. All rights reserved. // import Foundation extension String { //compute the length of string var length: Int { return self.characters.count } //returns characters of a string up to a specified index func substringToIndex(to: Int) -> String { return self.substringToIndex(self.startIndex.advancedBy(to)) } //return a character at a specific index func stringAtIndex(position: Int) -> String { return String(Array(self.characters)[position]) } //replace string content func replace(string:String, replacement:String) -> String { return self.stringByReplacingOccurrencesOfString(string, withString: replacement) } //removes empty string content func removeWhitespace() -> String { return self.replace(" ", replacement: "") } //insert a string at a specified index func insertSubstring(string:String, index:Int) -> String { return String(self.characters.prefix(index)) + string + String(self.characters.suffix(self.characters.count-index)) } //convert a string into a character array func characters() ->Array<Character>! { return Array(self.characters) } //reverse string order func reverse() -> String! { /* notes: While this operation would normally be done 'in-place', there are limited functions for manipulating native Swift strings. Even there is a native Array.reverse() method, this has been added as an example interview question. */ //convert to array var characters = self.characters() var findex: Int = 0 var bindex: Int = characters.count - 1 while findex < bindex { //swap positions - inout parameters swap(&characters[findex], &characters[bindex]) //update values findex += 1 bindex -= 1 } //end while return String(characters) } } extension Int { //iterates the closure body a specified number of times func times(closure:(Int)->Void) { for i in 0...self { closure(i) } } } extension Array { //returns the middle index func midIndex() -> Int { return Int(floor(Double(self.count / 2))) } //returns the first index func minIndex() ->Int { return 0 } //returns the max index func maxIndex() ->Int { return self.count - 1 } }
mit
131aaece77c1faa79ceb6ef7b1e33d9e
20.242424
124
0.57525
4.776831
false
false
false
false
DianQK/TransitionTreasury
TransitionAnimation/PopTipTransitionAnimation.swift
1
3988
// // PopTipTransitionAnimation.swift // TransitionTreasury // // Created by DianQK on 12/29/15. // Copyright © 2016 TransitionTreasury. All rights reserved. // import TransitionTreasury /// Pop Your Tip ViewController. open class PopTipTransitionAnimation: NSObject, TRViewControllerAnimatedTransitioning { open var transitionStatus: TransitionStatus open var transitionContext: UIViewControllerContextTransitioning? open var cancelPop: Bool = false open var interacting: Bool = false fileprivate var mainVC: UIViewController? lazy fileprivate var tapGestureRecognizer: UITapGestureRecognizer = { let tap = UITapGestureRecognizer(target: self, action: #selector(PopTipTransitionAnimation.tapDismiss(_:))) return tap }() lazy fileprivate var maskView: UIView = { let view = UIView() view.backgroundColor = UIColor.black return view }() open fileprivate(set) var visibleHeight: CGFloat fileprivate let bounce: Bool public init(visibleHeight height: CGFloat, bounce: Bool = false, status: TransitionStatus = .present) { transitionStatus = status visibleHeight = height self.bounce = bounce super.init() } open func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.3 } open func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { self.transitionContext = transitionContext var fromVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) var toVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) let containView = transitionContext.containerView let screenBounds = UIScreen.main.bounds var startFrame = screenBounds.offsetBy(dx: 0, dy: screenBounds.size.height) var finalFrame = screenBounds.offsetBy(dx: 0, dy: screenBounds.height - visibleHeight) var startOpacity: CGFloat = 0 var finalOpacity: CGFloat = 0.3 containView.addSubview(fromVC!.view) if transitionStatus == .dismiss { swap(&fromVC, &toVC) swap(&startFrame, &finalFrame) swap(&startOpacity, &finalOpacity) } else if transitionStatus == .present { let bottomView = UIView(frame: screenBounds) bottomView.layer.contents = { let scale = UIScreen.main.scale UIGraphicsBeginImageContextWithOptions(fromVC!.view.bounds.size, true, scale) fromVC!.view.layer.render(in: UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image?.cgImage }() bottomView.addGestureRecognizer(tapGestureRecognizer) containView.addSubview(bottomView) maskView.frame = screenBounds maskView.alpha = startOpacity bottomView.addSubview(maskView) mainVC = fromVC } toVC?.view.layer.frame = startFrame containView.addSubview(toVC!.view) UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0, usingSpringWithDamping: (bounce ? 0.8 : 1), initialSpringVelocity: (bounce ? 0.6 : 1), options: .curveEaseInOut, animations: { toVC?.view.layer.frame = finalFrame self.maskView.alpha = finalOpacity }) { finished in transitionContext.completeTransition(!transitionContext.transitionWasCancelled) } } @objc func tapDismiss(_ tap: UITapGestureRecognizer) { mainVC?.presentedViewController?.transitioningDelegate = nil mainVC?.dismiss(animated: true, completion: nil) } }
mit
e41969c849f05853f242a7bd9fa29e5e
36.971429
219
0.662654
5.897929
false
false
false
false
oghuz/PitchPerfect
PitchPerfect/AudioRecordingVC.swift
1
3333
// // ViewController.swift // PitchPerfect // // Created by osmanjan omar on 10/6/16. // Copyright © 2016 osmanjan omar. All rights reserved. // import UIKit import AVFoundation class AudioRecordingVC: UIViewController, AVAudioRecorderDelegate{ @IBOutlet var recordingStatus: UILabel! @IBOutlet var recordButtonOutlet: UIButton! @IBOutlet var stopRecordingButtonOutlet: UIButton! var recordAudio : AVAudioRecorder! let colors = [UIColor.white, .black, .green, .lightGray, .cyan] let audioSession = AVAudioSession.sharedInstance() override func viewDidLoad() { super.viewDidLoad() let randomIndex = Int(arc4random_uniform(UInt32(colors.count))) self.view.backgroundColor = colors[randomIndex] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) stopRecordingButtonOutlet.isEnabled = false } @IBAction func recordAudio(_ sender: AnyObject) { self.audioRecord() self.setUpButtons(recording: true) } @IBAction func stopRecording(_ sender: AnyObject) { recordAudio.stop() self.setUpButtons(recording: false) } func setUpButtons(recording:Bool) { // button label change based on which button pressed recordingStatus.text = recording ? "Now Recording" : "Tap to Record" // enable and disable buttons recordButtonOutlet.isEnabled = !recording stopRecordingButtonOutlet.isEnabled = recording } func audioRecord(){ let settings = [ AVFormatIDKey : Int(kAudioFormatMPEG4AAC), AVSampleRateKey : 12000, AVNumberOfChannelsKey : 1, AVEncoderAudioQualityKey:AVAudioQuality.max.rawValue ] let documentDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) let documentPathMember = documentDir[0] let filePathName = documentPathMember.appendingPathComponent("RecordedAudio.m4a") try! audioSession.setCategory( AVAudioSessionCategoryPlayAndRecord, with:AVAudioSessionCategoryOptions.defaultToSpeaker) try! audioSession.setActive(true) try! recordAudio = AVAudioRecorder.init(url: filePathName, settings: settings) recordAudio.delegate = self recordAudio.isMeteringEnabled = true recordAudio.prepareToRecord() recordAudio.record() } func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) { if flag{ self.performSegue(withIdentifier: "PlayBack", sender: recordAudio.url) print("Did finish recoeding") } else{ print("Error recording audio") } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let playAudioBack = segue.destination as! PlayBackVC let recordedAudioURL = sender as! NSURL playAudioBack.recordedAudioURL = recordedAudioURL } }
gpl-3.0
862e636564133a7bd316f2e05b517279
27.237288
128
0.641957
5.374194
false
false
false
false
russbishop/swift
test/SourceKit/CodeComplete/complete_sort_order.swift
1
6070
func foo(a a: String) {} func foo(a a: Int) {} func foo(b b: Int) {} func test() { let x = 1 } // XFAIL: broken_std_regex // RUN: %sourcekitd-test -req=complete -req-opts=hidelowpriority=0 -pos=7:1 %s -- %s > %t.orig // RUN: FileCheck -check-prefix=NAME %s < %t.orig // Make sure the order is as below, foo(Int) should come before foo(String). // NAME: key.description: "#column" // NAME: key.description: "AbsoluteValuable" // NAME: key.description: "foo(a: Int)" // NAME-NOT: key.description // NAME: key.description: "foo(a: String)" // NAME-NOT: key.description // NAME: key.description: "foo(b: Int)" // NAME: key.description: "test()" // NAME: key.description: "x" // RUN: %sourcekitd-test -req=complete.open -pos=7:1 -req-opts=hidelowpriority=0,hideunderscores=0 %s -- %s > %t.default // RUN: %sourcekitd-test -req=complete.open -pos=7:1 -req-opts=sort.byname=0,hidelowpriority=0,hideunderscores=0 %s -- %s > %t.on // RUN: %sourcekitd-test -req=complete.open -pos=7:1 -req-opts=sort.byname=1,hidelowpriority=0,hideunderscores=0 %s -- %s > %t.off // RUN: FileCheck -check-prefix=CONTEXT %s < %t.default // RUN: FileCheck -check-prefix=NAME %s < %t.off // FIXME: rdar://problem/20109989 non-deterministic sort order // RUN-disabled: diff %t.on %t.default // RUN: FileCheck -check-prefix=CONTEXT %s < %t.on // CONTEXT: key.kind: source.lang.swift.decl // CONTEXT-NEXT: key.name: "x" // CONTEXT-NOT: key.name: // CONTEXT: key.name: "foo(a:)" // CONTEXT-NOT: key.name: // CONTEXT: key.name: "foo(a:)" // CONTEXT-NOT: key.name: // CONTEXT: key.name: "foo(b:)" // CONTEXT-NOT: key.name: // CONTEXT: key.name: "test()" // CONTEXT: key.name: "#column" // CONTEXT: key.name: "AbsoluteValuable" // RUN: %complete-test -tok=STMT_0 %s | FileCheck %s -check-prefix=STMT func test1() { #^STMT_0^# } // STMT: let // STMT: var // STMT: if // STMT: for // STMT: while // STMT: return // STMT: func // STMT: foo(a: Int) // RUN: %complete-test -tok=STMT_1 %s | FileCheck %s -check-prefix=STMT_1 func test5() { var retLocal: Int #^STMT_1,r,ret,retur,return^# } // STMT_1-LABEL: Results for filterText: r [ // STMT_1-NEXT: return // STMT_1-NEXT: retLocal // STMT_1-NEXT: repeat // STMT_1-NEXT: required // STMT_1: ] // STMT_1-LABEL: Results for filterText: ret [ // STMT_1-NEXT: return // STMT_1-NEXT: retLocal // STMT_1-NEXT: repeat // STMT_1: ] // STMT_1-LABEL: Results for filterText: retur [ // STMT_1-NEXT: return // STMT_1: ] // STMT_1-LABEL: Results for filterText: return [ // STMT_1-NEXT: return // STMT_1: ] // RUN: %complete-test -top=0 -tok=EXPR_0 %s | FileCheck %s -check-prefix=EXPR func test2() { (#^EXPR_0^#) } // EXPR: 0 // EXPR: "abc" // EXPR: true // EXPR: false // EXPR: #colorLiteral(red: Float, green: Float, blue: Float, alpha: Float) // EXPR: #imageLiteral(resourceName: String) // EXPR: [values] // EXPR: [key: value] // EXPR: (values) // EXPR: nil // EXPR: foo(a: Int) // Top 1 // RUN: %complete-test -top=1 -tok=EXPR_1 %s | FileCheck %s -check-prefix=EXPR_TOP_1 func test3(x: Int) { let y = x let z = x let zzz = x (#^EXPR_1^#) } // EXPR_TOP_1: x // EXPR_TOP_1: 0 // EXPR_TOP_1: "abc" // EXPR_TOP_1: true // EXPR_TOP_1: false // EXPR_TOP_1: #colorLiteral(red: Float, green: Float, blue: Float, alpha: Float) // EXPR_TOP_1: #imageLiteral(resourceName: String) // EXPR_TOP_1: [values] // EXPR_TOP_1: [key: value] // EXPR_TOP_1: (values) // EXPR_TOP_1: nil // EXPR_TOP_1: y // EXPR_TOP_1: z // EXPR_TOP_1: zzz // Test where there are fewer results than 'top'. // RUN: %complete-test -top=1000 -tok=FEW_1 %s | FileCheck %s -check-prefix=FEW_1 func test3b() -> Int { return #^FEW_1^# } // FEW_1: test3b() // FEW_1: Int // FEW_1: 0 // Top 3 // RUN: %complete-test -top=3 -tok=EXPR_2 %s | FileCheck %s -check-prefix=EXPR_TOP_3 func test4(x: Int) { let y = x let z = x let zzz = x (#^EXPR_2^#) } // EXPR_TOP_3: x // EXPR_TOP_3: y // EXPR_TOP_3: z // EXPR_TOP_3: 0 // EXPR_TOP_3: "abc" // EXPR_TOP_3: true // EXPR_TOP_3: false // EXPR_TOP_3: #colorLiteral(red: Float, green: Float, blue: Float, alpha: Float) // EXPR_TOP_3: #imageLiteral(resourceName: String) // EXPR_TOP_3: [values] // EXPR_TOP_3: [key: value] // EXPR_TOP_3: (values) // EXPR_TOP_3: nil // EXPR_TOP_3: zzz // Top 3 with type matching // RUN: %complete-test -top=3 -tok=EXPR_3 %s | FileCheck %s -check-prefix=EXPR_TOP_3_TYPE_MATCH func test4(x: Int) { let y: String = "" let z: String = y let zzz = x let bar: Int = #^EXPR_3^# } // EXPR_TOP_3_TYPE_MATCH: x // EXPR_TOP_3_TYPE_MATCH: zzz // EXPR_TOP_3_TYPE_MATCH: 0 // EXPR_TOP_3_TYPE_MATCH: y // EXPR_TOP_3_TYPE_MATCH: z // RUN: %complete-test -tok=VOID_1 %s | FileCheck %s -check-prefix=VOID_1 // RUN: %complete-test -tok=VOID_1 %s -raw | FileCheck %s -check-prefix=VOID_1_RAW func test6() { func foo1() {} func foo2() -> Int {} func foo3() -> String {} let x: Int x = #^VOID_1,,foo^# } // VOID_1-LABEL: Results for filterText: [ // VOID_1-NOT: foo1 // VOID_1: foo2() // VOID_1-NOT: foo1 // VOID_1: foo3() // VOID_1-NOT: foo1 // VOID_1: ] // VOID_1-LABEL: Results for filterText: foo [ // VOID_1: foo2() // VOID_1: foo3() // VOID_1: foo1() // VOID_1: ] // VOID_1_RAW: key.name: "foo1()", // VOID_1_RAW-NEXT: key.sourcetext: "foo1()", // VOID_1_RAW-NEXT: key.description: "foo1()", // VOID_1_RAW-NEXT: key.typename: "Void", // VOID_1_RAW-NEXT: key.context: source.codecompletion.context.thismodule, // VOID_1_RAW-NEXT: key.num_bytes_to_erase: 0, // VOID_1_RAW-NEXT: key.not_recommended: 1, // RUN: %complete-test -tok=CASE_0 %s | FileCheck %s -check-prefix=CASE_0 func test7() { struct CaseSensitiveCheck { var member: Int = 0 } let caseSensitiveCheck = CaseSensitiveCheck() #^CASE_0,caseSensitiveCheck,CaseSensitiveCheck^# } // CASE_0: Results for filterText: caseSensitiveCheck [ // CASE_0: caseSensitiveCheck // CASE_0: CaseSensitiveCheck // CASE_0: caseSensitiveCheck. // CASE_0: ] // CASE_0: Results for filterText: CaseSensitiveCheck [ // CASE_0: caseSensitiveCheck // CASE_0: CaseSensitiveCheck // CASE_0: CaseSensitiveCheck( // CASE_0: ]
apache-2.0
6402837bff88297880bbb408c847bbf9
26.97235
130
0.636738
2.531276
false
true
false
false
externl/ice
swift/test/Ice/optional/ServerAMD.swift
1
870
// // Copyright (c) ZeroC, Inc. All rights reserved. // import Ice import TestCommon class ServerAMD: TestHelperI { public override func run(args: [String]) throws { let properties = try createTestProperties(args) var initData = Ice.InitializationData() initData.properties = properties initData.classResolverPrefix = ["IceOptionalAMD"] let communicator = try initialize(initData) defer { communicator.destroy() } communicator.getProperties().setProperty(key: "TestAdapter.Endpoints", value: getTestEndpoint(num: 0)) let adapter = try communicator.createObjectAdapter("TestAdapter") try adapter.add(servant: InitialDisp(InitialI()), id: Ice.stringToIdentity("initial")) try adapter.activate() serverReady() communicator.waitForShutdown() } }
gpl-2.0
3d5bf616c574bb2bd091c78e8b85fcef
31.222222
110
0.671264
4.78022
false
true
false
false
flutter/packages
packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/Utils.swift
1
949
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import Foundation func equals(_ x: Any?, _ y: Any?) -> Bool { if x == nil, y == nil { return true } guard let x = x as? AnyHashable, let y = y as? AnyHashable else { return false } return x == y } func equalsList(_ x: [Any?]?, _ y: [Any?]?) -> Bool { if x == nil, y == nil { return true } guard x?.count == y?.count else { return false } guard let x = x, let y = y else { return false } return (0..<x.count).allSatisfy { equals(x[$0], y[$0]) } } func equalsDictionary(_ x: [AnyHashable: Any?]?, _ y: [AnyHashable: Any?]?) -> Bool { if x == nil, y == nil { return true } guard x?.count == y?.count else { return false } guard let x = x, let y = y else { return false } return x.allSatisfy { equals($0.value, y[$0.key] as Any?) } }
bsd-3-clause
0f676d6a1b9adbcecc3a8cbe4b92ba5b
23.973684
85
0.592202
3.30662
false
false
false
false
djones6/swift-benchmarks
JSONTest.swift
1
3727
// // JSONTest.swift // Test performance of NSJSONSerialization converting to a Data // // Created by David Jones (@djones6) on 16/11/2016 // import Foundation import Dispatch // Determine how many concurrent blocks to schedule (user specified, or 10) var CONCURRENCY:Int = 2 // Determines how many times to convert per block var EFFORT:Int = 10000 // Determines the number of key:value pairs in the payload var LENGTH:Int = 10 // Determines how many times each block should be dispatched before terminating var NUM_LOOPS:Int = 1 // Debug var DEBUG = false func usage() { print("Options are:") print(" -c, --concurrency n: number of concurrent Dispatch blocks (default: \(CONCURRENCY))") print(" -n, --num_loops n: no. of times to invoke each block (default: \(NUM_LOOPS))") print(" -e, --effort n: no. of conversions to perform per block (default: \(EFFORT))") print(" -l, --length n: no. of key/value pairs to be converted (size of payload) (default: \(LENGTH))") print(" -d, --debug: print a lot of debugging output (default: \(DEBUG))") exit(1) } // Parse an expected int value provided on the command line func parseInt(param: String, value: String) -> Int { if let userInput = Int(value) { return userInput } else { print("Invalid value for \(param): '\(value)'") exit(1) } } // Parse command line options var param:String? = nil var remainingArgs = CommandLine.arguments.dropFirst(1) for arg in remainingArgs { if let _param = param { param = nil switch _param { case "-c", "--concurrency": CONCURRENCY = parseInt(param: _param, value: arg) case "-e", "--effort": EFFORT = parseInt(param: _param, value: arg) case "-l", "--length": LENGTH = parseInt(param: _param, value: arg) case "-n", "--num_loops": NUM_LOOPS = parseInt(param: _param, value: arg) default: print("Invalid option '\(arg)'") usage() } } else { switch arg { case "-c", "--concurrency", "-e", "--effort", "-l", "--length", "-n", "--num_loops": param = arg case "-d", "--debug": DEBUG = true case "-?", "-h", "--help", "--?": usage() default: print("Invalid option '\(arg)'") usage() } } } if (DEBUG) { print("Concurrency: \(CONCURRENCY)") print("Effort: \(EFFORT)") print("Length: \(LENGTH)") print("Debug: \(DEBUG)") } // The string to convert var PAYLOAD = [String:Any]() for i in 1...LENGTH { PAYLOAD["Item \(i)"] = Double(i) } if true { print("Payload length \(PAYLOAD.count), contents: \(PAYLOAD)") } // Create a queue to run blocks in parallel let queue = DispatchQueue(label: "hello", attributes: .concurrent) let group = DispatchGroup() // Block to be scheduled func code(block: Int, loops: Int) -> () -> Void { return { var data: Data? for _ in 1...EFFORT { do { data = try JSONSerialization.data(withJSONObject: PAYLOAD) } catch { fatalError("Could not serialize to JSON: \(error)") } } if DEBUG { print("Instance \(block) done") } if DEBUG { print("Serialized form = \(String(data: data!, encoding: .utf8)!)") } // Dispatch a new block to replace this one if (loops < NUM_LOOPS) { queue.async(group: group, execute: code(block: block, loops: loops+1)) } else { print("Block \(block) completed \(loops) loops") } } } print("Queueing \(CONCURRENCY) blocks") // Queue the initial blocks for i in 1...CONCURRENCY { queue.async(group: group, execute: code(block: i, loops: 1)) } print("Go!") // Go //dispatch_main() //_ = group.wait(timeout: .now() + DispatchTimeInterval.milliseconds(5000)) // 5 seconds _ = group.wait(timeout: .distantFuture) // forever //print("Waited 5 seconds, or completed")
mit
c48bd218264afae8e94b30753b630cd9
27.022556
106
0.632412
3.529356
false
false
false
false
dtrauger/Charts
Source/Charts/Renderers/CombinedChartRenderer.swift
1
6315
// // CombinedChartRenderer.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 import CoreGraphics open class CombinedChartRenderer: DataRenderer { open weak var chart: CombinedChartView? /// if set to true, all values are drawn above their bars, instead of below their top open var drawValueAboveBarEnabled = true /// if set to true, a grey area is drawn behind each bar that indicates the maximum value open var drawBarShadowEnabled = false internal var _renderers = [DataRenderer]() internal var _drawOrder: [CombinedChartView.DrawOrder] = [.bar, .bubble, .line, .candle, .scatter] public init(chart: CombinedChartView?, animator: Animator, viewPortHandler: ViewPortHandler?) { super.init(animator: animator, viewPortHandler: viewPortHandler) self.chart = chart createRenderers() } /// Creates the renderers needed for this combined-renderer in the required order. Also takes the DrawOrder into consideration. internal func createRenderers() { _renderers = [DataRenderer]() guard let chart = chart, let animator = animator, let viewPortHandler = self.viewPortHandler else { return } for order in drawOrder { switch (order) { case .bar: if chart.barData !== nil { _renderers.append(BarChartRenderer(dataProvider: chart, animator: animator, viewPortHandler: viewPortHandler)) } break case .line: if chart.lineData !== nil { _renderers.append(LineChartRenderer(dataProvider: chart, animator: animator, viewPortHandler: viewPortHandler)) } break case .candle: if chart.candleData !== nil { _renderers.append(CandleStickChartRenderer(dataProvider: chart, animator: animator, viewPortHandler: viewPortHandler)) } break case .scatter: if chart.scatterData !== nil { _renderers.append(ScatterChartRenderer(dataProvider: chart, animator: animator, viewPortHandler: viewPortHandler)) } break case .bubble: if chart.bubbleData !== nil { _renderers.append(BubbleChartRenderer(dataProvider: chart, animator: animator, viewPortHandler: viewPortHandler)) } break } } } open override func initBuffers() { for renderer in _renderers { renderer.initBuffers() } } open override func drawData(context: CGContext) { for renderer in _renderers { renderer.drawData(context: context) } } open override func drawValues(context: CGContext) { for renderer in _renderers { renderer.drawValues(context: context) } } open override func drawExtras(context: CGContext) { for renderer in _renderers { renderer.drawExtras(context: context) } } open override func drawHighlighted(context: CGContext, indices: [Highlight]) { for renderer in _renderers { var data: ChartData? if renderer is BarChartRenderer { data = (renderer as! BarChartRenderer).dataProvider?.barData } else if renderer is LineChartRenderer { data = (renderer as! LineChartRenderer).dataProvider?.lineData } else if renderer is CandleStickChartRenderer { data = (renderer as! CandleStickChartRenderer).dataProvider?.candleData } else if renderer is ScatterChartRenderer { data = (renderer as! ScatterChartRenderer).dataProvider?.scatterData } else if renderer is BubbleChartRenderer { data = (renderer as! BubbleChartRenderer).dataProvider?.bubbleData } let dataIndex = data == nil ? nil : (chart?.data as? CombinedChartData)?.allData.firstIndex(of: data!) let dataIndices = indices.filter{ $0.dataIndex == dataIndex || $0.dataIndex == -1 } renderer.drawHighlighted(context: context, indices: dataIndices) } } /// - returns: The sub-renderer object at the specified index. open func getSubRenderer(index: Int) -> DataRenderer? { if index >= _renderers.count || index < 0 { return nil } else { return _renderers[index] } } /// - returns: All sub-renderers. open var subRenderers: [DataRenderer] { get { return _renderers } set { _renderers = newValue } } // MARK: Accessors /// - returns: `true` if drawing values above bars is enabled, `false` ifnot open var isDrawValueAboveBarEnabled: Bool { return drawValueAboveBarEnabled } /// - returns: `true` if drawing shadows (maxvalue) for each bar is enabled, `false` ifnot open var isDrawBarShadowEnabled: Bool { return drawBarShadowEnabled } /// the order in which the provided data objects should be drawn. /// The earlier you place them in the provided array, the further they will be in the background. /// e.g. if you provide [DrawOrder.Bar, DrawOrder.Line], the bars will be drawn behind the lines. open var drawOrder: [CombinedChartView.DrawOrder] { get { return _drawOrder } set { if newValue.count > 0 { _drawOrder = newValue } } } }
apache-2.0
973d84f7ba1afd8ac224ef6ebea77908
29.955882
138
0.557878
5.55409
false
false
false
false
sfaxon/PyxisServer
Sources/RouteTree.swift
1
2846
// // TreeBuilder.swift // PyxisRouter // // Created by Seth Faxon on 7/21/15. // Copyright © 2015 SlashAndBurn. All rights reserved. // class RouteTree: CustomStringConvertible { typealias Handler = Connection -> Connection var rootNode: Node init() { self.rootNode = Node(token: Token.Slash) } func rootNode(handler: Handler) { self.rootNode.handler = handler } func addTokens(tokens: [Token], forHandler: Handler) { var currentNode = self.rootNode currentNode.handler = forHandler print("\naddTokens:") for (index, t) in tokens.enumerate() { let tokenNode = Node(token: t) print("index: \(index), t = \(t), currentNode.token = \(currentNode.token)") if tokenNode != self.rootNode { currentNode = currentNode.addChild(tokenNode) } if index + 1 == tokens.count { print("tokenNode.handler = \(forHandler)") tokenNode.handler = forHandler } } } var description: String { return "\(self.rootNode.children.map { $0.description })" } func findHandler(handler: Connection) -> (Handler)? { let request = handler.request let pathSplit = request.url.characters.split{$0 == "?"}.map(String.init) let requestTokens = Tokenizer.init(input: pathSplit[0]) var currentNode: Node? = self.rootNode // let mutatableRequest = request print("currentNode (root): \(currentNode!)") for (index, token) in requestTokens.pathTokens.enumerate() { print("index: \(index) is \(token)") if let cn = currentNode { print("calling matchingChild") let nodeString = cn.matchingChild(token) currentNode = nodeString.0 // if nodeString.1 != "" { // mutatableRequest.urlParams.append((nodeString.1, token.value)) // } print("currentNode: \(currentNode)") } else { print("returning root node handler") if let hndl = rootNode.handler { return hndl } else { // should be 404 return nil } } print("index: \(index) - tokenCount: \(requestTokens.tokens.count)") if index + 1 == requestTokens.pathTokens.count { print("found handler: \(currentNode?.handler)") // return request -> HttpResponse if let hndl = currentNode?.handler { print("returning hndl: \(hndl)") return hndl } } } return nil // 404 } }
mit
a28d76a7a7aee92291efe853e01568dc
33.277108
88
0.52232
4.702479
false
false
false
false
thanegill/RxSwift
Tests/RxSwiftTests/Tests/ObserverTests.swift
9
1941
// // ObserverTests.swift // RxTests // // Created by Rob Cheung on 9/15/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation import XCTest import RxSwift class ObserverTests: RxTest { } extension ObserverTests { func testConvenienceOn_Next() { var observer: AnyObserver<Int>! let a: Observable<Int> = Observable.create { o in observer = o return NopDisposable.instance } var elements = [Int]() _ = a.subscribeNext { n in elements.append(n) } XCTAssertEqual(elements, []) observer.onNext(0) XCTAssertEqual(elements, [0]) } func testConvenienceOn_Error() { var observer: AnyObserver<Int>! let a: Observable<Int> = Observable.create { o in observer = o return NopDisposable.instance } var elements = [Int]() var errorNotification: ErrorType! _ = a.subscribe( onNext: { n in elements.append(n) }, onError: { e in errorNotification = e } ) XCTAssertEqual(elements, []) observer.onNext(0) XCTAssertEqual(elements, [0]) observer.onError(testError) observer.onNext(1) XCTAssertEqual(elements, [0]) XCTAssertErrorEqual(errorNotification, testError) } func testConvenienceOn_Complete() { var observer: AnyObserver<Int>! let a: Observable<Int> = Observable.create { o in observer = o return NopDisposable.instance } var elements = [Int]() _ = a.subscribeNext { n in elements.append(n) } XCTAssertEqual(elements, []) observer.onNext(0) XCTAssertEqual(elements, [0]) observer.onCompleted() observer.onNext(1) XCTAssertEqual(elements, [0]) } }
mit
763b0e75283e39a7bec29ebfaedad9f0
20.797753
58
0.563402
4.608076
false
true
false
false
krzysztofzablocki/KZLinkedConsole
KZLinkedConsole/Extensions/NSTextView+Extensions.swift
1
3348
// // Created by Krzysztof Zabłocki on 05/12/15. // Copyright (c) 2015 pixle. All rights reserved. // import Foundation import AppKit extension NSTextView { func kz_mouseDown(event: NSEvent) { let pos = convertPoint(event.locationInWindow, fromView:nil) let idx = characterIndexForInsertionAtPoint(pos) guard let expectedClass = NSClassFromString("IDEConsoleTextView") where isKindOfClass(expectedClass) && attributedString().length > 1 && idx < attributedString().length else { kz_mouseDown(event) return } let attr = attributedString().attributesAtIndex(idx, effectiveRange: nil) guard let fileName = attr[KZLinkedConsole.Strings.linkedFileName] as? String, let lineNumber = attr[KZLinkedConsole.Strings.linkedLine] as? String else { kz_mouseDown(event) return } KZLinkedConsole.openFile(fromTextView: self, fileName: fileName, lineNumber: lineNumber) } } /** [workspacePath : [fileName : filePath]] */ var kz_filePathCache = [String : [String : String]]() /** Search for the given filename in the given workspace. To avoid parsing the project's header file inclusion path, we use the following heuristic: 1. Look in kz_filePathCache. 2. Look for the file in the current workspace. 3. Look in the parent directory of the current workspace, excluding the current workspace because we've already searched there. 4. Keep recursing upwards, but stop if we have gone more than 2 levels up or we have reached /foo/bar. The assumption here is that /foo/bar would actually be /Users/username and searching the developer's entire home directory is likely to be too expensive. Similarly, if the project is in some subdirectory heirarchy, then if we are three levels up then that search is likely to be large and too expensive also. */ func kz_findFile(workspacePath : String, _ fileName : String) -> String? { var thisWorkspaceCache = kz_filePathCache[workspacePath] ?? [:] if let result = thisWorkspaceCache[fileName] { if NSFileManager.defaultManager().fileExistsAtPath(result) { return result } } var searchPath = workspacePath var prevSearchPath : String? = nil var searchCount = 0 while true { let result = kz_findFile(fileName, searchPath, prevSearchPath) if result != nil && !result!.isEmpty { thisWorkspaceCache[fileName] = result kz_filePathCache[workspacePath] = thisWorkspaceCache return result } prevSearchPath = searchPath searchPath = (searchPath as NSString).stringByDeletingLastPathComponent searchCount += 1 let searchPathCount = searchPath.componentsSeparatedByString("/").count if searchPathCount <= 3 || searchCount >= 2 { return nil } } } func kz_findFile(fileName : String, _ searchPath : String, _ prevSearchPath : String?) -> String? { let args = (prevSearchPath == nil ? ["-L", searchPath, "-name", fileName, "-print", "-quit"] : ["-L", searchPath, "-name", prevSearchPath!, "-prune", "-o", "-name", fileName, "-print", "-quit"]) return KZPluginHelper.runShellCommand("/usr/bin/find", arguments: args) }
mit
3d876b036cc546f328a15ac1ece38930
34.231579
121
0.667165
4.572404
false
false
false
false
whitepixelstudios/Material
Sources/iOS/FABMenuController.swift
1
6411
/* * Copyright (C) 2015 - 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * 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. * * * Neither the name of CosmicMind 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 UIKit public enum FABMenuBacking { case none case fade case blur } extension UIViewController { /** A convenience property that provides access to the FABMenuController. This is the recommended method of accessing the FABMenuController through child UIViewControllers. */ public var fabMenuController: FABMenuController? { return traverseViewControllerHierarchyForClassType() } } open class FABMenuController: TransitionController { /// Reference to the MenuView. @IBInspectable open let fabMenu = FABMenu() /// A FABMenuBacking value type. open var fabMenuBacking = FABMenuBacking.blur /// The fabMenuBacking UIBlurEffectStyle. open var fabMenuBackingBlurEffectStyle = UIBlurEffectStyle.light /// A reference to the blurView. open fileprivate(set) var blurView: UIView? open override func layoutSubviews() { super.layoutSubviews() rootViewController.view.frame = view.bounds } open override func prepare() { super.prepare() prepareFABMenu() } } extension FABMenuController: FABMenuDelegate {} fileprivate extension FABMenuController { /// Prepares the fabMenu. func prepareFABMenu() { fabMenu.delegate = self fabMenu.layer.zPosition = 1000 fabMenu.handleFABButtonCallback = { [weak self] in self?.handleFABButtonCallback(button: $0) } fabMenu.handleOpenCallback = { [weak self] in self?.handleOpenCallback() } fabMenu.handleCloseCallback = { [weak self] in self?.handleCloseCallback() } fabMenu.handleCompletionCallback = { [weak self] in self?.handleCompletionCallback(view: $0) } view.addSubview(fabMenu) } } fileprivate extension FABMenuController { /// Shows the fabMenuBacking. func showFabMenuBacking() { showFade() showBlurView() } /// Hides the fabMenuBacking. func hideFabMenuBacking() { hideFade() hideBlurView() } /// Shows the blurView. func showBlurView() { guard .blur == fabMenuBacking else { return } guard !fabMenu.isOpened, fabMenu.isEnabled else { return } guard nil == blurView else { return } let blur = UIVisualEffectView(effect: UIBlurEffect(style: fabMenuBackingBlurEffectStyle)) blurView = UIView() blurView?.layout(blur).edges() view.layout(blurView!).edges() view.bringSubview(toFront: fabMenu) } /// Hides the blurView. func hideBlurView() { guard .blur == fabMenuBacking else { return } guard fabMenu.isOpened, fabMenu.isEnabled else { return } blurView?.removeFromSuperview() blurView = nil } /// Shows the fade. func showFade() { guard .fade == fabMenuBacking else { return } guard !fabMenu.isOpened, fabMenu.isEnabled else { return } UIView.animate(withDuration: 0.15, animations: { [weak self] in self?.rootViewController.view.alpha = 0.15 }) } /// Hides the fade. func hideFade() { guard .fade == fabMenuBacking else { return } guard fabMenu.isOpened, fabMenu.isEnabled else { return } UIView.animate(withDuration: 0.15, animations: { [weak self] in self?.rootViewController.view.alpha = 1 }) } } fileprivate extension FABMenuController { /** Handler to toggle the FABMenu opened or closed. - Parameter button: A UIButton. */ func handleFABButtonCallback(button: UIButton) { guard fabMenu.isOpened else { fabMenu.open(isTriggeredByUserInteraction: true) return } fabMenu.close(isTriggeredByUserInteraction: true) } /// Handler for when the FABMenu.open function is called. func handleOpenCallback() { isUserInteractionEnabled = false showFabMenuBacking() } /// Handler for when the FABMenu.close function is called. func handleCloseCallback() { isUserInteractionEnabled = false hideFabMenuBacking() } /** Completion handler for FABMenu open and close calls. - Parameter view: A UIView. */ func handleCompletionCallback(view: UIView) { if view == fabMenu.fabMenuItems.last { isUserInteractionEnabled = true } } }
bsd-3-clause
ed9143edc20d924af9e851eb9b2fa05f
28.543779
97
0.63703
4.912644
false
false
false
false
gregomni/swift
test/Generics/split_concrete_equivalence_class.swift
3
3325
// RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures -requirement-machine-inferred-signatures=on 2>&1 | %FileCheck %s // CHECK-LABEL: split_concrete_equivalence_class.(file).f01@ // CHECK-NEXT: Generic signature: <C, R where C : Collection, R : Collection, C.[Collection]SubSequence == Substring, R.[Sequence]Element == Character> func f01<C : Collection, R : Collection>(_: C, _: R) where C.SubSequence == Substring, C.Element == R.Element {} // CHECK-LABEL: split_concrete_equivalence_class.(file).f02@ // CHECK-NEXT: Generic signature: <C, R where C : Collection, R : Collection, C.[Sequence]Element == Character, R.[Collection]SubSequence == Substring> func f02<C : Collection, R : Collection>(_: C, _: R) where R.SubSequence == Substring, C.Element == R.Element {} // CHECK-LABEL: split_concrete_equivalence_class.(file).f03@ // CHECK-NEXT: Generic signature: <C, R where C : Collection, R : Collection, C.[Collection]SubSequence == Substring, R.[Sequence]Element == Character> func f03<C : Collection, R : Collection>(_: C, _: R) where C.SubSequence == Substring, C.Element == R.Element, C.Element == Character {} // CHECK-LABEL: split_concrete_equivalence_class.(file).f04@ // CHECK-NEXT: Generic signature: <C, R where C : Collection, R : Collection, C.[Sequence]Element == Character, R.[Collection]SubSequence == Substring> func f04<C : Collection, R : Collection>(_: C, _: R) where R.SubSequence == Substring, C.Element == R.Element, C.Element == Character {} // CHECK-LABEL: split_concrete_equivalence_class.(file).f05@ // CHECK-NEXT: Generic signature: <C, R where C : Collection, R : Collection, C.[Collection]SubSequence == Substring, R.[Sequence]Element == Character> func f05<C : Collection, R : Collection>(_: C, _: R) where C.SubSequence == Substring, C.Element == R.Element, R.Element == Character {} // CHECK-LABEL: split_concrete_equivalence_class.(file).f06@ // CHECK-NEXT: Generic signature: <C, R where C : Collection, R : Collection, C.[Sequence]Element == Character, R.[Collection]SubSequence == Substring> func f06<C : Collection, R : Collection>(_: C, _: R) where R.SubSequence == Substring, C.Element == R.Element, R.Element == Character {} // CHECK-LABEL: split_concrete_equivalence_class.(file).f07@ // CHECK-NEXT: Generic signature: <C, R where C : Collection, R : Collection, C.[Collection]SubSequence == Substring, R.[Collection]SubSequence == Substring> func f07<C : Collection, R : Collection>(_: C, _: R) where C.SubSequence == Substring, R.SubSequence == Substring, C.Element == R.Element {} // CHECK-LABEL: split_concrete_equivalence_class.(file).f08@ // CHECK-NEXT: Generic signature: <C, R where C : Collection, R : Collection, C.[Collection]SubSequence == Substring, R.[Collection]SubSequence == Substring> func f08<C : Collection, R : Collection>(_: C, _: R) where C.SubSequence == Substring, R.SubSequence == Substring, C.Element == R.Element, C.Element == Character {} // CHECK-LABEL: split_concrete_equivalence_class.(file).f09@ // CHECK-NEXT: Generic signature: <C, R where C : Collection, R : Collection, C.[Collection]SubSequence == Substring, R.[Collection]SubSequence == Substring> func f09<C : Collection, R : Collection>(_: C, _: R) where C.SubSequence == Substring, R.SubSequence == Substring, C.Element == R.Element, R.Element == Character {}
apache-2.0
e167aff75e2f89fd80fce34ae3106016
88.864865
164
0.706165
3.649835
false
false
false
false
alexcomu/swift3-tutorial
12-webRequest/12-webRequest/WeatherCell.swift
1
738
// // WeatherCell.swift // 12-webRequest // // Created by Alex Comunian on 20/01/17. // Copyright © 2017 Alex Comunian. All rights reserved. // import UIKit class WeatherCell: UITableViewCell { @IBOutlet weak var weatherIcon: UIImageView! @IBOutlet weak var highTemp: UILabel! @IBOutlet weak var lowTemp: UILabel! @IBOutlet weak var weatherType: UILabel! @IBOutlet weak var dayLabel: UILabel! func configureCell(forecast: Forecast){ lowTemp.text = "\(forecast.lowTemp!)°" highTemp.text = "\(forecast.highTemp!)°" weatherType.text = forecast.weatherType dayLabel.text = forecast.date weatherIcon.image = UIImage(named: forecast.weatherType) } }
mit
8f92154709f2df72f0f79cc236402e2d
24.344828
64
0.669388
4.129213
false
false
false
false
beanything/BAWebsite
Sources/App/Middleware/CorsMiddleware.swift
1
1614
// // CorsMiddleware.swift // BAWebsite // // Created by Sebastian Kreutzberger on 8/31/16. // Copyright © 2016 Sebastian Kreutzberger // Some rights reserved: http://opensource.org/licenses/MIT // import Foundation import Vapor import HTTP final class CorsMiddleware: Middleware { private var origin = "" // set to * to allow all private var pathPatterns = [String]() /// the given origin domain is allowed to access files /// which contain given path pattern strings init(_ origin: String, pathPatterns: [String]) { self.origin = origin self.pathPatterns = pathPatterns } /// set CORS headers for certain requested file types func respond(to request: Request, chainingTo chain: Responder) throws -> Response { // get the file extension (suffix) from the requested path let response = try chain.respond(to: request) let path = request.uri.path var setCors = false for part in pathPatterns { // set cors headers if the path contains at least one of the given path patterns if path.range(of: part) != nil { setCors = true } } if setCors { print("settings CORS for \(path)") response.headers["Access-Control-Allow-Origin"] = origin response.headers["Access-Control-Allow-Methods"] = "GET,OPTIONS" response.headers["Access-Control-Allow-Headers"] = "Content-Type, Authorization, Content-Length, X-Requested-With" } return response } }
mit
dbc2f261a89c043495c8d2adb2362a34
30.627451
126
0.620583
4.468144
false
false
false
false
i-schuetz/SwiftCharts
SwiftCharts/Views/ChartViewAnimators.swift
1
3651
// // ChartViewAnimators.swift // SwiftCharts // // Created by ischuetz on 02/09/16. // Copyright © 2016 ivanschuetz. All rights reserved. // import UIKit public struct ChartViewAnimatorsSettings { public let animDelay: Float public let animDuration: Float public let animDamping: CGFloat public let animInitSpringVelocity: CGFloat public init(animDelay: Float = 0, animDuration: Float = 0.3, animDamping: CGFloat = 0.7, animInitSpringVelocity: CGFloat = 1) { self.animDelay = animDelay self.animDuration = animDuration self.animDamping = animDamping self.animInitSpringVelocity = animInitSpringVelocity } public func copy(_ animDelay: Float? = nil, animDuration: Float? = nil, animDamping: CGFloat? = nil, animInitSpringVelocity: CGFloat? = nil) -> ChartViewAnimatorsSettings { return ChartViewAnimatorsSettings( animDelay: animDelay ?? self.animDelay, animDuration: animDuration ?? self.animDuration, animDamping: animDamping ?? self.animDamping, animInitSpringVelocity: animInitSpringVelocity ?? self.animInitSpringVelocity ) } public func withoutDamping() -> ChartViewAnimatorsSettings { return copy(animDelay, animDuration: animDuration, animDamping: 1, animInitSpringVelocity: animInitSpringVelocity) } } /// Runs a series of animations on a view open class ChartViewAnimators { open var animDelay: Float = 0 open var animDuration: Float = 10.3 open var animDamping: CGFloat = 0.4 open var animInitSpringVelocity: CGFloat = 0.5 fileprivate let animators: [ChartViewAnimator] fileprivate let onFinishAnimations: (() -> Void)? fileprivate let onFinishInverts: (() -> Void)? fileprivate let view: UIView fileprivate let settings: ChartViewAnimatorsSettings fileprivate let invertSettings: ChartViewAnimatorsSettings public init(view: UIView, animators: ChartViewAnimator..., settings: ChartViewAnimatorsSettings = ChartViewAnimatorsSettings(), invertSettings: ChartViewAnimatorsSettings? = nil, onFinishAnimations: (() -> Void)? = nil, onFinishInverts: (() -> Void)? = nil) { self.view = view self.animators = animators self.onFinishAnimations = onFinishAnimations self.onFinishInverts = onFinishInverts self.settings = settings self.invertSettings = invertSettings ?? settings } open func animate() { for animator in animators { animator.prepare(view) } animate(settings, animations: { for animator in self.animators { animator.animate(self.view) } }, onFinish: { self.onFinishAnimations?() }) } open func invert() { animate(invertSettings, animations: { for animator in self.animators { animator.invert(self.view) } }, onFinish: { self.onFinishInverts?() }) } fileprivate func animate(_ settings: ChartViewAnimatorsSettings, animations: @escaping () -> Void, onFinish: @escaping () -> Void) { UIView.animate(withDuration: TimeInterval(settings.animDuration), delay: TimeInterval(settings.animDelay), usingSpringWithDamping: settings.animDamping, initialSpringVelocity: settings.animInitSpringVelocity, options: UIView.AnimationOptions(), animations: { animations() }, completion: {finished in if finished { onFinish() } }) } }
apache-2.0
83dffe10989408860a3a4515c8699058
35.5
266
0.654247
5.538695
false
false
false
false