repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
srn214/Floral
Floral/Pods/SwiftLocation/Sources/Auto Complete/AutoComplete+Support.swift
1
7271
// // SwiftLocation - Efficient Location Tracking for iOS // // Created by Daniele Margutti // - Web: https://www.danielemargutti.com // - Twitter: https://twitter.com/danielemargutti // - Mail: [email protected] // // Copyright © 2019 Daniele Margutti. Licensed under MIT License. import Foundation import MapKit import CoreLocation public extension AutoCompleteRequest { /// Service to use. /// /// - apple: apple service. /// - google: google service. /// - openStreet: open streep map service. enum Service: CustomStringConvertible { case apple(Options?) case google(GoogleOptions) public static var all: [Service] { return [.apple(nil), .google(GoogleOptions(APIKey: ""))] } public var description: String { switch self { case .apple: return "Apple" case .google: return "Google" } } } /// Type of autocomplete operation. /// /// - partialSearch: it's a partial search operation. Usually it's used when you need to provide a search /// inside search boxes of the map. Once you have the full query or the address you can /// use a placeDetail search to retrive more info about the place. /// - placeDetail: when you have a full search query (from services like apple) or the place id (from service like google) /// you can use this operation to retrive more info about the place. enum Operation: CustomStringConvertible { case partialSearch(String) case placeDetail(String) public static var all: [Operation] { return [.partialSearch(""),.placeDetail("")] } public var value: String { switch self { case .partialSearch(let v): return v case .placeDetail(let v): return v } } public var description: String { switch self { case .partialSearch: return "Partial Search" case .placeDetail: return "Place Detail" } } } class Options { // MARK: - Public Properties - /// Type of autocomplete operation /// By default is `.partialSearch`. internal var operation: Operation = .partialSearch("") /// The region that defines the geographic scope of the search. /// Use this property to limit search results to the specified geographic area. /// The default value is nil which for `AppleOptions` means a region that spans the entire world. /// For other services when nil the entire parameter will be ignored. public var region: MKCoordinateRegion? // Use this property to determine whether you want completions that represent points-of-interest // or whether completions might yield additional relevant query strings. // The default value is set to `.locationAndQueries`: // Points of interest and query suggestions. /// Specify this value when you want both map-based points of interest and common /// query terms used to find locations. For example, the search string “cof” yields a completion for “coffee”. public var filter: MKLocalSearchCompleter.FilterType = .locationsAndQueries // MARK: - Private Methods - /// Return server parameters to compose the url. /// /// - Returns: URL internal func serverParams() -> [URLQueryItem] { return [] } } class GoogleOptions: Options { /// API Key for searvice. public var APIKey: String? /// Restrict results from a Place Autocomplete request to be of a certain type. /// See: https://developers.google.com/places/web-service/autocomplete#place_types /// /// - geocode: return only geocoding results, rather than business results. /// - address: return only geocoding results with a precise address. /// - establishment: return only business results. /// - regions: return any result matching the following types: `locality, sublocality, postal_code, country, administrative_area_level_1, administrative_area_level_2` /// - cities: return results that match `locality` or `administrative_area_level_3`. public enum PlaceTypes: String { case geocode case address case establishment case regions case cities } /// Restrict results to be of certain type, `nil` to ignore this filter. public var placeTypes: Set<PlaceTypes>? = nil /// The distance (in meters) within which to return place results. /// Note that setting a radius biases results to the indicated area, /// but may not fully restrict results to the specified area. /// More info: https://developers.google.com/places/web-service/autocomplete#location_biasing /// and https://developers.google.com/places/web-service/autocomplete#location_restrict. public var radius: Float? = nil /// Returns only those places that are strictly within the region defined by location and radius. /// This is a restriction, rather than a bias, meaning that results outside this region will /// not be returned even if they match the user input. public var strictBounds: Bool = false /// The language code, indicating in which language the results should be returned, if possible. public var locale: String? /// A grouping of places to which you would like to restrict your results up to 5 countries. /// Countries must be added in ISO3166-1_alpha-2 version you can found: /// https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2. public var countries: Set<String>? public init(APIKey: String?) { self.APIKey = APIKey } // MARK: - Private Functions - internal override func serverParams() -> [URLQueryItem] { var list = [URLQueryItem]() if let placeTypes = self.placeTypes { list.append(URLQueryItem(name: "types", value: placeTypes.map { $0.rawValue }.joined(separator: ","))) } if let radius = self.radius { list.append(URLQueryItem(name: "radius", value: String(radius))) } if self.strictBounds == true { list.append(URLQueryItem(name: "strictbounds", value: nil)) } if let locale = self.locale { list.append(URLQueryItem(name: "language", value: locale.lowercased())) } if let countries = self.countries { list.append(URLQueryItem(name: "components", value: countries.map { return "country:\($0)" }.joined(separator: "|"))) } return list } } }
mit
123c2cf404c168416820daa2f2f0ac02
39.121547
174
0.591848
5.106892
false
false
false
false
WeirdMath/TimetableSDK
Sources/Location.swift
1
11727
// // Location.swift // TimetableSDK // // Created by Sergej Jaskiewicz on 22.11.2016. // // import SwiftyJSON import PromiseKit import Foundation /// The information about a location that an `Event` may take place in. public final class Location : JSONRepresentable, TimetableEntity { /// The Timetable this entity was fetched from. `nil` if it was initialized from a custom JSON object. public weak var timetable: Timetable? /// The room that the current location refers to, if available. /// Use public var room: Room? public let educatorsDisplayText: String? public let hasEducators: Bool public let educatorIDs: [(Int, String)]? public let isEmpty: Bool public let displayName: String public let hasGeographicCoordinates: Bool public let latitude: Double? public let longitude: Double? public let latitudeValue: String? public let longitudeValue: String? internal init(educatorsDisplayText: String?, hasEducators: Bool, educatorIDs: [(Int, String)]?, isEmpty: Bool, displayName: String, hasGeographicCoordinates: Bool, latitude: Double?, longitude: Double?, latitudeValue: String?, longitudeValue: String?) { self.educatorsDisplayText = educatorsDisplayText self.hasEducators = hasEducators self.educatorIDs = educatorIDs self.isEmpty = isEmpty self.displayName = displayName self.hasGeographicCoordinates = hasGeographicCoordinates self.latitude = latitude self.longitude = longitude self.latitudeValue = latitudeValue self.longitudeValue = longitudeValue } /// Creates a new entity from its JSON representation. /// /// - Parameter json: The JSON representation of the entity. /// - Throws: `TimetableError.incorrectJSONFormat` public init(from json: JSON) throws { do { educatorsDisplayText = try map(json["EducatorsDisplayText"]) hasEducators = (try? map(json["HasEducators"])) ?? false educatorIDs = try map(json["EducatorIds"]) isEmpty = try map(json["IsEmpty"]) displayName = try map(json["DisplayName"]) hasGeographicCoordinates = try map(json["HasGeographicCoordinates"]) if hasGeographicCoordinates { latitude = try map(json["Latitude"]) longitude = try map(json["Longitude"]) latitudeValue = try map(json["LatitudeValue"]) longitudeValue = try map(json["LongitudeValue"]) } else { latitude = nil longitude = nil latitudeValue = nil longitudeValue = nil } } catch { throw TimetableError.incorrectJSON(json, whenConverting: Location.self) } } /// Fetches the room that the current location refers to, if available. Saves it to the `room` property. /// /// - Important: `timetable` property must be set. /// /// - Warning: This functionality is unstable, i. e. it is not guaranteed that the needed `Room` for this /// location will actually be found. That's not my fault. It's Timetable ¯\\_(ツ)_/¯ /// /// - Parameters: /// - addressesData: If this is not `nil`, then instead of networking uses provided json data for /// the list of addresses to search in. /// May be useful for deserializing from a local storage. Default value is `nil`. /// - roomsData: If this is not `nil`, then instead of networking uses provided json data for /// the list of rooms to search in. /// May be useful for deserializing from a local storage. Default value is `nil`. /// - dispatchQueue: If this is `nil`, uses `DispatchQueue.main` as a queue to asyncronously /// execute a completion handler on. Otherwise uses the specified queue. /// If `jsonData` is not `nil`, setting this /// makes no change as in this case fetching happens syncronously in the current queue. /// Default value is `nil`. /// - forceReloadAddresses: This method needs to fetch all the addresses. This is expensive. /// See also /// `Timetable.fetchAllAddresses(using:dispatchQueue:forceReload:completion:)`. /// Default value is `false`. /// - forceReloadRooms: For a matching adress this method needs to fetch all the rooms. /// This is expensive. See also /// `Address.fetchAllRooms(using:dispatchQueue:forceReload:completion:)`. /// Default value is `false`. /// - completion: A closure that is called after a responce is received. public func fetchRoom(addressesData: Data? = nil, roomsData: Data? = nil, dispatchQueue: DispatchQueue? = nil, forceReloadAddresses: Bool = false, forceReloadRooms: Bool = false, completion: @escaping (Result<Room>) -> Void) { guard let timetable = timetable else { completion(.failure(TimetableError.timetableIsDeallocated)) return } timetable .fetchAllAddresses(using: addressesData, dispatchQueue: dispatchQueue, forceReload: forceReloadAddresses) { result in switch result { case .success(let addresses): let selfName = self.displayName.lowercased() guard let matchingAddress = addresses .first(where: { selfName.contains($0.name.lowercased()) }) else { completion(.failure(TimetableError.couldntFindRoomForLocation)) return } let addressPart = matchingAddress.name.lowercased() let roomPart = selfName.replacingOccurrences(of: addressPart, with: "") matchingAddress.fetchAllRooms(using: roomsData, dispatchQueue: dispatchQueue, forceReload: forceReloadRooms) { result in switch result { case .success(let rooms): // Find the longest room name that contains in the roomPart. var matchingRoom: Room? var maxRoomNameLength = 0 for room in rooms { let roomNameLength = room.name.characters.count if roomNameLength > maxRoomNameLength && roomPart.contains(room.name.lowercased()) { matchingRoom = room maxRoomNameLength = roomNameLength } } if let matchingRoom = matchingRoom { self.room = matchingRoom completion(.success(matchingRoom)) } else { completion(.failure(TimetableError.couldntFindRoomForLocation)) } case .failure(let error): completion(.failure(error)) } } case .failure(let error): completion(.failure(error)) } } } /// Fetches the room that the current location refers to, if available. Saves it to the `room` property. /// /// - Important: `timetable` property must be set. /// /// - Parameters: /// - addressesData: If this is not `nil`, then instead of networking uses provided json data for /// the list of addresses to search in. /// May be useful for deserializing from a local storage. Default value is `nil`. /// - roomsData: If this is not `nil`, then instead of networking uses provided json data for /// the list of rooms to search in. /// May be useful for deserializing from a local storage. Default value is `nil`. /// - forceReloadAddresses: This method needs to fetch all the addresses. This is expensive. /// See also /// `Timetable.fetchAllAddresses(using:dispatchQueue:forceReload:completion:)`. /// Default value is `false`. /// - forceReloadRooms: For a matching adress this method needs to fetch all the rooms. /// This is expensive. See also /// `Address.fetchAllRooms(using:dispatchQueue:forceReload:completion:)`. /// Default value is `false`. /// - Returns: A promise. public func fetchRoom(addressesData: Data? = nil, roomsData: Data? = nil, forceReloadAddresses: Bool = false, forceReloadRooms: Bool = false) -> Promise<Room> { return makePromise { fetchRoom(addressesData: addressesData, roomsData: roomsData, forceReloadAddresses: forceReloadAddresses, forceReloadRooms: forceReloadRooms, completion: $0) } } } extension Location: Equatable { /// Returns a Boolean value indicating whether two values are equal. /// /// Equality is the inverse of inequality. For any values `a` and `b`, /// `a == b` implies that `a != b` is `false`. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. public static func ==(lhs: Location, rhs: Location) -> Bool { return lhs.educatorsDisplayText == rhs.educatorsDisplayText && lhs.hasEducators == rhs.hasEducators && lhs.educatorIDs == rhs.educatorIDs && lhs.isEmpty == rhs.isEmpty && lhs.displayName == rhs.displayName && lhs.hasGeographicCoordinates == rhs.hasGeographicCoordinates && lhs.latitude == rhs.latitude && lhs.longitude == rhs.longitude && lhs.latitudeValue == rhs.latitudeValue && lhs.longitudeValue == rhs.longitudeValue } }
mit
566d97981102d45ac8904764e3ef8340
47.442149
111
0.507464
5.668762
false
false
false
false
moyazi/SwiftDayList
SwiftDayList/Days/Day6/Interest.swift
1
2335
// // Interest.swift // SwiftDayList // // Created by leoo on 2017/6/27. // Copyright © 2017年 Het. All rights reserved. // import UIKit class Interest: NSObject { // MARK: - Public API var title = "" var descriptions = "" var numberOfMembers = 0 var numberOfPosts = 0 var featuredImage: UIImage! init(title: String, descriptions: String, featuredImage: UIImage!) { self.title = title self.descriptions = descriptions self.featuredImage = featuredImage numberOfMembers = 1 numberOfPosts = 1 } static func createInterests() -> [Interest] { return [ Interest(title: "Hello there, i miss u.", descriptions: "We love backpack and adventures! We walked to Antartica yesterday, and camped with some cute pinguines, and talked about this wonderful app idea. 🐧⛺️✨", featuredImage: UIImage(named: "Day6_hello")!), Interest(title: "🐳🐳🐳🐳🐳", descriptions: "We love romantic stories. We walked to Antartica yesterday, and camped with some cute pinguines, and talked about this wonderful app idea. 🐧⛺️✨", featuredImage: UIImage(named: "Day6_dudu")!), Interest(title: "Training like this, #bodyline", descriptions: "Create beautiful apps. We walked to Antartica yesterday, and camped with some cute pinguines, and talked about this wonderful app idea. 🐧⛺️✨", featuredImage: UIImage(named: "Day6_bodyline")!), Interest(title: "I'm hungry, indeed.", descriptions: "Cars and aircrafts and boats and sky. We walked to Antartica yesterday, and camped with some cute pinguines, and talked about this wonderful app idea. 🐧⛺️✨", featuredImage: UIImage(named: "Day6_wave")!), Interest(title: "Dark Varder, #emoji", descriptions: "Meet life with full presence. We walked to Antartica yesterday, and camped with some cute pinguines, and talked about this wonderful app idea. 🐧⛺️✨", featuredImage: UIImage(named: "Day6_darkvarder")!), Interest(title: "I have no idea, bitch", descriptions: "Get up to date with breaking-news. We walked to Antartica yesterday, and camped with some cute pinguines, and talked about this wonderful app idea. 🐧⛺️✨", featuredImage: UIImage(named: "Day6_hhhhh")!), ] } }
mit
8f402a0c962fd00b70a1454d741c49b4
57.025641
269
0.683606
3.679675
false
false
false
false
JadenGeller/Erratic
Sources/MutableLazyShuffleCollection.swift
1
2561
// // MutableLazyShuffleCollection.swift // Erratic // // Created by Jaden Geller on 2/19/16. // Copyright © 2016 Jaden Geller. All rights reserved. // import Permute public struct MutableLazyShuffleCollection<Base: MutableCollectionType where Base.Index.Distance == Int, Base.Index: Hashable> { internal var permuted: MutablePermuteCollection<Base> public var base: Base { get { return permuted.base } set { permuted.base = newValue } } public var permutation: LazyShufflePermutation<Base.Index> { get { return LazyShufflePermutation(permuted.permutation) } set { permuted.permutation = AnyPermutation(newValue) } } /// Constructs an unshuffled view of `collection`. public init(unshuffled collection: Base) { precondition(collection.count <= Int(UInt32.max), "Collection is too large.") self.permuted = MutablePermuteCollection(collection, withPermutation: IdentityPermutation()) } /// Shuffles the view in O(1) time complexity, resetting all indexed access operations to first /// access time complexity. public mutating func shuffleInPlace() { self.permutation = LazyShufflePermutation(indices: base.indices) } } extension MutableLazyShuffleCollection: LazyCollectionType, PermuteCollectionType, MutableCollectionType { public var startIndex: Base.Index { return base.startIndex } public var endIndex: Base.Index { return base.endIndex } /// Average case O(n) and worst case O(infinity) first access; worst case O(1) repeat access. public subscript(index: Base.Index) -> Base.Generator.Element { get { return permuted[index] } set { permuted[index] = newValue } } } extension MutableLazyShuffleCollection: CustomStringConvertible { public var description: String { return String(Array(self)) } } public func ==<Collection: CollectionType where Collection.Index.Distance == Int, Collection.Index: Hashable, Collection.Generator.Element: Equatable>(lhs: MutableLazyShuffleCollection<Collection>, rhs: MutableLazyShuffleCollection<Collection>) -> Bool { return lhs.count == rhs.count && zip(lhs, rhs).reduce(true) { $0 && $1.0 == $1.1 } } extension LazyShuffleCollection where Base: MutableCollectionType { init(_ collection: MutableLazyShuffleCollection<Base>) { self.permuted = PermuteCollection(collection.permuted) } }
mit
e028c5bd52cdac002198048fcebd3f5f
32.684211
254
0.680078
4.491228
false
false
false
false
makelove/Developing-iOS-8-Apps-with-Swift
Lession7-Psychologist/Psychologist Popover/Psychologist/DiagnosedHappinessViewController.swift
2
1590
// // DiagnosedHappinessViewController.swift // Psychologist // // Created by CS193p Instructor. // Copyright (c) 2015 Stanford University. All rights reserved. // import UIKit class DiagnosedHappinessViewController : HappinessViewController, UIPopoverPresentationControllerDelegate { override var happiness: Int { didSet { diagnosticHistory += [happiness] } } private let defaults = NSUserDefaults.standardUserDefaults() var diagnosticHistory: [Int] { get { return defaults.objectForKey(History.DefaultsKey) as? [Int] ?? [] } set { defaults.setObject(newValue, forKey: History.DefaultsKey) } } private struct History { static let SegueIdentifier = "Show Diagnostic History" static let DefaultsKey = "DiagnosedHappinessViewController.History" } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let identifier = segue.identifier { switch identifier { case History.SegueIdentifier: if let tvc = segue.destinationViewController as? TextViewController { if let ppc = tvc.popoverPresentationController { ppc.delegate = self } tvc.text = "\(diagnosticHistory)" } default: break } } } func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle { return UIModalPresentationStyle.None } }
apache-2.0
ee6e810b1773e374edfdc281ae05e97e
31.44898
127
0.642767
5.888889
false
false
false
false
infinitetoken/Arcade
Sources/Adapters/In Memory/InMemoryAdapter.swift
1
4069
// // InMemoryAdapter.swift // Arcade // // Created by A.C. Wright Design on 10/30/17. // Copyright © 2017 A.C. Wright Design. All rights reserved. // import Foundation open class InMemoryAdapter { public static var type: Arcade.AdapterType = .inMemory private var store: [String : AdapterTable] = [:] public init(store: [String : AdapterTable] = [:]) { self.store = store } } public extension InMemoryAdapter { struct AdapterTable { public var viewables: [Viewable] = [] mutating func insert(_ storable: Storable) { self.viewables.append(storable) } func find(_ id: String) -> Viewable? { return self.viewables.filter { $0.persistentId == id }.first } func fetch(_ query: Query?, sorts: [Sort] = [], limit: Int = 0, offset: Int = 0) -> [Viewable] { if let query = query { var storables = self.viewables.filter { query.evaluate(with: $0) } storables = self.sort(viewables: viewables, sorts: sorts) return storables.offset(by: offset).limit(to: limit) } else { return self.sort(viewables: self.viewables, sorts: sorts).offset(by: offset).limit(to: limit) } } mutating func update(_ storable: Storable) { if let existingStorable = find(storable.persistentId) { self.delete(existingStorable.persistentId) self.insert(storable) } else { self.insert(storable) } } mutating func delete(_ id: String) { self.viewables = self.viewables.filter {$0.persistentId != id} } func count(query: Query?) -> Int { return self.fetch(query, sorts: [], limit: 0, offset: 0).count } func sort(viewables: [Viewable], sorts: [Sort] = []) -> [Viewable] { return sorts.reduce(viewables) { $1.sort(viewables: $0) } } } } extension InMemoryAdapter: Adapter { @discardableResult public func insert<I>(storable: I) async throws -> I where I : Storable { var adapterTable = self.adapterTable(for: I.table.name) adapterTable.insert(storable) self.store[I.table.name] = adapterTable return storable } public func find<I>(id: String) async throws -> I? where I : Viewable { let adapterTable = self.adapterTable(for: I.table.name) return adapterTable.find(id) as? I } public func fetch<I>(query: Query?, sorts: [Sort] = [], limit: Int = 0, offset: Int = 0) async throws -> [I] where I : Viewable { let adapterTable = self.adapterTable(for: I.table.name) return adapterTable.fetch(query, sorts: sorts, limit: limit, offset: offset) as? [I] ?? [] } @discardableResult public func update<I>(storable: I) async throws -> I where I : Storable { var adapterTable = self.adapterTable(for: I.table.name) adapterTable.update(storable) self.store[I.table.name] = adapterTable return storable } @discardableResult public func delete<I>(storable: I) async throws -> I where I : Storable { var adapterTable = self.adapterTable(for: I.table.name) adapterTable.delete(storable.persistentId) self.store[I.table.name] = adapterTable return storable } public func count<T>(table: T, query: Query?) async throws -> Int where T : Table { let adapterTable = self.adapterTable(for: table.name) return adapterTable.count(query: query) } } extension InMemoryAdapter { private func adapterTable(for name: String) -> AdapterTable { if let adapterTable = self.store[name] { return adapterTable } else { let adapterTable = AdapterTable() self.store[name] = adapterTable return adapterTable } } }
mit
8807b14ee4fa652448a493511c4fc51c
29.818182
133
0.5794
4.159509
false
false
false
false
infinitedg/SwiftDDP
Examples/CoreData/Pods/SwiftDDP/SwiftDDP/Meteor.swift
2
14771
// Copyright (c) 2016 Peter Siegesmund <[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 import UIKit /* enum Error: String { case BadRequest = "400" // The server cannot or will not process the request due to something that is perceived to be a client error case Unauthorized = "401" // Similar to 403 Forbidden, but specifically for use when authentication is required and has failed or has not yet been provided. case NotFound = "404" // ex. Method not found, Subscription not found case Forbidden = "403" // Not authorized to access resource, also issued when you've been logged out by the server case RequestConflict = "409" // ex. MongoError: E11000 duplicate key error case PayloadTooLarge = "413" // The request is larger than the server is willing or able to process. case InternalServerError = "500" } */ public protocol MeteorCollectionType { func documentWasAdded(collection:String, id:String, fields:NSDictionary?) func documentWasChanged(collection:String, id:String, fields:NSDictionary?, cleared:[String]?) func documentWasRemoved(collection:String, id:String) } /** Meteor is a class to simplify communicating with and consuming MeteorJS server services */ public class Meteor { /** client is a singleton instance of DDPClient */ public static let client = Meteor.Client() // Client is a singleton object internal static var collections = [String:MeteorCollectionType]() /** returns a Meteor collection, if it exists */ public static func collection(name:String) -> MeteorCollectionType? { return collections[name] } /** Sends a subscription request to the server. - parameter name: The name of the subscription. */ public static func subscribe(name:String) -> String { return client.sub(name, params:nil) } /** Sends a subscription request to the server. - parameter name: The name of the subscription. - parameter params: An object containing method arguments, if any. */ public static func subscribe(name:String, params:[AnyObject]) -> String { return client.sub(name, params:params) } /** Sends a subscription request to the server. If a callback is passed, the callback asynchronously runs when the client receives a 'ready' message indicating that the initial subset of documents contained in the subscription has been sent by the server. - parameter name: The name of the subscription. - parameter params: An object containing method arguments, if any. - parameter callback: The closure to be executed when the server sends a 'ready' message. */ public static func subscribe(name:String, params:[AnyObject]?, callback: DDPCallback?) -> String { return client.sub(name, params:params, callback:callback) } /** Sends a subscription request to the server. If a callback is passed, the callback asynchronously runs when the client receives a 'ready' message indicating that the initial subset of documents contained in the subscription has been sent by the server. - parameter name: The name of the subscription. - parameter callback: The closure to be executed when the server sends a 'ready' message. */ public static func subscribe(name:String, callback: DDPCallback?) -> String { return client.sub(name, params: nil, callback: callback) } /** Sends an unsubscribe request to the server. */ public static func unsubscribe(name:String) -> String? { return client.unsub(name) } /** Sends an unsubscribe request to the server. If a callback is passed, the callback asynchronously runs when the unsubscribe transaction is complete. */ public static func unsubscribe(name:String, callback:DDPCallback?) -> String? { return client.unsub(name, callback: callback) } /** Calls a method on the server. If a callback is passed, the callback is asynchronously executed when the method has completed. The callback takes two arguments: result and error. It the method call is successful, result contains the return value of the method, if any. If the method fails, error contains information about the error. - parameter name: The name of the method - parameter params: An array containing method arguments, if any - parameter callback: The closure to be executed when the method has been executed */ public static func call(name:String, params:[AnyObject]?, callback:DDPMethodCallback?) -> String? { return client.method(name, params: params, callback: callback) } /** Call a single function to establish a DDP connection, and login with email and password - parameter url: The url of a Meteor server - parameter email: A string email address associated with a Meteor account - parameter password: A string password */ public static func connect(url:String, email:String, password:String) { client.connect(url) { session in client.loginWithPassword(email, password: password) { result, error in guard let _ = error else { if let _ = result as? NSDictionary { // client.userDidLogin(credentials) } return } } } } /** Connect to a Meteor server and resume a prior session, if the user was logged in - parameter url: The url of a Meteor server */ public static func connect(url:String) { client.resume(url, callback: nil) } /** Connect to a Meteor server and resume a prior session, if the user was logged in - parameter url: The url of a Meteor server - parameter callback: An optional closure to be executed after the connection is established */ public static func connect(url:String, callback:DDPCallback?) { client.resume(url, callback: callback) } /** Creates a user account on the server with an email and password - parameter email: An email string - parameter password: A password string - parameter callback: A closure with result and error parameters describing the outcome of the operation */ public static func signupWithEmail(email: String, password: String, callback: DDPMethodCallback?) { client.signupWithEmail(email, password: password, callback: callback) } /** Logs a user into the server using an email and password - parameter email: An email string - parameter password: A password string - parameter callback: A closure with result and error parameters describing the outcome of the operation */ public static func loginWithPassword(email:String, password:String, callback:DDPMethodCallback?) { client.loginWithPassword(email, password: password, callback: callback) } /** Logs a user into the server using an email and password - parameter email: An email string - parameter password: A password string */ public static func loginWithPassword(email:String, password:String) { client.loginWithPassword(email, password: password, callback: nil) } internal static func loginWithService<T: UIViewController>(service: String, clientId: String, viewController: T) { // Resume rather than if Meteor.client.loginWithToken(nil) == false { var url:String! switch service { case "twitter": url = MeteorOAuthServices.twitter() case "facebook": url = MeteorOAuthServices.facebook(clientId) case "github": url = MeteorOAuthServices.github(clientId) case "google": url = MeteorOAuthServices.google(clientId) default: url = nil } let oauthDialog = MeteorOAuthDialogViewController() oauthDialog.serviceName = service.capitalizedString oauthDialog.url = NSURL(string: url) viewController.presentViewController(oauthDialog, animated: true, completion: nil) } else { log.debug("Already have valid server login credentials. Logging in with preexisting login token") } } /** Logs a user into the server using Twitter - parameter viewController: A view controller from which to launch the OAuth modal dialog */ public static func loginWithTwitter<T: UIViewController>(viewController: T) { Meteor.loginWithService("twitter", clientId: "", viewController: viewController) } /** Logs a user into the server using Facebook - parameter viewController: A view controller from which to launch the OAuth modal dialog - parameter clientId: The apps client id, provided by the service (Facebook, Google, etc.) */ public static func loginWithFacebook<T: UIViewController>(clientId: String, viewController: T) { Meteor.loginWithService("facebook", clientId: clientId, viewController: viewController) } /** Logs a user into the server using Github - parameter viewController: A view controller from which to launch the OAuth modal dialog - parameter clientId: The apps client id, provided by the service (Facebook, Google, etc.) */ public static func loginWithGithub<T: UIViewController>(clientId: String, viewController: T) { Meteor.loginWithService("github", clientId: clientId, viewController: viewController) } /** Logs a user into the server using Google - parameter viewController: A view controller from which to launch the OAuth modal dialog - parameter clientId: The apps client id, provided by the service (Facebook, Google, etc.) */ public static func loginWithGoogle<T: UIViewController>(clientId: String, viewController: T) { Meteor.loginWithService("google", clientId: clientId, viewController: viewController) } /** Logs a user out of the server and executes a callback when the logout process has completed - parameter callback: An optional closure to be executed after the client has logged out */ public static func logout(callback:DDPMethodCallback?) { client.logout(callback) } /** Logs a user out of the server */ public static func logout() { client.logout() } /** Meteor.Client is a subclass of DDPClient that facilitates interaction with the MeteorCollection class */ public class Client: DDPClient { typealias SubscriptionCallback = () -> () let notifications = NSNotificationCenter.defaultCenter() public convenience init(url:String, email:String, password:String) { self.init() } /** Calls the documentWasAdded method in the MeteorCollection subclass instance associated with the document collection - parameter collection: the string name of the collection to which the document belongs - parameter id: the string unique id that identifies the document on the server - parameter fields: an optional NSDictionary with the documents properties */ public override func documentWasAdded(collection:String, id:String, fields:NSDictionary?) { if let meteorCollection = Meteor.collections[collection] { meteorCollection.documentWasAdded(collection, id: id, fields: fields) } } /** Calls the documentWasChanged method in the MeteorCollection subclass instance associated with the document collection - parameter collection: the string name of the collection to which the document belongs - parameter id: the string unique id that identifies the document on the server - parameter fields: an optional NSDictionary with the documents properties - parameter cleared: an optional array of string property names to delete */ public override func documentWasChanged(collection:String, id:String, fields:NSDictionary?, cleared:[String]?) { if let meteorCollection = Meteor.collections[collection] { meteorCollection.documentWasChanged(collection, id: id, fields: fields, cleared: cleared) } } /** Calls the documentWasRemoved method in the MeteorCollection subclass instance associated with the document collection - parameter collection: the string name of the collection to which the document belongs - parameter id: the string unique id that identifies the document on the server */ public override func documentWasRemoved(collection:String, id:String) { if let meteorCollection = Meteor.collections[collection] { meteorCollection.documentWasRemoved(collection, id: id) } } } }
mit
2ab8aff9c17d623fa33217cde0a152fa
39.138587
170
0.656421
5.171919
false
false
false
false
fulldecent/fastlane
snapshot/lib/assets/SnapshotHelper.swift
2
5856
// // SnapshotHelper.swift // Example // // Created by Felix Krause on 10/8/15. // Copyright © 2015 Felix Krause. All rights reserved. // import Foundation import XCTest var deviceLanguage = "" var locale = "" @available(*, deprecated, message: "use setupSnapshot: instead") func setLanguage(_ app: XCUIApplication) { setupSnapshot(app) } func setupSnapshot(_ app: XCUIApplication) { Snapshot.setupSnapshot(app) } func snapshot(_ name: String, waitForLoadingIndicator: Bool = true) { Snapshot.snapshot(name, waitForLoadingIndicator: waitForLoadingIndicator) } open class Snapshot: NSObject { open class func setupSnapshot(_ app: XCUIApplication) { setLanguage(app) setLocale(app) setLaunchArguments(app) } class func setLanguage(_ app: XCUIApplication) { guard let prefix = pathPrefix() else { return } let path = prefix.appendingPathComponent("language.txt") do { let trimCharacterSet = CharacterSet.whitespacesAndNewlines deviceLanguage = try String(contentsOf: path, encoding: .utf8).trimmingCharacters(in: trimCharacterSet) app.launchArguments += ["-AppleLanguages", "(\(deviceLanguage))"] } catch { print("Couldn't detect/set language...") } } class func setLocale(_ app: XCUIApplication) { guard let prefix = pathPrefix() else { return } let path = prefix.appendingPathComponent("locale.txt") do { let trimCharacterSet = CharacterSet.whitespacesAndNewlines locale = try String(contentsOf: path, encoding: .utf8).trimmingCharacters(in: trimCharacterSet) } catch { print("Couldn't detect/set locale...") } if locale.isEmpty { locale = Locale(identifier: deviceLanguage).identifier } app.launchArguments += ["-AppleLocale", "\"\(locale)\""] } class func setLaunchArguments(_ app: XCUIApplication) { guard let prefix = pathPrefix() else { return } let path = prefix.appendingPathComponent("snapshot-launch_arguments.txt") app.launchArguments += ["-FASTLANE_SNAPSHOT", "YES", "-ui_testing"] do { let launchArguments = try String(contentsOf: path, encoding: String.Encoding.utf8) let regex = try NSRegularExpression(pattern: "(\\\".+?\\\"|\\S+)", options: []) let matches = regex.matches(in: launchArguments, options: [], range: NSRange(location:0, length:launchArguments.characters.count)) let results = matches.map { result -> String in (launchArguments as NSString).substring(with: result.range) } app.launchArguments += results } catch { print("Couldn't detect/set launch_arguments...") } } open class func snapshot(_ name: String, waitForLoadingIndicator: Bool = true) { if waitForLoadingIndicator { waitForLoadingIndicatorToDisappear() } print("snapshot: \(name)") // more information about this, check out https://github.com/fastlane/fastlane/tree/master/snapshot#how-does-it-work sleep(1) // Waiting for the animation to be finished (kind of) #if os(tvOS) XCUIApplication().childrenMatchingType(.Browser).count #elseif os(OSX) XCUIApplication().typeKey(XCUIKeyboardKeySecondaryFn, modifierFlags: []) #else XCUIDevice.shared().orientation = .unknown #endif } class func waitForLoadingIndicatorToDisappear() { #if os(tvOS) return #endif let query = XCUIApplication().statusBars.children(matching: .other).element(boundBy: 1).children(matching: .other) while (0..<query.count).map({ query.element(boundBy: $0) }).contains(where: { $0.isLoadingIndicator }) { sleep(1) print("Waiting for loading indicator to disappear...") } } class func pathPrefix() -> URL? { let homeDir: URL //on OSX config is stored in /Users/<username>/Library //and on iOS/tvOS/WatchOS it's in simulator's home dir #if os(OSX) guard let user = ProcessInfo().environment["USER"] else { print("Couldn't find Snapshot configuration files - can't detect current user ") return nil } guard let usersDir = FileManager.default.urls(for: .userDirectory, in: .localDomainMask).first else { print("Couldn't find Snapshot configuration files - can't detect `Users` dir") return nil } homeDir = usersDir.appendingPathComponent(user) #else guard let simulatorHostHome = ProcessInfo().environment["SIMULATOR_HOST_HOME"] else { print("Couldn't find simulator home location. Please, check SIMULATOR_HOST_HOME env variable.") return nil } guard let homeDirUrl = URL(string: simulatorHostHome) else { print("Can't prepare environment. Simulator home location is inaccessible. Does \(simulatorHostHome) exist?") return nil } homeDir = homeDirUrl #endif return homeDir.appendingPathComponent("Library/Caches/tools.fastlane") } } extension XCUIElement { var isLoadingIndicator: Bool { let whiteListedLoaders = ["GeofenceLocationTrackingOn", "StandardLocationTrackingOn"] if whiteListedLoaders.contains(self.identifier) { return false } return self.frame.size == CGSize(width: 10, height: 20) } } // Please don't remove the lines below // They are used to detect outdated configuration files // SnapshotHelperVersion [1.3]
mit
08fe26bef37b7e631bfc7e53a05f6c29
34.271084
151
0.622203
5.025751
false
false
false
false
modocache/Gift
Gift/Error/NSError+Domain.swift
1
1544
import Foundation internal extension NSError { /** Returns an NSError with an error domain and message for libgit2 errors. :param: errorCode An error code returned by a libgit2 function. :param: libGit2PointOfFailure The name of the libgit2 function that produced the error code. :returns: An NSError with a libgit2 error domain, code, and message. */ internal class func libGit2Error(errorCode: Int32, libGit2PointOfFailure: String? = nil) -> NSError { let code = Int(errorCode) var userInfo: [String: String] = [:] if let message = errorMessage(errorCode) { userInfo[NSLocalizedDescriptionKey] = message } else { userInfo[NSLocalizedDescriptionKey] = "Unknown libgit2 error." } if let pointOfFailure = libGit2PointOfFailure { userInfo[NSLocalizedFailureReasonErrorKey] = "\(pointOfFailure) failed." } return NSError(domain: libGit2ErrorDomain, code: code, userInfo: userInfo) } /** Returns an NSError with an error domain and message for Gift errors. :param: errorCode An error code corresponding to the type of failure that occurred. :param: description A localized description for the error. :returns: An NSError with a Gift error domain, plus the given error code and description. */ internal class func giftError(errorCode: GiftErrorCode, description: String) -> NSError { return NSError(domain: giftErrorDomain, code: errorCode.rawValue, userInfo: [NSLocalizedDescriptionKey: description]) } }
mit
10f2748e5ba2892a21c2ef4ea17dc26b
38.589744
121
0.716321
4.721713
false
false
false
false
takuran/UsingCocoaPodsInSwift
UsingCocoaPodsInSwift/DataManager.swift
1
3588
// // DataManager.swift // UsingCocoaPodsInSwift // // Created by Naoyuki Takura on 2014/07/28. // Copyright (c) 2014年 Naoyuki Takura. All rights reserved. // import Foundation private let _dbFilename:String = "my.db" //instance private let _instance:DataManager = DataManager(dbFilename: _dbFilename) class DataManager { private var m_db:FMDatabase private var m_dbPath:String init(dbFilename:String) { //create database file path at the document Directory var documentPath: AnyObject = NSSearchPathForDirectoriesInDomains( .DocumentDirectory, .UserDomainMask, true)[0] m_dbPath = (documentPath as NSString).stringByAppendingPathComponent(dbFilename) NSLog("db file path : %@", m_dbPath) m_db = FMDatabase(path:m_dbPath) //initialize schema if does not create schema ever. var fileManager = NSFileManager.defaultManager() if !fileManager.fileExistsAtPath(m_dbPath) { //db file not exist //initialize db schema if m_db.open() { m_db.executeUpdate( "create table memo(id integer primary key autoincrement, contents text, 'update' integer)", withArgumentsInArray: []) m_db.close() NSLog("initialize database schema.") } } } func open() -> Bool { return m_db.open() } func close() -> Bool { return m_db.close() } func commit() -> Bool { return m_db.commit() } class func sharedInstance() -> DataManager { return _instance } func createNewContent(content:String) -> Bool { if m_db.goodConnection() { m_db.beginTransaction() m_db.executeUpdate("insert into memo (contents, 'update') values (?, ?)", withArgumentsInArray: [content, NSDate()]) m_db.commit() //OK return true } //FAIL, database not opend. return false; } func allContents() -> Array<(Int32, String!, NSDate!)> { if !m_db.goodConnection() { return []; } //empty array var contentsArray:[(Int32, String!, NSDate!)] = [] var resultSet:FMResultSet = m_db.executeQuery("select * from memo order by 'update'", withArgumentsInArray: []) while resultSet.next() { var index = resultSet.intForColumnIndex(0) var contents = resultSet.stringForColumnIndex(1) var nowDate = resultSet.dateForColumnIndex(2) var row:(Int32, String!, NSDate!) = (index, contents, nowDate) //append to array of contents contentsArray += [row] } return contentsArray } func deleteRecord(index:Int) -> Bool { if !m_db.goodConnection() { return false } m_db.beginTransaction() var result = m_db.executeUpdate("delete from memo where id = ?", withArgumentsInArray: [index]) m_db.commit() return result } func count() -> Int32? { if !m_db.goodConnection() { return nil } var resultSet:FMResultSet = m_db.executeQuery("select count(*) from memo", withArgumentsInArray: []) resultSet.next() var count:Int32 = resultSet.intForColumnIndex(0) return count } }
mit
e5a683dbb9fd9e106e7bbdf910fef160
26.381679
128
0.552705
4.730871
false
false
false
false
zhugejunwei/Algorithms-in-Java-Swift-CPP
Dijkstra & Floyd/Carthage/Checkouts/Charts/Charts/Classes/Charts/BarLineChartViewBase.swift
2
63054
// // BarLineChartViewBase.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics import UIKit /// Base-class of LineChart, BarChart, ScatterChart and CandleStickChart. public class BarLineChartViewBase: ChartViewBase, UIGestureRecognizerDelegate { /// the maximum number of entried to which values will be drawn internal var _maxVisibleValueCount = 100 /// flag that indicates if auto scaling on the y axis is enabled private var _autoScaleMinMaxEnabled = false private var _autoScaleLastLowestVisibleXIndex: Int! private var _autoScaleLastHighestVisibleXIndex: Int! private var _pinchZoomEnabled = false private var _doubleTapToZoomEnabled = true private var _dragEnabled = true private var _scaleXEnabled = true private var _scaleYEnabled = true /// the color for the background of the chart-drawing area (everything behind the grid lines). public var gridBackgroundColor = UIColor(red: 240/255.0, green: 240/255.0, blue: 240/255.0, alpha: 1.0) public var borderColor = UIColor.blackColor() public var borderLineWidth: CGFloat = 1.0 /// flag indicating if the grid background should be drawn or not public var drawGridBackgroundEnabled = true /// Sets drawing the borders rectangle to true. If this is enabled, there is no point drawing the axis-lines of x- and y-axis. public var drawBordersEnabled = false /// Sets the minimum offset (padding) around the chart, defaults to 10 public var minOffset = CGFloat(10.0) /// the object representing the labels on the y-axis, this object is prepared /// in the pepareYLabels() method internal var _leftAxis: ChartYAxis! internal var _rightAxis: ChartYAxis! /// the object representing the labels on the x-axis internal var _xAxis: ChartXAxis! internal var _leftYAxisRenderer: ChartYAxisRenderer! internal var _rightYAxisRenderer: ChartYAxisRenderer! internal var _leftAxisTransformer: ChartTransformer! internal var _rightAxisTransformer: ChartTransformer! internal var _xAxisRenderer: ChartXAxisRenderer! internal var _tapGestureRecognizer: UITapGestureRecognizer! internal var _doubleTapGestureRecognizer: UITapGestureRecognizer! #if !os(tvOS) internal var _pinchGestureRecognizer: UIPinchGestureRecognizer! #endif internal var _panGestureRecognizer: UIPanGestureRecognizer! /// flag that indicates if a custom viewport offset has been set private var _customViewPortEnabled = false public override init(frame: CGRect) { super.init(frame: frame) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } deinit { stopDeceleration() } internal override func initialize() { super.initialize() _leftAxis = ChartYAxis(position: .Left) _rightAxis = ChartYAxis(position: .Right) _xAxis = ChartXAxis() _leftAxisTransformer = ChartTransformer(viewPortHandler: _viewPortHandler) _rightAxisTransformer = ChartTransformer(viewPortHandler: _viewPortHandler) _leftYAxisRenderer = ChartYAxisRenderer(viewPortHandler: _viewPortHandler, yAxis: _leftAxis, transformer: _leftAxisTransformer) _rightYAxisRenderer = ChartYAxisRenderer(viewPortHandler: _viewPortHandler, yAxis: _rightAxis, transformer: _rightAxisTransformer) _xAxisRenderer = ChartXAxisRenderer(viewPortHandler: _viewPortHandler, xAxis: _xAxis, transformer: _leftAxisTransformer) _highlighter = ChartHighlighter(chart: self) _tapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("tapGestureRecognized:")) _doubleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("doubleTapGestureRecognized:")) _doubleTapGestureRecognizer.numberOfTapsRequired = 2 _panGestureRecognizer = UIPanGestureRecognizer(target: self, action: Selector("panGestureRecognized:")) _panGestureRecognizer.delegate = self self.addGestureRecognizer(_tapGestureRecognizer) self.addGestureRecognizer(_doubleTapGestureRecognizer) self.addGestureRecognizer(_panGestureRecognizer) _doubleTapGestureRecognizer.enabled = _doubleTapToZoomEnabled _panGestureRecognizer.enabled = _dragEnabled #if !os(tvOS) _pinchGestureRecognizer = UIPinchGestureRecognizer(target: self, action: Selector("pinchGestureRecognized:")) _pinchGestureRecognizer.delegate = self self.addGestureRecognizer(_pinchGestureRecognizer) _pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled #endif } public override func drawRect(rect: CGRect) { super.drawRect(rect) if (_dataNotSet) { return } let context = UIGraphicsGetCurrentContext() calcModulus() if (_xAxisRenderer !== nil) { _xAxisRenderer!.calcXBounds(chart: self, xAxisModulus: _xAxis.axisLabelModulus) } if (renderer !== nil) { renderer!.calcXBounds(chart: self, xAxisModulus: _xAxis.axisLabelModulus) } // execute all drawing commands drawGridBackground(context: context) if (_leftAxis.isEnabled) { _leftYAxisRenderer?.computeAxis(yMin: _leftAxis.axisMinimum, yMax: _leftAxis.axisMaximum) } if (_rightAxis.isEnabled) { _rightYAxisRenderer?.computeAxis(yMin: _rightAxis.axisMinimum, yMax: _rightAxis.axisMaximum) } _xAxisRenderer?.renderAxisLine(context: context) _leftYAxisRenderer?.renderAxisLine(context: context) _rightYAxisRenderer?.renderAxisLine(context: context) if (_autoScaleMinMaxEnabled) { let lowestVisibleXIndex = self.lowestVisibleXIndex, highestVisibleXIndex = self.highestVisibleXIndex if (_autoScaleLastLowestVisibleXIndex == nil || _autoScaleLastLowestVisibleXIndex != lowestVisibleXIndex || _autoScaleLastHighestVisibleXIndex == nil || _autoScaleLastHighestVisibleXIndex != highestVisibleXIndex) { calcMinMax() calculateOffsets() _autoScaleLastLowestVisibleXIndex = lowestVisibleXIndex _autoScaleLastHighestVisibleXIndex = highestVisibleXIndex } } // make sure the graph values and grid cannot be drawn outside the content-rect CGContextSaveGState(context) CGContextClipToRect(context, _viewPortHandler.contentRect) if (_xAxis.isDrawLimitLinesBehindDataEnabled) { _xAxisRenderer?.renderLimitLines(context: context) } if (_leftAxis.isDrawLimitLinesBehindDataEnabled) { _leftYAxisRenderer?.renderLimitLines(context: context) } if (_rightAxis.isDrawLimitLinesBehindDataEnabled) { _rightYAxisRenderer?.renderLimitLines(context: context) } _xAxisRenderer?.renderGridLines(context: context) _leftYAxisRenderer?.renderGridLines(context: context) _rightYAxisRenderer?.renderGridLines(context: context) renderer?.drawData(context: context) if (!_xAxis.isDrawLimitLinesBehindDataEnabled) { _xAxisRenderer?.renderLimitLines(context: context) } if (!_leftAxis.isDrawLimitLinesBehindDataEnabled) { _leftYAxisRenderer?.renderLimitLines(context: context) } if (!_rightAxis.isDrawLimitLinesBehindDataEnabled) { _rightYAxisRenderer?.renderLimitLines(context: context) } // if highlighting is enabled if (valuesToHighlight()) { renderer?.drawHighlighted(context: context, indices: _indicesToHightlight) } // Removes clipping rectangle CGContextRestoreGState(context) renderer!.drawExtras(context: context) _xAxisRenderer.renderAxisLabels(context: context) _leftYAxisRenderer.renderAxisLabels(context: context) _rightYAxisRenderer.renderAxisLabels(context: context) renderer!.drawValues(context: context) _legendRenderer.renderLegend(context: context) // drawLegend() drawMarkers(context: context) drawDescription(context: context) } internal func prepareValuePxMatrix() { _rightAxisTransformer.prepareMatrixValuePx(chartXMin: _chartXMin, deltaX: _deltaX, deltaY: CGFloat(_rightAxis.axisRange), chartYMin: _rightAxis.axisMinimum) _leftAxisTransformer.prepareMatrixValuePx(chartXMin: _chartXMin, deltaX: _deltaX, deltaY: CGFloat(_leftAxis.axisRange), chartYMin: _leftAxis.axisMinimum) } internal func prepareOffsetMatrix() { _rightAxisTransformer.prepareMatrixOffset(_rightAxis.isInverted) _leftAxisTransformer.prepareMatrixOffset(_leftAxis.isInverted) } public override func notifyDataSetChanged() { if (_dataNotSet) { return } calcMinMax() _leftAxis?._defaultValueFormatter = _defaultValueFormatter _rightAxis?._defaultValueFormatter = _defaultValueFormatter _leftYAxisRenderer?.computeAxis(yMin: _leftAxis.axisMinimum, yMax: _leftAxis.axisMaximum) _rightYAxisRenderer?.computeAxis(yMin: _rightAxis.axisMinimum, yMax: _rightAxis.axisMaximum) _xAxisRenderer?.computeAxis(xValAverageLength: _data.xValAverageLength, xValues: _data.xVals) if (_legend !== nil) { _legendRenderer?.computeLegend(_data) } calculateOffsets() setNeedsDisplay() } internal override func calcMinMax() { if (_autoScaleMinMaxEnabled) { _data.calcMinMax(start: lowestVisibleXIndex, end: highestVisibleXIndex) } var minLeft = _data.getYMin(.Left) var maxLeft = _data.getYMax(.Left) var minRight = _data.getYMin(.Right) var maxRight = _data.getYMax(.Right) let leftRange = abs(maxLeft - (_leftAxis.isStartAtZeroEnabled ? 0.0 : minLeft)) let rightRange = abs(maxRight - (_rightAxis.isStartAtZeroEnabled ? 0.0 : minRight)) // in case all values are equal if (leftRange == 0.0) { maxLeft = maxLeft + 1.0 if (!_leftAxis.isStartAtZeroEnabled) { minLeft = minLeft - 1.0 } } if (rightRange == 0.0) { maxRight = maxRight + 1.0 if (!_rightAxis.isStartAtZeroEnabled) { minRight = minRight - 1.0 } } let topSpaceLeft = leftRange * Double(_leftAxis.spaceTop) let topSpaceRight = rightRange * Double(_rightAxis.spaceTop) let bottomSpaceLeft = leftRange * Double(_leftAxis.spaceBottom) let bottomSpaceRight = rightRange * Double(_rightAxis.spaceBottom) _chartXMax = Double(_data.xVals.count - 1) _deltaX = CGFloat(abs(_chartXMax - _chartXMin)) // Consider sticking one of the edges of the axis to zero (0.0) if _leftAxis.isStartAtZeroEnabled { if minLeft < 0.0 && maxLeft < 0.0 { // If the values are all negative, let's stay in the negative zone _leftAxis.axisMinimum = min(0.0, !isnan(_leftAxis.customAxisMin) ? _leftAxis.customAxisMin : (minLeft - bottomSpaceLeft)) _leftAxis.axisMaximum = 0.0 } else if minLeft >= 0.0 { // We have positive values only, stay in the positive zone _leftAxis.axisMinimum = 0.0 _leftAxis.axisMaximum = max(0.0, !isnan(_leftAxis.customAxisMax) ? _leftAxis.customAxisMax : (maxLeft + topSpaceLeft)) } else { // Stick the minimum to 0.0 or less, and maximum to 0.0 or more (startAtZero for negative/positive at the same time) _leftAxis.axisMinimum = min(0.0, !isnan(_leftAxis.customAxisMin) ? _leftAxis.customAxisMin : (minLeft - bottomSpaceLeft)) _leftAxis.axisMaximum = max(0.0, !isnan(_leftAxis.customAxisMax) ? _leftAxis.customAxisMax : (maxLeft + topSpaceLeft)) } } else { // Use the values as they are _leftAxis.axisMinimum = !isnan(_leftAxis.customAxisMin) ? _leftAxis.customAxisMin : (minLeft - bottomSpaceLeft) _leftAxis.axisMaximum = !isnan(_leftAxis.customAxisMax) ? _leftAxis.customAxisMax : (maxLeft + topSpaceLeft) } if _rightAxis.isStartAtZeroEnabled { if minRight < 0.0 && maxRight < 0.0 { // If the values are all negative, let's stay in the negative zone _rightAxis.axisMinimum = min(0.0, !isnan(_rightAxis.customAxisMin) ? _rightAxis.customAxisMin : (minRight - bottomSpaceRight)) _rightAxis.axisMaximum = 0.0 } else if minRight >= 0.0 { // We have positive values only, stay in the positive zone _rightAxis.axisMinimum = 0.0 _rightAxis.axisMaximum = max(0.0, !isnan(_rightAxis.customAxisMax) ? _rightAxis.customAxisMax : (maxRight + topSpaceRight)) } else { // Stick the minimum to 0.0 or less, and maximum to 0.0 or more (startAtZero for negative/positive at the same time) _rightAxis.axisMinimum = min(0.0, !isnan(_rightAxis.customAxisMin) ? _rightAxis.customAxisMin : (minRight - bottomSpaceRight)) _rightAxis.axisMaximum = max(0.0, !isnan(_rightAxis.customAxisMax) ? _rightAxis.customAxisMax : (maxRight + topSpaceRight)) } } else { _rightAxis.axisMinimum = !isnan(_rightAxis.customAxisMin) ? _rightAxis.customAxisMin : (minRight - bottomSpaceRight) _rightAxis.axisMaximum = !isnan(_rightAxis.customAxisMax) ? _rightAxis.customAxisMax : (maxRight + topSpaceRight) } _leftAxis.axisRange = abs(_leftAxis.axisMaximum - _leftAxis.axisMinimum) _rightAxis.axisRange = abs(_rightAxis.axisMaximum - _rightAxis.axisMinimum) } internal override func calculateOffsets() { if (!_customViewPortEnabled) { var offsetLeft = CGFloat(0.0) var offsetRight = CGFloat(0.0) var offsetTop = CGFloat(0.0) var offsetBottom = CGFloat(0.0) // setup offsets for legend if (_legend !== nil && _legend.isEnabled) { if (_legend.position == .RightOfChart || _legend.position == .RightOfChartCenter) { offsetRight += min(_legend.neededWidth, _viewPortHandler.chartWidth * _legend.maxSizePercent) + _legend.xOffset * 2.0 } if (_legend.position == .LeftOfChart || _legend.position == .LeftOfChartCenter) { offsetLeft += min(_legend.neededWidth, _viewPortHandler.chartWidth * _legend.maxSizePercent) + _legend.xOffset * 2.0 } else if (_legend.position == .BelowChartLeft || _legend.position == .BelowChartRight || _legend.position == .BelowChartCenter) { // It's possible that we do not need this offset anymore as it // is available through the extraOffsets, but changing it can mean // changing default visibility for existing apps. let yOffset = _legend.textHeightMax offsetBottom += min(_legend.neededHeight + yOffset, _viewPortHandler.chartHeight * _legend.maxSizePercent) } else if (_legend.position == .AboveChartLeft || _legend.position == .AboveChartRight || _legend.position == .AboveChartCenter) { // It's possible that we do not need this offset anymore as it // is available through the extraOffsets, but changing it can mean // changing default visibility for existing apps. let yOffset = _legend.textHeightMax offsetTop += min(_legend.neededHeight + yOffset, _viewPortHandler.chartHeight * _legend.maxSizePercent) } } // offsets for y-labels if (leftAxis.needsOffset) { offsetLeft += leftAxis.requiredSize().width } if (rightAxis.needsOffset) { offsetRight += rightAxis.requiredSize().width } if (xAxis.isEnabled && xAxis.isDrawLabelsEnabled) { let xlabelheight = xAxis.labelHeight * 2.0 // offsets for x-labels if (xAxis.labelPosition == .Bottom) { offsetBottom += xlabelheight } else if (xAxis.labelPosition == .Top) { offsetTop += xlabelheight } else if (xAxis.labelPosition == .BothSided) { offsetBottom += xlabelheight offsetTop += xlabelheight } } offsetTop += self.extraTopOffset offsetRight += self.extraRightOffset offsetBottom += self.extraBottomOffset offsetLeft += self.extraLeftOffset _viewPortHandler.restrainViewPort( offsetLeft: max(self.minOffset, offsetLeft), offsetTop: max(self.minOffset, offsetTop), offsetRight: max(self.minOffset, offsetRight), offsetBottom: max(self.minOffset, offsetBottom)) } prepareOffsetMatrix() prepareValuePxMatrix() } /// calculates the modulus for x-labels and grid internal func calcModulus() { if (_xAxis === nil || !_xAxis.isEnabled) { return } if (!_xAxis.isAxisModulusCustom) { _xAxis.axisLabelModulus = Int(ceil((CGFloat(_data.xValCount) * _xAxis.labelWidth) / (_viewPortHandler.contentWidth * _viewPortHandler.touchMatrix.a))) } if (_xAxis.axisLabelModulus < 1) { _xAxis.axisLabelModulus = 1 } } public override func getMarkerPosition(entry e: ChartDataEntry, highlight: ChartHighlight) -> CGPoint { let dataSetIndex = highlight.dataSetIndex var xPos = CGFloat(e.xIndex) var yPos = CGFloat(e.value) if (self.isKindOfClass(BarChartView)) { let bd = _data as! BarChartData let space = bd.groupSpace let setCount = _data.dataSetCount let i = e.xIndex if self is HorizontalBarChartView { // calculate the x-position, depending on datasetcount let y = CGFloat(i + i * (setCount - 1) + dataSetIndex) + space * CGFloat(i) + space / 2.0 yPos = y if let entry = e as? BarChartDataEntry { if entry.values != nil && highlight.range !== nil { xPos = CGFloat(highlight.range!.to) } else { xPos = CGFloat(e.value) } } } else { let x = CGFloat(i + i * (setCount - 1) + dataSetIndex) + space * CGFloat(i) + space / 2.0 xPos = x if let entry = e as? BarChartDataEntry { if entry.values != nil && highlight.range !== nil { yPos = CGFloat(highlight.range!.to) } else { yPos = CGFloat(e.value) } } } } // position of the marker depends on selected value index and value var pt = CGPoint(x: xPos, y: yPos * _animator.phaseY) getTransformer(_data.getDataSetByIndex(dataSetIndex)!.axisDependency).pointValueToPixel(&pt) return pt } /// draws the grid background internal func drawGridBackground(context context: CGContext?) { if (drawGridBackgroundEnabled || drawBordersEnabled) { CGContextSaveGState(context) } if (drawGridBackgroundEnabled) { // draw the grid background CGContextSetFillColorWithColor(context, gridBackgroundColor.CGColor) CGContextFillRect(context, _viewPortHandler.contentRect) } if (drawBordersEnabled) { CGContextSetLineWidth(context, borderLineWidth) CGContextSetStrokeColorWithColor(context, borderColor.CGColor) CGContextStrokeRect(context, _viewPortHandler.contentRect) } if (drawGridBackgroundEnabled || drawBordersEnabled) { CGContextRestoreGState(context) } } /// - returns: the Transformer class that contains all matrices and is /// responsible for transforming values into pixels on the screen and /// backwards. public func getTransformer(which: ChartYAxis.AxisDependency) -> ChartTransformer { if (which == .Left) { return _leftAxisTransformer } else { return _rightAxisTransformer } } // MARK: - Gestures private enum GestureScaleAxis { case Both case X case Y } private var _isDragging = false private var _isScaling = false private var _gestureScaleAxis = GestureScaleAxis.Both private var _closestDataSetToTouch: ChartDataSet! private var _panGestureReachedEdge: Bool = false private weak var _outerScrollView: UIScrollView? private var _lastPanPoint = CGPoint() /// This is to prevent using setTranslation which resets velocity private var _decelerationLastTime: NSTimeInterval = 0.0 private var _decelerationDisplayLink: CADisplayLink! private var _decelerationVelocity = CGPoint() @objc private func tapGestureRecognized(recognizer: UITapGestureRecognizer) { if (_dataNotSet) { return } if (recognizer.state == UIGestureRecognizerState.Ended) { let h = getHighlightByTouchPoint(recognizer.locationInView(self)) if (h === nil || h!.isEqual(self.lastHighlighted)) { self.highlightValue(highlight: nil, callDelegate: true) self.lastHighlighted = nil } else { self.lastHighlighted = h self.highlightValue(highlight: h, callDelegate: true) } } } @objc private func doubleTapGestureRecognized(recognizer: UITapGestureRecognizer) { if (_dataNotSet) { return } if (recognizer.state == UIGestureRecognizerState.Ended) { if (!_dataNotSet && _doubleTapToZoomEnabled) { var location = recognizer.locationInView(self) location.x = location.x - _viewPortHandler.offsetLeft if (isAnyAxisInverted && _closestDataSetToTouch !== nil && getAxis(_closestDataSetToTouch.axisDependency).isInverted) { location.y = -(location.y - _viewPortHandler.offsetTop) } else { location.y = -(self.bounds.size.height - location.y - _viewPortHandler.offsetBottom) } self.zoom(isScaleXEnabled ? 1.4 : 1.0, scaleY: isScaleYEnabled ? 1.4 : 1.0, x: location.x, y: location.y) } } } #if !os(tvOS) @objc private func pinchGestureRecognized(recognizer: UIPinchGestureRecognizer) { if (recognizer.state == UIGestureRecognizerState.Began) { stopDeceleration() if (!_dataNotSet && (_pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled)) { _isScaling = true if (_pinchZoomEnabled) { _gestureScaleAxis = .Both } else { let x = abs(recognizer.locationInView(self).x - recognizer.locationOfTouch(1, inView: self).x) let y = abs(recognizer.locationInView(self).y - recognizer.locationOfTouch(1, inView: self).y) if (x > y) { _gestureScaleAxis = .X } else { _gestureScaleAxis = .Y } } } } else if (recognizer.state == UIGestureRecognizerState.Ended || recognizer.state == UIGestureRecognizerState.Cancelled) { if (_isScaling) { _isScaling = false // Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets. calculateOffsets() setNeedsDisplay() } } else if (recognizer.state == UIGestureRecognizerState.Changed) { let isZoomingOut = (recognizer.scale < 1) let canZoomMoreX = isZoomingOut ? _viewPortHandler.canZoomOutMoreX : _viewPortHandler.canZoomInMoreX if (_isScaling) { if (canZoomMoreX || (_gestureScaleAxis == .Both || _gestureScaleAxis == .Y && _scaleYEnabled)) { var location = recognizer.locationInView(self) location.x = location.x - _viewPortHandler.offsetLeft if (isAnyAxisInverted && _closestDataSetToTouch !== nil && getAxis(_closestDataSetToTouch.axisDependency).isInverted) { location.y = -(location.y - _viewPortHandler.offsetTop) } else { location.y = -(_viewPortHandler.chartHeight - location.y - _viewPortHandler.offsetBottom) } let scaleX = (_gestureScaleAxis == .Both || _gestureScaleAxis == .X) && _scaleXEnabled ? recognizer.scale : 1.0 let scaleY = (_gestureScaleAxis == .Both || _gestureScaleAxis == .Y) && _scaleYEnabled ? recognizer.scale : 1.0 var matrix = CGAffineTransformMakeTranslation(location.x, location.y) matrix = CGAffineTransformScale(matrix, scaleX, scaleY) matrix = CGAffineTransformTranslate(matrix, -location.x, -location.y) matrix = CGAffineTransformConcat(_viewPortHandler.touchMatrix, matrix) _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true) if (delegate !== nil) { delegate?.chartScaled?(self, scaleX: scaleX, scaleY: scaleY) } } recognizer.scale = 1.0 } } } #endif @objc private func panGestureRecognized(recognizer: UIPanGestureRecognizer) { if (recognizer.state == UIGestureRecognizerState.Began && recognizer.numberOfTouches() > 0) { stopDeceleration() if ((!_dataNotSet && _dragEnabled && !self.hasNoDragOffset) || !self.isFullyZoomedOut) { _isDragging = true _closestDataSetToTouch = getDataSetByTouchPoint(recognizer.locationOfTouch(0, inView: self)) let translation = recognizer.translationInView(self) let didUserDrag = (self is HorizontalBarChartView) ? translation.y != 0.0 : translation.x != 0.0 // Check to see if user dragged at all and if so, can the chart be dragged by the given amount if (didUserDrag && !performPanChange(translation: translation)) { if (_outerScrollView !== nil) { // We can stop dragging right now, and let the scroll view take control _outerScrollView = nil _isDragging = false } } else { if (_outerScrollView !== nil) { // Prevent the parent scroll view from scrolling _outerScrollView?.scrollEnabled = false } } _lastPanPoint = recognizer.translationInView(self) } } else if (recognizer.state == UIGestureRecognizerState.Changed) { if (_isDragging) { let originalTranslation = recognizer.translationInView(self) let translation = CGPoint(x: originalTranslation.x - _lastPanPoint.x, y: originalTranslation.y - _lastPanPoint.y) performPanChange(translation: translation) _lastPanPoint = originalTranslation } else if (isHighlightPerDragEnabled) { let h = getHighlightByTouchPoint(recognizer.locationInView(self)) let lastHighlighted = self.lastHighlighted if ((h === nil && lastHighlighted !== nil) || (h !== nil && lastHighlighted === nil) || (h !== nil && lastHighlighted !== nil && !h!.isEqual(lastHighlighted))) { self.lastHighlighted = h self.highlightValue(highlight: h, callDelegate: true) } } } else if (recognizer.state == UIGestureRecognizerState.Ended || recognizer.state == UIGestureRecognizerState.Cancelled) { if (_isDragging) { if (recognizer.state == UIGestureRecognizerState.Ended && isDragDecelerationEnabled) { stopDeceleration() _decelerationLastTime = CACurrentMediaTime() _decelerationVelocity = recognizer.velocityInView(self) _decelerationDisplayLink = CADisplayLink(target: self, selector: Selector("decelerationLoop")) _decelerationDisplayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes) } _isDragging = false } if (_outerScrollView !== nil) { _outerScrollView?.scrollEnabled = true _outerScrollView = nil } } } private func performPanChange(var translation translation: CGPoint) -> Bool { if (isAnyAxisInverted && _closestDataSetToTouch !== nil && getAxis(_closestDataSetToTouch.axisDependency).isInverted) { if (self is HorizontalBarChartView) { translation.x = -translation.x } else { translation.y = -translation.y } } let originalMatrix = _viewPortHandler.touchMatrix var matrix = CGAffineTransformMakeTranslation(translation.x, translation.y) matrix = CGAffineTransformConcat(originalMatrix, matrix) matrix = _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true) if (delegate !== nil) { delegate?.chartTranslated?(self, dX: translation.x, dY: translation.y) } // Did we managed to actually drag or did we reach the edge? return matrix.tx != originalMatrix.tx || matrix.ty != originalMatrix.ty } public func stopDeceleration() { if (_decelerationDisplayLink !== nil) { _decelerationDisplayLink.removeFromRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes) _decelerationDisplayLink = nil } } @objc private func decelerationLoop() { let currentTime = CACurrentMediaTime() _decelerationVelocity.x *= self.dragDecelerationFrictionCoef _decelerationVelocity.y *= self.dragDecelerationFrictionCoef let timeInterval = CGFloat(currentTime - _decelerationLastTime) let distance = CGPoint( x: _decelerationVelocity.x * timeInterval, y: _decelerationVelocity.y * timeInterval ) if (!performPanChange(translation: distance)) { // We reached the edge, stop _decelerationVelocity.x = 0.0 _decelerationVelocity.y = 0.0 } _decelerationLastTime = currentTime if (abs(_decelerationVelocity.x) < 0.001 && abs(_decelerationVelocity.y) < 0.001) { stopDeceleration() // Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets. calculateOffsets() setNeedsDisplay() } } public override func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool { if (!super.gestureRecognizerShouldBegin(gestureRecognizer)) { return false } if (gestureRecognizer == _panGestureRecognizer) { if (_dataNotSet || !_dragEnabled || !self.hasNoDragOffset || (self.isFullyZoomedOut && !self.isHighlightPerDragEnabled)) { return false } } else { #if !os(tvOS) if (gestureRecognizer == _pinchGestureRecognizer) { if (_dataNotSet || (!_pinchZoomEnabled && !_scaleXEnabled && !_scaleYEnabled)) { return false } } #endif } return true } public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { #if !os(tvOS) if ((gestureRecognizer.isKindOfClass(UIPinchGestureRecognizer) && otherGestureRecognizer.isKindOfClass(UIPanGestureRecognizer)) || (gestureRecognizer.isKindOfClass(UIPanGestureRecognizer) && otherGestureRecognizer.isKindOfClass(UIPinchGestureRecognizer))) { return true } #endif if (gestureRecognizer.isKindOfClass(UIPanGestureRecognizer) && otherGestureRecognizer.isKindOfClass(UIPanGestureRecognizer) && ( gestureRecognizer == _panGestureRecognizer )) { var scrollView = self.superview while (scrollView !== nil && !scrollView!.isKindOfClass(UIScrollView)) { scrollView = scrollView?.superview } var foundScrollView = scrollView as? UIScrollView if (foundScrollView !== nil && !foundScrollView!.scrollEnabled) { foundScrollView = nil } var scrollViewPanGestureRecognizer: UIGestureRecognizer! if (foundScrollView !== nil) { for scrollRecognizer in foundScrollView!.gestureRecognizers! { if (scrollRecognizer.isKindOfClass(UIPanGestureRecognizer)) { scrollViewPanGestureRecognizer = scrollRecognizer as! UIPanGestureRecognizer break } } } if (otherGestureRecognizer === scrollViewPanGestureRecognizer) { _outerScrollView = foundScrollView return true } } return false } /// MARK: Viewport modifiers /// Zooms in by 1.4, into the charts center. center. public func zoomIn() { let matrix = _viewPortHandler.zoomIn(x: self.bounds.size.width / 2.0, y: -(self.bounds.size.height / 2.0)) _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true) // Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets. calculateOffsets() setNeedsDisplay() } /// Zooms out by 0.7, from the charts center. center. public func zoomOut() { let matrix = _viewPortHandler.zoomOut(x: self.bounds.size.width / 2.0, y: -(self.bounds.size.height / 2.0)) _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true) // Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets. calculateOffsets() setNeedsDisplay() } /// Zooms in or out by the given scale factor. x and y are the coordinates /// (in pixels) of the zoom center. /// /// - parameter scaleX: if < 1 --> zoom out, if > 1 --> zoom in /// - parameter scaleY: if < 1 --> zoom out, if > 1 --> zoom in /// - parameter x: /// - parameter y: public func zoom(scaleX: CGFloat, scaleY: CGFloat, x: CGFloat, y: CGFloat) { let matrix = _viewPortHandler.zoom(scaleX: scaleX, scaleY: scaleY, x: x, y: -y) _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: false) // Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets. calculateOffsets() setNeedsDisplay() } /// Resets all zooming and dragging and makes the chart fit exactly it's bounds. public func fitScreen() { let matrix = _viewPortHandler.fitScreen() _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: false) // Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets. calculateOffsets() setNeedsDisplay() } /// Sets the minimum scale value to which can be zoomed out. 1 = fitScreen public func setScaleMinima(scaleX: CGFloat, scaleY: CGFloat) { _viewPortHandler.setMinimumScaleX(scaleX) _viewPortHandler.setMinimumScaleY(scaleY) } /// Sets the size of the area (range on the x-axis) that should be maximum visible at once (no further zomming out allowed). /// If this is e.g. set to 10, no more than 10 values on the x-axis can be viewed at once without scrolling. public func setVisibleXRangeMaximum(maxXRange: CGFloat) { let xScale = _deltaX / maxXRange _viewPortHandler.setMinimumScaleX(xScale) } /// Sets the size of the area (range on the x-axis) that should be minimum visible at once (no further zooming in allowed). /// If this is e.g. set to 10, no more than 10 values on the x-axis can be viewed at once without scrolling. public func setVisibleXRangeMinimum(minXRange: CGFloat) { let xScale = _deltaX / minXRange _viewPortHandler.setMaximumScaleX(xScale) } /// Limits the maximum and minimum value count that can be visible by pinching and zooming. /// e.g. minRange=10, maxRange=100 no less than 10 values and no more that 100 values can be viewed /// at once without scrolling public func setVisibleXRange(minXRange minXRange: CGFloat, maxXRange: CGFloat) { let maxScale = _deltaX / minXRange let minScale = _deltaX / maxXRange _viewPortHandler.setMinMaxScaleX(minScaleX: minScale, maxScaleX: maxScale) } /// Sets the size of the area (range on the y-axis) that should be maximum visible at once. /// /// - parameter yRange: /// - parameter axis: - the axis for which this limit should apply public func setVisibleYRangeMaximum(maxYRange: CGFloat, axis: ChartYAxis.AxisDependency) { let yScale = getDeltaY(axis) / maxYRange _viewPortHandler.setMinimumScaleY(yScale) } /// Moves the left side of the current viewport to the specified x-index. /// This also refreshes the chart by calling setNeedsDisplay(). public func moveViewToX(xIndex: Int) { if (_viewPortHandler.hasChartDimens) { var pt = CGPoint(x: CGFloat(xIndex), y: 0.0) getTransformer(.Left).pointValueToPixel(&pt) _viewPortHandler.centerViewPort(pt: pt, chart: self) } else { _sizeChangeEventActions.append({[weak self] () in self?.moveViewToX(xIndex); }) } } /// Centers the viewport to the specified y-value on the y-axis. /// This also refreshes the chart by calling setNeedsDisplay(). /// /// - parameter yValue: /// - parameter axis: - which axis should be used as a reference for the y-axis public func moveViewToY(yValue: CGFloat, axis: ChartYAxis.AxisDependency) { if (_viewPortHandler.hasChartDimens) { let valsInView = getDeltaY(axis) / _viewPortHandler.scaleY var pt = CGPoint(x: 0.0, y: yValue + valsInView / 2.0) getTransformer(axis).pointValueToPixel(&pt) _viewPortHandler.centerViewPort(pt: pt, chart: self) } else { _sizeChangeEventActions.append({[weak self] () in self?.moveViewToY(yValue, axis: axis); }) } } /// This will move the left side of the current viewport to the specified x-index on the x-axis, and center the viewport to the specified y-value on the y-axis. /// This also refreshes the chart by calling setNeedsDisplay(). /// /// - parameter xIndex: /// - parameter yValue: /// - parameter axis: - which axis should be used as a reference for the y-axis public func moveViewTo(xIndex xIndex: Int, yValue: CGFloat, axis: ChartYAxis.AxisDependency) { if (_viewPortHandler.hasChartDimens) { let valsInView = getDeltaY(axis) / _viewPortHandler.scaleY var pt = CGPoint(x: CGFloat(xIndex), y: yValue + valsInView / 2.0) getTransformer(axis).pointValueToPixel(&pt) _viewPortHandler.centerViewPort(pt: pt, chart: self) } else { _sizeChangeEventActions.append({[weak self] () in self?.moveViewTo(xIndex: xIndex, yValue: yValue, axis: axis); }) } } /// This will move the center of the current viewport to the specified x-index and y-value. /// This also refreshes the chart by calling setNeedsDisplay(). /// /// - parameter xIndex: /// - parameter yValue: /// - parameter axis: - which axis should be used as a reference for the y-axis public func centerViewTo(xIndex xIndex: Int, yValue: CGFloat, axis: ChartYAxis.AxisDependency) { if (_viewPortHandler.hasChartDimens) { let valsInView = getDeltaY(axis) / _viewPortHandler.scaleY let xsInView = CGFloat(xAxis.values.count) / _viewPortHandler.scaleX var pt = CGPoint(x: CGFloat(xIndex) - xsInView / 2.0, y: yValue + valsInView / 2.0) getTransformer(axis).pointValueToPixel(&pt) _viewPortHandler.centerViewPort(pt: pt, chart: self) } else { _sizeChangeEventActions.append({[weak self] () in self?.centerViewTo(xIndex: xIndex, yValue: yValue, axis: axis); }) } } /// Sets custom offsets for the current `ChartViewPort` (the offsets on the sides of the actual chart window). Setting this will prevent the chart from automatically calculating it's offsets. Use `resetViewPortOffsets()` to undo this. /// ONLY USE THIS WHEN YOU KNOW WHAT YOU ARE DOING, else use `setExtraOffsets(...)`. public func setViewPortOffsets(left left: CGFloat, top: CGFloat, right: CGFloat, bottom: CGFloat) { _customViewPortEnabled = true if (NSThread.isMainThread()) { self._viewPortHandler.restrainViewPort(offsetLeft: left, offsetTop: top, offsetRight: right, offsetBottom: bottom) prepareOffsetMatrix() prepareValuePxMatrix() } else { dispatch_async(dispatch_get_main_queue(), { self.setViewPortOffsets(left: left, top: top, right: right, bottom: bottom) }) } } /// Resets all custom offsets set via `setViewPortOffsets(...)` method. Allows the chart to again calculate all offsets automatically. public func resetViewPortOffsets() { _customViewPortEnabled = false calculateOffsets() } // MARK: - Accessors /// - returns: the delta-y value (y-value range) of the specified axis. public func getDeltaY(axis: ChartYAxis.AxisDependency) -> CGFloat { if (axis == .Left) { return CGFloat(leftAxis.axisRange) } else { return CGFloat(rightAxis.axisRange) } } /// - returns: the position (in pixels) the provided Entry has inside the chart view public func getPosition(e: ChartDataEntry, axis: ChartYAxis.AxisDependency) -> CGPoint { var vals = CGPoint(x: CGFloat(e.xIndex), y: CGFloat(e.value)) getTransformer(axis).pointValueToPixel(&vals) return vals } /// the number of maximum visible drawn values on the chart /// only active when `setDrawValues()` is enabled public var maxVisibleValueCount: Int { get { return _maxVisibleValueCount } set { _maxVisibleValueCount = newValue } } /// is dragging enabled? (moving the chart with the finger) for the chart (this does not affect scaling). public var dragEnabled: Bool { get { return _dragEnabled } set { if (_dragEnabled != newValue) { _dragEnabled = newValue } } } /// is dragging enabled? (moving the chart with the finger) for the chart (this does not affect scaling). public var isDragEnabled: Bool { return dragEnabled } /// is scaling enabled? (zooming in and out by gesture) for the chart (this does not affect dragging). public func setScaleEnabled(enabled: Bool) { if (_scaleXEnabled != enabled || _scaleYEnabled != enabled) { _scaleXEnabled = enabled _scaleYEnabled = enabled #if !os(tvOS) _pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled #endif } } public var scaleXEnabled: Bool { get { return _scaleXEnabled } set { if (_scaleXEnabled != newValue) { _scaleXEnabled = newValue #if !os(tvOS) _pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled #endif } } } public var scaleYEnabled: Bool { get { return _scaleYEnabled } set { if (_scaleYEnabled != newValue) { _scaleYEnabled = newValue #if !os(tvOS) _pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled #endif } } } public var isScaleXEnabled: Bool { return scaleXEnabled; } public var isScaleYEnabled: Bool { return scaleYEnabled; } /// flag that indicates if double tap zoom is enabled or not public var doubleTapToZoomEnabled: Bool { get { return _doubleTapToZoomEnabled } set { if (_doubleTapToZoomEnabled != newValue) { _doubleTapToZoomEnabled = newValue _doubleTapGestureRecognizer.enabled = _doubleTapToZoomEnabled } } } /// **default**: true /// - returns: true if zooming via double-tap is enabled false if not. public var isDoubleTapToZoomEnabled: Bool { return doubleTapToZoomEnabled } /// flag that indicates if highlighting per dragging over a fully zoomed out chart is enabled public var highlightPerDragEnabled = true /// If set to true, highlighting per dragging over a fully zoomed out chart is enabled /// You might want to disable this when using inside a `UIScrollView` /// /// **default**: true public var isHighlightPerDragEnabled: Bool { return highlightPerDragEnabled } /// **default**: true /// - returns: true if drawing the grid background is enabled, false if not. public var isDrawGridBackgroundEnabled: Bool { return drawGridBackgroundEnabled } /// **default**: false /// - returns: true if drawing the borders rectangle is enabled, false if not. public var isDrawBordersEnabled: Bool { return drawBordersEnabled } /// - returns: the Highlight object (contains x-index and DataSet index) of the selected value at the given touch point inside the Line-, Scatter-, or CandleStick-Chart. public func getHighlightByTouchPoint(pt: CGPoint) -> ChartHighlight? { if (_dataNotSet || _data === nil) { print("Can't select by touch. No data set.", terminator: "\n") return nil } return _highlighter?.getHighlight(x: Double(pt.x), y: Double(pt.y)) } /// - returns: the x and y values in the chart at the given touch point /// (encapsulated in a `CGPoint`). This method transforms pixel coordinates to /// coordinates / values in the chart. This is the opposite method to /// `getPixelsForValues(...)`. public func getValueByTouchPoint(var pt pt: CGPoint, axis: ChartYAxis.AxisDependency) -> CGPoint { getTransformer(axis).pixelToValue(&pt) return pt } /// Transforms the given chart values into pixels. This is the opposite /// method to `getValueByTouchPoint(...)`. public func getPixelForValue(x: Double, y: Double, axis: ChartYAxis.AxisDependency) -> CGPoint { var pt = CGPoint(x: CGFloat(x), y: CGFloat(y)) getTransformer(axis).pointValueToPixel(&pt) return pt } /// - returns: the y-value at the given touch position (must not necessarily be /// a value contained in one of the datasets) public func getYValueByTouchPoint(pt pt: CGPoint, axis: ChartYAxis.AxisDependency) -> CGFloat { return getValueByTouchPoint(pt: pt, axis: axis).y } /// - returns: the Entry object displayed at the touched position of the chart public func getEntryByTouchPoint(pt: CGPoint) -> ChartDataEntry! { let h = getHighlightByTouchPoint(pt) if (h !== nil) { return _data!.getEntryForHighlight(h!) } return nil } /// - returns: the DataSet object displayed at the touched position of the chart public func getDataSetByTouchPoint(pt: CGPoint) -> BarLineScatterCandleBubbleChartDataSet! { let h = getHighlightByTouchPoint(pt) if (h !== nil) { return _data.getDataSetByIndex(h!.dataSetIndex) as! BarLineScatterCandleBubbleChartDataSet! } return nil } /// - returns: the lowest x-index (value on the x-axis) that is still visible on he chart. public var lowestVisibleXIndex: Int { var pt = CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom) getTransformer(.Left).pixelToValue(&pt) return (pt.x <= 0.0) ? 0 : Int(pt.x + 1.0) } /// - returns: the highest x-index (value on the x-axis) that is still visible on the chart. public var highestVisibleXIndex: Int { var pt = CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentBottom) getTransformer(.Left).pixelToValue(&pt) return (_data != nil && Int(pt.x) >= _data.xValCount) ? _data.xValCount - 1 : Int(pt.x) } /// - returns: the current x-scale factor public var scaleX: CGFloat { if (_viewPortHandler === nil) { return 1.0 } return _viewPortHandler.scaleX } /// - returns: the current y-scale factor public var scaleY: CGFloat { if (_viewPortHandler === nil) { return 1.0 } return _viewPortHandler.scaleY } /// if the chart is fully zoomed out, return true public var isFullyZoomedOut: Bool { return _viewPortHandler.isFullyZoomedOut; } /// - returns: the left y-axis object. In the horizontal bar-chart, this is the /// top axis. public var leftAxis: ChartYAxis { return _leftAxis } /// - returns: the right y-axis object. In the horizontal bar-chart, this is the /// bottom axis. public var rightAxis: ChartYAxis { return _rightAxis; } /// - returns: the y-axis object to the corresponding AxisDependency. In the /// horizontal bar-chart, LEFT == top, RIGHT == BOTTOM public func getAxis(axis: ChartYAxis.AxisDependency) -> ChartYAxis { if (axis == .Left) { return _leftAxis } else { return _rightAxis } } /// - returns: the object representing all x-labels, this method can be used to /// acquire the XAxis object and modify it (e.g. change the position of the /// labels) public var xAxis: ChartXAxis { return _xAxis } /// flag that indicates if pinch-zoom is enabled. if true, both x and y axis can be scaled with 2 fingers, if false, x and y axis can be scaled separately public var pinchZoomEnabled: Bool { get { return _pinchZoomEnabled } set { if (_pinchZoomEnabled != newValue) { _pinchZoomEnabled = newValue #if !os(tvOS) _pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled #endif } } } /// **default**: false /// - returns: true if pinch-zoom is enabled, false if not public var isPinchZoomEnabled: Bool { return pinchZoomEnabled; } /// Set an offset in dp that allows the user to drag the chart over it's /// bounds on the x-axis. public func setDragOffsetX(offset: CGFloat) { _viewPortHandler.setDragOffsetX(offset) } /// Set an offset in dp that allows the user to drag the chart over it's /// bounds on the y-axis. public func setDragOffsetY(offset: CGFloat) { _viewPortHandler.setDragOffsetY(offset) } /// - returns: true if both drag offsets (x and y) are zero or smaller. public var hasNoDragOffset: Bool { return _viewPortHandler.hasNoDragOffset; } /// The X axis renderer. This is a read-write property so you can set your own custom renderer here. /// **default**: An instance of ChartXAxisRenderer /// - returns: The current set X axis renderer public var xAxisRenderer: ChartXAxisRenderer { get { return _xAxisRenderer } set { _xAxisRenderer = newValue } } /// The left Y axis renderer. This is a read-write property so you can set your own custom renderer here. /// **default**: An instance of ChartYAxisRenderer /// - returns: The current set left Y axis renderer public var leftYAxisRenderer: ChartYAxisRenderer { get { return _leftYAxisRenderer } set { _leftYAxisRenderer = newValue } } /// The right Y axis renderer. This is a read-write property so you can set your own custom renderer here. /// **default**: An instance of ChartYAxisRenderer /// - returns: The current set right Y axis renderer public var rightYAxisRenderer: ChartYAxisRenderer { get { return _rightYAxisRenderer } set { _rightYAxisRenderer = newValue } } public override var chartYMax: Double { return max(leftAxis.axisMaximum, rightAxis.axisMaximum) } public override var chartYMin: Double { return min(leftAxis.axisMinimum, rightAxis.axisMinimum) } /// - returns: true if either the left or the right or both axes are inverted. public var isAnyAxisInverted: Bool { return _leftAxis.isInverted || _rightAxis.isInverted } /// flag that indicates if auto scaling on the y axis is enabled. /// if yes, the y axis automatically adjusts to the min and max y values of the current x axis range whenever the viewport changes public var autoScaleMinMaxEnabled: Bool { get { return _autoScaleMinMaxEnabled; } set { _autoScaleMinMaxEnabled = newValue; } } /// **default**: false /// - returns: true if auto scaling on the y axis is enabled. public var isAutoScaleMinMaxEnabled : Bool { return autoScaleMinMaxEnabled; } /// Sets a minimum width to the specified y axis. public func setYAxisMinWidth(which: ChartYAxis.AxisDependency, width: CGFloat) { if (which == .Left) { _leftAxis.minWidth = width } else { _rightAxis.minWidth = width } } /// **default**: 0.0 /// - returns: the (custom) minimum width of the specified Y axis. public func getYAxisMinWidth(which: ChartYAxis.AxisDependency) -> CGFloat { if (which == .Left) { return _leftAxis.minWidth } else { return _rightAxis.minWidth } } /// Sets a maximum width to the specified y axis. /// Zero (0.0) means there's no maximum width public func setYAxisMaxWidth(which: ChartYAxis.AxisDependency, width: CGFloat) { if (which == .Left) { _leftAxis.maxWidth = width } else { _rightAxis.maxWidth = width } } /// Zero (0.0) means there's no maximum width /// /// **default**: 0.0 (no maximum specified) /// - returns: the (custom) maximum width of the specified Y axis. public func getYAxisMaxWidth(which: ChartYAxis.AxisDependency) -> CGFloat { if (which == .Left) { return _leftAxis.maxWidth } else { return _rightAxis.maxWidth } } /// - returns the width of the specified y axis. public func getYAxisWidth(which: ChartYAxis.AxisDependency) -> CGFloat { if (which == .Left) { return _leftAxis.requiredSize().width } else { return _rightAxis.requiredSize().width } } } /// Default formatter that calculates the position of the filled line. internal class BarLineChartFillFormatter: NSObject, ChartFillFormatter { private weak var _chart: BarLineChartViewBase! internal init(chart: BarLineChartViewBase) { _chart = chart } internal func getFillLinePosition(dataSet dataSet: LineChartDataSet, data: LineChartData, chartMaxY: Double, chartMinY: Double) -> CGFloat { var fillMin = CGFloat(0.0) if (dataSet.yMax > 0.0 && dataSet.yMin < 0.0) { fillMin = 0.0 } else { if (!_chart.getAxis(dataSet.axisDependency).isStartAtZeroEnabled) { var max: Double, min: Double if (data.yMax > 0.0) { max = 0.0 } else { max = chartMaxY } if (data.yMin < 0.0) { min = 0.0 } else { min = chartMinY } fillMin = CGFloat(dataSet.yMin >= 0.0 ? min : max) } else { fillMin = 0.0 } } return fillMin } }
mit
84fc1091205ae2d59d28007b834dffc4
35.258769
238
0.576046
5.620287
false
false
false
false
athiercelin/ATSketchKit
ATSketchKitDemo/ATControlPanelView.swift
1
3385
// // ATControlPanelView.swift // ATSketchKit // // Created by Arnaud Thiercelin on 1/12/16. // Copyright © 2016 Arnaud Thiercelin. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial // portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT // NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE // OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import UIKit class ATControlPanelView: UIView { let collapsedDistance: CGFloat = 36.0 let previewDistance: CGFloat = 90.0 let expandedDistance: CGFloat = 250.0 @IBOutlet weak var handleLabel: UILabel! @IBOutlet weak var positionConstraint: NSLayoutConstraint! override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let touchPoint = touches.first!.preciseLocation(in: self) let handleRect = handleLabel.frame if handleRect.contains(touchPoint) { self.toggleExpandCollapse() } } // MARK: - Expand/Collapse controls func toggleExpandCollapse() { let currentPositionConstant = self.positionConstraint.constant if currentPositionConstant == self.collapsedDistance { self.preview() } else if currentPositionConstant == self.previewDistance || currentPositionConstant == self.expandedDistance { self.collapse() } // This case here is for smooth drag n drop, split view style. To be implemented AT 01-2016 } func toggleShowDetails() { let currentPositionConstant = self.positionConstraint.constant if currentPositionConstant == self.expandedDistance { self.preview() } else { self.expand() } } func expand() { self.positionConstraint.constant = self.expandedDistance UIView.animate(withDuration: 0.3) { () -> Void in self.layoutIfNeeded() } } func preview() { self.positionConstraint.constant = self.previewDistance UIView.animate(withDuration: 0.3) { () -> Void in self.layoutIfNeeded() } } func collapse() { self.positionConstraint.constant = self.collapsedDistance UIView.animate(withDuration: 0.3) { () -> Void in self.layoutIfNeeded() } } // MARK: - Custom Drawing override func draw(_ rect: CGRect) { super.draw(rect) // Draw line to match navigation bar let path = UIBezierPath() path.move(to: CGPoint(x: rect.minX, y: rect.minY)) path.addLine(to: CGPoint(x: rect.maxX, y: rect.minY)) UIColor.lightGray.set() path.stroke() } }
mit
08936402bbad6d4523da8b3afad60e49
33.530612
113
0.697104
4.240602
false
false
false
false
albertoqa/Focusin
Focusin/PlistManager.swift
1
8693
// // PlistManager.swift // PlistManagerExample // // Created by SANDOR NAGY on 27/05/16. // Copyright © 2016 Rebeloper. All rights reserved. // import Foundation let plistFileName:String = "Tasks" struct Plist { enum PlistError: Error { case fileNotWritten case fileDoesNotExist } let name:String var sourcePath:String? { guard let path = Bundle.main.path(forResource: name, ofType: "plist") else { return .none } return path } var destPath:String? { guard sourcePath != .none else { return .none } let dir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] return (dir as NSString).appendingPathComponent("\(name).plist") } init?(name:String) { self.name = name let fileManager = FileManager.default guard let source = sourcePath else { return nil } guard let destination = destPath else { return nil } guard fileManager.fileExists(atPath: source) else { return nil } if !fileManager.fileExists(atPath: destination) { do { try fileManager.copyItem(atPath: source, toPath: destination) } catch let error as NSError { print("[PlistManager] Unable to copy file. ERROR: \(error.localizedDescription)") return nil } } } func getValuesInPlistFile() -> NSDictionary?{ let fileManager = FileManager.default if fileManager.fileExists(atPath: destPath!) { guard let dict = NSDictionary(contentsOfFile: destPath!) else { return .none } return dict } else { return .none } } func getMutablePlistFile() -> NSMutableDictionary?{ let fileManager = FileManager.default if fileManager.fileExists(atPath: destPath!) { guard let dict = NSMutableDictionary(contentsOfFile: destPath!) else { return .none } return dict } else { return .none } } func addValuesToPlistFile(_ dictionary:NSDictionary) throws { let fileManager = FileManager.default if fileManager.fileExists(atPath: destPath!) { if !dictionary.write(toFile: destPath!, atomically: false) { print("[PlistManager] File not written successfully") throw PlistError.fileNotWritten } } else { throw PlistError.fileDoesNotExist } } } class PlistManager { static let sharedInstance = PlistManager() fileprivate init() {} //This prevents others from using the default '()' initializer for this class. func startPlistManager() { if let _ = Plist(name: plistFileName) { print("[PlistManager] PlistManager started") } } func addNewItemWithKey(_ key:String, value:AnyObject) { print("[PlistManager] Starting to add item for key '\(key) with value '\(value)' . . .") if !keyAlreadyExists(key) { if let plist = Plist(name: plistFileName) { let dict = plist.getMutablePlistFile()! dict[key] = value do { try plist.addValuesToPlistFile(dict) } catch { print(error) } print("[PlistManager] An Action has been performed. You can check if it went ok by taking a look at the current content of the plist file: ") print("[PlistManager] \(plist.getValuesInPlistFile())") } else { print("[PlistManager] Unable to get Plist") } } else { print("[PlistManager] Item for key '\(key)' already exists. Not saving Item. Not overwriting value.") } } func removeItemForKey(_ key:String) { print("[PlistManager] Starting to remove item for key '\(key) . . .") if keyAlreadyExists(key) { if let plist = Plist(name: plistFileName) { let dict = plist.getMutablePlistFile()! dict.removeObject(forKey: key) do { try plist.addValuesToPlistFile(dict) } catch { print(error) } print("[PlistManager] An Action has been performed. You can check if it went ok by taking a look at the current content of the plist file: ") print("[PlistManager] \(plist.getValuesInPlistFile())") } else { print("[PlistManager] Unable to get Plist") } } else { print("[PlistManager] Item for key '\(key)' does not exists. Remove canceled.") } } func removeAllItemsFromPlist() { if let plist = Plist(name: plistFileName) { let dict = plist.getMutablePlistFile()! let keys = Array(dict.allKeys) if keys.count != 0 { dict.removeAllObjects() } else { print("[PlistManager] Plist is already empty. Removal of all items canceled.") } do { try plist.addValuesToPlistFile(dict) } catch { print(error) } print("[PlistManager] An Action has been performed. You can check if it went ok by taking a look at the current content of the plist file: ") print("[PlistManager] \(plist.getValuesInPlistFile())") } else { print("[PlistManager] Unable to get Plist") } } func saveValue(_ value:AnyObject, forKey:String) { if let plist = Plist(name: plistFileName) { let dict = plist.getMutablePlistFile()! if let dictValue = dict[forKey] { if type(of: value) != type(of: dictValue) { print("[PlistManager] WARNING: You are saving a \(type(of: value)) typed value into a \(type(of: dictValue)) typed value. Best practice is to save Int values to Int fields, String values to String fields etc. (For example: '_NSContiguousString' to '__NSCFString' is ok too; they are both String types) If you believe that this mismatch in the types of the values is ok and will not break your code than disregard this message.") } dict[forKey] = value } do { try plist.addValuesToPlistFile(dict) } catch { print(error) } print("[PlistManager] An Action has been performed. You can check if it went ok by taking a look at the current content of the plist file: ") print("[PlistManager] \(plist.getValuesInPlistFile())") } else { print("[PlistManager] Unable to get Plist") } } func getValueForKey(_ key:String) -> AnyObject? { var value:AnyObject? if let plist = Plist(name: plistFileName) { let dict = plist.getMutablePlistFile()! let keys = Array(dict.allKeys) //print("[PlistManager] Keys are: \(keys)") if keys.count != 0 { for (_,element) in keys.enumerated() { //print("[PlistManager] Key Index - \(index) = \(element)") if element as! String == key { print("[PlistManager] Found the Item that we were looking for for key: [\(key)]") value = dict[key]! as AnyObject? } else { //print("[PlistManager] This is Item with key '\(element)' and not the Item that we are looking for with key: \(key)") } } if value != nil { //print("[PlistManager] The Element that we were looking for exists: [\(key)]: \(value)") return value! } else { print("[PlistManager] WARNING: The Item for key '\(key)' does not exist! Please, check your spelling.") return .none } } else { print("[PlistManager] No Plist Item Found when searching for item with key: \(key). The Plist is Empty!") return .none } } else { print("[PlistManager] Unable to get Plist") return .none } } func keyAlreadyExists(_ key:String) -> Bool { var keyExists = false if let plist = Plist(name: plistFileName) { let dict = plist.getMutablePlistFile()! let keys = Array(dict.allKeys) //print("[PlistManager] Keys are: \(keys)") if keys.count != 0 { for (_,element) in keys.enumerated() { //print("[PlistManager] Key Index - \(index) = \(element)") if element as! String == key { print("[PlistManager] Checked if item exists and found it for key: [\(key)]") keyExists = true } else { //print("[PlistManager] This is Element with key '\(element)' and not the Element that we are looking for with Key: \(key)") } } } else { //print("[PlistManager] No Plist Element Found with Key: \(key). The Plist is Empty!") keyExists = false } } else { //print("[PlistManager] Unable to get Plist") keyExists = false } return keyExists } }
mit
c965bba99996fb6468fa03a512f2fe25
29.822695
438
0.600782
4.678149
false
false
false
false
wltrup/iOS-Swift-Circular-Progress-View
CircularProgressView/CustomCell.swift
2
3418
// // CustomCell.swift // CircularProgressView // // Created by Wagner Truppel on 01/05/2015. // Copyright (c) 2015 Wagner Truppel. All rights reserved. // import UIKit class CustomCell: UITableViewCell { @IBOutlet weak var photoView: UIImageView! @IBOutlet weak var progressView: CircularProgressView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var emailLabel: UILabel! var dataItem: DataItem? { didSet { if let dataItem = self.dataItem { self.nameLabel.text = dataItem.personName self.emailLabel.text = dataItem.personEmail self.photoView!.image = UIImage(named: dataItem.photoName) } else { self.nameLabel.text = nil self.emailLabel.text = nil self.photoView!.image = nil } } } override func awakeFromNib() { super.awakeFromNib() showContent(false, animated: false) } func showContent(show: Bool, animated: Bool) { if animated { let duration: NSTimeInterval = (show ? 0.3 : 0.25) animateContent(duration, show: show) } else { let alpha: CGFloat = (show ? 1.0 : 0.0) photoView.alpha = alpha progressView.alpha = 1.0 - alpha nameLabel.hidden = !show nameLabel.alpha = alpha emailLabel.hidden = !show emailLabel.alpha = alpha } } } // Content animation extension CustomCell { private func animateContent(duration: NSTimeInterval, show: Bool) { if show { UIView.animateWithDuration(0.75, animations: { self.photoView.alpha = 1.0 self.progressView.alpha = 0.0 }, completion: { (completed) -> Void in self.animateView(self.nameLabel, duration: duration, show: true, completion: { (completed) -> Void in self.animateView(self.emailLabel, duration: duration, show: show, completion: nil) }) }) } else { self.animateView(self.emailLabel, duration: duration, show: false, completion: { (completed) -> Void in self.animateView(self.nameLabel, duration: duration, show: false, completion: { (completed) -> Void in UIView.animateWithDuration(0.75, animations: { self.photoView.alpha = 0.0 self.progressView.alpha = 1.0 }) }) }) } } private func animateView(view: UIView, duration: NSTimeInterval, show: Bool, completion: ((Bool) -> Void)?) { let alpha: CGFloat = (show ? 1.0 : 0.0) UIView.animateWithDuration(duration, animations: { view.alpha = alpha }, completion: { (completed) -> Void in view.hidden = !show completion?(completed) }) } }
mit
02cdd5a554955dfc6f124b7ffa4aa2cd
27.966102
111
0.486834
5.210366
false
false
false
false
yeziahehe/Gank
Pods/PKHUD/PKHUD/PKHUD.swift
1
7129
// // HUD.swift // PKHUD // // Created by Philip Kluz on 6/13/14. // Copyright (c) 2016 NSExceptional. All rights reserved. // Licensed under the MIT license. // import UIKit /// The PKHUD object controls showing and hiding of the HUD, as well as its contents and touch response behavior. open class PKHUD: NSObject { fileprivate struct Constants { static let sharedHUD = PKHUD() } public var viewToPresentOn: UIView? fileprivate let container = ContainerView() fileprivate var hideTimer: Timer? public typealias TimerAction = (Bool) -> Void fileprivate var timerActions = [String: TimerAction]() /// Grace period is the time (in seconds) that the invoked method may be run without /// showing the HUD. If the task finishes before the grace time runs out, the HUD will /// not be shown at all. /// This may be used to prevent HUD display for very short tasks. /// Defaults to 0 (no grace time). @available(*, deprecated, message: "Will be removed with Swift4 support, use gracePeriod instead") public var graceTime: TimeInterval { get { return gracePeriod } set(newPeriod) { gracePeriod = newPeriod } } /// Grace period is the time (in seconds) that the invoked method may be run without /// showing the HUD. If the task finishes before the grace time runs out, the HUD will /// not be shown at all. /// This may be used to prevent HUD display for very short tasks. /// Defaults to 0 (no grace time). public var gracePeriod: TimeInterval = 0 fileprivate var graceTimer: Timer? // MARK: Public open class var sharedHUD: PKHUD { return Constants.sharedHUD } public override init () { super.init() #if swift(>=4.2) let notificationName = UIApplication.willEnterForegroundNotification #else let notificationName = NSNotification.Name.UIApplicationWillEnterForeground #endif NotificationCenter.default.addObserver(self, selector: #selector(PKHUD.willEnterForeground(_:)), name: notificationName, object: nil) userInteractionOnUnderlyingViewsEnabled = false container.frameView.autoresizingMask = [ .flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, .flexibleBottomMargin ] self.container.isAccessibilityElement = true self.container.accessibilityIdentifier = "PKHUD" } public convenience init(viewToPresentOn view: UIView) { self.init() viewToPresentOn = view } deinit { NotificationCenter.default.removeObserver(self) } open var dimsBackground = true open var userInteractionOnUnderlyingViewsEnabled: Bool { get { return !container.isUserInteractionEnabled } set { container.isUserInteractionEnabled = !newValue } } open var isVisible: Bool { return !container.isHidden } open var contentView: UIView { get { return container.frameView.content } set { container.frameView.content = newValue startAnimatingContentView() } } open var effect: UIVisualEffect? { get { return container.frameView.effect } set { container.frameView.effect = newValue } } open var leadingMargin: CGFloat = 0 open var trailingMargin: CGFloat = 0 open func show(onView view: UIView? = nil) { let view: UIView = view ?? viewToPresentOn ?? UIApplication.shared.keyWindow! if !view.subviews.contains(container) { view.addSubview(container) container.frame.origin = CGPoint.zero container.frame.size = view.frame.size container.autoresizingMask = [ .flexibleHeight, .flexibleWidth ] container.isHidden = true } if dimsBackground { container.showBackground(animated: true) } // If the grace time is set, postpone the HUD display if gracePeriod > 0.0 { let timer = Timer(timeInterval: gracePeriod, target: self, selector: #selector(PKHUD.handleGraceTimer(_:)), userInfo: nil, repeats: false) #if swift(>=4.2) RunLoop.current.add(timer, forMode: .common) #else RunLoop.current.add(timer, forMode: .commonModes) #endif graceTimer = timer } else { showContent() } } func showContent() { graceTimer?.invalidate() container.showFrameView() startAnimatingContentView() } open func hide(animated anim: Bool = true, completion: TimerAction? = nil) { graceTimer?.invalidate() container.hideFrameView(animated: anim, completion: completion) stopAnimatingContentView() } open func hide(_ animated: Bool, completion: TimerAction? = nil) { hide(animated: animated, completion: completion) } open func hide(afterDelay delay: TimeInterval, completion: TimerAction? = nil) { let key = UUID().uuidString let userInfo = ["timerActionKey": key] if let completion = completion { timerActions[key] = completion } hideTimer?.invalidate() hideTimer = Timer.scheduledTimer(timeInterval: delay, target: self, selector: #selector(PKHUD.performDelayedHide(_:)), userInfo: userInfo, repeats: false) } // MARK: Internal @objc internal func willEnterForeground(_ notification: Notification?) { self.startAnimatingContentView() } internal func startAnimatingContentView() { if let animatingContentView = contentView as? PKHUDAnimating, isVisible { animatingContentView.startAnimation() } } internal func stopAnimatingContentView() { if let animatingContentView = contentView as? PKHUDAnimating { animatingContentView.stopAnimation?() } } // MARK: Timer callbacks @objc internal func performDelayedHide(_ timer: Timer? = nil) { let userInfo = timer?.userInfo as? [String: AnyObject] let key = userInfo?["timerActionKey"] as? String var completion: TimerAction? if let key = key, let action = timerActions[key] { completion = action timerActions[key] = nil } hide(animated: true, completion: completion) } @objc internal func handleGraceTimer(_ timer: Timer? = nil) { // Show the HUD only if the task is still running if (graceTimer?.isValid)! { showContent() } } }
gpl-3.0
ab6b9e14440a00e634da3cdc09f72a58
30.96861
150
0.596718
5.230374
false
false
false
false
Johennes/firefox-ios
Client/Frontend/Browser/OpenInHelper.swift
1
9600
/* 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 PassKit import WebKit import SnapKit import Shared import XCGLogger private let log = Logger.browserLogger struct OpenInViewUX { static let ViewHeight: CGFloat = 40.0 static let TextFont = UIFont.systemFontOfSize(16) static let TextColor = UIColor(red: 74.0/255.0, green: 144.0/255.0, blue: 226.0/255.0, alpha: 1.0) static let TextOffset = -15 static let OpenInString = NSLocalizedString("Open in…", comment: "String indicating that the file can be opened in another application on the device") } enum MimeType: String { case PDF = "application/pdf" case PASS = "application/vnd.apple.pkpass" } protocol OpenInHelper { init?(response: NSURLResponse) var openInView: UIView? { get set } func open() } struct OpenIn { static let helpers: [OpenInHelper.Type] = [OpenPdfInHelper.self, OpenPassBookHelper.self, ShareFileHelper.self] static func helperForResponse(response: NSURLResponse) -> OpenInHelper? { return helpers.flatMap { $0.init(response: response) }.first } } class ShareFileHelper: NSObject, OpenInHelper { var openInView: UIView? = nil private var url: NSURL var pathExtension: String? required init?(response: NSURLResponse) { guard let MIMEType = response.MIMEType where !(MIMEType == MimeType.PASS.rawValue || MIMEType == MimeType.PDF.rawValue), let responseURL = response.URL else { return nil } url = responseURL super.init() } func open() { let alertController = UIAlertController( title: Strings.OpenInDownloadHelperAlertTitle, message: Strings.OpenInDownloadHelperAlertMessage, preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction( UIAlertAction(title: Strings.OpenInDownloadHelperAlertCancel, style: .Cancel, handler: nil)) alertController.addAction(UIAlertAction(title: Strings.OpenInDownloadHelperAlertConfirm, style: .Default) { (action) in let objectsToShare = [self.url] let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil) if let sourceView = self.openInView, popoverController = activityVC.popoverPresentationController { popoverController.sourceView = sourceView popoverController.sourceRect = CGRect(origin: CGPoint(x: CGRectGetMidX(sourceView.bounds), y: CGRectGetMaxY(sourceView.bounds)), size: CGSizeZero) popoverController.permittedArrowDirections = .Up } UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(activityVC, animated: true, completion: nil) }) UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(alertController, animated: true, completion: nil) } } class OpenPassBookHelper: NSObject, OpenInHelper { var openInView: UIView? = nil private var url: NSURL required init?(response: NSURLResponse) { guard let MIMEType = response.MIMEType where MIMEType == MimeType.PASS.rawValue && PKAddPassesViewController.canAddPasses(), let responseURL = response.URL else { return nil } url = responseURL super.init() } func open() { guard let passData = NSData(contentsOfURL: url) else { return } var error: NSError? = nil let pass = PKPass(data: passData, error: &error) if let _ = error { // display an error let alertController = UIAlertController( title: Strings.UnableToAddPassErrorTitle, message: Strings.UnableToAddPassErrorMessage, preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction( UIAlertAction(title: Strings.UnableToAddPassErrorDismiss, style: .Cancel) { (action) in // Do nothing. }) UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(alertController, animated: true, completion: nil) return } let passLibrary = PKPassLibrary() if passLibrary.containsPass(pass) { UIApplication.sharedApplication().openURL(pass.passURL!) } else { let addController = PKAddPassesViewController(pass: pass) UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(addController, animated: true, completion: nil) } } } class OpenPdfInHelper: NSObject, OpenInHelper, UIDocumentInteractionControllerDelegate { private var url: NSURL private var docController: UIDocumentInteractionController? = nil private var openInURL: NSURL? lazy var openInView: UIView? = getOpenInView(self)() lazy var documentDirectory: NSURL = { return NSURL(string: NSTemporaryDirectory())!.URLByAppendingPathComponent("pdfs")! }() private var filepath: NSURL? required init?(response: NSURLResponse) { guard let MIMEType = response.MIMEType where MIMEType == MimeType.PDF.rawValue && UIApplication.sharedApplication().canOpenURL(NSURL(string: "itms-books:")!), let responseURL = response.URL else { return nil } url = responseURL super.init() setFilePath(response.suggestedFilename ?? url.lastPathComponent ?? "file.pdf") } private func setFilePath(suggestedFilename: String) { var filename = suggestedFilename let pathExtension = filename.asURL?.pathExtension if pathExtension == nil { filename.appendContentsOf(".pdf") } filepath = documentDirectory.URLByAppendingPathComponent(filename) } deinit { guard let url = openInURL else { return } let fileManager = NSFileManager.defaultManager() do { try fileManager.removeItemAtURL(url) } catch { log.error("failed to delete file at \(url): \(error)") } } func getOpenInView() -> OpenInView { let overlayView = OpenInView() overlayView.openInButton.addTarget(self, action: #selector(OpenPdfInHelper.open), forControlEvents: .TouchUpInside) return overlayView } func createDocumentControllerForURL(url: NSURL) { docController = UIDocumentInteractionController(URL: url) docController?.delegate = self self.openInURL = url } func createLocalCopyOfPDF() { guard let filePath = filepath else { log.error("failed to create proper URL") return } if docController == nil { // if we already have a URL but no document controller, just create the document controller if let url = openInURL { createDocumentControllerForURL(url) return } let contentsOfFile = NSData(contentsOfURL: url) let fileManager = NSFileManager.defaultManager() do { try fileManager.createDirectoryAtPath(documentDirectory.absoluteString!, withIntermediateDirectories: true, attributes: nil) if fileManager.createFileAtPath(filePath.absoluteString!, contents: contentsOfFile, attributes: nil) { let openInURL = NSURL(fileURLWithPath: filePath.absoluteString!) createDocumentControllerForURL(openInURL) } else { log.error("Unable to create local version of PDF file at \(filePath)") } } catch { log.error("Error on creating directory at \(documentDirectory)") } } } func open() { createLocalCopyOfPDF() guard let _parentView = self.openInView!.superview, docController = self.docController else { log.error("view doesn't have a superview so can't open anything"); return } // iBooks should be installed by default on all devices we care about, so regardless of whether or not there are other pdf-capable // apps on this device, if we can open in iBooks we can open this PDF // simulators do not have iBooks so the open in view will not work on the simulator if UIApplication.sharedApplication().canOpenURL(NSURL(string: "itms-books:")!) { log.info("iBooks installed: attempting to open pdf") docController.presentOpenInMenuFromRect(CGRectZero, inView: _parentView, animated: true) } else { log.info("iBooks is not installed") } } } class OpenInView: UIView { let openInButton = UIButton() init() { super.init(frame: CGRectZero) openInButton.setTitleColor(OpenInViewUX.TextColor, forState: UIControlState.Normal) openInButton.setTitle(OpenInViewUX.OpenInString, forState: UIControlState.Normal) openInButton.titleLabel?.font = OpenInViewUX.TextFont openInButton.sizeToFit() self.addSubview(openInButton) openInButton.snp_makeConstraints { make in make.centerY.equalTo(self) make.height.equalTo(self) make.trailing.equalTo(self).offset(OpenInViewUX.TextOffset) } self.backgroundColor = UIColor.whiteColor() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mpl-2.0
635159d2e53fa0465e86b182ef8aa3fe
40.37069
177
0.668785
5.16577
false
false
false
false
gerdmuller/swiftnotes
SwiftMusic.playground/Contents.swift
2
2161
var c = Note() var a = Note() var C = Note() var f = Note() var Fis = Note() a.grundTon = .a C.oktave = .groß f.grundTon = .f Fis.grundTon = .f Fis.oktave = .groß Fis.vorzeichen = .kreuz print("------------------------") print(c.describe) print(a.describe) print(C.describe) print(f.describe) print(Fis.describe) print("------------------------") var i = Interval.determineFromNote(f, note2: a) print(i!.name) print("------------------------") i = Interval.determineFromNote(Fis, note2: c) print(i!.name) print("------------------------") i = Interval.determineFromNote(Fis, note2: C) print(i!.name) print("------------------------") i = Interval.determineFromNote(c, note2: C) print(i!.name) var A = Note() A.grundTon = .a A.oktave = .klein var aisis = Note() aisis.grundTon = .a aisis.vorzeichen = .doppelKreuz print("------------------------") i = Interval.determineFromNote(A, note2: aisis) print(i!.name) var terz = Interval(type: .Terz, modifier: .groß) var tri = Interval(type: .Quinte, modifier: .vermindert) var tri2 = Interval(type: .Quarte, modifier: .übermäßig) var tri3 = Interval(type: .Quarte, modifier: .tritonus) var tri4 = Interval(type: .Quinte, modifier: .tritonus) var tri5 = Interval(type: .Prim, modifier: .tritonus) var quarte = Interval(type: .Quarte, modifier: .doppeltVermindert) print("\(terz.describe)\n") print("\(tri.describe)\n") print("\(tri2.describe)\n") print("\(tri3.describe)\n") print("\(tri4.describe)\n") print("\(tri5.describe)\n") print("\(quarte.describe)\n") var d = Note() var fis = Note() d.grundTon = .d fis.grundTon = .f fis.vorzeichen = .kreuz print(d.describe) print(fis.describe) /* Was will ich berechnen können? - Note(n) parsen: c#' d'' D eb' - Intervall aus zwei Noten bestimmen - zweite Note aus erster Note und Intervall - zu einem Intervall alle möglichen Modifier bestimmen - Akkord aus drei oder vier Noten bestimmen - Folgenoten aus Grund-Note und Akkord - Note (von Tonart) nach Tonart modulieren - geht das so? - Tonleiter-Noten aus Grund-Note und Tonleiter erzeugen - Tonleiter aus Noten bestimmen - Paralleltonleiter bestimmen - Folgetonleiter bestimmen */
gpl-2.0
7a78ddff21c530163d7c27381f85bb4e
21.663158
67
0.656758
2.603386
false
false
false
false
swernimo/QuickSample
QuickSample/QuickSampleTests/SampleEntityTests.swift
1
911
// // SampleEntityTests.swift // QuickSample // // Created by Sean Wernimont on 11/19/16. // Copyright © 2016 The Blind Squirrel. All rights reserved. // import Quick import Nimble @testable import QuickSample class SampleEntityTests: QuickSpec { override func spec(){ describe("Sample Entity"){ it("speak should say Hello and append the supplied word"){ let entity = SampleEntity() let expected = "Hello Jane" let actual = entity.speak("Jane") expect(actual).to(equal(expected)) } it("square the supplied number"){ let entity = SampleEntity() let number = 2 let expected = 4 let actual = entity.squareNumber(number: number) expect(actual).to(equal(expected)) } } } }
mit
2da98382970a92aa631b4f494f870dcc
25
70
0.543956
4.739583
false
true
false
false
groue/GRDB.swift
GRDB/QueryInterface/Request/Association/HasOneAssociation.swift
1
3918
/// The `HasOneAssociation` indicates a one-to-one connection between two /// record types, such as each instance of the declaring record "has one" /// instances of the other record. /// /// For example, if your application has one database table for countries, and /// another for their demographic profiles, you'd declare the association /// this way: /// /// ```swift /// struct Demographics: TableRecord { } /// struct Country: TableRecord { /// static let demographics = hasOne(Demographics.self) /// } /// ``` /// /// A `HasOneAssociation` should be supported by an SQLite foreign key. /// /// Foreign keys are the recommended way to declare relationships between /// database tables because not only will SQLite guarantee the integrity of your /// data, but GRDB will be able to use those foreign keys to automatically /// configure your associations. /// /// You define the foreign key when you create database tables. For example: /// /// ```swift /// try db.create(table: "country") { t in /// t.column("code", .text).primaryKey() // (1) /// t.column("name", .text) /// } /// try db.create(table: "demographics") { t in /// t.autoIncrementedPrimaryKey("id") /// t.column("countryCode", .text) // (2) /// .notNull() // (3) /// .unique() // (4) /// .references("country", onDelete: .cascade) // (5) /// t.column("population", .integer) /// t.column("density", .double) /// } /// ``` /// /// 1. The country table has a primary key. /// 2. The `demographics.countryCode` column is used to link a demographic /// profile to the country it belongs to. /// 3. Make the `demographics.countryCode` column not null if you want SQLite to /// guarantee that all profiles are linked to a country. /// 4. Create a unique index on the `demographics.countryCode` column in order /// to guarantee the unicity of any country's demographics. /// 5. Create a foreign key from `demographics.countryCode` column to /// `country.code`, so that SQLite guarantees that no profile refers to a /// missing country. The `onDelete: .cascade` option has SQLite automatically /// delete a profile when its country is deleted. /// See <https://sqlite.org/foreignkeys.html#fk_actions> for more information. /// /// The example above uses a string primary for the country table. But generally /// speaking, all primary keys are supported. /// /// If the database schema does not define foreign keys between tables, you can /// still use `HasOneAssociation`. But your help is needed to define the /// missing foreign key: /// /// ```swift /// struct Demographics: TableRecord { } /// struct Country: TableRecord { /// static let demographics = hasOne(Demographics.self, using: ForeignKey(...) /// } /// ``` public struct HasOneAssociation<Origin, Destination> { public var _sqlAssociation: _SQLAssociation init( to destinationRelation: SQLRelation, key: String?, using foreignKey: ForeignKey?) { let destinationTable = destinationRelation.source.tableName let foreignKeyCondition = SQLForeignKeyCondition( destinationTable: destinationTable, foreignKey: foreignKey, originIsLeft: false) let associationKey: SQLAssociationKey if let key = key { associationKey = .fixedSingular(key) } else { associationKey = .inflected(destinationTable) } _sqlAssociation = _SQLAssociation( key: associationKey, condition: .foreignKey(foreignKeyCondition), relation: destinationRelation, cardinality: .toOne) } } extension HasOneAssociation: AssociationToOne { public typealias OriginRowDecoder = Origin public typealias RowDecoder = Destination }
mit
87f7ccbecb135c4b705be4b2625dbf6e
38.18
82
0.650587
4.447219
false
false
false
false
chaserx/streakerbar
streakerbar/GHEvent.swift
1
2327
// // GHEvent.swift // streakerbar // // Created by Michael on 3/23/15. // Copyright (c) 2015 Chase Southard. All rights reserved. // import Foundation struct GHEvent { var id: String var type: GHEventType var createdDate: NSDate var repoName: String var repoURL: NSURL } struct GHEventFactory { typealias ParsedJSON = [[String: AnyObject]] static func eventsFromJSONResponse(data: NSData) -> [GHEvent] { if let parsedJSON = NSJSONSerialization.JSONObjectWithData(data, options: .allZeros, error: nil) as? ParsedJSON { return eventsFromJSONObjects(parsedJSON) } return [GHEvent]() } static func eventsFromJSONObjects(json: ParsedJSON) -> [GHEvent] { var events = [GHEvent]() for object in json { if let id = object["id"] as? String { let typeString = object["type"] as? String || "UnknownEvent" if let type = GHEventType(rawValue: typeString) { if let createdDateString = object["created_at"] as? String { if let createdDate = NSDate.dateWithJSONString(createdDateString) { let repo = object["repo"] as? [String: AnyObject] let repoName = repo?["name"] as? String || "" let repoURLString = repo?["url"] as? String || "" let repoURL = NSURL(string: repoURLString)! let event = GHEvent(id: id, type: type, createdDate: createdDate, repoName: repoName, repoURL: repoURL) events.append(event) } } } } } return events } } enum GHEventType: String { case CommitComment = "CommitCommentEvent" case Create = "CreateEvent" case Delete = "DeleteEvent" case Deployment = "DeploymentEvent" case DeploymentStatus = "DeploymentStatusEvent" case Download = "DownloadEvent" case Follow = "FollowEvent" case Fork = "ForkEvent" case ForkApply = "ForkApplyEvent" case Gist = "GistEvent" case Gollum = "GollumEvent" case IssueComment = "IssueCommentEvent" case Issues = "IssuesEvent" case Member = "MemberEvent" case Membership = "MembershipEvent" case PageBuild = "PageBuildEvent" case Public = "PublicEvent" case PullRequest = "PullRequestEvent" case PullRequestReviewComment = "PullRequestReviewCommentEvent" case Push = "PushEvent" case Release = "ReleaseEvent" case Repository = "RepositoryEvent" case Status = "StatusEvent" case TeamAdd = "TeamAddEvent" case Watch = "WatchEvent" }
mit
dd78f32afcff1d367f49b80980a9b1d8
26.05814
115
0.702621
3.641628
false
false
false
false
LiuDeng/FYIM
FYIM/Module/Message/View/MessageBubbleView.swift
2
4233
// // MessageBubbleView.swift // FYIM // // Created by dai.fengyi on 15/7/18. // Copyright (c) 2015年 childrenOurFuture. All rights reserved. // import UIKit import SnapKit class MessageBubbleView: UIView { var message: XHMessage! @IBOutlet weak var displayTextView: SETextView? @IBOutlet weak var bubbleImageView: UIImageView? @IBOutlet weak var emotionImageView: UIImageView? @IBOutlet weak var animationVoiceImageView: UIImageView? @IBOutlet weak var voiceUnreadDotImageView: UIImageView? @IBOutlet weak var bubblePhotoImageView: UIImageView? @IBOutlet weak var videoPlayImageView: UIImageView? @IBOutlet weak var geolocationsLabel: UILabel? override func awakeFromNib() { bubbleImageView?.userInteractionEnabled = true displayTextView?.backgroundColor = UIColor .clearColor() // displayTextView?.selectable = false // displayTextView?.lineSpacing = 3.0 // displayTextView?.showsEditingMenuAutomatically = false // displayTextView?.highlighted = false geolocationsLabel?.numberOfLines = 0 geolocationsLabel?.lineBreakMode = NSLineBreakMode.ByTruncatingTail geolocationsLabel?.textColor = UIColor .whiteColor() geolocationsLabel?.backgroundColor = UIColor .clearColor() // geolocationsLabel?.font = UIFont .systemFontSize(12) } func configureCellWithMessage(message:XHMessage) { configureBubbleImageView(message) configureMessageDisplayMedia(message) configureConstraints(message) } private func configureBubbleImageView(message:XHMessage) { let currentType = message.messageMediaType switch currentType { case XHBubbleMessageMediaType.Voice: voiceUnreadDotImageView?.hidden = message.isRead case XHBubbleMessageMediaType.Text: fallthrough case XHBubbleMessageMediaType.Emotion: bubbleImageView?.image = XHMessageBubbleFactory .bubbleImageViewForType(message.bubbleMessageType, style: XHBubbleImageViewStyle.WeChat, meidaType: message.messageMediaType) bubbleImageView?.hidden = false bubblePhotoImageView?.hidden = true if currentType == XHBubbleMessageMediaType.Text { displayTextView?.hidden = false animationVoiceImageView?.hidden = true emotionImageView?.hidden = true }else { displayTextView?.hidden = true if currentType == XHBubbleMessageMediaType.Voice { animationVoiceImageView?.hidden = false }else { emotionImageView?.hidden = false bubbleImageView?.hidden = true animationVoiceImageView?.hidden = true } } case XHBubbleMessageMediaType.Photo: fallthrough case XHBubbleMessageMediaType.Video: fallthrough case XHBubbleMessageMediaType.LocalPosition: bubblePhotoImageView?.hidden = false videoPlayImageView?.hidden = (currentType != XHBubbleMessageMediaType.Video) geolocationsLabel?.hidden = (currentType != XHBubbleMessageMediaType.LocalPosition) displayTextView?.hidden = true bubbleImageView?.hidden = true animationVoiceImageView?.hidden = true emotionImageView?.hidden = true default: break } } private func configureMessageDisplayMedia(message:XHMessage) { switch message.messageMediaType { case XHBubbleMessageMediaType.Text: displayTextView?.attributedText = XHMessageBubbleHelper .sharedMessageBubbleHelper() .bubbleAttributtedStringWithText(message.text) //need more // case XHBubbleMessageMediaType.Photo: // bubblePhotoImageView default: break } } private func configureConstraints(message:XHMessage) { let rect = SETextView .frameRectWithAttributtedString(XHMessageBubbleHelper .sharedMessageBubbleHelper() .bubbleAttributtedStringWithText(message.text), constraintSize: CGSizeMake(UIScreen .mainScreen().bounds.width - 56 - 20, CGFloat(MAXFLOAT)), lineSpacing: 3, paragraphSpacing: 3, font: displayTextView?.font) // displayTextView?.bounds = rect displayTextView?.snp_makeConstraints({ (make) -> Void in make.size.equalTo(rect.size) }) // displayTextView?.snp_width = rect.size.width // displayTextView?.snp_height = rect.size.height } }
mit
a9b5eedf8c5ce6472e5e25bb5148da9e
36.776786
316
0.736233
4.76464
false
true
false
false
lyimin/EyepetizerApp
EyepetizerApp/EyepetizerApp/Extensions/Request+Eye.swift
1
1381
// // Request+Eye.swift // EyepetizerApp // // Created by 梁亦明 on 16/3/14. // Copyright © 2016年 xiaoming. All rights reserved. // import Foundation import Alamofire import SwiftyJSON extension Request { public func responseSwiftyJSON(completionHandler: (NSURLRequest, NSHTTPURLResponse?, SwiftyJSON.JSON, ErrorType?) -> Void) -> Self { return responseSwiftyJSON(nil, options:NSJSONReadingOptions.AllowFragments, completionHandler:completionHandler) } public func responseSwiftyJSON(queue: dispatch_queue_t? = nil, options: NSJSONReadingOptions = .AllowFragments, completionHandler: (NSURLRequest, NSHTTPURLResponse?, JSON, ErrorType?) -> Void) -> Self { return responseJSON(options: options, completionHandler: { (response) -> Void in dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { var responseJSON : JSON if response.result.error != nil { responseJSON = JSON.null } else { responseJSON = SwiftyJSON.JSON(response.result.value!) } dispatch_async(queue ?? dispatch_get_main_queue(), { completionHandler(self.request!, self.response, responseJSON, response.result.error) }) }) }) } }
mit
4287e668db2cdfa13d4ec57c4aedf0db
37.111111
210
0.62828
5.007299
false
false
false
false
nathawes/swift
test/expr/cast/as_coerce.swift
2
5892
// RUN: %target-typecheck-verify-swift -enable-objc-interop // Test the use of 'as' for type coercion (which requires no checking). @objc protocol P1 { func foo() } class A : P1 { @objc func foo() { } } @objc class B : A { func bar() { } } func doFoo() {} func test_coercion(_ a: A, b: B) { // Coercion to a protocol type let x = a as P1 x.foo() // Coercion to a superclass type let y = b as A y.foo() } class C : B { } class D : C { } func prefer_coercion(_ c: inout C) { let d = c as! D c = d } // Coerce literals var i32 = 1 as Int32 var i8 = -1 as Int8 // Coerce to a superclass with generic parameter inference class C1<T> { func f(_ x: T) { } } class C2<T> : C1<Int> { } var c2 = C2<()>() var c1 = c2 as C1 c1.f(5) @objc protocol P {} class CC : P {} let cc: Any = CC() if cc is P { doFoo() } if let p = cc as? P { doFoo() _ = p } // Test that 'as?' coercion fails. let strImplicitOpt: String! = nil _ = strImplicitOpt as? String // expected-warning{{conditional downcast from 'String?' to 'String' does nothing}}{{19-30=}} class C3 {} class C4 : C3 {} class C5 {} var c: AnyObject = C3() // XXX TODO: Constant-folding should generate an error about 'C3' not being convertible to 'C4' //if let castX = c as! C4? {} // XXX TODO: Only suggest replacing 'as' with 'as!' if it would fix the error. C3() as C4 // expected-error {{'C3' is not convertible to 'C4'; did you mean to use 'as!' to force downcast?}} {{6-8=as!}} C3() as C5 // expected-error {{cannot convert value of type 'C3' to type 'C5' in coercion}} // Diagnostic shouldn't include @lvalue in type of c3. var c3 = C3() // XXX TODO: This should not suggest `as!` c3 as C4 // expected-error {{'C3' is not convertible to 'C4'; did you mean to use 'as!' to force downcast?}} {{4-6=as!}} // <rdar://problem/19495142> Various incorrect diagnostics for explicit type conversions 1 as Double as Float // expected-error{{cannot convert value of type 'Double' to type 'Float' in coercion}} 1 as Int as String // expected-error{{cannot convert value of type 'Int' to type 'String' in coercion}} Double(1) as Double as String // expected-error{{cannot convert value of type 'Double' to type 'String' in coercion}} ["awd"] as [Int] // expected-error{{cannot convert value of type 'String' to expected element type 'Int'}} ([1, 2, 1.0], 1) as ([String], Int) // expected-error@-1 2 {{cannot convert value of type 'Int' to expected element type 'String'}} // expected-error@-2 {{cannot convert value of type 'Double' to expected element type 'String'}} [[1]] as [[String]] // expected-error{{cannot convert value of type 'Int' to expected element type 'String'}} (1, 1.0) as (Int, Int) // expected-error{{cannot convert value of type '(Int, Double)' to type '(Int, Int)' in coercion}} (1.0, 1, "asd") as (String, Int, Float) // expected-error{{cannot convert value of type '(Double, Int, String)' to type '(String, Int, Float)' in coercion}} (1, 1.0, "a", [1, 23]) as (Int, Double, String, [String]) // expected-error@-1 2 {{cannot convert value of type 'Int' to expected element type 'String'}} _ = [1] as! [String] // OK _ = [(1, (1, 1))] as! [(Int, (String, Int))] // OK // <rdar://problem/19495253> Incorrect diagnostic for explicitly casting to the same type _ = "hello" as! String // expected-warning{{forced cast of 'String' to same type has no effect}} {{13-24=}} // <rdar://problem/19499340> QoI: Nimble as -> as! changes not covered by Fix-Its func f(_ x : String) {} f("what" as Any as String) // expected-error {{'Any' is not convertible to 'String'; did you mean to use 'as!' to force downcast?}} {{17-19=as!}} f(1 as String) // expected-error{{cannot convert value of type 'Int' to type 'String' in coercion}} // <rdar://problem/19650402> Swift compiler segfaults while running the annotation tests let s : AnyObject = C3() s as C3 // expected-error{{'AnyObject' is not convertible to 'C3'; did you mean to use 'as!' to force downcast?}} {{3-5=as!}} // SR-6022 func sr6022() -> Any { return 0 } func sr6022_1() { return; } protocol SR6022_P {} _ = sr6022 as! SR6022_P // expected-warning {{cast from '() -> Any' to unrelated type 'SR6022_P' always fails}} // expected-note {{did you mean to call 'sr6022' with '()'?}}{{11-11=()}} _ = sr6022 as? SR6022_P // expected-warning {{cast from '() -> Any' to unrelated type 'SR6022_P' always fails}} // expected-note {{did you mean to call 'sr6022' with '()'}}{{11-11=()}} _ = sr6022_1 as! SR6022_P // expected-warning {{cast from '() -> ()' to unrelated type 'SR6022_P' always fails}} _ = sr6022_1 as? SR6022_P // expected-warning {{cast from '() -> ()' to unrelated type 'SR6022_P' always fails}} func testSR6022_P<T: SR6022_P>(_: T.Type) { _ = sr6022 as! T // expected-warning {{cast from '() -> Any' to unrelated type 'T' always fails}} // expected-note {{did you mean to call 'sr6022' with '()'?}}{{13-13=()}} _ = sr6022 as? T // expected-warning {{cast from '() -> Any' to unrelated type 'T' always fails}} // expected-note {{did you mean to call 'sr6022' with '()'?}}{{13-13=()}} _ = sr6022_1 as! T // expected-warning {{cast from '() -> ()' to unrelated type 'T' always fails}} _ = sr6022_1 as? T // expected-warning {{cast from '() -> ()' to unrelated type 'T' always fails}} } func testSR6022_P_1<U>(_: U.Type) { _ = sr6022 as! U // Okay _ = sr6022 as? U // Okay _ = sr6022_1 as! U // Okay _ = sr6022_1 as? U // Okay } _ = sr6022 as! AnyObject // expected-warning {{forced cast from '() -> Any' to 'AnyObject' always succeeds; did you mean to use 'as'?}} _ = sr6022 as? AnyObject // expected-warning {{conditional cast from '() -> Any' to 'AnyObject' always succeeds}} _ = sr6022_1 as! Any // expected-warning {{forced cast from '() -> ()' to 'Any' always succeeds; did you mean to use 'as'?}} _ = sr6022_1 as? Any // expected-warning {{conditional cast from '() -> ()' to 'Any' always succeeds}}
apache-2.0
b75e8d3c03227ef705c531fe8332bb9c
41.388489
185
0.641378
3.13571
false
false
false
false
hironytic/Kiretan0
Kiretan0/View/Setting/TeamSelectionViewController.swift
1
2478
// // TeamSelectionViewController.swift // Kiretan0 // // Copyright (c) 2017 Hironori Ichimiya <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit import RxSwift public class TeamSelectionViewController: UITableViewController { public var viewModel: TeamSelectionViewModel? private var _disposeBag: DisposeBag? public init() { super.init(style: .grouped) } public required init?(coder aDecoder: NSCoder) { fatalError() } public override func viewDidLoad() { super.viewDidLoad() title = R.String.teamSelectionTitle.localized() tableView.register(CheckableTableCell.self, forCellReuseIdentifier: CheckableTableCellViewModel.typeIdentifier) bindViewModel() } private func bindViewModel() { _disposeBag = nil guard let viewModel = viewModel else { return } let disposeBag = DisposeBag() TableUI() .bind(viewModel.tableData, to: tableView) .disposed(by: disposeBag) _disposeBag = disposeBag } } extension DefaultTeamSelectionViewModel: ViewControllerCreatable { public func createViewController() -> UIViewController { let viewController = TeamSelectionViewController() viewController.viewModel = self return UINavigationController(rootViewController: viewController) } }
mit
cebf3df8a45cbbcd3409a9c29b2b6405
33.416667
119
0.709443
5.141079
false
false
false
false
volodg/iAsync.network
Sources/XQueryComponents/String+XQueryComponents.swift
1
2297
// // String+XQueryComponents.swift // iAsync_network // // Created by Vladimir Gorbenko on 13.10.14. // Copyright © 2014 EmbeddedSources. All rights reserved. // import Foundation import iAsync_utils extension String { public static var digits: String { return "0123456789" } public static var lowercase: String { return "abcdefghijklmnopqrstuvwxyz" } public static var uppercase: String { return "ABCDEFGHIJKLMNOPQRSTUVWXYZ" } public static var letters: String { return lowercase + uppercase } public static var uriQueryValueAllowed: String { return "!$\'()*+,-.;?@_~" + letters + digits } } public extension String { func stringByDecodingURLQueryComponents() -> String? { return removingPercentEncoding } func stringByEncodingURLQueryComponents() -> String { let query = CharacterSet(charactersIn: String.uriQueryValueAllowed) let result = addingPercentEncoding(withAllowedCharacters: query) return result ?? self } func dictionaryFromQueryComponents() -> [String:[String]] { var result = [String:[String]]() for keyValuePairString in components(separatedBy: "&") { let keyValuePairArray = keyValuePairString.components(separatedBy: "=") as [String] // Verify that there is at least one key, and at least one value. Ignore extra = signs if keyValuePairArray.count < 2 { continue } let decodedKey = keyValuePairArray[0] guard let key = decodedKey.stringByDecodingURLQueryComponents() else { iAsync_utils_logger.logError("can not decode key: \(decodedKey)", context: #function) continue } let decodedVal = keyValuePairArray[1] guard let value = decodedVal.stringByDecodingURLQueryComponents() else { iAsync_utils_logger.logError("can not decode val: \(decodedVal)", context: #function) continue } var results = result[key] ?? [String]() // URL spec says that multiple values are allowed per key results.append(value) result[key] = results } return result } }
mit
1b875c02c2a9ba53b34f56ec3bcc3d0a
25.697674
109
0.623258
5.046154
false
false
false
false
ptwoms/CountDownTimer
P2MSCountDownTimer/Classes/UIColor+Interpolate.swift
1
1163
// // UIColor+Interpolate.swift // P2MSCountDownTimer // // Created by Pyae Phyo Myint Soe on 16/9/15. // Copyright © 2015 PYAE PHYO MYINT SOE. All rights reserved. // import UIKit extension UIColor { class func interpolatedColorBetweenColor(firstColor: UIColor, andColor lastColor: UIColor, ratio aRatio: CGFloat) -> UIColor{ let firstColorComponents = CGColorGetComponents(firstColor.CGColor) let secondColorComponents = CGColorGetComponents(lastColor.CGColor) let numberOfComp : Int = CGColorGetNumberOfComponents(firstColor.CGColor) var interpolatedComponents = [CGFloat](count: numberOfComp, repeatedValue: 0) for index in 0...numberOfComp-1{ interpolatedComponents[index] = firstColorComponents[index] * (1 - aRatio) + secondColorComponents[index] * aRatio } let interpolatedCGColor = CGColorCreate(CGColorGetColorSpace(firstColor.CGColor), interpolatedComponents) if interpolatedCGColor != nil{ //no need to call CGColorRelease in swift return UIColor(CGColor: interpolatedCGColor!) } return UIColor.clearColor() } }
mit
eca69ed8cdb81f0b5e070b3df5b04579
40.535714
129
0.709122
4.704453
false
false
false
false
OctMon/OMExtension
OMExtension/OMExtension/Source/Foundation/OMDate.swift
1
4369
// // OMDatet.swift // OMExtension // // The MIT License (MIT) // // Copyright (c) 2016 OctMon // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation public struct OMDateInfo { /// Year var year = 0 /// Month of the year var month = 0 /// Day of the month var day = 0 /// Day of the week var weekday = 0 /// Hour of the day var hour = 0 /// Minute of the hour var minute = 0 /// Second of the minute var second = 0 /// Nanosecond of the second var nanosecond = 0 } public extension Date { /** G: 公元时代,例如AD公元 yy:年的后2位 yyyy:完整年 MM:月,显示为1-12 MMM:月,显示为英文月份简写,如 Jan MMMM:月,显示为英文月份全称,如 Janualy dd:日,2位数表示,如02 d:日,1-2位显示,如 2 EEE:简写星期几,如Sun EEEE:全写星期几,如Sunday aa:上下午,AM/PM H:时,24小时制,0-23 K:时,12小时制,0-11 m:分,1-2位 mm:分,2位 s:秒,1-2位 ss:秒,2位 S:毫秒 */ func omFormatString(_ dateFormat: String = "yyyy-MM-dd HH:mm:ss") -> String { let dateFormatter: DateFormatter = DateFormatter() dateFormatter.dateFormat = dateFormat return dateFormatter.string(from: self) } var omYearString: String { return omFormatString("yyyy") } var omMonthString: String { return omFormatString("MMMM") } var omWeekdayString: String { return omFormatString("EEEE") } func omDateInfo(_ timeZone: TimeZone = TimeZone.current) -> OMDateInfo { var calendar = Calendar.autoupdatingCurrent calendar.timeZone = timeZone return OMDateInfo(year: (calendar as NSCalendar).components(.year, from: self).year!, month: (calendar as NSCalendar).components(.month, from: self).month!, day: (calendar as NSCalendar).components(.day, from: self).day!, weekday: (calendar as NSCalendar).components(.weekdayOrdinal, from: self).weekdayOrdinal!, hour: (calendar as NSCalendar).components(.hour, from: self).hour!, minute: (calendar as NSCalendar).components(.minute, from: self).minute!, second: (calendar as NSCalendar).components(.second, from: self).second!, nanosecond: (calendar as NSCalendar).components(.nanosecond, from: self).nanosecond!) } } public extension OMDateInfo { func string(dateSeparator: String = "-", dateNormal: Bool = true, nanosecond: Bool = false) -> String { var description: String if dateNormal { description = String(format: "%04li%@%02li%@%02li %02li:%02li:%02li", self.year, dateSeparator, self.month, dateSeparator, self.day, self.hour, self.minute, self.second) } else { description = String(format: "%02li%@%02li%@%04li %02li:%02li:%02li", self.month, dateSeparator, self.day, dateSeparator, self.year, self.hour, self.minute, self.second) } if nanosecond { description += String(format: ":%03li", self.nanosecond / 1000000) } return description } }
mit
07d50320b40862407dc8dc83ab146afe
31.732283
622
0.636757
3.970392
false
false
false
false
Antondomashnev/Sourcery
SourceryTests/Stub/Performance-Code/Kiosk/Sale Artwork Details/ImageTiledDataSource.swift
2
476
import Foundation import ARTiledImageView class TiledImageDataSourceWithImage: ARWebTiledImageDataSource { let image: Image init(image: Image) { self.image = image super.init() tileFormat = "jpg" tileBaseURL = URL(string: image.baseURL) tileSize = image.tileSize maxTiledHeight = image.maxTiledHeight maxTiledWidth = image.maxTiledWidth maxTileLevel = image.maxLevel minTileLevel = 11 } }
mit
c7612ab6ac9ef2f4e2102e8a2a61120b
24.052632
64
0.663866
4.327273
false
false
false
false
GetMagicVision/MagicVision-iOS-SDK
Example/ViewController.swift
1
2702
// // ViewController.swift // Example // // Copyright © 2015 cienet. All rights reserved. // import UIKit import MagicVision class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { @IBOutlet weak var faceImageView: UIImageView! @IBOutlet weak var faceRectView: UIView! @IBOutlet weak var faceImageWidthCons: NSLayoutConstraint! @IBOutlet weak var faceImageHeightCons: NSLayoutConstraint! @IBOutlet weak var faceRectTopCons: NSLayoutConstraint! @IBOutlet weak var faceRectLeftCons: NSLayoutConstraint! @IBOutlet weak var faceRectWidthCons: NSLayoutConstraint! @IBOutlet weak var faceRectHeightCons: NSLayoutConstraint! var imagePicker: UIImagePickerController? // MARK: Overrides override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func detectFace(image: UIImage) { faceRectView.layer.borderColor = UIColor.greenColor().CGColor faceRectView.layer.borderWidth = 2 // let faceImagePath = NSBundle.mainBundle().pathForResource("face_example_1", ofType: "png") // let faceImage = UIImage(contentsOfFile: faceImagePath!) faceImageWidthCons.constant = 300 faceImageHeightCons.constant = 300 * (image.size.height / image.size.width) faceImageView.image = image let face = MVFaceDetector.detectFace(image) print("face x \(face.origin.x) y \(face.origin.y) width \(face.width) height \(face.height)") let ratio = (300 / image.size.width) faceRectLeftCons.constant = face.origin.x * ratio faceRectTopCons.constant = face.origin.y * ratio faceRectWidthCons.constant = face.width * ratio faceRectHeightCons.constant = face.height * ratio } @IBAction func onSelectImageBtnClicked(sender: AnyObject) { imagePicker = UIImagePickerController() imagePicker!.sourceType = UIImagePickerControllerSourceType.PhotoLibrary imagePicker!.delegate = self self.presentViewController(imagePicker!, animated: true, completion: nil) } } extension ViewController { func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { self.dismissViewControllerAnimated(true, completion: nil) if let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage { self.detectFace(selectedImage) } } func imagePickerControllerDidCancel(picker: UIImagePickerController) { self.dismissViewControllerAnimated(true, completion: nil) } }
mit
557e19b94ceb35d07758d72be79f0143
28.681319
121
0.734173
5.096226
false
false
false
false
seanwoodward/IBAnimatable
IBAnimatable/PortalAnimator.swift
1
6873
// // Created by Tom Baranes on 17/04/16. // Copyright © 2016 IBAnimatable. All rights reserved. // import UIKit public class PortalAnimator: NSObject, AnimatedTransitioning { // MARK: - AnimatorProtocol public var transitionAnimationType: TransitionAnimationType public var transitionDuration: Duration = defaultTransitionDuration public var reverseAnimationType: TransitionAnimationType? public var interactiveGestureType: InteractiveGestureType? // MARK: - private private var fromDirection: TransitionDirection private var zoomScale: CGFloat = 0.8 public init(fromDirection: TransitionDirection, params: [String], transitionDuration: Duration) { self.transitionDuration = transitionDuration self.fromDirection = fromDirection if let firstParam = params.first, unwrappedZoomScale = Double(firstParam) { zoomScale = CGFloat(unwrappedZoomScale) } switch fromDirection { case .Forward: self.transitionAnimationType = .Portal(direction: .Forward, params: params) self.reverseAnimationType = .Portal(direction: .Backward, params: params) self.interactiveGestureType = .Pinch(direction: .Close) default: self.transitionAnimationType = .Portal(direction: .Backward, params: params) self.reverseAnimationType = .Portal(direction: .Forward, params: params) self.interactiveGestureType = .Pinch(direction: .Open) } super.init() } } extension PortalAnimator: UIViewControllerAnimatedTransitioning { public func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return retrieveTransitionDuration(transitionContext) } public func animateTransition(transitionContext: UIViewControllerContextTransitioning) { let (tempfromView, tempToView, tempContainerView) = retrieveViews(transitionContext) guard let fromView = tempfromView, toView = tempToView, containerView = tempContainerView else { transitionContext.completeTransition(true) return } switch fromDirection { case .Forward: executeForwardAnimation(transitionContext, containerView: containerView, fromView: fromView, toView: toView) default: executeBackwardAnimation(transitionContext, containerView: containerView, fromView: fromView, toView: toView) } } } // MARK: - Forward private extension PortalAnimator { func executeForwardAnimation(transitionContext: UIViewControllerContextTransitioning, containerView: UIView, fromView: UIView, toView: UIView) { let toViewSnapshot = toView.resizableSnapshotViewFromRect(toView.frame, afterScreenUpdates: true, withCapInsets: UIEdgeInsetsZero) let scale = CATransform3DIdentity toViewSnapshot.layer.transform = CATransform3DScale(scale, zoomScale, zoomScale, 1) containerView.insertSubview(toViewSnapshot, atIndex: 0) let leftSnapshotRegion = CGRect(x: 0, y: 0, width: fromView.frame.width / 2, height: fromView.bounds.height) let leftHandView = fromView.resizableSnapshotViewFromRect(leftSnapshotRegion, afterScreenUpdates: false, withCapInsets: UIEdgeInsetsZero) leftHandView.frame = leftSnapshotRegion containerView.addSubview(leftHandView) let rightSnapshotRegion = CGRect(x: fromView.frame.width / 2, y: 0, width: fromView.frame.width / 2, height: fromView.frame.height) let rightHandView = fromView.resizableSnapshotViewFromRect(rightSnapshotRegion, afterScreenUpdates: false, withCapInsets: UIEdgeInsetsZero) rightHandView.frame = rightSnapshotRegion containerView.addSubview(rightHandView) fromView.hidden = true UIView.animateWithDuration(transitionDuration, delay: 0.0, options: .CurveEaseOut, animations: { leftHandView.frame = leftHandView.frame.offsetBy(dx: -leftHandView.frame.width, dy: 0.0) rightHandView.frame = rightHandView.frame.offsetBy(dx: rightHandView.frame.width, dy: 0.0) toViewSnapshot.center = toView.center toViewSnapshot.frame = containerView.frame }, completion: { _ in fromView.hidden = false if transitionContext.transitionWasCancelled() { self.removeOtherViews(fromView) } else { toView.frame = containerView.frame containerView.addSubview(toView) self.removeOtherViews(toView) } transitionContext.completeTransition(!transitionContext.transitionWasCancelled()) } ) } } // MARK: - Reverse private extension PortalAnimator { func executeBackwardAnimation(transitionContext: UIViewControllerContextTransitioning, containerView: UIView, fromView: UIView, toView: UIView) { containerView.addSubview(fromView) toView.frame = toView.frame.offsetBy(dx: toView.frame.width, dy: 0) containerView.addSubview(toView) let leftSnapshotRegion = CGRect(x: 0, y: 0, width: toView.frame.width / 2, height: toView.bounds.height) let leftHandView = toView.resizableSnapshotViewFromRect(leftSnapshotRegion, afterScreenUpdates: true, withCapInsets: UIEdgeInsetsZero) leftHandView.frame = leftSnapshotRegion leftHandView.frame = leftHandView.frame.offsetBy(dx: -leftHandView.frame.width, dy: 0) containerView.addSubview(leftHandView) let rightSnapshotRegion = CGRect(x: toView.frame.width / 2, y: 0, width: toView.frame.width / 2, height: fromView.frame.height) let rightHandView = toView.resizableSnapshotViewFromRect(rightSnapshotRegion, afterScreenUpdates: true, withCapInsets: UIEdgeInsetsZero) rightHandView.frame = rightSnapshotRegion rightHandView.frame = rightHandView.frame.offsetBy(dx: rightHandView.frame.width, dy: 0) containerView.addSubview(rightHandView) UIView.animateWithDuration(transitionDuration, delay: 0.0, options: .CurveEaseOut, animations: { leftHandView.frame = leftHandView.frame.offsetBy(dx: leftHandView.frame.size.width, dy: 0) rightHandView.frame = rightHandView.frame.offsetBy(dx: -rightHandView.frame.size.width, dy: 0) let scale = CATransform3DIdentity fromView.layer.transform = CATransform3DScale(scale, self.zoomScale, self.zoomScale, 1) }, completion: { _ in if transitionContext.transitionWasCancelled() { self.removeOtherViews(fromView) } else { self.removeOtherViews(toView) toView.frame = containerView.bounds fromView.layer.transform = CATransform3DIdentity } transitionContext.completeTransition(!transitionContext.transitionWasCancelled()) } ) } } // MARK: - Helper private extension PortalAnimator { func removeOtherViews(viewToKeep: UIView) { guard let containerView = viewToKeep.superview else { return } containerView.subviews.forEach { if $0 != viewToKeep { $0.removeFromSuperview() } } } }
mit
8ef404a5b19635520646641e7fa1ba4e
39.423529
147
0.741269
4.782185
false
false
false
false
hovansuit/FoodAndFitness
FoodAndFitness/Controllers/Analysis/NutritionCell/AnalysisNutritionCell.swift
1
867
// // AnalysisNutritionCell.swift // FoodAndFitness // // Created by Mylo Ho on 5/1/17. // Copyright © 2017 SuHoVan. All rights reserved. // import UIKit class AnalysisNutritionCell: BaseTableViewCell { @IBOutlet fileprivate(set) weak var caloriesLabel: UILabel! @IBOutlet fileprivate(set) weak var proteinLabel: UILabel! @IBOutlet fileprivate(set) weak var carbsLabel: UILabel! @IBOutlet fileprivate(set) weak var fatLabel: UILabel! struct Data { var calories: String var protein: String var carbs: String var fat: String } var data: Data? { didSet { guard let data = data else { return } caloriesLabel.text = data.calories proteinLabel.text = data.protein carbsLabel.text = data.carbs fatLabel.text = data.fat } } }
mit
5bac1f995ff7361e7d7654fc31a830a7
25.242424
63
0.633949
4.26601
false
false
false
false
interchen/ICWebViewController
ICWebViewController/ICWebViewController.swift
1
4472
// // ICWebViewController.swift // ICWebViewController // // Created by azhunchen on 2017/3/3. // Copyright © 2017年 azhunchen. All rights reserved. // import UIKit import WebKit open class ICWebViewController: UIViewController { let webView = WKWebView(frame: .zero, configuration: WKWebViewConfiguration()) let progressView = UIProgressView() open var url: URL? // MARK: Life cycle public convenience init(_ url: URL) { self.init() self.url = url } deinit { if self.isViewLoaded { self.webView.removeObserver(self, forKeyPath: "estimatedProgress", context: nil) self.webView.removeObserver(self, forKeyPath: "title", context: nil) } } override open func viewDidLoad() { super.viewDidLoad() initUI() self.webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil) self.webView.addObserver(self, forKeyPath: "title", options: .new, context: nil) self.loadRequest() } override open func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() self.progressView.frame = CGRect(x: 0, y: 0 - self.webView.scrollView.bounds.origin.y, width: self.webView.bounds.size.width, height: 2.0) } override open func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } fileprivate func initUI() { self.view.backgroundColor = .white self.webView.translatesAutoresizingMaskIntoConstraints = false self.webView.addSubview(self.progressView) self.view.addSubview(self.webView) // webView constraints let views: [String : Any] = ["webView" : self.webView, "topLayoutGuide" : self.topLayoutGuide] let hConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[webView]-0-|", options: [], metrics: nil, views: views) var vvf = "V:[topLayoutGuide]-0-[webView]-0-|" if self.navigationController != nil { vvf = "V:|-0-[webView]-0-|" } let vConstraints = NSLayoutConstraint.constraints(withVisualFormat: vvf, options: [], metrics: nil, views: views) self.view.addConstraints(hConstraints) self.view.addConstraints(vConstraints) self.webView.allowsBackForwardNavigationGestures = true self.progressView.progress = 0.1 // to fix short time blank when view did load } override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if let keyPath = keyPath { switch keyPath { case "estimatedProgress": let newProgress = change![.newKey] as! Float switch newProgress { case 0.0: self.progressView.isHidden = false case 1.0: self.progressView.progress = newProgress delay(0.5, closure: { UIView.animate(withDuration: 0.2, animations: { self.progressView.isHidden = true }) }) default: self.progressView.progress = newProgress self.progressView.isHidden = false } case "title": let title = change![.newKey] as! String self.title = title default: break } } } // MARK: - private open func loadRequest() { if let url = self.url { let request = NSMutableURLRequest(url: url, cachePolicy:.useProtocolCachePolicy, timeoutInterval: 86400) // add request cookie here // request.addValue("key=value;", forHTTPHeaderField: "Cookie") webView.load(request as URLRequest) } } func delay(_ delay:Double? = 1.0, closure:@escaping ()->Void) { DispatchQueue.main.asyncAfter( deadline: DispatchTime.now() + Double(Int64(delay! * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure ) } }
mit
59f339b56829ae31cde2fe6960d1831d
34.752
156
0.569031
5.142693
false
false
false
false
r-mckay/montreal-iqa
montrealIqaCore/Carthage/Checkouts/realm-cocoa/RealmSwift/Object.swift
12
18605
//////////////////////////////////////////////////////////////////////////// // // 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 import Realm.Private /** `Object` is a class used to define Realm model objects. In Realm you define your model classes by subclassing `Object` and adding properties to be managed. You then instantiate and use your custom subclasses instead of using the `Object` class directly. ```swift class Dog: Object { @objc dynamic var name: String = "" @objc dynamic var adopted: Bool = false let siblings = List<Dog>() } ``` ### Supported property types - `String`, `NSString` - `Int` - `Int8`, `Int16`, `Int32`, `Int64` - `Float` - `Double` - `Bool` - `Date`, `NSDate` - `Data`, `NSData` - `RealmOptional<T>` for optional numeric properties - `Object` subclasses, to model many-to-one relationships - `List<T>`, to model many-to-many relationships `String`, `NSString`, `Date`, `NSDate`, `Data`, `NSData` and `Object` subclass properties can be declared as optional. `Int`, `Int8`, `Int16`, `Int32`, `Int64`, `Float`, `Double`, `Bool`, and `List` properties cannot. To store an optional number, use `RealmOptional<Int>`, `RealmOptional<Float>`, `RealmOptional<Double>`, or `RealmOptional<Bool>` instead, which wraps an optional numeric value. All property types except for `List` and `RealmOptional` *must* be declared as `@objc dynamic var`. `List` and `RealmOptional` properties must be declared as non-dynamic `let` properties. Swift `lazy` properties are not allowed. Note that none of the restrictions listed above apply to properties that are configured to be ignored by Realm. ### Querying You can retrieve all objects of a given type from a Realm by calling the `objects(_:)` instance method. ### Relationships See our [Cocoa guide](http://realm.io/docs/cocoa) for more details. */ @objc(RealmSwiftObject) open class Object: RLMObjectBase, ThreadConfined { // MARK: Initializers /** Creates an unmanaged instance of a Realm object. Call `add(_:)` on a `Realm` instance to add an unmanaged object into that Realm. - see: `Realm().add(_:)` */ public override required init() { super.init() } /** Creates an unmanaged instance of a Realm object. The `value` argument is used to populate the object. It can be a key-value coding compliant object, an array or dictionary returned from the methods in `NSJSONSerialization`, or an `Array` containing one element for each managed property. An exception will be thrown if any required properties are not present and those properties were not defined with default values. When passing in an `Array` as the `value` argument, all properties must be present, valid and in the same order as the properties defined in the model. Call `add(_:)` on a `Realm` instance to add an unmanaged object into that Realm. - parameter value: The value used to populate the object. */ public init(value: Any) { type(of: self).sharedSchema() // ensure this class' objectSchema is loaded in the partialSharedSchema super.init(value: value, schema: RLMSchema.partialShared()) } // MARK: Properties /// The Realm which manages the object, or `nil` if the object is unmanaged. public var realm: Realm? { if let rlmReam = RLMObjectBaseRealm(self) { return Realm(rlmReam) } return nil } /// The object schema which lists the managed properties for the object. public var objectSchema: ObjectSchema { return ObjectSchema(RLMObjectBaseObjectSchema(self)!) } /// Indicates if the object can no longer be accessed because it is now invalid. /// /// An object can no longer be accessed if the object has been deleted from the Realm that manages it, or if /// `invalidate()` is called on that Realm. open override var isInvalidated: Bool { return super.isInvalidated } /// A human-readable description of the object. open override var description: String { return super.description } #if os(OSX) /// Helper to return the class name for an Object subclass. public final override var className: String { return "" } #else /// Helper to return the class name for an Object subclass. public final var className: String { return "" } #endif /** WARNING: This is an internal helper method not intended for public use. :nodoc: */ open override class func objectUtilClass(_ isSwift: Bool) -> AnyClass { return ObjectUtil.self } // MARK: Object Customization /** Override this method to specify the name of a property to be used as the primary key. Only properties of types `String` and `Int` can be designated as the primary key. Primary key properties enforce uniqueness for each value whenever the property is set, which incurs minor overhead. Indexes are created automatically for primary key properties. - returns: The name of the property designated as the primary key, or `nil` if the model has no primary key. */ @objc open class func primaryKey() -> String? { return nil } /** Override this method to specify the names of properties to ignore. These properties will not be managed by the Realm that manages the object. - returns: An array of property names to ignore. */ @objc open class func ignoredProperties() -> [String] { return [] } /** Returns an array of property names for properties which should be indexed. Only string, integer, boolean, `Date`, and `NSDate` properties are supported. - returns: An array of property names. */ @objc open class func indexedProperties() -> [String] { return [] } // MARK: Key-Value Coding & Subscripting /// Returns or sets the value of the property with the given name. @objc open subscript(key: String) -> Any? { get { if realm == nil { return value(forKey: key) } return RLMDynamicGetByName(self, key, true) } set(value) { if realm == nil { setValue(value, forKey: key) } else { RLMDynamicValidatedSet(self, key, value) } } } // MARK: Notifications /** Registers a block to be called each time the object changes. The block will be asynchronously called after each write transaction which deletes the object or modifies any of the managed properties of the object, including self-assignments that set a property to its existing value. For write transactions performed on different threads or in different processes, the block will be called when the managing Realm is (auto)refreshed to a version including the changes, while for local write transactions it will be called at some point in the future after the write transaction is committed. 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. Unlike with `List` and `Results`, there is no "initial" callback made after you add a new notification block. Only objects which are managed by a Realm can be observed in this way. You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving updates, call `stop()` on the token. It is safe to capture a strong reference to the observed object within the callback block. There is no retain cycle due to that the callback is retained by the returned token and not by the object itself. - warning: This method cannot be called during a write transaction, or when the containing Realm is read-only. - parameter block: The block to call with information about changes to the object. - returns: A token which must be held for as long as you want updates to be delivered. */ public func addNotificationBlock(_ block: @escaping (ObjectChange) -> Void) -> NotificationToken { return RLMObjectAddNotificationBlock(self, { names, oldValues, newValues, error in if let error = error { block(.error(error as NSError)) return } guard let names = names, let newValues = newValues else { block(.deleted) return } block(.change((0..<newValues.count).map { i in PropertyChange(name: names[i], oldValue: oldValues?[i], newValue: newValues[i]) })) }) } // MARK: Dynamic list /** Returns a list of `DynamicObject`s for a given property name. - warning: This method is useful only in specialized circumstances, for example, when building components that integrate with Realm. If you are simply building an app on Realm, it is recommended to use instance variables or cast the values returned from key-value coding. - parameter propertyName: The name of the property. - returns: A list of `DynamicObject`s. :nodoc: */ public func dynamicList(_ propertyName: String) -> List<DynamicObject> { return noWarnUnsafeBitCast(RLMDynamicGetByName(self, propertyName, true) as! RLMListBase, to: List<DynamicObject>.self) } // MARK: Equatable /** Returns whether two Realm objects are equal. Objects are considered equal if and only if they are both managed by the same Realm and point to the same underlying object in the database. - parameter object: The object to compare the receiver to. */ open override func isEqual(_ object: Any?) -> Bool { return RLMObjectBaseAreEqual(self as RLMObjectBase?, object as? RLMObjectBase) } // MARK: Private functions // FIXME: None of these functions should be exposed in the public interface. /** WARNING: This is an internal initializer not intended for public use. :nodoc: */ public override required init(realm: RLMRealm, schema: RLMObjectSchema) { super.init(realm: realm, schema: schema) } /** WARNING: This is an internal initializer not intended for public use. :nodoc: */ public override required init(value: Any, schema: RLMSchema) { super.init(value: value, schema: schema) } } /** Information about a specific property which changed in an `Object` change notification. */ public struct PropertyChange { /** The name of the property which changed. */ public let name: String /** Value of the property before the change occurred. This is not supplied if the change happened on the same thread as the notification and for `List` properties. For object properties this will give the object which was previously linked to, but that object will have its new values and not the values it had before the changes. This means that `previousValue` may be a deleted object, and you will need to check `isInvalidated` before accessing any of its properties. */ public let oldValue: Any? /** The value of the property after the change occurred. This is not supplied for `List` properties and will always be nil. */ public let newValue: Any? } /** Information about the changes made to an object which is passed to `Object`'s notification blocks. */ public enum ObjectChange { /** If an error occurs, notification blocks are called one time with a `.error` result and an `NSError` containing details about the error. Currently the only errors which can occur are when opening the Realm on a background worker thread to calculate the change set. The callback will never be called again after `.error` is delivered. */ case error(_: NSError) /** One or more of the properties of the object have been changed. */ case change(_: [PropertyChange]) /// The object has been deleted from the Realm. case deleted } /// Object interface which allows untyped getters and setters for Objects. /// :nodoc: public final class DynamicObject: Object { public override subscript(key: String) -> Any? { get { let value = RLMDynamicGetByName(self, key, false) if let array = value as? RLMArray { return List<DynamicObject>(rlmArray: array) } return value } set(value) { RLMDynamicValidatedSet(self, key, value) } } /// :nodoc: public override func value(forUndefinedKey key: String) -> Any? { return self[key] } /// :nodoc: public override func setValue(_ value: Any?, forUndefinedKey key: String) { self[key] = value } /// :nodoc: public override class func shouldIncludeInDefaultSchema() -> Bool { return false } } /// :nodoc: /// Internal class. Do not use directly. @objc(RealmSwiftObjectUtil) public class ObjectUtil: NSObject { @objc private class func swiftVersion() -> NSString { return swiftLanguageVersion as NSString } @objc private class func ignoredPropertiesForClass(_ type: AnyClass) -> NSArray? { if let type = type as? Object.Type { return type.ignoredProperties() as NSArray? } return nil } @objc private class func indexedPropertiesForClass(_ type: AnyClass) -> NSArray? { if let type = type as? Object.Type { return type.indexedProperties() as NSArray? } return nil } @objc private class func linkingObjectsPropertiesForClass(_ type: AnyClass) -> NSDictionary? { // Not used for Swift. getLinkingObjectsProperties(_:) is used instead. return nil } // Get the names of all properties in the object which are of type List<>. @objc private class func getGenericListPropertyNames(_ object: Any) -> NSArray { return Mirror(reflecting: object).children.filter { (prop: Mirror.Child) in return type(of: prop.value) is RLMListBase.Type }.flatMap { (prop: Mirror.Child) in return prop.label } as NSArray } // swiftlint:disable:next cyclomatic_complexity @objc private class func getOptionalProperties(_ object: Any) -> [String: Any] { let children = Mirror(reflecting: object).children return children.reduce([:]) { (properties: [String: Any], prop: Mirror.Child) in guard let name = prop.label else { return properties } let mirror = Mirror(reflecting: prop.value) let type = mirror.subjectType var properties = properties if type is Optional<String>.Type || type is Optional<NSString>.Type { properties[name] = NSNumber(value: PropertyType.string.rawValue) } else if type is Optional<Date>.Type { properties[name] = NSNumber(value: PropertyType.date.rawValue) } else if type is Optional<Data>.Type { properties[name] = NSNumber(value: PropertyType.data.rawValue) } else if type is Optional<Object>.Type { properties[name] = NSNumber(value: PropertyType.object.rawValue) } else if type is RealmOptional<Int>.Type || type is RealmOptional<Int8>.Type || type is RealmOptional<Int16>.Type || type is RealmOptional<Int32>.Type || type is RealmOptional<Int64>.Type { properties[name] = NSNumber(value: PropertyType.int.rawValue) } else if type is RealmOptional<Float>.Type { properties[name] = NSNumber(value: PropertyType.float.rawValue) } else if type is RealmOptional<Double>.Type { properties[name] = NSNumber(value: PropertyType.double.rawValue) } else if type is RealmOptional<Bool>.Type { properties[name] = NSNumber(value: PropertyType.bool.rawValue) } else if prop.value as? RLMOptionalBase != nil { throwRealmException("'\(type)' is not a valid RealmOptional type.") } else if mirror.displayStyle == .optional || type is ExpressibleByNilLiteral.Type { properties[name] = NSNull() } return properties } } @objc private class func requiredPropertiesForClass(_: Any) -> [String] { return [] } // Get information about each of the linking objects properties. @objc private class func getLinkingObjectsProperties(_ object: Any) -> [String: [String: String]] { let properties = Mirror(reflecting: object).children.filter { (prop: Mirror.Child) in return prop.value as? LinkingObjectsBase != nil }.flatMap { (prop: Mirror.Child) in (prop.label!, prop.value as! LinkingObjectsBase) } return properties.reduce([:]) { (dictionary, property) in var d = dictionary let (name, results) = property d[name] = ["class": results.objectClassName, "property": results.propertyName] return d } } } // MARK: AssistedObjectiveCBridgeable // FIXME: Remove when `as! Self` can be written private func forceCastToInferred<T, V>(_ x: T) -> V { return x as! V } extension Object: AssistedObjectiveCBridgeable { static func bridging(from objectiveCValue: Any, with metadata: Any?) -> Self { return forceCastToInferred(objectiveCValue) } var bridged: (objectiveCValue: Any, metadata: Any?) { return (objectiveCValue: unsafeCastToRLMObject(), metadata: nil) } }
mit
66229505ffdf8a3cf167df3d1aa12ada
36.585859
120
0.653856
4.755879
false
false
false
false
warnerbros/cpe-manifest-ios-experience
Source/Out-of-Movie Experience/ExtrasShoppingViewController.swift
1
6650
// // ExtrasShoppingViewController.swift // import UIKit import CPEData import MBProgressHUD class ExtrasShoppingViewController: MenuedViewController { private var extrasShoppingItemsViewController: ExtrasShoppingItemsViewController? { for viewController in self.childViewControllers { if let viewController = viewController as? ExtrasShoppingItemsViewController { return viewController } if let navigationController = viewController as? UINavigationController, let viewController = navigationController.topViewController as? ExtrasShoppingItemsViewController { return viewController } } return nil } private var hud: MBProgressHUD? private var didAutoSelectCategory = false private var productCategoriesSessionDataTask: URLSessionDataTask? private var productListSessionDataTask: URLSessionDataTask? deinit { if let currentTask = productCategoriesSessionDataTask { currentTask.cancel() productCategoriesSessionDataTask = nil } if let currentTask = productListSessionDataTask { currentTask.cancel() productListSessionDataTask = nil } } override func viewDidLoad() { super.viewDidLoad() menuSections.append(MenuSection(title: String.localize("label.all"))) if let productCategories = experience.productCategories { populateMenu(withCategories: productCategories) } else if let productAPIUtil = CPEXMLSuite.Settings.productAPIUtil { _ = productAPIUtil.getProductCategories(completion: { [weak self] (productCategories) in DispatchQueue.main.async { if let productCategories = productCategories { self?.experience.productCategories = productCategories self?.populateMenu(withCategories: productCategories) } self?.autoSelectFirstCategory() } }) } else { menuTableView?.removeFromSuperview() } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) autoSelectFirstCategory() } private func populateMenu(withCategories productCategories: [ProductCategory]) { for category in productCategories { let categoryTitle = category.name let categoryValue = String(category.id) var categoryChildren: [MenuItem]? if let children = (category.childCategories ?? nil) { if children.count > 1 { categoryChildren = [MenuItem(title: String.localize("label.all"), value: String(category.id))] for child in children { categoryChildren!.append(MenuItem(title: child.name, value: String(child.id))) } } } menuSections.append(MenuSection(title: categoryTitle, value: categoryValue, items: categoryChildren)) } menuTableView?.reloadData() } private func autoSelectFirstCategory() { if !didAutoSelectCategory { if let menuTableView = menuTableView { let selectedPath = IndexPath(row: 0, section: 0) if menuTableView.cellForRow(at: selectedPath) != nil { menuTableView.selectRow(at: selectedPath, animated: false, scrollPosition: UITableViewScrollPosition.top) self.tableView(menuTableView, didSelectRowAt: selectedPath) if let menuSection = menuSections.first { if menuSection.isExpandable { let selectedPath = IndexPath(row: 1, section: 0) menuTableView.selectRow(at: selectedPath, animated: false, scrollPosition: UITableViewScrollPosition.top) self.tableView(menuTableView, didSelectRowAt: selectedPath) } didAutoSelectCategory = true } } } else { selectProducts() didAutoSelectCategory = true } } } private func selectProducts(categoryID: String? = nil) { if let app = experience.app, app.isProductApp, let productAPIUtil = CPEXMLSuite.Settings.productAPIUtil { productListSessionDataTask?.cancel() DispatchQueue.main.async { self.hud = MBProgressHUD.showAdded(to: self.view, animated: true) } DispatchQueue.global(qos: .userInitiated).async { self.productListSessionDataTask = productAPIUtil.getCategoryProducts(categoryID, completion: { [weak self] (products) in self?.productListSessionDataTask = nil DispatchQueue.main.async { self?.extrasShoppingItemsViewController?.products = products self?.hud?.hide(true) } }) } Analytics.log(event: .extrasShopAction, action: .selectCategory, itemId: categoryID) } else if let childExperiences = experience.childExperiences { var products = [ProductItem]() for childExperience in childExperiences { if let product = childExperience.product { if let categoryID = categoryID { if let category = product.category, category.id == categoryID { products.append(product) } } else { products.append(product) } } } extrasShoppingItemsViewController?.products = products Analytics.log(event: .extrasShopAction, action: .selectCategory, itemId: categoryID, itemName: products.first?.category??.name) } } // MARK: UITableViewDelegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { super.tableView(tableView, didSelectRowAt: indexPath) if let cell = tableView.cellForRow(at: indexPath) { if let menuSection = (cell as? MenuSectionCell)?.menuSection { if !menuSection.isExpandable { selectProducts(categoryID: menuSection.value) } } else { selectProducts(categoryID: (cell as? MenuItemCell)?.menuItem?.value) } } } }
apache-2.0
15985d82eaa363d08b826d148f475f20
38.349112
184
0.594887
6.0181
false
false
false
false
laszlokorte/reform-swift
ReformCore/ReformCore/RuntimeStack.swift
1
2326
// // RuntimeStack.swift // ReformCore // // Created by Laszlo Korte on 14.08.15. // Copyright © 2015 Laszlo Korte. All rights reserved. // final class RuntimeStack { var frames = [StackFrame]() var data : [UInt64] = [] var dataSize : Int = 0 var formMap : [FormIdentifier:Form] = [:] var forms : [FormIdentifier] = [] var offsets : [FormIdentifier:Int] = [:] func pushFrame() { frames.append(StackFrame()) } func popFrame() { let top = frames.removeLast() for id in top.forms.reversed() { remove(id) } } func declare(_ form : Form) { if let topFrame = frames.last { topFrame.forms.append(form.identifier) formMap[form.identifier] = form offsets[form.identifier] = dataSize dataSize += type(of: form).stackSize growIfNeeded() forms.append(form.identifier) } } func growIfNeeded() { while data.count < dataSize { data.append(0) } } func getData(_ id: FormIdentifier, offset: Int) -> UInt64? { guard let o = offsets[id], o + offset < dataSize else { return nil } return data[o+offset] } func setData(_ id: FormIdentifier, offset: Int, newValue: UInt64){ if let o = offsets[id], o + offset < dataSize { data[o+offset] = newValue } } func getForm(_ id: FormIdentifier) -> Form? { return formMap[id] } func clear() { frames.removeAll(keepingCapacity: true) data.removeAll(keepingCapacity: true) dataSize = 0 formMap.removeAll(keepingCapacity: true) forms.removeAll(keepingCapacity: true) offsets.removeAll(keepingCapacity: true) } private func remove(_ id: FormIdentifier) { if let form = formMap.removeValue(forKey: id) { let offset = offsets.removeValue(forKey: id)! let size = type(of: form).stackSize for i in 0..<size { data[offset + i] = 0 } dataSize -= size forms.removeLast() // TODO: fix } } } final class StackFrame { var forms : [FormIdentifier] = [] }
mit
70bc104b032714a13ed7c6408c466e2e
24.833333
70
0.537204
4.297597
false
false
false
false
DylanSecreast/uoregon-cis-portfolio
uoregon-cis-399/finalProject/TotalTime/Source/View/JobViewController.swift
1
2089
// // JobViewController.swift // TotalTime // // Created by Dylan Secreast on 3/1/17. // Copyright © 2017 Dylan Secreast. All rights reserved. // import UIKit import CoreData class JobViewController : UIViewController { @IBOutlet weak var jobTitleField: UITextField! @IBOutlet weak var hourlyRateField: UITextField! @IBOutlet weak var clientNameField: UITextField! @IBOutlet weak var clientPhoneField: UITextField! @IBOutlet weak var clientEmailField: UITextField! override func viewDidLoad() { super.viewDidLoad() } @IBAction func saveButton(_ sender: Any) { let delegate = UIApplication.shared.delegate as! AppDelegate let context = delegate.persistentContainer.viewContext let job = Job(context: context) let client = Client(context: context) if (jobTitleField.text == "" || hourlyRateField.text == "" || clientEmailField.text == "") { let alertController = UIAlertController(title: "Not Enough Info", message: "Please enter Job Title, Hourly Rate, and Client Email to save", preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) present(alertController, animated: true, completion: nil) return } job.title = jobTitleField.text job.hourlyRate = Float(hourlyRateField.text!)! job.secondsWorked = 0 job.completed = false client.name = clientNameField.text client.email = clientEmailField.text delegate.saveContext() let alertController = UIAlertController(title: "Saved!", message: "Successfully saved " + jobTitleField.text!, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) present(alertController, animated: true, completion: nil) jobTitleField.text = "" hourlyRateField.text = "" clientNameField.text = "" clientEmailField.text = "" } }
gpl-3.0
ce9bb9a2b7cbbe0d0efafa7a20f9cc87
33.8
175
0.653257
4.745455
false
false
false
false
qingtianbuyu/Mono
Moon/Classes/Explore/Controller/MNTeaViewController.swift
1
2419
// // MNTeaViewController.swift // Moon // // Created by YKing on 16/5/21. // Copyright © 2016年 YKing. All rights reserved. // import UIKit class MNTeaViewController: UIViewController { var recentTeaEntityList = MNRecentTeaEntityList() var collectionView: UICollectionView? override func viewDidLoad() { super.viewDidLoad() setupCollectionView() initData() } func initData() { recentTeaEntityList.loadRecentTeaData() } func setupCollectionView() { let layout = UICollectionViewFlowLayout() layout.scrollDirection = UICollectionViewScrollDirection.vertical let width = (ScreenWidth - 1) * 0.5 layout.itemSize = CGSize(width: width, height: 187.5) layout.minimumLineSpacing = 1 layout.minimumInteritemSpacing = 1 let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout) self.view.addSubview(collectionView) collectionView.backgroundColor = UIColor.clear collectionView.delegate = self collectionView.dataSource = self self.collectionView = collectionView self.collectionView?.collectionViewLayout = layout let top: CGFloat = 64 let bottom: CGFloat = self.tabBarController?.tabBar.height ?? 0 self.collectionView?.contentInset = UIEdgeInsetsMake(top, 0, bottom, 0) let nib = UINib(nibName: MNTeaCell.viewIdentify, bundle: nil) self.collectionView?.register(nib, forCellWithReuseIdentifier: MNTeaCell.viewIdentify) } } extension MNTeaViewController: UICollectionViewDataSource, UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return recentTeaEntityList.recent_tea?.count ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MNTeaCell.viewIdentify, for: indexPath) as! MNTeaCell let tea = recentTeaEntityList.recent_tea![(indexPath as NSIndexPath).row] cell.tea = tea return cell } }
mit
e930c41b3146a0f81467f9796fec552b
37.349206
124
0.649421
5.380846
false
false
false
false
LuAndreCast/iOS_WatchProjects
watchOS3/HealthKit Workout/HKworkout/AppDelegate.swift
1
3297
// // AppDelegate.swift // HKworkout // // Created by Luis Castillo on 9/12/16. // Copyright © 2016 LC. All rights reserved. // import UIKit import HealthKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? //MARK: - Request Permission func requestHKpermission() { if let hrQuantityType:HKQuantityType = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate) { let healthStore:HKHealthStore = HKHealthStore() let hkPermission:HealthStorePermission = HealthStorePermission() let hkQuantities:[HKObjectType] = [ hrQuantityType, HKObjectType.workoutType() ] // let hkQuantities:[HKObjectType] = [ hrQuantityType ] hkPermission.requestPermission(healthStore: healthStore, types: hkQuantities, withWriting: false) { (success:Bool, error:Error?) in if error != nil { print("\(error!.localizedDescription)") } } } }//eom //MARK: - Lifecycle func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. /* request HealthStore Permission */ self.requestHKpermission() return true }//eom func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
cc760fa8a06e18a353f22407180fb989
40.721519
285
0.670206
5.90681
false
false
false
false
APUtils/APExtensions
APExtensions/Classes/Storyboard/UITextField+Storyboard.swift
1
1504
// // UITextField+Storyboard.swift // APExtensions // // Created by Anton Plebanovich on 8.02.22. // Copyright © 2022 Anton Plebanovich. All rights reserved. // import UIKit private var defaultFontAssociationKey = 0 extension UITextField { private var defaultFont: UIFont? { get { return objc_getAssociatedObject(self, &defaultFontAssociationKey) as? UIFont } set { objc_setAssociatedObject(self, &defaultFontAssociationKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /// Scale title font for screen @IBInspectable var fitScreenSize: Bool { get { return defaultFont != nil } set { if newValue { defaultFont = font font = font?.screenFitFont } else { // Restore if let defaultFont = defaultFont { font = defaultFont self.defaultFont = nil } } } } /// Makes font scalable depending on device content size category @available(iOS 11.0, *) @IBInspectable var scalable: Bool { @available(*, unavailable) get { return false } set { if newValue { font = font?.scalable adjustsFontForContentSizeCategory = true } else { adjustsFontForContentSizeCategory = false } } } }
mit
737e6711de31d891b43f535fc530cf91
24.913793
116
0.538257
5.445652
false
false
false
false
bmichotte/HSTracker
HSTracker/Logging/Enums/State.swift
1
662
// // State.swift // HSTracker // // Created by Benjamin Michotte on 24/05/16. // Copyright © 2016 Benjamin Michotte. All rights reserved. // import Foundation // swiftlint:disable type_name enum State: Int, EnumCollection { case invalid = 0, loading = 1, running = 2, complete = 3 init?(rawString: String) { let string = rawString.lowercased() for _enum in State.cases() where "\(_enum)" == string { self = _enum return } if let value = Int(rawString), let _enum = State(rawValue: value) { self = _enum return } self = .invalid } }
mit
f0514cdde6ca271028d2eeadc21b9d9e
20.322581
75
0.556732
4.006061
false
false
false
false
haitran2011/Rocket.Chat.iOS
Rocket.Chat/Managers/Model/MessageManager.swift
1
5289
// // MessageManager.swift // Rocket.Chat // // Created by Rafael K. Streit on 7/14/16. // Copyright © 2016 Rocket.Chat. All rights reserved. // import Foundation import RealmSwift struct MessageManager { static let historySize = 30 } let kBlockedUsersIndentifiers = "kBlockedUsersIndentifiers" extension MessageManager { static var blockedUsersList = UserDefaults.standard.value(forKey: kBlockedUsersIndentifiers) as? [String] ?? [] static func getHistory(_ subscription: Subscription, lastMessageDate: Date?, completion: @escaping VoidCompletion) { var lastDate: Any! if let lastMessageDate = lastMessageDate { lastDate = ["$date": lastMessageDate.timeIntervalSince1970 * 1000] } else { lastDate = NSNull() } let request = [ "msg": "method", "method": "loadHistory", "params": ["\(subscription.rid)", lastDate, historySize, [ "$date": Date().timeIntervalSince1970 * 1000 ]] ] as [String : Any] SocketManager.send(request) { response in guard !response.isError() else { return Log.debug(response.result.string) } let list = response.result["result"]["messages"].array let validMessages = List<Message>() let subscriptionIdentifier = subscription.identifier Realm.execute({ (realm) in guard let detachedSubscription = realm.object(ofType: Subscription.self, forPrimaryKey: subscriptionIdentifier ?? "") else { return } list?.forEach { object in let message = Message.getOrCreate(realm: realm, values: object, updates: { (object) in object?.subscription = detachedSubscription }) realm.add(message, update: true) if !message.userBlocked { validMessages.append(message) } } }, completion: completion) } } static func changes(_ subscription: Subscription) { let eventName = "\(subscription.rid)" let request = [ "msg": "sub", "name": "stream-room-messages", "params": [eventName, false] ] as [String : Any] SocketManager.subscribe(request, eventName: eventName) { response in guard !response.isError() else { return Log.debug(response.result.string) } let object = response.result["fields"]["args"][0] let subscriptionIdentifier = subscription.identifier Realm.execute({ (realm) in guard let detachedSubscription = realm.object(ofType: Subscription.self, forPrimaryKey: subscriptionIdentifier ?? "") else { return } let message = Message.getOrCreate(realm: realm, values: object, updates: { (object) in object?.subscription = detachedSubscription }) realm.add(message, update: true) }) } } static func report(_ message: Message, completion: @escaping MessageCompletion) { guard let messageIdentifier = message.identifier else { return } let request = [ "msg": "method", "method": "reportMessage", "params": [messageIdentifier, "Message reported by user."] ] as [String : Any] SocketManager.send(request) { response in guard !response.isError() else { return Log.debug(response.result.string) } completion(response) } } static func pin(_ message: Message, completion: @escaping MessageCompletion) { guard let messageIdentifier = message.identifier else { return } let request = [ "msg": "method", "method": "pinMessage", "params": [ ["rid": message.rid, "_id": messageIdentifier ] ] ] as [String : Any] SocketManager.send(request, completion: completion) } static func unpin(_ message: Message, completion: @escaping MessageCompletion) { guard let messageIdentifier = message.identifier else { return } let request = [ "msg": "method", "method": "unpinMessage", "params": [ ["rid": message.rid, "_id": messageIdentifier ] ] ] as [String : Any] SocketManager.send(request, completion: completion) } static func blockMessagesFrom(_ user: User, completion: @escaping VoidCompletion) { guard let userIdentifier = user.identifier else { return } var blockedUsers: [String] = UserDefaults.standard.value(forKey: kBlockedUsersIndentifiers) as? [String] ?? [] blockedUsers.append(userIdentifier) UserDefaults.standard.setValue(blockedUsers, forKey: kBlockedUsersIndentifiers) self.blockedUsersList = blockedUsers Realm.execute({ (realm) in let messages = realm.objects(Message.self).filter("user.identifier = '\(userIdentifier)'") for message in messages { message.userBlocked = true } realm.add(messages, update: true) DispatchQueue.main.async { completion() } }) } }
mit
cfa7d22f70e8cec9e040cfaa9258b4af
34.019868
149
0.591717
4.909935
false
false
false
false
kumabook/MusicFav
MusicFav/OnpuRefreshControl.swift
1
3829
// // OnpuRefreshControl.swift // MusicFav // // Created by Hiroki Kumamoto on 4/29/15. // Copyright (c) 2015 Hiroki Kumamoto. All rights reserved. // import ISAlternativeRefreshControl class OnpuRefreshControl: ISAlternativeRefreshControl, CAAnimationDelegate { enum AnimationState { case normal case animating case completing case completed } let margin: CGFloat = 15.0 var imageView: UIImageView! var timer: Timer? var prog: CGFloat = 0 var animationState: AnimationState = .normal override init(frame: CGRect) { super.init(frame: frame) let s = frame.size clipsToBounds = false imageView = UIImageView(image: UIImage(named: "loading_icon")) imageView.contentMode = UIViewContentMode.scaleAspectFit let height = s.height * 0.65 imageView.frame = CGRect(x: 0, y: (s.height - height) / 2, width: s.width, height: height) addSubview(imageView) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func didChangeProgress() { switch refreshingState { case .normal: prog = (2.0 * progress).truncatingRemainder(dividingBy: 2.0) updateView() case .refreshing: break case .refreshed: break } } override func willChangeRefreshingState(_ refreshingState: ISRefreshingState) { switch refreshingState { case .normal: imageView.image = UIImage(named: "loading_icon") imageView.layer.removeAllAnimations() animationState = .normal case .refreshing: animationState = .animating startLayerAnimation(false) case .refreshed: animationState = .normal } } override func beginRefreshing() { super.beginRefreshing() } override func endRefreshing() { animationState = .completing } func startLayerAnimation(_ returnNormal: Bool) { let layer = imageView.layer; let animation = CABasicAnimation(keyPath: "transform.rotation") let fromValue = Double.pi * Double(prog) let toValue = returnNormal ? (2 * Double.pi) : (fromValue + 2 * Double.pi) animation.duration = 0.64 * (toValue - fromValue) / (2 * Double.pi) animation.repeatCount = 0 animation.beginTime = CACurrentMediaTime() animation.autoreverses = false animation.fromValue = NSNumber(value: Float(fromValue) as Float) animation.toValue = NSNumber(value: Float(toValue) as Float) animation.isRemovedOnCompletion = false animation.fillMode = kCAFillModeForwards animation.delegate = self layer.add(animation , forKey:"rotate-animation") } func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { switch animationState { case .normal: break case .animating: animationState = .completing startLayerAnimation(false) case .completing: startLayerAnimation(true) animationState = .completed case .completed: self.imageView.image = UIImage(named: "loading_icon_\(arc4random_uniform(4))") let startTime = DispatchTime.now() + Double(Int64(1.0 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: startTime) { super.endRefreshing() } } } func updateView() { imageView.layer.transform = CATransform3DMakeAffineTransform(CGAffineTransform(rotationAngle: CGFloat(Double.pi) * prog)) } }
mit
9a787121c9b56920a0ae9a3e28bb23d0
32.884956
129
0.605902
4.908974
false
false
false
false
jVirus/AERatingControl
AERatingControl/AERatingButton.swift
1
11089
// MIT License // Copyright (c) 2016 Astemir Eleev // // 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 extension CGPath { /** * This CGPath extension allows to automatically adjust the size of the CGPath * to the size of the current frame using affine transformations. * This is helpful in cases when the frame of the view has been changed or/and when * the size of the view's frame is not matching the current CGPath's size */ class func rescaleForFrame(path path: CGPath, frame: CGRect) -> CGPath { let boundingBox = CGPathGetBoundingBox(path) let boundingBoxAspectRatio = CGRectGetWidth(boundingBox) / CGRectGetHeight(boundingBox) let viewAspectRatio = CGRectGetWidth(frame) / CGRectGetHeight(frame) var scaleFactor: CGFloat = 1 if boundingBoxAspectRatio > viewAspectRatio { scaleFactor = CGRectGetWidth(frame) / CGRectGetWidth(boundingBox) } else { scaleFactor = CGRectGetHeight(frame) / CGRectGetHeight(boundingBox) } var scaleTransform = CGAffineTransformIdentity scaleTransform = CGAffineTransformScale(scaleTransform, scaleFactor, scaleFactor) scaleTransform = CGAffineTransformTranslate(scaleTransform, -CGRectGetMinX(boundingBox), CGRectGetMinY(boundingBox)) let scaleSize = CGSizeApplyAffineTransform(boundingBox.size, CGAffineTransformMakeScale(scaleFactor, scaleFactor)) let centerOffset = CGSizeMake((CGRectGetWidth(frame) - scaleSize.width) / (scaleFactor * 2.0), (CGRectGetHeight(frame) - scaleSize.height) / (scaleFactor * 2.0)) scaleTransform = CGAffineTransformTranslate(scaleTransform, centerOffset.width, centerOffset.height) if let scaleTransform = CGPathCreateCopyByTransformingPath(path, &scaleTransform) { return scaleTransform } else { return path } } } @IBDesignable public class AERatingButton: UIButton { @IBInspectable public var starColor: UIColor = UIColor.clearColor() { didSet { if starLayer != nil { starLayer.fillColor = starColor.CGColor } } } @IBInspectable public var starStrokeColor: UIColor = UIColor.clearColor() { didSet { if starLayer != nil { starLayer.strokeColor = starStrokeColor.CGColor } } } @IBInspectable public var starScaleX: CGFloat = 1.0 { didSet { setNeedsLayout() } } @IBInspectable public var starScaleY: CGFloat = 1.0 { didSet { setNeedsLayout() } } @IBInspectable public var starAnimScaleUpX: CGFloat = 1.15 { didSet { setNeedsLayout() } } @IBInspectable public var starAnimScaleUpY: CGFloat = 1.15 { didSet { setNeedsLayout() } } @IBInspectable public var starAnimScaleGrowX: CGFloat = 1.35 { didSet { setNeedsLayout() } } @IBInspectable public var starAnimScaleGrowY: CGFloat = 1.35 { didSet { setNeedsLayout() } } @IBInspectable public var starAnimPressDuration: Double = 0.5 { didSet { setNeedsLayout() } } @IBInspectable public var starOpacity: Float = 1.0 { didSet { setNeedsLayout() } } @IBInspectable public var starLineWidth: CGFloat = 1.0 { didSet { setNeedsLayout() } } @IBInspectable public var backgroundLayerColor: UIColor = UIColor.clearColor() { didSet { self.layer.backgroundColor = backgroundLayerColor.CGColor } } private var starLayer: CAShapeLayer! private var circleLayer: CAShapeLayer! private var currentStarBounds: CGRect? private var currentCircleBounds: CGRect? private var currentStarPosition: CGPoint? private var currentCirclePosition: CGPoint? public override init(frame: CGRect) { super.init(frame: frame) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.addTarget(self, action: #selector(AERatingButton.animation(_:)), forControlEvents: .TouchUpInside) } public override func layoutSubviews() { super.layoutSubviews() createLayersIfNeeded() } public override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() setNeedsLayout() } public func ratingPressAnimation(duration: Double, delay: Double) { if starLayer != nil { var scaleUp = CATransform3DIdentity scaleUp = CATransform3DMakeScale(starAnimScaleUpX, starAnimScaleUpY, 1.0) var scaleDown = CATransform3DIdentity scaleDown = CATransform3DMakeScale(0.01, 0.01, 0.01) let keyframePress = CAKeyframeAnimation(keyPath: "transform") keyframePress.values = [ NSValue(CATransform3D: CATransform3DIdentity), NSValue(CATransform3D: scaleUp), NSValue(CATransform3D: scaleDown) ] keyframePress.keyTimes = [0.0, 0.4, 0.6] keyframePress.duration = duration keyframePress.beginTime = CACurrentMediaTime() + 0.05 + delay keyframePress.fillMode = kCAFillModeBackwards starLayer.addAnimation(keyframePress, forKey: "keyframe_press") starLayer.transform = scaleUp var fillGrow = CATransform3DIdentity fillGrow = CATransform3DScale(fillGrow, starAnimScaleGrowX, starAnimScaleGrowY, 1.0) let fillNoteAnimaiton = CAKeyframeAnimation(keyPath: "transform") fillNoteAnimaiton.values = [ NSValue(CATransform3D: starLayer.transform), NSValue(CATransform3D: fillGrow), NSValue(CATransform3D: CATransform3DIdentity) ] fillNoteAnimaiton.keyTimes = [0.0, 0.4, 0.6] fillNoteAnimaiton.duration = duration fillNoteAnimaiton.beginTime = CACurrentMediaTime() + 0.25 + delay fillNoteAnimaiton.fillMode = kCAFillModeBackwards starLayer.addAnimation(fillNoteAnimaiton, forKey: "fill_note_keyframe_animaiton") starLayer.transform = CATransform3DIdentity } } /** * Animation that fills the rating button with a color */ public func fillColorAnimation(duration: Double, fromColor: UIColor, toColor: UIColor, delay: Double, fillMode: String) { if starLayer != nil { let colorAnimation = CABasicAnimation(keyPath: "fillColor") colorAnimation.fromValue = fromColor.CGColor colorAnimation.toValue = toColor.CGColor colorAnimation.duration = duration colorAnimation.beginTime = CACurrentMediaTime() + delay colorAnimation.fillMode = fillMode colorAnimation.removedOnCompletion = true starLayer.addAnimation(colorAnimation, forKey: "simple_color_animation") } } public func animation(button: AERatingButton) { ratingPressAnimation(starAnimPressDuration, delay: 0) } public func setStarAnchorPoint(point: CGPoint) { if starLayer != nil { starLayer.anchorPoint = point } } public func updateStarLayout() { if starLayer != nil { updateLayerLayout(starLayer, path: AEPath.star, scaleX: starScaleX, scaleY: starScaleY) } } private func createLayersIfNeeded() { if starLayer == nil { starLayer = CAShapeLayer() updateStarLayout() currentStarBounds = CGPathGetBoundingBox(starLayer.path) currentStarPosition = CGPointMake(CGRectGetWidth(self.bounds) / 2, CGRectGetHeight(self.bounds) / 2) starLayer.fillColor = starColor.CGColor starLayer.opacity = starOpacity starLayer.lineWidth = starLineWidth starLayer.strokeColor = starStrokeColor.CGColor self.layer.addSublayer(starLayer) } else { updateStarLayout() animateLayerLayoutTransition(starLayer, newPath: AEPath.star, duration: 0.5) currentStarBounds = CGPathGetBoundingBox(starLayer.path) currentStarPosition = starLayer.position } self.layer.backgroundColor = backgroundLayerColor.CGColor } private func updateLayerLayout(caShapeLayer: CAShapeLayer, path: CGPath, scaleX: CGFloat, scaleY: CGFloat) { caShapeLayer.path = CGPath.rescaleForFrame(path: path, frame: self.bounds) caShapeLayer.bounds = CGPathGetBoundingBox(caShapeLayer.path) caShapeLayer.position = CGPoint(x: CGRectGetWidth(self.bounds) / 2, y: CGRectGetHeight(self.bounds)/2) caShapeLayer.transform = CATransform3DIdentity caShapeLayer.transform = CATransform3DMakeScale(CGFloat(scaleX), CGFloat(scaleY), 1.0) } private func animateLayerLayoutTransition(shapeLayer: CAShapeLayer, newPath: CGPath, duration: Double) { let pathAnimation = CABasicAnimation(keyPath: "path") pathAnimation.fromValue = NSValue(nonretainedObject: shapeLayer.path) pathAnimation.toValue = NSValue(nonretainedObject: newPath) pathAnimation.duration = duration pathAnimation.beginTime = CACurrentMediaTime() shapeLayer.addAnimation(pathAnimation, forKey: "path_animation") shapeLayer.transform = CATransform3DIdentity } }
mit
4b20192aebf4fa8c4f85de1933e32c1e
34.428115
169
0.635404
5.318465
false
false
false
false
smaltby/Canary
iOS/Canary/Canary/WebViewController.swift
1
2299
import UIKit import WebKit @objc protocol WebViewControllerDelegate { func webViewControllerDidFinish(_ controller: WebViewController) /*! @abstract Invoked when the initial URL load is complete. @param success YES if loading completed successfully, NO if loading failed. @discussion This method is invoked when SFSafariViewController completes the loading of the URL that you pass to its initializer. It is not invoked for any subsequent page loads in the same SFSafariViewController instance. */ @objc optional func webViewController(_ controller: WebViewController, didCompleteInitialLoad didLoadSuccessfully: Bool) } class WebViewController: UIViewController, UIWebViewDelegate { var loadComplete: Bool = false var initialURL: URL! var webView: UIWebView! var delegate: WebViewControllerDelegate? override func viewDidLoad() { super.viewDidLoad() print(initialURL) let initialRequest = URLRequest(url: self.initialURL) self.webView = UIWebView(frame: self.view.bounds) self.webView.delegate = self self.webView.autoresizingMask = [.flexibleWidth, .flexibleHeight] self.view.addSubview(self.webView) self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(self.done)) self.webView.loadRequest(initialRequest) } func done() { self.delegate?.webViewControllerDidFinish(self) self.presentingViewController?.dismiss(animated: true, completion: { _ in }) } func webViewDidFinishLoad(_ webView: UIWebView) { if !self.loadComplete { delegate?.webViewController?(self, didCompleteInitialLoad: true) self.loadComplete = true } } func webView(_ webView: UIWebView, didFailLoadWithError error: Error) { if !self.loadComplete { delegate?.webViewController?(self, didCompleteInitialLoad: true) self.loadComplete = true } } init(url URL: URL) { super.init(nibName: nil, bundle: nil) self.initialURL = URL as URL! } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
mit
ef8bca3dd219ec058e150c08d121d069
34.921875
135
0.678556
5.26087
false
false
false
false
Yalantis/PixPic
PixPic/Classes/Flow/FollowersList/FollowersListViewController.swift
1
3734
// // FollowersViewController.swift // PixPic // // Created by anna on 3/3/16. // Copyright © 2016 Yalantis. All rights reserved. // import UIKit typealias FollowersListRouterInterface = protocol<ProfilePresenter, AlertManagerDelegate> final class FollowersListViewController: UIViewController, StoryboardInitiable { static let storyboardName = Constants.Storyboard.profile private var router: FollowersListRouterInterface! private var user: User! private var followType: FollowType = .Followers private lazy var followerAdapter = FollowerAdapter() private weak var locator: ServiceLocator! @IBOutlet weak var tableView: UITableView! // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() setupTableView() setupAdapter() setupObserver() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) AlertManager.sharedInstance.setAlertDelegate(router) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } // MARK: - Setup methods func setLocator(locator: ServiceLocator) { self.locator = locator } func setUser(user: User) { self.user = user } func setFollowType(type: FollowType) { self.followType = type } func setRouter(router: FollowersListRouterInterface) { self.router = router } // MARK: - Private methods private func setupTableView() { tableView.delegate = self tableView.registerNib(FollowerViewCell.cellNib, forCellReuseIdentifier: FollowerViewCell.id) } private func setupAdapter() { tableView.dataSource = followerAdapter followerAdapter.delegate = self let cache = AttributesCache.sharedCache let activityService: ActivityService = locator.getService() let isFollowers = (followType == .Followers) let key = isFollowers ? Constants.Attributes.followers : Constants.Attributes.following if let attributes = cache.attributes(for: user), cachedUsers = attributes[key] as? [User] { self.followerAdapter.update(withFollowers: cachedUsers, action: .Reload) } activityService.fetchFollowers(followType, forUser: user) { [weak self] followers, _ in if let followers = followers { self?.followerAdapter.update(withFollowers: followers, action: .Reload) } } } private func setupObserver() { NSNotificationCenter.defaultCenter().addObserver( self, selector: #selector(updateData), name: Constants.NotificationName.followersListIsUpdated, object: nil ) } @objc private func updateData() { setupAdapter() } } // MARK: - FollowerAdapterDelegate methods extension FollowersListViewController: FollowerAdapterDelegate { func followerAdapterRequestedViewUpdate(adapter: FollowerAdapter) { tableView.reloadData() } } // MARK: - UITableViewDelegate methods extension FollowersListViewController: UITableViewDelegate { func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let follower = followerAdapter.getFollower(atIndexPath: indexPath) router.showProfile(follower) } } // MARK: - NavigationControllerAppearanceContext methods extension FollowersListViewController: NavigationControllerAppearanceContext { func preferredNavigationControllerAppearance(navigationController: UINavigationController) -> Appearance? { var appearance = Appearance() appearance.title = followType.rawValue return appearance } }
mit
fc11fee47adb204f63ab74eb94a3f963
27.280303
111
0.693276
5.099727
false
false
false
false
evering7/iSpeak8
iSpeak8/Data_Global.swift
1
5452
// // Data_Global.swift // iSpeak8 // // Created by JianFei Li on 14/08/2017. // Copyright © 2017 JianFei Li. All rights reserved. // import Foundation import CoreData //import CoreStore // TODO: 2017.9.21 // 1. add support of nsset for memory // 2. add support of # and auto extract http string from a line let globalData = GlobalData() class GlobalData: NSObject { var listSourceFeeds = ListOfSourceFeeds_Memory_TS(queueLabel: "main list of source feeds") var listShowSourceFeeds = ListOfSourceFeeds_Memory_TS(queueLabel: "show list of source feeds") var listShowItemFeeds = ListOfItemFeeds_Memory_TS(queueLabel: "show list of feed items") func initializeSourceBasicInformation() { // let app = application() // Here: we should add the read function, to read out the record in database self.listSourceFeeds.readSourceFeed_FromCoreData_ToMem() // let tmpCount = 0 let tmpCount = globalCoreData.getCountOfSourceFeed_InCoreData_V4() printLog("list of source feed sourcs count = \(String(describing: tmpCount))") // 1. test if the sources list is empty // if self.listSourceFeeds.count == 0 { // if tmpCount == 0 { if tmpCount < 100 { // Here 2017 July 16th, we need to add the initial url of feeds // Here, these lines had better being merged into one function 2017.9.15 if false == self.listSourceFeeds.initializeSourceData_HighLevel(){ printLog("fail to initialize the list of sources RSS auto by this app.") } if false == self.listSourceFeeds.getSourceFeedsFromFileInBundle(strFileName: "SourcesFeed_List.txt"){ printLog("fail to get list of sourcefeed from file in the bundle.") } // Here: save the listSourceFeeds elements url to disk 2017.9.8 self.listSourceFeeds.saveListOfSourceFeeds_ToCoreData() } // if app.globalData.listSourceRSS.count == 0 } // initializeSourceBasicInformation 2017 July 19th func refreshSourceAndItemData() -> Void { if self.listSourceFeeds.count == 0 { printLog("Unexpected the list source feeds count = 0") return } var downIndex = self.listSourceFeeds.startIndex // Download Index printLog("start cycling with first index = \(downIndex)") while true { if let sourceFeed_Unwrap = self.listSourceFeeds[downIndex] { // succefully unwrap the sourceFeed_Unwrap //if true == sourceFeed_Unwrap.loadSourceAndItems_OfFeed_FromWeb(){ printLog("currently scanning source feed: \(sourceFeed_Unwrap.url.getStrValue())") let (isSuccess, feedKitResult, swXMLhashResult) = sourceFeed_Unwrap.loadInformationSourceFeed_FromXMLFile() if true == isSuccess { // successfully to download and analyze the feed and item // Here: import information of items into memory variable // add the sourcefeed to list self.listShowSourceFeeds.append(sourceFeed_Unwrap) let isSucceedUpdate = sourceFeed_Unwrap.updateType_2Titles_Lang_InCoreData() // change name to updateSave_Type_2Titles_Lang_InCoreData() if false == isSucceedUpdate { printLog("fail to get updating the CoreData 4 data items") printLog("url = \(sourceFeed_Unwrap.url.getStrValue())") continue } // if false == isSucceedUpdate 2017.9.19 // Here: add support to analyze the // TODO: // loadAndSave_ItemFeeds_FromParsedResult 2017.9.19 if true == sourceFeed_Unwrap.loadAndSave_ItemFeeds_FromParsedResult( resultFeedKit: feedKitResult, resultSWXMLHash: swXMLhashResult) { // if ok to save items, then // sort the items in source feed show list. } } else { // fail to download and analyze the feed and item printLog("fail to download and analyze the feed at URL") printLog("URL = \(sourceFeed_Unwrap.url.getStrValue())") } } else { // sourceFeed Unwrap failure printLog("Warning: fail to unwrap the source feed") } // if - else - sourceFeed unwrap let clause printLog("before iterating: downIndex = \(downIndex)") downIndex = self.listSourceFeeds.getNextQueryIndex_BasicSafe(downIndex) printLog("after iterating: downIndex = \(downIndex)") if (downIndex > self.listSourceFeeds.endIndex) || (downIndex < 0) { break } // break } // while loop to get downloading all sorceFeeds } // func refreshSourceAndItemData() 2017.9.13 } // class GlobalData: NSObject 2017.8.14
mit
036b396bf869ddbdc9d161414b5e7d9e
42.261905
113
0.567052
4.97354
false
false
false
false
manGoweb/SpecTools
SpecTools/Classes/Checks/Checks+UITableView.swift
1
1626
// // Checks+UITableView.swift // SpecTools // // Created by Ondrej Rafaj on 11/09/2017. // import Foundation import UIKit extension Check where T: UITableView { // MARK: UITableView /// Check if there are any cells that don't fit criteria specified in a closure /// - Parameter fit: Closure that needs to evaluate the cell which is passed onto it /// - Returns: Bool (true if no issue is found) public func allCells(fit evaluateClosure: (UITableViewCell)->Bool) -> Bool { return allCells(thatDontFit: evaluateClosure).count == 0 } /// Check if there are any cells that don't fit criteria specified in a closure /// - Parameter fit: Closure that needs to evaluate the cell which is passed onto it /// - Returns: [IndexPath] Index path of all cells that do not match the given criteria public func allCells(thatDontFit evaluateClosure: (UITableViewCell)->Bool) -> [IndexPath] { var indexPaths: [IndexPath] = [] for sectionIndex in 0...element.spec.find.numberOfSections() { row: for rowIndex in 0...element.spec.find.number(ofRowsIn: sectionIndex) { let indexPath = IndexPath(item: rowIndex, section: sectionIndex) guard let cell = element.dataSource?.tableView(element, cellForRowAt: indexPath) else { fatalError("Data source is not set") } let ok = evaluateClosure(cell) if !ok { indexPaths.append(indexPath) } } } return indexPaths } }
mit
2c7513e89f50de9713a44c73c9a91834
35.133333
103
0.618081
4.740525
false
false
false
false
borglab/SwiftFusion
Tests/SwiftFusionTests/Inference/ChordalInitializationTests.swift
1
6228
// Copyright 2020 The SwiftFusion Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import _Differentiation import Foundation import TensorFlow import XCTest import PenguinStructures import SwiftFusion // MARK: sample data // symbol shorthands let x0 = TypedID<Pose3>(0) let x1 = TypedID<Pose3>(1) let x2 = TypedID<Pose3>(2) let x3 = TypedID<Pose3>(3) // ground truth let p0 = Vector3(0,0,0); let R0 = Rot3.fromTangent(Vector3(0.0,0.0,0.0)) let p1 = Vector3(1,2,0) // let R1 = Rot3.fromTangent(Vector3(0.0,0.0,1.570796)) let R1 = Rot3(3.26795e-07, -1, 0, 1, 3.26795e-07, 0, 0, 0, 1) let p2 = Vector3(0,2,0) let R2 = Rot3.fromTangent(Vector3(0.0,0.0,3.141593)) let p3 = Vector3(-1,1,0) let R3 = Rot3.fromTangent(Vector3(0.0,0.0,4.712389)) let pose0 = Pose3(R0,p0) let pose1 = Pose3(R1,p1) let pose2 = Pose3(R2,p2) let pose3 = Pose3(R3,p3) /// simple test graph for the chordal initialization func graph1() -> FactorGraph { var g = FactorGraph() g.store(BetweenFactor(x0, x1, between(pose0, pose1))) g.store(BetweenFactor(x1, x2, between(pose1, pose2))) g.store(BetweenFactor(x2, x3, between(pose2, pose3))) g.store(BetweenFactor(x2, x0, between(pose2, pose0))) g.store(BetweenFactor(x0, x3, between(pose0, pose3))) g.store(PriorFactor(x0, pose0)) return g } class ChordalInitializationTests: XCTestCase { /// make sure the derivatives are correct func testFrobeniusRot3BetweenJacobians() { print(Matrix3.standardBasis) var val = VariableAssignments() let p0 = val.store(Matrix3(1,0,0,0,1,0,0,0,1)) let p1 = val.store(Matrix3(1,0,0,0,1,0,0,0,1)) let frf = RelaxedRotationFactorRot3(p0, p1, Matrix3(0.0,0.1,0.2,1.0,1.1,1.2,2.0,2.1,2.2)) let frf_j = JacobianFactor9x3x3_2(linearizing: frf, at: Tuple2(val[p0], val[p1])) let Rij = Matrix3(0.0,0.1,0.2,1.0,1.1,1.2,2.0,2.1,2.2) let M9: Jacobian9x3x3_2 = [ Tuple2(Matrix3(-1,0,0,0,0,0,0,0,0), Matrix3(Rij[0, 0],Rij[0, 1],Rij[0, 2],0,0,0,0,0,0)), Tuple2(Matrix3(0,-1,0,0,0,0,0,0,0), Matrix3(Rij[1, 0],Rij[1, 1],Rij[1, 2],0,0,0,0,0,0)), Tuple2(Matrix3(0,0,-1,0,0,0,0,0,0), Matrix3(Rij[2, 0],Rij[2, 1],Rij[2, 2],0,0,0,0,0,0)), Tuple2(Matrix3(0,0,0,-1,0,0,0,0,0), Matrix3(0,0,0,Rij[0, 0],Rij[0, 1],Rij[0, 2],0,0,0)), Tuple2(Matrix3(0,0,0,0,-1,0,0,0,0), Matrix3(0,0,0,Rij[1, 0],Rij[1, 1],Rij[1, 2],0,0,0)), Tuple2(Matrix3(0,0,0,0,0,-1,0,0,0), Matrix3(0,0,0,Rij[2, 0],Rij[2, 1],Rij[2, 2],0,0,0)), Tuple2(Matrix3(0,0,0,0,0,0,-1,0,0), Matrix3(0,0,0,0,0,0,Rij[0, 0],Rij[0, 1],Rij[0, 2])), Tuple2(Matrix3(0,0,0,0,0,0,0,-1,0), Matrix3(0,0,0,0,0,0,Rij[1, 0],Rij[1, 1],Rij[1, 2])), Tuple2(Matrix3(0,0,0,0,0,0,0,0,-1), Matrix3(0,0,0,0,0,0,Rij[2, 0],Rij[2, 1],Rij[2, 2])) ] let b = Vector9(0, 0, 0, 0, 0, 0, 0, 0, 0) let jf = JacobianFactor9x3x3_2(jacobian: M9, error: b, edges: Tuple2(TypedID<Matrix3>(0), TypedID<Matrix3>(1))) // assert the jacobian is correct assertEqual( Tensor<Double>(stacking: frf_j.jacobian.map { $0.flatTensor }), Tensor<Double>(stacking: jf.jacobian.map { $0.flatTensor }) , accuracy: 1e-4 ) let frf_zero = RelaxedRotationFactorRot3(p0, p1, Matrix3.identity) let frf_zero_j = JacobianFactor9x3x3_2(linearizing: frf_zero, at: Tuple2(val[p0], val[p1])) // assert the zero error is correct assertAllKeyPathEqual(frf_zero_j.error, jf.error, accuracy: 1e-5) let fpf = RelaxedAnchorFactorRot3(p0, Matrix3.identity) let fpf_j = JacobianFactor9x3x3_1(linearizing: fpf, at: Tuple1(Matrix3.zero)) let I_9x9: Jacobian9x3x3_1 = [ Tuple1(Matrix3(1,0,0,0,0,0,0,0,0)), Tuple1(Matrix3(0,1,0,0,0,0,0,0,0)), Tuple1(Matrix3(0,0,1,0,0,0,0,0,0)), Tuple1(Matrix3(0,0,0,1,0,0,0,0,0)), Tuple1(Matrix3(0,0,0,0,1,0,0,0,0)), Tuple1(Matrix3(0,0,0,0,0,1,0,0,0)), Tuple1(Matrix3(0,0,0,0,0,0,1,0,0)), Tuple1(Matrix3(0,0,0,0,0,0,0,1,0)), Tuple1(Matrix3(0,0,0,0,0,0,0,0,1)) ] // prior on the anchor orientation let jf_p = JacobianFactor9x3x3_1(jacobian: I_9x9, error: Vector9(1.0, 0.0, 0.0, /* */ 0.0, 1.0, 0.0, /* */ 0.0, 0.0, 1.0), edges: Tuple1(TypedID<Matrix3>(0))) // assert the Jacobian is correct assertEqual( Tensor<Double>(stacking: fpf_j.jacobian.map { $0.flatTensor }), Tensor<Double>(stacking: jf_p.jacobian.map { $0.flatTensor }) , accuracy: 1e-4 ) // assert the error at zero is correct assertAllKeyPathEqual(fpf_j.error, jf_p.error, accuracy: 1e-5) } /// sanity test for the chordal initialization on `graph1` func testChordalOrientation() { var ci = ChordalInitialization() var val = VariableAssignments() let _ = val.store(pose0) let _ = val.store(pose0) let _ = val.store(pose0) let _ = val.store(pose0) var val_copy = val ci.anchorId = val_copy.store(Pose3()) let pose3Graph = ci.buildPose3graph(graph: graph1()) let initial = ci.solveOrientationGraph(g: pose3Graph, v: val_copy, ids: [x0, x1, x2, x3]) assertAllKeyPathEqual(Matrix3.identity, initial[TypedID<Rot3>(ci.anchorId.perTypeID)].coordinate.R, accuracy: 1e-5) assertAllKeyPathEqual( R0, initial[TypedID<Rot3>(x0.perTypeID)], accuracy: 1e-5) assertAllKeyPathEqual( R1, initial[TypedID<Rot3>(x1.perTypeID)], accuracy: 1e-5) assertAllKeyPathEqual( R2, initial[TypedID<Rot3>(x2.perTypeID)], accuracy: 1e-5) assertAllKeyPathEqual( R3, initial[TypedID<Rot3>(x3.perTypeID)], accuracy: 1e-5) } }
apache-2.0
bc6d53d98a26e6a41aa2cc7e42d3117b
37.68323
119
0.629416
2.467512
false
false
false
false
josherick/DailySpend
DailySpend/ExpenseTableViewCell.swift
1
9611
// // DatePickerTableViewCell.swift // DailySpend // // Created by Josh Sherick on 9/9/17. // Copyright © 2017 Josh Sherick. All rights reserved. // import UIKit class ExpenseCellButton : UIButton { let pressedColor = UIColor(red:0.50, green:0.50, blue:0.51, alpha:1.00) var nonHighlightedBackgroundColor: UIColor? { didSet { backgroundColor = nonHighlightedBackgroundColor } } override open var isHighlighted: Bool { didSet { if isHighlighted { backgroundColor = pressedColor } else { backgroundColor = nonHighlightedBackgroundColor } } } override init(frame: CGRect) { super.init(frame: frame) self.layer.cornerRadius = 5 // let lightColor = UIColor(red:0.99, green:0.98, blue:0.99, alpha:1.00) let darkColor = UIColor(red:0.66, green:0.70, blue:0.75, alpha:1.00) self.nonHighlightedBackgroundColor = darkColor self.backgroundColor = darkColor } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class ExpenseTableViewCell: UITableViewCell, UITextFieldDelegate, CalculatorTextFieldDelegate { let margin: CGFloat = 8 let inset: CGFloat = 15 let collapsedHeight: CGFloat = 44 let expandedHeight: CGFloat = 88 let amountFieldMaxWidth: CGFloat = 120 var descriptionField: UITextField! var amountField: CalculatorTextField! var detailDisclosureButton: UIButton! var plusButton: UIButton! var saveButton: ExpenseCellButton! var cancelButton: ExpenseCellButton! var detailDisclosureButtonOnscreen: Bool = false var plusButtonOnscreen: Bool = false var beganEditing: ((ExpenseTableViewCell, UITextField) -> ())? var shouldBegin: ((ExpenseTableViewCell, UITextField) -> ())? var willReturn: ((ExpenseTableViewCell, UITextField, UITextField) -> ())? var endedEditing: ((ExpenseTableViewCell, UITextField) -> ())? var changedDescription: ((UITextField) -> ())? var changedEvaluatedAmount: ((UITextField, Decimal?) -> ())? var tappedSave: ((UITextField, CalculatorTextField) -> ())? var tappedCancel: ((UITextField, CalculatorTextField) -> ())? var selectedDetailDisclosure: (() -> ())? override func layoutSubviews() { super.layoutSubviews() layoutOwnSubviews(animated: false) } private func setDetailDisclosureButtonFrame(onscreen: Bool) { let ics = detailDisclosureButton.intrinsicContentSize let x = bounds.size.width - ics.width - inset let y = (collapsedHeight / 2) - (ics.height / 2) var frame = CGRect(x: x, y: y, width: ics.width, height: ics.height) if !onscreen { frame.origin.x = bounds.size.width + ics.width + inset } detailDisclosureButton.frame = frame } private func setPlusButtonFrame(onscreen: Bool) { var frame = CGRect(x: margin, y: 0, width: 25, height: 38) if !onscreen { frame.origin.x = -25 - margin } plusButton.frame = frame } private func layoutOwnSubviews(animated: Bool) { if animated { UIView.beginAnimations("ExpenseTableViewCell.layoutOwnSubviews", context: nil) } var adjustedDetailDisclosureWidth: CGFloat = 0 var adjustedPlusWidth: CGFloat = 0 if detailDisclosureButton != nil { setDetailDisclosureButtonFrame(onscreen: detailDisclosureButtonOnscreen) let width = detailDisclosureButton.frame.size.width + margin / 2 adjustedDetailDisclosureWidth = detailDisclosureButtonOnscreen ? width : 0 } if plusButton != nil { setPlusButtonFrame(onscreen: plusButtonOnscreen) let width = plusButton.frame.size.width + margin * 1.5 - inset adjustedPlusWidth = plusButtonOnscreen ? width : 0 } if amountField != nil { let height = collapsedHeight - (margin * 2) let minWidth = amountField.placeholder?.calculatedWidthForHeight(height, font: amountField.font) ?? 80 let calcWidth = amountField.text?.calculatedWidthForHeight(height, font: amountField.font) ?? minWidth let width = min(max(calcWidth, minWidth), amountFieldMaxWidth) let rightSide = inset + margin / 2 + adjustedDetailDisclosureWidth amountField.frame = CGRect( x: bounds.size.width - rightSide - width, y: margin, width: width, height: height ) } if descriptionField != nil { let rightSide = bounds.size.width - ( amountField?.frame.leftEdge ?? inset + margin / 2 + adjustedDetailDisclosureWidth ) let leftSide = inset + adjustedPlusWidth descriptionField.frame = CGRect( x: leftSide, y: margin, width: bounds.size.width - leftSide - rightSide, height: collapsedHeight - (margin * 2) ) } // Bottom buttons let halfWidth = bounds.size.width / 2 let cancelFrame = CGRect( x: 0, y: collapsedHeight, width: halfWidth, height: expandedHeight - collapsedHeight ).insetBy(dx: margin, dy: margin) if cancelButton != nil { cancelButton.frame = cancelFrame.shiftedLeftEdge(by: margin) } if saveButton != nil { saveButton.frame = cancelFrame.offsetBy(dx: halfWidth, dy: 0).shiftedRightEdge(by: -margin) } if animated { UIView.commitAnimations() } } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) descriptionField = UITextField() amountField = CalculatorTextField() descriptionField.borderStyle = .none descriptionField.delegate = self descriptionField.returnKeyType = .next descriptionField.smartInsertDeleteType = .no amountField.borderStyle = .none amountField.smartInsertDeleteType = .no amountField.delegate = self amountField.textAlignment = .right amountField.calcDelegate = self descriptionField.addTarget(self, action: #selector(textFieldChanged(field:)), for: .editingChanged) amountField.addTarget(self, action: #selector(textFieldChanged(field:)), for: .editingChanged) detailDisclosureButton = UIButton(type: .detailDisclosure) detailDisclosureButton.add(for: .touchUpInside, { self.selectedDetailDisclosure?() }) plusButton = UIButton(type: .custom) plusButton.setTitle("+", for: .normal) plusButton.setTitleColor(UIColor(red255: 198, green: 198, blue: 198), for: .normal) plusButton.titleLabel?.font = UIFont.systemFont(ofSize: 41.0, weight: .thin) plusButton.add(for: .touchUpInside) { self.descriptionField.becomeFirstResponder() } saveButton = ExpenseCellButton(type: .custom) saveButton.setTitle("Save", for: .normal) saveButton.add(for: .touchUpInside) { self.tappedSave?(self.descriptionField, self.amountField) } cancelButton = ExpenseCellButton(type: .custom) cancelButton.setTitle("Cancel", for: .normal) cancelButton.add(for: .touchUpInside) { self.tappedCancel?(self.descriptionField, self.amountField) } self.addSubviews([descriptionField, amountField, detailDisclosureButton, plusButton, saveButton, cancelButton]) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func textFieldDidBeginEditing(_ textField: UITextField) { beganEditing?(self, textField) } func textFieldDidEndEditing(_ textField: UITextField) { endedEditing?(self, textField) } func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField == descriptionField { willReturn?(self, descriptionField, amountField) } else { willReturn?(self, amountField, descriptionField) } return true } func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { shouldBegin?(self, textField) return true } @objc func textFieldChanged(field: UITextField!) { if field == descriptionField { changedDescription?(field) } else { // Size of amount field may have changed. self.setNeedsLayout() } } func textFieldChangedEvaluatedValue(_ textField: CalculatorTextField, to newValue: Decimal?) { changedEvaluatedAmount?(textField, newValue) } func setDetailDisclosure(show: Bool, animated: Bool) { if show != detailDisclosureButtonOnscreen { detailDisclosureButtonOnscreen = show self.layoutOwnSubviews(animated: animated) } } func setPlusButton(show: Bool, animated: Bool) { if show != plusButtonOnscreen { plusButtonOnscreen = show self.layoutOwnSubviews(animated: animated) } } }
mit
d5eceaa5bc0519a8ce2bb20afb159920
34.592593
119
0.616337
5.015658
false
false
false
false
faimin/ZDOpenSourceDemo
ZDOpenSourceSwiftDemo/Pods/lottie-ios/lottie-swift/src/Private/Model/ShapeItems/Stroke.swift
1
2146
// // Stroke.swift // lottie-swift // // Created by Brandon Withrow on 1/8/19. // import Foundation /// An item that define an ellipse shape final class Stroke: ShapeItem { /// The opacity of the stroke let opacity: KeyframeGroup<Vector1D> /// The Color of the stroke let color: KeyframeGroup<Color> /// The width of the stroke let width: KeyframeGroup<Vector1D> /// Line Cap let lineCap: LineCap /// Line Join let lineJoin: LineJoin /// Miter Limit let miterLimit: Double /// The dash pattern of the stroke let dashPattern: [DashElement]? private enum CodingKeys : String, CodingKey { case opacity = "o" case color = "c" case width = "w" case lineCap = "lc" case lineJoin = "lj" case miterLimit = "ml" case dashPattern = "d" } required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: Stroke.CodingKeys.self) self.opacity = try container.decode(KeyframeGroup<Vector1D>.self, forKey: .opacity) self.color = try container.decode(KeyframeGroup<Color>.self, forKey: .color) self.width = try container.decode(KeyframeGroup<Vector1D>.self, forKey: .width) self.lineCap = try container.decodeIfPresent(LineCap.self, forKey: .lineCap) ?? .round self.lineJoin = try container.decodeIfPresent(LineJoin.self, forKey: .lineJoin) ?? .round self.miterLimit = try container.decodeIfPresent(Double.self, forKey: .miterLimit) ?? 4 self.dashPattern = try container.decodeIfPresent([DashElement].self, forKey: .dashPattern) try super.init(from: decoder) } override func encode(to encoder: Encoder) throws { try super.encode(to: encoder) var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(opacity, forKey: .opacity) try container.encode(color, forKey: .color) try container.encode(width, forKey: .width) try container.encode(lineCap, forKey: .lineCap) try container.encode(lineJoin, forKey: .lineJoin) try container.encode(miterLimit, forKey: .miterLimit) try container.encodeIfPresent(dashPattern, forKey: .dashPattern) } }
mit
cdf88fd6623ebd842474b16b76ba0627
31.029851
94
0.701305
4.003731
false
false
false
false
xmartlabs/Bender
Sources/Adapters/Tensorflow/TFDeleteOptimizers.swift
1
2098
// // TFDeleteSave.swift // Bender // // Created by Mathias Claassen on 5/22/17. // // /// Strips common nodes that are used in training but not in evaluating/testing public class TFStripTrainingOps: TFOptimizer { public var regexes: [Regex] = [TFDeleteSave().regex, TFDeleteRegularizer().regex, TFDeleteInitializer().regex] public func optimize(graph: TFGraph) { for node in graph.nodes { if regexes.first(where: { $0.test(node.nodeDef.name) }) != nil { node.strip() } } } } public class TFIgnoredOpsDeleter: TFOptimizer { let ops = ["NoOp", "ExpandDims", "Cast", "Squeeze", "StopGradient", "CheckNumerics", "Assert", "Equal", "All", "Dequantize", "RequantizationRange", "Requantize", "PlaceholderWithDefault", "Identity"] public func optimize(graph: TFGraph) { for node in graph.nodes { if ops.contains(node.nodeDef.op) { node.removeFromGraph() } } } } // swiftlint:disable force_try /// Deletes 'Save' subgraphs public class TFDeleteSave: TFDeleteSubgraphOptimizer { public var regex: Regex = try! Regex("save(_\\d+)?/") } /// Deletes 'Initializer' subgraphs public class TFDeleteInitializer: TFDeleteSubgraphOptimizer { public var regex: Regex = try! Regex("Initializer(_\\d+)?/") } /// Deletes 'Regularizer' subgraphs public class TFDeleteRegularizer: TFDeleteSubgraphOptimizer { public var regex: Regex = try! Regex("Regularizer(_\\d+)?/") } /// Deletes 'Dropout' subgraphs public class TFDeleteDropout: TFDeleteSubgraphOptimizer { public var regex: Regex = try! Regex("dropout(_\\d+)?/") public func isInputNode(_ node: TFNode) -> Bool { return node.nodeDef.isTFShapeOp } public func isOutputNode(_ node: TFNode) -> Bool { return node.nodeDef.name.isTFDropoutMulName } } fileprivate extension String { var isTFDropoutMulName: Bool { let regex = try! Regex("dropout(_\\d+)?/mul") return regex.test(self) } } // swiftlint:enable force_try
mit
e71725df018a43cd9e4edf6c5b589b27
23.114943
114
0.64347
3.629758
false
false
false
false
aschwaighofer/swift
test/SILGen/protocol_enum_witness.swift
1
2634
// RUN: %target-swift-emit-silgen %s | %FileCheck %s protocol Foo { static var button: Self { get } } enum Bar: Foo { case button } protocol AnotherFoo { static func bar(arg: Int) -> Self } enum AnotherBar: AnotherFoo { case bar(arg: Int) } // CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s21protocol_enum_witness3BarOAA3FooA2aDP6buttonxvgZTW : $@convention(witness_method: Foo) (@thick Bar.Type) -> @out Bar { // CHECK: bb0([[BAR:%.*]] : $*Bar, [[BAR_TYPE:%.*]] : $@thick Bar.Type): // CHECK-NEXT: [[META_TYPE:%.*]] = metatype $@thin Bar.Type // CHECK: [[REF:%.*]] = function_ref @$s21protocol_enum_witness3BarO6buttonyA2CmF : $@convention(method) (@thin Bar.Type) -> Bar // CHECK-NEXT: [[RESULT:%.*]] = apply [[REF]]([[META_TYPE]]) : $@convention(method) (@thin Bar.Type) -> Bar // CHECK-NEXT: store [[RESULT]] to [trivial] [[BAR]] : $*Bar // CHECK-NEXT: [[TUPLE:%.*]] = tuple () // CHECK-NEXT: return [[TUPLE]] : $() // CHECK-END: } // CHECK-LABEL: sil hidden [transparent] [ossa] @$s21protocol_enum_witness3BarO6buttonyA2CmF : $@convention(method) (@thin Bar.Type) -> Bar { // CHECK: bb0({{%.*}} : $@thin Bar.Type): // CHECK-NEXT: [[CASE:%.*]] = enum $Bar, #Bar.button!enumelt // CHECK-NEXT: return [[CASE]] : $Bar // CHECK-END: } // CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s21protocol_enum_witness10AnotherBarOAA0D3FooA2aDP3bar3argxSi_tFZTW : $@convention(witness_method: AnotherFoo) (Int, @thick AnotherBar.Type) -> @out AnotherBar { // CHECK: bb0([[ANOTHER_BAR:%.*]] : $*AnotherBar, [[INT_ARG:%.*]] : $Int, [[ANOTHER_BAR_TYPE:%.*]] : $@thick AnotherBar.Type): // CHECK-NEXT: [[META_TYPE:%.*]] = metatype $@thin AnotherBar.Type // CHECK: [[REF:%.*]] = function_ref @$s21protocol_enum_witness10AnotherBarO3baryACSi_tcACmF : $@convention(method) (Int, @thin AnotherBar.Type) -> AnotherBar // CHECK-NEXT: [[RESULT:%.*]] = apply [[REF]]([[INT_ARG]], [[META_TYPE]]) : $@convention(method) (Int, @thin AnotherBar.Type) -> AnotherBar // CHECK-NEXT: store [[RESULT]] to [trivial] [[ANOTHER_BAR]] : $*AnotherBar // CHECK-NEXT: [[TUPLE:%.*]] = tuple () // CHECK-NEXT: return [[TUPLE]] : $() // CHECK-END: } // CHECK-LABEL: sil_witness_table hidden Bar: Foo module protocol_enum_witness { // CHECK: method #Foo.button!getter: <Self where Self : Foo> (Self.Type) -> () -> Self : @$s21protocol_enum_witness3BarOAA3FooA2aDP6buttonxvgZTW // CHECK-LABEL: sil_witness_table hidden AnotherBar: AnotherFoo module protocol_enum_witness { // CHECK: method #AnotherFoo.bar: <Self where Self : AnotherFoo> (Self.Type) -> (Int) -> Self : @$s21protocol_enum_witness10AnotherBarOAA0D3FooA2aDP3bar3argxSi_tFZTW
apache-2.0
02063c51d2677d74479c26c344ab19b5
52.755102
220
0.660972
3.109799
false
false
false
false
ahoppen/swift
test/Interop/Cxx/stdlib/use-std-iterator.swift
1
1214
// RUN: %target-run-simple-swift(-I %S/Inputs -Xfrontend -enable-experimental-cxx-interop) // // REQUIRES: executable_test // // Enable this everywhere once we have a solution for modularizing libstdc++: rdar://87654514 // REQUIRES: OS=macosx import StdlibUnittest import StdVector import std.vector var StdIteratorTestSuite = TestSuite("StdIterator") StdIteratorTestSuite.test("init") { var vector = Vector() var _1: CInt = 1 //There seems to be an issue when importing this method, where the const_ref is mapped with //the correct typealias to be able to pass immutable values. related to: https://github.com/apple/swift/pull/41611 vector.push_back(&_1) //ideally we should call vector.begin(), however we need to prevent a copy of self before vector.begin() is invoked //current workaround is to use beginMutating() let it = vector.beginMutating() expectEqual(it[0], 1) } StdIteratorTestSuite.test("advance") { var vector = Vector() var _1: CInt = 1, _2: CInt = 2, _3: CInt = 3 vector.push_back(&_1) vector.push_back(&_2) vector.push_back(&_3) var it = vector.beginMutating() std.__1.advance(&it, 2) expectEqual(it[0], 3) } runAllTests()
apache-2.0
bc2b70763504aa208b46a81500e02ce3
31.837838
119
0.693575
3.602374
false
true
false
false
AnirudhDas/AniruddhaDas.github.io
CricketNews/CricketNews/Service/FetchNewsService.swift
1
2624
// // FetchNewsService.swift // CricketNews // // Created by Anirudh Das on 7/5/18. // Copyright © 2018 Aniruddha Das. All rights reserved. // import Foundation import SwiftyJSON /** CricbuzzServiceProtocol for Mocking Service */ protocol CricbuzzServiceProtocol { func fetchAllNews(completionBlock: @escaping (_ response: CricbuzzNewsResponse?) -> Void) func fetchDetailedNews(detailUrl: String, completionBlock: @escaping (_ response: CricbuzzStory?) -> Void) } /** Handles the API calls and parses the Response */ class CricbuzzService: CricbuzzServiceProtocol { var apiURL: String init(apiURL: String) { self.apiURL = apiURL } func fetchAllNews(completionBlock: @escaping (_ response: CricbuzzNewsResponse?) -> Void) { AlamofireConfig.shared.manager.request(apiURL) .validate(statusCode: 200..<300) .responseJSON { response in switch response.result { case .success: let json = JSON(data: response.data!) guard json != JSON.null, let detailedURL = json["detailed_URL"].string, let items = json["news"].array else { completionBlock(nil) return } var newsArray: [CricbuzzNews] = [] for item in items { if let news = CricbuzzNews(item) { newsArray.append(news) } } guard !newsArray.isEmpty else { completionBlock(nil) return } completionBlock(CricbuzzNewsResponse(detailedBaseUrl: detailedURL, newsArray: newsArray)) case .failure(_): completionBlock(nil) } } } func fetchDetailedNews(detailUrl: String, completionBlock: @escaping (_ response: CricbuzzStory?) -> Void) { AlamofireConfig.shared.manager.request(detailUrl) .validate(statusCode: 200..<300) .responseJSON { response in switch response.result { case .success: let json = JSON(data: response.data!) guard json != JSON.null, let story = CricbuzzStory(json) else { completionBlock(nil) return } completionBlock(story) case .failure(_): completionBlock(nil) } } } }
apache-2.0
e9fd920aa0760426279acbe0802cae82
33.973333
129
0.53069
5.123047
false
false
false
false
kstaring/swift
benchmark/single-source/TypeFlood.swift
7
3907
//===--- TypeFlood.swift --------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // We use this test to benchmark the runtime memory that Swift programs use. // // The Swift compiler caches the metadata that it needs to generate to support // code that checks for protocol conformance and other operations that require // use of metadata. // This mechanism has the potential to allocate a lot of memory. This benchmark // program generates 2^15 calls to swift_conformsToProtocol and fills the // metadata/conformance caches with data that we never free. We use this // program to track the runtime memory usage of swift programs. The test is // optimized away in Release builds but kept in Debug mode. import TestsUtils protocol Pingable {} struct Some1<T> { init() {} func foo(_ x: T) {} } struct Some0<T> { init() {} func foo(_ x: T) {} } @inline(never) func flood<T>(_ x: T) { _ = Some1<Some1<Some1<Some1<T>>>>() is Pingable _ = Some1<Some1<Some1<Some0<T>>>>() is Pingable _ = Some1<Some1<Some0<Some1<T>>>>() is Pingable _ = Some1<Some1<Some0<Some0<T>>>>() is Pingable _ = Some1<Some0<Some1<Some1<T>>>>() is Pingable _ = Some1<Some0<Some1<Some0<T>>>>() is Pingable _ = Some1<Some0<Some0<Some1<T>>>>() is Pingable _ = Some1<Some0<Some0<Some0<T>>>>() is Pingable _ = Some0<Some1<Some1<Some1<T>>>>() is Pingable _ = Some0<Some1<Some1<Some0<T>>>>() is Pingable _ = Some0<Some1<Some0<Some1<T>>>>() is Pingable _ = Some0<Some1<Some0<Some0<T>>>>() is Pingable _ = Some0<Some0<Some1<Some1<T>>>>() is Pingable _ = Some0<Some0<Some1<Some0<T>>>>() is Pingable _ = Some0<Some0<Some0<Some1<T>>>>() is Pingable _ = Some0<Some0<Some0<Some0<T>>>>() is Pingable } @inline(never) func flood3<T>(_ x: T) { flood(Some1<Some1<Some1<Some1<T>>>>()) flood(Some1<Some1<Some1<Some0<T>>>>()) flood(Some1<Some1<Some0<Some1<T>>>>()) flood(Some1<Some1<Some0<Some0<T>>>>()) flood(Some1<Some0<Some1<Some1<T>>>>()) flood(Some1<Some0<Some1<Some0<T>>>>()) flood(Some1<Some0<Some0<Some1<T>>>>()) flood(Some1<Some0<Some0<Some0<T>>>>()) flood(Some0<Some1<Some1<Some1<T>>>>()) flood(Some0<Some1<Some1<Some0<T>>>>()) flood(Some0<Some1<Some0<Some1<T>>>>()) flood(Some0<Some1<Some0<Some0<T>>>>()) flood(Some0<Some0<Some1<Some1<T>>>>()) flood(Some0<Some0<Some1<Some0<T>>>>()) flood(Some0<Some0<Some0<Some1<T>>>>()) flood(Some0<Some0<Some0<Some0<T>>>>()) } @inline(never) func flood2<T>(_ x: T) { flood3(Some1<Some1<Some1<Some1<T>>>>()) flood3(Some1<Some1<Some1<Some0<T>>>>()) flood3(Some1<Some1<Some0<Some1<T>>>>()) flood3(Some1<Some1<Some0<Some0<T>>>>()) flood3(Some1<Some0<Some1<Some1<T>>>>()) flood3(Some1<Some0<Some1<Some0<T>>>>()) flood3(Some1<Some0<Some0<Some1<T>>>>()) flood3(Some1<Some0<Some0<Some0<T>>>>()) flood3(Some0<Some1<Some1<Some1<T>>>>()) flood3(Some0<Some1<Some1<Some0<T>>>>()) flood3(Some0<Some1<Some0<Some1<T>>>>()) flood3(Some0<Some1<Some0<Some0<T>>>>()) flood3(Some0<Some0<Some1<Some1<T>>>>()) flood3(Some0<Some0<Some1<Some0<T>>>>()) flood3(Some0<Some0<Some0<Some1<T>>>>()) flood3(Some0<Some0<Some0<Some0<T>>>>()) } @inline(never) public func run_TypeFlood(_ N: Int) { for _ in 1...N { flood3(Some1<Some1<Some1<Int>>>()) flood3(Some1<Some1<Some0<Int>>>()) flood3(Some1<Some0<Some1<Int>>>()) flood3(Some1<Some0<Some0<Int>>>()) flood3(Some0<Some1<Some1<Int>>>()) flood3(Some0<Some1<Some0<Int>>>()) flood3(Some0<Some0<Some1<Int>>>()) flood3(Some0<Some0<Some0<Int>>>()) } }
apache-2.0
4bc08f1a0a0c5fa1b8afbd918bd817c5
34.518182
80
0.639109
2.874908
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/AppAppearanceViewController.swift
1
34045
// // AppAppearanceViewController.swift // Telegram // // Created by Mikhail Filimonov on 14/09/2019. // Copyright © 2019 Telegram. All rights reserved. // import Cocoa import TelegramCore import ThemeSettings import ColorPalette import SwiftSignalKit import Postbox import TGUIKit import InAppSettings private extension TelegramBuiltinTheme { var baseTheme: TelegramBaseTheme { switch self { case .dark: return .night case .nightAccent: return .tinted case .day: return .day case .dayClassic: return .classic default: if !palette.isDark { return .classic } else { return .tinted } } } } struct SmartThemeCachedData : Equatable { enum Source : Equatable { case local(ColorPalette) case cloud(TelegramTheme) } struct Data : Equatable { let appTheme: TelegramPresentationTheme let previewIcon: CGImage let emoticon: String } let source: Source let data: Data } struct CloudThemesCachedData { struct Key : Hashable { let base: TelegramBaseTheme let bubbled: Bool var colors: ColorPalette { return base.palette } static var all: [Key] { return [.init(base: .classic, bubbled: true), .init(base: .day, bubbled: true), .init(base: .night, bubbled: true), .init(base: .classic, bubbled: false), .init(base: .day, bubbled: false), .init(base: .night, bubbled: false)] } } let themes: [TelegramTheme] let list: [Key : [SmartThemeCachedData]] let `default`: SmartThemeCachedData? let custom: SmartThemeCachedData? } struct AppearanceAccentColor : Equatable { let accent: PaletteAccentColor let cloudTheme: TelegramTheme? let cachedTheme: InstallCloudThemeCachedData? init(accent: PaletteAccentColor, cloudTheme: TelegramTheme?, cachedTheme: InstallCloudThemeCachedData? = nil) { self.accent = accent self.cloudTheme = cloudTheme self.cachedTheme = cachedTheme } func withUpdatedCachedTheme(_ cachedTheme: InstallCloudThemeCachedData?) -> AppearanceAccentColor { return .init(accent: self.accent, cloudTheme: self.cloudTheme, cachedTheme: cachedTheme) } } enum ThemeSettingsEntryTag: ItemListItemTag { case fontSize case theme case autoNight case chatMode case accentColor func isEqual(to other: ItemListItemTag) -> Bool { if let other = other as? ThemeSettingsEntryTag, self == other { return true } else { return false } } var stableId: InputDataEntryId { switch self { case .fontSize: return .custom(_id_theme_text_size) case .theme: return .custom(_id_theme_list) case .autoNight: return .general(_id_theme_auto_night) case .chatMode: return .general(_id_theme_chat_mode) case .accentColor: return .custom(_id_theme_accent_list) } } } struct InstallCloudThemeCachedData : Equatable { let palette: ColorPalette let wallpaper: Wallpaper let cloudWallpaper: TelegramWallpaper? } enum InstallThemeSource : Equatable { case local(ColorPalette) case cloud(TelegramTheme, InstallCloudThemeCachedData?) } private final class AppAppearanceViewArguments { let context: AccountContext let togglePalette:(InstallThemeSource)->Void let toggleBubbles:(Bool)->Void let toggleFontSize:(CGFloat)->Void let selectAccentColor:(AppearanceAccentColor?)->Void let selectChatBackground:()->Void let openAutoNightSettings:()->Void let removeTheme:(TelegramTheme)->Void let editTheme:(TelegramTheme)->Void let shareTheme:(TelegramTheme)->Void let shareLocal:(ColorPalette)->Void let toggleDarkMode:(Bool)->Void let toggleRevealThemes:()->Void init(context: AccountContext, togglePalette: @escaping(InstallThemeSource)->Void, toggleBubbles: @escaping(Bool)->Void, toggleFontSize: @escaping(CGFloat)->Void, selectAccentColor: @escaping(AppearanceAccentColor?)->Void, selectChatBackground:@escaping()->Void, openAutoNightSettings:@escaping()->Void, removeTheme:@escaping(TelegramTheme)->Void, editTheme: @escaping(TelegramTheme)->Void, shareTheme:@escaping(TelegramTheme)->Void, shareLocal:@escaping(ColorPalette)->Void, toggleDarkMode: @escaping(Bool)->Void, toggleRevealThemes:@escaping()->Void) { self.context = context self.togglePalette = togglePalette self.toggleBubbles = toggleBubbles self.toggleFontSize = toggleFontSize self.selectAccentColor = selectAccentColor self.selectChatBackground = selectChatBackground self.openAutoNightSettings = openAutoNightSettings self.removeTheme = removeTheme self.editTheme = editTheme self.shareTheme = shareTheme self.shareLocal = shareLocal self.toggleDarkMode = toggleDarkMode self.toggleRevealThemes = toggleRevealThemes } } private let _id_theme_preview = InputDataIdentifier("_id_theme_preview") private let _id_theme_list = InputDataIdentifier("_id_theme_list") private let _id_theme_accent_list = InputDataIdentifier("_id_theme_accent_list") private let _id_theme_chat_mode = InputDataIdentifier("_id_theme_chat_mode") private let _id_theme_wallpaper1 = InputDataIdentifier("_id_theme_wallpaper") private let _id_theme_wallpaper2 = InputDataIdentifier("_id_theme_wallpaper") private let _id_theme_text_size = InputDataIdentifier("_id_theme_text_size") private let _id_theme_auto_night = InputDataIdentifier("_id_theme_auto_night") private let _id_theme_night_mode = InputDataIdentifier("_id_theme_night_mode") private let _id_cloud_themes = InputDataIdentifier("_id_cloud_themes") private func appAppearanceEntries(appearance: Appearance, state: State, settings: ThemePaletteSettings, cloudThemes: [TelegramTheme], generated: CloudThemesCachedData, autoNightSettings: AutoNightThemePreferences, animatedEmojiStickers: [String: StickerPackItem], arguments: AppAppearanceViewArguments) -> [InputDataEntry] { var entries:[InputDataEntry] = [] var sectionId: Int32 = 0 var index:Int32 = 0 entries.append(.sectionId(sectionId, type: .normal)) sectionId += 1 entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().appearanceSettingsColorThemeHeader), data: .init(viewType: .textTopItem))) index += 1 entries.append(InputDataEntry.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_theme_preview, equatable: InputDataEquatable(appearance), comparable: nil, item: { initialSize, stableId in return ThemePreviewRowItem(initialSize, stableId: stableId, context: arguments.context, theme: appearance.presentation, viewType: .firstItem) })) var accentList = appearance.presentation.cloudTheme == nil || appearance.presentation.cloudTheme?.settings != nil ? appearance.presentation.colors.accentList.map { AppearanceAccentColor(accent: $0, cloudTheme: nil) } : [] var cloudThemes = cloudThemes if let cloud = appearance.presentation.cloudTheme { if !cloudThemes.contains(where: {$0.id == cloud.id}) { cloudThemes.append(cloud) } } // var smartThemesList:[SmartThemeCachedData] = [] // var values:[SmartThemeCachedData] = generated.list[.init(base: appearance.presentation.colors.parent.baseTheme, bubbled: appearance.presentation.bubbled)] ?? [] // if let value = generated.default { // smartThemesList.append(value) // } // if values.isEmpty { // values = generated.list[.init(base: appearance.presentation.dark ? .night : .classic, bubbled: appearance.presentation.bubbled)] ?? [] // } // for smartTheme in values { // smartThemesList.append(smartTheme) // } // if let custom = generated.custom { // smartThemesList.append(custom) // } if appearance.presentation.cloudTheme == nil || appearance.presentation.cloudTheme?.settings != nil { let copy = cloudThemes var cloudAccents:[AppearanceAccentColor] = [] for cloudTheme in copy { if let settings = cloudTheme.effectiveSettings(for: appearance.presentation.colors) { cloudAccents.append(AppearanceAccentColor(accent: settings.accent, cloudTheme: cloudTheme)) } } accentList.insert(contentsOf: cloudAccents, at: 0) } cloudThemes.removeAll(where:{ $0.settings != nil }) struct ListEquatable : Equatable { let theme: TelegramPresentationTheme let cloudThemes:[TelegramTheme] } entries.append(InputDataEntry.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_theme_list, equatable: InputDataEquatable(ListEquatable(theme: appearance.presentation, cloudThemes: cloudThemes)), comparable: nil, item: { initialSize, stableId in let selected: ThemeSource if let cloud = appearance.presentation.cloudTheme { if let _ = cloud.settings { selected = .local(appearance.presentation.colors, cloud) } else { selected = .cloud(cloud) } } else { selected = .local(appearance.presentation.colors, nil) } let dayClassicCloud = settings.associated.first(where: { $0.local == dayClassicPalette.parent })?.cloud?.cloud let dayCloud = settings.associated.first(where: { $0.local == whitePalette.parent })?.cloud?.cloud let nightAccentCloud = settings.associated.first(where: { $0.local == nightAccentPalette.parent })?.cloud?.cloud var locals: [LocalPaletteWithReference] = [LocalPaletteWithReference(palette: dayClassicPalette, cloud: dayClassicCloud), LocalPaletteWithReference(palette: whitePalette, cloud: dayCloud), LocalPaletteWithReference(palette: nightAccentPalette, cloud: nightAccentCloud), LocalPaletteWithReference(palette: systemPalette, cloud: nil)] for (i, local) in locals.enumerated() { if let accent = settings.accents.first(where: { $0.name == local.palette.parent }), accent.color.accent != local.palette.basicAccent { locals[i] = local.withAccentColor(accent.color) } } return ThemeListRowItem(initialSize, stableId: stableId, context: arguments.context, theme: appearance.presentation, selected: selected, local: locals, cloudThemes: cloudThemes, viewType: accentList.isEmpty ? .lastItem : .innerItem, togglePalette: arguments.togglePalette, menuItems: { source in var items:[ContextMenuItem] = [] var cloud: TelegramTheme? switch source { case let .cloud(c): cloud = c case let .local(_, c): cloud = c } if let cloud = cloud { if cloud.isCreator { items.append(ContextMenuItem(strings().appearanceThemeEdit, handler: { arguments.editTheme(cloud) }, itemImage: MenuAnimation.menu_edit.value)) } items.append(ContextMenuItem(strings().appearanceThemeShare, handler: { arguments.shareTheme(cloud) }, itemImage: MenuAnimation.menu_share.value)) items.append(ContextSeparatorItem()) items.append(ContextMenuItem(strings().appearanceThemeRemove, handler: { arguments.removeTheme(cloud) }, itemMode: .destruct, itemImage: MenuAnimation.menu_delete.value)) } return items }) })) if !accentList.isEmpty { struct ALEquatable : Equatable { let accentList: [AppearanceAccentColor] let theme: TelegramPresentationTheme } entries.append(InputDataEntry.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_theme_accent_list, equatable: InputDataEquatable(ALEquatable(accentList: accentList, theme: appearance.presentation)), comparable: nil, item: { initialSize, stableId in // return SmartThemeListRowItem(initialSize, stableId: stableId, context: arguments.context, theme: appearance.presentation, list: smartThemesList, animatedEmojiStickers: animatedEmojiStickers, viewType: .innerItem, togglePalette: arguments.togglePalette) return AccentColorRowItem(initialSize, stableId: stableId, context: arguments.context, list: accentList, isNative: true, theme: appearance.presentation, viewType: .lastItem, selectAccentColor: arguments.selectAccentColor, menuItems: { accent in var items:[ContextMenuItem] = [] if let cloud = accent.cloudTheme { items.append(ContextMenuItem(strings().appearanceThemeShare, handler: { arguments.shareTheme(cloud) }, itemImage: MenuAnimation.menu_share.value)) items.append(ContextSeparatorItem()) items.append(ContextMenuItem(strings().appearanceThemeRemove, handler: { arguments.removeTheme(cloud) }, itemMode: .destruct, itemImage: MenuAnimation.menu_delete.value)) } return items }) })) index += 1 // if state.revealed { // // } // entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: _id_cloud_themes, data: .init(name: !state.revealed ? strings().appearanceSettingsShowMore : strings().appearanceSettingsShowLess, color: appearance.presentation.colors.accent, type: .none, viewType: .lastItem, action: arguments.toggleRevealThemes))) // index += 1 } entries.append(.sectionId(sectionId, type: .normal)) sectionId += 1 entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: _id_theme_night_mode, data: InputDataGeneralData(name: strings().appearanceSettingsDarkMode, color: appearance.presentation.colors.text, type: .switchable(appearance.presentation.dark), viewType: .firstItem, action: { arguments.toggleDarkMode(!appearance.presentation.dark) }))) index += 1 entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: _id_theme_chat_mode, data: InputDataGeneralData(name: strings().appearanceSettingsBubblesMode, color: appearance.presentation.colors.text, type: .switchable(appearance.presentation.bubbled), viewType: appearance.presentation.bubbled ? .innerItem : .lastItem, action: { arguments.toggleBubbles(!appearance.presentation.bubbled) }))) index += 1 if appearance.presentation.bubbled { entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: _id_theme_wallpaper1, data: InputDataGeneralData(name: strings().generalSettingsChatBackground, color: appearance.presentation.colors.text, type: .next, viewType: .lastItem, action: arguments.selectChatBackground))) index += 1 } entries.append(.sectionId(sectionId, type: .normal)) sectionId += 1 entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().appearanceSettingsTextSizeHeader), data: .init(viewType: .textTopItem))) index += 1 entries.append(InputDataEntry.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_theme_text_size, equatable: InputDataEquatable(appearance), comparable: nil, item: { initialSize, stableId in let sizes:[Int32] = [11, 12, 13, 14, 15, 16, 17, 18] return SelectSizeRowItem(initialSize, stableId: stableId, current: Int32(appearance.presentation.fontSize), sizes: sizes, hasMarkers: true, viewType: .singleItem, selectAction: { index in arguments.toggleFontSize(CGFloat(sizes[index])) }) })) index += 1 entries.append(.sectionId(sectionId, type: .normal)) sectionId += 1 entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().appearanceSettingsAutoNightHeader), data: .init(viewType: .textTopItem))) index += 1 let autoNightText: String if autoNightSettings.systemBased { autoNightText = strings().autoNightSettingsSystemBased } else if let _ = autoNightSettings.schedule { autoNightText = strings().autoNightSettingsScheduled } else { autoNightText = strings().autoNightSettingsDisabled } sectionId += 1 entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: _id_theme_auto_night, data: InputDataGeneralData(name: strings().appearanceSettingsAutoNight, color: appearance.presentation.colors.text, type: .nextContext(autoNightText), viewType: .singleItem, action: arguments.openAutoNightSettings))) index += 1 entries.append(.sectionId(sectionId, type: .normal)) sectionId += 1 return entries } private struct State : Equatable { var revealed: Bool } func AppAppearanceViewController(context: AccountContext, focusOnItemTag: ThemeSettingsEntryTag? = nil) -> InputDataController { let applyCloudThemeDisposable = MetaDisposable() let updateDisposable = MetaDisposable() let initialState = State(revealed: false) let statePromise = ValuePromise(initialState, ignoreRepeated: true) let stateValue = Atomic(value: initialState) let updateState: ((State) -> State) -> Void = { f in statePromise.set(stateValue.modify (f)) } let applyTheme:(InstallThemeSource)->Void = { source in switch source { case let .local(palette): updateDisposable.set(updateThemeInteractivetly(accountManager: context.sharedContext.accountManager, f: { settings in var settings = settings settings = settings.withUpdatedPalette(palette).withUpdatedCloudTheme(nil) let defaultTheme = DefaultTheme(local: palette.parent, cloud: nil) if palette.isDark { settings = settings.withUpdatedDefaultDark(defaultTheme) } else { settings = settings.withUpdatedDefaultDay(defaultTheme) } return settings.installDefaultWallpaper().installDefaultAccent().withUpdatedDefaultIsDark(palette.isDark).withSavedAssociatedTheme() }).start()) case let .cloud(cloud, cached): if let cached = cached { updateDisposable.set(updateThemeInteractivetly(accountManager: context.sharedContext.accountManager, f: { settings in var settings = settings settings = settings.withUpdatedPalette(cached.palette) settings = settings.withUpdatedCloudTheme(cloud) settings = settings.updateWallpaper { _ in return ThemeWallpaper(wallpaper: cached.wallpaper, associated: AssociatedWallpaper(cloud: cached.cloudWallpaper, wallpaper: cached.wallpaper)) } let defaultTheme = DefaultTheme(local: cached.palette.parent, cloud: DefaultCloudTheme(cloud: cloud, palette: cached.palette, wallpaper: AssociatedWallpaper(cloud: cached.cloudWallpaper, wallpaper: cached.wallpaper))) if cached.palette.isDark { settings = settings.withUpdatedDefaultDark(defaultTheme) } else { settings = settings.withUpdatedDefaultDay(defaultTheme) } return settings .saveDefaultWallpaper() .withUpdatedDefaultIsDark(cached.palette.isDark) .withSavedAssociatedTheme() }).start(completed: { applyCloudThemeDisposable.set(downloadAndApplyCloudTheme(context: context, theme: cloud, palette: cached.palette, install: true).start()) })) } else if cloud.file != nil { applyCloudThemeDisposable.set(showModalProgress(signal: downloadAndApplyCloudTheme(context: context, theme: cloud, install: true), for: context.window).start()) } else { showEditThemeModalController(context: context, theme: cloud) } } } let arguments = AppAppearanceViewArguments(context: context, togglePalette: { source in let nightSettings = autoNightSettings(accountManager: context.sharedContext.accountManager) |> take(1) |> deliverOnMainQueue _ = nightSettings.start(next: { settings in if settings.systemBased || settings.schedule != nil { confirm(for: context.window, header: strings().darkModeConfirmNightModeHeader, information: strings().darkModeConfirmNightModeText, okTitle: strings().darkModeConfirmNightModeOK, successHandler: { _ in let disableNightMode = context.sharedContext.accountManager.transaction { transaction -> Void in transaction.updateSharedData(ApplicationSharedPreferencesKeys.autoNight, { entry in let settings: AutoNightThemePreferences = entry?.get(AutoNightThemePreferences.self) ?? AutoNightThemePreferences.defaultSettings return PreferencesEntry(settings.withUpdatedSystemBased(false).withUpdatedSchedule(nil)) }) } |> deliverOnMainQueue _ = disableNightMode.start(next: { applyTheme(source) }) }) } else { applyTheme(source) } }) }, toggleBubbles: { value in updateDisposable.set(updateThemeInteractivetly(accountManager: context.sharedContext.accountManager, f: { settings in return settings.withUpdatedBubbled(value) }).start()) }, toggleFontSize: { value in updateDisposable.set(updateThemeInteractivetly(accountManager: context.sharedContext.accountManager, f: { settings in return settings.withUpdatedFontSize(value) }).start()) }, selectAccentColor: { value in let updateColor:(AppearanceAccentColor)->Void = { color in if let cloudTheme = color.cloudTheme { applyTheme(.cloud(cloudTheme, color.cachedTheme)) } else { updateDisposable.set(updateThemeInteractivetly(accountManager: context.sharedContext.accountManager, f: { settings in let clearPalette = settings.palette.withoutAccentColor() var settings = settings if color.accent.accent == settings.palette.basicAccent { settings = settings.withUpdatedPalette(clearPalette) } else { settings = settings.withUpdatedPalette(clearPalette.withAccentColor(color.accent)) } let defaultTheme = DefaultTheme(local: settings.palette.parent, cloud: nil) if settings.palette.isDark { settings = settings.withUpdatedDefaultDark(defaultTheme) } else { settings = settings.withUpdatedDefaultDay(defaultTheme) } return settings.withUpdatedCloudTheme(nil).saveDefaultAccent(color: color.accent).installDefaultWallpaper().withSavedAssociatedTheme() }).start()) } } if let color = value { updateColor(color) } else { showModal(with: CustomAccentColorModalController(context: context, updateColor: { accent in updateColor(AppearanceAccentColor(accent: accent, cloudTheme: nil)) }), for: context.window) } }, selectChatBackground: { showModal(with: ChatWallpaperModalController(context), for: context.window) }, openAutoNightSettings: { context.bindings.rootNavigation().push(AutoNightSettingsController(context: context)) }, removeTheme: { cloudTheme in confirm(for: context.window, header: strings().appearanceConfirmRemoveTitle, information: strings().appearanceConfirmRemoveText, okTitle: strings().appearanceConfirmRemoveOK, successHandler: { _ in var signals:[Signal<Void, NoError>] = [] if theme.cloudTheme?.id == cloudTheme.id { signals.append(updateThemeInteractivetly(accountManager: context.sharedContext.accountManager, f: { settings in var settings = settings.withUpdatedCloudTheme(nil) .withUpdatedToDefault(dark: settings.defaultIsDark, onlyLocal: true) let defaultTheme = DefaultTheme(local: settings.palette.parent, cloud: nil) if settings.defaultIsDark { settings = settings.withUpdatedDefaultDark(defaultTheme) } else { settings = settings.withUpdatedDefaultDay(defaultTheme) } return settings.withSavedAssociatedTheme() })) } signals.append(deleteThemeInteractively(account: context.account, accountManager: context.sharedContext.accountManager, theme: cloudTheme)) updateDisposable.set(combineLatest(signals).start()) }) }, editTheme: { value in showEditThemeModalController(context: context, theme: value) }, shareTheme: { value in showModal(with: ShareModalController(ShareLinkObject(context, link: "https://t.me/addtheme/\(value.slug)")), for: context.window) }, shareLocal: { palette in }, toggleDarkMode: { _ in toggleDarkMode(context: context) }, toggleRevealThemes: { updateState { current in var current = current current.revealed = !current.revealed return current } }) let nightSettings = autoNightSettings(accountManager: context.sharedContext.accountManager) let animatedEmojiStickers = context.engine.stickers.loadedStickerPack(reference: .animatedEmoji, forceActualized: false) |> map { result -> [String: StickerPackItem] in switch result { case let .result(_, items, _): var animatedEmojiStickers: [String: StickerPackItem] = [:] for case let item in items { if let emoji = item.getStringRepresentationsOfIndexKeys().first { animatedEmojiStickers[emoji] = item } } return animatedEmojiStickers default: return [:] } } |> deliverOnMainQueue let signal:Signal<InputDataSignalValue, NoError> = combineLatest(queue: prepareQueue, themeUnmodifiedSettings(accountManager: context.sharedContext.accountManager), context.cloudThemes, nightSettings, appearanceSignal, animatedEmojiStickers, statePromise.get()) |> map { themeSettings, themes, autoNightSettings, appearance, animatedEmojiStickers, state in return appAppearanceEntries(appearance: appearance, state: state, settings: themeSettings, cloudThemes: themes.themes.reversed(), generated: themes, autoNightSettings: autoNightSettings, animatedEmojiStickers: animatedEmojiStickers, arguments: arguments) } |> map { entries in return InputDataSignalValue(entries: entries, animated: true) } |> deliverOnMainQueue let controller = InputDataController(dataSignal: signal, title: strings().telegramAppearanceViewController, removeAfterDisappear:false, identifier: "app_appearance", customRightButton: { controller in let view = ImageBarView(controller: controller, theme.icons.chatActions) view.button.contextMenu = { var items:[ContextMenuItem] = [] if theme.colors.parent != .system { items.append(ContextMenuItem(strings().appearanceNewTheme, handler: { showModal(with: NewThemeController(context: context, palette: theme.colors.withUpdatedWallpaper(theme.wallpaper.paletteWallpaper)), for: context.window) }, itemImage: MenuAnimation.menu_change_colors.value)) items.append(ContextMenuItem(strings().appearanceExportTheme, handler: { exportPalette(palette: theme.colors.withUpdatedName(theme.cloudTheme?.title ?? theme.colors.name).withUpdatedWallpaper(theme.wallpaper.paletteWallpaper)) }, itemImage: MenuAnimation.menu_save_as.value)) if let cloudTheme = theme.cloudTheme { items.append(ContextMenuItem(strings().appearanceThemeShare, handler: { showModal(with: ShareModalController(ShareLinkObject(context, link: "https://t.me/addtheme/\(cloudTheme.slug)")), for: context.window) }, itemImage: MenuAnimation.menu_share.value)) } if theme.cloudTheme != nil || theme.colors.accent != theme.colors.basicAccent { items.append(ContextMenuItem(strings().appearanceReset, handler: { _ = updateThemeInteractivetly(accountManager: context.sharedContext.accountManager, f: { settings in var settings = settings if settings.defaultIsDark { settings = settings.withUpdatedDefaultDark(DefaultTheme(local: TelegramBuiltinTheme.nightAccent, cloud: nil)).saveDefaultAccent(color: PaletteAccentColor(nightAccentPalette.accent)) } else { settings = settings.withUpdatedDefaultDay(DefaultTheme(local: TelegramBuiltinTheme.dayClassic, cloud: nil)).saveDefaultAccent(color: PaletteAccentColor(dayClassicPalette.accent)) } return settings.installDefaultAccent().withUpdatedCloudTheme(nil).updateWallpaper({ _ -> ThemeWallpaper in return ThemeWallpaper(wallpaper: settings.palette.wallpaper.wallpaper, associated: nil) }).installDefaultWallpaper() }).start() }, itemImage: MenuAnimation.menu_reset.value)) } let menu = ContextMenu() for item in items { menu.addItem(item) } return menu } return nil } view.button.set(image: theme.icons.chatActions, for: .Normal) view.button.set(image: theme.icons.chatActionsActive, for: .Highlight) return view }) controller.updateRightBarView = { view in if let view = view as? ImageBarView { view.button.set(image: theme.icons.chatActions, for: .Normal) view.button.set(image: theme.icons.chatActionsActive, for: .Highlight) } } controller.didLoaded = { controller, _ in if let focusOnItemTag = focusOnItemTag { controller.genericView.tableView.scroll(to: .center(id: focusOnItemTag.stableId, innerId: nil, animated: true, focus: .init(focus: true), inset: 0), inset: NSEdgeInsets()) } controller.genericView.tableView.needUpdateVisibleAfterScroll = true } return controller } func toggleDarkMode(context: AccountContext) { let nightSettings = autoNightSettings(accountManager: context.sharedContext.accountManager) |> take(1) |> deliverOnMainQueue _ = nightSettings.start(next: { settings in if settings.systemBased || settings.schedule != nil { confirm(for: context.window, header: strings().darkModeConfirmNightModeHeader, information: strings().darkModeConfirmNightModeText, okTitle: strings().darkModeConfirmNightModeOK, successHandler: { _ in _ = context.sharedContext.accountManager.transaction { transaction -> Void in transaction.updateSharedData(ApplicationSharedPreferencesKeys.autoNight, { entry in let settings: AutoNightThemePreferences = entry?.get(AutoNightThemePreferences.self) ?? AutoNightThemePreferences.defaultSettings return PreferencesEntry(settings.withUpdatedSystemBased(false).withUpdatedSchedule(nil)) }) transaction.updateSharedData(ApplicationSharedPreferencesKeys.themeSettings, { entry in let settings = entry?.get(ThemePaletteSettings.self) ?? ThemePaletteSettings.defaultTheme return PreferencesEntry(settings.withUpdatedToDefault(dark: !theme.colors.isDark).withUpdatedDefaultIsDark(!theme.colors.isDark)) }) }.start() }) } else { _ = updateThemeInteractivetly(accountManager: context.sharedContext.accountManager, f: { settings -> ThemePaletteSettings in return settings.withUpdatedToDefault(dark: !theme.colors.isDark).withUpdatedDefaultIsDark(!theme.colors.isDark) }).start() } }) }
gpl-2.0
c4b0fea0592ccdf662c122610557d99e
47.773639
557
0.644901
4.986671
false
false
false
false
noppoMan/Prorsum
Sources/Prorsum/HTTP/Serializer/ResponseSerializer.swift
1
2166
// // ResponseSerializer.swift // Prorsum // // Created by Yuki Takei on 2016/11/28. // // public struct ResponseSerializer { let stream: DuplexStream let bufferSize: Int public init(stream: DuplexStream, bufferSize: Int = 2048) { self.stream = stream self.bufferSize = bufferSize } public func serialize(_ response: Response, deadline: Double) throws { var header = "HTTP/" header += response.version.major.description header += "." header += response.version.minor.description header += " " header += response.status.statusCode.description header += " " header += response.reasonPhrase header += "\r\n" for (name, value) in response.headers.headers { header += name.string header += ": " header += value header += "\r\n" } for cookie in response.cookieHeaders { header += "Set-Cookie: " header += cookie header += "\r\n" } header += "\r\n" try stream.write(header.bytes, deadline: deadline) switch response.body { case .buffer(let buffer): try stream.write(buffer.bytes, deadline: deadline) case .reader(let reader): while !reader.isClosed { let bytes = try reader.read(upTo: bufferSize, deadline: deadline) guard !bytes.isEmpty else { break } try stream.write(String(bytes.count, radix: 16).bytes, deadline: deadline) try stream.write("\r\n".bytes, deadline: deadline) try stream.write(bytes, deadline: deadline) try stream.write("\r\n".bytes, deadline: deadline) } try stream.write("0\r\n\r\n".bytes, deadline: deadline) case .writer(let writer): let body = BodyStream(stream) try writer(body) try stream.write("0\r\n\r\n".bytes, deadline: deadline) } } }
mit
2a392760de8062cb7425d20d9b6b7ae7
29.942857
90
0.523084
4.618337
false
false
false
false
aktowns/swen
Sources/Swen/Util/Vector.swift
1
4474
// // Vector.swift created on 28/12/15 // Swen project // // Copyright 2015 Ashley Towns <[email protected]> // // 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. // public struct Vector: Comparable { /// The x coordinate of this Vector. public var x: Double /// The y coordinate of this Vector2. public var y: Double public init(x: Double, y: Double) { self.x = x self.y = y } public static func fromInt16(x x: Int16, y: Int16) -> Vector { return Vector(x: Double(x), y: Double(y)) } public static func fromInt32(x x: Int32, y: Int32) -> Vector { return Vector(x: Double(x), y: Double(y)) } public static var zero: Vector { return Vector(x: 0.0, y: 0.0) } /// Negates the vector. public var negated: Vector { return Vector(x: -self.x, y: -self.y) } /// Returns a perpendicular vector. (90 degree rotation) public var perp: Vector { return Vector(x: -self.y, y: self.x) } /// Returns a perpendicular vector. (-90 degree rotation) public var rperp: Vector { return Vector(x: self.y, y: -self.x) } /// Scalar multiplication. public func mult(s: Double) -> Vector { return Vector(x: self.x * s, y: self.y * s) } /// Vector dot product. public func dot(v2: Vector) -> Double { return (self.x * v2.x) + (self.y * v2.y) } /// 2D vector cross product analog. /// The cross product of 2D vectors results in a 3D vector with only a z component. /// This function returns the magnitude of the z value. public func cross(v2: Vector) -> Double { return (self.x * v2.y) - (self.y * v2.x) } /// Returns the vector projection of the vector onto v2. public func project(v2: Vector) -> Vector { return v2.mult(self.dot(v2) / v2.dot(v2)) } /// Returns the unit length vector for the given angle (in radians). public static func forAngle(a: Double) -> Vector { return Vector(x: Math.cos(a), y: Math.sin(a)) } /// Returns the angular direction the vector is pointing in (in radians). public var angle: Double { return Math.atan2(self.y, self.x) } /// Uses complex number multiplication to rotate the vector by v2. Scaling will occur /// if the vector is not a unit vector. public func rotate(v2: Vector) -> Vector { return Vector(x: self.x * v2.x - self.y * v2.y, y: self.x * v2.y + self.y * v2.x) } /// Inverse of rotate(). public func unrotate(v2: Vector) -> Vector { return Vector(x: self.x * v2.x + self.y * v2.y, y: self.y * v2.x - self.x * v2.y) } /// Returns the squared length of the vector. Faster than length() when you only need to compare lengths. public var lengthsq: Double { return self.dot(self) } /// Returns the length of the vector. public var length: Double { return Math.sqrt(self.dot(self)) } /// Linearly interpolate between the vector and v2. public func lerp(v2: Vector, t: Double) -> Vector { return self.mult(1.0 - t) + v2.mult(t) } /// Returns a normalized copy of the vector. public var normalize: Vector { return self.mult(1.0 / (self.length + Math.DBL_MIN)) } /// Returns the distance between the vector and v2. public func dist(v2: Vector) -> Double { return (self - v2).length } } public func ==(l: Vector, r: Vector) -> Bool { return (l.x == r.x && l.y == r.y) } public func <(l: Vector, r: Vector) -> Bool { return (l.x < r.x && l.y < r.y) } /// Add two vectors public func +(l: Vector, r: Vector) -> Vector { return Vector(x: l.x + r.x, y: l.y + r.y) } public func +=(inout l: Vector, r: Vector) { l = l + r } public func -=(inout l: Vector, r: Vector) { l = l - r } /// Subtract two vectors. public func -(l: Vector, r: Vector) -> Vector { return Vector(x: l.x - r.x, y: l.y - r.y) } public func *(l: Vector, r: Vector) -> Vector { return Vector(x: l.x * r.x, y: l.y * r.y) } public func /(l: Vector, r: Vector) -> Vector { return Vector(x: l.x / r.x, y: l.y / r.y) }
apache-2.0
abfff2e2de44e5af4ea75dd77bb5d065
26.9625
107
0.632544
3.139649
false
false
false
false
jpsim/SWXMLHash
SWXMLHashPlayground.playground/section-1.swift
1
2219
// Playground - noun: a place where people can play // swiftlint:disable force_unwrapping import Foundation import SWXMLHash let xmlWithNamespace = "<root xmlns:h=\"http://www.w3.org/TR/html4/\"" + " xmlns:f=\"http://www.w3schools.com/furniture\">" + " <h:table>" + " <h:tr>" + " <h:td>Apples</h:td>" + " <h:td>Bananas</h:td>" + " </h:tr>" + " </h:table>" + " <f:table>" + " <f:name>African Coffee Table</f:name>" + " <f:width>80</f:width>" + " <f:length>120</f:length>" + " </f:table>" + "</root>" var xml = SWXMLHash.parse(xmlWithNamespace) // one root element let count = xml["root"].all.count // "Apples" xml["root"]["h:table"]["h:tr"]["h:td"][0].element!.text // enumerate all child elements (procedurally) func enumerate(indexer: XMLIndexer, level: Int) { for child in indexer.children { let name = child.element!.name print("\(level) \(name)") enumerate(indexer: child, level: level + 1) } } enumerate(indexer: xml, level: 0) // enumerate all child elements (functionally) func reduceName(names: String, elem: XMLIndexer) -> String { return names + elem.element!.name + elem.children.reduce(", ", reduceName) } xml.children.reduce("elements: ", reduceName) // custom types conversion let booksXML = "<root>" + " <books>" + " <book>" + " <title>Book A</title>" + " <price>12.5</price>" + " <year>2015</year>" + " </book>" + " <book>" + " <title>Book B</title>" + " <price>10</price>" + " <year>1988</year>" + " </book>" + " <book>" + " <title>Book C</title>" + " <price>8.33</price>" + " <year>1990</year>" + " <amount>10</amount>" + " </book>" + " <books>" + "</root>" struct Book: XMLIndexerDeserializable { let title: String let price: Double let year: Int let amount: Int? static func deserialize(_ node: XMLIndexer) throws -> Book { return try Book( title: node["title"].value(), price: node["price"].value(), year: node["year"].value(), amount: node["amount"].value() ) } } xml = SWXMLHash.parse(booksXML) let books: [Book] = try xml["root"]["books"]["book"].value()
mit
7b64e76ad8c68ee1595ee9decadaf7a8
23.655556
78
0.568274
3.056474
false
false
false
false
Tatoeba/tatoeba-ios
Tatoeba/Common/Networking/ContributionsRequest.swift
1
1094
// // ContributionsRequest.swift // Tatoeba // // Created by Jack Cook on 8/6/17. // Copyright © 2017 Tatoeba. All rights reserved. // import Alamofire import SwiftyJSON /// Returns recent contributions using the specified parameters. final class ContributionsRequest: TatoebaRequest { typealias ResponseData = JSON typealias Value = [Contribution] var endpoint: String { return "/contributions" } var parameters: Parameters { return [String: String]() } var responseType: TatoebaResponseType { return .json } func handleRequest(_ json: JSON?, _ completion: @escaping ([Contribution]?) -> Void) { guard let contributionData = json?.array else { completion(nil) return } var contributions = [Contribution]() for contributionDatum in contributionData { let contribution = Contribution(json: contributionDatum) contributions.append(contribution) } completion(contributions) } }
mit
c3ef5e19728723b6f3f410fabc7965fc
23.288889
90
0.617566
4.923423
false
false
false
false
scoremedia/Fisticuffs
iOS Example/Tests/AddItemViewModelSpec.swift
1
2573
// The MIT License (MIT) // // Copyright (c) 2015 theScore Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Quick import Nimble import Fisticuffs @testable import iOS_Example class AddItemViewModelSpec: QuickSpec { override func spec() { describe("AddItemViewModel") { var viewModel = AddItemViewModel() var finishedResult: AddItemResult? beforeEach { viewModel = AddItemViewModel() viewModel.finished += { _, result in finishedResult = result } } it("should finish with a cancel result if Cancel is tapped") { viewModel.cancelTapped() guard case .some(.Cancelled) = finishedResult else { fail(); return } } it("should finish with a new item result if Done is tapped and input is valid") { viewModel.item.title.value = "Hello" viewModel.doneTapped() guard case .some(.NewToDoItem(let item)) = finishedResult, item.title.value == "Hello" else { fail(); return } } it("should require a non-empty title to be valid") { viewModel.item.title.value = "" expect(viewModel.inputIsValid.value) == false viewModel.item.title.value = "Testing" expect(viewModel.inputIsValid.value) == true } } } }
mit
b911f0d3dab1c615fafaffb741e4af22
39.203125
126
0.625729
4.845574
false
false
false
false
zisko/swift
stdlib/public/core/LazyCollection.swift
1
8223
//===--- LazyCollection.swift ---------------------------------*- swift -*-===// // // 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 collection on which normally-eager operations such as `map` and /// `filter` are implemented lazily. /// /// Please see `LazySequenceProtocol` for background; `LazyCollectionProtocol` /// is an analogous component, but for collections. /// /// To add new lazy collection operations, extend this protocol with /// methods that return lazy wrappers that are themselves /// `LazyCollectionProtocol`s. public protocol LazyCollectionProtocol: Collection, LazySequenceProtocol { /// A `Collection` that can contain the same elements as this one, /// possibly with a simpler type. /// /// - See also: `elements` associatedtype Elements : Collection = Self } extension LazyCollectionProtocol { // Lazy things are already lazy @_inlineable // FIXME(sil-serialize-all) public var lazy: LazyCollection<Elements> { return elements.lazy } } extension LazyCollectionProtocol where Elements: LazyCollectionProtocol { // Lazy things are already lazy @_inlineable // FIXME(sil-serialize-all) public var lazy: Elements { return elements } } /// A collection containing the same elements as a `Base` collection, /// but on which some operations such as `map` and `filter` are /// implemented lazily. /// /// - See also: `LazySequenceProtocol`, `LazyCollection` @_fixed_layout public struct LazyCollection<Base : Collection> { /// Creates an instance with `base` as its underlying Collection /// instance. @_inlineable @_versioned internal init(_base: Base) { self._base = _base } @_versioned internal var _base: Base } extension LazyCollection: LazyCollectionProtocol { /// The type of the underlying collection. public typealias Elements = Base /// The underlying collection. @_inlineable public var elements: Elements { return _base } } /// Forward implementations to the base collection, to pick up any /// optimizations it might implement. extension LazyCollection : Sequence { public typealias Iterator = Base.Iterator /// Returns an iterator over the elements of this sequence. /// /// - Complexity: O(1). @_inlineable public func makeIterator() -> Iterator { return _base.makeIterator() } /// A value less than or equal to the number of elements in the sequence, /// calculated nondestructively. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length /// of the collection. @_inlineable public var underestimatedCount: Int { return _base.underestimatedCount } @_inlineable public func _copyToContiguousArray() -> ContiguousArray<Base.Iterator.Element> { return _base._copyToContiguousArray() } @_inlineable public func _copyContents( initializing buf: UnsafeMutableBufferPointer<Iterator.Element> ) -> (Iterator,UnsafeMutableBufferPointer<Iterator.Element>.Index) { return _base._copyContents(initializing: buf) } @_inlineable public func _customContainsEquatableElement( _ element: Base.Iterator.Element ) -> Bool? { return _base._customContainsEquatableElement(element) } } extension LazyCollection : Collection { /// A type that represents a valid position in the collection. /// /// Valid indices consist of the position of every element and a /// "past the end" position that's not valid for use as a subscript. public typealias Element = Base.Element public typealias Index = Base.Index public typealias Indices = Base.Indices /// The position of the first element in a non-empty collection. /// /// In an empty collection, `startIndex == endIndex`. @_inlineable public var startIndex: Index { return _base.startIndex } /// The collection's "past the end" position---that is, the position one /// greater than the last valid subscript argument. /// /// `endIndex` is always reachable from `startIndex` by zero or more /// applications of `index(after:)`. @_inlineable public var endIndex: Index { return _base.endIndex } @_inlineable public var indices: Indices { return _base.indices } // TODO: swift-3-indexing-model - add docs @_inlineable public func index(after i: Index) -> Index { return _base.index(after: i) } /// Accesses the element at `position`. /// /// - Precondition: `position` is a valid position in `self` and /// `position != endIndex`. @_inlineable public subscript(position: Index) -> Element { return _base[position] } /// A Boolean value indicating whether the collection is empty. @_inlineable public var isEmpty: Bool { return _base.isEmpty } /// Returns the number of elements. /// /// To check whether a collection is empty, use its `isEmpty` property /// instead of comparing `count` to zero. Unless the collection guarantees /// random-access performance, calculating `count` can be an O(*n*) /// operation. /// /// - Complexity: O(1) if `Self` conforms to `RandomAccessCollection`; /// O(*n*) otherwise. @_inlineable public var count: Int { return _base.count } // The following requirement enables dispatching for index(of:) when // the element type is Equatable. /// Returns `Optional(Optional(index))` if an element was found; /// `nil` otherwise. /// /// - Complexity: O(*n*) @_inlineable public func _customIndexOfEquatableElement( _ element: Element ) -> Index?? { return _base._customIndexOfEquatableElement(element) } /// Returns the first element of `self`, or `nil` if `self` is empty. @_inlineable public var first: Element? { return _base.first } // TODO: swift-3-indexing-model - add docs @_inlineable public func index(_ i: Index, offsetBy n: Int) -> Index { return _base.index(i, offsetBy: n) } // TODO: swift-3-indexing-model - add docs @_inlineable public func index( _ i: Index, offsetBy n: Int, limitedBy limit: Index ) -> Index? { return _base.index(i, offsetBy: n, limitedBy: limit) } // TODO: swift-3-indexing-model - add docs @_inlineable public func distance(from start: Index, to end: Index) -> Int { return _base.distance(from:start, to: end) } } extension LazyCollection : BidirectionalCollection where Base : BidirectionalCollection { @_inlineable public func index(before i: Index) -> Index { return _base.index(before: i) } @_inlineable public var last: Element? { return _base.last } } extension LazyCollection : RandomAccessCollection where Base : RandomAccessCollection {} /// Augment `self` with lazy methods such as `map`, `filter`, etc. extension Collection { /// A view onto this collection that provides lazy implementations of /// normally eager operations, such as `map` and `filter`. /// /// Use the `lazy` property when chaining operations to prevent /// intermediate operations from allocating storage, or when you only /// need a part of the final collection to avoid unnecessary computation. @_inlineable public var lazy: LazyCollection<Self> { return LazyCollection(_base: self) } } extension Slice: LazySequenceProtocol where Base: LazySequenceProtocol { } extension Slice: LazyCollectionProtocol where Base: LazyCollectionProtocol { } extension ReversedCollection: LazySequenceProtocol where Base: LazySequenceProtocol { } extension ReversedCollection: LazyCollectionProtocol where Base: LazyCollectionProtocol { } @available(*, deprecated, renamed: "LazyCollection") public typealias LazyBidirectionalCollection<T> = LazyCollection<T> where T : BidirectionalCollection @available(*, deprecated, renamed: "LazyCollection") public typealias LazyRandomAccessCollection<T> = LazyCollection<T> where T : RandomAccessCollection
apache-2.0
2e032736c00f3fa15ce41bde618854de
30.872093
101
0.69938
4.586168
false
false
false
false
melling/ios_topics
TransitionWithView/TransitionWithView/ViewController.swift
1
4100
// // ViewController.swift // TransitionWithView // // Created by Michael Mellinger on 4/28/15. // Copyright (c) 2015 h4labs. All rights reserved. // import UIKit class ViewController: UIViewController { /* Need to use a container as described here: http://stackoverflow.com/questions/29923061/trying-to-curl-up-curl-down-with-two-views-using-autolayout-in-swift?noredirect=1#comment47975892_29923061 http://stackoverflow.com/questions/9524048/how-to-flip-an-individual-uiview-without-flipping-the-parent-view */ var container:UIView! // Place cardFront/cardBack in this container var cardFront:UIView! var cardBack:UIView! func centerViewXY(_ parent: UIView, child: UIView) { let constX = NSLayoutConstraint(item: child, attribute: NSLayoutConstraint.Attribute.centerX, relatedBy: NSLayoutConstraint.Relation.equal, toItem: parent, attribute: NSLayoutConstraint.Attribute.centerX, multiplier: 1, constant: 0) parent.addConstraint(constX) let constY = NSLayoutConstraint(item: child, attribute: NSLayoutConstraint.Attribute.centerY, relatedBy: NSLayoutConstraint.Relation.equal, toItem: parent, attribute: NSLayoutConstraint.Attribute.centerY, multiplier: 1, constant: 0) parent.addConstraint(constY) } func addStandardConstraints(_ view:UIView, constraint:String, viewDictionary:Dictionary<String,AnyObject>, metrics:Dictionary<String, Int>) { view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: constraint, options: [], metrics: metrics, views: viewDictionary)) } @objc func curlUp() { let transitionOptions = UIView.AnimationOptions.transitionCurlUp UIView.transition(from: cardFront, to: cardBack, duration: 5.0, options: transitionOptions, completion: { _ in let transitionOptions = UIView.AnimationOptions.transitionCurlDown UIView.transition(from: self.cardBack, to: self.cardFront, duration: 5.0, options: transitionOptions, completion: { _ in // }) }) } func buildView() { let height = 100 let width = 100 container = UIView() container.translatesAutoresizingMaskIntoConstraints = false container.backgroundColor = UIColor.black self.view.addSubview(container) cardBack = UIView(frame: CGRect(x: 0, y: 0, width: CGFloat(width), height: CGFloat(height))) cardBack.backgroundColor = UIColor.red container.addSubview(cardBack) cardFront = UIView(frame: CGRect(x: 0, y: 0, width: CGFloat(width), height: CGFloat(height))) cardFront.backgroundColor = UIColor.green container.addSubview(cardFront) let viewDictionary:Dictionary<String,UIView> = ["container": container] let metrics:Dictionary<String,Int> = ["width": width, "height": height] let h0Constraint = "H:[container(==width)]" let v0Constraint = "V:[container(==height)]" addStandardConstraints(self.view, constraint: h0Constraint, viewDictionary: viewDictionary, metrics: metrics) addStandardConstraints(self.view, constraint: v0Constraint, viewDictionary: viewDictionary, metrics: metrics) centerViewXY(self.view, child: container) Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(ViewController.curlUp), userInfo: nil, repeats: false) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.view.backgroundColor = UIColor.purple buildView() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
cc0-1.0
93830e1e4cdddc0413c0e41f93677e76
34.964912
240
0.650976
4.85782
false
false
false
false
Peterrkang/SpotMe
SpotMe/SpotMe/HomeVC.swift
1
2732
// // HomeVC.swift // SpotMe // // Created by Peter Kang on 10/18/16. // Copyright © 2016 Peter Kang. All rights reserved. // import UIKit import FirebaseAuth import FirebaseDatabase import SwiftKeychainWrapper class HomeVC: UIViewController, UITableViewDelegate, UITableViewDataSource { private let _userID: String? = KeychainWrapper.standard.string(forKey: KEY_UID) @IBOutlet weak var tableView: UITableView! private var events = [Event]() override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self observeEvent() } override func viewDidAppear(_ animated: Bool) { //performSegue(withIdentifier: "LoginVC", sender: nil) guard FIRAuth.auth()?.currentUser != nil else{ performSegue(withIdentifier: "LoginVC", sender: nil) return } } func observeEvent(){ DataService.instance.eventsRef.observeSingleEvent(of: .value) { (snapshot: FIRDataSnapshot) in if let events = snapshot.value as? Dictionary<String, AnyObject>{ for(key, value) in events{ if(value["userId"] as? String == self._userID){ if let title = value["title"] as? String { let event = Event(id: key, userId: self._userID!, title: title) self.events.append(event) } } } } self.tableView.reloadData() } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "EventCell") as! EventCell let event = events[indexPath.row] cell.updateUI(event: event) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let event = events[indexPath.row] performSegue(withIdentifier: "ConvoVC", sender: event) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "ConvoVC" { if let destination = segue.destination as? ConvoVC { if let event = sender as? Event { destination.event = event } } } } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return events.count } }
mit
8bc22ce61e0e9fb4c2a3a758d21c93ea
26.867347
102
0.567558
5.211832
false
false
false
false
8bytes/drift-sdk-ios
Drift/Birdsong/Response.swift
2
940
// // Response.swift // Pods // // Created by Simon Manning on 23/06/2016. // // import Foundation class Response { let ref: String let topic: String let event: String let payload: Socket.Payload init?(data: Data) { do { guard let jsonObject = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions()) as? Socket.Payload else { return nil } ref = jsonObject["ref"] as? String ?? "" if let topic = jsonObject["topic"] as? String, let event = jsonObject["event"] as? String, let payload = jsonObject["payload"] as? Socket.Payload { self.topic = topic self.event = event self.payload = payload } else { return nil } } catch { return nil } } }
mit
ee9f2e2a29d08cbf96296e5c47a216f4
23.736842
163
0.509574
4.747475
false
false
false
false
modocache/swift
test/IRGen/clang_inline.swift
3
2944
// RUN: rm -rf %t && mkdir -p %t // RUN: %target-swift-frontend -sdk %S/Inputs -primary-file %s -emit-ir | %FileCheck %s // RUN: mkdir -p %t/Empty.framework/Modules/Empty.swiftmodule // RUN: %target-swift-frontend -emit-module-path %t/Empty.framework/Modules/Empty.swiftmodule/%target-swiftmodule-name %S/../Inputs/empty.swift -module-name Empty // RUN: %target-swift-frontend -sdk %S/Inputs -primary-file %s -F %t -DIMPORT_EMPTY -emit-ir > %t.ll // RUN: %FileCheck %s < %t.ll // RUN: %FileCheck -check-prefix=NEGATIVE %s < %t.ll // REQUIRES: CPU=i386_or_x86_64 // XFAIL: linux #if IMPORT_EMPTY import Empty #endif import gizmo // CHECK-LABEL: define hidden i64 @_TFC12clang_inline16CallStaticInline10ReturnZerofT_Vs5Int64(%C12clang_inline16CallStaticInline*) {{.*}} { class CallStaticInline { func ReturnZero() -> Int64 { return Int64(zero()) } } // CHECK-LABEL: define internal i32 @zero() // CHECK: [[INLINEHINT_SSP_UWTABLE:#[0-9]+]] { // CHECK-LABEL: define hidden i64 @_TFC12clang_inline17CallStaticInline210ReturnZerofT_Vs5Int64(%C12clang_inline17CallStaticInline2*) {{.*}} { class CallStaticInline2 { func ReturnZero() -> Int64 { return Int64(wrappedZero()) } } // CHECK-LABEL: define internal i32 @wrappedZero() // CHECK: [[INLINEHINT_SSP_UWTABLE:#[0-9]+]] { // CHECK-LABEL: define hidden i32 @_TF12clang_inline10testExternFT_Vs5Int32() {{.*}} { func testExtern() -> CInt { return wrappedGetInt() } // CHECK-LABEL: define internal i32 @wrappedGetInt() // CHECK: [[INLINEHINT_SSP_UWTABLE:#[0-9]+]] { // CHECK-LABEL: define hidden i32 @_TF12clang_inline16testAlwaysInlineFT_Vs5Int32() // CHECK: [[SSP:#[0-9]+]] { // NEGATIVE-NOT: @alwaysInlineNumber // CHECK: ret i32 17 func testAlwaysInline() -> CInt { return alwaysInlineNumber() } // CHECK-LABEL: define hidden i32 @_TF12clang_inline20testInlineRedeclaredFT_Vs5Int32() {{.*}} { func testInlineRedeclared() -> CInt { return zeroRedeclared() } // CHECK-LABEL: define internal i32 @zeroRedeclared() #{{[0-9]+}} { // CHECK-LABEL: define hidden i32 @_TF12clang_inline27testInlineRedeclaredWrappedFT_Vs5Int32() {{.*}} { func testInlineRedeclaredWrapped() -> CInt { return wrappedZeroRedeclared() } // CHECK-LABEL: define internal i32 @wrappedZeroRedeclared() #{{[0-9]+}} { // CHECK-LABEL: define hidden i32 @_TF12clang_inline22testStaticButNotInlineFT_Vs5Int32() {{.*}} { func testStaticButNotInline() -> CInt { return staticButNotInline() } // CHECK-LABEL: define internal i32 @staticButNotInline() #{{[0-9]+}} { // CHECK-LABEL: define internal i32 @innerZero() // CHECK: [[INNER_ZERO_ATTR:#[0-9]+]] { // CHECK-LABEL: declare i32 @getInt() // CHECK: [[GET_INT_ATTR:#[0-9]+]] // CHECK: attributes [[INLINEHINT_SSP_UWTABLE]] = { inlinehint ssp {{.*}}} // CHECK: attributes [[SSP]] = { ssp {{.*}} } // CHECK: attributes [[INNER_ZERO_ATTR]] = { inlinehint nounwind ssp // CHECK: attributes [[GET_INT_ATTR]] = {
apache-2.0
7c4a4313aa8bdbc95daf1b501a0d57a4
35.8
162
0.683764
3.141942
false
true
false
false
kstaring/swift
validation-test/compiler_crashers_fixed/00216-swift-unqualifiedlookup-unqualifiedlookup.swift
11
1269
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse ({}) var f = 1 var e: Int -> Int = { return $0 } let d: Int = { c, b in }(f, e) class k { func l((Any, k))(m } } func j<f: l: e -> e = { { l) { m } } protocol k { class func j() } class e: k{ } } func a(x: Any, y: Any) -> (((Any, Any) -> Any) -> Any) { return { (m: (Any, Any) -> Any) -> Any in return m(x, y) } } func b(z: (((Any, Any) - = b =b as c=b func q(v: h) -> <r>(() -> r) -> h { n { u o "\(v): \(u())" } } struct e<r> { j p: , () -> ())] = [] } protocol p { } protocol m : p { } protocol v : p { } protocol m { v = m } func s<s : m, v : m u v.v == s> (m: v) { } func s<v : m u v.v == v> (m: v) { } s( { ({}) } t func c<g>() -> (g, g -> g) -> g { d b d.f = { } { g) { i } } i c { class func f() } class d: c{ class func f {} struct d<c : f,f where g.i == c.i> fu ^(a: Bo } }
apache-2.0
44a301612ee61a1304f835eccdb115fe
15.697368
78
0.488574
2.498031
false
false
false
false
cubixlabs/GIST-Framework
GISTFramework/Classes/Controls/FloatingLabelTextField.swift
1
19740
// // FloatingLabelTextField.swift // GISTFramework // // Created by Shoaib Abdul on 14/03/2017. // Copyright © 2017 Social Cubix. All rights reserved. // import UIKit open class FloatingLabelTextField: ValidatedTextField { // MARK: Animation timing /// The value of the title appearing duration open var titleFadeInDuration:TimeInterval = 0.2 /// The value of the title disappearing duration open var titleFadeOutDuration:TimeInterval = 0.3 // MARK: Title /// The String to display when the textfield is not editing and the input is not empty. @IBInspectable open var title:String? { didSet { self.updateControl(); } } //P.E. /// The String to display when the textfield is editing and the input is not empty. @IBInspectable open var titleSelected:String? { didSet { self.updateControl(); } } //P.E. // MARK: Font Style /// Font size/style key from Sync Engine. /// Font name key from Sync Engine. @IBInspectable open var titleFontName:String = GIST_CONFIG.fontName { didSet { self.titleLabel.fontName = self.titleFontName; } } @IBInspectable open var titleFontStyle:String = GIST_CONFIG.fontStyle { didSet { self.titleLabel.fontStyle = self.titleFontStyle; } } //P.E. // MARK: Colors /// A UIColor value that determines the text color of the title label when in the normal state @IBInspectable open var titleColor:String? { didSet { self.updateTitleColor(); } } /// A UIColor value that determines the text color of the title label when editing @IBInspectable open var titleColorSelected:String? { didSet { self.updateTitleColor(); } } /// A UIColor value that determines the color of the bottom line when in the normal state @IBInspectable open var lineColor:String? { didSet { self.updateLineView(); } } /// A UIColor value that determines the color of the line in a selected state @IBInspectable open var lineColorSelected:String? { didSet { self.updateLineView(); } } //P.E. /// A UIColor value that determines the color used for the title label and the line when the error message is not `nil` @IBInspectable open var errorColor:String? { didSet { self.updateColors(); } } //P.E. // MARK: Title Case /// Flag for upper case formatting @IBInspectable open var uppercaseTitle:Bool = false { didSet { self.updateControl(); } } // MARK: Line height /// A CGFloat value that determines the height for the bottom line when the control is in the normal state @IBInspectable open var lineHeight:CGFloat = GIST_CONFIG.seperatorWidth { didSet { self.updateLineView(); self.setNeedsDisplay(); } } //P.E. /// A CGFloat value that determines the height for the bottom line when the control is in a selected state @IBInspectable open var lineHeightSelected:CGFloat = GIST_CONFIG.seperatorWidth { didSet { self.updateLineView(); self.setNeedsDisplay(); } } // MARK: View components /// The internal `UIView` to display the line below the text input. open var lineView:UIView! /// The internal `UILabel` that displays the selected, deselected title or the error message based on the current state. open var titleLabel:BaseUILabel! // MARK: Properties /** Identifies whether the text object should hide the text being entered. */ override open var isSecureTextEntry:Bool { set { super.isSecureTextEntry = newValue; self.fixCaretPosition(); } get { return super.isSecureTextEntry; } } /// The backing property for the highlighted property fileprivate var _highlighted = false; /// A Boolean value that determines whether the receiver is highlighted. When changing this value, highlighting will be done with animation override open var isHighlighted:Bool { get { return _highlighted } set { _highlighted = newValue; self.updateTitleColor(); self.updateLineView(); } } /// A Boolean value that determines whether the textfield is being edited or is selected. open var editingOrSelected:Bool { get { return super.isEditing || self.isSelected; } } /// A Boolean value that determines whether the receiver has an error message. open var hasErrorMessage:Bool = false { didSet { self.updateControl(false); } } fileprivate var _renderingInInterfaceBuilder:Bool = false /// The text content of the textfield override open var text:String? { didSet { self.updateControl(false); } } /** The String to display when the input field is empty. The placeholder can also appear in the title label when both `title` `selectedTitle` and are `nil`. */ override open var placeholder:String? { set { super.placeholder = newValue; self.setNeedsDisplay(); self.updateTitleLabel(); } get { return super.placeholder; } } // Determines whether the field is selected. When selected, the title floats above the textbox. open override var isSelected:Bool { didSet { self.updateControl(true); } } override open var fontName: String { didSet { self.titleLabel.fontName = self.fontName; } } // P.E. open override var isInvalidSignHidden: Bool { set { super.isInvalidSignHidden = newValue; self.hasErrorMessage = (isInvalidSignHidden == false && self.errorMsg != ""); } get { return super.isInvalidSignHidden } } //P.E. // MARK: - Initializers /** Initializes the control - parameter frame the frame of the control */ override public init(frame: CGRect) { super.init(frame: frame) self.setupFloatingLabel(); } /** Intialzies the control by deserializing it - parameter coder the object to deserialize the control from */ required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder); self.setupFloatingLabel(); } // MARK: - Methods fileprivate final func setupFloatingLabel() { self.borderStyle = .none; self.createTitleLabel(); self.createLineView(); self.updateColors(); self.addEditingChangedObserver(); } fileprivate func addEditingChangedObserver() { self.addTarget(self, action: #selector(editingChanged), for: .editingChanged) } /** Invoked when the editing state of the textfield changes. Override to respond to this change. */ @objc open func editingChanged() { self.updateControl(true); self.updateTitleLabel(true); } /** The formatter to use before displaying content in the title label. This can be the `title`, `selectedTitle` or the `errorMessage`. The default implementation converts the text to uppercase. */ private func titleFormatter(_ txt:String) -> String { let rtnTxt:String = SyncedText.text(forKey: txt); return (self.uppercaseTitle == true) ? rtnTxt.uppercased():rtnTxt; } //F.E. // MARK: create components private func createTitleLabel() { let titleLabel = BaseUILabel() titleLabel.autoresizingMask = [.flexibleWidth, .flexibleHeight] titleLabel.fontName = self.titleFontName; titleLabel.fontStyle = self.titleFontStyle; titleLabel.alpha = 0.0 self.addSubview(titleLabel) self.titleLabel = titleLabel } private func createLineView() { if self.lineView == nil { let lineView = UIView() lineView.isUserInteractionEnabled = false; self.lineView = lineView self.configureDefaultLineHeight() } lineView.autoresizingMask = [.flexibleWidth, .flexibleTopMargin] self.addSubview(lineView) } private func configureDefaultLineHeight() { //??let onePixel:CGFloat = 1.0 / UIScreen.main.scale self.lineHeight = GIST_CONFIG.seperatorWidth; self.lineHeightSelected = GIST_CONFIG.seperatorWidth; } // MARK: Responder handling open override func updateData(_ data: Any?) { super.updateData(data); let dicData:NSMutableDictionary? = data as? NSMutableDictionary; self.title = dicData?["title"] as? String; } //F.E. /** Attempt the control to become the first responder - returns: True when successfull becoming the first responder */ @discardableResult override open func becomeFirstResponder() -> Bool { let result = super.becomeFirstResponder() self.updateControl(true) return result } /** Attempt the control to resign being the first responder - returns: True when successfull resigning being the first responder */ @discardableResult override open func resignFirstResponder() -> Bool { let result = super.resignFirstResponder() self.updateControl(true); return result } // MARK: - View updates private func updateControl(_ animated:Bool = false, completion: ((_ completed: Bool) -> Void)? = nil) { self.updateColors() self.updateLineView() self.updateTitleLabel(animated, completion:completion) } private func updateLineView() { if let lineView = self.lineView { lineView.frame = self.lineViewRectForBounds(self.bounds, editing: self.editingOrSelected) } self.updateLineColor() } // MARK: - Color updates /// Update the colors for the control. Override to customize colors. open func updateColors() { self.updateLineColor() self.updateTitleColor() self.updateTextColor() } private func updateLineColor() { if self.hasErrorMessage { self.lineView.backgroundColor = UIColor.color(forKey: self.errorColor) ?? UIColor.red; } else { self.lineView.backgroundColor = UIColor.color(forKey: (self.editingOrSelected && self.lineColorSelected != nil) ? (self.lineColorSelected) : self.lineColor); } } private func updateTitleColor() { if self.hasErrorMessage { self.titleLabel.textColor = UIColor.color(forKey: self.errorColor) ?? UIColor.red; } else { if ((self.editingOrSelected || self.isHighlighted) && self.titleColorSelected != nil) { self.titleLabel.textColor = UIColor.color(forKey: self.titleColorSelected); } else { self.titleLabel.textColor = UIColor.color(forKey: self.titleColor); } } } private func updateTextColor() { if self.hasErrorMessage { super.textColor = UIColor.color(forKey: self.errorColor); } else { super.textColor = UIColor.color(forKey: self.fontColorStyle); } } // MARK: - Title handling private func updateTitleLabel(_ animated:Bool = false, completion: ((_ completed: Bool) -> Void)? = nil) { var titleText:String? = nil if self.hasErrorMessage { titleText = self.titleFormatter(self.errorMsg); } else { if self.editingOrSelected { titleText = self.selectedTitleOrTitlePlaceholder() if titleText == nil { titleText = self.titleOrPlaceholder() } } else { titleText = self.titleOrPlaceholder() } } self.titleLabel.text = titleText self.updateTitleVisibility(animated, completion:completion); } private var _titleVisible = false /* * Set this value to make the title visible */ open func setTitleVisible(_ titleVisible:Bool, animated:Bool = false, animationCompletion: ((_ completed: Bool) -> Void)? = nil) { if(_titleVisible == titleVisible) { return } _titleVisible = titleVisible self.updateTitleColor() self.updateTitleVisibility(animated, completion: animationCompletion) } /** Returns whether the title is being displayed on the control. - returns: True if the title is displayed on the control, false otherwise. */ open func isTitleVisible() -> Bool { return self.hasText || self.hasErrorMessage || _titleVisible; } fileprivate func updateTitleVisibility(_ animated:Bool = false, completion: ((_ completed: Bool) -> Void)? = nil) { let alpha:CGFloat = self.isTitleVisible() ? 1.0 : 0.0 let frame:CGRect = self.titleLabelRectForBounds(self.bounds, editing: self.isTitleVisible()) let updateBlock = { () -> Void in self.titleLabel.alpha = alpha self.titleLabel.frame = frame } if animated { let animationOptions:UIView.AnimationOptions = .curveEaseOut; let duration = self.isTitleVisible() ? titleFadeInDuration : titleFadeOutDuration UIView.animate(withDuration: duration, delay: 0, options: animationOptions, animations: { () -> Void in updateBlock() }, completion: completion) } else { updateBlock() completion?(true) } } // MARK: - UITextField text/placeholder positioning overrides /** Calculate the rectangle for the textfield when it is not being edited - parameter bounds: The current bounds of the field - returns: The rectangle that the textfield should render in */ override open func textRect(forBounds bounds: CGRect) -> CGRect { _ = super.textRect(forBounds: bounds); let titleHeight = self.titleHeight() let lineHeight = self.lineHeightSelected let rect = CGRect(x: 0, y: titleHeight, width: bounds.size.width, height: bounds.size.height - titleHeight - lineHeight) return rect } /** Calculate the rectangle for the textfield when it is being edited - parameter bounds: The current bounds of the field - returns: The rectangle that the textfield should render in */ override open func editingRect(forBounds bounds: CGRect) -> CGRect { let titleHeight = self.titleHeight() let lineHeight = self.lineHeightSelected let rect = CGRect(x: 0, y: titleHeight, width: bounds.size.width, height: bounds.size.height - titleHeight - lineHeight) return rect } /** Calculate the rectangle for the placeholder - parameter bounds: The current bounds of the placeholder - returns: The rectangle that the placeholder should render in */ override open func placeholderRect(forBounds bounds: CGRect) -> CGRect { let titleHeight = self.titleHeight() let lineHeight = self.lineHeightSelected let rect = CGRect(x: 0, y: titleHeight, width: bounds.size.width, height: bounds.size.height - titleHeight - lineHeight) return rect } // MARK: - Positioning Overrides /** Calculate the bounds for the title label. Override to create a custom size title field. - parameter bounds: The current bounds of the title - parameter editing: True if the control is selected or highlighted - returns: The rectangle that the title label should render in */ open func titleLabelRectForBounds(_ bounds:CGRect, editing:Bool) -> CGRect { let titleHeight = self.titleHeight() if editing { return CGRect(x: 0, y: 0, width: bounds.size.width, height: titleHeight) } return CGRect(x: 0, y: titleHeight, width: bounds.size.width, height: titleHeight) } /** Calculate the bounds for the bottom line of the control. Override to create a custom size bottom line in the textbox. - parameter bounds: The current bounds of the line - parameter editing: True if the control is selected or highlighted - returns: The rectangle that the line bar should render in */ open func lineViewRectForBounds(_ bounds:CGRect, editing:Bool) -> CGRect { let lineHeight:CGFloat = editing ? CGFloat(self.lineHeightSelected) : CGFloat(self.lineHeight) return CGRect(x: 0, y: bounds.size.height - lineHeight, width: bounds.size.width, height: lineHeight); } /** Calculate the height of the title label. -returns: the calculated height of the title label. Override to size the title with a different height */ open func titleHeight() -> CGFloat { if let titleLabel = self.titleLabel, let font = titleLabel.font { return font.lineHeight } return GISTUtility.convertToRatio(15.0, sizedForIPad: self.sizeForIPad); } /** Calcualte the height of the textfield. -returns: the calculated height of the textfield. Override to size the textfield with a different height */ open func textHeight() -> CGFloat { return self.font!.lineHeight + GISTUtility.convertToRatio(7.0, sizedForIPad: self.sizeForIPad); } // MARK: - Layout /// Invoked when the interface builder renders the control override open func prepareForInterfaceBuilder() { if #available(iOS 8.0, *) { super.prepareForInterfaceBuilder() } self.borderStyle = .none self.isSelected = true _renderingInInterfaceBuilder = true self.updateControl(false) self.invalidateIntrinsicContentSize() } /// Invoked by layoutIfNeeded automatically override open func layoutSubviews() { super.layoutSubviews() self.titleLabel.frame = self.titleLabelRectForBounds(self.bounds, editing: self.isTitleVisible() || _renderingInInterfaceBuilder) self.lineView.frame = self.lineViewRectForBounds(self.bounds, editing: self.editingOrSelected || _renderingInInterfaceBuilder) } /** Calculate the content size for auto layout - returns: the content size to be used for auto layout */ override open var intrinsicContentSize : CGSize { return CGSize(width: self.bounds.size.width, height: self.titleHeight() + self.textHeight()) } // MARK: - Helpers fileprivate func titleOrPlaceholder() -> String? { if let title = self.title ?? self.placeholder { return self.titleFormatter(title) } return nil } fileprivate func selectedTitleOrTitlePlaceholder() -> String? { if let title = self.titleSelected ?? self.title ?? self.placeholder { return self.titleFormatter(title) } return nil } } //CLS END
agpl-3.0
98bb5a018fae634ab3cb3013ede5d016
32.17479
169
0.616495
5.101835
false
false
false
false
gezi0630/weiboDemo
weiboDemo/weiboDemo/Classes/Home/HomeViewController.swift
1
3368
// // HomeViewController.swift // weiboDemo // // Created by MAC on 2016/12/23. // Copyright © 2016年 GuoDongge. All rights reserved. // import UIKit class HomeViewController: BaseTableViewController { override func viewDidLoad() { super.viewDidLoad() if !userLogin { visitorView?.setupVisitorInfo(true, imageName: "visitordiscover_feed_image_house", message: "关注一些人,回这里看看有什么惊喜") return } setupNav() // 3.注册通知, 监听菜单 NotificationCenter.default.addObserver(self, selector: #selector(HomeViewController.change), name: NSNotification.Name(rawValue: XMGPopoverAnimatorWillShow), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(HomeViewController.change), name: NSNotification.Name(rawValue: XMGPopoverAnimatorWilldismiss), object: nil) } deinit { // 移除通知 NotificationCenter.default.removeObserver(self) } /** 修改标题按钮的状态 */ func change(){ // 修改标题按钮的状态 let titleBtn = navigationItem.titleView as! TitleButton titleBtn.isSelected = !titleBtn.isSelected } private func setupNav() { //初始化左右按钮 navigationItem.leftBarButtonItem = UIBarButtonItem.creatBarButtonItem(imageName: "navigationbar_friendattention", target: self, action: #selector(HomeViewController.leftItemClick)) navigationItem.rightBarButtonItem = UIBarButtonItem.creatBarButtonItem(imageName: "navigationbar_pop", target: self, action:#selector(HomeViewController.rightItemClick)) //初始化标题按钮 let titleBtn = TitleButton() titleBtn.setTitle("冬哥的爱 ", for: UIControlState()) titleBtn.addTarget(self, action: #selector(titleBtnClick), for: UIControlEvents.touchUpInside); navigationItem.titleView = titleBtn } func titleBtnClick(btn : TitleButton){ //1.修改箭头的方向 // btn.isSelected = !btn.isSelected //2、弹出菜单 let sb = UIStoryboard(name: "PopoverViewController", bundle: nil) let vc = sb.instantiateInitialViewController() // 2.1设置转场代理 // 默认情况下modal会移除以前控制器的view, 替换为当前弹出的view // 如果自定义转场, 那么就不会移除以前控制器的view vc?.transitioningDelegate = popverAnimator //2.2设置转场样式 vc?.modalPresentationStyle = UIModalPresentationStyle.custom present(vc!, animated: true, completion: nil) } func leftItemClick() { print(#function) } func rightItemClick() { let sb = UIStoryboard(name: "QRCodeViewController", bundle: nil) let vc = sb.instantiateInitialViewController() present(vc!, animated: true, completion: nil) } //记录当前是否展开 var isPresent:Bool = false } // MARK: - 懒加载 // 一定要定义一个属性来报错自定义转场对象, 否则会报错 fileprivate var popverAnimator:PopoverAnimator = { let pa = PopoverAnimator() pa.presentFrame = CGRect(x: 100, y: 56, width: 200, height: 350) return pa }()
apache-2.0
542ac1ead1c9a6268d40eace4e2d3270
26.098214
184
0.653048
4.669231
false
false
false
false
zmeyc/GRDB.swift
GRDB/Utils/Utils.swift
1
2353
import Foundation #if SWIFT_PACKAGE import CSQLite #endif // MARK: - Public extension String { /// Returns the receiver, quoted for safe insertion as an identifier in an /// SQL query. /// /// db.execute("SELECT * FROM \(tableName.quotedDatabaseIdentifier)") public var quotedDatabaseIdentifier: String { // See https://www.sqlite.org/lang_keywords.html return "\"" + self + "\"" } } /// Return as many question marks separated with commas as the *count* argument. /// /// databaseQuestionMarks(count: 3) // "?,?,?" public func databaseQuestionMarks(count: Int) -> String { return Array(repeating: "?", count: count).joined(separator: ",") } // MARK: - Internal /// Reserved for GRDB: do not use. func GRDBPrecondition(_ condition: @autoclosure() -> Bool, _ message: @autoclosure() -> String = "", file: StaticString = #file, line: UInt = #line) { /// Custom precondition function which aims at solving /// https://bugs.swift.org/browse/SR-905 and /// https://github.com/groue/GRDB.swift/issues/37 /// /// TODO: remove this function when https://bugs.swift.org/browse/SR-905 is solved. if !condition() { fatalError(message, file: file, line: line) } } // Workaround Swift inconvenience around factory methods of non-final classes func cast<T, U>(_ value: T) -> U? { return value as? U } extension Array { /// Removes the first object that matches *predicate*. mutating func removeFirst(_ predicate: (Element) throws -> Bool) rethrows { if let index = try index(where: predicate) { remove(at: index) } } } extension Dictionary { /// Create a dictionary with the keys and values in the given sequence. init<Sequence: Swift.Sequence>(keyValueSequence: Sequence) where Sequence.Iterator.Element == (Key, Value) { self.init(minimumCapacity: keyValueSequence.underestimatedCount) for (key, value) in keyValueSequence { self[key] = value } } /// Create a dictionary from keys and a value builder. init<Sequence: Swift.Sequence>(keys: Sequence, value: (Key) -> Value) where Sequence.Iterator.Element == Key { self.init(minimumCapacity: keys.underestimatedCount) for key in keys { self[key] = value(key) } } }
mit
1d5bc75c6c7aca25866463777a908a62
31.232877
150
0.643009
4.120841
false
false
false
false
roytornado/Flow-iOS
Example/Flow/ViewController.swift
1
4304
import UIKit import Flow_iOS class ViewController: UIViewController { @IBOutlet weak var summaryTextView: UITextView! override func viewDidLoad() { super.viewDidLoad() } func commonWillStartBlock(block: FlowWillStartBlock? = nil) -> FlowWillStartBlock { let result: FlowWillStartBlock = { flow in block?(flow) self.summaryTextView.text = "Flow Starting..." } return result } func commonDidFinishBlock(block: FlowDidFinishBlock? = nil) -> FlowDidFinishBlock { let result: FlowDidFinishBlock = { flow in block?(flow) self.summaryTextView.text = flow.generateSummary() } return result } func showAlert(message: String) { let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) present(alert, animated: true, completion: nil) } @IBAction func simpleChainedFlow() { Flow() .add(operation: SimplePrintOp(message: "hello world")) .add(operation: SimplePrintOp(message: "good bye")) .setWillStartBlock(block: commonWillStartBlock()) .setDidFinishBlock(block: commonDidFinishBlock()) .start() } @IBAction func demoLoginSuccess() { Flow() .setDataBucket(dataBucket: ["email": "[email protected]", "password": "123456"]) .add(operation: MockAsyncLoginOp()) .add(operation: MockAsyncLoadProfileOp()) .setWillStartBlock(block: commonWillStartBlock()) .setDidFinishBlock(block: commonDidFinishBlock() { flow in if flow.isSuccess { self.showAlert(message: "Login Success for \(flow.dataBucket["email"]!)") } else { self.showAlert(message: "Login Fail") } }) .start() } @IBAction func demoLoginFlowWithMissingData() { // MockAsyncLoginSuccessOp requires email but not exist in data bucket Flow() .setDataBucket(dataBucket: ["email_address": "[email protected]", "password": "123456"]) .add(operation: MockAsyncLoginOp()) .add(operation: MockAsyncLoadProfileOp()) .setWillStartBlock(block: commonWillStartBlock()) .setDidFinishBlock(block: commonDidFinishBlock()) .start() } @IBAction func demoLoginFlowWithIncorrectDataType() { // MockAsyncLoginSuccessOp requires password with String type but it's Int in data bucket Flow() .setDataBucket(dataBucket: ["email": "[email protected]", "password": 123456]) .add(operation: MockAsyncLoginOp()) .add(operation: MockAsyncLoadProfileOp()) .setWillStartBlock(block: commonWillStartBlock()) .setDidFinishBlock(block: commonDidFinishBlock()) .start() } @IBAction func demoLoginFail() { Flow() .setDataBucket(dataBucket: ["email": "[email protected]", "password": "654321"]) .add(operation: MockAsyncLoginOp()) .add(operation: MockAsyncLoadProfileOp()) .setWillStartBlock(block: commonWillStartBlock()) .setDidFinishBlock(block: commonDidFinishBlock()) .start() } @IBAction func demoDispatcher() { Flow() .setDataBucket(dataBucket: ["images": ["a", "b", "c", "d", 1]]) //.setDataBucket(dataBucket: ["images": [1]]) .addGrouped(operationCreator: UploadSingleImageOp.self, dispatcher: FlowArrayGroupDispatcher(inputKey: "images", outputKey: "imageURLs", maxConcurrentOperationCount: 3, allowFailure: false)) .setWillStartBlock(block: commonWillStartBlock()) .setDidFinishBlock(block: commonDidFinishBlock()) .start() } @IBAction func demoCases() { Flow() .setDataBucket(dataBucket: ["images": ["a", "b", "c", "d", 1], "target": "A"]) .add(operation: SimplePrintOp(message: "Step1")) .add(operation: SimplePrintOp(message: "Step2A1"), flowCase: FlowCase(key: "target", value: "A")) .add(operation: SimplePrintOp(message: "Step2A2")) .add(operation: SimplePrintOp(message: "Step2B1"), flowCase: FlowCase(key: "target", value: "B")) .add(operation: SimplePrintOp(message: "Step2B2")) .combine() .add(operation: SimplePrintOp(message: "Step3")) .setWillStartBlock(block: commonWillStartBlock()) .setDidFinishBlock(block: commonDidFinishBlock()) .start() } }
mit
68f7bdab6b803452003ced874dc60e99
34.570248
196
0.666125
4.011184
false
false
false
false
hooman/swift
test/Reflection/typeref_decoding_concurrency.swift
1
1510
// REQUIRES: no_asan // REQUIRES: executable_test // REQUIRES: concurrency // REQUIRES: libdispatch // REQUIRES: OS=macosx // rdar://76038845 // UNSUPPORTED: use_os_stdlib // UNSUPPORTED: back_deployment_runtime // RUN: %empty-directory(%t) // RUN: %target-build-swift -Xfrontend -enable-anonymous-context-mangled-names %S/Inputs/ConcurrencyTypes.swift -parse-as-library -emit-module -emit-library -module-name TypesToReflect -o %t/%target-library-name(TypesToReflect) -target x86_64-apple-macosx12.0 // RUN: %target-build-swift -Xfrontend -enable-anonymous-context-mangled-names %S/Inputs/ConcurrencyTypes.swift %S/Inputs/main.swift -emit-module -emit-executable -module-name TypesToReflect -o %t/TypesToReflect -target x86_64-apple-macosx12.0 // For macOS versions before 12.0, the mangling for concurrency-related // types cannot be used to create type metadata. // RUN: %target-swift-reflection-dump -binary-filename %t/%target-library-name(TypesToReflect) | %FileCheck %s // RUN: %target-swift-reflection-dump -binary-filename %t/TypesToReflect | %FileCheck %s // CHECK: FIELDS: // CHECK: ======= // CHECK: TypesToReflect.UsesConcurrency // CHECK: ------------------ // CHECK: mainActorFunction: @Swift.MainActor () -> () // CHECK: (function // CHECK: (global-actor // CHECK: (class Swift.MainActor)) // CHECK: actorIsolatedFunction: (isolated TypesToReflect.SomeActor) -> () // CHECK: (function // CHECK: (parameters // CHECK: isolated // CHECK: (class TypesToReflect.SomeActor))
apache-2.0
d0a77f52041cfa4e18266e8725bb58fa
40.944444
259
0.725828
3.61244
false
false
false
false
toineheuvelmans/Metron
source/Metron/Test/PolygonTest.swift
1
1883
@testable import Metron import CoreGraphics import Foundation import Nimble import Quick internal class PolygonSpec: Spec { override internal func spec() { it("can calculate convex hull") { // Thanks to http://www2.lawrence.edu/fast/GREGGJ/CMSC210/convex/convex.html. let polygonPoints: [CGPoint] = Array([(2, 6), (4, 6), (3, 5), (0.1, 4), (2.1, 4), (4.1, 4), (6.1, 4), (1.3, 3), (3.3, 3), (5.3, 3), (0, 2), (2.1, 2), (4.1, 2), (6.1, 2), (3, 1), (2, 0), (4, 0)]) let expectedConvexHullPoints: [CGPoint] = Array([(2, 0), (4, 0), (6.1, 2), (6.1, 4), (4, 6), (2, 6), (0.1, 4), (0, 2)]) let convexHull: Metron.Polygon? = polygonPoints.convexHull expect(convexHull).toNot(beNil()) expect(convexHull?.points) == expectedConvexHullPoints } it("can return line segments") { let points: [CGPoint] = Array([(0, 0), (0, 5), (5, 5), (5, 0)]) let segments = zip(points, points.suffix(from: 1) + points.prefix(1)).map({ LineSegment(a: $0, b: $1) }) let polygon: Metron.Polygon = Metron.Polygon(points: points) expect(polygon.lineSegments) == segments } it("can check if self intersecting") { expect(Metron.Polygon(points: Array([(0, 0), (10, 5), (10, 0), (0, 5)])).isSelfIntersecting) == true expect(Metron.Polygon(points: Array([(0, 0), (10, 0), (10, 5), (0, 5)])).isSelfIntersecting) == false } it("can calculate area") { expect(Metron.Polygon(points: Array([(0, 0), (10, 0), (10, 5)])).area) == 25 expect(Metron.Polygon(points: Array([(0, 0), (10, 0), (10, 5), (0, 5)])).area) == 50 expect(Metron.Polygon(points: Array([(0, 0), (10, 5), (10, 0), (0, 5)])).area.isNaN) == true // Self-intersecting polygon area is not available. } } }
mit
aed7e6e8bc04e54dab15f0e608b8306a
46.075
206
0.541689
3.11755
false
false
false
false
flassa/cordova-plugin-geofence
src/ios/GeofencePlugin.swift
3
16188
// // GeofencePlugin.swift // ionic-geofence // // Created by tomasz on 07/10/14. // // import Foundation import AudioToolbox let TAG = "GeofencePlugin" let iOS8 = floor(NSFoundationVersionNumber) > floor(NSFoundationVersionNumber_iOS_7_1) let iOS7 = floor(NSFoundationVersionNumber) <= floor(NSFoundationVersionNumber_iOS_7_1) func log(message: String){ NSLog("%@ - %@", TAG, message) } @objc(HWPGeofencePlugin) class GeofencePlugin : CDVPlugin { var isDeviceReady: Bool = false let geoNotificationManager = GeoNotificationManager() let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT override func pluginInitialize () { NSNotificationCenter.defaultCenter().addObserver( self, selector: "didReceiveLocalNotification:", name: "CDVLocalNotification", object: nil ) NSNotificationCenter.defaultCenter().addObserver( self, selector: "didReceiveTransition:", name: "handleTransition", object: nil ) } func initialize(command: CDVInvokedUrlCommand) { log("Plugin initialization") //let faker = GeofenceFaker(manager: geoNotificationManager) //faker.start() if iOS8 { promptForNotificationPermission() } var pluginResult = CDVPluginResult(status: CDVCommandStatus_OK) commandDelegate.sendPluginResult(pluginResult, callbackId: command.callbackId) } func ping(command: CDVInvokedUrlCommand) { log("Ping") var pluginResult = CDVPluginResult(status: CDVCommandStatus_OK) commandDelegate.sendPluginResult(pluginResult, callbackId: command.callbackId) } func promptForNotificationPermission() { UIApplication.sharedApplication().registerUserNotificationSettings(UIUserNotificationSettings( forTypes: UIUserNotificationType.Sound | UIUserNotificationType.Alert | UIUserNotificationType.Badge, categories: nil ) ) } func addOrUpdate(command: CDVInvokedUrlCommand) { dispatch_async(dispatch_get_global_queue(priority, 0)) { // do some task for geo in command.arguments { self.geoNotificationManager.addOrUpdateGeoNotification(JSON(geo)) } dispatch_async(dispatch_get_main_queue()) { var pluginResult = CDVPluginResult(status: CDVCommandStatus_OK) self.commandDelegate.sendPluginResult(pluginResult, callbackId: command.callbackId) } } } func deviceReady(command: CDVInvokedUrlCommand) { isDeviceReady = true var pluginResult = CDVPluginResult(status: CDVCommandStatus_OK) commandDelegate.sendPluginResult(pluginResult, callbackId: command.callbackId) } func getWatched(command: CDVInvokedUrlCommand) { dispatch_async(dispatch_get_global_queue(priority, 0)) { var watched = self.geoNotificationManager.getWatchedGeoNotifications()! let watchedJsonString = watched.description dispatch_async(dispatch_get_main_queue()) { var pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAsString: watchedJsonString) self.commandDelegate.sendPluginResult(pluginResult, callbackId: command.callbackId) } } } func remove(command: CDVInvokedUrlCommand) { dispatch_async(dispatch_get_global_queue(priority, 0)) { for id in command.arguments { self.geoNotificationManager.removeGeoNotification(id as! String) } dispatch_async(dispatch_get_main_queue()) { var pluginResult = CDVPluginResult(status: CDVCommandStatus_OK) self.commandDelegate.sendPluginResult(pluginResult, callbackId: command.callbackId) } } } func removeAll(command: CDVInvokedUrlCommand) { dispatch_async(dispatch_get_global_queue(priority, 0)) { self.geoNotificationManager.removeAllGeoNotifications() dispatch_async(dispatch_get_main_queue()) { var pluginResult = CDVPluginResult(status: CDVCommandStatus_OK) self.commandDelegate.sendPluginResult(pluginResult, callbackId: command.callbackId) } } } func didReceiveTransition (notification: NSNotification) { log("didReceiveTransition") if let geoNotificationString = notification.object as? String { let geoNotification = JSON(geoNotificationString) var mustBeArray = [JSON]() mustBeArray.append(geoNotification) let js = "setTimeout('geofence.onTransitionReceived(" + mustBeArray.description + ")',0)" evaluateJs(js) } } func didReceiveLocalNotification (notification: NSNotification) { log("didReceiveLocalNotification") if UIApplication.sharedApplication().applicationState != UIApplicationState.Active { var data = "undefined" if let uiNotification = notification.object as? UILocalNotification { if let notificationData = uiNotification.userInfo?["geofence.notification.data"] as? String { data = notificationData } let js = "setTimeout('geofence.onNotificationClicked(" + data + ")',0)" evaluateJs(js) } } } func evaluateJs (script: String) { if webView != nil { webView.stringByEvaluatingJavaScriptFromString(script) } else { log("webView is null") } } } // class for faking crossing geofences class GeofenceFaker { let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT let geoNotificationManager: GeoNotificationManager init(manager: GeoNotificationManager) { geoNotificationManager = manager } func start() { dispatch_async(dispatch_get_global_queue(priority, 0)) { while (true) { log("FAKER") let notify = arc4random_uniform(4) if notify == 0 { log("FAKER notify chosen, need to pick up some region") var geos = self.geoNotificationManager.getWatchedGeoNotifications()! if geos.count > 0 { //WTF Swift?? let index = arc4random_uniform(UInt32(geos.count)) var geo = geos[Int(index)] let id = geo["id"].asString! dispatch_async(dispatch_get_main_queue()) { if let region = self.geoNotificationManager.getMonitoredRegion(id) { log("FAKER Trigger didEnterRegion") self.geoNotificationManager.locationManager( self.geoNotificationManager.locationManager, didEnterRegion: region ) } } } } NSThread.sleepForTimeInterval(3) } } } func stop() { } } class GeoNotificationManager : NSObject, CLLocationManagerDelegate { let locationManager = CLLocationManager() let store = GeoNotificationStore() override init() { log("GeoNotificationManager init") super.init() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest if (!CLLocationManager.locationServicesEnabled()) { log("Location services is not enabled") } else { log("Location services enabled") } if iOS8 { locationManager.requestAlwaysAuthorization() } if (!CLLocationManager.isMonitoringAvailableForClass(CLRegion)) { log("Geofencing not available") } } func addOrUpdateGeoNotification(geoNotification: JSON) { log("GeoNotificationManager addOrUpdate") if (!CLLocationManager.locationServicesEnabled()) { log("Locationservices is not enabled") } var location = CLLocationCoordinate2DMake( geoNotification["latitude"].asDouble!, geoNotification["longitude"].asDouble! ) log("AddOrUpdate geo: \(geoNotification)") var radius = geoNotification["radius"].asDouble! as CLLocationDistance //let uuid = NSUUID().UUIDString let id = geoNotification["id"].asString var region = CLCircularRegion( circularRegionWithCenter: location, radius: radius, identifier: id ) var transitionType = 0 if let i = geoNotification["transitionType"].asInt { transitionType = i } region.notifyOnEntry = 0 != transitionType & 1 region.notifyOnExit = 0 != transitionType & 2 //store store.addOrUpdate(geoNotification) locationManager.startMonitoringForRegion(region) } func getWatchedGeoNotifications() -> [JSON]? { return store.getAll() } func getMonitoredRegion(id: String) -> CLRegion? { for object in locationManager.monitoredRegions { let region = object as! CLRegion if (region.identifier == id) { return region } } return nil } func removeGeoNotification(id: String) { store.remove(id) var region = getMonitoredRegion(id) if (region != nil) { log("Stoping monitoring region \(id)") locationManager.stopMonitoringForRegion(region) } } func removeAllGeoNotifications() { store.clear() for object in locationManager.monitoredRegions { let region = object as! CLRegion log("Stoping monitoring region \(region.identifier)") locationManager.stopMonitoringForRegion(region) } } func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) { log("update location") } func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) { log("fail with error: \(error)") } func locationManager(manager: CLLocationManager!, didFinishDeferredUpdatesWithError error: NSError!) { log("deferred fail error: \(error)") } func locationManager(manager: CLLocationManager!, didEnterRegion region: CLRegion!) { log("Entering region \(region.identifier)") handleTransition(region) } func locationManager(manager: CLLocationManager!, didExitRegion region: CLRegion!) { log("Exiting region \(region.identifier)") handleTransition(region) } func locationManager(manager: CLLocationManager!, didStartMonitoringForRegion region: CLRegion!) { let lat = (region as! CLCircularRegion).center.latitude let lng = (region as! CLCircularRegion).center.longitude let radius = (region as! CLCircularRegion).radius log("Starting monitoring for region \(region) lat \(lat) lng \(lng)") } func locationManager(manager: CLLocationManager, didDetermineState state: CLRegionState, forRegion region: CLRegion) { log("State for region " + region.identifier) } func locationManager(manager: CLLocationManager, monitoringDidFailForRegion region: CLRegion!, withError error: NSError!) { log("Monitoring region " + region.identifier + " failed " + error.description) } func handleTransition(region: CLRegion!) { if let geo = store.findById(region.identifier) { if let notification = geo["notification"].asDictionary { notifyAbout(geo) } NSNotificationCenter.defaultCenter().postNotificationName("handleTransition", object: geo.description) } } func notifyAbout(geo: JSON) { log("Creating notification") var notification = UILocalNotification() notification.timeZone = NSTimeZone.defaultTimeZone() var dateTime = NSDate() notification.fireDate = dateTime notification.soundName = UILocalNotificationDefaultSoundName notification.alertBody = geo["notification"]["text"].asString! if let json = geo["notification"]["data"] as? JSON { notification.userInfo = ["geofence.notification.data": json.description] } UIApplication.sharedApplication().scheduleLocalNotification(notification) if let vibrate = geo["notification"]["vibrate"].asArray { if (!vibrate.isEmpty && vibrate[0].asInt > 0) { AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate)) } } } } class GeoNotificationStore { init() { createDBStructure() } func createDBStructure() { let (tables, err) = SD.existingTables() if (err != nil) { log("Cannot fetch sqlite tables: \(err)") return } if (tables.filter { $0 == "GeoNotifications" }.count == 0) { if let err = SD.executeChange("CREATE TABLE GeoNotifications (ID TEXT PRIMARY KEY, Data TEXT)") { //there was an error during this function, handle it here log("Error while creating GeoNotifications table: \(err)") } else { //no error, the table was created successfully log("GeoNotifications table was created successfully") } } } func addOrUpdate(geoNotification: JSON) { if (findById(geoNotification["id"].asString!) != nil) { update(geoNotification) } else { add(geoNotification) } } func add(geoNotification: JSON) { let id = geoNotification["id"].asString! let err = SD.executeChange("INSERT INTO GeoNotifications (Id, Data) VALUES(?, ?)", withArgs: [id, geoNotification.description]) if err != nil { log("Error while adding \(id) GeoNotification: \(err)") } } func update(geoNotification: JSON) { let id = geoNotification["id"].asString! let err = SD.executeChange("UPDATE GeoNotifications SET Data = ? WHERE Id = ?", withArgs: [geoNotification.description, id]) if err != nil { log("Error while adding \(id) GeoNotification: \(err)") } } func findById(id: String) -> JSON? { let (resultSet, err) = SD.executeQuery("SELECT * FROM GeoNotifications WHERE Id = ?", withArgs: [id]) if err != nil { //there was an error during the query, handle it here log("Error while fetching \(id) GeoNotification table: \(err)") return nil } else { if (resultSet.count > 0) { return JSON(string: resultSet[0]["Data"]!.asString()!) } else { return nil } } } func getAll() -> [JSON]? { let (resultSet, err) = SD.executeQuery("SELECT * FROM GeoNotifications") if err != nil { //there was an error during the query, handle it here log("Error while fetching from GeoNotifications table: \(err)") return nil } else { var results = [JSON]() for row in resultSet { if let data = row["Data"]?.asString() { results.append(JSON(string: data)) } } return results } } func remove(id: String) { let err = SD.executeChange("DELETE FROM GeoNotifications WHERE Id = ?", withArgs: [id]) if err != nil { log("Error while removing \(id) GeoNotification: \(err)") } } func clear() { let err = SD.executeChange("DELETE FROM GeoNotifications") if err != nil { log("Error while deleting all from GeoNotifications: \(err)") } } }
apache-2.0
a289416cbd8301a479d117faa0d57447
34.114967
127
0.60514
5.288468
false
false
false
false
shhuangtwn/ProjectLynla
Pods/FacebookCore/Sources/Core/AppEvents/AppEventName.swift
2
5685
// Copyright (c) 2016-present, Facebook, Inc. All rights reserved. // // You are hereby granted a non-exclusive, worldwide, royalty-free license to use, // copy, modify, and distribute this software in source code or binary form for use // in connection with the web services and APIs provided by Facebook. // // As with any software that integrates with the Facebook platform, your use of // this software is subject to the Facebook Developer Principles and Policies // [http://developers.facebook.com/policy/]. This copyright 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 FBSDKCoreKit.FBSDKAppEvents /** Represents a name of the Facebook Analytics application event. Could either be one of built-in names or a custom `String`. - seealso: AppEvent - seealso: AppEventLoggable */ public enum AppEventName { // MARK: General /// Name of the event that indicates that the user has completed a registration. case CompletedRegistration /// Name of the event that indicates that the user has completed a tutorial. case CompletedTutorial /// Name of the event that indicates that the user has viewed a content. case ViewedContent /// Name of the event that indicates that the user has performed search within the application. case Searched /// Name of the event that indicates that the user has has rated an item in the app. case Rated // MARK: Commerce /// Name of the event that indicates that the user has purchased something in the application. case Purchased /// Name of the event that indicates that the user has added an item to the cart. case AddedToCart /// Name of the event that indicates that the user has added an item to the wishlist. case AddedToWishlist /// Name of the event that indicates that the user has added payment information. case AddedPaymentInfo /// Name of the event that indicates that the user has initiated a checkout. case InitiatedCheckout // MARK: Gaming /// Name of the event that indicates that the user has achieved a level. case AchievedLevel /// Name of the event that indicates that the user has unlocked an achievement. case UnlockedAchievement /// Name of the event that indicates that the user has spent in-app credits. case SpentCredits // MARK: Custom /// Custom name of the event that is represented by a string. case Custom(String) /** Create an `AppEventName` from `String`. - parameter string: String to create an app event name from. */ public init(_ string: String) { self = .Custom(string) } } extension AppEventName: RawRepresentable { /** Create an `AppEventName` from `String`. - parameter rawValue: String to create an app event name from. */ public init?(rawValue: String) { self = .Custom(rawValue) } /// The corresponding `String` value. public var rawValue: String { switch self { case .CompletedRegistration: return FBSDKAppEventNameCompletedRegistration case .CompletedTutorial: return FBSDKAppEventNameCompletedTutorial case .ViewedContent: return FBSDKAppEventNameViewedContent case .Searched: return FBSDKAppEventNameSearched case .Rated: return FBSDKAppEventNameRated case .Purchased: return "fb_mobile_purchase" // Hard-coded as a string, since it's internal API of FBSDKCoreKit. case .AddedToCart: return FBSDKAppEventNameAddedToCart case .AddedToWishlist: return FBSDKAppEventNameAddedToWishlist case .AddedPaymentInfo: return FBSDKAppEventNameAddedPaymentInfo case .InitiatedCheckout: return FBSDKAppEventNameInitiatedCheckout case .AchievedLevel: return FBSDKAppEventNameAchievedLevel case .UnlockedAchievement: return FBSDKAppEventNameUnlockedAchievement case .SpentCredits: return FBSDKAppEventNameSpentCredits case .Custom(let string): return string } } } extension AppEventName: StringLiteralConvertible { /** Create an `AppEventName` from a string literal. - parameter value: The string literal to create from. */ public init(stringLiteral value: StringLiteralType) { self = .Custom(value) } /** Create an `AppEventName` from a unicode scalar literal. - parameter value: The string literal to create from. */ public init(unicodeScalarLiteral value: String) { self.init(stringLiteral: value) } /** Create an `AppEventName` from an extended grapheme cluster. - parameter value: The string literal to create from. */ public init(extendedGraphemeClusterLiteral value: String) { self.init(stringLiteral: value) } } extension AppEventName: Hashable { /// The hash value. public var hashValue: Int { return self.rawValue.hashValue } } extension AppEventName: CustomStringConvertible { /// Textual representation of an app event name. public var description: String { return rawValue } } /** Compare two `AppEventName`s for equality. - parameter lhs: The first app event name to compare. - parameter rhs: The second app event name to compare. - returns: Whether or not the app event names are equal. */ public func == (lhs: AppEventName, rhs: AppEventName) -> Bool { return lhs.rawValue == rhs.rawValue }
mit
bc110c75ccdbaec15a8efbbe336cf8b1
33.041916
116
0.745295
4.573612
false
false
false
false
stomp1128/TIY-Assignments
04-OutaTime/04-OutaTime/TimeCircuitsViewController.swift
1
3083
// // TimeCircuitsViewController.swift // 04-OutaTime // // Created by Chris Stomp on 11/5/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import UIKit @objc protocol DatePickerDelegate { func dateWasChosen(date: NSDate) } class TimeCircuitsViewController: UIViewController, DatePickerDelegate { @IBOutlet weak var destinationTimeLabel: UILabel! @IBOutlet weak var presentTimeLabel: UILabel! @IBOutlet weak var lastTimeDepartedLabel: UILabel! @IBOutlet weak var speedLabel: UILabel! var timer: NSTimer? var currentSpeed = 0 let dateFormatter = NSDateFormatter() override func viewDidLoad() { super.viewDidLoad() title = "Time Circuits" let dateString = formatTime(NSDate()) destinationTimeLabel.text = "_ _ _ _ _ _ _ _ _" presentTimeLabel.text = dateString speedLabel.text = "\(currentSpeed) MPH" lastTimeDepartedLabel.text = "_ _ _ _ _ _ _ _ _" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "ShowDatePickerSegue" { let datePickerVC = segue.destinationViewController as! DatePickerViewController datePickerVC.delegate = self } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ @IBAction func travelBackTapped(sender: UIButton) { startTimer() updateSpeed() } func formatTime(timeToFormat: NSDate) -> String { self.dateFormatter.dateStyle = .MediumStyle dateFormatter.dateFormat = "MMM dd, yyyy" let formattedTime = dateFormatter.stringFromDate(timeToFormat) return String(formattedTime) } func dateWasChosen(date: NSDate) { destinationTimeLabel.text = dateFormatter.stringFromDate(date) } func startTimer() { if timer == nil { timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "updateSpeed", userInfo: nil, repeats: true) } } func updateSpeed() { if currentSpeed < 88 { currentSpeed += 1 speedLabel.text = String(currentSpeed) } else { stopTimer() } } func stopTimer() { timer?.invalidate() speedLabel.text = "0" //String(currentSpeed) presentTimeLabel.text = destinationTimeLabel.text lastTimeDepartedLabel.text = formatTime(NSDate()) } }
cc0-1.0
94b50501c9cfcfebcbdfbea65265b3b3
24.471074
131
0.615185
5.035948
false
false
false
false
kumabook/FeedlyKit
Source/Feed.swift
1
4108
// // Feed.swift // MusicFav // // Created by Hiroki Kumamoto on 1/4/15. // Copyright (c) 2015 Hiroki Kumamoto. All rights reserved. // import Foundation import SwiftyJSON public final class Feed: Stream, ResponseObjectSerializable, ResponseCollectionSerializable { public var id: String public var subscribers: Int public var title: String public var description: String? public var language: String? public var velocity: Float? public var website: String? public var topics: [String]? public var status: String? public var curated: Bool? public var featured: Bool? public var lastUpdated: Int64? public var visualUrl: String? public var iconUrl: String? public var coverUrl: String? public var facebookUsername: String? public var facebookLikes: Int? public var twitterScreenName: String? public var twitterFollowers: String? public var contentType: String? public var coverColor: String? public var partial: Bool? public var hint: String? public var score: Float? public var scheme: String? public var estimatedEngagement: Int? public var websiteTitle: String? public var deliciousTags: [String]? public override var streamId: String { return id } public override var streamTitle: String { return title } public class func collection(_ response: HTTPURLResponse, representation: Any) -> [Feed]? { let json = JSON(representation) return json.arrayValue.map({ Feed(json: $0) }) } @objc required public convenience init?(response: HTTPURLResponse, representation: Any) { let json = JSON(representation) self.init(json: json) } public init(id: String, title: String, description: String, subscribers: Int) { self.id = id self.title = title self.description = description self.subscribers = subscribers } public init(json: JSON) { if let fid = json["id"].string { id = fid } else if let fid = json["feedId"].string { id = fid } else { id = "unknownId" } subscribers = json["subscribers"].intValue title = json["title"].stringValue description = json["description"].string language = json["language"].string velocity = json["velocity"].float website = json["website"].string topics = json["topics"].array?.map({ $0.stringValue }) status = json["status"].string curated = json["curated"].bool featured = json["featured"].bool lastUpdated = json["lastUpdated"].int64 visualUrl = json["visualUrl"].string iconUrl = json["iconUrl"].string coverUrl = json["coverUrl"].string facebookUsername = json["facebookUsername"].string facebookLikes = json["facebookLikes"].int twitterScreenName = json["twitterScreenName"].string twitterFollowers = json["twitterFollowers"].string contentType = json["contentType"].string coverColor = json["coverColor"].string partial = json["partial"].bool hint = json["hint"].string score = json["score"].float scheme = json["scheme"].string estimatedEngagement = json["estimatedEngagement"].int websiteTitle = json["websiteTitle"].string deliciousTags = json["deliciousTags"].array?.map({ $0.stringValue }) } public override var thumbnailURL: URL? { if let url = visualUrl { return URL(string: url) } else if let url = coverUrl { return URL(string: url) } else if let url = iconUrl { return URL(string: url) } else { return nil } } }
mit
9d11e97bcd3468eceaff86a4aaba9c15
33.813559
95
0.580818
4.75463
false
false
false
false
JamesBirchall/udemyiossamples
Pokedex/Pokedex/PokemonDetailViewController.swift
1
5154
// // PokemonDetailViewController.swift // Pokedex // // Created by James Birchall on 28/07/2017. // Copyright © 2017 James Birchall. All rights reserved. // import UIKit import AVFoundation class PokemonDetailViewController: UIViewController { // MARK: - IBOutlets @IBOutlet weak var pokemonNameLabel: UILabel! @IBOutlet weak var musicIconImageView: UIImageView! @IBOutlet weak var backIconImageView: UIImageView! @IBOutlet weak var pokemonMainImageView: UIImageView! @IBOutlet weak var pokemonDescriptionTextView: UITextView! @IBOutlet weak var pokemonTypeLabel: UILabel! @IBOutlet weak var pokemonHeightLabel: UILabel! @IBOutlet weak var pokemonWeightLabel: UILabel! @IBOutlet weak var pokemonDefenceLabel: UILabel! @IBOutlet weak var pokemonIDLabel: UILabel! @IBOutlet weak var pokemonBaseAttackLabel: UILabel! @IBOutlet weak var pokemonNextEvolutionLabel: UILabel! @IBOutlet weak var pokemonCurrentEvolutionImageView: UIImageView! @IBOutlet weak var pokemonNextEvolutionImageView: UIImageView! @IBOutlet weak var activitySpinner: UIActivityIndicatorView! // MARK: - Private Variables private var _pokemon: Pokemon! private var _audioPlayer: AVAudioPlayer! fileprivate let showPokemonDetail = "showPokemonDetail" // MARK: - Public Variables var pokemon: Pokemon { get { return _pokemon } set { _pokemon = newValue } } var audioPlayer: AVAudioPlayer { get { return _audioPlayer } set { _audioPlayer = newValue } } // MARK: - ViewController Overrides override func viewDidLoad() { super.viewDidLoad() activitySpinner.startAnimating() UIApplication.shared.isNetworkActivityIndicatorVisible = true pokemon.downloadPokemonDetails { [weak self] in // Code here for completion // print("Download Pokemon Details Returned.") DispatchQueue.main.async { self?.updateUI() } self?.pokemon.downloadPokemonDescription { // print("Download Pokemon Description Returned.") DispatchQueue.main.async { UIApplication.shared.isNetworkActivityIndicatorVisible = false self?.updateDescription() self?.activitySpinner.stopAnimating() } } } initTouchOnMusicIconImageView() initTouchOnBackIconImageView() if !audioPlayer.isPlaying { musicIconImageView.alpha = 0.4 } pokemonNameLabel.text = _pokemon.name pokemonIDLabel.text = "\(_pokemon.pokedexID)" pokemonMainImageView.image = UIImage(named: "\(_pokemon.pokedexID)") pokemonCurrentEvolutionImageView.image = UIImage(named: "\(_pokemon.pokedexID)") } // MARK: - Private Methods private func updateUI() { pokemonTypeLabel.text = pokemon.type pokemonHeightLabel.text = "\(pokemon.height)" pokemonWeightLabel.text = "\(pokemon.weight)" pokemonBaseAttackLabel.text = "\(pokemon.attack)" pokemonDefenceLabel.text = "\(pokemon.defense)" if pokemon.nextEvolutionPokedexID == 0 || pokemon.nextEvolutionPokedexID > 1000 { pokemonNextEvolutionLabel.text = "No evolution" pokemonNextEvolutionImageView.isHidden = true } else { pokemonNextEvolutionLabel.text = pokemon.nextEvolution pokemonNextEvolutionImageView.image = UIImage(named: "\(pokemon.nextEvolutionPokedexID)") pokemonNextEvolutionImageView.isHidden = false } // print("Label and UI Updates Completed.") } private func updateDescription() { pokemonDescriptionTextView.text = pokemon.description } private func initTouchOnMusicIconImageView() { let tapGestureRegocogniser = UITapGestureRecognizer(target: self, action: #selector(musicIconPressed(gestureRecogniser:))) musicIconImageView.isUserInteractionEnabled = true musicIconImageView.addGestureRecognizer(tapGestureRegocogniser) } private func initTouchOnBackIconImageView() { let tapGestureRegocogniser = UITapGestureRecognizer(target: self, action: #selector(backIconPressed(gestureRecogniser:))) backIconImageView.isUserInteractionEnabled = true backIconImageView.addGestureRecognizer(tapGestureRegocogniser) } // MARK: - Public Methods func musicIconPressed(gestureRecogniser: UITapGestureRecognizer) { if audioPlayer.isPlaying { audioPlayer.pause() musicIconImageView.alpha = 0.4 } else { audioPlayer.play() musicIconImageView.alpha = 1 } } func backIconPressed(gestureRecogniser: UITapGestureRecognizer) { dismiss(animated: true, completion: nil) } }
apache-2.0
fb6d6c3057a3fd6b9c3d2dda93f42439
32.679739
130
0.644867
5.418507
false
false
false
false
honghaoz/CrackingTheCodingInterview
Swift/LeetCode/Divide and Conquer/973_K Closest Points to Origin.swift
1
1972
// 973_K Closest Points to Origin // https://leetcode.com/problems/k-closest-points-to-origin // // Created by Honghao Zhang on 10/20/19. // Copyright © 2019 Honghaoz. All rights reserved. // // Description: // We have a list of points on the plane. Find the K closest points to the origin (0, 0). // //(Here, the distance between two points on a plane is the Euclidean distance.) // //You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in.) // // // //Example 1: // //Input: points = [[1,3],[-2,2]], K = 1 //Output: [[-2,2]] //Explanation: //The distance between (1, 3) and the origin is sqrt(10). //The distance between (-2, 2) and the origin is sqrt(8). //Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin. //We only want the closest K = 1 points from the origin, so the answer is just [[-2,2]]. //Example 2: // //Input: points = [[3,3],[5,-1],[-2,4]], K = 2 //Output: [[3,3],[-2,4]] //(The answer [[-2,4],[3,3]] would also be accepted.) // // //Note: // //1 <= K <= points.length <= 10000 //-10000 < points[i][0] < 10000 //-10000 < points[i][1] < 10000 // // 找出离(0, 0)点最近的K个点 import Foundation class Num973 { // MARK: - Just sort for the first K elements // Then return the first K // TODO: 实现一遍partition!!! // https://leetcode.com/problems/k-closest-points-to-origin/discuss/367728/swift-quick-select /// Get the distance squared ( to the second power) private func distance(_ point: [Int]) -> Int { return point[0] * point[0] + point[1] * point[1] } // MARK: - Sort and return the first K // O(n lg n) // There's extra work for elements in range K... No need to sort them func kClosest_sort(_ points: [[Int]], _ K: Int) -> [[Int]] { let sorted = points.sorted(by: { (p1: [Int], p2: [Int]) -> Bool in return (p1[0] * p1[0] + p1[1] * p1[1]) < (p2[0] * p2[0] + p2[1] * p2[1]) }).prefix(K) return Array(sorted) } }
mit
7b06abc0842abcef93c9645d5ed72d44
29.296875
118
0.616297
2.915789
false
false
false
false
Ryce/flickrpickr
Carthage/Checkouts/judokit/Tests/CardDetailsSetTests.swift
2
3404
// // CardDetailsSetTests.swift // JudoKit // // Copyright (c) 2016 Alternative Payments Ltd // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import XCTest @testable import JudoKit class CardDetailsSetTests : JudoTestCase { func testCardDetailsMustBePresent() { let cardDetails = getCardDetails() let jpvc = getJudoPayViewController(cardDetails, paymentToken: nil) let cardInputField = jpvc.myView.cardInputField let expiryDateInputField = jpvc.myView.expiryDateInputField XCTAssertEqual("4976 0000 0000 3436", cardInputField.textField.text) XCTAssertEqual("12/20", expiryDateInputField.textField.text) } func testCardDetailsMustBeMasked() { let cardDetails = getCardDetails() let paymentToken = getPaymentToken() let jpvc = getJudoPayViewController(cardDetails, paymentToken: paymentToken) let cardInputField = jpvc.myView.cardInputField let expiryDateInputField = jpvc.myView.expiryDateInputField XCTAssertEqual("**** **** **** 3436", cardInputField.textField.text) XCTAssertEqual("12/20", expiryDateInputField.textField.text) } func testCardDetailsMustBeNotPresent() { let paymentToken = getPaymentToken() let jpvc = getJudoPayViewController(nil, paymentToken: paymentToken) let cardInputField = jpvc.myView.cardInputField let expiryDateInputField = jpvc.myView.expiryDateInputField XCTAssertEqual("", cardInputField.textField.text) XCTAssertEqual("", expiryDateInputField.textField.text) } fileprivate func getCardDetails() -> CardDetails{ return CardDetails(cardNumber: "4976000000003436", expiryMonth: 12, expiryYear: 20) } fileprivate func getPaymentToken() -> PaymentToken{ return PaymentToken(consumerToken: "MY CONSUMER TOKEN", cardToken: "MY CARD TOKEN") } fileprivate func getJudoPayViewController(_ cardDetails: CardDetails?, paymentToken: PaymentToken?) -> JudoPayViewController{ return try! JudoPayViewController(judoId: myJudoId, amount: oneGBPAmount, reference: validReference, transactionType: .Payment, completion: {_ in}, currentSession: judo, cardDetails: cardDetails, paymentToken: paymentToken) } }
mit
ce8702d3703fa187955e9550a8bdb3a0
42.088608
231
0.715629
4.835227
false
true
false
false
optimistapp/optimistapp
Optimist/beamAnnotation.swift
1
1227
// // beamAnnotation.swift // optimismMap // // Created by Johnson Zhou on 1/31/15. // Copyright (c) 2015 Optimist. All rights reserved. // import Foundation import MapKit class beamAnnotation:NSObject,MKAnnotation { var coordinate:CLLocationCoordinate2D var msg:String var locked = true init(msg:String, location:CLLocationCoordinate2D) { coordinate = location self.msg = msg } //annotation for unlocked item func annotationViewUnlocked() -> MKAnnotationView{ var annotationView = MKAnnotationView(annotation: self, reuseIdentifier: "AnnoUnlock") annotationView.enabled = true annotationView.canShowCallout = false annotationView.image = UIImage(named: "unlocked.png") self.locked = false return annotationView } //annotation for locked item func annotationViewLocked() -> MKAnnotationView{ var annotationView = MKAnnotationView(annotation: self, reuseIdentifier: "AnnoLock") annotationView.enabled = true annotationView.canShowCallout = false annotationView.image = UIImage(named:"locked.png") self.locked = true return annotationView } }
apache-2.0
19ef770715880a8b2f08a06e21bdd24e
27.55814
94
0.678892
5.049383
false
false
false
false
BBBInc/AlzPrevent-ios
researchline/DrawImageView.swift
1
1646
// // SignatureView.swift // researchline // // Created by Leo Kang on 11/15/15. // Copyright © 2015 bbb. All rights reserved. // import UIKit class DrawImageView: UIImageView { var swiped = false var lastPoint = CGPoint.zero var signed = false func drawLineFrom(fromPoint: CGPoint, toPoint: CGPoint) { // 1 UIGraphicsBeginImageContext(frame.size) let context = UIGraphicsGetCurrentContext() image?.drawInRect(bounds) // 2 CGContextMoveToPoint(context!, fromPoint.x, fromPoint.y) CGContextAddLineToPoint(context!, toPoint.x, toPoint.y) // 3 CGContextSetLineCap(context!, CGLineCap.Square) CGContextSetLineWidth(context!, 1) CGContextSetBlendMode(context!, CGBlendMode.Normal) // 4 CGContextStrokePath(context!) // 5 image = UIGraphicsGetImageFromCurrentImageContext() alpha = 1 UIGraphicsEndImageContext() } // MARK: UIResponder Methods override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { swiped = false if let touch = touches.first { lastPoint = touch.locationInView(self) } } override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { signed = true swiped = true if let touch = touches.first { let currentPoint = touch.locationInView(self) drawLineFrom(lastPoint, toPoint: currentPoint) lastPoint = currentPoint } } }
bsd-3-clause
5bc6cef2efbf6f6bb3e590541e7d3ad5
25.532258
82
0.599392
5.393443
false
false
false
false
bcylin/QuickTableViewController
Source/Protocol/Reusable.swift
1
2494
// // Reusable.swift // QuickTableViewController // // Created by Ben on 21/08/2017. // Copyright © 2017 bcylin. // // 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 extension UITableViewCell: Reusable {} internal protocol Reusable { static var reuseIdentifier: String { get } } internal extension Reusable { static var reuseIdentifier: String { let type = String(describing: self) return type.matches(of: String.typeDescriptionPattern).last ?? type } } // MARK: - internal extension String { static var typeDescriptionPattern: String { // For the types in the format of "(CustomCell in _B5334F301B8CC6AA00C64A6D)" return "^\\(([\\w\\d]+)\\sin\\s_[0-9A-F]+\\)$" } func matches(of pattern: String) -> [String] { let regex = try? NSRegularExpression(pattern: pattern, options: .caseInsensitive) #if swift(>=3.2) let fullText = NSRange(location: 0, length: count) #else let fullText = NSRange(location: 0, length: characters.count) #endif guard let matches = regex?.matches(in: self, options: [], range: fullText) else { return [] } return matches.reduce([]) { accumulator, match in accumulator + (0..<match.numberOfRanges).map { #if swift(>=4) return (self as NSString).substring(with: match.range(at: $0)) #else return (self as NSString).substring(with: match.rangeAt($0)) #endif } } } }
mit
7f2c6f06a0d3a98559059142d56b1dce
31.802632
85
0.692339
4.040519
false
false
false
false
github/Nimble
Nimble/Matchers/Equal.swift
77
3835
import Foundation public func equal<T: Equatable>(expectedValue: T?) -> MatcherFunc<T> { return MatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "equal <\(stringify(expectedValue))>" let matches = actualExpression.evaluate() == expectedValue && expectedValue != nil if expectedValue == nil || actualExpression.evaluate() == nil { failureMessage.postfixMessage += " (will not match nils, use beNil() instead)" return false } return matches } } // perhaps try to extend to SequenceOf or Sequence types instead of dictionaries public func equal<T: Equatable, C: Equatable>(expectedValue: [T: C]?) -> MatcherFunc<[T: C]> { return MatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "equal <\(stringify(expectedValue))>" if expectedValue == nil || actualExpression.evaluate() == nil { failureMessage.postfixMessage += " (will not match nils, use beNil() instead)" return false } var expectedGen = expectedValue!.generate() var actualGen = actualExpression.evaluate()!.generate() var expectedItem = expectedGen.next() var actualItem = actualGen.next() var matches = elementsAreEqual(expectedItem, actualItem) while (matches && (actualItem != nil || expectedItem != nil)) { actualItem = actualGen.next() expectedItem = expectedGen.next() matches = elementsAreEqual(expectedItem, actualItem) } return matches } } // perhaps try to extend to SequenceOf or Sequence types instead of arrays public func equal<T: Equatable>(expectedValue: [T]?) -> MatcherFunc<[T]> { return MatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "equal <\(stringify(expectedValue))>" if expectedValue == nil || actualExpression.evaluate() == nil { failureMessage.postfixMessage += " (will not match nils, use beNil() instead)" return false } var expectedGen = expectedValue!.generate() var actualGen = actualExpression.evaluate()!.generate() var expectedItem = expectedGen.next() var actualItem = actualGen.next() var matches = actualItem == expectedItem while (matches && (actualItem != nil || expectedItem != nil)) { actualItem = actualGen.next() expectedItem = expectedGen.next() matches = actualItem == expectedItem } return matches } } public func ==<T: Equatable>(lhs: Expectation<T>, rhs: T?) { lhs.to(equal(rhs)) } public func !=<T: Equatable>(lhs: Expectation<T>, rhs: T?) { lhs.toNot(equal(rhs)) } public func ==<T: Equatable>(lhs: Expectation<[T]>, rhs: [T]?) { lhs.to(equal(rhs)) } public func !=<T: Equatable>(lhs: Expectation<[T]>, rhs: [T]?) { lhs.toNot(equal(rhs)) } public func ==<T: Equatable, C: Equatable>(lhs: Expectation<[T: C]>, rhs: [T: C]?) { lhs.to(equal(rhs)) } public func !=<T: Equatable, C: Equatable>(lhs: Expectation<[T: C]>, rhs: [T: C]?) { lhs.toNot(equal(rhs)) } extension NMBObjCMatcher { public class func equalMatcher(expected: NSObject) -> NMBMatcher { return NMBObjCMatcher { actualExpression, failureMessage, location in let expr = Expression(expression: actualExpression, location: location) return equal(expected).matches(expr, failureMessage: failureMessage) } } } internal func elementsAreEqual<T: Equatable, C: Equatable>(a: (T, C)?, b: (T, C)?) -> Bool { if a == nil || b == nil { return a == nil && b == nil } else { let (aKey, aValue) = a! let (bKey, bValue) = b! return (aKey == bKey && aValue == bValue) } }
apache-2.0
9885b4988286c63930fb14e4fe56b2eb
35.875
94
0.627901
4.459302
false
false
false
false
MukeshKumarS/Swift
test/Prototypes/CollectionsMoveIndices.swift
1
28187
// RUN: %target-run-simple-swift // REQUIRES: executable_test // https://bugs.swift.org/browse/SR-122 // // Summary // ======= // // This file implements a prototype for a collection model where // indices can't move themselves forward or backward. Instead, the // corresponding collection moves the indices. // // Problem // ======= // // In practice it has turned out that every one of our concrete // collection's non random-access indices holds a reference to the // collection it traverses. This introduces complexity in // implementations (especially as we try to avoid multiple-reference // effects that can cause unnecessary COW copies -- see `Dictionary` // and `Set`) and presumably translates into less-efficient codegen. // We should consider other schemes. // // Solution // ======== // // Change indices so that they can't be moved forward or backward by // themselves (`i.successor()`). Then indices can store the minimal // amount of information about the element position in the collection, // and avoid keeping a reference to the whole collection. public protocol MyGeneratorType { typealias Element mutating func next() -> Element? } public protocol MySequenceType { typealias Generator : MyGeneratorType typealias SubSequence /* : MySequenceType */ func generate() -> Generator @warn_unused_result func map<T>( @noescape transform: (Generator.Element) throws -> T ) rethrows -> [T] } extension MySequenceType { @warn_unused_result public func map<T>( @noescape transform: (Generator.Element) throws -> T ) rethrows -> [T] { var result: [T] = [] for element in OldSequence(self) { result.append(try transform(element)) } return result } } //------------------------------------------------------------------------ // Bridge between the old world and the new world struct OldSequence<S : MySequenceType> : SequenceType { let _base: S init(_ base: S) { self._base = base } func generate() -> OldGenerator<S.Generator> { return OldGenerator(_base.generate()) } } struct OldGenerator<G : MyGeneratorType> : GeneratorType { var _base: G init(_ base: G) { self._base = base } mutating func next() -> G.Element? { return _base.next() } } // End of the bridge //------------------------------------------------------------------------ public protocol MyIndexableType { typealias Index : MyIndexType typealias _Element typealias UnownedHandle var startIndex: Index { get } var endIndex: Index { get } subscript(i: Index) -> _Element { get } init(from handle: UnownedHandle) var unownedHandle: UnownedHandle { get } @warn_unused_result func next(i: Index) -> Index func _nextInPlace(inout i: Index) func _failEarlyRangeCheck(index: Index, bounds: MyRange<Index>) func _failEarlyRangeCheck2( rangeStart: Index, rangeEnd: Index, boundsStart: Index, boundsEnd: Index) } extension MyIndexableType { @inline(__always) public func _nextInPlace(inout i: Index) { i = next(i) } } public protocol MyForwardCollectionType : MySequenceType, MyIndexableType { typealias Generator = DefaultGenerator<Self> typealias Index : MyIndexType typealias SubSequence : MySequenceType /* : MyForwardCollectionType */ = MySlice<Self> typealias UnownedHandle = Self // DefaultUnownedForwardCollection<Self> typealias IndexRange : MyIndexRangeType, MySequenceType, MyIndexableType /* : MyForwardCollectionType */ // FIXME: where IndexRange.Generator.Element == Index // FIXME: where IndexRange.Index == Index = DefaultForwardIndexRange<Self> var startIndex: Index { get } var endIndex: Index { get } subscript(i: Index) -> Generator.Element { get } subscript(bounds: MyRange<Index>) -> SubSequence { get } init(from handle: UnownedHandle) var unownedHandle: UnownedHandle { get } @warn_unused_result func next(i: Index) -> Index @warn_unused_result func advance(i: Index, by: Index.Distance) -> Index @warn_unused_result func advance(i: Index, by: Index.Distance, limit: Index) -> Index @warn_unused_result func distanceFrom(start: Index, to: Index) -> Index.Distance func _failEarlyRangeCheck(index: Index, bounds: MyRange<Index>) func _failEarlyRangeCheck2( rangeStart: Index, rangeEnd: Index, boundsStart: Index, boundsEnd: Index) var indices: IndexRange { get } @warn_unused_result func _customIndexOfEquatableElement(element: Generator.Element) -> Index?? var first: Generator.Element? { get } var isEmpty: Bool { get } var count: Index.Distance { get } } extension MyForwardCollectionType // FIXME: this constraint shouldn't be necessary. where IndexRange.Index == Index { // FIXME: do we want this overload? Would we provide such an overload // for every method that accepts ranges of indices? // FIXME: can we have a generic subscript on MyIndexRangeType instead? public subscript(bounds: IndexRange) -> SubSequence { return self[MyRange(start: bounds.startIndex, end: bounds.endIndex)] } } extension MyForwardCollectionType { /// Do not use this method directly; call advancedBy(n) instead. @inline(__always) @warn_unused_result internal func _advanceForward(i: Index, by n: Index.Distance) -> Index { _precondition(n >= 0, "Only BidirectionalIndexType can be advanced by a negative amount") var i = i for var offset: Index.Distance = 0; offset != n; ++offset { _nextInPlace(&i) } return i } /// Do not use this method directly; call advancedBy(n, limit) instead. @inline(__always) @warn_unused_result internal func _advanceForward( i: Index, by n: Index.Distance, limit: Index ) -> Index { _precondition(n >= 0, "Only BidirectionalIndexType can be advanced by a negative amount") var i = i for var offset: Index.Distance = 0; offset != n && i != limit; ++offset { _nextInPlace(&i) } return i } @warn_unused_result public func advance(i: Index, by n: Index.Distance) -> Index { return self._advanceForward(i, by: n) } @warn_unused_result public func advance(i: Index, by n: Index.Distance, limit: Index) -> Index { return self._advanceForward(i, by: n, limit: limit) } @warn_unused_result public func distanceFrom(start: Index, to end: Index) -> Index.Distance { var start = start var count: Index.Distance = 0 while start != end { ++count _nextInPlace(&start) } return count } public func _failEarlyRangeCheck( index: Index, bounds: MyRange<Index>) { // Can't perform range checks in O(1) on forward indices. } public func _failEarlyRangeCheck2( rangeStart: Index, rangeEnd: Index, boundsStart: Index, boundsEnd: Index ) { // Can't perform range checks in O(1) on forward indices. } @warn_unused_result public func _customIndexOfEquatableElement( element: Generator.Element ) -> Index?? { return nil } public var first: Generator.Element? { return isEmpty ? nil : self[startIndex] } public var isEmpty: Bool { return startIndex == endIndex } public var count: Index.Distance { return distanceFrom(startIndex, to: endIndex) } } extension MyForwardCollectionType where Generator == DefaultGenerator<Self> { public func generate() -> DefaultGenerator<Self> { return DefaultGenerator(self) } } extension MyForwardCollectionType where UnownedHandle == Self // where UnownedHandle == DefaultUnownedForwardCollection<Self> { public init(from handle: UnownedHandle) { self = handle } public var unownedHandle: UnownedHandle { return self } } extension MyForwardCollectionType where SubSequence == MySlice<Self> { public subscript(bounds: MyRange<Index>) -> SubSequence { return MySlice(base: self, start: bounds.startIndex, end: bounds.endIndex) } } extension MyForwardCollectionType where IndexRange == DefaultForwardIndexRange<Self> { public var indices: IndexRange { return DefaultForwardIndexRange( collection: self, startIndex: startIndex, endIndex: endIndex) } } extension MyForwardCollectionType where Index : MyRandomAccessIndex { @warn_unused_result public func next(i: Index) -> Index { return advance(i, by: 1) } @warn_unused_result public func advance(i: Index, by n: Index.Distance) -> Index { _precondition(n >= 0, "Can't advance an Index of MyForwardCollectionType by a negative amount") return i.advancedBy(n) } @warn_unused_result public func advance(i: Index, by n: Index.Distance, limit: Index) -> Index { _precondition(n >= 0, "Can't advance an Index of MyForwardCollectionType by a negative amount") let d = i.distanceTo(limit) _precondition(d >= 0, "The specified limit is behind the index") if d <= n { return limit } return i.advancedBy(n) } } extension MyForwardCollectionType where Generator.Element : Equatable, IndexRange.Generator.Element == Index // FIXME { public func indexOf(element: Generator.Element) -> Index? { if let result = _customIndexOfEquatableElement(element) { return result } for i in OldSequence(self.indices) { if self[i] == element { return i } } return nil } public func indexOf_optimized(element: Generator.Element) -> Index? { if let result = _customIndexOfEquatableElement(element) { return result } var i = startIndex while i != endIndex { if self[i] == element { return i } _nextInPlace(&i) } return nil } } extension MyForwardCollectionType where SubSequence == Self { @warn_unused_result public mutating func popFirst() -> Generator.Element? { guard !isEmpty else { return nil } let element = first! self = self[MyRange(start: self.next(startIndex), end: endIndex)] return element } } public protocol MyBidirectionalCollectionType : MyForwardCollectionType { @warn_unused_result func previous(i: Index) -> Index func _previousInPlace(inout i: Index) } extension MyBidirectionalCollectionType { @inline(__always) public func _previousInPlace(inout i: Index) { i = previous(i) } @warn_unused_result public func advance(i: Index, by n: Index.Distance) -> Index { if n >= 0 { return _advanceForward(i, by: n) } var i = i for var offset: Index.Distance = n; offset != 0; ++offset { _previousInPlace(&i) } return i } @warn_unused_result public func advance(i: Index, by n: Index.Distance, limit: Index) -> Index { if n >= 0 { return _advanceForward(i, by: n, limit: limit) } var i = i for var offset: Index.Distance = n; offset != 0 && i != limit; ++offset { _previousInPlace(&i) } return i } } extension MyBidirectionalCollectionType where Index : MyRandomAccessIndex { @warn_unused_result public func previous(i: Index) -> Index { return advance(i, by: -1) } @warn_unused_result public func advance(i: Index, by n: Index.Distance) -> Index { return i.advancedBy(n) } @warn_unused_result public func advance(i: Index, by n: Index.Distance, limit: Index) -> Index { let d = i.distanceTo(limit) if d == 0 || (d > 0 ? d <= n : d >= n) { return limit } return i.advancedBy(n) } } public protocol MyRandomAccessCollectionType : MyBidirectionalCollectionType { typealias Index : MyRandomAccessIndex } public struct DefaultUnownedForwardCollection<Collection : MyForwardCollectionType> { internal let _collection: Collection public init(_ collection: Collection) { self._collection = collection } } public struct DefaultForwardIndexRange<Collection : MyIndexableType /* MyForwardCollectionType */> : MyForwardCollectionType, MyIndexRangeType { internal let _unownedCollection: Collection.UnownedHandle public let startIndex: Collection.Index public let endIndex: Collection.Index // FIXME: remove explicit typealiases. public typealias _Element = Collection.Index public typealias Generator = DefaultForwardIndexRangeGenerator<Collection> public typealias Index = Collection.Index public typealias SubSequence = DefaultForwardIndexRange<Collection> public typealias UnownedHandle = DefaultForwardIndexRange<Collection> public init( collection: Collection, startIndex: Collection.Index, endIndex: Collection.Index ) { self._unownedCollection = collection.unownedHandle self.startIndex = startIndex self.endIndex = endIndex } // FIXME: use DefaultGenerator when the type checker bug is fixed. public func generate() -> Generator { return DefaultForwardIndexRangeGenerator( Collection(from: _unownedCollection), start: startIndex, end: endIndex) } public subscript(i: Collection.Index) -> Collection.Index { return i } public subscript(bounds: MyRange<Index>) -> DefaultForwardIndexRange<Collection> { fatalError("implement") } public init(from handle: UnownedHandle) { self = handle } public var unownedHandle: UnownedHandle { return self } @warn_unused_result public func next(i: Index) -> Index { return Collection(from: _unownedCollection).next(i) } } // FIXME: use DefaultGenerator when the type checker bug is fixed. public struct DefaultForwardIndexRangeGenerator<Collection : MyIndexableType /* MyForwardCollectionType */> : MyGeneratorType { internal let _collection: Collection internal var _i: Collection.Index internal var _endIndex: Collection.Index public init( _ collection: Collection, start: Collection.Index, end: Collection.Index ) { self._collection = collection self._i = collection.startIndex self._endIndex = end } public mutating func next() -> Collection.Index? { if _i == _endIndex { return nil } let result = _i _i = _collection.next(_i) return result } } public struct MyRange<Index : MyIndexType> : MyIndexRangeType { public let startIndex: Index public let endIndex: Index public init(start: Index, end: Index) { self.startIndex = start self.endIndex = end } public subscript(i: Index) -> Index { return i } } // FIXME: in order for all this to be useable, we need to unify MyRange and // MyHalfOpenInterval. We can do that by constraining the Bound to comparable, // and providing a conditional conformance to collection when the Bound is // strideable. public struct MyHalfOpenInterval<Bound : Comparable> { public let start: Bound public let end: Bound } public struct MySlice<Collection : MyIndexableType /* : MyForwardCollectionType */> : MyForwardCollectionType // : MyIndexableType { internal let _base: Collection public let startIndex: Collection.Index public let endIndex: Collection.Index // FIXME: remove explicit typealiases. public typealias _Element = Collection._Element public typealias Index = Collection.Index public init( base: Collection, start: Collection.Index, end: Collection.Index) { self._base = base self.startIndex = start self.endIndex = end } public subscript(i: Collection.Index) -> Collection._Element { _base._failEarlyRangeCheck( i, bounds: MyRange(start: startIndex, end: endIndex)) return _base[i] } public typealias Generator = DefaultGenerator<MySlice> public func generate() -> Generator { return DefaultGenerator(self) } public typealias SubSequence = MySlice public subscript(bounds: MyRange<Index>) -> SubSequence { _base._failEarlyRangeCheck2( bounds.startIndex, rangeEnd: bounds.endIndex, boundsStart: startIndex, boundsEnd: endIndex) return MySlice(base: _base, start: bounds.startIndex, end: bounds.endIndex) } @warn_unused_result public func next(i: Index) -> Index { return _base.next(i) } public func _failEarlyRangeCheck(index: Index, bounds: MyRange<Index>) { fatalError("FIXME") } public func _failEarlyRangeCheck2( rangeStart: Index, rangeEnd: Index, boundsStart: Index, boundsEnd: Index) { fatalError("FIXME") } // FIXME: use Collection.UnownedHandle instead. public typealias UnownedHandle = MySlice public var unownedHandle: UnownedHandle { return self } public init(from handle: UnownedHandle) { self = handle } // FIXME: use DefaultForwardIndexRange instead. public typealias IndexRange = MySliceIndexRange<MySlice> public var indices: IndexRange { return MySliceIndexRange( collection: self, startIndex: startIndex, endIndex: endIndex) } } public struct MySliceIndexRange<Collection : MyIndexableType /* MyForwardCollectionType */> //: MyForwardCollectionType : MyIndexRangeType, MySequenceType, MyIndexableType { internal let _unownedCollection: Collection.UnownedHandle public let startIndex: Collection.Index public let endIndex: Collection.Index // FIXME: remove explicit typealiases. public typealias _Element = Collection.Index public typealias Generator = DefaultForwardIndexRangeGenerator<Collection> public typealias Index = Collection.Index public typealias SubSequence = MySliceIndexRange<Collection> public typealias UnownedHandle = MySliceIndexRange<Collection> public init( collection: Collection, startIndex: Collection.Index, endIndex: Collection.Index ) { self._unownedCollection = collection.unownedHandle self.startIndex = startIndex self.endIndex = endIndex } public func generate() -> Generator { return DefaultForwardIndexRangeGenerator( Collection(from: _unownedCollection), start: startIndex, end: endIndex) } public subscript(i: Collection.Index) -> Collection.Index { return i } public subscript(bounds: MyRange<Index>) -> MySliceIndexRange<Collection> { fatalError("implement") } public init(from handle: UnownedHandle) { self = handle } public var unownedHandle: UnownedHandle { return self } @warn_unused_result public func next(i: Index) -> Index { return Collection(from: _unownedCollection).next(i) } public func _failEarlyRangeCheck(index: Index, bounds: MyRange<Index>) { } public func _failEarlyRangeCheck2( rangeStart: Index, rangeEnd: Index, boundsStart: Index, boundsEnd: Index) { } public typealias IndexRange = MySliceIndexRange public var indices: IndexRange { return self } } public struct MyMutableSlice<Collection : MyMutableCollectionType> {} public struct MyAnyGenerator<Element> : MyGeneratorType { public init<G : MyGeneratorType>(_ g: G) { fatalError("FIXME") } public mutating func next() -> Element? { fatalError("FIXME") } } public struct MyAnySequence<Element> : MySequenceType { public typealias SubSequence = MyAnySequence<Element> public init<S : MySequenceType>(_ s: S) { fatalError("FIXME") } public func generate() -> MyAnyGenerator<Element> { fatalError("FIXME") } } public struct DefaultGenerator<Collection : MyIndexableType> : MyGeneratorType { internal let _collection: Collection internal var _i: Collection.Index public init(_ collection: Collection) { self._collection = collection self._i = collection.startIndex } public mutating func next() -> Collection._Element? { if _i == _collection.endIndex { return nil } let result = _collection[_i] _i = _collection.next(_i) return result } } public protocol MyMutableCollectionType : MyForwardCollectionType { typealias SubSequence : MyForwardCollectionType = MyMutableSlice<Self> subscript(i: Index) -> Generator.Element { get set } } public protocol MyIndexType : Equatable { // Move to CollectionType? typealias Distance : SignedIntegerType = Int } public protocol MyIndexRangeType : Equatable { typealias Index : MyIndexType var startIndex: Index { get } var endIndex: Index { get } } public func == <IR : MyIndexRangeType> (lhs: IR, rhs: IR) -> Bool { return lhs.startIndex == rhs.startIndex && lhs.endIndex == rhs.endIndex } /* public protocol MyRandomAccessIndexType : MyBidirectionalIndexType, MyStrideable, _RandomAccessAmbiguity { @warn_unused_result func distanceTo(other: Self) -> Distance @warn_unused_result func advancedBy(n: Distance) -> Self @warn_unused_result func advancedBy(n: Distance, limit: Self) -> Self } extension MyRandomAccessIndexType { public func _failEarlyRangeCheck(index: Self, bounds: MyRange<Self>) { _precondition( bounds.startIndex <= index, "index is out of bounds: index designates a position before bounds.startIndex") _precondition( index < bounds.endIndex, "index is out of bounds: index designates the bounds.endIndex position or a position after it") } public func _failEarlyRangeCheck2( rangeStart: Self, rangeEnd: Self, boundsStart: Self, boundsEnd: Self ) { let range = MyRange(startIndex: rangeStart, endIndex: rangeEnd) let bounds = MyRange(startIndex: boundsStart, endIndex: boundsEnd) _precondition( bounds.startIndex <= range.startIndex, "range.startIndex is out of bounds: index designates a position before bounds.startIndex") _precondition( bounds.startIndex <= range.endIndex, "range.endIndex is out of bounds: index designates a position before bounds.startIndex") _precondition( range.startIndex <= bounds.endIndex, "range.startIndex is out of bounds: index designates a position after bounds.endIndex") _precondition( range.endIndex <= bounds.endIndex, "range.startIndex is out of bounds: index designates a position after bounds.endIndex") } @transparent @warn_unused_result public func advancedBy(n: Distance, limit: Self) -> Self { let d = self.distanceTo(limit) if d == 0 || (d > 0 ? d <= n : d >= n) { return limit } return self.advancedBy(n) } } */ //------------ public protocol MyStrideable : Comparable { typealias Distance : SignedNumberType @warn_unused_result func distanceTo(other: Self) -> Distance @warn_unused_result func advancedBy(n: Distance) -> Self } public protocol MyRandomAccessIndex : MyIndexType, MyStrideable {} extension Int : MyIndexType {} extension Int : MyStrideable {} extension Int : MyRandomAccessIndex {} //------------------------------------------------------------------------ // Array public struct MyArray<Element> : MyForwardCollectionType { internal var _elements: [Element] = [] init() {} init(_ elements: [Element]) { self._elements = elements } public var startIndex: Int { return _elements.startIndex } public var endIndex: Int { return _elements.endIndex } public subscript(i: Int) -> Element { return _elements[i] } } //------------------------------------------------------------------------ // Simplest Forward Collection public struct MySimplestForwardCollection<Element> : MyForwardCollectionType { internal let _elements: [Element] public init(_ elements: [Element]) { self._elements = elements } public var startIndex: MySimplestForwardCollectionIndex { return MySimplestForwardCollectionIndex(_elements.startIndex) } public var endIndex: MySimplestForwardCollectionIndex { return MySimplestForwardCollectionIndex(_elements.endIndex) } @warn_unused_result public func next(i: MySimplestForwardCollectionIndex) -> MySimplestForwardCollectionIndex { return MySimplestForwardCollectionIndex(i._index + 1) } public subscript(i: MySimplestForwardCollectionIndex) -> Element { return _elements[i._index] } } public struct MySimplestForwardCollectionIndex : MyIndexType { internal let _index: Int internal init(_ index: Int) { self._index = index } } public func == ( lhs: MySimplestForwardCollectionIndex, rhs: MySimplestForwardCollectionIndex ) -> Bool { return lhs._index == rhs._index } //------------------------------------------------------------------------ // Simplest Bidirectional Collection public struct MySimplestBidirectionalCollection<Element> : MyBidirectionalCollectionType { internal let _elements: [Element] public init(_ elements: [Element]) { self._elements = elements } public var startIndex: MySimplestBidirectionalCollectionIndex { return MySimplestBidirectionalCollectionIndex(_elements.startIndex) } public var endIndex: MySimplestBidirectionalCollectionIndex { return MySimplestBidirectionalCollectionIndex(_elements.endIndex) } @warn_unused_result public func next(i: MySimplestBidirectionalCollectionIndex) -> MySimplestBidirectionalCollectionIndex { return MySimplestBidirectionalCollectionIndex(i._index + 1) } @warn_unused_result public func previous(i: MySimplestBidirectionalCollectionIndex) -> MySimplestBidirectionalCollectionIndex { return MySimplestBidirectionalCollectionIndex(i._index - 1) } public subscript(i: MySimplestBidirectionalCollectionIndex) -> Element { return _elements[i._index] } } public struct MySimplestBidirectionalCollectionIndex : MyIndexType { internal let _index: Int internal init(_ index: Int) { self._index = index } } public func == ( lhs: MySimplestBidirectionalCollectionIndex, rhs: MySimplestBidirectionalCollectionIndex ) -> Bool { return lhs._index == rhs._index } //------------------------------------------------------------------------ // Simplest Bidirectional Collection public struct MySimplestRandomAccessCollection<Element> : MyRandomAccessCollectionType { internal let _elements: [Element] public init(_ elements: [Element]) { self._elements = elements } // FIXME: 'typealias Index' should be inferred. public typealias Index = MySimplestRandomAccessCollectionIndex public var startIndex: MySimplestRandomAccessCollectionIndex { return MySimplestRandomAccessCollectionIndex(_elements.startIndex) } public var endIndex: MySimplestRandomAccessCollectionIndex { return MySimplestRandomAccessCollectionIndex(_elements.endIndex) } public subscript(i: MySimplestRandomAccessCollectionIndex) -> Element { return _elements[i._index] } } public struct MySimplestRandomAccessCollectionIndex : MyRandomAccessIndex { internal let _index: Int internal init(_ index: Int) { self._index = index } @warn_unused_result public func distanceTo(other: MySimplestRandomAccessCollectionIndex) -> Int { return other._index - _index } @warn_unused_result public func advancedBy(n: Int) -> MySimplestRandomAccessCollectionIndex { return MySimplestRandomAccessCollectionIndex(_index + n) } } public func == ( lhs: MySimplestRandomAccessCollectionIndex, rhs: MySimplestRandomAccessCollectionIndex ) -> Bool { return lhs._index == rhs._index } public func < ( lhs: MySimplestRandomAccessCollectionIndex, rhs: MySimplestRandomAccessCollectionIndex ) -> Bool { return lhs._index < rhs._index } //------------------------------------------------------------------------ // FIXME: how does AnyCollection look like in the new scheme? import StdlibUnittest // Also import modules which are used by StdlibUnittest internally. This // workaround is needed to link all required libraries in case we compile // StdlibUnittest with -sil-serialize-all. import SwiftPrivate #if _runtime(_ObjC) import ObjectiveC #endif var NewCollection = TestSuite("NewCollection") NewCollection.test("indexOf") { expectEqual(1, MyArray([1,2,3]).indexOf(2)) expectEmpty(MyArray([1,2,3]).indexOf(42)) } NewCollection.test("first") { expectOptionalEqual(1, MyArray([1,2,3]).first) expectEmpty(MyArray<Int>().first) } NewCollection.test("count") { expectEqual(3, MyArray([1,2,3]).count) expectEqual(0, MyArray<Int>().count) } NewCollection.test("isEmpty") { expectFalse(MyArray([1,2,3]).isEmpty) expectTrue(MyArray<Int>().isEmpty) } NewCollection.test("popFirst") { let c = MyArray([1,2,3]) var s0 = c[c.indices] var s = c[MyRange(start: c.startIndex, end: c.endIndex)] expectOptionalEqual(1, s.popFirst()) expectOptionalEqual(2, s.popFirst()) expectOptionalEqual(3, s.popFirst()) expectEmpty(s.popFirst()) } runAllTests()
apache-2.0
9ee2c6c58a668cf88b01846469de7f53
26.907921
109
0.698194
4.241198
false
false
false
false
bradhilton/Table
Table/StackView/UIView+Constraints.swift
1
3447
// // UIView+Constraints.swift // Table // // Created by Bradley Hilton on 10/8/18. // Copyright © 2018 Brad Hilton. All rights reserved. // extension Sequence where Element == ([Constraint], UIView) { func constraints(superview: UIView, window: UIWindow) -> ( newConstraints: (activated: [NSLayoutConstraint], deactivated: [NSLayoutConstraint]), visibleConstraints: (activated: [NSLayoutConstraint], deactivated: [NSLayoutConstraint]) ) { let siblings = lazy.map { $1 }.siblings let constraints = map { (constraints, view) in return ( constraints: view.constraints( for: constraints.resolvedConstraints( view: view, superview: superview, window: window, siblings: siblings ) ), isVisible: view.isVisible ) } return ( newConstraints: ( activated: constraints.lazy.filter { !$0.isVisible }.flatMap { $0.constraints.activated }, deactivated: constraints.lazy.filter { !$0.isVisible }.flatMap { $0.constraints.deactivated } ), visibleConstraints: ( activated: constraints.lazy.filter { $0.isVisible }.flatMap { $0.constraints.activated }, deactivated: constraints.lazy.filter { $0.isVisible }.flatMap { $0.constraints.deactivated } ) ) } } extension Sequence where Element : NSObject { var siblings: [AnyHashable: AnyObject] { return Dictionary(uniqueKeysWithValues: filter { $0.key != nil && $0.key != .auto }.map { ($0.key!, $0) }) } } extension Array where Element == Constraint { func resolvedConstraints(view: UIView, superview: UIView, window: UIWindow, siblings: [AnyHashable: AnyObject]) -> [ResolvedConstraint] { return map { constraint in ResolvedConstraint( constraint: constraint, firstItem: view, secondItem: constraint.target.map { $0.item(superview: superview, window: window, siblings: siblings) } ) } } } extension UIView { func updateConstraints(_ constraints: (activated: [NSLayoutConstraint], deactivated: [NSLayoutConstraint])) { let (activated, deactivated) = constraints NSLayoutConstraint.deactivate(deactivated) NSLayoutConstraint.activate(activated) } func constraints(for resolvedConstraints: [ResolvedConstraint]) -> (activated: [NSLayoutConstraint], deactivated: [NSLayoutConstraint]) { var pool = constraintsPool return ( activated: resolvedConstraints.compactMap { resolvedConstraint in if let constraint = pool.popFirst(where: { $0.matches(resolvedConstraint) }) { return !constraint.isActive ? constraint : nil } else { return NSLayoutConstraint(resolvedConstraint) } }, deactivated: pool ) } private var constraintsPool: [NSLayoutConstraint] { let allConstraints: [NSLayoutConstraint] = (superview?.constraints ?? []) + constraints return allConstraints.filter { $0.firstItem === self && $0.type == ResolvedConstraintType() as AnyHashable } } }
mit
b32b0e3abeb1c0723b9b5b65e997cb52
36.456522
141
0.589379
5.253049
false
false
false
false
yuyedaidao/YQTabBarController
Classes/YQTabBarItem.swift
1
6969
// // YQTabBarItem.swift // YQTabBarController // // Created by Wang on 14-9-23. // Copyright (c) 2014年 Wang. All rights reserved. // import UIKit class YQTabBarItem: UIControl { // weak var tabBar:YQTabBar? private var _index:Int! = 0 var index:Int{ return _index } var title:String? var titlePositionAdjustment:UIOffset! = YQTitlePositionAdjustment var unselectedTitleAttributes:Dictionary<NSString,AnyObject>! var selectedTitleAttributes:Dictionary<NSString,AnyObject>! // var unselectedBackgroundImage:UIImage? = YQUnselectedBackgroundImage // var selectedBackgroundImage:UIImage? = YQSelectedBackgroundImage var unselectedBackgroundColor:UIColor? = YQUnselectedBackgroundColor var selectedBackgroundColor:UIColor? = YQSelectedBackgroundColor var unselectedImage:UIImage! var selectedImage:UIImage! var imagePositionAdjustment:UIOffset! = YQImagePositionAdjustment var badgeValue:Int? lazy var badgeBackgroundColor:UIColor! = YQBadgeBackgroundColor lazy var badgeTextColor:UIColor! = YQBadgeTextColor lazy var badgeTextFont:UIFont! = YQBadgeTextFont lazy var badgePositionAdjustment:UIOffset! = YQBadgePositionAdjustment init(frame:CGRect,title:String?,selectedImage:UIImage!,unselectedImage:UIImage!,index:Int!,tabBar:YQTabBar){ super.init(frame:frame) self.title = title self._index = index self.unselectedImage = unselectedImage; self.selectedImage = selectedImage; self.commonInitialization() } override init(frame: CGRect) { super.init(frame: frame) self.commonInitialization() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.commonInitialization() } func commonInitialization(){ self.backgroundColor = UIColor.clearColor() unselectedTitleAttributes = [NSFontAttributeName:UIFont.systemFontOfSize(12),NSForegroundColorAttributeName:UIColor.blackColor()] selectedTitleAttributes = unselectedTitleAttributes } // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code var titleAttributes:Dictionary<NSString,AnyObject>? var backgroundImage:UIImage? var backgroundColor:UIColor? var image:UIImage! if self.selected { if (self.title != nil) { titleAttributes = self.selectedTitleAttributes } image = self.selectedImage backgroundColor = self.selectedBackgroundColor // backgroundImage = self.selectedBackgroundImage }else{ if (self.title != nil) { titleAttributes = self.unselectedTitleAttributes } image = self.unselectedImage backgroundColor = self.unselectedBackgroundColor // backgroundImage = self.unselectedBackgroundImage } var imageSize:CGSize = image.size var size:CGSize = self.frame.size var context:CGContextRef = UIGraphicsGetCurrentContext() CGContextSaveGState(context) //画背景 if backgroundColor != nil{ CGContextSetFillColorWithColor(context, backgroundColor?.CGColor) CGContextFillRect(context, self.bounds) } //画标题和图片 if let title:NSString = self.title{ var titleSize:CGSize = title.boundingRectWithSize(CGSize(width: size.width,height: 40), options:NSStringDrawingOptions.UsesLineFragmentOrigin , attributes:titleAttributes, context: nil).size var imageStartingY = round((size.height-imageSize.height-titleSize.height))/2 image.drawInRect(CGRectMake(round((size.width-imageSize.width)/2)+imagePositionAdjustment.horizontal,imageStartingY+imagePositionAdjustment.vertical,imageSize.width,imageSize.height)) CGContextSetFillColorWithColor(context, (titleAttributes?[NSForegroundColorAttributeName] as UIColor).CGColor) title.drawInRect(CGRectMake(round((size.width-titleSize.width)/2)+titlePositionAdjustment.horizontal, imageStartingY+imageSize.height+titlePositionAdjustment.vertical, titleSize.width, titleSize.height), withAttributes: titleAttributes) }else{ var rect:CGRect = CGRectMake(round((size.width-imageSize.width)/2)+imagePositionAdjustment.horizontal,round((size.height-imageSize.height)/2)+imagePositionAdjustment.vertical, imageSize.width, imageSize.height) image.drawInRect(rect) } //画badges if let badge = self.badgeValue{ if(badge>0){ var badgeStr:NSString = "\(badge)" var badgeSize:CGSize = badgeStr.boundingRectWithSize(CGSizeMake(size.width, 20), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName:self.badgeTextFont], context: nil).size var textOffset:CGFloat = 2.0 if(badgeSize.width < badgeSize.height){//否则单个数字时不是正圆 badgeSize = CGSizeMake(badgeSize.height, badgeSize.height) } var badgeBackgroundFrame:CGRect = CGRectMake(round((size.width+imageSize.width) / 2 * 0.9) + self.badgePositionAdjustment.horizontal, textOffset + self.badgePositionAdjustment.vertical, badgeSize.width + 2 * textOffset, badgeSize.height + 2 * textOffset) CGContextSetFillColorWithColor(context, self.badgeBackgroundColor.CGColor) CGContextFillEllipseInRect(context, badgeBackgroundFrame) var badgeTextStyle:NSMutableParagraphStyle = NSMutableParagraphStyle() badgeTextStyle.lineBreakMode = NSLineBreakMode.ByWordWrapping badgeTextStyle.alignment = NSTextAlignment.Center var badgeTextAttributes:Dictionary<NSString,AnyObject> = [NSFontAttributeName:self.badgeTextFont,NSForegroundColorAttributeName:self.badgeTextColor,NSParagraphStyleAttributeName:badgeTextStyle] CGContextSetFillColorWithColor(context, self.badgeTextColor.CGColor) badgeStr.drawInRect(CGRectMake(CGRectGetMinX(badgeBackgroundFrame)+textOffset, CGRectGetMinY(badgeBackgroundFrame)+textOffset, badgeSize.width, badgeSize.height), withAttributes: badgeTextAttributes) } } CGContextRestoreGState(context) }//draw }
mit
ea3f27ea8ab4ba6e95ef9146164ebdf9
40.467066
248
0.66296
5.611831
false
false
false
false
gcharita/XMLMapper
XMLMapperTests/Tests/BasicTypesTestsToXML.swift
1
19804
// // BasicTypesTestsToXML.swift // XMLMapperTests // // Created by Giorgos Charitakis on 18/02/2018. // import Foundation import XCTest import XMLMapper class BasicTypesTestsToXML: XCTestCase { let mapper = XMLMapper<BasicTypes>() override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } // MARK: Test mapping to XML and back (basic types: Bool, Int, Double, Float, String) // func testShouldIncludeNilValues(){ // let object = BasicTypes() // // let XMLWithNil = XMLMapper<BasicTypes>().toXMLString(object) // let XMLWithoutNil = XMLMapper<BasicTypes>().toXMLString(object) // // //TODO This test could be improved // XCTAssertNotNil(XMLWithNil) // XCTAssertTrue((XMLWithNil!.characters.count) > 5) // XCTAssertTrue((XMLWithNil!.characters.count) != (XMLWithoutNil!.characters.count)) // } func testMappingBoolToXML(){ let value: Bool = true let object = BasicTypes() object.bool = value object.boolOptional = value object.boolImplicityUnwrapped = value let XMLString = XMLMapper().toXMLString(object) let mappedObject = mapper.map(XMLString: XMLString!) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.bool, value) XCTAssertEqual(mappedObject?.boolOptional, value) XCTAssertEqual(mappedObject?.boolImplicityUnwrapped, value) } func testMappingIntegerToXML(){ let object = BasicTypes() object.int = 123 object.intOptional = 123 object.intImplicityUnwrapped = 123 object.int8 = 123 object.int8Optional = 123 object.int8ImplicityUnwrapped = 123 object.int16 = 123 object.int16Optional = 123 object.int16ImplicityUnwrapped = 123 object.int32 = 123 object.int32Optional = 123 object.int32ImplicityUnwrapped = 123 object.int64 = 123 object.int64Optional = 123 object.int64ImplicityUnwrapped = 123 object.uint = 123 object.uintOptional = 123 object.uintImplicityUnwrapped = 123 object.uint8 = 123 object.uint8Optional = 123 object.uint8ImplicityUnwrapped = 123 object.uint16 = 123 object.uint16Optional = 123 object.uint16ImplicityUnwrapped = 123 object.uint32 = 123 object.uint32Optional = 123 object.uint32ImplicityUnwrapped = 123 object.uint64 = 123 object.uint64Optional = 123 object.uint64ImplicityUnwrapped = 123 let XMLString = XMLMapper().toXMLString(object) let mappedObject = mapper.map(XMLString: XMLString!) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.int, 123) XCTAssertEqual(mappedObject?.intOptional, 123) XCTAssertEqual(mappedObject?.intImplicityUnwrapped, 123) XCTAssertEqual(mappedObject?.int8, 123) XCTAssertEqual(mappedObject?.int8Optional, 123) XCTAssertEqual(mappedObject?.int8ImplicityUnwrapped, 123) XCTAssertEqual(mappedObject?.int16, 123) XCTAssertEqual(mappedObject?.int16Optional, 123) XCTAssertEqual(mappedObject?.int16ImplicityUnwrapped, 123) XCTAssertEqual(mappedObject?.int32, 123) XCTAssertEqual(mappedObject?.int32Optional, 123) XCTAssertEqual(mappedObject?.int32ImplicityUnwrapped, 123) XCTAssertEqual(mappedObject?.int64, 123) XCTAssertEqual(mappedObject?.int64Optional, 123) XCTAssertEqual(mappedObject?.int64ImplicityUnwrapped, 123) XCTAssertEqual(mappedObject?.uint, 123) XCTAssertEqual(mappedObject?.uintOptional, 123) XCTAssertEqual(mappedObject?.uintImplicityUnwrapped, 123) XCTAssertEqual(mappedObject?.uint8, 123) XCTAssertEqual(mappedObject?.uint8Optional, 123) XCTAssertEqual(mappedObject?.uint8ImplicityUnwrapped, 123) XCTAssertEqual(mappedObject?.uint16, 123) XCTAssertEqual(mappedObject?.uint16Optional, 123) XCTAssertEqual(mappedObject?.uint16ImplicityUnwrapped, 123) XCTAssertEqual(mappedObject?.uint32, 123) XCTAssertEqual(mappedObject?.uint32Optional, 123) XCTAssertEqual(mappedObject?.uint32ImplicityUnwrapped, 123) XCTAssertEqual(mappedObject?.uint64, 123) XCTAssertEqual(mappedObject?.uint64Optional, 123) XCTAssertEqual(mappedObject?.uint64ImplicityUnwrapped, 123) } func testMappingDoubleToXML(){ let value: Double = 11 let object = BasicTypes() object.double = value object.doubleOptional = value object.doubleImplicityUnwrapped = value let XMLString = XMLMapper().toXMLString(object) let mappedObject = mapper.map(XMLString: XMLString!) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.double, value) XCTAssertEqual(mappedObject?.doubleOptional, value) XCTAssertEqual(mappedObject?.doubleImplicityUnwrapped, value) } func testMappingFloatToXML(){ let value: Float = 11 let object = BasicTypes() object.float = value object.floatOptional = value object.floatImplicityUnwrapped = value let XMLString = XMLMapper().toXMLString(object) let mappedObject = mapper.map(XMLString: XMLString!) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.float, value) XCTAssertEqual(mappedObject?.floatOptional, value) XCTAssertEqual(mappedObject?.floatImplicityUnwrapped, value) } func testMappingStringToXML(){ let value: String = "STRINGNGNGG" let object = BasicTypes() object.string = value object.stringOptional = value object.stringImplicityUnwrapped = value let XMLString = XMLMapper().toXMLString(object) let mappedObject = mapper.map(XMLString: XMLString!) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.string, value) XCTAssertEqual(mappedObject?.stringOptional, value) XCTAssertEqual(mappedObject?.stringImplicityUnwrapped, value) } func testMappingAnyObjectToXML(){ let value: String = "STRINGNGNGG" let object = BasicTypes() object.anyObject = value object.anyObjectOptional = value object.anyObjectImplicitlyUnwrapped = value let XMLString = XMLMapper().toXMLString(object) let mappedObject = mapper.map(XMLString: XMLString!) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.anyObject as? String, value) XCTAssertEqual(mappedObject?.anyObjectOptional as? String, value) XCTAssertEqual(mappedObject?.anyObjectImplicitlyUnwrapped as? String, value) } // MARK: Test mapping Arrays to XML and back (with basic types in them Bool, Int, Double, Float, String) func testMappingBoolArrayToXML(){ let value: Bool = true let object = BasicTypes() object.arrayBool = [value] object.arrayBoolOptional = [value] object.arrayBoolImplicityUnwrapped = [value] let XMLString = XMLMapper().toXMLString(object) let mappedObject = mapper.map(XMLString: XMLString!) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.arrayBool.first, value) XCTAssertEqual(mappedObject?.arrayBoolOptional?.first, value) XCTAssertEqual(mappedObject?.arrayBoolImplicityUnwrapped.first, value) } func testMappingIntArrayToXML(){ let value1: Int = 1 let object = BasicTypes() object.arrayInt = [value1] object.arrayIntOptional = [value1] object.arrayIntImplicityUnwrapped = [value1] let XMLString = XMLMapper().toXMLString(object) let mappedObject = mapper.map(XMLString: XMLString!) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.arrayInt.first, value1) XCTAssertEqual(mappedObject?.arrayIntOptional?.first, value1) XCTAssertEqual(mappedObject?.arrayIntImplicityUnwrapped.first, value1) } func testMappingDoubleArrayToXML(){ let value1: Double = 1.0 let object = BasicTypes() object.arrayDouble = [value1] object.arrayDoubleOptional = [value1] object.arrayDoubleImplicityUnwrapped = [value1] let XMLString = XMLMapper().toXMLString(object) let mappedObject = mapper.map(XMLString: XMLString!) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.arrayDouble.first, value1) XCTAssertEqual(mappedObject?.arrayDoubleOptional?.first, value1) XCTAssertEqual(mappedObject?.arrayDoubleImplicityUnwrapped.first, value1) } func testMappingFloatArrayToXML(){ let value1: Float = 1.001 let object = BasicTypes() object.arrayFloat = [value1] object.arrayFloatOptional = [value1] object.arrayFloatImplicityUnwrapped = [value1] let XMLString = XMLMapper().toXMLString(object) let mappedObject = mapper.map(XMLString: XMLString!) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.arrayFloat.first, value1) XCTAssertEqual(mappedObject?.arrayFloatOptional?.first, value1) XCTAssertEqual(mappedObject?.arrayFloatImplicityUnwrapped.first, value1) } func testMappingStringArrayToXML(){ let value: String = "Stringgggg" let object = BasicTypes() object.arrayString = [value] object.arrayStringOptional = [value] object.arrayStringImplicityUnwrapped = [value] let XMLString = XMLMapper().toXMLString(object) let mappedObject = mapper.map(XMLString: XMLString!) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.arrayString.first, value) XCTAssertEqual(mappedObject?.arrayStringOptional?.first, value) XCTAssertEqual(mappedObject?.arrayStringImplicityUnwrapped.first, value) } func testMappingAnyObjectArrayToXML(){ let value: String = "Stringgggg" let object = BasicTypes() object.arrayAnyObject = [value] object.arrayAnyObjectOptional = [value] object.arrayAnyObjectImplicitlyUnwrapped = [value] let XMLString = XMLMapper().toXMLString(object) let mappedObject = mapper.map(XMLString: XMLString!) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.arrayAnyObject.first as? String, value) XCTAssertEqual(mappedObject?.arrayAnyObjectOptional?.first as? String, value) XCTAssertEqual(mappedObject?.arrayAnyObjectImplicitlyUnwrapped.first as? String, value) } // MARK: Test mapping Dictionaries to XML and back (with basic types in them Bool, Int, Double, Float, String) func testMappingBoolDictionaryToXML(){ let key = "key" let value: Bool = true let object = BasicTypes() object.dictBool = [key:value] object.dictBoolOptional = [key:value] object.dictBoolImplicityUnwrapped = [key:value] let XMLString = XMLMapper().toXMLString(object) let mappedObject = mapper.map(XMLString: XMLString!) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.dictBool[key], value) XCTAssertEqual(mappedObject?.dictBoolOptional?[key], value) XCTAssertEqual(mappedObject?.dictBoolImplicityUnwrapped[key], value) } func testMappingIntDictionaryToXML(){ let key = "key" let value: Int = 11 let object = BasicTypes() object.dictInt = [key:value] object.dictIntOptional = [key:value] object.dictIntImplicityUnwrapped = [key:value] let XMLString = XMLMapper().toXMLString(object) let mappedObject = mapper.map(XMLString: XMLString!) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.dictInt[key], value) XCTAssertEqual(mappedObject?.dictIntOptional?[key], value) XCTAssertEqual(mappedObject?.dictIntImplicityUnwrapped[key], value) } func testMappingDoubleDictionaryToXML(){ let key = "key" let value: Double = 11 let object = BasicTypes() object.dictDouble = [key:value] object.dictDoubleOptional = [key:value] object.dictDoubleImplicityUnwrapped = [key:value] let XMLString = XMLMapper().toXMLString(object) let mappedObject = mapper.map(XMLString: XMLString!) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.dictDouble[key], value) XCTAssertEqual(mappedObject?.dictDoubleOptional?[key], value) XCTAssertEqual(mappedObject?.dictDoubleImplicityUnwrapped[key], value) } func testMappingFloatDictionaryToXML(){ let key = "key" let value: Float = 11 let object = BasicTypes() object.dictFloat = [key:value] object.dictFloatOptional = [key:value] object.dictFloatImplicityUnwrapped = [key:value] let XMLString = XMLMapper().toXMLString(object) let mappedObject = mapper.map(XMLString: XMLString!) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.dictFloat[key], value) XCTAssertEqual(mappedObject?.dictFloatOptional?[key], value) XCTAssertEqual(mappedObject?.dictFloatImplicityUnwrapped[key], value) } func testMappingStringDictionaryToXML(){ let key = "key" let value = "value" let object = BasicTypes() object.dictString = [key:value] object.dictStringOptional = [key:value] object.dictStringImplicityUnwrapped = [key:value] let XMLString = XMLMapper().toXMLString(object) let mappedObject = mapper.map(XMLString: XMLString!) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.dictString[key], value) XCTAssertEqual(mappedObject?.dictStringOptional?[key], value) XCTAssertEqual(mappedObject?.dictStringImplicityUnwrapped[key], value) } func testMappingAnyObjectDictionaryToXML(){ let key = "key" let value = "value" let object = BasicTypes() object.dictAnyObject = [key:value] object.dictAnyObjectOptional = [key:value] object.dictAnyObjectImplicitlyUnwrapped = [key:value] let XMLString = XMLMapper().toXMLString(object) let mappedObject = mapper.map(XMLString: XMLString!) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.dictAnyObject[key] as? String, value) XCTAssertEqual(mappedObject?.dictAnyObjectOptional?[key] as? String, value) XCTAssertEqual(mappedObject?.dictAnyObjectImplicitlyUnwrapped[key] as? String, value) } func testMappingIntEnumToXML(){ let value = BasicTypes.EnumInt.another let object = BasicTypes() object.enumInt = value object.enumIntOptional = value object.enumIntImplicitlyUnwrapped = value let XMLString = XMLMapper().toXMLString(object) let mappedObject = mapper.map(XMLString: XMLString!) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.enumInt, value) XCTAssertEqual(mappedObject?.enumIntOptional, value) XCTAssertEqual(mappedObject?.enumIntImplicitlyUnwrapped, value) } func testMappingDoubleEnumToXML(){ let value = BasicTypes.EnumDouble.another let object = BasicTypes() object.enumDouble = value object.enumDoubleOptional = value object.enumDoubleImplicitlyUnwrapped = value let XMLString = XMLMapper().toXMLString(object) let mappedObject = mapper.map(XMLString: XMLString!) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.enumDouble, value) XCTAssertEqual(mappedObject?.enumDoubleOptional, value) XCTAssertEqual(mappedObject?.enumDoubleImplicitlyUnwrapped, value) } func testMappingFloatEnumToXML(){ let value = BasicTypes.EnumFloat.another let object = BasicTypes() object.enumFloat = value object.enumFloatOptional = value object.enumFloatImplicitlyUnwrapped = value let XMLString = XMLMapper().toXMLString(object) let mappedObject = mapper.map(XMLString: XMLString!) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.enumFloat, value) XCTAssertEqual(mappedObject?.enumFloatOptional, value) XCTAssertEqual(mappedObject?.enumFloatImplicitlyUnwrapped, value) } func testMappingStringEnumToXML(){ let value = BasicTypes.EnumString.another let object = BasicTypes() object.enumString = value object.enumStringOptional = value object.enumStringImplicitlyUnwrapped = value let XMLString = XMLMapper().toXMLString(object) let mappedObject = mapper.map(XMLString: XMLString!) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.enumString, value) XCTAssertEqual(mappedObject?.enumStringOptional, value) XCTAssertEqual(mappedObject?.enumStringImplicitlyUnwrapped, value) } func testMappingEnumIntArrayToXML(){ let value = BasicTypes.EnumInt.another let object = BasicTypes() object.arrayEnumInt = [value] object.arrayEnumIntOptional = [value] object.arrayEnumIntImplicitlyUnwrapped = [value] let XMLString = XMLMapper().toXMLString(object) let mappedObject = mapper.map(XMLString: XMLString!) XCTAssertNotNil(mappedObject) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.arrayEnumInt.first, value) XCTAssertEqual(mappedObject?.arrayEnumIntOptional?.first, value) XCTAssertEqual(mappedObject?.arrayEnumIntImplicitlyUnwrapped.first, value) } func testMappingEnumIntDictionaryToXML(){ let key = "key" let value = BasicTypes.EnumInt.another let object = BasicTypes() object.dictEnumInt = [key: value] object.dictEnumIntOptional = [key: value] object.dictEnumIntImplicitlyUnwrapped = [key: value] let XMLString = XMLMapper().toXMLString(object) let mappedObject = mapper.map(XMLString: XMLString!) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.dictEnumInt[key], value) XCTAssertEqual(mappedObject?.dictEnumIntOptional?[key], value) XCTAssertEqual(mappedObject?.dictEnumIntImplicitlyUnwrapped[key], value) } func testObjectToModelDictionnaryOfPrimitives() { let object = TestCollectionOfPrimitives() object.dictStringString = ["string": "string"] object.dictStringBool = ["string": false] object.dictStringInt = ["string": 1] object.dictStringDouble = ["string": 1.2] object.dictStringFloat = ["string": 1.3] let XML = XMLMapper<TestCollectionOfPrimitives>().toXML(object) XCTAssertTrue((XML["dictStringString"] as? [String:String])?.isEmpty == false) XCTAssertTrue((XML["dictStringBool"] as? [String:String])?.isEmpty == false) XCTAssertTrue((XML["dictStringInt"] as? [String:String])?.isEmpty == false) XCTAssertTrue((XML["dictStringDouble"] as? [String:String])?.isEmpty == false) XCTAssertTrue((XML["dictStringFloat"] as? [String:String])?.isEmpty == false) XCTAssertEqual((XML["dictStringString"] as? [String:String])?["string"], "string") } }
mit
10551416043b7f89438e25327e701aac
36.65019
114
0.683751
5.119959
false
true
false
false
polymr/polymyr-api
Sources/App/Stripe/Models/StripeSubscription.swift
1
3349
// // Subscription.swift // Stripe // // Created by Hakon Hanesand on 12/2/16. // // import Node import Foundation public enum SubscriptionStatus: String, NodeConvertible { case trialing case active case pastDue = "past_due" case canceled case unpaid } public final class StripeSubscription: NodeConvertible { static let type = "subscription" public let id: String public let application_fee_percent: Double? public let cancel_at_period_end: Bool public let canceled_at: Date? public let created: Date public let current_period_end: Date public let current_period_start: Date public let customer: String public let discount: String? public let ended_at: Date? public let livemode: Bool public let plan: Plan public let quantity: Int public let start: Date public let status: SubscriptionStatus public let tax_percent: Double? public let trial_end: Date? public let trial_start: Date? public init(node: Node) throws { guard try node.extract("object") == StripeSubscription.type else { throw NodeError.unableToConvert(input: node, expectation: StripeSubscription.type, path: ["object"]) } id = try node.extract("id") application_fee_percent = try? node.extract("application_fee_percent") cancel_at_period_end = try node.extract("cancel_at_period_end") canceled_at = try? node.extract("canceled_at") created = try node.extract("created") current_period_end = try node.extract("current_period_end") current_period_start = try node.extract("current_period_start") customer = try node.extract("customer") discount = try? node.extract("discount") ended_at = try? node.extract("ended_at") livemode = try node.extract("livemode") plan = try node.extract("plan") quantity = try node.extract("quantity") start = try node.extract("start") status = try node.extract("status") tax_percent = try? node.extract("tax_percent") trial_end = try? node.extract("trial_end") trial_start = try? node.extract("trial_start") } public func makeNode(in context: Context?) throws -> Node { return try Node(node: [ "id" : .string(id), "cancel_at_period_end" : .bool(cancel_at_period_end), "created" : .number(.double(created.timeIntervalSince1970)), "current_period_end" : .number(.double(current_period_end.timeIntervalSince1970)), "current_period_start" : .number(.double(current_period_start.timeIntervalSince1970)), "customer" : .string(customer), "livemode" : .bool(livemode), "plan" : plan.makeNode(in: context), "quantity" : .number(.int(quantity)), "start" : .number(.double(start.timeIntervalSince1970)), "status" : .string(status.rawValue), ] as [String : Node]).add(objects: [ "canceled_at" : canceled_at, "ended_at" : ended_at, "tax_percent" : tax_percent, "trial_end" : trial_end, "trial_start" : trial_start, "application_fee_percent" : application_fee_percent, "discount" : discount ]) } }
mit
030caaf2fcbb76c832a5448913835621
35.010753
112
0.617498
4.109202
false
false
false
false
DevHospital/Video
Video/VideoPlayerViewController.swift
1
2447
// // VideoPlayerViewController.swift // Video // // Created by Jakub Gert on 02.12.2015. // Copyright © 2015 Dev-Hospital. All rights reserved. // import Foundation import Foundation import AVFoundation public class VideoPlayerViewController: UIViewController, VideoPlayer { @IBOutlet public private(set) var videoPlayerView: VideoPlayerView? public var videoPlayerDidChangeTime: VideoPlayerView.VideoPlayerDidChangeTime? { didSet { videoPlayerView?.videoPlayerDidChangeTime = videoPlayerDidChangeTime } } public var videoPlayerDidPlayToEnd: VideoPlayerView.VideoPlayerDidPlayToEnd? { didSet { videoPlayerView?.videoPlayerDidPlayToEnd = videoPlayerDidPlayToEnd } } public override func viewDidLoad() { super.viewDidLoad() initializeVideoView() } } extension VideoPlayerViewController { public func play() { videoPlayerView?.play() } public func pause() { videoPlayerView?.pause() } public func setTime(time: NSTimeInterval) { videoPlayerView?.setTime(time) } public func setPlayerItem(playerItem: AVPlayerItem, autoPlay: Bool) { videoPlayerView?.setPlayerItem(playerItem, autoPlay: autoPlay) } } extension VideoPlayerViewController { private func initializeVideoView() { if videoPlayerView == nil { videoPlayerView = VideoPlayerView() if let videoView = videoPlayerView { videoView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(videoView) view.addConstraints( NSLayoutConstraint.constraintsWithVisualFormat( "H:|[view]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["view": videoView])) view.addConstraints( NSLayoutConstraint.constraintsWithVisualFormat( "V:|[view]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["view": videoView])) videoView.videoPlayerDidPlayToEnd = videoPlayerDidPlayToEnd videoView.videoPlayerDidChangeTime = videoPlayerDidChangeTime } else { assertionFailure("Faield to create video view") } } } }
mit
6c2b775feac413823c1a053f26f780fb
27.114943
84
0.61897
6.115
false
false
false
false
bitjammer/swift
test/SILGen/nested_types_referencing_nested_functions.swift
1
978
// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s do { func foo() { bar(2) } func bar<T>(_: T) { foo() } class Foo { // CHECK-LABEL: sil shared @_T0025nested_types_referencing_A10_functions3FooL_CACycfc : $@convention(method) (@owned Foo) -> @owned Foo { init() { foo() } // CHECK-LABEL: sil shared @_T0025nested_types_referencing_A10_functions3FooL_C3zimyyF : $@convention(method) (@guaranteed Foo) -> () func zim() { foo() } // CHECK-LABEL: sil shared @_T0025nested_types_referencing_A10_functions3FooL_C4zangyxlF : $@convention(method) <T> (@in T, @guaranteed Foo) -> () func zang<T>(_ x: T) { bar(x) } // CHECK-LABEL: sil shared @_T0025nested_types_referencing_A10_functions3FooL_CfD : $@convention(method) (@owned Foo) -> () deinit { foo() } } let x = Foo() x.zim() x.zang(1) _ = Foo.zim _ = Foo.zang as (Foo) -> (Int) -> () _ = x.zim _ = x.zang as (Int) -> () }
apache-2.0
7f84d9fa33a2ea434f6c14bcf67a2a9b
28.636364
150
0.579755
2.963636
false
false
false
false
hollance/YOLO-CoreML-MPSNNGraph
TinyYOLO-NNGraph/TinyYOLO-NNGraph/UIImage+RawBytes.swift
1
1632
import UIKit extension UIImage { /** Converts the image into an array of RGBA bytes. */ @nonobjc public func toByteArray() -> [UInt8] { let width = Int(size.width) let height = Int(size.height) var bytes = [UInt8](repeating: 0, count: width * height * 4) bytes.withUnsafeMutableBytes { ptr in if let context = CGContext( data: ptr.baseAddress, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) { if let image = self.cgImage { let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) context.draw(image, in: rect) } } } return bytes } /** Creates a new UIImage from an array of RGBA bytes. */ @nonobjc public class func fromByteArray(_ bytes: UnsafeMutableRawPointer, width: Int, height: Int) -> UIImage { if let context = CGContext(data: bytes, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue), let cgImage = context.makeImage() { return UIImage(cgImage: cgImage, scale: 0, orientation: .up) } else { return UIImage() } } }
mit
b663675b01c1d116f02ee242b831960f
33
88
0.536765
5.132075
false
false
false
false
syoung-smallwisdom/BridgeAppSDK
BridgeAppSDK/SBAConsentDocumentFactory.swift
1
7634
// // SBAConsentDocument.swift // BridgeAppSDK // // Copyright © 2016 Sage Bionetworks. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // 3. Neither the name of the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // 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 OWNER 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 ResearchKit open class SBAConsentDocumentFactory: SBASurveyFactory { lazy open var consentDocument: ORKConsentDocument = { // Setup the consent document let consentDocument = ORKConsentDocument() consentDocument.title = Localization.localizedString("SBA_CONSENT_TITLE") consentDocument.signaturePageTitle = Localization.localizedString("SBA_CONSENT_TITLE") consentDocument.signaturePageContent = Localization.localizedString("SBA_CONSENT_SIGNATURE_CONTENT") // Add the signature let signature = ORKConsentSignature(forPersonWithTitle: Localization.localizedString("SBA_CONSENT_PERSON_TITLE"), dateFormatString: nil, identifier: "participant") consentDocument.addSignature(signature) return consentDocument }() public convenience init?(jsonNamed: String) { guard let json = SBAResourceFinder.shared.json(forResource: jsonNamed) else { return nil } self.init(dictionary: json as NSDictionary) } public convenience init(dictionary: NSDictionary) { self.init() // Load the sections var previousSectionType: SBAConsentSectionType? if let sections = dictionary["sections"] as? [NSDictionary] { self.consentDocument.sections = sections.map({ (dictionarySection) -> ORKConsentSection in let consentSection = dictionarySection.createConsentSection(previous: previousSectionType) previousSectionType = dictionarySection.consentSectionType return consentSection }) } // Load the document for the HTML content if let properties = dictionary["documentProperties"] as? NSDictionary, let documentHtmlContent = properties["htmlDocument"] as? String { self.consentDocument.htmlReviewContent = SBAResourceFinder.shared.html(forResource: documentHtmlContent) } // After loading the consentDocument, map the steps self.mapSteps(dictionary) } override open func createSurveyStepWithCustomType(_ inputItem: SBASurveyItem) -> ORKStep? { guard let subtype = inputItem.surveyItemType.consentSubtype() else { return super.createSurveyStepWithCustomType(inputItem) } switch (subtype) { case .visual: return ORKVisualConsentStep(identifier: inputItem.identifier, document: self.consentDocument) case .sharingOptions: return SBAConsentSharingStep(inputItem: inputItem) case .review: if let consentReview = inputItem as? SBAConsentReviewOptions , consentReview.usesDeprecatedOnboarding { // If this uses the deprecated onboarding (consent review defined by ORKConsentReviewStep) // then return that object type. let signature = self.consentDocument.signatures?.first signature?.requiresName = consentReview.requiresSignature signature?.requiresSignatureImage = consentReview.requiresSignature return ORKConsentReviewStep(identifier: inputItem.identifier, signature: signature, in: self.consentDocument) } else { let review = inputItem as! SBAFormStepSurveyItem let step = SBAConsentReviewStep(inputItem: review, inDocument: self.consentDocument) return step; } } } /** * Return visual consent step */ open func visualConsentStep() -> ORKVisualConsentStep { return self.steps?.find({ $0 is ORKVisualConsentStep }) as? ORKVisualConsentStep ?? ORKVisualConsentStep(identifier: SBAOnboardingSectionBaseType.consent.rawValue, document: self.consentDocument) } /** * Return subtask step with only the steps required for reconsent */ open func reconsentStep() -> SBASubtaskStep { // Strip out the registration steps let steps = self.steps?.filter({ !isRegistrationStep($0) }) let task = SBANavigableOrderedTask(identifier: SBAOnboardingSectionBaseType.consent.rawValue, steps: steps) return SBASubtaskStep(subtask: task) } /** * Return subtask step with only the steps required for consent or reconsent on login */ open func loginConsentStep() -> SBASubtaskStep { // Strip out the registration steps let steps = self.steps?.filter({ !isRegistrationStep($0) }) let task = SBANavigableOrderedTask(identifier: SBAOnboardingSectionBaseType.consent.rawValue, steps: steps) return SBAConsentSubtaskStep(subtask: task) } private func isRegistrationStep(_ step: ORKStep) -> Bool { return (step is SBARegistrationStep) || (step is ORKRegistrationStep) || (step is SBAExternalIDStep) } /** * Return subtask step with only the steps required for initial registration */ open func registrationConsentStep() -> SBASubtaskStep { // Strip out the reconsent steps let steps = self.steps?.filter({ (step) -> Bool in // If this is a step that conforms to the custom step protocol and the custom step type is // a reconsent subtype, then this is not to be included in the registration steps if let customStep = step as? SBACustomTypeStep, let customType = customStep.customTypeIdentifier, customType.hasPrefix("reconsent") { return false } return true }) let task = SBANavigableOrderedTask(identifier: SBAOnboardingSectionBaseType.consent.rawValue, steps: steps) return SBASubtaskStep(subtask: task) } }
bsd-3-clause
f436341ddf78712c68045a15edca19a8
46.117284
171
0.680728
5.319164
false
false
false
false
graphcool-examples/react-apollo-auth0-example
quickstart-with-apollo/Instagram/Carthage/Checkouts/apollo-ios/Tests/ApolloTests/GraphQLResultReaderTests.swift
1
9097
import XCTest @testable import Apollo // Because XCTAssertThrowsError expects an @autoclosure argument and that doesn't allow // us to specify an explicit return type, we need this wrapper function to select // the right overloaded version of the GraphQLDataReader method under test private func with<T>(returnType: T.Type, _ body: @autoclosure () throws -> T) rethrows -> T { let value: T = try body() return value } private func read(from rootObject: JSONObject) -> GraphQLResultReader { return GraphQLResultReader { field, _, _ in return rootObject[field.responseName] } } class GraphQLResultReaderTests: XCTestCase { static var allTests: [(String, (GraphQLResultReaderTests) -> () throws -> Void)] { return [ ("testGetValue", testGetValue), ("testGetValueWithMissingKey", testGetValueWithMissingKey), ("testGetValueWithNull", testGetValueWithNull), ("testGetValueWithWrongType", testGetValueWithWrongType), ("testGetOptionalValue", testGetOptionalValue), ("testGetOptionalValueWithMissingKey", testGetOptionalValueWithMissingKey), ("testGetOptionalValueWithNull", testGetOptionalValueWithNull), ("testGetOptionalValueWithWrongType", testGetOptionalValueWithWrongType), ("testGetList", testGetList), ("testGetListWithMissingKey", testGetListWithMissingKey), ("testGetListWithNull", testGetListWithNull), ("testGetListWithWrongType", testGetListWithWrongType), ("testGetOptionalList", testGetOptionalList), ("testGetOptionalListWithNull", testGetOptionalListWithNull), ("testGetOptionalListWithWrongType", testGetOptionalListWithWrongType), ("testGetOptionalListWithMissingKey", testGetOptionalListWithMissingKey), ("testGetListWithOptionalElements", testGetListWithOptionalElements), ("testGetOptionalListWithOptionalElements", testGetOptionalListWithOptionalElements) ] } func testGetValue() throws { let reader = read(from: ["name": "Luke Skywalker"]) let value: String = try reader.value(for: Field(responseName: "name")) XCTAssertEqual(value, "Luke Skywalker") } func testGetValueWithMissingKey() { let reader = read(from: [:]) XCTAssertThrowsError(try with(returnType: String.self, reader.value(for: Field(responseName: "name")))) { (error) in if case let error as GraphQLResultError = error { XCTAssertEqual(error.path, ["name"]) XCTAssertMatch(error.underlying, JSONDecodingError.missingValue) } else { XCTFail("Unexpected error: \(error)") } } } func testGetValueWithNull() throws { let reader = read(from: ["name": NSNull()]) XCTAssertThrowsError(try with(returnType: String.self, reader.value(for: Field(responseName: "name")))) { (error) in if case let error as GraphQLResultError = error { XCTAssertEqual(error.path, ["name"]) XCTAssertMatch(error.underlying, JSONDecodingError.nullValue) } else { XCTFail("Unexpected error: \(error)") } } } func testGetValueWithWrongType() throws { let reader = read(from: ["name": 10]) XCTAssertThrowsError(try with(returnType: String.self, reader.value(for: Field(responseName: "name")))) { (error) in if let error = error as? GraphQLResultError, case JSONDecodingError.couldNotConvert(let value, let expectedType) = error.underlying { XCTAssertEqual(error.path, ["name"]) XCTAssertEqual(value as? Int, 10) XCTAssertTrue(expectedType == String.self) } else { XCTFail("Unexpected error: \(error)") } } } func testGetOptionalValue() throws { let reader = read(from: ["name": "Luke Skywalker"]) let value: String? = try reader.optionalValue(for: Field(responseName: "name")) XCTAssertEqual(value, "Luke Skywalker") } func testGetOptionalValueWithMissingKey() throws { let reader = read(from: [:]) XCTAssertThrowsError(try with(returnType: Optional<String>.self, reader.optionalValue(for: Field(responseName: "name")))) { (error) in if case let error as GraphQLResultError = error { XCTAssertEqual(error.path, ["name"]) XCTAssertMatch(error.underlying, JSONDecodingError.missingValue) } else { XCTFail("Unexpected error: \(error)") } } } func testGetOptionalValueWithNull() throws { let reader = read(from: ["name": NSNull()]) let value: String? = try reader.optionalValue(for: Field(responseName: "name")) XCTAssertNil(value) } func testGetOptionalValueWithWrongType() throws { let reader = read(from: ["name": 10]) XCTAssertThrowsError(try with(returnType: Optional<String>.self, reader.optionalValue(for: Field(responseName: "name")))) { (error) in if let error = error as? GraphQLResultError, case JSONDecodingError.couldNotConvert(let value, let expectedType) = error.underlying { XCTAssertEqual(error.path, ["name"]) XCTAssertEqual(value as? Int, 10) XCTAssertTrue(expectedType == String.self) } else { XCTFail("Unexpected error: \(error)") } } } func testGetList() throws { let reader = read(from: ["appearsIn": ["NEWHOPE", "EMPIRE", "JEDI"]]) let value: [Episode] = try reader.list(for: Field(responseName: "appearsIn")) XCTAssertEqual(value, [.newhope, .empire, .jedi]) } func testGetListWithMissingKey() { let reader = read(from: [:]) XCTAssertThrowsError(try with(returnType: Array<Episode>.self, reader.list(for: Field(responseName: "appearsIn")))) { (error) in if case let error as GraphQLResultError = error { XCTAssertEqual(error.path, ["appearsIn"]) XCTAssertMatch(error.underlying, JSONDecodingError.missingValue) } else { XCTFail("Unexpected error: \(error)") } } } func testGetListWithNull() throws { let reader = read(from: ["appearsIn": NSNull()]) XCTAssertThrowsError(try with(returnType: Array<Episode>.self, reader.list(for: Field(responseName: "appearsIn")))) { (error) in if case let error as GraphQLResultError = error { XCTAssertEqual(error.path, ["appearsIn"]) XCTAssertMatch(error.underlying, JSONDecodingError.nullValue) } else { XCTFail("Unexpected error: \(error)") } } } func testGetListWithWrongType() throws { let reader = read(from: ["appearsIn": [4, 5, 6]]) XCTAssertThrowsError(try with(returnType: Array<Episode>.self, reader.list(for: Field(responseName: "appearsIn")))) { (error) in if let error = error as? GraphQLResultError, case JSONDecodingError.couldNotConvert(let value, let expectedType) = error.underlying { XCTAssertEqual(error.path, ["appearsIn", "0"]) XCTAssertEqual(value as? Int, 4) XCTAssertTrue(expectedType == String.self) } else { XCTFail("Unexpected error: \(error)") } } } func testGetOptionalList() throws { let reader = read(from: ["appearsIn": ["NEWHOPE", "EMPIRE", "JEDI"]]) let value: [Episode]? = try reader.optionalList(for: Field(responseName: "appearsIn")) XCTAssertEqual(value!, [.newhope, .empire, .jedi]) } func testGetOptionalListWithMissingKey() throws { let reader = read(from: [:]) XCTAssertThrowsError(try with(returnType: Optional<Array<Episode>>.self, reader.optionalList(for: Field(responseName: "appearsIn")))) { (error) in if case let error as GraphQLResultError = error { XCTAssertEqual(error.path, ["appearsIn"]) XCTAssertMatch(error.underlying, JSONDecodingError.missingValue) } else { XCTFail("Unexpected error: \(error)") } } } func testGetOptionalListWithNull() throws { let reader = read(from: ["appearsIn": NSNull()]) let value: [Episode]? = try reader.optionalList(for: Field(responseName: "appearsIn")) XCTAssertNil(value) } func testGetOptionalListWithWrongType() throws { let reader = read(from: ["appearsIn": [4, 5, 6]]) XCTAssertThrowsError(try with(returnType: Optional<Array<Episode>>.self, reader.optionalList(for: Field(responseName: "appearsIn")))) { (error) in if let error = error as? GraphQLResultError, case JSONDecodingError.couldNotConvert(let value, let expectedType) = error.underlying { XCTAssertEqual(error.path, ["appearsIn", "0"]) XCTAssertEqual(value as? Int, 4) XCTAssertTrue(expectedType == String.self) } else { XCTFail("Unexpected error: \(error)") } } } func testGetListWithOptionalElements() throws { let reader = read(from: ["appearsIn": ["NEWHOPE", "EMPIRE", "JEDI"]]) let value: [Episode?] = try reader.list(for: Field(responseName: "appearsIn")) XCTAssertEqual(value, [.newhope, .empire, .jedi] as [Episode?]) } func testGetOptionalListWithOptionalElements() throws { let reader = read(from: ["appearsIn": ["NEWHOPE", "EMPIRE", "JEDI"]]) let value: [Episode?]? = try reader.optionalList(for: Field(responseName: "appearsIn")) XCTAssertEqual(value, [.newhope, .empire, .jedi] as [Episode?]) } }
mit
23f585c6d95d9c8154b9909ac513e44f
39.793722
150
0.684072
4.36307
false
true
false
false
hejunbinlan/Operations
Operations/Observers/BackgroundObserver.swift
1
2871
// // BackgroundObserver.swift // Operations // // Created by Daniel Thorpe on 19/07/2015. // Copyright © 2015 Daniel Thorpe. All rights reserved. // import UIKit public protocol BackgroundTaskApplicationInterface { var applicationState: UIApplicationState { get } func beginBackgroundTaskWithName(taskName: String?, expirationHandler handler: (() -> Void)?) -> UIBackgroundTaskIdentifier func endBackgroundTask(identifier: UIBackgroundTaskIdentifier) } extension UIApplication: BackgroundTaskApplicationInterface { } /** An observer which will automatically start & stop a background task if the application enters the background. Attach a `BackgroundObserver` to an operation which must be completed even if the app goes in the background. */ public class BackgroundObserver: NSObject { public static let backgroundTaskName = "Background Operation Observer" private var identifier: UIBackgroundTaskIdentifier? = .None private let application: BackgroundTaskApplicationInterface private var isInBackground: Bool { return application.applicationState == .Background } public override convenience init() { self.init(app: UIApplication.sharedApplication()) } init(app: BackgroundTaskApplicationInterface) { application = app super.init() let nc = NSNotificationCenter.defaultCenter() nc.addObserver(self, selector: "didEnterBackground:", name: UIApplicationDidEnterBackgroundNotification, object: .None) nc.addObserver(self, selector: "didBecomeActive:", name: UIApplicationDidBecomeActiveNotification, object: .None) if isInBackground { startBackgroundTask() } } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } @objc func didEnterBackground(notification: NSNotification) { if isInBackground { startBackgroundTask() } } @objc func didBecomeActive(notification: NSNotification) { if !isInBackground { endBackgroundTask() } } private func startBackgroundTask() { if identifier == nil { identifier = application.beginBackgroundTaskWithName(self.dynamicType.backgroundTaskName) { self.endBackgroundTask() } } } private func endBackgroundTask() { if let id = identifier { application.endBackgroundTask(id) identifier = .None } } } extension BackgroundObserver: OperationObserver { public func operationDidStart(operation: Operation) { // no-op } public func operation(operation: Operation, didProduceOperation newOperation: NSOperation) { // no-op } public func operationDidFinish(operation: Operation, errors: [ErrorType]) { endBackgroundTask() } }
mit
884f6b1453339288adb1ac73b52067c0
27.7
127
0.692334
5.562016
false
false
false
false
LuizZak/GPEngine
Tests/SerializationTests/SerializationTests.swift
1
44163
// // SerializationTests.swift // GPEngine // // Created by Luiz Fernando Silva on 01/04/17. // Copyright © 2017 CocoaPods. All rights reserved. // import XCTest @testable import GPEngine #if SWIFT_PACKAGE @testable import Serialization #endif class SerializationTests: XCTestCase { struct SerializableCodableComponent: Component, Serializable, Codable { var field1: Int var field2: String } struct SerializableComponent: Component, Serializable { var field: Int init(field: Int) { self.field = field } init(json: JSON, path: JsonPath) throws { field = try json[path: "field"].integer(prefixPath: path) } func serialized() -> JSON { return ["field": field.json] } } final class SerializableSubspace: Subspace, Serializable { var subspaceField: Int init(subspaceField: Int) { self.subspaceField = subspaceField } init(json: JSON, path: JsonPath) throws { subspaceField = try json[path: "subspaceField"].integer(prefixPath: path) } func serialized() -> JSON { return ["subspaceField": subspaceField.json] } } struct UnserializableComponent: Component { } final class UnserializableSubspace: Subspace { } class Provider: BasicSerializationTypeProvider { var serializableTypes: [(Serializable.Type, (JSON, JsonPath) throws -> Serializable)] = [ (SerializableCodableComponent.self, SerializableCodableComponent.init), (SerializableComponent.self, SerializableComponent.init), (SerializableSubspace.self, SerializableSubspace.init) ] } // MARK: Component func testSerializationType() throws { let serializer = GameSerializer(typeProvider: Provider()) let original = SerializableComponent(field: 10) let object = serializer.serialize(original) XCTAssertEqual(object.contentType, .component) let ser: SerializableComponent = try serializer.extract(from: object, path: .root) XCTAssertEqual(ser.field, original.field) } func testSerializationCodableType() throws { let serializer = GameSerializer(typeProvider: Provider()) let original = SerializableCodableComponent(field1: 10, field2: "abc") let object = serializer.serialize(original) XCTAssertEqual(object.contentType, .component) let ser: SerializableCodableComponent = try serializer.extract(from: object, path: .root) XCTAssertEqual(ser.field1, original.field1) XCTAssertEqual(ser.field2, original.field2) } // MARK: Entity func testSerializeEntity() throws { let serializer = GameSerializer(typeProvider: Provider()) let expected: JSON = [ "typeName": "Entity", "contentType": "entity", "data": [ "id": 20.0, "type": 3.0, "components": [ [ "typeName": "SerializableComponent", "contentType": "component", "data": [ "field": 10.0, ], ], [ "typeName": "SerializableComponent", "contentType": "component", "data": [ "field": 20.0, ], ], ], ], ] let entity = Entity(components: [ SerializableComponent(field: 10), SerializableComponent(field: 20), ]) entity.id = 20 entity.type = 3 let object = try serializer.serialize(entity) assertEquals(expected, object.serialized()) } func testSerializeEntity_roundtrip() throws { let serializer = GameSerializer(typeProvider: Provider()) let originalComponents = [ SerializableComponent(field: 10), SerializableComponent(field: 20), ] let original = Entity(components: originalComponents) original.id = 20 original.type = 3 let object = try serializer.serialize(original) let deserialized: Entity = try serializer.extract(from: object, path: .root) // Check basic deserialization XCTAssertEqual(object.contentType, .entity) XCTAssertEqual(deserialized.id, 20) XCTAssertEqual(deserialized.type, 3) // Check deserialized components XCTAssertEqual(2, deserialized.components.count) let deserializedComps = deserialized.components(ofType: SerializableComponent.self) XCTAssert(deserializedComps.elementsEqual(originalComponents) { $0.field == $1.field }) } func testSerializeEntityError() throws { // Tests error thrown when trying to serialize an entity with an // unserializable component let serializer = GameSerializer(typeProvider: Provider()) let original = Entity(components: [UnserializableComponent()]) do { _ = try serializer.serialize(original) XCTFail("Should not have serialized successfully") } catch { XCTAssert(error is SerializationError) } } func testCanSerializeEntity() { let entity = Entity() XCTAssertTrue(GameSerializer.canSerialize(entity)) } func testCanSerializeEntityChecksComponents() { let entity = Entity(components: [SerializableComponent(field: 1)]) XCTAssertTrue(GameSerializer.canSerialize(entity)) } func testCanSerializeEntityFailsOnNonSerializableComponent() { let entity = Entity(components: [UnserializableComponent()]) XCTAssertFalse(GameSerializer.canSerialize(entity)) } // MARK: Space func testSerializeSpace() throws { let serializer = GameSerializer(typeProvider: Provider()) let expected: JSON = [ "typeName": "Space", "contentType": "space", "data": [ "entities": [ [ "typeName": "Entity", "contentType": "entity", "data": [ "id": 20.0, "type": 3.0, "components": [ [ "typeName": "SerializableComponent", "contentType": "component", "data": [ "field": 10.0, ], ], [ "typeName": "SerializableComponent", "contentType": "component", "data": [ "field": 20.0, ], ], ], ], ], ], "subspaces": [ [ "typeName": "SerializableSubspace", "contentType": "subspace", "data": [ "subspaceField": 1.0, ], ], ], ], ] let entity = Entity(components: [ SerializableComponent(field: 10), SerializableComponent(field: 20), ]) entity.id = 20 entity.type = 3 let space = Space() space.addEntity(entity) space.addSubspace(SerializableSubspace(subspaceField: 1)) let object = try serializer.serialize(space) assertEquals(expected, object.serialized()) } func testSerializeSpace_roundtrip() throws { let serializer = GameSerializer(typeProvider: Provider()) let original = Space() original.addEntity(Entity(components: [SerializableComponent(field: 10)])) original.addSubspace(SerializableSubspace(subspaceField: 20)) let object = try serializer.serialize(original) XCTAssertEqual(object.contentType, .space) let deserialized: Space = try serializer.extract(from: object, path: .root) XCTAssertEqual(1, deserialized.entities.count) XCTAssertEqual(1, deserialized.entities[0].components.count) XCTAssertEqual(1, deserialized.subspaces.count) XCTAssertEqual(deserialized.subspace(SerializableSubspace.self)?.subspaceField, 20) } func testSerializeSpaceEntityError() throws { // Tests error thrown when trying to serialize a space with an // unserializable entity let serializer = GameSerializer(typeProvider: Provider()) let original = Space() original.addEntity(Entity(components: [UnserializableComponent()])) do { _ = try serializer.serialize(original) XCTFail("Should not have serialized successfully") } catch { XCTAssert(error is SerializationError) } } func testSerializeSpaceSubspaceError() throws { // Tests error thrown when trying to serialize a space with an // unserializable subspace let serializer = GameSerializer(typeProvider: Provider()) let original = Space() original.addSubspace(Subspace()) // Default Subspace is unserializable by default do { _ = try serializer.serialize(original) XCTFail("Should not have serialized successfully") } catch { XCTAssert(error is SerializationError) } } func testFullDeserialize() throws { let serializer = GameSerializer(typeProvider: Provider()) let json: JSON = [ "contentType": "space", "typeName": "Space", // Must always be 'Space' for spaces "data": [ "subspaces": [ [ "contentType": "subspace", "typeName": "SerializableSubspace", "data": [ "subspaceField": 10, ], ], ], "entities": [ [ "contentType": "entity", "typeName": "Entity", // Must always be 'Entity' for entities "presets": [ [ "presetName": "Comp", "presetType": "component", "presetVariables": [ "x": "number", ], "presetData": [ "contentType": "component", "typeName": "SerializableComponent", "data": [ "field": [ "presetVariable": "x" ], ], ], ] ], "data": [ "id": 1, "type": 2, "components": [ [ "contentType": "preset", "typeName": "Comp", "data": [ "x": 20, ], ], ], ], ], ], ], ] let serialized = try Serialized(json: json, path: .root) let space: Space = try serializer.extract(from: serialized, path: .root) XCTAssertEqual(space.subspaces.count, 1) XCTAssertEqual(space.subspace(SerializableSubspace.self)?.subspaceField, 10) XCTAssertEqual(space.entities.count, 1) XCTAssertEqual(space.entities[0].id, 1) XCTAssertEqual(space.entities[0].type, 2) XCTAssertEqual(space.entities[0].component(ofType: SerializableComponent.self)?.field, 20) } func testCanSerializeSpace() { let space = Space() XCTAssertTrue(GameSerializer.canSerialize(space)) } func testCanSerializeSpaceChecksComponents() { let space = Space() space.addEntity(Entity(components: [SerializableComponent(field: 1)])) XCTAssertTrue(GameSerializer.canSerialize(space)) } func testCanSerializeSpaceFailsOnNonSerializableComponent() { let space = Space() space.addEntity(Entity(components: [UnserializableComponent()])) XCTAssertFalse(GameSerializer.canSerialize(space)) } func testCanSerializeSpaceFailsOnNonSerializableSubspace() { let space = Space() space.addSubspace(UnserializableSubspace()) XCTAssertFalse(GameSerializer.canSerialize(space)) } // MARK: Presets func testDeserializePreset() throws { let json: JSON = [ "presetName": "Player", "presetType": "entity", "presetVariables": [ "x": "number", "y": [ "type": "number", "default": 20.2 ], ], "presetData": [ "contentType": "entity", "typeName": "Entity", "data": [ "id": 1, "type": 0xff, "components": [ [ "contentType": "component", "typeName": "PositionComponent", "data": [ "x": [ "presetVariable": "x" ], "y": [ "presetVariable": "y" ], ], ], ], ], ], ] let preset = try SerializedPreset(json: json, path: .root) XCTAssertEqual("Player", preset.name) XCTAssertEqual(.entity, preset.type) // Check preset serialized within XCTAssertEqual(preset.data.contentType, .entity) XCTAssertEqual(preset.data.typeName, "Entity") } func testReplacePresetVariables() throws { let json: JSON = [ "presetName": "Player", "presetType": "entity", "presetVariables": [ "x": "number", "y": "bool", "z": [ "type": "string", "default": "abc" ], ], "presetData": [ "contentType": "entity", "typeName": "Entity", "data": [ "id": 1, "type": 0xff, "components": [ [ "contentType": "component", "typeName": "PositionComponent", "data": [ "x": [ "presetVariable": "x" ], "y": [ "presetVariable": "y" ], "z": [ "presetVariable": "z" ], ], ], ], ], ], ] let preset = try SerializedPreset(json: json, path: .root) let expanded = try preset.expandPreset(withVariables: [ "x": 10, "y": false, ]) let data = expanded.data // Verify data XCTAssertEqual(data["components"]?[0]["data"]?["x"]?.double, 10) XCTAssertEqual(data["components"]?[0]["data"]?["y"]?.bool, false) XCTAssertEqual(data["components"]?[0]["data"]?["z"]?.string, "abc") } func testReplacePresetVariables_respectsVariablesPlaceholderValue() throws { let json: JSON = [ "presetName": "Player", "presetType": "entity", "presetVariables": [ "x": "number", "y": "bool", "z": [ "type": "string", "default": "abc" ] ], "variablesPlaceholder": "aCustomPlaceholder", "presetData": [ "contentType": "entity", "typeName": "Entity", "data": [ "id": 1, "type": 0xff, "components": [ [ "contentType": "component", "typeName": "PositionComponent", "data": [ "x": [ "aCustomPlaceholder": "x" ], "y": [ "aCustomPlaceholder": "y" ], "z": [ "aCustomPlaceholder": "z" ], ], ], ], ], ], ] let preset = try SerializedPreset(json: json, path: .root) let expanded = try preset.expandPreset(withVariables: [ "x": 10, "y": false, ]) let data = expanded.data // Verify data XCTAssertEqual(data["components"]?[0]["data"]?["x"]?.double, 10) XCTAssertEqual(data["components"]?[0]["data"]?["y"]?.bool, false) XCTAssertEqual(data["components"]?[0]["data"]?["z"]?.string, "abc") } func testEmptyPresetSerialization() { let expected: JSON = [ "presetName": "PresetName", "presetType": "entity", "presetVariables": [:], "presetData": [ "contentType": "entity", "data": [:], "typeName": "Entity", ] ] let preset = SerializedPreset( name: "PresetName", type: .entity, variables: [:], data: Serialized(typeName: "Entity", contentType: .entity, data: [:]) ) let result = preset.serialized() assertEquals(expected, result) } func testPresetSerialization_emitsVariablesPlaceholder() { let expected: JSON = [ "presetName": "PresetName", "presetType": "entity", "presetVariables": [:], "variablesPlaceholder": "aCustomPlaceholder", "presetData": [ "contentType": "entity", "data": [:], "typeName": "Entity", ] ] let preset = SerializedPreset( name: "PresetName", type: .entity, variables: [:], variablesPlaceholder: "aCustomPlaceholder", data: Serialized(typeName: "Entity", contentType: .entity, data: [:]) ) let result = preset.serialized() assertEquals(expected, result) } func testPresetSerialization() { let expected: JSON = [ "presetName": "PresetName", "presetType": "entity", "presetVariables": [ "var1": [ "type": "number", "default": 1, ], "var2": "number", ], "presetData": [ "typeName": "TypeName", "presets": [ [ "presetName": "Player", "presetType": "entity", "presetVariables": [:], "presetData": [ "contentType": "entity", "data": [:], "typeName": "Entity", ] ] ], "data": [:], "contentType": "entity", ] ] let innerPreset = SerializedPreset( name: "Player", type: .entity, variables: [:], data: Serialized(typeName: "Entity", contentType: .entity, data: [:]) ) let preset = SerializedPreset( name: "PresetName", type: .entity, variables: [ "var1": SerializedPreset.Variable(name: "var1", type: .number, defaultValue: 1), "var2": SerializedPreset.Variable(name: "var2", type: .number) ], data: Serialized(typeName: "TypeName", presets: [innerPreset], contentType: .entity, data: [:]) ) let result = preset.serialized() assertEquals(expected, result) } func testSimplePresetDeserialization() throws { let json: JSON = [ "presetName": "Player", "presetType": "entity", "presetVariables": [ "var1": [ "type": "number", "default": 0 ], "var2": "string", ], "presetData": [ "contentType": "entity", "typeName": "Entity", "data": [], ], ] let preset = try SerializedPreset(json: json, path: .root) XCTAssertEqual(preset.name, "Player") XCTAssertEqual(preset.type, .entity) XCTAssertEqual(preset.variables.count, 2) XCTAssertEqual(preset.variables["var1"]?.name, "var1") XCTAssertEqual(preset.variables["var1"]?.type, .number) XCTAssertEqual(preset.variables["var1"]?.defaultValue, .number(0)) XCTAssertEqual(preset.variables["var2"]?.name, "var2") XCTAssertEqual(preset.variables["var2"]?.type, .string) } func testPresetDeserialization_presetsAreProperlyScoped() throws { let json: JSON = [ "presetName": "Object", "presetType": "space", "presetVariables": [ "var1": [ "type": "number", "default": 0 ], "var2": "string", ], "presetData": [ "contentType": "space", "typeName": "Space", "data": [ "entities": [ [ "contentType": "entity", "typeName": "Entity", "presets": [ [ "presetName": "Nested", "presetType": "component", "presetVariables": [ "var1": [ "type": "number", "default": 0 ], ], "presetData": [ "contentType": "component", "typeName": "SerializableComponent", "data": [ "field": [ "presetVariable": "var1" ], ], ], ], ], "data": [ "id": 0, "type": 0, "components": [], ], ], [ "contentType": "entity", "typeName": "Entity", "data": [ "id": 0, "type": 0, "components": [ // Reference to preset created in previous // entity should not be visible in this entity. [ "contentType": "preset", "typeName": "Nested", "vars": [ "var1": 2, ], ], ], ], ], ], "subspaces": [], ], ], ] do { let preset = try SerializedPreset(json: json, path: .root) let serializer = GameSerializer(typeProvider: Provider()) let _: Space = try serializer.extract( from: preset.data, path: .root.dictionary("presetData").dictionary("data") ) XCTFail("Should have thrown error") } catch DeserializationError.presetNotFound( "Nested", let path ) { XCTAssertEqual(path.asJsonAccessString(), "<root>.presetData.data.entities[1].components[0].typeName") } catch { XCTFail("Expected DeserializationError.presetNotFound error, found \(error).") } } func testPresetSerializedDataDifferentTypeError() { // If the type specified in 'presetName' differs from the presetData's // inner 'contentType', an error should be raised. do { let json: JSON = [ "presetName": "Player", "presetType": "entity", "presetVariables": [:], "presetData": [ "contentType": "custom", "typeName": "MyType", "data": [:], ] ] _ = try SerializedPreset(json: json, path: .root) XCTFail("Should have thrown error") } catch let error as DeserializationError { XCTAssertEqual( error.description, "Deserialization error @ <root>.presetData.contentType: Expected preset data of type 'entity', but received preset with contentType 'custom' in preset 'Player'" ) } catch { XCTFail("Expected DeserializationError error, found \(error)") } } func testPresetSerializedDataNotDictionaryError() { // Presets can only contain dictionaries within their 'presetData' key do { let json: JSON = [ "presetName": "Player", "presetType": "entity", "presetVariables": [:], "presetData": [], ] _ = try SerializedPreset(json: json, path: .root) XCTFail("Should have thrown error") } catch let error as DeserializationError { XCTAssertEqual( error.description, "Deserialization error @ <root>.presetData: Expected 'presetData' to contain a dictionary in preset 'Player'" ) } catch { XCTFail("Expected DeserializationError error, found \(error)") } } func testDeserializePresetsKeyNotArray() { // 'presets' key in serialized objects need to be an array. do { let json: JSON = [ "contentType": "entity", "typeName": "Entity", "presets": [ // Dictionary, not an array "presetName": "Player", "presetType": "entity", "presetVariables": [:], "presetData": [], ], "data": [ "id": 0, "type": 0, "components": [], ], ] _ = try Serialized(json: json, path: .root) XCTFail("Should have thrown error") } catch let error as DeserializationError { XCTAssertEqual( error.description, "Deserialization error @ <root>.presets: Expected 'presets' to be an array, found 'dictionary'" ) } catch { XCTFail("Expected DeserializationError error, found \(error)") } } func testPresetCannotRepresentPresets() { // Presets are not allowed to represent 'preset' typed contents do { let json: JSON = [ "presetName": "Player", "presetType": "preset", "presetVariables": [:], "presetData": [ "contentType": "preset", "typeName": "SerializedPreset", "data": [:], ], ] _ = try SerializedPreset(json: json, path: .root) XCTFail("Should have thrown error") } catch let error as DeserializationError { XCTAssertEqual( error.description, "Deserialization error @ <root>: Presets cannot represent preset types themselves in preset 'Player'" ) } catch { XCTFail("Expected DeserializationError error, found \(error)") } } func testPresetVariableTypeError() { do { let json: JSON = [ "presetName": "Player", "presetType": "entity", "presetVariables": [ "var": "number", ], "presetData": [ "contentType": "entity", "typeName": "Entity", "data": [ "from-preset": [ "presetVariable": "var" ], ], ], ] let preset = try SerializedPreset(json: json, path: .root) _ = try preset.expandPreset(withVariables: [ "var": "but i'm a string!" ]) XCTFail("Should have thrown error") } catch { XCTAssert(error is SerializedPreset.VariableReplaceError) } } func testPresetNonExistentVariableError() { do { let json: JSON = [ "presetName": "Player", "presetType": "entity", "presetVariables": [:], "presetData": [ "contentType": "entity", "typeName": "Entity", "data": [ "from-preset": [ "presetVariable": "var" ], ], ], ] let preset = try SerializedPreset(json: json, path: .root) _ = try preset.expandPreset(withVariables: ["var": "abc"]) XCTFail("Should have thrown error") } catch { XCTAssert(error is SerializedPreset.VariableReplaceError) } } func testPresetMissingVariableError() { do { let json: JSON = [ "presetName": "Player", "presetType": "entity", "presetVariables": [ "var": "number" ], "presetData": [ "contentType": "entity", "typeName": "Entity", "data": [ "from-preset": [ "presetVariable": "var" ], ], ], ] let preset = try SerializedPreset(json: json, path: .root) _ = try preset.expandPreset(withVariables: [:]) XCTFail("Should have thrown error") } catch { XCTAssert(error is SerializedPreset.VariableReplaceError) } } func testPresetDefaultVariableTypeError() { do { let json: JSON = [ "presetName": "Player", "presetType": "entity", "presetVariables": [ "broken": [ "type": "number", "default": "but i'm a string!" ], ], "presetData": [ "contentType": "entity", "typeName": "Entity", "data": [:], ], ] _ = try SerializedPreset(json: json, path: .root) XCTFail("Should have failed") } catch let error as DeserializationError { XCTAssertEqual( error.description, "Deserialization error @ <root>.presetVariables.broken: Default value for preset variable 'broken' has a different type (string) than declared (number) in preset 'Player'" ) } catch { XCTFail("Expected DeserializationError error, found \(error)") } } // MARK: Preset expansion in serialized object func testPresetExpansion() throws { let serializer = GameSerializer(typeProvider: Provider()) let json: JSON = [ "contentType": "space", "typeName": "Space", // Presets are defined here, for an entity and a subspace... "presets": [ [ "presetName": "Player", "presetType": "entity", "presetVariables": [ "var": "number", ], "presetData": [ "contentType": "entity", "typeName": "Entity", "data": [ "id": 1, "type": 2, "components": [ [ "contentType": "component", "typeName": "SerializableComponent", "data": [ "field": [ "presetVariable": "var" ], ], ], ], ], ], ], [ "presetName": "ASubspace", "presetType": "subspace", "presetVariables": [ "var": "number", ], "presetData": [ "contentType": "subspace", "typeName": "SerializableSubspace", "data": [ "subspaceField": [ "presetVariable": "var" ], ], ], ], ], // Presets are expanded here! "data": [ "subspaces": [ [ "contentType": "preset", "typeName": "ASubspace", "data": [ "var": 10, ], ], ], "entities": [ [ "contentType": "preset", "typeName": "Player", "data": [ "var": 20, ], ], ], ], ] let serialized = try Serialized(json: json, path: .root) let space: Space = try serializer.extract(from: serialized, path: .root) XCTAssertEqual(space.subspaces.count, 1) XCTAssertEqual(space.subspace(SerializableSubspace.self)?.subspaceField, 10) XCTAssertEqual(space.entities.count, 1) XCTAssertEqual(space.entities[0].id, 1) XCTAssertEqual(space.entities[0].type, 2) XCTAssertEqual(space.entities[0].component(ofType: SerializableComponent.self)?.field, 20) } func testRecursivePresetExpansion() throws { // Tests that a moderately recursive-looking preset does not explode // during expansion, and results in an error during deserialization let serializer = GameSerializer(typeProvider: Provider()) let json: JSON = [ "contentType": "space", "typeName": "Space", "presets": [ [ "presetName": "Player", "presetType": "entity", "presetVariables": [ "var": "number", ], "presetData": [ "contentType": "entity", "typeName": "Entity", "presets": [ [ "presetName": "Player", "presetType": "entity", "presetVariables": [:], "presetData": [ "contentType": "entity", "typeName": "Entity", "data": [:], ], ], ], "data": [ "id": 1, "type": 2, "components": [ [ "contentType": "preset", "typeName": "Player", "data": [:], ], ], ], ], ], ], "data": [ "subspaces": [], "entities": [ [ "contentType": "preset", "typeName": "Player", "data": [ "var": 20, ], ], ], ], ] let serialized = try Serialized(json: json, path: .root) do { let _: Space = try serializer.extract(from: serialized, path: .root) } catch let error as DeserializationError { XCTAssertEqual( error.description, "Deserialization error @ <root>.entities[0].components[0].presetData.data.data: unrecognized serialized type name 'Entity'" ) } catch { XCTFail("Expected DeserializationError error, found \(error)") } } func testRecursivePresetExpansion_2() throws { // Tests that a moderately recursive-looking preset does not explode // during expansion, and results in an error during deserialization let serializer = GameSerializer(typeProvider: Provider()) let json: JSON = [ "contentType": "space", "typeName": "Space", "presets": [ [ "presetName": "Player", "presetType": "entity", "presetVariables": [ "var": "number", ], "presets": [ [ "presetName": "Player", "presetType": "entity", "presetVariables": [:], "presetData": [ "contentType": "entity", "typeName": "Entity", "data": [ "id": 1, "type": 2, "components": [ [ "contentType": "preset", "typeName": "Player", "data": [:], ], ], ], ], ], ], "presetData": [ "contentType": "entity", "typeName": "Entity", "presets": [ [ "presetName": "Player", "presetType": "entity", "presetVariables": [:], "presetData": [ "contentType": "entity", "typeName": "Entity", "data": [:], ], ], ], "data": [ "id": 1, "type": 2, "components": [ [ "contentType": "preset", "typeName": "Player", "data": [:], ], ], ], ], ], ], "data": [ "subspaces": [], "entities": [ [ "contentType": "preset", "typeName": "Player", "data": [ "var": 20, ], ], ], ], ] let serialized = try Serialized(json: json, path: .root) do { let _: Space = try serializer.extract(from: serialized, path: .root) } catch let error as DeserializationError { XCTAssertEqual( error.description, "Deserialization error @ <root>.entities[0].components[0].presetData.data.data: unrecognized serialized type name 'Entity'" ) } catch { XCTFail("Expected DeserializationError error, found \(error)") } } private func assertEquals(_ expected: JSON, _ actual: JSON, line: UInt = #line) { guard expected != actual else { return } do { let encoder = JSONEncoder() encoder.outputFormatting = [.prettyPrinted, .sortedKeys] let expString = try XCTUnwrap(String(data: try encoder.encode(expected), encoding: .utf8)) let actString = try XCTUnwrap(String(data: try encoder.encode(actual), encoding: .utf8)) XCTFail( """ (\(expected)) is not equal to (\(actual)) Expected JSON: \(expString) Actual JSON: \(actString) """, line: line ) } catch { XCTFail("(\(expected)) is not equal to (\(actual))", line: line) } } }
mit
01c379f010149173b9bc939e351143d7
34.216906
187
0.413704
5.869484
false
false
false
false
HassanEskandari/Eureka
Source/Core/Core.swift
1
42513
// Core.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import UIKit // MARK: Row internal class RowDefaults { static var cellUpdate = [String: (BaseCell, BaseRow) -> Void]() static var cellSetup = [String: (BaseCell, BaseRow) -> Void]() static var onCellHighlightChanged = [String: (BaseCell, BaseRow) -> Void]() static var rowInitialization = [String: (BaseRow) -> Void]() static var onRowValidationChanged = [String: (BaseCell, BaseRow) -> Void]() static var rawCellUpdate = [String: Any]() static var rawCellSetup = [String: Any]() static var rawOnCellHighlightChanged = [String: Any]() static var rawRowInitialization = [String: Any]() static var rawOnRowValidationChanged = [String: Any]() } // MARK: FormCells public struct CellProvider<Cell: BaseCell> where Cell: CellType { /// Nibname of the cell that will be created. public private (set) var nibName: String? /// Bundle from which to get the nib file. public private (set) var bundle: Bundle! public init() {} public init(nibName: String, bundle: Bundle? = nil) { self.nibName = nibName self.bundle = bundle ?? Bundle(for: Cell.self) } /** Creates the cell with the specified style. - parameter cellStyle: The style with which the cell will be created. - returns: the cell */ func makeCell(style: UITableViewCellStyle) -> Cell { if let nibName = self.nibName { return bundle.loadNibNamed(nibName, owner: nil, options: nil)!.first as! Cell } return Cell.init(style: style, reuseIdentifier: nil) } } /** Enumeration that defines how a controller should be created. - Callback->VCType: Creates the controller inside the specified block - NibFile: Loads a controller from a nib file in some bundle - StoryBoard: Loads the controller from a Storyboard by its storyboard id */ public enum ControllerProvider<VCType: UIViewController> { /** * Creates the controller inside the specified block */ case callback(builder: (() -> VCType)) /** * Loads a controller from a nib file in some bundle */ case nibFile(name: String, bundle: Bundle?) /** * Loads the controller from a Storyboard by its storyboard id */ case storyBoard(storyboardId: String, storyboardName: String, bundle: Bundle?) func makeController() -> VCType { switch self { case .callback(let builder): return builder() case .nibFile(let nibName, let bundle): return VCType.init(nibName: nibName, bundle:bundle ?? Bundle(for: VCType.self)) case .storyBoard(let storyboardId, let storyboardName, let bundle): let sb = UIStoryboard(name: storyboardName, bundle: bundle ?? Bundle(for: VCType.self)) return sb.instantiateViewController(withIdentifier: storyboardId) as! VCType } } } /** Defines how a controller should be presented. - Show?: Shows the controller with `showViewController(...)`. - PresentModally?: Presents the controller modally. - SegueName?: Performs the segue with the specified identifier (name). - SegueClass?: Performs a segue from a segue class. */ public enum PresentationMode<VCType: UIViewController> { /** * Shows the controller, created by the specified provider, with `showViewController(...)`. */ case show(controllerProvider: ControllerProvider<VCType>, onDismiss: ((UIViewController) -> Void)?) /** * Presents the controller, created by the specified provider, modally. */ case presentModally(controllerProvider: ControllerProvider<VCType>, onDismiss: ((UIViewController) -> Void)?) /** * Performs the segue with the specified identifier (name). */ case segueName(segueName: String, onDismiss: ((UIViewController) -> Void)?) /** * Performs a segue from a segue class. */ case segueClass(segueClass: UIStoryboardSegue.Type, onDismiss: ((UIViewController) -> Void)?) case popover(controllerProvider: ControllerProvider<VCType>, onDismiss: ((UIViewController) -> Void)?) public var onDismissCallback: ((UIViewController) -> Void)? { switch self { case .show(_, let completion): return completion case .presentModally(_, let completion): return completion case .segueName(_, let completion): return completion case .segueClass(_, let completion): return completion case .popover(_, let completion): return completion } } /** Present the view controller provided by PresentationMode. Should only be used from custom row implementation. - parameter viewController: viewController to present if it makes sense (normally provided by makeController method) - parameter row: associated row - parameter presentingViewController: form view controller */ public func present(_ viewController: VCType!, row: BaseRow, presentingController: FormViewController) { switch self { case .show(_, _): presentingController.show(viewController, sender: row) case .presentModally(_, _): presentingController.present(viewController, animated: true) case .segueName(let segueName, _): presentingController.performSegue(withIdentifier: segueName, sender: row) case .segueClass(let segueClass, _): let segue = segueClass.init(identifier: row.tag, source: presentingController, destination: viewController) presentingController.prepare(for: segue, sender: row) segue.perform() case .popover(_, _): guard let porpoverController = viewController.popoverPresentationController else { fatalError() } porpoverController.sourceView = porpoverController.sourceView ?? presentingController.tableView presentingController.present(viewController, animated: true) } } /** Creates the view controller specified by presentation mode. Should only be used from custom row implementation. - returns: the created view controller or nil depending on the PresentationMode type. */ public func makeController() -> VCType? { switch self { case .show(let controllerProvider, let completionCallback): let controller = controllerProvider.makeController() let completionController = controller as? RowControllerType if let callback = completionCallback { completionController?.onDismissCallback = callback } return controller case .presentModally(let controllerProvider, let completionCallback): let controller = controllerProvider.makeController() let completionController = controller as? RowControllerType if let callback = completionCallback { completionController?.onDismissCallback = callback } return controller case .popover(let controllerProvider, let completionCallback): let controller = controllerProvider.makeController() controller.modalPresentationStyle = .popover let completionController = controller as? RowControllerType if let callback = completionCallback { completionController?.onDismissCallback = callback } return controller default: return nil } } } /** * Protocol to be implemented by custom formatters. */ public protocol FormatterProtocol { func getNewPosition(forPosition: UITextPosition, inTextInput textInput: UITextInput, oldValue: String?, newValue: String?) -> UITextPosition } // MARK: Predicate Machine enum ConditionType { case hidden, disabled } /** Enumeration that are used to specify the disbaled and hidden conditions of rows - Function: A function that calculates the result - Predicate: A predicate that returns the result */ public enum Condition { /** * Calculate the condition inside a block * * @param Array of tags of the rows this function depends on * @param Form->Bool The block that calculates the result * * @return If the condition is true or false */ case function([String], (Form)->Bool) /** * Calculate the condition using a NSPredicate * * @param NSPredicate The predicate that will be evaluated * * @return If the condition is true or false */ case predicate(NSPredicate) } extension Condition : ExpressibleByBooleanLiteral { /** Initialize a condition to return afixed boolean value always */ public init(booleanLiteral value: Bool) { self = Condition.function([]) { _ in return value } } } extension Condition : ExpressibleByStringLiteral { /** Initialize a Condition with a string that will be converted to a NSPredicate */ public init(stringLiteral value: String) { self = .predicate(NSPredicate(format: value)) } /** Initialize a Condition with a string that will be converted to a NSPredicate */ public init(unicodeScalarLiteral value: String) { self = .predicate(NSPredicate(format: value)) } /** Initialize a Condition with a string that will be converted to a NSPredicate */ public init(extendedGraphemeClusterLiteral value: String) { self = .predicate(NSPredicate(format: value)) } } // MARK: Errors /** Errors thrown by Eureka - DuplicatedTag: When a section or row is inserted whose tag dows already exist */ public enum EurekaError: Error { case duplicatedTag(tag: String) } //Mark: FormViewController /** * A protocol implemented by FormViewController */ public protocol FormViewControllerProtocol { var tableView: UITableView! { get } func beginEditing<T>(of: Cell<T>) func endEditing<T>(of: Cell<T>) func insertAnimation(forRows rows: [BaseRow]) -> UITableViewRowAnimation func deleteAnimation(forRows rows: [BaseRow]) -> UITableViewRowAnimation func reloadAnimation(oldRows: [BaseRow], newRows: [BaseRow]) -> UITableViewRowAnimation func insertAnimation(forSections sections: [Section]) -> UITableViewRowAnimation func deleteAnimation(forSections sections: [Section]) -> UITableViewRowAnimation func reloadAnimation(oldSections: [Section], newSections: [Section]) -> UITableViewRowAnimation } /** * Navigation options for a form view controller. */ public struct RowNavigationOptions: OptionSet { private enum NavigationOptions: Int { case disabled = 0, enabled = 1, stopDisabledRow = 2, skipCanNotBecomeFirstResponderRow = 4 } public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue} private init(_ options: NavigationOptions ) { self.rawValue = options.rawValue } /// No navigation. public static let Disabled = RowNavigationOptions(.disabled) /// Full navigation. public static let Enabled = RowNavigationOptions(.enabled) /// Break navigation when next row is disabled. public static let StopDisabledRow = RowNavigationOptions(.stopDisabledRow) /// Break navigation when next row cannot become first responder. public static let SkipCanNotBecomeFirstResponderRow = RowNavigationOptions(.skipCanNotBecomeFirstResponderRow) } /** * Defines the configuration for the keyboardType of FieldRows. */ public struct KeyboardReturnTypeConfiguration { /// Used when the next row is available. public var nextKeyboardType = UIReturnKeyType.next /// Used if next row is not available. public var defaultKeyboardType = UIReturnKeyType.default public init() {} public init(nextKeyboardType: UIReturnKeyType, defaultKeyboardType: UIReturnKeyType) { self.nextKeyboardType = nextKeyboardType self.defaultKeyboardType = defaultKeyboardType } } /** * Options that define when an inline row should collapse. */ public struct InlineRowHideOptions: OptionSet { private enum _InlineRowHideOptions: Int { case never = 0, anotherInlineRowIsShown = 1, firstResponderChanges = 2 } public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue} private init(_ options: _InlineRowHideOptions ) { self.rawValue = options.rawValue } /// Never collapse automatically. Only when user taps inline row. public static let Never = InlineRowHideOptions(.never) /// Collapse qhen another inline row expands. Just one inline row will be expanded at a time. public static let AnotherInlineRowIsShown = InlineRowHideOptions(.anotherInlineRowIsShown) /// Collapse when first responder changes. public static let FirstResponderChanges = InlineRowHideOptions(.firstResponderChanges) } /// View controller that shows a form. open class FormViewController: UIViewController, FormViewControllerProtocol, FormDelegate { @IBOutlet public var tableView: UITableView! private lazy var _form: Form = { [weak self] in let form = Form() form.delegate = self return form }() public var form: Form { get { return _form } set { guard form !== newValue else { return } _form.delegate = nil tableView?.endEditing(false) _form = newValue _form.delegate = self if isViewLoaded { tableView?.reloadData() } } } /// Extra space to leave between between the row in focus and the keyboard open var rowKeyboardSpacing: CGFloat = 0 /// Enables animated scrolling on row navigation open var animateScroll = false /// Accessory view that is responsible for the navigation between rows open var navigationAccessoryView: NavigationAccessoryView! /// Defines the behaviour of the navigation between rows public var navigationOptions: RowNavigationOptions? private var tableViewStyle: UITableViewStyle = .grouped public init(style: UITableViewStyle) { super.init(nibName: nil, bundle: nil) tableViewStyle = style } public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } open override func viewDidLoad() { super.viewDidLoad() navigationAccessoryView = NavigationAccessoryView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 44.0)) navigationAccessoryView.autoresizingMask = .flexibleWidth if tableView == nil { tableView = UITableView(frame: view.bounds, style: tableViewStyle) tableView.autoresizingMask = UIViewAutoresizing.flexibleWidth.union(.flexibleHeight) if #available(iOS 9.0, *) { tableView.cellLayoutMarginsFollowReadableWidth = false } } if tableView.superview == nil { view.addSubview(tableView) } if tableView.delegate == nil { tableView.delegate = self } if tableView.dataSource == nil { tableView.dataSource = self } tableView.estimatedRowHeight = BaseRow.estimatedRowHeight tableView.setEditing(true, animated: false) tableView.allowsSelectionDuringEditing = true } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) animateTableView = true let selectedIndexPaths = tableView.indexPathsForSelectedRows ?? [] if !selectedIndexPaths.isEmpty { tableView.reloadRows(at: selectedIndexPaths, with: .none) } selectedIndexPaths.forEach { tableView.selectRow(at: $0, animated: false, scrollPosition: .none) } let deselectionAnimation = { [weak self] (context: UIViewControllerTransitionCoordinatorContext) in selectedIndexPaths.forEach { self?.tableView.deselectRow(at: $0, animated: context.isAnimated) } } let reselection = { [weak self] (context: UIViewControllerTransitionCoordinatorContext) in if context.isCancelled { selectedIndexPaths.forEach { self?.tableView.selectRow(at: $0, animated: false, scrollPosition: .none) } } } if let coordinator = transitionCoordinator { coordinator.animate(alongsideTransition: deselectionAnimation, completion: reselection) } else { selectedIndexPaths.forEach { tableView.deselectRow(at: $0, animated: false) } } NotificationCenter.default.addObserver(self, selector: #selector(FormViewController.keyboardWillShow(_:)), name: Notification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(FormViewController.keyboardWillHide(_:)), name: Notification.Name.UIKeyboardWillHide, object: nil) } open override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) NotificationCenter.default.removeObserver(self, name: Notification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.removeObserver(self, name: Notification.Name.UIKeyboardWillHide, object: nil) } open override func prepare(for segue: UIStoryboardSegue, sender: Any?) { super.prepare(for: segue, sender: sender) let baseRow = sender as? BaseRow baseRow?.prepare(for: segue) } /** Returns the navigation accessory view if it is enabled. Returns nil otherwise. */ open func inputAccessoryView(for row: BaseRow) -> UIView? { let options = navigationOptions ?? Form.defaultNavigationOptions guard options.contains(.Enabled) else { return nil } guard row.baseCell.cellCanBecomeFirstResponder() else { return nil} navigationAccessoryView.previousButton.isEnabled = nextRow(for: row, withDirection: .up) != nil navigationAccessoryView.doneButton.target = self navigationAccessoryView.doneButton.action = #selector(FormViewController.navigationDone(_:)) navigationAccessoryView.previousButton.target = self navigationAccessoryView.previousButton.action = #selector(FormViewController.navigationAction(_:)) navigationAccessoryView.nextButton.target = self navigationAccessoryView.nextButton.action = #selector(FormViewController.navigationAction(_:)) navigationAccessoryView.nextButton.isEnabled = nextRow(for: row, withDirection: .down) != nil return navigationAccessoryView } // MARK: FormViewControllerProtocol /** Called when a cell becomes first responder */ public final func beginEditing<T>(of cell: Cell<T>) { cell.row.isHighlighted = true cell.row.updateCell() RowDefaults.onCellHighlightChanged["\(type(of: cell.row!))"]?(cell, cell.row) cell.row.callbackOnCellHighlightChanged?() guard let _ = tableView, (form.inlineRowHideOptions ?? Form.defaultInlineRowHideOptions).contains(.FirstResponderChanges) else { return } let row = cell.baseRow let inlineRow = row?._inlineRow for row in form.allRows.filter({ $0 !== row && $0 !== inlineRow && $0._inlineRow != nil }) { if let inlineRow = row as? BaseInlineRowType { inlineRow.collapseInlineRow() } } } /** Called when a cell resigns first responder */ public final func endEditing<T>(of cell: Cell<T>) { cell.row.isHighlighted = false cell.row.wasBlurred = true RowDefaults.onCellHighlightChanged["\(type(of: self))"]?(cell, cell.row) cell.row.callbackOnCellHighlightChanged?() if cell.row.validationOptions.contains(.validatesOnBlur) || (cell.row.wasChanged && cell.row.validationOptions.contains(.validatesOnChangeAfterBlurred)) { cell.row.validate() } cell.row.updateCell() } /** Returns the animation for the insertion of the given rows. */ open func insertAnimation(forRows rows: [BaseRow]) -> UITableViewRowAnimation { return .fade } /** Returns the animation for the deletion of the given rows. */ open func deleteAnimation(forRows rows: [BaseRow]) -> UITableViewRowAnimation { return .fade } /** Returns the animation for the reloading of the given rows. */ open func reloadAnimation(oldRows: [BaseRow], newRows: [BaseRow]) -> UITableViewRowAnimation { return .automatic } /** Returns the animation for the insertion of the given sections. */ open func insertAnimation(forSections sections: [Section]) -> UITableViewRowAnimation { return .automatic } /** Returns the animation for the deletion of the given sections. */ open func deleteAnimation(forSections sections: [Section]) -> UITableViewRowAnimation { return .automatic } /** Returns the animation for the reloading of the given sections. */ open func reloadAnimation(oldSections: [Section], newSections: [Section]) -> UITableViewRowAnimation { return .automatic } // MARK: TextField and TextView Delegate open func textInputShouldBeginEditing<T>(_ textInput: UITextInput, cell: Cell<T>) -> Bool { return true } open func textInputDidBeginEditing<T>(_ textInput: UITextInput, cell: Cell<T>) { if let row = cell.row as? KeyboardReturnHandler { let next = nextRow(for: cell.row, withDirection: .down) if let textField = textInput as? UITextField { textField.returnKeyType = next != nil ? (row.keyboardReturnType?.nextKeyboardType ?? (form.keyboardReturnType?.nextKeyboardType ?? Form.defaultKeyboardReturnType.nextKeyboardType )) : (row.keyboardReturnType?.defaultKeyboardType ?? (form.keyboardReturnType?.defaultKeyboardType ?? Form.defaultKeyboardReturnType.defaultKeyboardType)) } else if let textView = textInput as? UITextView { textView.returnKeyType = next != nil ? (row.keyboardReturnType?.nextKeyboardType ?? (form.keyboardReturnType?.nextKeyboardType ?? Form.defaultKeyboardReturnType.nextKeyboardType )) : (row.keyboardReturnType?.defaultKeyboardType ?? (form.keyboardReturnType?.defaultKeyboardType ?? Form.defaultKeyboardReturnType.defaultKeyboardType)) } } } open func textInputShouldEndEditing<T>(_ textInput: UITextInput, cell: Cell<T>) -> Bool { return true } open func textInputDidEndEditing<T>(_ textInput: UITextInput, cell: Cell<T>) { } open func textInput<T>(_ textInput: UITextInput, shouldChangeCharactersInRange range: NSRange, replacementString string: String, cell: Cell<T>) -> Bool { return true } open func textInputShouldClear<T>(_ textInput: UITextInput, cell: Cell<T>) -> Bool { return true } open func textInputShouldReturn<T>(_ textInput: UITextInput, cell: Cell<T>) -> Bool { if let nextRow = nextRow(for: cell.row, withDirection: .down) { if nextRow.baseCell.cellCanBecomeFirstResponder() { nextRow.baseCell.cellBecomeFirstResponder() return true } } tableView?.endEditing(true) return true } // MARK: FormDelegate open func valueHasBeenChanged(for: BaseRow, oldValue: Any?, newValue: Any?) {} // MARK: UITableViewDelegate @objc open func tableView(_ tableView: UITableView, willBeginReorderingRowAtIndexPath indexPath: IndexPath) { // end editing if inline cell is first responder let row = form[indexPath] if let inlineRow = row as? BaseInlineRowType, row._inlineRow != nil { inlineRow.collapseInlineRow() } } // MARK: FormDelegate open func sectionsHaveBeenAdded(_ sections: [Section], at indexes: IndexSet) { guard animateTableView else { return } tableView?.beginUpdates() tableView?.insertSections(indexes, with: insertAnimation(forSections: sections)) tableView?.endUpdates() } open func sectionsHaveBeenRemoved(_ sections: [Section], at indexes: IndexSet) { guard animateTableView else { return } tableView?.beginUpdates() tableView?.deleteSections(indexes, with: deleteAnimation(forSections: sections)) tableView?.endUpdates() } open func sectionsHaveBeenReplaced(oldSections: [Section], newSections: [Section], at indexes: IndexSet) { guard animateTableView else { return } tableView?.beginUpdates() tableView?.reloadSections(indexes, with: reloadAnimation(oldSections: oldSections, newSections: newSections)) tableView?.endUpdates() } open func rowsHaveBeenAdded(_ rows: [BaseRow], at indexes: [IndexPath]) { guard animateTableView else { return } tableView?.beginUpdates() tableView?.insertRows(at: indexes, with: insertAnimation(forRows: rows)) tableView?.endUpdates() } open func rowsHaveBeenRemoved(_ rows: [BaseRow], at indexes: [IndexPath]) { guard animateTableView else { return } tableView?.beginUpdates() tableView?.deleteRows(at: indexes, with: deleteAnimation(forRows: rows)) tableView?.endUpdates() } open func rowsHaveBeenReplaced(oldRows: [BaseRow], newRows: [BaseRow], at indexes: [IndexPath]) { guard animateTableView else { return } tableView?.beginUpdates() tableView?.reloadRows(at: indexes, with: reloadAnimation(oldRows: oldRows, newRows: newRows)) tableView?.endUpdates() } // MARK: Private var oldBottomInset: CGFloat? var animateTableView = false } extension FormViewController : UITableViewDelegate { // MARK: UITableViewDelegate open func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { return indexPath } open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard tableView == self.tableView else { return } let row = form[indexPath] // row.baseCell.cellBecomeFirstResponder() may be cause InlineRow collapsed then section count will be changed. Use orignal indexPath will out of section's bounds. if !row.baseCell.cellCanBecomeFirstResponder() || !row.baseCell.cellBecomeFirstResponder() { self.tableView?.endEditing(true) } row.didSelect() } open func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { guard tableView == self.tableView else { return tableView.rowHeight } let row = form[indexPath.section][indexPath.row] return row.baseCell.height?() ?? tableView.rowHeight } open func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { guard tableView == self.tableView else { return tableView.rowHeight } let row = form[indexPath.section][indexPath.row] return row.baseCell.height?() ?? tableView.estimatedRowHeight } open func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return form[section].header?.viewForSection(form[section], type: .header) } open func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return form[section].footer?.viewForSection(form[section], type:.footer) } open func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if let height = form[section].header?.height { return height() } guard let view = form[section].header?.viewForSection(form[section], type: .header) else { return UITableViewAutomaticDimension } guard view.bounds.height != 0 else { return UITableViewAutomaticDimension } return view.bounds.height } open func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { if let height = form[section].footer?.height { return height() } guard let view = form[section].footer?.viewForSection(form[section], type: .footer) else { return UITableViewAutomaticDimension } guard view.bounds.height != 0 else { return UITableViewAutomaticDimension } return view.bounds.height } open func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { guard let section = form[indexPath.section] as? MultivaluedSection else { return false } let row = form[indexPath] guard !row.isDisabled else { return false } guard !(indexPath.row == section.count - 1 && section.multivaluedOptions.contains(.Insert) && section.showInsertIconInAddButton) else { return true } if indexPath.row > 0 && section[indexPath.row - 1] is BaseInlineRowType && section[indexPath.row - 1]._inlineRow != nil { return false } return true } open func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { let row = form[indexPath] let section = row.section! if let _ = row.baseCell.findFirstResponder() { tableView.endEditing(true) } _ = section.remove(at: indexPath.row) DispatchQueue.main.async { tableView.isEditing = !tableView.isEditing tableView.isEditing = !tableView.isEditing } } else if editingStyle == .insert { guard var section = form[indexPath.section] as? MultivaluedSection else { return } guard let multivaluedRowToInsertAt = section.multivaluedRowToInsertAt else { fatalError("Multivalued section multivaluedRowToInsertAt property must be set up") } let newRow = multivaluedRowToInsertAt(max(0, section.count - 1)) section.insert(newRow, at: section.count - 1) DispatchQueue.main.async { tableView.isEditing = !tableView.isEditing tableView.isEditing = !tableView.isEditing } tableView.scrollToRow(at: IndexPath(row: section.count - 1, section: indexPath.section), at: .bottom, animated: true) if newRow.baseCell.cellCanBecomeFirstResponder() { newRow.baseCell.cellBecomeFirstResponder() } else if let inlineRow = newRow as? BaseInlineRowType { inlineRow.expandInlineRow() } } } open func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { guard let section = form[indexPath.section] as? MultivaluedSection, section.multivaluedOptions.contains(.Reorder) && section.count > 1 else { return false } if section.multivaluedOptions.contains(.Insert) && (section.count <= 2 || indexPath.row == (section.count - 1)) { return false } if indexPath.row > 0 && section[indexPath.row - 1] is BaseInlineRowType && section[indexPath.row - 1]._inlineRow != nil { return false } return true } open func tableView(_ tableView: UITableView, targetIndexPathForMoveFromRowAt sourceIndexPath: IndexPath, toProposedIndexPath proposedDestinationIndexPath: IndexPath) -> IndexPath { guard let section = form[sourceIndexPath.section] as? MultivaluedSection else { return sourceIndexPath } guard sourceIndexPath.section == proposedDestinationIndexPath.section else { return sourceIndexPath } let destRow = form[proposedDestinationIndexPath] if destRow is BaseInlineRowType && destRow._inlineRow != nil { return IndexPath(row: proposedDestinationIndexPath.row + (sourceIndexPath.row < proposedDestinationIndexPath.row ? 1 : -1), section:sourceIndexPath.section) } if proposedDestinationIndexPath.row > 0 { let previousRow = form[IndexPath(row: proposedDestinationIndexPath.row - 1, section: proposedDestinationIndexPath.section)] if previousRow is BaseInlineRowType && previousRow._inlineRow != nil { return IndexPath(row: proposedDestinationIndexPath.row + (sourceIndexPath.row < proposedDestinationIndexPath.row ? 1 : -1), section:sourceIndexPath.section) } } if section.multivaluedOptions.contains(.Insert) && proposedDestinationIndexPath.row == section.count - 1 { return IndexPath(row: section.count - 2, section: sourceIndexPath.section) } return proposedDestinationIndexPath } open func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { guard var section = form[sourceIndexPath.section] as? MultivaluedSection else { return } if sourceIndexPath.row < section.count && destinationIndexPath.row < section.count && sourceIndexPath.row != destinationIndexPath.row { let sourceRow = form[sourceIndexPath] animateTableView = false _ = section.remove(at: sourceIndexPath.row) section.insert(sourceRow, at: destinationIndexPath.row) animateTableView = true // update the accessory view let _ = inputAccessoryView(for: sourceRow) } } open func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle { guard let section = form[indexPath.section] as? MultivaluedSection else { return .none } if section.multivaluedOptions.contains(.Insert) && indexPath.row == section.count - 1 { return .insert } if section.multivaluedOptions.contains(.Delete) { return .delete } return .none } open func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool { return self.tableView(tableView, editingStyleForRowAt: indexPath) != .none } } extension FormViewController : UITableViewDataSource { // MARK: UITableViewDataSource open func numberOfSections(in tableView: UITableView) -> Int { return form.count } open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return form[section].count } open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { form[indexPath].updateCell() return form[indexPath].baseCell } open func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return form[section].header?.title } open func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { return form[section].footer?.title } open func sectionIndexTitles(for tableView: UITableView) -> [String]? { return nil } open func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int { return 0 } } extension FormViewController : UIScrollViewDelegate { // MARK: UIScrollViewDelegate open func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { guard let tableView = tableView, scrollView === tableView else { return } tableView.endEditing(true) } } extension FormViewController { // MARK: KeyBoard Notifications /** Called when the keyboard will appear. Adjusts insets of the tableView and scrolls it if necessary. */ @objc open func keyboardWillShow(_ notification: Notification) { guard let table = tableView, let cell = table.findFirstResponder()?.formCell() else { return } let keyBoardInfo = notification.userInfo! let endFrame = keyBoardInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue let keyBoardFrame = table.window!.convert(endFrame.cgRectValue, to: table.superview) let newBottomInset = table.frame.origin.y + table.frame.size.height - keyBoardFrame.origin.y + rowKeyboardSpacing var tableInsets = table.contentInset var scrollIndicatorInsets = table.scrollIndicatorInsets oldBottomInset = oldBottomInset ?? tableInsets.bottom if newBottomInset > oldBottomInset! { tableInsets.bottom = newBottomInset scrollIndicatorInsets.bottom = tableInsets.bottom UIView.beginAnimations(nil, context: nil) UIView.setAnimationDuration((keyBoardInfo[UIKeyboardAnimationDurationUserInfoKey] as! Double)) UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: (keyBoardInfo[UIKeyboardAnimationCurveUserInfoKey] as! Int))!) table.contentInset = tableInsets table.scrollIndicatorInsets = scrollIndicatorInsets if let selectedRow = table.indexPath(for: cell) { table.scrollToRow(at: selectedRow, at: .none, animated: animateScroll) } UIView.commitAnimations() } } /** Called when the keyboard will disappear. Adjusts insets of the tableView. */ @objc open func keyboardWillHide(_ notification: Notification) { guard let table = tableView, let oldBottom = oldBottomInset else { return } let keyBoardInfo = notification.userInfo! var tableInsets = table.contentInset var scrollIndicatorInsets = table.scrollIndicatorInsets tableInsets.bottom = oldBottom scrollIndicatorInsets.bottom = tableInsets.bottom oldBottomInset = nil UIView.beginAnimations(nil, context: nil) UIView.setAnimationDuration((keyBoardInfo[UIKeyboardAnimationDurationUserInfoKey] as! Double)) UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: (keyBoardInfo[UIKeyboardAnimationCurveUserInfoKey] as! Int))!) table.contentInset = tableInsets table.scrollIndicatorInsets = scrollIndicatorInsets UIView.commitAnimations() } } public enum Direction { case up, down } extension FormViewController { // MARK: Navigation Methods @objc func navigationDone(_ sender: UIBarButtonItem) { tableView?.endEditing(true) } @objc func navigationAction(_ sender: UIBarButtonItem) { navigateTo(direction: sender == navigationAccessoryView.previousButton ? .up : .down) } public func navigateTo(direction: Direction) { guard let currentCell = tableView?.findFirstResponder()?.formCell() else { return } guard let currentIndexPath = tableView?.indexPath(for: currentCell) else { assertionFailure(); return } guard let nextRow = nextRow(for: form[currentIndexPath], withDirection: direction) else { return } if nextRow.baseCell.cellCanBecomeFirstResponder() { tableView?.scrollToRow(at: nextRow.indexPath!, at: .none, animated: animateScroll) nextRow.baseCell.cellBecomeFirstResponder(withDirection: direction) } } func nextRow(for currentRow: BaseRow, withDirection direction: Direction) -> BaseRow? { let options = navigationOptions ?? Form.defaultNavigationOptions guard options.contains(.Enabled) else { return nil } guard let next = direction == .down ? form.nextRow(for: currentRow) : form.previousRow(for: currentRow) else { return nil } if next.isDisabled && options.contains(.StopDisabledRow) { return nil } if !next.baseCell.cellCanBecomeFirstResponder() && !next.isDisabled && !options.contains(.SkipCanNotBecomeFirstResponderRow) { return nil } if !next.isDisabled && next.baseCell.cellCanBecomeFirstResponder() { return next } return nextRow(for: next, withDirection:direction) } } extension FormViewControllerProtocol { // MARK: Helpers func makeRowVisible(_ row: BaseRow) { guard let cell = row.baseCell, let indexPath = row.indexPath, let tableView = tableView else { return } if cell.window == nil || (tableView.contentOffset.y + tableView.frame.size.height <= cell.frame.origin.y + cell.frame.size.height) { tableView.scrollToRow(at: indexPath, at: .bottom, animated: true) } } }
mit
6ce9af4bf7b715ac54fa84a6822167e8
39.411597
185
0.669395
5.252409
false
false
false
false
loganSims/wsdot-ios-app
wsdot/TrafficMapViewController.swift
1
26428
// // TrafficMapViewController.swift // WSDOT // // Copyright (c) 2016 Washington State Department of Transportation // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/> // import UIKit import GoogleMaps import GoogleMobileAds import EasyTipView class TrafficMapViewController: UIViewController, MapMarkerDelegate, GMSMapViewDelegate, GMUClusterManagerDelegate, GADBannerViewDelegate { let serviceGroup = DispatchGroup() let SegueGoToPopover = "TrafficMapGoToViewController" let SegueAlertsInArea = "AlertsInAreaViewController" let SegueSettingsPopover = "TrafficMapSettingsViewController" let SegueTravlerInfoViewController = "TravelerInfoViewController" let SegueCameraClusterViewController = "CameraClusterViewController" // Marker Segues let SegueCamerasViewController = "CamerasViewController" let SegueRestAreaViewController = "RestAreaViewController" let SegueHighwayAlertViewController = "HighwayAlertViewController" let SegueCalloutViewController = "CalloutViewController" fileprivate var alertMarkers = Set<GMSMarker>() fileprivate var cameraMarkers = Set<CameraClusterItem>() fileprivate var restAreaMarkers = Set<GMSMarker>() fileprivate let JBLMMarker = GMSMarker(position: CLLocationCoordinate2D(latitude: 47.103033, longitude: -122.584394)) // Mark: Map Icons fileprivate let restAreaIconImage = UIImage(named: "icMapRestArea") fileprivate let restAreaDumpIconImage = UIImage(named: "icMapRestAreaDump") fileprivate let cameraIconImage = UIImage(named: "icMapCamera") fileprivate let cameraBarButtonImage = UIImage(named: "icCamera") fileprivate let cameraHighlightBarButtonImage = UIImage(named: "icCameraHighlight") var tipView = EasyTipView(text: "") @IBOutlet weak var travelInformationButton: UIBarButtonItem! @IBOutlet weak var cameraBarButton: UIBarButtonItem! @IBOutlet weak var bannerView: GADBannerView! @IBOutlet weak var activityIndicatorView: UIActivityIndicatorView! weak fileprivate var embeddedMapViewController: MapViewController! override func viewDidLoad() { super.viewDidLoad() // Set defualt value for camera display if there is none if (UserDefaults.standard.string(forKey: UserDefaultsKeys.cameras) == nil){ UserDefaults.standard.set("on", forKey: UserDefaultsKeys.cameras) } if (UserDefaults.standard.string(forKey: UserDefaultsKeys.cameras) == "on"){ cameraBarButton.image = cameraHighlightBarButtonImage } JBLMMarker.icon = UIImage(named: "icMapJBLM") JBLMMarker.snippet = "jblm" JBLMMarker.userData = "https://images.wsdot.wa.gov/traffic/flowmaps/jblm.png" self.loadCameraMarkers() self.drawCameras() self.loadAlertMarkers() self.drawAlerts() embeddedMapViewController.clusterManager.setDelegate(self, mapDelegate: self) checkForTravelCharts() // Ad Banner bannerView.adUnitID = ApiKeys.getAdId() bannerView.adSize = getFullWidthAdaptiveAdSize() bannerView.rootViewController = self let request = DFPRequest() request.customTargeting = ["wsdotapp":"traffic"] bannerView.load(request) bannerView.delegate = self } func adViewDidReceiveAd(_ bannerView: GADBannerView) { bannerView.isAccessibilityElement = true bannerView.accessibilityLabel = "advertisement banner." } @IBAction func refreshPressed(_ sender: UIBarButtonItem) { MyAnalytics.event(category: "Traffic Map", action: "UIAction", label: "Refresh") self.activityIndicatorView.isHidden = false self.activityIndicatorView.startAnimating() let serviceGroup = DispatchGroup(); fetchCameras(force: true, group: serviceGroup) fetchAlerts(force: true, group: serviceGroup) checkForTravelCharts() serviceGroup.notify(queue: DispatchQueue.main) { self.activityIndicatorView.stopAnimating() self.activityIndicatorView.isHidden = true } } @IBAction func myLocationButtonPressed(_ sender: UIBarButtonItem) { MyAnalytics.event(category: "Traffic Map", action: "UIAction", label: "My Location") embeddedMapViewController.goToUsersLocation() } @IBAction func alertsInAreaButtonPressed(_ sender: UIBarButtonItem) { performSegue(withIdentifier: SegueAlertsInArea, sender: sender) } @IBAction func goToLocation(_ sender: UIBarButtonItem) { performSegue(withIdentifier: SegueGoToPopover, sender: self) } @IBAction func cameraToggleButtonPressed(_ sender: UIBarButtonItem) { let camerasPref = UserDefaults.standard.string(forKey: UserDefaultsKeys.cameras) if let camerasVisible = camerasPref { if (camerasVisible == "on") { MyAnalytics.event(category: "Traffic Map", action: "UIAction", label: "Hide Cameras") UserDefaults.standard.set("off", forKey: UserDefaultsKeys.cameras) sender.image = cameraBarButtonImage removeCameras() } else { MyAnalytics.event(category: "Traffic Map", action: "UIAction", label: "Show Cameras") sender.image = cameraHighlightBarButtonImage UserDefaults.standard.set("on", forKey: UserDefaultsKeys.cameras) drawCameras() } } } @IBAction func travelerInfoAction(_ sender: UIBarButtonItem) { performSegue(withIdentifier: SegueTravlerInfoViewController, sender: self) } @IBAction func settingsAction(_ sender: UIBarButtonItem) { tipView.dismiss() performSegue(withIdentifier: SegueSettingsPopover, sender: self) } // zoom in and out to reload icons for when clustering is toggled func resetMapCamera() { if let mapView = embeddedMapViewController.view as? GMSMapView{ let camera = mapView.camera let camera2 = GMSCameraPosition.camera(withLatitude: camera.target.latitude, longitude: camera.target.longitude, zoom: camera.zoom - 1.0) mapView.moveCamera(GMSCameraUpdate.setCamera(camera2)) mapView.moveCamera(GMSCameraUpdate.setCamera(camera)) } } func resetMapStyle() { if let mapView = embeddedMapViewController.view as? GMSMapView{ MapThemeUtils.setMapStyle(mapView, traitCollection) } } func goTo(_ lat: Double, _ long: Double, _ zoom: Float){ if let mapView = embeddedMapViewController.view as? GMSMapView{ mapView.moveCamera(GMSCameraUpdate.setCamera(GMSCameraPosition.camera(withLatitude: lat, longitude: long, zoom: zoom))) } } /* Checks if "best times to travel charts" are available from the data server, if they are, display an alert badge on the Traveler information menu */ func checkForTravelCharts(){ DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated).async { [weak self] in BestTimesToTravelStore.isBestTimesToTravelAvailable({ available, error in DispatchQueue.main.async { [weak self] in if let selfValue = self{ // show badge on travel information icon let travelInfoButton = UIButton(frame: CGRect(x: 0, y: 0, width: 24, height: 24)) let menuImage = UIImage(named: "icMenu") let templateImage = menuImage?.withRenderingMode(.alwaysTemplate) travelInfoButton.setBackgroundImage(templateImage, for: .normal) travelInfoButton.addTarget(selfValue, action: #selector(selfValue.travelerInfoAction), for: .touchUpInside) if (available){ travelInfoButton.addSubview(UIHelpers.getAlertLabel()) } selfValue.travelInformationButton.customView = travelInfoButton } } }) } } func fetchCameras(force: Bool, group: DispatchGroup) { serviceGroup.enter() DispatchQueue.global().async {[weak self] in CamerasStore.updateCameras(force, completion: { error in if (error == nil){ DispatchQueue.main.async {[weak self] in if let selfValue = self{ selfValue.serviceGroup.leave() selfValue.loadCameraMarkers() selfValue.drawCameras() } } }else{ DispatchQueue.main.async { [weak self] in if let selfValue = self{ selfValue.serviceGroup.leave() AlertMessages.getConnectionAlert(backupURL: WsdotURLS.trafficCameras, message: WSDOTErrorStrings.cameras) } } } }) } } // MARK: Camera marker logic func loadCameraMarkers(){ removeCameras() cameraMarkers.removeAll() let cameras = CamerasStore.getAllCameras() for camera in cameras{ let position = CLLocationCoordinate2D(latitude: camera.latitude, longitude: camera.longitude) cameraMarkers.insert(CameraClusterItem(position: position, name: "camera", camera: camera)) } } func drawCameras(){ let camerasPref = UserDefaults.standard.string(forKey: UserDefaultsKeys.cameras) if (camerasPref! == "on") { for camera in cameraMarkers { embeddedMapViewController.addClusterableMarker(camera) } embeddedMapViewController.clusterReady() } } func removeCameras(){ embeddedMapViewController.removeClusterItems() } // MARK: Alerts marker logic func removeAlerts(){ for alert in alertMarkers{ alert.map = nil } } func fetchAlerts(force: Bool, group: DispatchGroup) { group.enter() HighwayAlertsStore.updateAlerts(force, completion: { error in if (error == nil){ DispatchQueue.main.async {[weak self] in if let selfValue = self{ group.leave() selfValue.loadAlertMarkers() selfValue.drawAlerts() } } }else{ DispatchQueue.main.async { group.leave() AlertMessages.getConnectionAlert(backupURL: WsdotURLS.trafficAlerts, message: WSDOTErrorStrings.highwayAlerts) } } }) } func loadAlertMarkers(){ removeAlerts() alertMarkers.removeAll() for alert in HighwayAlertsStore.getAllAlerts(){ if (alert.startLatitude != 0 && alert.startLongitude != 0) { let alertLocation = CLLocationCoordinate2D(latitude: alert.startLatitude, longitude: alert.startLongitude) let marker = GMSMarker(position: alertLocation) marker.snippet = "alert" marker.icon = UIHelpers.getAlertIcon(forAlert: alert) marker.userData = alert alertMarkers.insert(marker) } } } func drawAlerts(){ if let mapView = embeddedMapViewController.view as? GMSMapView{ let alertsPref = UserDefaults.standard.string(forKey: UserDefaultsKeys.alerts) if let alertsPrefValue = alertsPref { if (alertsPrefValue == "on") { for alertMarker in alertMarkers{ let bounds = GMSCoordinateBounds(coordinate: mapView.projection.visibleRegion().farLeft, coordinate: mapView.projection.visibleRegion().nearRight) if (bounds.contains(alertMarker.position)){ alertMarker.map = mapView } else { alertMarker.map = nil } } } }else{ UserDefaults.standard.set("on", forKey: UserDefaultsKeys.alerts) for alertMarker in alertMarkers{ let bounds = GMSCoordinateBounds(coordinate: mapView.projection.visibleRegion().farLeft, coordinate: mapView.projection.visibleRegion().nearRight) if (bounds.contains(alertMarker.position)){ alertMarker.map = mapView } else { alertMarker.map = nil } } } } } func getAlertsOnScreen() -> [HighwayAlertItem] { var alerts = [HighwayAlertItem]() if let mapView = embeddedMapViewController.view as? GMSMapView{ for alertMarker in alertMarkers{ let bounds = GMSCoordinateBounds(coordinate: mapView.projection.visibleRegion().farLeft, coordinate: mapView.projection.visibleRegion().nearRight) if (bounds.contains(alertMarker.position)){ alerts.append(alertMarker.userData as! HighwayAlertItem) } } } return alerts } func convertAlertMarkersToHighwayAlertItems(markers: [GMSMarker]) -> [HighwayAlertItem] { var alerts = [HighwayAlertItem]() for alertMarker in markers{ alerts.append(alertMarker.userData as! HighwayAlertItem) } return alerts } // MARK: Rest area marker logic func removeRestAreas(){ for restarea in restAreaMarkers{ restarea.map = nil } } func fetchRestAreas(group: DispatchGroup) { group.enter() loadRestAreaMarkers() drawRestArea() group.leave() } func loadRestAreaMarkers(){ removeRestAreas() restAreaMarkers.removeAll() for restarea in RestAreaStore.readRestAreas(){ let restareaLocation = CLLocationCoordinate2D(latitude: restarea.latitude, longitude: restarea.longitude) let marker = GMSMarker(position: restareaLocation) marker.snippet = "restarea" if (restarea.hasDump){ marker.icon = restAreaDumpIconImage }else{ marker.icon = restAreaIconImage } marker.userData = restarea restAreaMarkers.insert(marker) } } func drawRestArea(){ if let mapView = embeddedMapViewController.view as? GMSMapView{ let restAreaPref = UserDefaults.standard.string(forKey: UserDefaultsKeys.restAreas) if let restAreaPrefValue = restAreaPref{ if (restAreaPrefValue == "on") { for restAreaMarker in restAreaMarkers{ restAreaMarker.map = mapView } } } else { UserDefaults.standard.set("on", forKey: UserDefaultsKeys.restAreas) for restAreaMarker in restAreaMarkers{ restAreaMarker.map = mapView } } } } // MARK: JBLM Marker logic func removeJBLM(){ JBLMMarker.map = nil } func drawJBLM(){ if let mapView = embeddedMapViewController.view as? GMSMapView{ let jblmPref = UserDefaults.standard.string(forKey: UserDefaultsKeys.jblmCallout) if let jblmPrefValue = jblmPref{ if (jblmPrefValue == "on") { JBLMMarker.map = mapView } }else{ UserDefaults.standard.set("on", forKey: UserDefaultsKeys.jblmCallout) JBLMMarker.map = mapView } } } // MARK: favorite location func saveCurrentLocation(){ let alertController = UIAlertController(title: "New Favorite Location", message:nil, preferredStyle: .alert) alertController.addTextField { (textfield) in textfield.placeholder = "Name" } alertController.view.tintColor = Colors.tintColor alertController.addAction(UIAlertAction(title: "Cancel", style: .default, handler: nil)) let okAction = UIAlertAction(title: "Ok", style: .default) { (_) -> Void in MyAnalytics.event(category: "Traffic Map", action: "UIAction", label: "Favorite Location Saved") let textf = alertController.textFields![0] as UITextField if let mapView = self.embeddedMapViewController.view as? GMSMapView{ let favoriteLocation = FavoriteLocationItem() favoriteLocation.name = textf.text! favoriteLocation.latitude = mapView.camera.target.latitude favoriteLocation.longitude = mapView.camera.target.longitude favoriteLocation.zoom = mapView.camera.zoom FavoriteLocationStore.saveFavorite(favoriteLocation) } } alertController.addAction(okAction) present(alertController, animated: false, completion: nil) } func mapView(_ mapView: GMSMapView, didChange position: GMSCameraPosition) { drawAlerts() } // MARK: MapMarkerViewController protocol method func mapReady(){ self.activityIndicatorView.isHidden = false activityIndicatorView.startAnimating() let serviceGroup = DispatchGroup(); drawJBLM() fetchCameras(force: false, group: serviceGroup) fetchAlerts(force: false, group: serviceGroup) fetchRestAreas(group: serviceGroup) serviceGroup.notify(queue: DispatchQueue.main) { self.activityIndicatorView.stopAnimating() self.activityIndicatorView.isHidden = true } } // MARK: GMUClusterManagerDelegate // If a cluster has less then 11 cameras go to a list view will all cameras, otherwise zoom in. func clusterManager(_ clusterManager: GMUClusterManager, didTap cluster: GMUCluster) { if let mapView = embeddedMapViewController.view as? GMSMapView{ if mapView.camera.zoom > Utils.maxClusterOpenZoom { performSegue(withIdentifier: SegueCameraClusterViewController, sender: cluster) } else { let newCamera = GMSCameraPosition.camera(withTarget: cluster.position, zoom: mapView.camera.zoom + 1) mapView.animate(to: newCamera) } } } // MARK: GMSMapViewDelegate func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool { if (marker.userData as? CameraClusterItem) != nil { performSegue(withIdentifier: SegueCamerasViewController, sender: marker) } if marker.snippet == "alert" { // Check for overlapping markers. var markers = alertMarkers markers.remove(marker) if markers.contains(where: {($0.position.latitude == marker.position.latitude) && ($0.position.latitude == marker.position.latitude)}) { performSegue(withIdentifier: SegueAlertsInArea, sender: marker) } else { performSegue(withIdentifier: SegueHighwayAlertViewController, sender: marker) } } if marker.snippet == "restarea" { performSegue(withIdentifier: SegueRestAreaViewController, sender: marker) } if marker.snippet == "jblm" { performSegue(withIdentifier: SegueCalloutViewController, sender: marker) } return true } func mapView(_ mapView: GMSMapView, idleAt position: GMSCameraPosition) { if let mapView = embeddedMapViewController.view as? GMSMapView { UserDefaults.standard.set(mapView.camera.target.latitude, forKey: UserDefaultsKeys.mapLat) UserDefaults.standard.set(mapView.camera.target.longitude, forKey: UserDefaultsKeys.mapLon) UserDefaults.standard.set(mapView.camera.zoom, forKey: UserDefaultsKeys.mapZoom) } } func mapViewDidStartTileRendering(_ mapView: GMSMapView) { serviceGroup.enter() } func mapViewDidFinishTileRendering(_ mapView: GMSMapView) { serviceGroup.leave() } // MARK: Naviagtion // Get refrence to child VC override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let vc = segue.destination as? MapViewController, segue.identifier == "EmbedMapSegue" { vc.markerDelegate = self vc.mapDelegate = self self.embeddedMapViewController = vc } if segue.identifier == SegueGoToPopover { let destinationViewController = segue.destination as! TrafficMapGoToViewController destinationViewController.my_parent = self } if segue.identifier == SegueAlertsInArea { //Check sender - could be alertsInArea button or a marker with overlap. if let marker = sender as? GMSMarker { // Get the overlapping markers let alerts = convertAlertMarkersToHighwayAlertItems(markers: alertMarkers.filter({($0.position.latitude == marker.position.latitude) && ($0.position.latitude == marker.position.latitude)})) let destinationViewController = segue.destination as! AlertsInAreaViewController destinationViewController.alerts = alerts destinationViewController.title = "Alert" } else { let alerts = getAlertsOnScreen() let destinationViewController = segue.destination as! AlertsInAreaViewController destinationViewController.alerts = alerts destinationViewController.title = "Alerts In This Area" } } if segue.identifier == SegueSettingsPopover { let destinationViewController = segue.destination as! TrafficMapSettingsViewController destinationViewController.my_parent = self } if segue.identifier == SegueHighwayAlertViewController { let alertItem = ((sender as! GMSMarker).userData as! HighwayAlertItem) let destinationViewController = segue.destination as! HighwayAlertViewController destinationViewController.alertId = alertItem.alertId } if segue.identifier == SegueCamerasViewController { let poiItem = ((sender as! GMSMarker).userData as! CameraClusterItem) let cameraItem = poiItem.camera let destinationViewController = segue.destination as! CameraViewController destinationViewController.adTarget = "traffic" destinationViewController.cameraItem = cameraItem } if segue.identifier == SegueCameraClusterViewController { let cameraCluster = ((sender as! GMUCluster)).items var cameras = [CameraItem]() for clusterItem in cameraCluster { let camera = (clusterItem as! CameraClusterItem).camera cameras.append(camera) } let destinationViewController = segue.destination as! CameraClusterViewController destinationViewController.cameraItems = cameras } if segue.identifier == SegueRestAreaViewController { let restAreaItem = ((sender as! GMSMarker).userData as! RestAreaItem) let destinationViewController = segue.destination as! RestAreaViewController destinationViewController.restAreaItem = restAreaItem } if segue.identifier == SegueCalloutViewController { let calloutURL = ((sender as! GMSMarker).userData as! String) let destinationViewController = segue.destination as! CalloutViewController destinationViewController.calloutURL = calloutURL destinationViewController.title = "JBLM" } } } extension TrafficMapViewController: EasyTipViewDelegate { public func easyTipViewDidDismiss(_ tipView: EasyTipView) { UserDefaults.standard.set(true, forKey: UserDefaultsKeys.hasSeenTravelerInfoTipView) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) tipView.dismiss() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) MyAnalytics.screenView(screenName: "TrafficMap") if (!UserDefaults.standard.bool(forKey: UserDefaultsKeys.hasSeenTravelerInfoTipView) && !UIAccessibility.isVoiceOverRunning){ tipView = EasyTipView(text: "Tap here for live traffic updates, travel times and more.", delegate: self) tipView.show(forItem: self.travelInformationButton) } } }
gpl-3.0
658da72519eee8f230d6f2d11fbbadac
38.801205
205
0.612911
5.472769
false
false
false
false
sunshineclt/NKU-Helper
NKU Helper/设置/SettingTableViewController.swift
1
4507
// // SettingTableViewController.swift // NKU Helper // // Created by 陈乐天 on 15/3/1. // Copyright (c) 2015年 陈乐天. All rights reserved. // import UIKit class SettingTableViewController: UITableViewController { override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tableView.reloadData() } override func numberOfSections(in tableView: UITableView) -> Int { return 5 } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch (section) { case 0:return "账户信息" case 1:return "偏好设置" case 2:return "支持NKU Helper" case 3:return "关于NKU Helper\n" default:return "" } } override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { switch (section) { case 0:return "NKU Helper将会把您的密码存储在系统钥匙串中,请放心填写" case 2:return "NKU Helper本身是完全免费的,但开发和运营都需要投入。如果您觉得好用并想鼓励我们做得更好,不妨通过捐赠来支持我们的团队。无论多少,我们都非常感谢!" case 3:return "如果大家对NKU Helper的使用有吐槽,或是希望有什么功能,欢迎到“关于”页面中戳我的邮箱,我会尽快给大家回复!\nNKU Helper已经开源,详情请见关于页面,欢迎大家一起为NKU Helper贡献代码" case 4:return "NKU Helper目前已有其他平台版本,在Google Play,百度,91助手和豌豆荚中均可下载" default:return "" } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0,2,3: return 1 case 1: return 2 case 4: return 0 default: return 0 } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch indexPath.section { case 0: do { let user = try UserAgent.sharedInstance.getUserInfo() let cell = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.accountCell.identifier) as! AccountTableViewCell let timeEnteringSchool = (user.timeEnteringSchool as NSString).substring(with: NSMakeRange(2, 2)) cell.nameLabel.text = user.name cell.userIDLabel.text = user.userID cell.departmentLabel.text = user.departmentAdmitted + (timeEnteringSchool as String) + "级本科生" return cell } catch { let cell = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.addAccountCell.identifier)! cell.textLabel?.text = "请先登录!" cell.detailTextLabel?.text = "欢迎使用NKU Helper!" return cell } case 1: if indexPath.row == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.choosePreferredColorCell.identifier)! return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.chooseClassTimeTablePreferenceCell.identifier)! return cell } case 2: let cell = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.supportGroupCell.identifier)! cell.textLabel?.text = "请开发团队喝一杯咖啡" return cell case 3: let cell = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.aboutCell.identifier)! cell.textLabel?.text = "关于" return cell default: let cell = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.aboutCell.identifier)! return cell } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.section == 2 { let url = URL(string: "https://qr.alipay.com/ae5g3m2kfloxr5tte5")! UIApplication.shared.openURL(url) } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { segue.destination.hidesBottomBarWhenPushed = true } }
gpl-3.0
cc81f24dd2f07bdc5f57742450d3155f
37.103774
139
0.625402
4.233753
false
false
false
false
oneWarcraft/PictureBrowser-Swift
PictureBrowser/PictureBrowser/Classes/Home/HomeCollectionViewController.swift
1
4669
// // HomeCollectionViewController.swift // PictureBrowser // // Created by 王继伟 on 16/7/14. // Copyright © 2016年 WangJiwei. All rights reserved. // import UIKit import AFNetworking private let reuseIdentifier = "Cell" class HomeCollectionViewController: UICollectionViewController { lazy var shops : [Shop] = [Shop]() // var isPresented : Bool = false lazy var pictureBrowserAnimator : PictureBrowserAnimator = PictureBrowserAnimator() override func viewDidLoad() { super.viewDidLoad() loadData(0) } } extension HomeCollectionViewController { func loadData(offset: Int) { // 发送网络请求 NetworkTools.shareInstance.loadHomeData(offset) { (resultArray, error) in // 1. 错误校验 if error != nil { return } // 2. 取出可选类型中的数据 guard let resultArray = resultArray else { return } // 3. 遍历数组,将数据中的字典转换成模型对象 for dict in resultArray { let shop = Shop(dict: dict) self.shops.append(shop) } // 4. 刷新表格 self.collectionView?.reloadData() } } } /* //原则上不要在extension里override方法 extension NSMutableArray { public override func descriptionWithLocale(locale: AnyObject?) -> String { var str = "(\n" [self .enumerateObjectsUsingBlock({ str += "\t\($0.0), \n" })] str += ")" return str } } */ extension HomeCollectionViewController { override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.shops.count } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { // "HomeCell" cell ID let cell = collectionView .dequeueReusableCellWithReuseIdentifier("HomeCell", forIndexPath: indexPath) as! HomeViewCell // cell.backgroundColor = UIColor.redColor() cell.shop = shops[indexPath.row] if indexPath.row == shops.count - 1 { loadData(shops.count) } return cell } override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { // 1. 创建图片浏览器控制器 let pictureBrowser = PictureBrowserController() // 2. 设置控制器相关属性 pictureBrowser.indexPath = indexPath pictureBrowser.shops = shops pictureBrowserAnimator.indexPath = indexPath pictureBrowserAnimator.presentedDelegate = self pictureBrowserAnimator.dismissDelegate = pictureBrowser // 3 pictureBrowser.modalTransitionStyle = .PartialCurl pictureBrowser.modalPresentationStyle = .Custom pictureBrowser.transitioningDelegate = pictureBrowserAnimator // 4. 弹出控制器 presentViewController(pictureBrowser, animated: true, completion: nil) } } // MARK:- 实现presentedDelegate的代理方法 extension HomeCollectionViewController : PresentedProtocol { func getImageView(indexPath: NSIndexPath) -> UIImageView { // 1. 创建UIImageView对象 let imageView = UIImageView() // 2. 设置图片 let cell = collectionView?.cellForItemAtIndexPath(indexPath) as! HomeViewCell imageView.image = cell.imageView.image imageView.contentMode = .ScaleAspectFill imageView.clipsToBounds = true return imageView } func getStartRect(indexPath: NSIndexPath) -> CGRect { guard let cell = collectionView?.cellForItemAtIndexPath(indexPath) as? HomeViewCell else { return CGRectZero } // 将cell的frame转换成所有屏幕的frame let startRect = collectionView!.convertRect(cell.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!) return startRect } func getEndRect(indexPath: NSIndexPath) -> CGRect { //获取当前正在现实的cell let cell = collectionView?.cellForItemAtIndexPath(indexPath) as! HomeViewCell // 获取image对象 let image = cell.imageView.image return calculateImageViewFrame(image!) } }
apache-2.0
29d2d52bcb175dc40e652bf12f9fd0cc
24.929825
139
0.614569
5.447174
false
false
false
false