repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
wireapp/wire-ios-data-model
Source/Model/User/UserType+Materialize.swift
1
2931
// // Wire // Copyright (C) 2020 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation extension Sequence where Element: UserType { /// Materialize a sequence of UserType into concrete ZMUser instances. /// /// - parameter context: NSManagedObjectContext on which users should be created. /// /// - Returns: List of concrete users which could be materialized. public func materialize(in context: NSManagedObjectContext) -> [ZMUser] { precondition(context.zm_isUserInterfaceContext, "You can only materialize users on the UI context") let nonExistingUsers = self.compactMap({ $0 as? ZMSearchUser }).filter({ $0.user == nil }) nonExistingUsers.createLocalUsers(in: context.zm_sync) return self.compactMap({ $0.unbox(in: context) }) } } extension UserType { public func materialize(in context: NSManagedObjectContext) -> ZMUser? { return [self].materialize(in: context).first } fileprivate func unbox(in context: NSManagedObjectContext) -> ZMUser? { if let user = self as? ZMUser { return user } else if let searchUser = self as? ZMSearchUser { if let user = searchUser.user { return user } else if let remoteIdentifier = searchUser.remoteIdentifier { return ZMUser.fetch(with: remoteIdentifier, domain: searchUser.domain, in: context) } } return nil } } extension Sequence where Element: ZMSearchUser { fileprivate func createLocalUsers(in context: NSManagedObjectContext) { let nonExistingUsers = filter({ $0.user == nil }).map { (userID: $0.remoteIdentifier, teamID: $0.teamIdentifier, domain: $0.domain) } context.performGroupedBlockAndWait { nonExistingUsers.forEach { guard let remoteIdentifier = $0.userID else { return } let user = ZMUser.fetchOrCreate(with: remoteIdentifier, domain: $0.domain, in: context) user.teamIdentifier = $0.teamID user.createOrDeleteMembershipIfBelongingToTeam() } context.saveOrRollback() } } }
gpl-3.0
18da7a0008ed92d53a3c1a311ed95ce1
35.185185
107
0.639713
4.909548
false
false
false
false
openHPI/xikolo-ios
Common/Data/Model/EnrollmentCertificates.swift
1
1542
// // Created for xikolo-ios under GPL-3.0 license. // Copyright © HPI. All rights reserved. // import Foundation import Stockpile public final class EnrollmentCertificates: NSObject, NSSecureCoding, IncludedPullable { public static var supportsSecureCoding: Bool { return true } public var confirmationOfParticipation: URL? public var recordOfAchievement: URL? public var qualifiedCertificate: URL? public required init(object: ResourceData) throws { self.confirmationOfParticipation = try object.failsafeURL(for: "confirmation_of_participation") self.recordOfAchievement = try object.failsafeURL(for: "record_of_achievement") self.qualifiedCertificate = try object.failsafeURL(for: "qualified_certificate") } public required init(coder decoder: NSCoder) { self.confirmationOfParticipation = decoder.decodeObject(of: NSURL.self, forKey: "confirmation_of_participation")?.absoluteURL self.recordOfAchievement = decoder.decodeObject(of: NSURL.self, forKey: "record_of_achievement")?.absoluteURL self.qualifiedCertificate = decoder.decodeObject(of: NSURL.self, forKey: "qualified_certificate")?.absoluteURL } public func encode(with coder: NSCoder) { coder.encode(self.confirmationOfParticipation?.asNSURL(), forKey: "confirmation_of_participation") coder.encode(self.recordOfAchievement?.asNSURL(), forKey: "record_of_achievement") coder.encode(self.qualifiedCertificate?.asNSURL(), forKey: "qualified_certificate") } }
gpl-3.0
0564e5e96f55611d0f8f094b121f3a87
43.028571
133
0.744971
4.390313
false
false
false
false
davidholmesnyc/Caster-for-iOS-
HelloVideo-Swift/SearchView.swift
1
2678
// // ViewController.swift // InfiniteNestedData // // Created by Richard S on 23/03/2015. // Copyright (c) 2015 Richard S. All rights reserved. // import UIKit class SearchView: UIViewController, UITableViewDataSource, UITableViewDelegate { var faqData:Array<AnyObject>? @IBOutlet var tableView:UITableView! override func viewDidLoad() { super.viewDidLoad() if (self.faqData == nil) { self.fetchFAQ { (data) -> Void in self.faqData = data self.tableView.reloadData() } } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if (segue.identifier == "showNextPage") { let destVC:SearchView = segue.destinationViewController as! SearchView let selectedRow = self.tableView.indexPathForSelectedRow()!.row let content:Array<AnyObject> = self.faqData![selectedRow]["children"] as! Array<AnyObject> destVC.faqData = content } } func fetchFAQ(completion:(Array<AnyObject>?) -> Void) { let url = NSURL(string: "http://localhost/chromecast/data.json")! let dataTask = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data, response, error) -> Void in if let json:AnyObject = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: nil) { dispatch_async(dispatch_get_main_queue(), { () -> Void in completion(json as? Array<AnyObject>) }) } }) dataTask.resume() } // MARK: Tableview Delegate func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if (self.faqData != nil) { return count(self.faqData!) } return 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell:InfoTableViewCell = tableView.dequeueReusableCellWithIdentifier("infoCell") as! InfoTableViewCell if let infoDict:Dictionary<String, AnyObject> = self.faqData![indexPath.row] as? Dictionary<String, AnyObject> { cell.infoLabel.text = infoDict["title"] as? String cell.userInteractionEnabled = false if let children:Array<AnyObject> = infoDict["children"] as? Array<AnyObject> { if (count(children) > 0) { cell.userInteractionEnabled = true } } } return cell } }
apache-2.0
1c2a1c667e55d289837c022565d19ff8
33.779221
140
0.601942
5.091255
false
false
false
false
Urinx/SublimeCode
Sublime/Sublime/Utils/Plist.swift
1
1863
// // Plist.swift // Sublime // // Created by Eular on 3/31/16. // Copyright © 2016 Eular. All rights reserved. // import Foundation struct Plist { enum PlistError: ErrorType { case FileNotWritten case FileDoesNotExist } let name: String let path: String init(path: String) { self.path = path self.name = path.lastPathComponent if !NSFileManager.defaultManager().fileExistsAtPath(path) { let f = Folder(path: path.stringByDeletingLastPathComponent) f.newFile(name) } } func getDictInPlistFile() -> NSDictionary? { guard let dict = NSDictionary(contentsOfFile: path) else { return .None } return dict } func getMutableDictInPlistFile() -> NSMutableDictionary? { guard let dict = NSMutableDictionary(contentsOfFile: path) else { return .None } return dict } func getArrayInPlistFile() -> NSArray? { guard let arr = NSArray(contentsOfFile: path) else { return .None } return arr } func getMutableArrayInPlistFile() -> NSMutableArray? { guard let arr = NSMutableArray(contentsOfFile: path) else { return .None } return arr } func saveToPlistFile(any: AnyObject) throws { if !any.writeToFile(path, atomically: false) { throw PlistError.FileNotWritten } } func appendToPlistFile(any: AnyObject) throws { if let arr = getMutableArrayInPlistFile() { arr.addObject(any) if !arr.writeToFile(path, atomically: false) { throw PlistError.FileNotWritten } } else { if !NSArray(array: [any]).writeToFile(path, atomically: false) { throw PlistError.FileNotWritten } } } }
gpl-3.0
60cdb143a1d4847a102f951082c632fe
26.397059
88
0.594522
4.725888
false
false
false
false
superk589/CGSSGuide
DereGuide/Controller/BaseTableViewController.swift
2
698
// // BaseTableViewController.swift // DereGuide // // Created by zzk on 16/8/13. // Copyright © 2016 zzk. All rights reserved. // import UIKit class BaseTableViewController: UITableViewController { override var shouldAutorotate: Bool { return UIDevice.current.userInterfaceIdiom == .pad } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return UIDevice.current.userInterfaceIdiom == .pad ? .all : .portrait } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white clearsSelectionOnViewWillAppear = true tableView.keyboardDismissMode = .onDrag } }
mit
47ca87b3ec357dfa4fc636ff05cdd13c
23.892857
77
0.680057
5.361538
false
false
false
false
bluesky0109/Happiness
Happiness/HappinessViewController.swift
1
1471
// // HappinessViewController.swift // Happiness // // Created by sky on 15/4/12. // Copyright (c) 2015年 xkhouse. All rights reserved. // import UIKit class HappinessViewController: UIViewController,FaceViewDataSource { var happiness:Int = 10 { didSet { happiness = min(max(happiness, 0), 100) println("happiness = \(happiness)") updateUI() } } @IBOutlet weak var faceView: FaceView! { didSet { faceView.dataSource = self faceView.addGestureRecognizer(UIPinchGestureRecognizer(target: faceView, action: "scale:")) } } private struct Constants { static let HappinessGestureScale: CGFloat = 4 } @IBAction func changeHappiness(sender: UIPanGestureRecognizer) { switch sender.state { case .Ended: fallthrough case .Changed: let translation = sender.translationInView(faceView) let happinessChange = -Int(translation.y / Constants.HappinessGestureScale) if happinessChange != 0 { happiness += happinessChange sender.setTranslation(CGPointZero, inView: faceView) } default: break } } func updateUI() { faceView.setNeedsDisplay() } func smilinessForFaceView(sender: FaceView) -> Double? { return Double(happiness - 50)/50 } }
gpl-2.0
cfc7ce74680efdbeca0196b2a155b1cf
24.789474
103
0.586794
5.227758
false
false
false
false
eungkyu/JSONCodable
JSONCodable/JSONString.swift
1
2649
// // JSONString.swift // JSONCodable // // Created by Matthew Cheok on 17/7/15. // Copyright © 2015 matthewcheok. All rights reserved. // import Foundation public extension JSONEncodable { public func toJSONString() throws -> String { switch self { case let str as String: return escapeJSONString(str) case is Bool, is Int, is Float, is Double: return String(self) default: let json = try toJSON() let data = try NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions(rawValue: 0)) guard let string = NSString(data: data, encoding: NSUTF8StringEncoding) else { return "" } return string as String } } } private func escapeJSONString(str: String) -> String { var chars = String.CharacterView("\"") for c in str.characters { switch c { case "\\": chars.append("\\") chars.append("\\") case "\"": chars.append("\\") chars.append("\"") default: chars.append(c) } } chars.append("\"") return String(chars) } public extension Optional where Wrapped: JSONEncodable { public func toJSONString() throws -> String { switch self { case let .Some(jsonEncodable): return try jsonEncodable.toJSONString() case nil: return "null" } } } public extension JSONDecodable { init?(JSONString: String) { guard let data = JSONString.dataUsingEncoding(NSUTF8StringEncoding) else { return nil } let result: AnyObject do { result = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0)) } catch { return nil } guard let converted = result as? [String: AnyObject] else { return nil } self.init(JSONDictionary: converted) } } public extension Array where Element: JSONDecodable { init?(JSONString: String) { guard let data = JSONString.dataUsingEncoding(NSUTF8StringEncoding) else { return nil } let result: AnyObject do { result = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0)) } catch { return nil } guard let converted = result as? [AnyObject] else { return nil } self.init(JSONArray: converted) } }
mit
341b0b4e12deca8fabd9d2d016b8de74
25.48
115
0.561178
5.121857
false
false
false
false
larryhou/swift
TexasHoldem/TexasHoldem/HandV6Flush.swift
1
937
// // HandV6Flush.swift // TexasHoldem // // Created by larryhou on 6/3/2016. // Copyright © 2016 larryhou. All rights reserved. // import Foundation // 同花 class HandV6Flush: PatternEvaluator { static func getOccurrences() -> UInt { return combinate(13, select: 5) * 4 * combinate(52 - 5, select: 2) } static func evaluate(_ hand: PokerHand) { var cards = (hand.givenCards + hand.tableCards).sort() var flush: PokerColor! var dict: [PokerColor: [PokerCard]] = [:] for i in 0..<cards.count { let item = cards[i] if dict[item.color] == nil { dict[item.color] = [] } dict[item.color]?.append(item) if let count = dict[item.color]?.count where count >= 5 { flush = item.color } } hand.matches = Array(dict[flush]![0..<5]) } }
mit
929c0447c995d87a262b3708aec8981e
23.526316
69
0.526824
3.713147
false
false
false
false
iOS-Swift-Developers/Swift
实战项目一/JQLiveTV/Pods/Kingfisher/Sources/ImageView+Kingfisher.swift
54
13216
// // ImageView+Kingfisher.swift // Kingfisher // // Created by Wei Wang on 15/4/6. // // Copyright (c) 2016 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(macOS) import AppKit #else import UIKit #endif // MARK: - Extension methods. /** * Set image to use from web. */ extension Kingfisher where Base: ImageView { /** Set an image with a resource, a placeholder image, options, progress handler and completion handler. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter placeholder: A placeholder image when retrieving the image at URL. - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called when the image downloading progress gets updated. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread. The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method. */ @discardableResult public func setImage(with resource: Resource?, placeholder: Image? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: CompletionHandler? = nil) -> RetrieveImageTask { base.image = placeholder guard let resource = resource else { completionHandler?(nil, nil, .none, nil) return .empty } let maybeIndicator = indicator maybeIndicator?.startAnimatingView() setWebURL(resource.downloadURL) var options = options ?? KingfisherEmptyOptionsInfo if shouldPreloadAllGIF() { options.append(.preloadAllGIFData) } let task = KingfisherManager.shared.retrieveImage( with: resource, options: options, progressBlock: { receivedSize, totalSize in if let progressBlock = progressBlock { progressBlock(receivedSize, totalSize) } }, completionHandler: {[weak base] image, error, cacheType, imageURL in DispatchQueue.main.safeAsync { guard let strongBase = base, imageURL == self.webURL else { return } self.setImageTask(nil) guard let image = image else { maybeIndicator?.stopAnimatingView() completionHandler?(nil, error, cacheType, imageURL) return } guard let transitionItem = options.firstMatchIgnoringAssociatedValue(.transition(.none)), case .transition(let transition) = transitionItem, ( options.forceTransition || cacheType == .none) else { maybeIndicator?.stopAnimatingView() strongBase.image = image completionHandler?(image, error, cacheType, imageURL) return } #if !os(macOS) UIView.transition(with: strongBase, duration: 0.0, options: [], animations: { maybeIndicator?.stopAnimatingView() }, completion: { _ in UIView.transition(with: strongBase, duration: transition.duration, options: [transition.animationOptions, .allowUserInteraction], animations: { // Set image property in the animation. transition.animations?(strongBase, image) }, completion: { finished in transition.completion?(finished) completionHandler?(image, error, cacheType, imageURL) }) }) #endif } }) setImageTask(task) return task } /** Cancel the image download task bounded to the image view if it is running. Nothing will happen if the downloading has already finished. */ public func cancelDownloadTask() { imageTask?.downloadTask?.cancel() } func shouldPreloadAllGIF() -> Bool { return true } } // MARK: - Associated Object private var lastURLKey: Void? private var indicatorKey: Void? private var indicatorTypeKey: Void? private var imageTaskKey: Void? extension Kingfisher where Base: ImageView { /// Get the image URL binded to this image view. public var webURL: URL? { return objc_getAssociatedObject(base, &lastURLKey) as? URL } fileprivate func setWebURL(_ url: URL) { objc_setAssociatedObject(base, &lastURLKey, url, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } /// Holds which indicator type is going to be used. /// Default is .none, means no indicator will be shown. public var indicatorType: IndicatorType { get { let indicator = (objc_getAssociatedObject(base, &indicatorTypeKey) as? Box<IndicatorType?>)?.value return indicator ?? .none } set { switch newValue { case .none: indicator = nil case .activity: indicator = ActivityIndicator() case .image(let data): indicator = ImageIndicator(imageData: data) case .custom(let anIndicator): indicator = anIndicator } objc_setAssociatedObject(base, &indicatorTypeKey, Box(value: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /// Holds any type that conforms to the protocol `Indicator`. /// The protocol `Indicator` has a `view` property that will be shown when loading an image. /// It will be `nil` if `indicatorType` is `.none`. public fileprivate(set) var indicator: Indicator? { get { return (objc_getAssociatedObject(base, &indicatorKey) as? Box<Indicator?>)?.value } set { // Remove previous if let previousIndicator = indicator { previousIndicator.view.removeFromSuperview() } // Add new if var newIndicator = newValue { newIndicator.view.frame = base.frame newIndicator.viewCenter = CGPoint(x: base.bounds.midX, y: base.bounds.midY) newIndicator.view.isHidden = true base.addSubview(newIndicator.view) } // Save in associated object objc_setAssociatedObject(base, &indicatorKey, Box(value: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } fileprivate var imageTask: RetrieveImageTask? { return objc_getAssociatedObject(base, &imageTaskKey) as? RetrieveImageTask } fileprivate func setImageTask(_ task: RetrieveImageTask?) { objc_setAssociatedObject(base, &imageTaskKey, task, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } // MARK: - Deprecated. Only for back compatibility. /** * Set image to use from web. Deprecated. Use `kf` namespacing instead. */ extension ImageView { /** Set an image with a resource, a placeholder image, options, progress handler and completion handler. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter placeholder: A placeholder image when retrieving the image at URL. - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called when the image downloading progress gets updated. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread. The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method. */ @available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.setImage` instead.", renamed: "kf.setImage") @discardableResult public func kf_setImage(with resource: Resource?, placeholder: Image? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: CompletionHandler? = nil) -> RetrieveImageTask { return kf.setImage(with: resource, placeholder: placeholder, options: options, progressBlock: progressBlock, completionHandler: completionHandler) } /** Cancel the image download task bounded to the image view if it is running. Nothing will happen if the downloading has already finished. */ @available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.cancelDownloadTask` instead.", renamed: "kf.cancelDownloadTask") public func kf_cancelDownloadTask() { kf.cancelDownloadTask() } /// Get the image URL binded to this image view. @available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.webURL` instead.", renamed: "kf.webURL") public var kf_webURL: URL? { return kf.webURL } /// Holds which indicator type is going to be used. /// Default is .none, means no indicator will be shown. @available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.indicatorType` instead.", renamed: "kf.indicatorType") public var kf_indicatorType: IndicatorType { get { return kf.indicatorType } set { kf.indicatorType = newValue } } @available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.indicator` instead.", renamed: "kf.indicator") /// Holds any type that conforms to the protocol `Indicator`. /// The protocol `Indicator` has a `view` property that will be shown when loading an image. /// It will be `nil` if `kf_indicatorType` is `.none`. public private(set) var kf_indicator: Indicator? { get { return kf.indicator } set { kf.indicator = newValue } } @available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "kf.imageTask") fileprivate var kf_imageTask: RetrieveImageTask? { return kf.imageTask } @available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "kf.setImageTask") fileprivate func kf_setImageTask(_ task: RetrieveImageTask?) { kf.setImageTask(task) } @available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "kf.setWebURL") fileprivate func kf_setWebURL(_ url: URL) { kf.setWebURL(url) } @available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "kf.shouldPreloadAllGIF") func shouldPreloadAllGIF() -> Bool { return kf.shouldPreloadAllGIF() } }
mit
91775763a4c722db5808d7958157c30b
45.20979
173
0.604722
5.585799
false
false
false
false
yeziahehe/Gank
Pods/LeanCloud/Sources/Storage/DataType/Installation.swift
1
5226
// // Installation.swift // LeanCloud // // Created by Tianyong Tang on 2018/10/12. // Copyright © 2018 LeanCloud. All rights reserved. // import Foundation /** LeanCloud installation type. */ public final class LCInstallation: LCObject { /// The badge of installation. @objc public dynamic var badge: LCNumber? /// The time zone of installtion. @objc public dynamic var timeZone: LCString? /// The channels of installation, which contains client ID of IM. @objc public dynamic var channels: LCArray? /// The type of device. @objc public dynamic var deviceType: LCString? /// The device token used to push notification. @objc public private(set) dynamic var deviceToken: LCString? /// The device profile. You can use this property to select one from mutiple push certificates or configurations. @objc public private(set) dynamic var deviceProfile: LCString? /// The installation ID of device, it's mainly for Android device. @objc public dynamic var installationId: LCString? /// The APNs topic of installation. @objc public dynamic var apnsTopic: LCString? /// The APNs Team ID of installation. @objc public private(set) dynamic var apnsTeamId: LCString? public override class func objectClassName() -> String { return "_Installation" } public required init() { super.init() initialize() } func initialize() { timeZone = NSTimeZone.system.identifier.lcString if let bundleIdentifier = Bundle.main.bundleIdentifier { apnsTopic = bundleIdentifier.lcString } #if os(iOS) deviceType = "ios" #elseif os(macOS) deviceType = "macos" #elseif os(watchOS) deviceType = "watchos" #elseif os(tvOS) deviceType = "tvos" #elseif os(Linux) deviceType = "linux" #elseif os(FreeBSD) deviceType = "freebsd" #elseif os(Android) deviceType = "android" #elseif os(PS4) deviceType = "ps4" #elseif os(Windows) deviceType = "windows" #elseif os(Cygwin) deviceType = "cygwin" #elseif os(Haiku) deviceType = "haiku" #endif } /** Set required properties for installation. - parameter deviceToken: The device token. - parameter deviceProfile: The device profile. - parameter apnsTeamId: The Team ID of your Apple Developer Account. */ public func set( deviceToken: LCDeviceTokenConvertible, deviceProfile: LCStringConvertible? = nil, apnsTeamId: LCStringConvertible) { self.deviceToken = deviceToken.lcDeviceToken if let deviceProfile = deviceProfile { self.deviceProfile = deviceProfile.lcString } self.apnsTeamId = apnsTeamId.lcString } override func preferredBatchRequest(method: HTTPClient.Method, path: String, internalId: String) throws -> [String : Any]? { switch method { case .post, .put: var request: [String: Any] = [:] request["method"] = HTTPClient.Method.post.rawValue request["path"] = try HTTPClient.default.getBatchRequestPath(object: self, method: .post) if var body = dictionary.lconValue as? [String: Any] { body["__internalId"] = internalId body.removeValue(forKey: "createdAt") body.removeValue(forKey: "updatedAt") request["body"] = body } return request default: return nil } } override func validateBeforeSaving() throws { try super.validateBeforeSaving() guard let _ = deviceToken else { throw LCError(code: .inconsistency, reason: "Installation device token not found.") } guard let _ = apnsTeamId else { throw LCError(code: .inconsistency, reason: "Installation APNs team ID not found.") } } override func objectDidSave() { super.objectDidSave() let application = LCApplication.default if application.currentInstallation == self { application.storageContextCache.installation = self } } } extension LCApplication { public var currentInstallation: LCInstallation { return lc_lazyload("currentInstallation", .OBJC_ASSOCIATION_RETAIN) { storageContextCache.installation ?? LCInstallation() } } } public protocol LCDeviceTokenConvertible { var lcDeviceToken: LCString { get } } extension String: LCDeviceTokenConvertible { public var lcDeviceToken: LCString { return lcString } } extension NSString: LCDeviceTokenConvertible { public var lcDeviceToken: LCString { return (self as String).lcDeviceToken } } extension Data: LCDeviceTokenConvertible { public var lcDeviceToken: LCString { let string = map { String(format: "%02.2hhx", $0) }.joined() return LCString(string) } } extension NSData: LCDeviceTokenConvertible { public var lcDeviceToken: LCString { return (self as Data).lcDeviceToken } }
gpl-3.0
d2573a46317993c7c0fa8ac2b836795e
24.995025
128
0.632727
4.737081
false
false
false
false
atomkirk/TouchForms
Example/Example/SignUpForm.swift
1
3209
// // SignUpForm.swift // Example // // Created by Adam Kirk on 8/25/15. // Copyright (c) 2015 Adam Kirk. All rights reserved. // import UIKit import TouchForms class SignUpForm: FormController { override func viewDidLoad() { super.viewDidLoad() model = ExampleUser() } override func configureForm() { // HEADER let labelElement = LabelFormElement(text: "Sign Up") addFormElement(labelElement) // FOOTNOTE let footnoteElement = LabelFormElement(text: "Example of a subclassed form view controller where a blank model is created in its viewDidLoad.") footnoteElement.configureCellBlock { (cell) -> Void in if let cell = cell as? LabelFormCell { cell.formLabel?.font = UIFont.preferredFontForTextStyle(UIFontTextStyleFootnote) } } addFormElement(footnoteElement) // FIRST NAME let firstNameElement = TextFieldFormElement(label: "First Name") firstNameElement.modelKeyPath = "firstName" addFormElement(firstNameElement) // LAST NAME let lastNameElement = TextFieldFormElement(label: "Last Name") lastNameElement.modelKeyPath = "lastName" addFormElement(lastNameElement) // EMAIL let emailElement = TextFieldFormElement(label: "Email") emailElement.modelKeyPath = "email" emailElement.configureCellBlock { cell in if let cell = cell as? TextFieldFormCell { cell.formTextField?.keyboardType = .EmailAddress } } addFormElement(emailElement) // PASSWoRD let passwordElement = TextFieldFormElement(label: "Password") passwordElement.modelKeyPath = "password" passwordElement.configureCellBlock { cell in if let cell = cell as? TextFieldFormCell { cell.formTextField?.secureTextEntry = true } } addFormElement(passwordElement) // PRINT MODEL let printButtonElement = ButtonFormElement(label: "Log Current Model") { print("\(self.model)") } addFormElement(printButtonElement) // SET RANDOM VAlUES let setValuesButtonElement = ButtonFormElement(label: "Set Random Data on Model") { if let user = self.model as? ExampleUser { user.firstName = randomStringWithLength(10) user.lastName = randomStringWithLength(10) user.email = randomStringWithLength(10) user.password = randomStringWithLength(10) } } addFormElement(setValuesButtonElement) } } private let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" as NSString private func randomStringWithLength(length: Int) -> String { var randomString = "" for _ in 0..<length { let range = NSMakeRange(Int(arc4random()) % letters.length, 1) let character = letters.substringWithRange(range) randomString.append(Character(character)) } return randomString }
mit
5feca422d3f4ed2e8f84d57fb820dd9b
32.427083
151
0.622312
5.167472
false
false
false
false
february29/Learning
swift/ReactiveCocoaDemo/Pods/RxSwift/RxSwift/Observables/Skip.swift
94
4885
// // Skip.swift // RxSwift // // Created by Krunoslav Zaher on 6/25/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // extension ObservableType { /** Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. - seealso: [skip operator on reactivex.io](http://reactivex.io/documentation/operators/skip.html) - parameter count: The number of elements to skip before returning the remaining elements. - returns: An observable sequence that contains the elements that occur after the specified index in the input sequence. */ public func skip(_ count: Int) -> Observable<E> { return SkipCount(source: asObservable(), count: count) } } extension ObservableType { /** Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. - seealso: [skip operator on reactivex.io](http://reactivex.io/documentation/operators/skip.html) - parameter duration: Duration for skipping elements from the start of the sequence. - parameter scheduler: Scheduler to run the timer on. - returns: An observable sequence with the elements skipped during the specified duration from the start of the source sequence. */ public func skip(_ duration: RxTimeInterval, scheduler: SchedulerType) -> Observable<E> { return SkipTime(source: self.asObservable(), duration: duration, scheduler: scheduler) } } // count version final fileprivate class SkipCountSink<O: ObserverType> : Sink<O>, ObserverType { typealias Element = O.E typealias Parent = SkipCount<Element> let parent: Parent var remaining: Int init(parent: Parent, observer: O, cancel: Cancelable) { self.parent = parent self.remaining = parent.count super.init(observer: observer, cancel: cancel) } func on(_ event: Event<Element>) { switch event { case .next(let value): if remaining <= 0 { forwardOn(.next(value)) } else { remaining -= 1 } case .error: forwardOn(event) self.dispose() case .completed: forwardOn(event) self.dispose() } } } final fileprivate class SkipCount<Element>: Producer<Element> { let source: Observable<Element> let count: Int init(source: Observable<Element>, count: Int) { self.source = source self.count = count } override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { let sink = SkipCountSink(parent: self, observer: observer, cancel: cancel) let subscription = source.subscribe(sink) return (sink: sink, subscription: subscription) } } // time version final fileprivate class SkipTimeSink<ElementType, O: ObserverType> : Sink<O>, ObserverType where O.E == ElementType { typealias Parent = SkipTime<ElementType> typealias Element = ElementType let parent: Parent // state var open = false init(parent: Parent, observer: O, cancel: Cancelable) { self.parent = parent super.init(observer: observer, cancel: cancel) } func on(_ event: Event<Element>) { switch event { case .next(let value): if open { forwardOn(.next(value)) } case .error: forwardOn(event) self.dispose() case .completed: forwardOn(event) self.dispose() } } func tick() { open = true } func run() -> Disposable { let disposeTimer = parent.scheduler.scheduleRelative((), dueTime: self.parent.duration) { self.tick() return Disposables.create() } let disposeSubscription = parent.source.subscribe(self) return Disposables.create(disposeTimer, disposeSubscription) } } final fileprivate class SkipTime<Element>: Producer<Element> { let source: Observable<Element> let duration: RxTimeInterval let scheduler: SchedulerType init(source: Observable<Element>, duration: RxTimeInterval, scheduler: SchedulerType) { self.source = source self.scheduler = scheduler self.duration = duration } override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { let sink = SkipTimeSink(parent: self, observer: observer, cancel: cancel) let subscription = sink.run() return (sink: sink, subscription: subscription) } }
mit
4dae2d75383954ace186956fd8f55800
29.716981
145
0.629197
4.788235
false
false
false
false
groue/GRDB.swift
Tests/GRDBTests/AssociationHasOneThroughSQLTests.swift
1
74531
import XCTest import GRDB /// Test SQL generation class AssociationHasOneThroughSQLTests: GRDBTestCase { // MARK: - Two Steps func testBelongsToBelongsTo() throws { struct A: TableRecord, EncodableRecord { static let b = belongsTo(B.self) static let c = hasOne(C.self, through: b, using: B.c) func encode(to container: inout PersistenceContainer) { container["bId"] = 1 } } struct B: TableRecord { static let c = belongsTo(C.self) } struct C: TableRecord { } let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.create(table: "c") { t in t.autoIncrementedPrimaryKey("id") } try db.create(table: "b") { t in t.autoIncrementedPrimaryKey("id") t.column("cId").references("c") } try db.create(table: "a") { t in t.autoIncrementedPrimaryKey("id") t.column("bId").references("b") } try testHasOneWithTwoSteps( db, ab: A.b, ac: A.c, bCondition: "\"b\".\"id\" = \"a\".\"bId\"", cCondition: "\"c\".\"id\" = \"b\".\"cId\"") try assertEqualSQL(db, A().request(for: A.c), """ SELECT "c".* FROM "c" \ JOIN "b" ON ("b"."cId" = "c"."id") AND ("b"."id" = 1) """) } } func testBelongsToHasOne() throws { struct A: TableRecord, EncodableRecord { static let b = belongsTo(B.self) static let c = hasOne(C.self, through: b, using: B.c) func encode(to container: inout PersistenceContainer) { container["bId"] = 1 } } struct B: TableRecord { static let c = hasOne(C.self) } struct C: TableRecord { } let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.create(table: "b") { t in t.autoIncrementedPrimaryKey("id") } try db.create(table: "a") { t in t.autoIncrementedPrimaryKey("id") t.column("bId").references("b") } try db.create(table: "c") { t in t.autoIncrementedPrimaryKey("id") t.column("bId").references("b") } try testHasOneWithTwoSteps( db, ab: A.b, ac: A.c, bCondition: "\"b\".\"id\" = \"a\".\"bId\"", cCondition: "\"c\".\"bId\" = \"b\".\"id\"") try assertEqualSQL(db, A().request(for: A.c), """ SELECT "c".* FROM "c" \ JOIN "b" ON ("b"."id" = "c"."bId") AND ("b"."id" = 1) """) } } func testHasOneBelongsTo() throws { struct A: TableRecord, EncodableRecord { static let b = hasOne(B.self) static let c = hasOne(C.self, through: b, using: B.c) func encode(to container: inout PersistenceContainer) { container["id"] = 1 } } struct B: TableRecord { static let c = belongsTo(C.self) } struct C: TableRecord { } let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.create(table: "a") { t in t.autoIncrementedPrimaryKey("id") } try db.create(table: "c") { t in t.autoIncrementedPrimaryKey("id") } try db.create(table: "b") { t in t.autoIncrementedPrimaryKey("id") t.column("cId").references("c") t.column("aId").references("a") } try testHasOneWithTwoSteps( db, ab: A.b, ac: A.c, bCondition: "\"b\".\"aId\" = \"a\".\"id\"", cCondition: "\"c\".\"id\" = \"b\".\"cId\"") try assertEqualSQL(db, A().request(for: A.c), """ SELECT "c".* FROM "c" \ JOIN "b" ON ("b"."cId" = "c"."id") AND ("b"."aId" = 1) """) } } func testHasOneHasOne() throws { struct A: TableRecord, EncodableRecord { static let b = hasOne(B.self) static let c = hasOne(C.self, through: b, using: B.c) func encode(to container: inout PersistenceContainer) { container["id"] = 1 } } struct B: TableRecord { static let c = hasOne(C.self) } struct C: TableRecord { } let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.create(table: "a") { t in t.autoIncrementedPrimaryKey("id") } try db.create(table: "b") { t in t.autoIncrementedPrimaryKey("id") t.column("aId").references("a") } try db.create(table: "c") { t in t.autoIncrementedPrimaryKey("id") t.column("bId").references("b") } try testHasOneWithTwoSteps( db, ab: A.b, ac: A.c, bCondition: "\"b\".\"aId\" = \"a\".\"id\"", cCondition: "\"c\".\"bId\" = \"b\".\"id\"") try assertEqualSQL(db, A().request(for: A.c), """ SELECT "c".* FROM "c" \ JOIN "b" ON ("b"."id" = "c"."bId") AND ("b"."aId" = 1) """) } } private func testHasOneWithTwoSteps<BAssociation, CAssociation>( _ db: Database, ab: BAssociation, ac: CAssociation, bCondition: String, cCondition: String) throws where BAssociation: AssociationToOne, CAssociation: AssociationToOne, BAssociation.OriginRowDecoder: TableRecord, BAssociation.OriginRowDecoder == CAssociation.OriginRowDecoder { let A = BAssociation.OriginRowDecoder.self do { try assertEqualSQL(db, A.including(optional: ac), """ SELECT "a".*, "c".* \ FROM "a" \ LEFT JOIN "b" ON \(bCondition) \ LEFT JOIN "c" ON \(cCondition) """) try assertEqualSQL(db, A.including(required: ac), """ SELECT "a".*, "c".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) """) try assertEqualSQL(db, A.joining(optional: ac), """ SELECT "a".* \ FROM "a" \ LEFT JOIN "b" ON \(bCondition) \ LEFT JOIN "c" ON \(cCondition) """) try assertEqualSQL(db, A.joining(required: ac), """ SELECT "a".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) """) try assertEqualSQL(db, A.annotated(withOptional: ac), """ SELECT "a".*, "c".* \ FROM "a" \ LEFT JOIN "b" ON \(bCondition) \ LEFT JOIN "c" ON \(cCondition) """) try assertEqualSQL(db, A.annotated(withRequired: ac), """ SELECT "a".*, "c".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) """) try assertEqualSQL(db, A.annotated(withRequired: ac.select(Column.rowID)), """ SELECT "a".*, "c"."rowid" \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) """) } do { try assertEqualSQL(db, A.including(optional: ac).including(optional: ab), """ SELECT "a".*, "b".*, "c".* \ FROM "a" \ LEFT JOIN "b" ON \(bCondition) \ LEFT JOIN "c" ON \(cCondition) """) try assertEqualSQL(db, A.including(optional: ac).including(required: ab), """ SELECT "a".*, "b".*, "c".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ LEFT JOIN "c" ON \(cCondition) """) try assertEqualSQL(db, A.including(optional: ac).joining(optional: ab), """ SELECT "a".*, "c".* \ FROM "a" \ LEFT JOIN "b" ON \(bCondition) \ LEFT JOIN "c" ON \(cCondition) """) try assertEqualSQL(db, A.including(optional: ac).joining(required: ab), """ SELECT "a".*, "c".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ LEFT JOIN "c" ON \(cCondition) """) try assertEqualSQL(db, A.annotated(withOptional: ab).including(optional: ac), """ SELECT "a".*, "b".*, "c".* \ FROM "a" \ LEFT JOIN "b" ON \(bCondition) \ LEFT JOIN "c" ON \(cCondition) """) try assertEqualSQL(db, A.including(optional: ac).annotated(withRequired: ab), """ SELECT "a".*, "b".*, "c".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ LEFT JOIN "c" ON \(cCondition) """) try assertEqualSQL(db, A.including(optional: ac).annotated(withRequired: ab.select(Column.rowID)), """ SELECT "a".*, "b"."rowid", "c".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ LEFT JOIN "c" ON \(cCondition) """) } do { try assertEqualSQL(db, A.including(required: ac).including(optional: ab), """ SELECT "a".*, "b".*, "c".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) """) try assertEqualSQL(db, A.including(required: ac).including(required: ab), """ SELECT "a".*, "b".*, "c".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) """) try assertEqualSQL(db, A.including(required: ac).joining(optional: ab), """ SELECT "a".*, "c".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) """) try assertEqualSQL(db, A.including(required: ac).joining(required: ab), """ SELECT "a".*, "c".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) """) try assertEqualSQL(db, A.annotated(withOptional: ab).including(required: ac), """ SELECT "a".*, "b".*, "c".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) """) try assertEqualSQL(db, A.including(required: ac).annotated(withRequired: ab), """ SELECT "a".*, "b".*, "c".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) """) try assertEqualSQL(db, A.including(required: ac).annotated(withRequired: ab.select(Column.rowID)), """ SELECT "a".*, "b"."rowid", "c".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) """) } do { try assertEqualSQL(db, A.joining(optional: ac).including(optional: ab), """ SELECT "a".*, "b".* \ FROM "a" \ LEFT JOIN "b" ON \(bCondition) \ LEFT JOIN "c" ON \(cCondition) """) try assertEqualSQL(db, A.joining(optional: ac).including(required: ab), """ SELECT "a".*, "b".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ LEFT JOIN "c" ON \(cCondition) """) try assertEqualSQL(db, A.joining(optional: ac).joining(optional: ab), """ SELECT "a".* \ FROM "a" \ LEFT JOIN "b" ON \(bCondition) \ LEFT JOIN "c" ON \(cCondition) """) try assertEqualSQL(db, A.joining(optional: ac).joining(required: ab), """ SELECT "a".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ LEFT JOIN "c" ON \(cCondition) """) try assertEqualSQL(db, A.annotated(withOptional: ab).joining(optional: ac), """ SELECT "a".*, "b".* \ FROM "a" \ LEFT JOIN "b" ON \(bCondition) \ LEFT JOIN "c" ON \(cCondition) """) try assertEqualSQL(db, A.joining(optional: ac).annotated(withRequired: ab), """ SELECT "a".*, "b".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ LEFT JOIN "c" ON \(cCondition) """) try assertEqualSQL(db, A.joining(optional: ac).annotated(withRequired: ab.select(Column.rowID)), """ SELECT "a".*, "b"."rowid" \ FROM "a" \ JOIN "b" ON \(bCondition) \ LEFT JOIN "c" ON \(cCondition) """) } do { try assertEqualSQL(db, A.joining(required: ac).including(optional: ab), """ SELECT "a".*, "b".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) """) try assertEqualSQL(db, A.joining(required: ac).including(required: ab), """ SELECT "a".*, "b".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) """) try assertEqualSQL(db, A.joining(required: ac).joining(optional: ab), """ SELECT "a".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) """) try assertEqualSQL(db, A.joining(required: ac).joining(required: ab), """ SELECT "a".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) """) try assertEqualSQL(db, A.annotated(withOptional: ab).joining(required: ac), """ SELECT "a".*, "b".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) """) try assertEqualSQL(db, A.joining(required: ac).annotated(withRequired: ab), """ SELECT "a".*, "b".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) """) try assertEqualSQL(db, A.joining(required: ac).annotated(withRequired: ab.select(Column.rowID)), """ SELECT "a".*, "b"."rowid" \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) """) } } // MARK: - Three Steps func testBelongsToBelongsToBelongsTo() throws { struct A: TableRecord, EncodableRecord { static let b = belongsTo(B.self) static let c = hasOne(C.self, through: b, using: B.c) static let dThroughC = hasOne(D.self, through: c, using: C.d) static let dThroughB = hasOne(D.self, through: b, using: B.d) func encode(to container: inout PersistenceContainer) { container["bId"] = 1 } } struct B: TableRecord { static let c = belongsTo(C.self) static let d = hasOne(D.self, through: c, using: C.d) } struct C: TableRecord { static let d = belongsTo(D.self) } struct D: TableRecord { } let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.create(table: "d") { t in t.autoIncrementedPrimaryKey("id") } try db.create(table: "c") { t in t.autoIncrementedPrimaryKey("id") t.column("dId").references("d") } try db.create(table: "b") { t in t.autoIncrementedPrimaryKey("id") t.column("cId").references("c") } try db.create(table: "a") { t in t.autoIncrementedPrimaryKey("id") t.column("bId").references("b") } try testHasOneWithThreeSteps( db, b: A.b, c: A.c, dThroughC: A.dThroughC, dThroughB: A.dThroughB, bCondition: "\"b\".\"id\" = \"a\".\"bId\"", cCondition: "\"c\".\"id\" = \"b\".\"cId\"", dCondition: "\"d\".\"id\" = \"c\".\"dId\"") try assertEqualSQL(db, A().request(for: A.dThroughC), """ SELECT "d".* FROM "d" \ JOIN "c" ON "c"."dId" = "d"."id" \ JOIN "b" ON ("b"."cId" = "c"."id") AND ("b"."id" = 1) """) try assertEqualSQL(db, A().request(for: A.dThroughB), """ SELECT "d".* FROM "d" \ JOIN "c" ON "c"."dId" = "d"."id" \ JOIN "b" ON ("b"."cId" = "c"."id") AND ("b"."id" = 1) """) } } func testBelongsToBelongsToHasOne() throws { struct A: TableRecord, EncodableRecord { static let b = belongsTo(B.self) static let c = hasOne(C.self, through: b, using: B.c) static let dThroughC = hasOne(D.self, through: c, using: C.d) static let dThroughB = hasOne(D.self, through: b, using: B.d) func encode(to container: inout PersistenceContainer) { container["bId"] = 1 } } struct B: TableRecord { static let c = belongsTo(C.self) static let d = hasOne(D.self, through: c, using: C.d) } struct C: TableRecord { static let d = hasOne(D.self) } struct D: TableRecord { } let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.create(table: "c") { t in t.autoIncrementedPrimaryKey("id") } try db.create(table: "d") { t in t.autoIncrementedPrimaryKey("id") t.column("cId").references("c") } try db.create(table: "b") { t in t.autoIncrementedPrimaryKey("id") t.column("cId").references("c") } try db.create(table: "a") { t in t.autoIncrementedPrimaryKey("id") t.column("bId").references("b") } try testHasOneWithThreeSteps( db, b: A.b, c: A.c, dThroughC: A.dThroughC, dThroughB: A.dThroughB, bCondition: "\"b\".\"id\" = \"a\".\"bId\"", cCondition: "\"c\".\"id\" = \"b\".\"cId\"", dCondition: "\"d\".\"cId\" = \"c\".\"id\"") try assertEqualSQL(db, A().request(for: A.dThroughC), """ SELECT "d".* FROM "d" \ JOIN "c" ON "c"."id" = "d"."cId" \ JOIN "b" ON ("b"."cId" = "c"."id") AND ("b"."id" = 1) """) try assertEqualSQL(db, A().request(for: A.dThroughB), """ SELECT "d".* FROM "d" \ JOIN "c" ON "c"."id" = "d"."cId" \ JOIN "b" ON ("b"."cId" = "c"."id") AND ("b"."id" = 1) """) } } func testBelongsToHasOneBelongsTo() throws { struct A: TableRecord, EncodableRecord { static let b = belongsTo(B.self) static let c = hasOne(C.self, through: b, using: B.c) static let dThroughC = hasOne(D.self, through: c, using: C.d) static let dThroughB = hasOne(D.self, through: b, using: B.d) func encode(to container: inout PersistenceContainer) { container["bId"] = 1 } } struct B: TableRecord { static let c = hasOne(C.self) static let d = hasOne(D.self, through: c, using: C.d) } struct C: TableRecord { static let d = belongsTo(D.self) } struct D: TableRecord { } let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.create(table: "d") { t in t.autoIncrementedPrimaryKey("id") } try db.create(table: "b") { t in t.autoIncrementedPrimaryKey("id") } try db.create(table: "c") { t in t.autoIncrementedPrimaryKey("id") t.column("bId").references("b") t.column("dId").references("d") } try db.create(table: "a") { t in t.autoIncrementedPrimaryKey("id") t.column("bId").references("b") } try testHasOneWithThreeSteps( db, b: A.b, c: A.c, dThroughC: A.dThroughC, dThroughB: A.dThroughB, bCondition: "\"b\".\"id\" = \"a\".\"bId\"", cCondition: "\"c\".\"bId\" = \"b\".\"id\"", dCondition: "\"d\".\"id\" = \"c\".\"dId\"") try assertEqualSQL(db, A().request(for: A.dThroughC), """ SELECT "d".* FROM "d" \ JOIN "c" ON "c"."dId" = "d"."id" \ JOIN "b" ON ("b"."id" = "c"."bId") AND ("b"."id" = 1) """) try assertEqualSQL(db, A().request(for: A.dThroughB), """ SELECT "d".* FROM "d" \ JOIN "c" ON "c"."dId" = "d"."id" \ JOIN "b" ON ("b"."id" = "c"."bId") AND ("b"."id" = 1) """) } } func testBelongsToHasOneHasOne() throws { struct A: TableRecord, EncodableRecord { static let b = belongsTo(B.self) static let c = hasOne(C.self, through: b, using: B.c) static let dThroughC = hasOne(D.self, through: c, using: C.d) static let dThroughB = hasOne(D.self, through: b, using: B.d) func encode(to container: inout PersistenceContainer) { container["bId"] = 1 } } struct B: TableRecord { static let c = hasOne(C.self) static let d = hasOne(D.self, through: c, using: C.d) } struct C: TableRecord { static let d = hasOne(D.self) } struct D: TableRecord { } let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.create(table: "b") { t in t.autoIncrementedPrimaryKey("id") } try db.create(table: "c") { t in t.autoIncrementedPrimaryKey("id") t.column("bId").references("b") } try db.create(table: "d") { t in t.autoIncrementedPrimaryKey("id") t.column("cId").references("c") } try db.create(table: "a") { t in t.autoIncrementedPrimaryKey("id") t.column("bId").references("b") } try testHasOneWithThreeSteps( db, b: A.b, c: A.c, dThroughC: A.dThroughC, dThroughB: A.dThroughB, bCondition: "\"b\".\"id\" = \"a\".\"bId\"", cCondition: "\"c\".\"bId\" = \"b\".\"id\"", dCondition: "\"d\".\"cId\" = \"c\".\"id\"") try assertEqualSQL(db, A().request(for: A.dThroughC), """ SELECT "d".* FROM "d" \ JOIN "c" ON "c"."id" = "d"."cId" \ JOIN "b" ON ("b"."id" = "c"."bId") AND ("b"."id" = 1) """) try assertEqualSQL(db, A().request(for: A.dThroughB), """ SELECT "d".* FROM "d" \ JOIN "c" ON "c"."id" = "d"."cId" \ JOIN "b" ON ("b"."id" = "c"."bId") AND ("b"."id" = 1) """) } } func testHasOneBelongsToBelongsTo() throws { struct A: TableRecord, EncodableRecord { static let b = hasOne(B.self) static let c = hasOne(C.self, through: b, using: B.c) static let dThroughC = hasOne(D.self, through: c, using: C.d) static let dThroughB = hasOne(D.self, through: b, using: B.d) func encode(to container: inout PersistenceContainer) { container["id"] = 1 } } struct B: TableRecord { static let c = belongsTo(C.self) static let d = hasOne(D.self, through: c, using: C.d) } struct C: TableRecord { static let d = belongsTo(D.self) } struct D: TableRecord { } let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.create(table: "a") { t in t.autoIncrementedPrimaryKey("id") } try db.create(table: "d") { t in t.autoIncrementedPrimaryKey("id") } try db.create(table: "c") { t in t.autoIncrementedPrimaryKey("id") t.column("dId").references("d") } try db.create(table: "b") { t in t.autoIncrementedPrimaryKey("id") t.column("aId").references("a") t.column("cId").references("c") } try testHasOneWithThreeSteps( db, b: A.b, c: A.c, dThroughC: A.dThroughC, dThroughB: A.dThroughB, bCondition: "\"b\".\"aId\" = \"a\".\"id\"", cCondition: "\"c\".\"id\" = \"b\".\"cId\"", dCondition: "\"d\".\"id\" = \"c\".\"dId\"") try assertEqualSQL(db, A().request(for: A.dThroughC), """ SELECT "d".* FROM "d" \ JOIN "c" ON "c"."dId" = "d"."id" \ JOIN "b" ON ("b"."cId" = "c"."id") AND ("b"."aId" = 1) """) try assertEqualSQL(db, A().request(for: A.dThroughB), """ SELECT "d".* FROM "d" \ JOIN "c" ON "c"."dId" = "d"."id" \ JOIN "b" ON ("b"."cId" = "c"."id") AND ("b"."aId" = 1) """) } } func testHasOneBelongsToHasOne() throws { struct A: TableRecord, EncodableRecord { static let b = hasOne(B.self) static let c = hasOne(C.self, through: b, using: B.c) static let dThroughC = hasOne(D.self, through: c, using: C.d) static let dThroughB = hasOne(D.self, through: b, using: B.d) func encode(to container: inout PersistenceContainer) { container["id"] = 1 } } struct B: TableRecord { static let c = belongsTo(C.self) static let d = hasOne(D.self, through: c, using: C.d) } struct C: TableRecord { static let d = hasOne(D.self) } struct D: TableRecord { } let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.create(table: "a") { t in t.autoIncrementedPrimaryKey("id") } try db.create(table: "c") { t in t.autoIncrementedPrimaryKey("id") } try db.create(table: "d") { t in t.autoIncrementedPrimaryKey("id") t.column("cId").references("c") } try db.create(table: "b") { t in t.autoIncrementedPrimaryKey("id") t.column("aId").references("a") t.column("cId").references("c") } try testHasOneWithThreeSteps( db, b: A.b, c: A.c, dThroughC: A.dThroughC, dThroughB: A.dThroughB, bCondition: "\"b\".\"aId\" = \"a\".\"id\"", cCondition: "\"c\".\"id\" = \"b\".\"cId\"", dCondition: "\"d\".\"cId\" = \"c\".\"id\"") try assertEqualSQL(db, A().request(for: A.dThroughC), """ SELECT "d".* FROM "d" \ JOIN "c" ON "c"."id" = "d"."cId" \ JOIN "b" ON ("b"."cId" = "c"."id") AND ("b"."aId" = 1) """) try assertEqualSQL(db, A().request(for: A.dThroughB), """ SELECT "d".* FROM "d" \ JOIN "c" ON "c"."id" = "d"."cId" \ JOIN "b" ON ("b"."cId" = "c"."id") AND ("b"."aId" = 1) """) } } func testHasOneHasOneBelongsTo() throws { struct A: TableRecord, EncodableRecord { static let b = hasOne(B.self) static let c = hasOne(C.self, through: b, using: B.c) static let dThroughC = hasOne(D.self, through: c, using: C.d) static let dThroughB = hasOne(D.self, through: b, using: B.d) func encode(to container: inout PersistenceContainer) { container["id"] = 1 } } struct B: TableRecord { static let c = hasOne(C.self) static let d = hasOne(D.self, through: c, using: C.d) } struct C: TableRecord { static let d = belongsTo(D.self) } struct D: TableRecord { } let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.create(table: "a") { t in t.autoIncrementedPrimaryKey("id") } try db.create(table: "d") { t in t.autoIncrementedPrimaryKey("id") } try db.create(table: "b") { t in t.autoIncrementedPrimaryKey("id") t.column("aId").references("a") } try db.create(table: "c") { t in t.autoIncrementedPrimaryKey("id") t.column("bId").references("b") t.column("dId").references("d") } try testHasOneWithThreeSteps( db, b: A.b, c: A.c, dThroughC: A.dThroughC, dThroughB: A.dThroughB, bCondition: "\"b\".\"aId\" = \"a\".\"id\"", cCondition: "\"c\".\"bId\" = \"b\".\"id\"", dCondition: "\"d\".\"id\" = \"c\".\"dId\"") try assertEqualSQL(db, A().request(for: A.dThroughC), """ SELECT "d".* FROM "d" \ JOIN "c" ON "c"."dId" = "d"."id" \ JOIN "b" ON ("b"."id" = "c"."bId") AND ("b"."aId" = 1) """) try assertEqualSQL(db, A().request(for: A.dThroughB), """ SELECT "d".* FROM "d" \ JOIN "c" ON "c"."dId" = "d"."id" \ JOIN "b" ON ("b"."id" = "c"."bId") AND ("b"."aId" = 1) """) } } func testHasOneHasOneHasOne() throws { struct A: TableRecord, EncodableRecord { static let b = hasOne(B.self) static let c = hasOne(C.self, through: b, using: B.c) static let dThroughC = hasOne(D.self, through: c, using: C.d) static let dThroughB = hasOne(D.self, through: b, using: B.d) func encode(to container: inout PersistenceContainer) { container["id"] = 1 } } struct B: TableRecord { static let c = hasOne(C.self) static let d = hasOne(D.self, through: c, using: C.d) } struct C: TableRecord { static let d = hasOne(D.self) } struct D: TableRecord { } let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.create(table: "a") { t in t.autoIncrementedPrimaryKey("id") } try db.create(table: "b") { t in t.autoIncrementedPrimaryKey("id") t.column("aId").references("a") } try db.create(table: "c") { t in t.autoIncrementedPrimaryKey("id") t.column("bId").references("b") } try db.create(table: "d") { t in t.autoIncrementedPrimaryKey("id") t.column("cId").references("c") } try testHasOneWithThreeSteps( db, b: A.b, c: A.c, dThroughC: A.dThroughC, dThroughB: A.dThroughB, bCondition: "\"b\".\"aId\" = \"a\".\"id\"", cCondition: "\"c\".\"bId\" = \"b\".\"id\"", dCondition: "\"d\".\"cId\" = \"c\".\"id\"") try assertEqualSQL(db, A().request(for: A.dThroughC), """ SELECT "d".* FROM "d" \ JOIN "c" ON "c"."id" = "d"."cId" \ JOIN "b" ON ("b"."id" = "c"."bId") AND ("b"."aId" = 1) """) try assertEqualSQL(db, A().request(for: A.dThroughB), """ SELECT "d".* FROM "d" \ JOIN "c" ON "c"."id" = "d"."cId" \ JOIN "b" ON ("b"."id" = "c"."bId") AND ("b"."aId" = 1) """) } } private func testHasOneWithThreeSteps<BAssociation, CAssociation, DCAssociation, DBAssociation>( _ db: Database, b: BAssociation, c: CAssociation, dThroughC: DCAssociation, dThroughB: DBAssociation, bCondition: String, cCondition: String, dCondition: String) throws where BAssociation: AssociationToOne, CAssociation: AssociationToOne, DCAssociation: AssociationToOne, DBAssociation: AssociationToOne, BAssociation.OriginRowDecoder: TableRecord, BAssociation.OriginRowDecoder == CAssociation.OriginRowDecoder, BAssociation.OriginRowDecoder == DCAssociation.OriginRowDecoder, BAssociation.OriginRowDecoder == DBAssociation.OriginRowDecoder { let A = CAssociation.OriginRowDecoder.self do { for request in [ A.including(optional: dThroughC), A.including(optional: dThroughB)] { try assertEqualSQL(db, request, """ SELECT "a".*, "d".* \ FROM "a" \ LEFT JOIN "b" ON \(bCondition) \ LEFT JOIN "c" ON \(cCondition) \ LEFT JOIN "d" ON \(dCondition) """) } for request in [ A.including(required: dThroughC), A.including(required: dThroughB)] { try assertEqualSQL(db, request, """ SELECT "a".*, "d".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) \ JOIN "d" ON \(dCondition) """) } for request in [ A.joining(optional: dThroughC), A.joining(optional: dThroughB)] { try assertEqualSQL(db, request, """ SELECT "a".* \ FROM "a" \ LEFT JOIN "b" ON \(bCondition) \ LEFT JOIN "c" ON \(cCondition) \ LEFT JOIN "d" ON \(dCondition) """) } for request in [ A.joining(required: dThroughC), A.joining(required: dThroughB)] { try assertEqualSQL(db, request, """ SELECT "a".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) \ JOIN "d" ON \(dCondition) """) } for request in [ A.annotated(withOptional: dThroughC), A.annotated(withOptional: dThroughB)] { try assertEqualSQL(db, request, """ SELECT "a".*, "d".* \ FROM "a" \ LEFT JOIN "b" ON \(bCondition) \ LEFT JOIN "c" ON \(cCondition) \ LEFT JOIN "d" ON \(dCondition) """) } for request in [ A.annotated(withRequired: dThroughC), A.annotated(withRequired: dThroughB)] { try assertEqualSQL(db, request, """ SELECT "a".*, "d".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) \ JOIN "d" ON \(dCondition) """) } for request in [ A.annotated(withRequired: dThroughC.select(Column.rowID)), A.annotated(withRequired: dThroughB.select(Column.rowID))] { try assertEqualSQL(db, request, """ SELECT "a".*, "d"."rowid" \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) \ JOIN "d" ON \(dCondition) """) } } do { do { for request in [ A.including(optional: dThroughC).including(optional: b), A.including(optional: dThroughB).including(optional: b)] { try assertEqualSQL(db, request, """ SELECT "a".*, "b".*, "d".* \ FROM "a" \ LEFT JOIN "b" ON \(bCondition) \ LEFT JOIN "c" ON \(cCondition) \ LEFT JOIN "d" ON \(dCondition) """) } for request in [ A.including(required: dThroughC).including(optional: b), A.including(required: dThroughB).including(optional: b)] { try assertEqualSQL(db, request, """ SELECT "a".*, "b".*, "d".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) \ JOIN "d" ON \(dCondition) """) } for request in [ A.joining(optional: dThroughC).including(optional: b), A.joining(optional: dThroughB).including(optional: b)] { try assertEqualSQL(db, request, """ SELECT "a".*, "b".* \ FROM "a" \ LEFT JOIN "b" ON \(bCondition) \ LEFT JOIN "c" ON \(cCondition) \ LEFT JOIN "d" ON \(dCondition) """) } for request in [ A.joining(required: dThroughC).including(optional: b), A.joining(required: dThroughB).including(optional: b)] { try assertEqualSQL(db, request, """ SELECT "a".*, "b".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) \ JOIN "d" ON \(dCondition) """) } for request in [ A.including(optional: b).annotated(withOptional: dThroughC), A.annotated(withOptional: dThroughB).including(optional: b)] { try assertEqualSQL(db, request, """ SELECT "a".*, "d".*, "b".* \ FROM "a" \ LEFT JOIN "b" ON \(bCondition) \ LEFT JOIN "c" ON \(cCondition) \ LEFT JOIN "d" ON \(dCondition) """) } for request in [ A.including(optional: b).annotated(withRequired: dThroughC), A.annotated(withRequired: dThroughB).including(optional: b)] { try assertEqualSQL(db, request, """ SELECT "a".*, "d".*, "b".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) \ JOIN "d" ON \(dCondition) """) } for request in [ A.including(optional: b).annotated(withRequired: dThroughC.select(Column.rowID)), A.annotated(withRequired: dThroughB.select(Column.rowID)).including(optional: b)] { try assertEqualSQL(db, request, """ SELECT "a".*, "d"."rowid", "b".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) \ JOIN "d" ON \(dCondition) """) } } do { for request in [ A.including(optional: dThroughC).including(required: b), A.including(optional: dThroughB).including(required: b)] { try assertEqualSQL(db, request, """ SELECT "a".*, "b".*, "d".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ LEFT JOIN "c" ON \(cCondition) \ LEFT JOIN "d" ON \(dCondition) """) } for request in [ A.including(required: dThroughC).including(required: b), A.including(required: dThroughB).including(required: b)] { try assertEqualSQL(db, request, """ SELECT "a".*, "b".*, "d".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) \ JOIN "d" ON \(dCondition) """) } for request in [ A.joining(optional: dThroughC).including(required: b), A.joining(optional: dThroughB).including(required: b)] { try assertEqualSQL(db, request, """ SELECT "a".*, "b".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ LEFT JOIN "c" ON \(cCondition) \ LEFT JOIN "d" ON \(dCondition) """) } for request in [ A.joining(required: dThroughC).including(required: b), A.joining(required: dThroughB).including(required: b)] { try assertEqualSQL(db, request, """ SELECT "a".*, "b".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) \ JOIN "d" ON \(dCondition) """) } for request in [ A.including(required: b).annotated(withOptional: dThroughC), A.annotated(withOptional: dThroughB).including(required: b)] { try assertEqualSQL(db, request, """ SELECT "a".*, "d".*, "b".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ LEFT JOIN "c" ON \(cCondition) \ LEFT JOIN "d" ON \(dCondition) """) } for request in [ A.including(required: b).annotated(withRequired: dThroughC), A.annotated(withRequired: dThroughB).including(required: b)] { try assertEqualSQL(db, request, """ SELECT "a".*, "d".*, "b".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) \ JOIN "d" ON \(dCondition) """) } for request in [ A.including(required: b).annotated(withRequired: dThroughC.select(Column.rowID)), A.annotated(withRequired: dThroughB.select(Column.rowID)).including(required: b)] { try assertEqualSQL(db, request, """ SELECT "a".*, "d"."rowid", "b".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) \ JOIN "d" ON \(dCondition) """) } } do { for request in [ A.including(optional: dThroughC).joining(optional: b), A.including(optional: dThroughB).joining(optional: b)] { try assertEqualSQL(db, request, """ SELECT "a".*, "d".* \ FROM "a" \ LEFT JOIN "b" ON \(bCondition) \ LEFT JOIN "c" ON \(cCondition) \ LEFT JOIN "d" ON \(dCondition) """) } for request in [ A.including(required: dThroughC).joining(optional: b), A.including(required: dThroughB).joining(optional: b)] { try assertEqualSQL(db, request, """ SELECT "a".*, "d".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) \ JOIN "d" ON \(dCondition) """) } for request in [ A.joining(optional: dThroughC).joining(optional: b), A.joining(optional: dThroughB).joining(optional: b)] { try assertEqualSQL(db, request, """ SELECT "a".* \ FROM "a" \ LEFT JOIN "b" ON \(bCondition) \ LEFT JOIN "c" ON \(cCondition) \ LEFT JOIN "d" ON \(dCondition) """) } for request in [ A.joining(required: dThroughC).joining(optional: b), A.joining(required: dThroughB).joining(optional: b)] { try assertEqualSQL(db, request, """ SELECT "a".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) \ JOIN "d" ON \(dCondition) """) } for request in [ A.joining(optional: b).annotated(withOptional: dThroughC), A.annotated(withOptional: dThroughB).joining(optional: b)] { try assertEqualSQL(db, request, """ SELECT "a".*, "d".* \ FROM "a" \ LEFT JOIN "b" ON \(bCondition) \ LEFT JOIN "c" ON \(cCondition) \ LEFT JOIN "d" ON \(dCondition) """) } for request in [ A.joining(optional: b).annotated(withRequired: dThroughC), A.annotated(withRequired: dThroughB).joining(optional: b)] { try assertEqualSQL(db, request, """ SELECT "a".*, "d".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) \ JOIN "d" ON \(dCondition) """) } for request in [ A.joining(optional: b).annotated(withRequired: dThroughC.select(Column.rowID)), A.annotated(withRequired: dThroughB.select(Column.rowID)).joining(optional: b)] { try assertEqualSQL(db, request, """ SELECT "a".*, "d"."rowid" \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) \ JOIN "d" ON \(dCondition) """) } } do { for request in [ A.including(optional: dThroughC).joining(required: b), A.including(optional: dThroughB).joining(required: b)] { try assertEqualSQL(db, request, """ SELECT "a".*, "d".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ LEFT JOIN "c" ON \(cCondition) \ LEFT JOIN "d" ON \(dCondition) """) } for request in [ A.including(required: dThroughC).joining(required: b), A.including(required: dThroughB).joining(required: b)] { try assertEqualSQL(db, request, """ SELECT "a".*, "d".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) \ JOIN "d" ON \(dCondition) """) } for request in [ A.joining(optional: dThroughC).joining(required: b), A.joining(optional: dThroughB).joining(required: b)] { try assertEqualSQL(db, request, """ SELECT "a".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ LEFT JOIN "c" ON \(cCondition) \ LEFT JOIN "d" ON \(dCondition) """) } for request in [ A.joining(required: dThroughC).joining(required: b), A.joining(required: dThroughB).joining(required: b)] { try assertEqualSQL(db, request, """ SELECT "a".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) \ JOIN "d" ON \(dCondition) """) } for request in [ A.joining(required: b).annotated(withOptional: dThroughC), A.annotated(withOptional: dThroughB).joining(required: b)] { try assertEqualSQL(db, request, """ SELECT "a".*, "d".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ LEFT JOIN "c" ON \(cCondition) \ LEFT JOIN "d" ON \(dCondition) """) } for request in [ A.joining(required: b).annotated(withRequired: dThroughC), A.annotated(withRequired: dThroughB).joining(required: b)] { try assertEqualSQL(db, request, """ SELECT "a".*, "d".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) \ JOIN "d" ON \(dCondition) """) } for request in [ A.joining(required: b).annotated(withRequired: dThroughC.select(Column.rowID)), A.annotated(withRequired: dThroughB.select(Column.rowID)).joining(required: b)] { try assertEqualSQL(db, request, """ SELECT "a".*, "d"."rowid" \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) \ JOIN "d" ON \(dCondition) """) } } } do { do { for request in [ A.including(optional: dThroughC).including(optional: c), A.including(optional: dThroughB).including(optional: c)] { try assertEqualSQL(db, request, """ SELECT "a".*, "c".*, "d".* \ FROM "a" \ LEFT JOIN "b" ON \(bCondition) \ LEFT JOIN "c" ON \(cCondition) \ LEFT JOIN "d" ON \(dCondition) """) } for request in [ A.including(required: dThroughC).including(optional: c), A.including(required: dThroughB).including(optional: c)] { try assertEqualSQL(db, request, """ SELECT "a".*, "c".*, "d".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) \ JOIN "d" ON \(dCondition) """) } for request in [ A.joining(optional: dThroughC).including(optional: c), A.joining(optional: dThroughB).including(optional: c)] { try assertEqualSQL(db, request, """ SELECT "a".*, "c".* \ FROM "a" \ LEFT JOIN "b" ON \(bCondition) \ LEFT JOIN "c" ON \(cCondition) \ LEFT JOIN "d" ON \(dCondition) """) } for request in [ A.joining(required: dThroughC).including(optional: c), A.joining(required: dThroughB).including(optional: c)] { try assertEqualSQL(db, request, """ SELECT "a".*, "c".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) \ JOIN "d" ON \(dCondition) """) } for request in [ A.including(optional: c).annotated(withOptional: dThroughC), A.annotated(withOptional: dThroughB).including(optional: c)] { try assertEqualSQL(db, request, """ SELECT "a".*, "d".*, "c".* \ FROM "a" \ LEFT JOIN "b" ON \(bCondition) \ LEFT JOIN "c" ON \(cCondition) \ LEFT JOIN "d" ON \(dCondition) """) } for request in [ A.including(optional: c).annotated(withRequired: dThroughC), A.annotated(withRequired: dThroughB).including(optional: c)] { try assertEqualSQL(db, request, """ SELECT "a".*, "d".*, "c".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) \ JOIN "d" ON \(dCondition) """) } for request in [ A.including(optional: c).annotated(withRequired: dThroughC.select(Column.rowID)), A.annotated(withRequired: dThroughB.select(Column.rowID)).including(optional: c)] { try assertEqualSQL(db, request, """ SELECT "a".*, "d"."rowid", "c".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) \ JOIN "d" ON \(dCondition) """) } } do { for request in [ A.including(optional: dThroughC).including(required: c), A.including(optional: dThroughB).including(required: c)] { try assertEqualSQL(db, request, """ SELECT "a".*, "c".*, "d".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) \ LEFT JOIN "d" ON \(dCondition) """) } for request in [ A.including(required: dThroughC).including(required: c), A.including(required: dThroughB).including(required: c)] { try assertEqualSQL(db, request, """ SELECT "a".*, "c".*, "d".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) \ JOIN "d" ON \(dCondition) """) } for request in [ A.joining(optional: dThroughC).including(required: c), A.joining(optional: dThroughB).including(required: c)] { try assertEqualSQL(db, request, """ SELECT "a".*, "c".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) \ LEFT JOIN "d" ON \(dCondition) """) } for request in [ A.joining(required: dThroughC).including(required: c), A.joining(required: dThroughB).including(required: c)] { try assertEqualSQL(db, request, """ SELECT "a".*, "c".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) \ JOIN "d" ON \(dCondition) """) } for request in [ A.including(required: c).annotated(withOptional: dThroughC), A.annotated(withOptional: dThroughB).including(required: c)] { try assertEqualSQL(db, request, """ SELECT "a".*, "d".*, "c".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) \ LEFT JOIN "d" ON \(dCondition) """) } for request in [ A.including(required: c).annotated(withRequired: dThroughC), A.annotated(withRequired: dThroughB).including(required: c)] { try assertEqualSQL(db, request, """ SELECT "a".*, "d".*, "c".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) \ JOIN "d" ON \(dCondition) """) } for request in [ A.including(required: c).annotated(withRequired: dThroughC.select(Column.rowID)), A.annotated(withRequired: dThroughB.select(Column.rowID)).including(required: c)] { try assertEqualSQL(db, request, """ SELECT "a".*, "d"."rowid", "c".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) \ JOIN "d" ON \(dCondition) """) } } do { for request in [ A.including(optional: dThroughC).joining(optional: c), A.including(optional: dThroughB).joining(optional: c)] { try assertEqualSQL(db, request, """ SELECT "a".*, "d".* \ FROM "a" \ LEFT JOIN "b" ON \(bCondition) \ LEFT JOIN "c" ON \(cCondition) \ LEFT JOIN "d" ON \(dCondition) """) } for request in [ A.including(required: dThroughC).joining(optional: c), A.including(required: dThroughB).joining(optional: c)] { try assertEqualSQL(db, request, """ SELECT "a".*, "d".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) \ JOIN "d" ON \(dCondition) """) } for request in [ A.joining(optional: dThroughC).joining(optional: c), A.joining(optional: dThroughB).joining(optional: c)] { try assertEqualSQL(db, request, """ SELECT "a".* \ FROM "a" \ LEFT JOIN "b" ON \(bCondition) \ LEFT JOIN "c" ON \(cCondition) \ LEFT JOIN "d" ON \(dCondition) """) } for request in [ A.joining(required: dThroughC).joining(optional: c), A.joining(required: dThroughB).joining(optional: c)] { try assertEqualSQL(db, request, """ SELECT "a".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) \ JOIN "d" ON \(dCondition) """) } for request in [ A.joining(optional: c).annotated(withOptional: dThroughC), A.annotated(withOptional: dThroughB).joining(optional: c)] { try assertEqualSQL(db, request, """ SELECT "a".*, "d".* \ FROM "a" \ LEFT JOIN "b" ON \(bCondition) \ LEFT JOIN "c" ON \(cCondition) \ LEFT JOIN "d" ON \(dCondition) """) } for request in [ A.joining(optional: c).annotated(withRequired: dThroughC), A.annotated(withRequired: dThroughB).joining(optional: c)] { try assertEqualSQL(db, request, """ SELECT "a".*, "d".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) \ JOIN "d" ON \(dCondition) """) } for request in [ A.joining(optional: c).annotated(withRequired: dThroughC.select(Column.rowID)), A.annotated(withRequired: dThroughB.select(Column.rowID)).joining(optional: c)] { try assertEqualSQL(db, request, """ SELECT "a".*, "d"."rowid" \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) \ JOIN "d" ON \(dCondition) """) } } do { for request in [ A.including(optional: dThroughC).joining(required: c), A.including(optional: dThroughB).joining(required: c)] { try assertEqualSQL(db, request, """ SELECT "a".*, "d".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) \ LEFT JOIN "d" ON \(dCondition) """) } for request in [ A.including(required: dThroughC).joining(required: c), A.including(required: dThroughB).joining(required: c)] { try assertEqualSQL(db, request, """ SELECT "a".*, "d".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) \ JOIN "d" ON \(dCondition) """) } for request in [ A.joining(optional: dThroughC).joining(required: c), A.joining(optional: dThroughB).joining(required: c)] { try assertEqualSQL(db, request, """ SELECT "a".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) \ LEFT JOIN "d" ON \(dCondition) """) } for request in [ A.joining(required: dThroughC).joining(required: c), A.joining(required: dThroughB).joining(required: c)] { try assertEqualSQL(db, request, """ SELECT "a".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) \ JOIN "d" ON \(dCondition) """) } for request in [ A.joining(required: c).annotated(withOptional: dThroughC), A.annotated(withOptional: dThroughB).joining(required: c)] { try assertEqualSQL(db, request, """ SELECT "a".*, "d".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) \ LEFT JOIN "d" ON \(dCondition) """) } for request in [ A.joining(required: c).annotated(withRequired: dThroughC), A.annotated(withRequired: dThroughB).joining(required: c)] { try assertEqualSQL(db, request, """ SELECT "a".*, "d".* \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) \ JOIN "d" ON \(dCondition) """) } for request in [ A.joining(required: c).annotated(withRequired: dThroughC.select(Column.rowID)), A.annotated(withRequired: dThroughB.select(Column.rowID)).joining(required: c)] { try assertEqualSQL(db, request, """ SELECT "a".*, "d"."rowid" \ FROM "a" \ JOIN "b" ON \(bCondition) \ JOIN "c" ON \(cCondition) \ JOIN "d" ON \(dCondition) """) } } } } // MARK: - Four Steps func testBelongsToBelongsToBelongsToBelongsTo() throws { struct A: TableRecord, EncodableRecord { static let b = belongsTo(B.self) static let c = hasOne(C.self, through: b, using: B.c) static let dThroughB = hasOne(D.self, through: b, using: B.d) static let dThroughC = hasOne(D.self, through: c, using: C.d) static let eThroughBThroughC = hasOne(E.self, through: b, using: B.eThroughC) static let eThroughBThroughD = hasOne(E.self, through: b, using: B.eThroughD) static let eThroughC = hasOne(E.self, through: c, using: C.e) static let eThroughDThroughB = hasOne(E.self, through: dThroughB, using: D.e) static let eThroughDThroughC = hasOne(E.self, through: dThroughC, using: D.e) func encode(to container: inout PersistenceContainer) { container["bId"] = 1 } } struct B: TableRecord { static let c = belongsTo(C.self) static let d = hasOne(D.self, through: c, using: C.d) static let eThroughC = hasOne(E.self, through: c, using: C.e) static let eThroughD = hasOne(E.self, through: d, using: D.e) } struct C: TableRecord { static let d = belongsTo(D.self) static let e = hasOne(E.self, through: d, using: D.e) } struct D: TableRecord { static let e = belongsTo(E.self) } struct E: TableRecord { } let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.create(table: "e") { t in t.autoIncrementedPrimaryKey("id") } try db.create(table: "d") { t in t.autoIncrementedPrimaryKey("id") t.column("eId").references("e") } try db.create(table: "c") { t in t.autoIncrementedPrimaryKey("id") t.column("dId").references("d") } try db.create(table: "b") { t in t.autoIncrementedPrimaryKey("id") t.column("cId").references("c") } try db.create(table: "a") { t in t.autoIncrementedPrimaryKey("id") t.column("bId").references("b") } let associations = [ A.eThroughBThroughC, A.eThroughBThroughD, A.eThroughC, A.eThroughDThroughB, A.eThroughDThroughC, ] for association in associations { try assertEqualSQL(db, A.including(required: association), """ SELECT "a".*, "e".* \ FROM "a" \ JOIN "b" ON "b"."id" = "a"."bId" \ JOIN "c" ON "c"."id" = "b"."cId" \ JOIN "d" ON "d"."id" = "c"."dId" \ JOIN "e" ON "e"."id" = "d"."eId" """) try assertEqualSQL(db, A.including(optional: association), """ SELECT "a".*, "e".* \ FROM "a" \ LEFT JOIN "b" ON "b"."id" = "a"."bId" \ LEFT JOIN "c" ON "c"."id" = "b"."cId" \ LEFT JOIN "d" ON "d"."id" = "c"."dId" \ LEFT JOIN "e" ON "e"."id" = "d"."eId" """) try assertEqualSQL(db, A.joining(required: association), """ SELECT "a".* \ FROM "a" \ JOIN "b" ON "b"."id" = "a"."bId" \ JOIN "c" ON "c"."id" = "b"."cId" \ JOIN "d" ON "d"."id" = "c"."dId" \ JOIN "e" ON "e"."id" = "d"."eId" """) try assertEqualSQL(db, A.joining(optional: association), """ SELECT "a".* \ FROM "a" \ LEFT JOIN "b" ON "b"."id" = "a"."bId" \ LEFT JOIN "c" ON "c"."id" = "b"."cId" \ LEFT JOIN "d" ON "d"."id" = "c"."dId" \ LEFT JOIN "e" ON "e"."id" = "d"."eId" """) try assertEqualSQL(db, A().request(for: association), """ SELECT "e".* \ FROM "e" \ JOIN "d" ON "d"."eId" = "e"."id" \ JOIN "c" ON "c"."dId" = "d"."id" \ JOIN "b" ON ("b"."cId" = "c"."id") AND ("b"."id" = 1) """) } } } }
mit
0a3a56357b8a3187621980f557e11679
40.59096
114
0.400209
4.591609
false
false
false
false
almapp/uc-access-ios
uc-access/src/WebPage.swift
1
2568
// // WebPage.swift // uc-access // // Created by Patricio Lopez on 13-01-16. // Copyright © 2016 Almapp. All rights reserved. // import Foundation import PromiseKit import SwiftyJSON public class WebPageCategory { let name: String let detail: String var webpages: [WebPage] init(name: String, detail: String, webpages: [WebPage]) { self.name = name self.detail = detail self.webpages = webpages } var activeWebpages: [WebPage] { get { return self.webpages.filter { $0.selected } } } } public class WebPageGroup { let name: String let detail: String var categories: [WebPageCategory] init(name: String, detail: String, categories: [WebPageCategory]) { self.name = name self.detail = detail self.categories = categories } var activeCategories: [WebPageCategory] { get { return self.categories.filter { $0.activeWebpages.count > 0 } } } } public class WebPageFetcher { var URL: String init(URL: String) { self.URL = URL } func fetch() -> Promise<[WebPageGroup]> { return Request.GET(self.URL).then { (response, data) -> [WebPageGroup] in return JSON(data: data).arrayValue.map { group in WebPageGroup(name: group["name"].stringValue, detail: group["detail"].stringValue, categories: group["categories"].arrayValue.map { category in WebPageCategory(name: category["name"].stringValue, detail: category["detail"].stringValue, webpages: category["services"].arrayValue.map { service in WebPage.fromJSON(service) }) }) } } } } public class WebPage { let id: String? let name: String let description: String let URL: String let imageURL: String var selected: Bool init(id: String?, name: String, description: String, URL: String, imageURL: String, selected: Bool = true) { self.id = id self.name = name self.description = description self.URL = URL self.imageURL = imageURL self.selected = true } static func fromJSON(json: JSON) -> WebPage { return WebPage( id: json["id"].stringValue, name: json["name"].stringValue, description: json["description"].stringValue, URL: json["url"].stringValue, imageURL: json["image"].stringValue ) } }
gpl-3.0
5242089081f9172544e64cf263646781
26.021053
170
0.585508
4.292642
false
false
false
false
davidisaaclee/VectorSwift
Example/Pods/Quick/Sources/Quick/World.swift
1
8727
import Foundation /** A closure that, when evaluated, returns a dictionary of key-value pairs that can be accessed from within a group of shared examples. */ public typealias SharedExampleContext = () -> (NSDictionary) /** A closure that is used to define a group of shared examples. This closure may contain any number of example and example groups. */ public typealias SharedExampleClosure = (SharedExampleContext) -> () /** A collection of state Quick builds up in order to work its magic. World is primarily responsible for maintaining a mapping of QuickSpec classes to root example groups for those classes. It also maintains a mapping of shared example names to shared example closures. You may configure how Quick behaves by calling the -[World configure:] method from within an overridden +[QuickConfiguration configure:] method. */ final internal class World: NSObject { /** The example group that is currently being run. The DSL requires that this group is correctly set in order to build a correct hierarchy of example groups and their examples. */ internal var currentExampleGroup: ExampleGroup! /** The example metadata of the test that is currently being run. This is useful for using the Quick test metadata (like its name) at runtime. */ internal var currentExampleMetadata: ExampleMetadata? /** A flag that indicates whether additional test suites are being run within this test suite. This is only true within the context of Quick functional tests. */ #if _runtime(_ObjC) // Convention of generating Objective-C selector has been changed on Swift 3 @objc(isRunningAdditionalSuites) internal var isRunningAdditionalSuites = false #else internal var isRunningAdditionalSuites = false #endif private var specs: Dictionary<String, ExampleGroup> = [:] private var sharedExamples: [String: SharedExampleClosure] = [:] private let configuration = Configuration() private var isConfigurationFinalized = false internal var exampleHooks: ExampleHooks {return configuration.exampleHooks } internal var suiteHooks: SuiteHooks { return configuration.suiteHooks } // MARK: Singleton Constructor private override init() {} static let sharedWorld = World() // MARK: Public Interface /** Exposes the World's Configuration object within the scope of the closure so that it may be configured. This method must not be called outside of an overridden +[QuickConfiguration configure:] method. - parameter closure: A closure that takes a Configuration object that can be mutated to change Quick's behavior. */ internal func configure(_ closure: QuickConfigurer) { assert(!isConfigurationFinalized, "Quick cannot be configured outside of a +[QuickConfiguration configure:] method. You should not call -[World configure:] directly. Instead, subclass QuickConfiguration and override the +[QuickConfiguration configure:] method.") closure(configuration) } /** Finalizes the World's configuration. Any subsequent calls to World.configure() will raise. */ internal func finalizeConfiguration() { isConfigurationFinalized = true } /** Returns an internally constructed root example group for the given QuickSpec class. A root example group with the description "root example group" is lazily initialized for each QuickSpec class. This root example group wraps the top level of a -[QuickSpec spec] method--it's thanks to this group that users can define beforeEach and it closures at the top level, like so: override func spec() { // These belong to the root example group beforeEach {} it("is at the top level") {} } - parameter cls: The QuickSpec class for which to retrieve the root example group. - returns: The root example group for the class. */ internal func rootExampleGroupForSpecClass(_ cls: AnyClass) -> ExampleGroup { #if _runtime(_ObjC) let name = NSStringFromClass(cls) #else let name = String(cls) #endif if let group = specs[name] { return group } else { let group = ExampleGroup( description: "root example group", flags: [:], isInternalRootExampleGroup: true ) specs[name] = group return group } } /** Returns all examples that should be run for a given spec class. There are two filtering passes that occur when determining which examples should be run. That is, these examples are the ones that are included by inclusion filters, and are not excluded by exclusion filters. - parameter specClass: The QuickSpec subclass for which examples are to be returned. - returns: A list of examples to be run as test invocations. */ internal func examples(_ specClass: AnyClass) -> [Example] { // 1. Grab all included examples. let included = includedExamples // 2. Grab the intersection of (a) examples for this spec, and (b) included examples. let spec = rootExampleGroupForSpecClass(specClass).examples.filter { included.contains($0) } // 3. Remove all excluded examples. return spec.filter { example in !self.configuration.exclusionFilters.reduce(false) { $0 || $1(example) } } } #if _runtime(_ObjC) @objc(examplesForSpecClass:) private func objc_examples(_ specClass: AnyClass) -> [Example] { return examples(specClass) } #endif // MARK: Internal internal func registerSharedExample(_ name: String, closure: SharedExampleClosure) { raiseIfSharedExampleAlreadyRegistered(name) sharedExamples[name] = closure } internal func sharedExample(_ name: String) -> SharedExampleClosure { raiseIfSharedExampleNotRegistered(name) return sharedExamples[name]! } internal var includedExampleCount: Int { return includedExamples.count } internal var beforesCurrentlyExecuting: Bool { let suiteBeforesExecuting = suiteHooks.phase == .beforesExecuting let exampleBeforesExecuting = exampleHooks.phase == .beforesExecuting var groupBeforesExecuting = false if let runningExampleGroup = currentExampleMetadata?.example.group { groupBeforesExecuting = runningExampleGroup.phase == .beforesExecuting } return suiteBeforesExecuting || exampleBeforesExecuting || groupBeforesExecuting } internal var aftersCurrentlyExecuting: Bool { let suiteAftersExecuting = suiteHooks.phase == .aftersExecuting let exampleAftersExecuting = exampleHooks.phase == .aftersExecuting var groupAftersExecuting = false if let runningExampleGroup = currentExampleMetadata?.example.group { groupAftersExecuting = runningExampleGroup.phase == .aftersExecuting } return suiteAftersExecuting || exampleAftersExecuting || groupAftersExecuting } internal func performWithCurrentExampleGroup(_ group: ExampleGroup, closure: () -> Void) { let previousExampleGroup = currentExampleGroup currentExampleGroup = group closure() currentExampleGroup = previousExampleGroup } private var allExamples: [Example] { var all: [Example] = [] for (_, group) in specs { group.walkDownExamples { all.append($0) } } return all } private var includedExamples: [Example] { let all = allExamples let included = all.filter { example in return self.configuration.inclusionFilters.reduce(false) { $0 || $1(example) } } if included.isEmpty && configuration.runAllWhenEverythingFiltered { return all } else { return included } } private func raiseIfSharedExampleAlreadyRegistered(_ name: String) { if sharedExamples[name] != nil { raiseError("A shared example named '\(name)' has already been registered.") } } private func raiseIfSharedExampleNotRegistered(_ name: String) { if sharedExamples[name] == nil { raiseError("No shared example named '\(name)' has been registered. Registered shared examples: '\(Array(sharedExamples.keys))'") } } }
mit
f9c6c6dd960e1e9fd0d91b53828404c7
35.978814
243
0.665865
5.305167
false
true
false
false
apple/swift-corelibs-foundation
Darwin/Foundation-swiftoverlay/Notification.swift
1
6180
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module /** `Notification` encapsulates information broadcast to observers via a `NotificationCenter`. */ public struct Notification : ReferenceConvertible, Equatable, Hashable { public typealias ReferenceType = NSNotification /// A tag identifying the notification. public var name: Name /// An object that the poster wishes to send to observers. /// /// Typically this is the object that posted the notification. public var object: Any? /// Storage for values or objects related to this notification. public var userInfo: [AnyHashable : Any]? /// Initialize a new `Notification`. /// /// The default value for `userInfo` is nil. public init(name: Name, object: Any? = nil, userInfo: [AnyHashable : Any]? = nil) { self.name = name self.object = object self.userInfo = userInfo } public func hash(into hasher: inout Hasher) { hasher.combine(name) // FIXME: We should feed `object` to the hasher, too. However, this // cannot be safely done if its value happens not to be Hashable. // FIXME: == compares `userInfo` by bridging it to NSDictionary, so its // contents should be fully hashed here. However, to prevent stability // issues with userInfo dictionaries that include non-Hashable values, // we only feed the keys to the hasher here. // // FIXME: This makes for weak hashes. We really should hash everything // that's compared in ==. // // The algorithm below is the same as the one used by Dictionary. var commutativeKeyHash = 0 if let userInfo = userInfo { for (k, _) in userInfo { var nestedHasher = hasher nestedHasher.combine(k) commutativeKeyHash ^= nestedHasher.finalize() } } hasher.combine(commutativeKeyHash) } public var description: String { return "name = \(name.rawValue), object = \(String(describing: object)), userInfo = \(String(describing: userInfo))" } public var debugDescription: String { return description } // FIXME: Handle directly via API Notes public typealias Name = NSNotification.Name /// Compare two notifications for equality. public static func ==(lhs: Notification, rhs: Notification) -> Bool { if lhs.name.rawValue != rhs.name.rawValue { return false } if let lhsObj = lhs.object { if let rhsObj = rhs.object { // FIXME: Converting an arbitrary value to AnyObject won't use a // stable address when the value needs to be boxed. Therefore, // this comparison makes == non-reflexive, violating Equatable // requirements. (rdar://problem/49797185) if lhsObj as AnyObject !== rhsObj as AnyObject { return false } } else { return false } } else if rhs.object != nil { return false } if lhs.userInfo != nil { if rhs.userInfo != nil { // user info must be compared in the object form since the userInfo in swift is not comparable // FIXME: This violates reflexivity when userInfo contains any // non-Hashable values, for the same reason as described above. return lhs._bridgeToObjectiveC() == rhs._bridgeToObjectiveC() } else { return false } } else if rhs.userInfo != nil { return false } return true } } extension Notification: CustomReflectable { public var customMirror: Mirror { var children: [(label: String?, value: Any)] = [] children.append((label: "name", value: self.name.rawValue)) if let o = self.object { children.append((label: "object", value: o)) } if let u = self.userInfo { children.append((label: "userInfo", value: u)) } let m = Mirror(self, children:children, displayStyle: Mirror.DisplayStyle.class) return m } } extension Notification : _ObjectiveCBridgeable { public static func _getObjectiveCType() -> Any.Type { return NSNotification.self } @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSNotification { return NSNotification(name: name, object: object, userInfo: userInfo) } public static func _forceBridgeFromObjectiveC(_ x: NSNotification, result: inout Notification?) { if !_conditionallyBridgeFromObjectiveC(x, result: &result) { fatalError("Unable to bridge type") } } public static func _conditionallyBridgeFromObjectiveC(_ x: NSNotification, result: inout Notification?) -> Bool { result = Notification(name: x.name, object: x.object, userInfo: x.userInfo) return true } @_effects(readonly) public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNotification?) -> Notification { guard let src = source else { return Notification(name: Notification.Name("")) } return Notification(name: src.name, object: src.object, userInfo: src.userInfo) } } extension NSNotification : _HasCustomAnyHashableRepresentation { // Must be @nonobjc to avoid infinite recursion during bridging. @nonobjc public func _toCustomAnyHashable() -> AnyHashable? { return AnyHashable(self as Notification) } }
apache-2.0
6334e27fade08173d03421ffdb1962b0
36.228916
124
0.606472
5.137157
false
false
false
false
studyYF/SingleSugar
SingleSugar/SingleSugar/Classes/Monosaccharide(单糖)/Controller/YFSearchViewController.swift
1
1599
// // YFSearchViewController.swift // SingleSugar // // Created by YangFan on 2017/4/19. // Copyright © 2017年 YangFan. All rights reserved. // import UIKit class YFSearchViewController: ViewController { //MARK: 定义属性 lazy var searchBar: UISearchBar = { let searchBar = UISearchBar() searchBar.placeholder = "搜索商品、专题" searchBar.layer.cornerRadius = 5 searchBar.tintColor = UIColor.blue searchBar.backgroundColor = UIColor.white return searchBar }() //MARK: 生命周期函数 override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white setUI() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) searchBar.becomeFirstResponder() } override func viewWillDisappear(_ animated: Bool) { super.viewWillAppear(animated) searchBar.resignFirstResponder() } } extension YFSearchViewController { fileprivate func setUI() { //1.隐藏左侧返回,添加取消按钮 navigationItem.leftBarButtonItem = UIBarButtonItem(customView: UIView()) navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: .plain, target: self, action: #selector(YFSearchViewController.cancle)) //2.设置导航栏搜索 navigationItem.titleView = searchBar } } //MARK: 方法 extension YFSearchViewController { @objc fileprivate func cancle() { navigationController?.popViewController(animated: true) } }
apache-2.0
08937355c7e3fba6f2a1e50b16cc2d1b
26.071429
151
0.668206
4.906149
false
false
false
false
kysonyangs/ysbilibili
ysbilibili/Expand/CustomUI/YSRabbitFreshBaseViewController.swift
1
18864
// // YSRabbitFreshBaseViewController.swift // ysbilibili // // Created by MOLBASE on 2017/8/7. // Copyright © 2017年 YangShen. All rights reserved. // import UIKit class YSRabbitFreshBaseViewController: UIViewController { // MARK: - 常量变量 fileprivate var dragging: Bool = false fileprivate var isinherit: Bool = true fileprivate var freshing: Bool = false // 是否在刷新状态 fileprivate let krabbitEarWidth: CGFloat = 35 fileprivate let krabbitEarHeight: CGFloat = 6 fileprivate let kfreshMinHeight: CGFloat = 50// 兔耳朵开始显示的高度 fileprivate let KfreshMaxHeight: CGFloat = 100// 兔耳朵转动到最大值90度的高度 fileprivate let knoticelabelCenterY: CGFloat = 40 fileprivate let kscrollViewCornerRadius: CGFloat = 8 fileprivate let screenWidth = UIScreen.main.bounds.width fileprivate var animateTimer:Timer? var contentScrollView:UIScrollView? // MARK: - 懒加载 fileprivate lazy var containerView: UIView = { let tempView = UIView() tempView.backgroundColor = UIColor.clear return tempView }() fileprivate lazy var rabbitEarMaskView: UIView = {[unowned self] in let maskView = UIView() maskView.backgroundColor = UIColor.clear maskView.layer.cornerRadius = self.kscrollViewCornerRadius return maskView }() lazy var rabbitEarMaskTopView: UIView = {[unowned self] in let maskTopView = UIView() maskTopView.clipsToBounds = true maskTopView.backgroundColor = kHomeBackColor maskTopView.layer.cornerRadius = self.kscrollViewCornerRadius return maskTopView }() fileprivate lazy var leftRabbitEar: UIView = {[unowned self] in let tempRabbitEar = UIImageView() tempRabbitEar.backgroundColor = UIColor.ysColor(red: 241, green: 241, blue: 241, alpha: 1) tempRabbitEar.layer.cornerRadius = self.krabbitEarHeight/2 return tempRabbitEar }() fileprivate lazy var rightRabbitEar: UIView = {[unowned self] in let tempRabbitEar = UIImageView() tempRabbitEar.backgroundColor = UIColor.ysColor(red: 241, green: 241, blue: 241, alpha: 1) tempRabbitEar.layer.cornerRadius = self.krabbitEarHeight/2 return tempRabbitEar }() fileprivate lazy var firstSingleView: UIImageView = { let firstSingleView = UIImageView() firstSingleView.backgroundColor = UIColor.clear firstSingleView.layer.borderColor = UIColor.white.cgColor firstSingleView.layer.borderWidth = 0.3 firstSingleView.layer.cornerRadius = 2 return firstSingleView }() fileprivate lazy var secondSingleView: UIImageView = { let secondSingleView = UIImageView() secondSingleView.backgroundColor = UIColor.clear secondSingleView.layer.borderColor = UIColor.white.cgColor secondSingleView.layer.borderWidth = 0.3 secondSingleView.layer.cornerRadius = 2 return secondSingleView }() fileprivate lazy var noticeLabel: UILabel = { let noticeLabel = UILabel() noticeLabel.text = "再用点力!" noticeLabel.textAlignment = NSTextAlignment.center noticeLabel.textColor = UIColor.ysColor(red: 244, green: 169, blue: 191, alpha: 1) noticeLabel.font = UIFont.systemFont(ofSize: 12) noticeLabel.alpha = 0 return noticeLabel }() fileprivate lazy var gifImageView: UIImageView = { let tempGif = UIImageView.createRabbitReFreshGif(); return tempGif }() fileprivate lazy var gifNoticeLabel: UILabel = { let gifLabel = UILabel() gifLabel.text = "正在加载.." gifLabel.textColor = UIColor.lightGray gifLabel.font = UIFont.systemFont(ofSize: 12) gifLabel.textAlignment = NSTextAlignment.center gifLabel.isHidden = true return gifLabel }() // MARK: - 控制器的生命周期 override func viewDidLoad() { super.viewDidLoad() // 加载ui self.setupUI() // 隐藏navibar之后默认滑动返回失效,可以通过设置代理 重载gestureRecognizerShouldBegin方法来使滑动返回返回继续生效 self.navigationController?.interactivePopGestureRecognizer?.delegate = self } deinit { contentScrollView?.removeObserver(self, forKeyPath: "contentOffset", context: nil) print(" rabbitfreshcontroller -- 销毁了") } } //======================================================================== // MARK:- 私有方法 //======================================================================== extension YSRabbitFreshBaseViewController { // 设置控件的transform fileprivate func valueTransform(trans:CGFloat,rota:CGFloat){ var Ltransform = CGAffineTransform.identity Ltransform = Ltransform.rotated(by: rota) var Rtransform = CGAffineTransform.identity Rtransform = Rtransform.rotated(by: -rota) leftRabbitEar.transform = Ltransform rightRabbitEar.transform = Rtransform } // 初始化ui fileprivate func setupUI() { // 1.初始化scrollview contentScrollView = setUpScrollView() contentScrollView?.layer.cornerRadius = kscrollViewCornerRadius contentScrollView?.delegate = self contentScrollView?.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.new, context: nil) contentScrollView?.backgroundColor = UIColor.clear assert(isinherit, "ZHNrabbitFreshBaseViewController的子类需要重载setUpScrollView方法") view.backgroundColor = kNavBarColor // 2.展示gifview的父控件 view.addSubview(rabbitEarMaskView) rabbitEarMaskView.frame = CGRect(x: 0, y: kNavBarHeight, width: view.ysWidth, height: view.ysHeight) // 3.左耳 rabbitEarMaskView.addSubview(leftRabbitEar) leftRabbitEar.frame = CGRect(x: screenWidth/2 - (krabbitEarWidth) + 5, y: 10, width: krabbitEarWidth, height: krabbitEarHeight) leftRabbitEar.layer.anchorPoint = CGPoint(x: 1, y: 0.5) // 4.右耳 rabbitEarMaskView.addSubview(rightRabbitEar) rightRabbitEar.frame = CGRect(x: screenWidth/2 - 5, y: 10, width: krabbitEarWidth, height: krabbitEarHeight) rightRabbitEar.layer.anchorPoint = CGPoint(x: 0, y: 0.5) // 5.滑动view的父控件 view.addSubview(containerView) containerView.frame = view.bounds // 6.滑动控件 containerView.addSubview(contentScrollView!) contentScrollView?.frame = CGRect(x: 0, y: kNavBarHeight, width: view.ysWidth, height: view.ysHeight) // 7.展示gif的view rabbitEarMaskView.addSubview(rabbitEarMaskTopView) rabbitEarMaskTopView.frame = rabbitEarMaskView.bounds // 8.信号动画view // 1 rabbitEarMaskView.addSubview(firstSingleView) firstSingleView.center = CGPoint(x: rabbitEarMaskView.ysCenterX, y: -20) firstSingleView.bounds = CGRect(x: 0, y: 0, width: 8, height: 4) firstSingleView.isHidden = true // 2 rabbitEarMaskView.addSubview(secondSingleView) secondSingleView.center = CGPoint(x: rabbitEarMaskView.ysCenterX, y: -20) secondSingleView.bounds = CGRect(x: 0, y: 0, width: 8, height: 4) secondSingleView.isHidden = true // 9.刷新gifview rabbitEarMaskTopView.addSubview(gifImageView) gifImageView.center = CGPoint(x: rabbitEarMaskTopView.ysCenterX, y: 15) gifImageView.bounds = CGRect(x: 0, y: 0, width: 100, height: 40) rabbitEarMaskTopView.addSubview(gifNoticeLabel) gifNoticeLabel.center = CGPoint(x: rabbitEarMaskTopView.ysCenterX, y: 35) gifNoticeLabel.bounds = CGRect(x: 0, y: 0, width: 100, height: 30) // 10.下拉提示文字label view.addSubview(noticeLabel) noticeLabel.center = CGPoint(x: view.center.x, y: knoticelabelCenterY) noticeLabel.bounds = CGRect(x: 0, y: 0, width: 100, height: 30) } // 设置动画的定时器 fileprivate func setTimer(){ // 1. 添加kongj rabbitEarMaskView.addSubview(firstSingleView) rabbitEarMaskView.addSubview(secondSingleView) // 2. 先添加一次动画 self.addAnimation() // 3. 定时间添加定间隔的动画 animateTimer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(timerAnimation), userInfo: nil, repeats: true) RunLoop.current.add(animateTimer!, forMode: RunLoopMode.commonModes) } // 添加动画 fileprivate func addAnimation(){ // 1.信号动画 self.firstSingleView.isHidden = false UIView.animate(withDuration: 1, animations: { self.firstSingleView.transform = self.firstSingleView.transform.scaledBy(x: 16, y: 16) self.firstSingleView.alpha = 0 }, completion: { (completed) in self.firstSingleView.transform = CGAffineTransform.identity self.firstSingleView.alpha = 1 self.firstSingleView.isHidden = true }) let when = DispatchTime.now() + 0.3 DispatchQueue.main.asyncAfter(deadline: when, execute: { self.secondSingleView.isHidden = false UIView.animate(withDuration: 1, animations: { self.secondSingleView.transform = self.secondSingleView.transform.scaledBy(x: 16, y: 16) self.secondSingleView.alpha = 0 }, completion: { (complete) in self.secondSingleView.transform = CGAffineTransform.identity self.secondSingleView.alpha = 1 self.secondSingleView.isHidden = true }) }) // 2.耳朵动画 self.leftRabbitEar.layer.add(self.creatAnimation(right: false), forKey: "left") self.rightRabbitEar.layer.add(self.creatAnimation(right: true), forKey: "right") } // 生成keyframe动画 fileprivate func creatAnimation(right:Bool) -> CAKeyframeAnimation{ var delta:CGFloat = 1 if right { delta = -1 } let earAnimation = CAKeyframeAnimation(keyPath: "transform.rotation.z") earAnimation.values = [delta*CGFloat(Float.pi / 2),delta*CGFloat(Float.pi / 4),delta*CGFloat(Float.pi / 2),delta*CGFloat(Float.pi / 4),delta*CGFloat(Float.pi / 2)] earAnimation.keyTimes = [0,0.25,0.5,0.75,1] earAnimation.duration = 0.75 return earAnimation } // 刷新动画结束 清空状态 fileprivate func clearAnimation(){ self.animateTimer?.invalidate() self.animateTimer = nil leftRabbitEar.layer.removeAllAnimations() rightRabbitEar.layer.removeAllAnimations() firstSingleView.removeFromSuperview() secondSingleView.removeFromSuperview() gifImageView.stopAnimating() gifNoticeLabel.isHidden = true gifNoticeLabel.text = "正在加载.." gifImageView.center = CGPoint(x: rabbitEarMaskTopView.ysCenterX, y: 15) gifNoticeLabel.center = CGPoint(x: rabbitEarMaskTopView.ysCenterX, y: 35) } } //====================================================================== // MARK:- target action //====================================================================== extension YSRabbitFreshBaseViewController { @objc fileprivate func timerAnimation() { addAnimation() } } //========================================================================== // MARK:- 公开的方法 //========================================================================== extension YSRabbitFreshBaseViewController { // 外部必须重载这个方法来满足实现不同的布局的 collectionview 或者说是 tableview func setUpScrollView() -> UIScrollView { isinherit = false return UIScrollView() } // 结束刷新 func endRefresh(loadSuccess:Bool) { // 1.获取动画时长 var delaytime:Double = 0 if freshing { delaytime = 0.7 } let deadlineTime = DispatchTime.now() + delaytime // 2.添加一个延时动画 DispatchQueue.main.asyncAfter(deadline: deadlineTime) { // <1 成功还是失败 loadSuccess == true ? (self.gifNoticeLabel.text = "加载成功") : (self.gifNoticeLabel.text = "加载失败") // <2 处理一直拉了放再拉再放的情况 if !self.dragging { UIView.animate(withDuration: 0.2, animations: { self.contentScrollView?.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: kNavBarHeight + 50, right: 0) self.gifImageView.center = CGPoint(x: self.rabbitEarMaskTopView.ysCenterX, y: -40) self.gifNoticeLabel.center = CGPoint(x: self.rabbitEarMaskTopView.ysCenterX, y: -20) }, completion: { (completed) in self.clearAnimation() self.freshing = false }) } } } // 开始刷新 (子类重载这个方法,刷新的逻辑在这里实现) func startRefresh() { print("子控制器需要重载这个方法") } } //========================================================================== // MARK:- KVO //========================================================================== extension YSRabbitFreshBaseViewController { override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { // 1.判断offset漫步满足条件 let offsetY = contentScrollView!.contentOffset.y guard keyPath == "contentOffset" else {return} guard dragging else {return} // 2.移除动画timer if offsetY > -KfreshMaxHeight { self.clearAnimation() } // 3.耳朵旋转加位移(minheight 到 maxheight) let delta = (-offsetY - kfreshMinHeight)/(KfreshMaxHeight - kfreshMinHeight) let rota = CGFloat(Float.pi / 2)*delta if offsetY < -kfreshMinHeight && offsetY > -KfreshMaxHeight{ // <1.耳朵旋转 valueTransform(trans: (-offsetY - kfreshMinHeight), rota: rota) // <2.耳朵父控件位移 rabbitEarMaskView.frame = CGRect(x: 0, y: kNavBarHeight+(-offsetY - kfreshMinHeight), width: view.ysWidth, height: view.ysHeight) // <3.提示label位移加透明度变化 noticeLabel.text = "再用点力!" let noticeLabelDelta = (-offsetY - kfreshMinHeight) - 20 if noticeLabelDelta > 0 { noticeLabel.center = CGPoint(x: kScreenWidth/2, y: knoticelabelCenterY+noticeLabelDelta) noticeLabel.alpha = (-offsetY - kfreshMinHeight-20)/(KfreshMaxHeight - kfreshMinHeight-20) } } // 4.耳朵只位移(> maxheight) if offsetY <= -KfreshMaxHeight { valueTransform(trans: (-offsetY - kfreshMinHeight), rota: CGFloat(Float.pi / 2)) rabbitEarMaskView.frame = CGRect(x: 0, y: kNavBarHeight+(-offsetY - kfreshMinHeight), width: view.ysWidth, height: view.ysHeight) noticeLabel.text = "松手加载" if self.animateTimer == nil { setTimer() } } } } //============================================================================ // MARK:- scrollview delegate //============================================================================ extension YSRabbitFreshBaseViewController : UIScrollViewDelegate { func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { dragging = true } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { dragging = false // 1.移除动画 self.clearAnimation() // 2.没有超过最小高度 guard scrollView.contentOffset.y < -kfreshMinHeight else {return} // 3.没有到达需要fresh的高度的处理 var noFresh:Bool = true // 4.达到了需要刷新的状态 if scrollView.contentOffset.y < -KfreshMaxHeight { // if !freshing { // startRefresh() // } startRefresh() freshing = true noFresh = false gifImageView.startAnimating() gifNoticeLabel.isHidden = false } // 5.动画 DispatchQueue.main.async {// 经过测试这里不用异步加载动画的情况下会有抖动(之前写过的下拉刷新不用异步,具体不是很清楚。。为什么会抖动是因为你设置了contentInset之后contentOffset也会改变,然后EndDragging之后会有bounce效果这个效果需要contentOffset做动画) UIView.animate(withDuration: 0.25, animations: { // 1. self.noticeLabel.center = CGPoint(x: kScreenWidth/2, y: self.knoticelabelCenterY) self.noticeLabel.alpha = 0 // 2. self.rabbitEarMaskView.frame = CGRect(x: 0, y: kNavBarHeight, width: self.view.ysWidth, height:self.view.ysHeight) self.leftRabbitEar.transform = CGAffineTransform.identity self.rightRabbitEar.transform = CGAffineTransform.identity // 3. self.contentScrollView?.contentInset = UIEdgeInsets(top: self.kfreshMinHeight, left: 0, bottom: kNavBarHeight+50, right: 0) self.contentScrollView?.setContentOffset(CGPoint(x: 0, y: -self.kfreshMinHeight), animated: false) }, completion: { (complete) in if noFresh { self.endRefresh(loadSuccess: true) } }) } } } //====================================================================== // MARK:- 右滑返回的代理方法 //====================================================================== extension YSRabbitFreshBaseViewController: UIGestureRecognizerDelegate { func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { return true } }
mit
d7965bb567e252c801dbfe0c219c8082
38.232967
176
0.595037
4.685302
false
false
false
false
Jnosh/swift
test/IDE/print_clang_decls.swift
3
8216
// RUN: rm -rf %t // RUN: mkdir -p %t // XFAIL: linux // This file deliberately does not use %clang-importer-sdk for most RUN lines. // Instead, it generates custom overlay modules itself, and uses -I %t when it // wants to use them. // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/ObjectiveC.swift // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/CoreGraphics.swift // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/Foundation.swift // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -print-module -source-filename %s -module-to-print=ctypes -function-definitions=false -prefer-type-repr=true > %t.printed.txt // RUN: %FileCheck %s -check-prefix=TAG_DECLS_AND_TYPEDEFS -strict-whitespace < %t.printed.txt // RUN: %FileCheck %s -check-prefix=NEGATIVE -strict-whitespace < %t.printed.txt // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -print-module -source-filename %s -module-to-print=Foundation -function-definitions=false -prefer-type-repr=true > %t.printed.txt // RUN: %FileCheck %s -check-prefix=FOUNDATION -strict-whitespace < %t.printed.txt // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -print-module -source-filename %s -module-to-print=ctypes.bits -function-definitions=false -prefer-type-repr=true > %t.printed.txt // RUN: %FileCheck %s -check-prefix=CTYPESBITS -strict-whitespace < %t.printed.txt // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -print-module -source-filename %s -module-to-print=nullability -function-definitions=false -prefer-type-repr=true > %t.printed.txt // RUN: %FileCheck %s -check-prefix=CHECK-NULLABILITY -strict-whitespace < %t.printed.txt // TAG_DECLS_AND_TYPEDEFS: {{^}}struct FooStruct1 {{{$}} // TAG_DECLS_AND_TYPEDEFS: {{^}} var x: Int32{{$}} // TAG_DECLS_AND_TYPEDEFS: {{^}} var y: Double{{$}} // TAG_DECLS_AND_TYPEDEFS: {{^}} init(){{$}} // TAG_DECLS_AND_TYPEDEFS: {{^}} init(x: Int32, y: Double){{$}} // TAG_DECLS_AND_TYPEDEFS: {{^}}}{{$}} // TAG_DECLS_AND_TYPEDEFS: /*! // TAG_DECLS_AND_TYPEDEFS-NEXT: @keyword Foo2 // TAG_DECLS_AND_TYPEDEFS-NEXT: */ // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}}struct FooStruct2 {{{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} var x: Int32{{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} var y: Double{{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} init(){{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} init(x: Int32, y: Double){{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}}}{{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}}typealias FooStructTypedef1 = FooStruct2{{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}}struct FooStructTypedef2 {{{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} var x: Int32{{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} var y: Double{{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} init(){{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} init(x: Int32, y: Double){{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}}}{{$}} // TAG_DECLS_AND_TYPEDEFS: {{^}}struct FooStruct3 {{{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} var x: Int32{{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} var y: Double{{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} init(){{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} init(x: Int32, y: Double){{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}}}{{$}} // TAG_DECLS_AND_TYPEDEFS: {{^}}struct FooStruct4 {{{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} var x: Int32{{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} var y: Double{{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} init(){{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} init(x: Int32, y: Double){{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}}}{{$}} // TAG_DECLS_AND_TYPEDEFS: {{^}}struct FooStruct5 {{{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} var x: Int32{{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} var y: Double{{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} init(){{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} init(x: Int32, y: Double){{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}}}{{$}} // TAG_DECLS_AND_TYPEDEFS: {{^}}struct FooStruct6 {{{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} var x: Int32{{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} var y: Double{{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} init(){{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} init(x: Int32, y: Double){{$}} // TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}}}{{$}} // Skip through unavailable typedefs when importing types. // TAG_DECLS_AND_TYPEDEFS: @available(*, unavailable, message: "use double") // TAG_DECLS_AND_TYPEDEFS-NEXT: typealias real_t = Double // TAG_DECLS_AND_TYPEDEFS-NEXT: func realSin(_ value: Double) -> Double // NEGATIVE-NOT: typealias FooStructTypedef2 // FOUNDATION-LABEL: {{^}}/// Aaa. NSArray. Bbb.{{$}} // FOUNDATION-NEXT: {{^}}class NSArray : NSObject {{{$}} // FOUNDATION-NEXT: subscript(idx: Int) -> Any { get } // FOUNDATION-LABEL: {{^}}/// Aaa. NSRuncingMode. Bbb.{{$}} // FOUNDATION-NEXT: {{^}}enum NSRuncingMode : UInt {{{$}} // FOUNDATION-NEXT: {{^}} init?(rawValue: UInt){{$}} // FOUNDATION-NEXT: {{^}} var rawValue: UInt { get }{{$}} // FOUNDATION-NEXT: {{^}} case mince{{$}} // FOUNDATION-NEXT: {{^}} @available(swift, obsoleted: 3, renamed: "mince"){{$}} // FOUNDATION-NEXT: {{^}} static var Mince: NSRuncingMode { get }{{$}} // FOUNDATION-NEXT: {{^}} case quince{{$}} // FOUNDATION-NEXT: {{^}} @available(swift, obsoleted: 3, renamed: "quince"){{$}} // FOUNDATION-NEXT: {{^}} static var Quince: NSRuncingMode { get }{{$}} // FOUNDATION-NEXT: {{^}}}{{$}} // FOUNDATION-LABEL: {{^}}/// Aaa. NSRuncingOptions. Bbb.{{$}} // FOUNDATION-NEXT: {{^}}struct NSRuncingOptions : OptionSet {{{$}} // FOUNDATION-NEXT: {{^}} init(rawValue: UInt){{$}} // FOUNDATION-NEXT: {{^}} let rawValue: UInt{{$}} // FOUNDATION-NEXT: {{^}} typealias RawValue = UInt // FOUNDATION-NEXT: {{^}} typealias Element = NSRuncingOptions // FOUNDATION-NEXT: {{^}} @available(*, unavailable, message: "use [] to construct an empty option set"){{$}} // FOUNDATION-NEXT: {{^}} static var none: NSRuncingOptions { get }{{$}} // FOUNDATION-NEXT: {{^}} @available(*, unavailable, message: "use [] to construct an empty option set"){{$}} // FOUNDATION-NEXT: {{^}} @available(swift, obsoleted: 3, renamed: "none"){{$}} // FOUNDATION-NEXT: {{^}} static var None: NSRuncingOptions { get } // FOUNDATION-NEXT: {{^}} static var enableMince: NSRuncingOptions { get }{{$}} // FOUNDATION-NEXT: {{^}} @available(swift, obsoleted: 3, renamed: "enableMince"){{$}} // FOUNDATION-NEXT: {{^}} static var EnableMince: NSRuncingOptions { get }{{$}} // FOUNDATION-NEXT: {{^}} static var enableQuince: NSRuncingOptions { get }{{$}} // FOUNDATION-NEXT: {{^}} @available(swift, obsoleted: 3, renamed: "enableQuince"){{$}} // FOUNDATION-NEXT: {{^}} static var EnableQuince: NSRuncingOptions { get }{{$}} // FOUNDATION-NEXT: {{^}}}{{$}} // FOUNDATION-LABEL: {{^}}/// Unavailable Global Functions{{$}} // FOUNDATION-NEXT: @available(*, unavailable, message: "Zone-based memory management is unavailable") // FOUNDATION-NEXT: NSSetZoneName(_ zone: NSZone, _ name: String) // CTYPESBITS-NOT: FooStruct1 // CTYPESBITS: {{^}}typealias DWORD = Int32{{$}} // CTYPESBITS-NEXT: {{^}}var MY_INT: Int32 { get }{{$}} // CTYPESBITS-NOT: FooStruct1 // CHECK-NULLABILITY: func getId1() -> Any? // CHECK-NULLABILITY: var global_id: AnyObject? // CHECK-NULLABILITY: class SomeClass { // CHECK-NULLABILITY: class func methodA(_ obj: SomeClass?) -> Any{{$}} // CHECK-NULLABILITY: func methodA(_ obj: SomeClass?) -> Any{{$}} // CHECK-NULLABILITY: class func methodB(_ block: ((Int32, Int32) -> Int32)? = nil) -> Any{{$}} // CHECK-NULLABILITY: func methodB(_ block: ((Int32, Int32) -> Int32)? = nil) -> Any{{$}} // CHECK-NULLABILITY: func methodC() -> Any? // CHECK-NULLABILITY: var property: Any? // CHECK-NULLABILITY: func stringMethod() -> String{{$}} // CHECK-NULLABILITY: func optArrayMethod() -> [Any]? // CHECK-NULLABILITY: } // CHECK-NULLABILITY: func compare_classes(_ sc1: SomeClass, _ sc2: SomeClass, _ sc3: SomeClass!)
apache-2.0
581f1a5dc6aebe3eef5fdd054eed779e
56.454545
215
0.638389
3.268099
false
false
false
false
twobitlabs/TBLCategories
Swift Extensions/UIView+TBL.swift
1
1475
import UIKit @objc public extension UIView { var visible: Bool { get { return !isHidden } set { isHidden = !newValue } } func top() -> CGFloat { return frame.origin.y } func bottom() -> CGFloat { return frame.origin.y + frame.size.height } func left() -> CGFloat { return frame.origin.x } func right() -> CGFloat { return frame.origin.x + frame.size.width } func height() -> CGFloat { return frame.size.height } func width() -> CGFloat { return frame.size.width } func roundCorners() { roundCorners(.allCorners) } func roundCorners(_ corners: UIRectCorner) { roundCorners(corners, withRadius:8) } /** Note only works for .allCorners, or if view has a native size. If view is sized by autolayout, bounds will be 0. */ func roundCorners(_ corners: UIRectCorner, withRadius radius: CGFloat) { if (corners == .allCorners) { self.layer.cornerRadius = radius; } else { let roundedPath = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius)) let maskLayer = CAShapeLayer() maskLayer.path = roundedPath.cgPath self.layer.mask = maskLayer } clipsToBounds = true } }
mit
ce3b46b8c5e08de2101b516baaabdb28
23.180328
148
0.558644
4.788961
false
false
false
false
coach-plus/ios
Pods/RxSwift/RxSwift/Observables/Sample.swift
6
4081
// // Sample.swift // RxSwift // // Created by Krunoslav Zaher on 5/1/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // extension ObservableType { /** Samples the source observable sequence using a sampler observable sequence producing sampling ticks. Upon each sampling tick, the latest element (if any) in the source sequence during the last sampling interval is sent to the resulting sequence. **In case there were no new elements between sampler ticks, no element is sent to the resulting sequence.** - seealso: [sample operator on reactivex.io](http://reactivex.io/documentation/operators/sample.html) - parameter sampler: Sampling tick sequence. - returns: Sampled observable sequence. */ public func sample<Source: ObservableType>(_ sampler: Source) -> Observable<Element> { return Sample(source: self.asObservable(), sampler: sampler.asObservable()) } } final private class SamplerSink<Observer: ObserverType, SampleType> : ObserverType , LockOwnerType , SynchronizedOnType { typealias Element = SampleType typealias Parent = SampleSequenceSink<Observer, SampleType> private let _parent: Parent var _lock: RecursiveLock { return self._parent._lock } init(parent: Parent) { self._parent = parent } func on(_ event: Event<Element>) { self.synchronizedOn(event) } func _synchronized_on(_ event: Event<Element>) { switch event { case .next, .completed: if let element = _parent._element { self._parent._element = nil self._parent.forwardOn(.next(element)) } if self._parent._atEnd { self._parent.forwardOn(.completed) self._parent.dispose() } case .error(let e): self._parent.forwardOn(.error(e)) self._parent.dispose() } } } final private class SampleSequenceSink<Observer: ObserverType, SampleType> : Sink<Observer> , ObserverType , LockOwnerType , SynchronizedOnType { typealias Element = Observer.Element typealias Parent = Sample<Element, SampleType> private let _parent: Parent let _lock = RecursiveLock() // state fileprivate var _element = nil as Element? fileprivate var _atEnd = false private let _sourceSubscription = SingleAssignmentDisposable() init(parent: Parent, observer: Observer, cancel: Cancelable) { self._parent = parent super.init(observer: observer, cancel: cancel) } func run() -> Disposable { self._sourceSubscription.setDisposable(self._parent._source.subscribe(self)) let samplerSubscription = self._parent._sampler.subscribe(SamplerSink(parent: self)) return Disposables.create(_sourceSubscription, samplerSubscription) } func on(_ event: Event<Element>) { self.synchronizedOn(event) } func _synchronized_on(_ event: Event<Element>) { switch event { case .next(let element): self._element = element case .error: self.forwardOn(event) self.dispose() case .completed: self._atEnd = true self._sourceSubscription.dispose() } } } final private class Sample<Element, SampleType>: Producer<Element> { fileprivate let _source: Observable<Element> fileprivate let _sampler: Observable<SampleType> init(source: Observable<Element>, sampler: Observable<SampleType>) { self._source = source self._sampler = sampler } override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { let sink = SampleSequenceSink(parent: self, observer: observer, cancel: cancel) let subscription = sink.run() return (sink: sink, subscription: subscription) } }
mit
3b322a961e031dac50efee6a30ee70c7
29.676692
171
0.63799
4.892086
false
false
false
false
maitruonghcmus/QuickChat
QuickChat/ViewControllers/ConversVC.swift
1
10857
import UIKit import Firebase import AudioToolbox import UserNotifications class ConversVC: UITableViewController, UISearchBarDelegate { //MARK: *** Variable var items = [Conversation]() var selectedUser: User? var filtered:[Conversation] = [] var searchActive : Bool = false // permission push notification var allowPush : Bool = false let requestIdentifier = "PushRequest" let USERID = "userid" let requestImageIdentifier = "PushImageRequest" //MARK: *** UI Elements @IBOutlet weak var btnEdit: UIBarButtonItem! @IBOutlet weak var searchBar: UISearchBar! func setLanguague(){ DispatchQueue.main.async { self.navigationItem.title = MultiLanguague.messageItem } } //MARK: *** Custom Functions //Download all conversation func fetchData() { Conversation.showConversations { (conversations) in if Other.useTouchID == true{ self.items = conversations.filter{$0.locked == false} } else { self.items = conversations } self.items.sort{ $0.lastMessage.timestamp > $1.lastMessage.timestamp } self.filtered = self.items DispatchQueue.main.async { self.tableView.reloadData() for conversation in self.items { if conversation.lastMessage.isRead == false { self.playSound() } let state = UIApplication.shared.applicationState if state == .background { if Other.useNotification == true && conversation.locked == false && conversation.lastMessage.isRead == false && conversation.lastMessage.owner == .sender { self.pushNotification(conv: conversation) } } else if state == .active { } } } } if Other.useNotification == false { UIApplication.shared.applicationIconBadgeNumber = 0 } } //Shows Chat viewcontroller with given user func pushToUserMesssages(notification: NSNotification) { if let user = notification.userInfo?["user"] as? User { self.selectedUser = user self.performSegue(withIdentifier: "segue", sender: self) } } //Play sound when give a new message func playSound() { var soundURL: NSURL? var soundID:SystemSoundID = 0 let filePath = Bundle.main.path(forResource: "newMessage", ofType: "wav") soundURL = NSURL(fileURLWithPath: filePath!) AudioServicesCreateSystemSoundID(soundURL!, &soundID) AudioServicesPlaySystemSound(soundID) } func showEditing() { if(self.tableView.isEditing == true) { self.tableView.isEditing = false self.navigationItem.rightBarButtonItem?.title = "Done" } else { self.tableView.isEditing = true self.navigationItem.rightBarButtonItem?.title = "Edit" } } //MARK: *** push notification func pushNotification(conv: Conversation) { let content = UNMutableNotificationContent() content.title = "New message" content.subtitle = "From \(conv.user.name)" switch conv.lastMessage.type { case .text: let message = conv.lastMessage.content as! String content.body = message case .location: content.body = "Location" default: content.body = "Add new image" //To Present image in notification let url = URL.init(string: conv.lastMessage.content as! String) do { let attachment = try UNNotificationAttachment(identifier: requestImageIdentifier, url: url!, options: nil) content.attachments = [attachment] } catch { print("attachment not found.") } } content.badge = 1 content.userInfo = [USERID:conv.user.id] let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false) let request = UNNotificationRequest(identifier: requestIdentifier, content: content, trigger: trigger) UNUserNotificationCenter.current().add(request, withCompletionHandler: nil) } //MARK: *** UI Events //MARK: *** View override func viewDidLoad() { super.viewDidLoad() self.fetchData() searchBar.delegate = self // let leftBarButton = UIBarButtonItem(title: "Edit", style: UIBarButtonItemStyle.plain, target: self, action: Selector(("showEditing:"))) // self.navigationItem.leftBarButtonItem = leftBarButton // add permission push notification } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewWillAppear(_ animated: Bool) { self.setLanguague() super.viewWillAppear(animated) if allowPush == true { } if let selectionIndexPath = self.tableView.indexPathForSelectedRow { self.tableView.deselectRow(at: selectionIndexPath, animated: animated) } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "NewSegue" { let vc = segue.destination as! ChatVC vc.currentUser = self.selectedUser } } //MARK: *** Table View override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.filtered.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ConversCell", for: indexPath) as! ConversCell if self.filtered.count > 0{ let currentItem = filtered[indexPath.row] cell.clearCellData() cell.profilePic.image = currentItem.user.profilePic cell.nameLabel.text = currentItem.user.name switch currentItem.lastMessage.type { case .text: let message = currentItem.lastMessage.content as! String cell.messageLabel.text = message case .location: cell.messageLabel.text = "Location" default: cell.messageLabel.text = "Media" } let messageDate = Date.init(timeIntervalSince1970: TimeInterval(currentItem.lastMessage.timestamp)) let dataformatter = DateFormatter.init() dataformatter.timeStyle = .short let date = dataformatter.string(from: messageDate) cell.timeLabel.text = date if currentItem.lastMessage.owner == .sender && currentItem.lastMessage.isRead == false { cell.nameLabel.font = UIFont(name:"AvenirNext-DemiBold", size: 17.0) cell.messageLabel.font = UIFont(name:"AvenirNext-DemiBold", size: 14.0) cell.timeLabel.font = UIFont(name:"AvenirNext-DemiBold", size: 13.0) cell.profilePic.layer.borderColor = GlobalVariables.blue.cgColor cell.messageLabel.textColor = GlobalVariables.blue } } return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if self.filtered.count > 0 { self.selectedUser = self.filtered[indexPath.row].user let currentItem = filtered[indexPath.row] if currentItem.lastMessage.isRead == false { UIApplication.shared.applicationIconBadgeNumber -= 1 } self.performSegue(withIdentifier: "NewSegue", sender: self) } } // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source if self.filtered.count > 0 { self.selectedUser = self.filtered[indexPath.row].user let currentItem = filtered[indexPath.row] Conversation.delete(conv: currentItem, completion: {(ok) in if ok == true { UIApplication.shared.applicationIconBadgeNumber -= 1 self.filtered.remove(at: indexPath.row) self.tableView.deleteRows(at: [indexPath], with: .automatic) } else { let alertVC = UIAlertController(title: "Fail", message: "Please try again", preferredStyle: .alert) let okAction = UIAlertAction(title: "Ok", style: .default, handler: nil) alertVC.addAction(okAction) DispatchQueue.main.async() { () -> Void in self.present(alertVC, animated: true, completion: nil) } } }) } } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } //MARK: *** Search Bar func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { searchActive = true } func searchBarTextDidEndEditing(_ searchBar: UISearchBar) { searchActive = false } func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { searchActive = false } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { searchActive = false } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { if searchText != "" { filtered = items.filter { $0.user.name.lowercased().contains(searchText.lowercased()) } searchActive = true } else { filtered = items searchActive = false } self.tableView.reloadData() } }
mit
a98bffb784c8425e2e4196dd771de9fb
36.697917
179
0.578889
5.590628
false
false
false
false
zjzsliyang/FoodToday
FoodToday/ReportsViewController.swift
1
1112
// // FirstViewController.swift // FoodToday // // Created by Yang on 20/09/2016. // Copyright © 2016 Yang Li. All rights reserved. // import UIKit class ReportsViewController: UIViewController { @IBOutlet weak var dessertView: UIView! @IBOutlet weak var fruitView: UIView! @IBOutlet weak var lunchView: UIView! @IBOutlet weak var dinnerView: UIView! override func viewDidLoad() { super.viewDidLoad() dessertView.layer.cornerRadius = 10 fruitView.layer.cornerRadius = 10 lunchView.layer.cornerRadius = 10 dinnerView.layer.cornerRadius = 10 dessertView.backgroundColor = UIColor(red: 74 / 255, green: 242 / 255, blue: 161 / 255, alpha: 1) fruitView.backgroundColor = UIColor(red: 247 / 255, green: 138 / 255, blue: 224 / 255, alpha: 1) lunchView.backgroundColor = UIColor(red: 92 / 255, green: 201 / 255, blue: 245 / 255, alpha: 1) dinnerView.backgroundColor = UIColor(red: 176 / 255, green: 245 / 255, blue: 102 / 255, alpha: 1) dessertView.alpha = 0.8 fruitView.alpha = 0.8 lunchView.alpha = 0.8 dinnerView.alpha = 0.8 } }
mit
c5a10a515672db03834040055da44e7e
29.861111
101
0.682268
3.618893
false
false
false
false
ATFinke-Productions/Steppy-2
SwiftSteppy/Helpers/STPYHKManager.swift
1
17030
// // STPYHKManager.swift // SwiftSteppy // // Created by Andrew Finke on 1/10/15. // Copyright (c) 2015 Andrew Finke. All rights reserved. // import UIKit import HealthKit protocol STPYHKManagerProtocol { func loadingProgressUpdated(progress : String) } class STPYHKManager: NSObject { class var sharedInstance : STPYHKManager { struct Static { static let instance : STPYHKManager = STPYHKManager() } return Static.instance } let gkHelper = STPYGCHelper() let cmHelper = STPYCMHelper() let hkStore : HKHealthStore = HKHealthStore() let stepSampleType = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount) let distanceSampleType = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDistanceWalkingRunning) var stepCountData = [String:[String:Int]]() var distanceData = [String:Double]() var distanceDayData = [String:Double]() var totalSteps = 0 var weeksOfData = 0 var graphEqualizer = 1 var totalQueries = 0 var completedQueries = 0 var lastDate : NSDate? var delegate : STPYHKManagerProtocol? var dataFinalized : (((NSError!) -> Void)!) //MARK: HealthKit Access /** Detects if the app had access to necessary HealthKit data */ func hasAccess(completion: ((access : Bool) -> Void)!) { lastDateQuery(true) { (date) -> Void in if let date = date { self.lastDateQuery(false) { (date) -> Void in if let date = date { self.cmHelper.pedometerDataForToday({ (steps, distance, date) -> Void in //To get inital access }) completion(access: true) } else { completion(access: false) } self.completedQueries++ } } else { completion(access: false) } } } /** Shows an alert for having no HealthKit data :param: viewController The view controller to present the alert view controller from */ func showDataAlert(viewController : UIViewController) { let alertController = UIAlertController(title: NSLocalizedString("No Data Title", comment: ""), message: NSLocalizedString("No Data Message", comment: ""), preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: NSLocalizedString("Shared GC Error Button", comment: ""), style: UIAlertActionStyle.Default, handler: nil)) viewController.presentViewController(alertController, animated: true, completion: nil) } //MARK: Starting And Ending Data Process /** Queries the HealthKit data */ func queryData(completion: ((NSError!) -> Void)!) { dataFinalized = completion loadData() completedQueries = 0 totalQueries = 0 lastDateQuery(true) { (date) -> Void in var date = date if let lastDate = self.lastDate { date = lastDate } if let date = date { self.buildDataStoreWithLastDataDate(date) self.loadDistanceDataWithLastDataDate(date) self.loadStepDataWithLastDataDate(date) self.lastDate = date } else { completion(NSError(domain: "com.atfinkeproductions.SwiftSteppy", code: 101, userInfo: nil)) } self.completedQueries++ } getTotalSteps { (steps, error) -> Void in if error == nil { self.totalSteps = Int(steps) } } NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: "finalizeData:", userInfo: nil, repeats: true) } /** Finalizes the data for display and processing */ func finalizeData(timer : NSTimer) { if !isDataReady() { if totalQueries < 2 { delegate?.loadingProgressUpdated(STPYFormatter.sharedInstance.percentString(0)) } else { delegate?.loadingProgressUpdated(STPYFormatter.sharedInstance.percentString(Double(completedQueries) / Double(totalQueries))) } return } timer.invalidate() cmHelper.pedometerDataForToday { (steps, distance, date) -> Void in self.graphEqualizer = max(self.graphEqualizer, steps) self.adjustCurrentDataForPedometerData(steps, distance: distance, date: date) self.delegate?.loadingProgressUpdated(STPYFormatter.sharedInstance.percentString(1)) self.saveData() self.dataFinalized(nil) } } /** Adjusts the HealthKit data with the lastest Pedometer data which is more up to date :param: steps The step count :param: steps The distance :param: steps The date */ func adjustCurrentDataForPedometerData(steps : Int, distance : Double, date : NSDate) { let hack = stepCountData // Sometimes swift forgets when something is mutable. This fixes it. SUPER annoying. let hack1 = distanceDayData // Sometimes swift forgets when something is mutable. This fixes it. SUPER annoying. let hack2 = distanceData // Sometimes swift forgets when something is mutable. This fixes it. SUPER annoying. if let week = stepCountData[date.beginningOfWeek().key()] { if let currentDay = week[date.key()] { if currentDay < steps { totalSteps = max(totalSteps, totalSteps - currentDay + steps) stepCountData[date.beginningOfWeek().key()]![date.key()] = steps self.graphEqualizer = max(self.graphEqualizer, steps) let oldDistance = distanceDayData[date.key()]! distanceDayData[date.key()] = distance let oldWeekDistance = distanceData[date.beginningOfWeek().key()]! distanceData[date.beginningOfWeek().key()] = oldWeekDistance - oldDistance + distance } } } } /** Detects if still waiting for queries */ func isDataReady() -> Bool { return completedQueries >= totalQueries && distanceData.count > 0 } //MARK: Getting Distance Data /** Loads the distance data since the date :param: lastDate The last date to get data from */ func loadDistanceDataWithLastDataDate(lastDate : NSDate) { let date = NSDate() var start = date.beginningOfWeek() var end = date while lastDate.timeIntervalSinceDate(start) <= 0 { loadDistanceData(start, end, forWeek: true) end = start.endOfPreviousDay() start = end.beginningOfWeek() } } /** Loads the distance data for a specifc week or day :param: start The start of the time period :param: end The end of the time period */ func loadDistanceData(start : NSDate,_ end : NSDate, forWeek : Bool) { statsQuery(start, end, steps: false) { (result, error) -> Void in if let sumQuantity = result?.sumQuantity() { let key = start.key() let value = sumQuantity.doubleValueForUnit(HKUnit.meterUnit()) if forWeek == true { let hack = self.distanceData // Sometimes swift forgets when something is mutable. This fixes it. SUPER annoying. self.distanceData[key] = value } else { let hack = self.distanceDayData // Sometimes swift forgets when something is mutable. This fixes it. SUPER annoying. self.distanceDayData[key] = value } } self.completedQueries++ } } //MARK: Getting Step Counts /** Loads the step data since the date :param: lastDate The last date to get data from */ func loadStepDataWithLastDataDate(lastDate : NSDate) { let date = NSDate() var start = date.beginningOfDay() var end = date while lastDate.timeIntervalSinceDate(start) < 0 { loadStepDataForDay(start, end) loadDistanceData(start, end, forWeek: false) end = start.endOfPreviousDay() start = end.beginningOfDay() } } /** Loads the step data for a specifc day :param: start The start of the day :param: end The end of the day */ func loadStepDataForDay(start : NSDate,_ end : NSDate) { let key = start.key() let weekKey = start.beginningOfWeekKey() statsQuery(start, end, steps: true) { (result, error) -> Void in let hack = self.stepCountData // Sometimes swift forgets when something is mutable. This fixes it. SUPER annoying. if let sumQuantity = result?.sumQuantity() { let steps = Int(sumQuantity.doubleValueForUnit(HKUnit.countUnit())) if self.stepCountData[weekKey] != nil { self.stepCountData[weekKey]![key] = steps } self.graphEqualizer = max(self.graphEqualizer, steps) } else { if self.stepCountData[weekKey]![key] == nil { self.stepCountData[weekKey]![key] = 0 } } self.completedQueries++ } } /** Counts the steps for a set of week data :param: data The week data :returns: The number of steps */ func getWeekStepsFromData(data : [String:Int]) -> Int { var steps = 0 for day in data.keys { steps += data[day]! } return steps } /** Gets the total number of steps */ func getTotalSteps(completion: ((Double!, NSError!) -> Void)!) { statsQuery(NSDate.distantPast() as! NSDate, NSDate(), steps: true) { (result, error) -> Void in if let sumQuantity = result?.sumQuantity() { completion(sumQuantity.doubleValueForUnit(HKUnit.countUnit()),nil) } else { completion(0,error) } self.completedQueries++ } } /** Generic stats query :param: start The start date :param: end The end date :param: steps Bool if is step query */ func statsQuery(start : NSDate,_ end : NSDate, steps : Bool, completion: (result : HKStatistics!, error : NSError!) -> Void) { totalQueries++ let quantityType = steps ? stepSampleType : distanceSampleType let query = HKStatisticsQuery(quantityType: quantityType, quantitySamplePredicate: HKQuery.predicateForSamplesWithStartDate(start, endDate:end, options: .None), options: .CumulativeSum) { (query, result, error) -> Void in completion(result: result, error: error) } hkStore.executeQuery(query) } /** Generic sample query :param: steps Bool if is step query */ func lastDateQuery(steps : Bool, completion: (date : NSDate?) -> Void) { totalQueries++ let quantityType = steps ? stepSampleType : distanceSampleType let sampleQuery = HKSampleQuery(sampleType: quantityType, predicate: HKQuery.predicateForSamplesWithStartDate(NSDate.distantPast() as! NSDate, endDate:NSDate(), options: .None), limit: 1, sortDescriptors: [NSSortDescriptor(key:HKSampleSortIdentifierStartDate, ascending: true)]) { (sampleQuery : HKSampleQuery!, results : [AnyObject]?, error : NSError?) -> Void in if let results = results { if let firstSample = results.first as? HKQuantitySample { completion(date: firstSample.startDate.beginningOfWeek()) } else { completion(date: nil) } } else { completion(date: nil) } } hkStore.executeQuery(sampleQuery) } //MARK: Building the data store /** Builds the default data values and keys from a date :param: lastDate The last date to build the data */ func buildDataStoreWithLastDataDate(lastDate : NSDate) { let date = NSDate() var start = date.beginningOfWeek() var end = date while lastDate.timeIntervalSinceDate(start) <= 0 { let key = start.key() let hack = stepCountData // Sometimes swift forgets when something is mutable. This fixes it. SUPER annoying. if stepCountData[key] == nil { stepCountData[key] = [String:Int]() } buildDataStoreForWeekStart(start) let hack1 = distanceData // Sometimes swift forgets when something is mutable. This fixes it. SUPER annoying. if distanceData[key] == nil { distanceData[key] = 0.0 } end = start.endOfPreviousDay() start = end.beginningOfWeek() } } /** Builds the default data values and keys for a specific week :param: lastDate The last date of the week */ func buildDataStoreForWeekStart(lastDate : NSDate) { var date = lastDate for var day = 1; day < 8; day++ { let hack = distanceDayData // Sometimes swift forgets when something is mutable. This fixes it. SUPER annoying. let hack1 = stepCountData // Sometimes swift forgets when something is mutable. This fixes it. SUPER annoying. if distanceDayData[date.key()] == nil { distanceDayData[date.key()] = 0.0 } if stepCountData[lastDate.key()]![date.key()] == nil { stepCountData[lastDate.key()]![date.key()] = 0 } date = date.nextDay() } } //MARK: Saving, Storing, and Moving Data /** Saves the latest data */ func saveData() { weeksOfData = distanceData.count STPYDataHelper.saveDataForKey(graphEqualizer, key: "graphEqualizer") STPYDataHelper.saveDataForKey(distanceData, key: "distanceData") STPYDataHelper.saveDataForKey(distanceDayData, key: "distanceDayData") STPYDataHelper.saveDataForKey(stepCountData, key: "stepCountData") STPYDataHelper.saveDataForKey(NSDate(timeIntervalSinceNow: -200000), key: "lastDate") saveDataForExtension() if STPYDataHelper.key("GKEnabled") { self.sendGKData() } } /** Loads previously saved data */ func loadData() { if let object = STPYDataHelper.getObjectForKey("lastDate") as? NSDate { lastDate = object.beginningOfDay() } if let object = STPYDataHelper.getObjectForKey("graphEqualizer") as? Int { graphEqualizer = object } if let object = STPYDataHelper.getObjectForKey("distanceData") as? [String:Double] { distanceData = object } if let object = STPYDataHelper.getObjectForKey("distanceDayData") as? [String:Double] { distanceDayData = object } if let object = STPYDataHelper.getObjectForKey("stepCountData") as? [String:[String:Int]] { stepCountData = object } } /** Saves the user's step data for the extensions */ func saveDataForExtension() { if let defaults = NSUserDefaults(suiteName: "group.com.atfinkeproductions.SwiftSteppy") { let date = NSDate() let weekKey = date.beginningOfWeekKey() if let weekCountData = stepCountData[weekKey] { if let todaySteps = weekCountData[date.key()] { defaults.setObject(todaySteps as NSNumber, forKey: "T-Steps") } defaults.setObject(getWeekStepsFromData(weekCountData) as NSNumber, forKey: "W-Steps") defaults.setObject(weekCountData, forKey: "W-Data") } defaults.setObject((totalSteps as NSNumber), forKey: "A-Steps") defaults.synchronize() } } /** Sends the user's step data to Game Center */ func sendGKData() { if distanceData.count > 0 { let date = NSDate() let dayKey = date.beginningOfDay().key() let weekKey = date.beginningOfWeekKey() var daySteps = 0 var weekSteps = 0 if let weekData = stepCountData[weekKey] { if let data = weekData[dayKey] { daySteps = data } weekSteps = getWeekStepsFromData(weekData) } gkHelper.reportSteps(daySteps, weekSteps, totalSteps) } } }
mit
a04fadb3cfdb6e6387b52b117f837141
36.023913
372
0.585672
4.838068
false
false
false
false
Mqhong/IMSingularity_Swift
Pod/Classes/TargetUserInfo.swift
1
769
// // TargetUserInfo.swift // IMSingularity_Swift // // Created by apple on 3/18/16. // Copyright © 2016 apple. All rights reserved. // import UIKit public class TargetUserInfo: NSObject { public var chat_session_id:String? public var target_id:String? public var target_name:String? public var target_picture:String? func targetUserMethod(Dict dict:Dictionary<String,AnyObject>)->TargetUserInfo{ self.chat_session_id = dict["chat_session_id"] as? String self.target_id = dict["target_id"] as? String self.target_name = dict["target_name"] as? String let target_picture = dict["target_picture"]! self.target_picture = String(target_picture) return self } }
mit
0f812afaa8d8b63f33625462f2cb2ff6
25.482759
82
0.647135
3.859296
false
false
false
false
swifteroid/store
source/Test/Batch/Test.Batch.swift
1
1236
import CoreData import Store import Nimble internal class BatchTestCase: TestCase { internal func test() { let batch: Batch = Batch() var request: NSFetchRequest<NSManagedObject> = NSFetchRequest() let configuration: Configuration = Configuration(request: Request.Configuration(limit: 1, offset: 2, sort: [NSSortDescriptor(key: "foo", ascending: true)])) expect(request.fetchLimit).to(equal(0)) expect(request.fetchOffset).to(equal(0)) expect(request.sortDescriptors).to(beNil()) request = batch.prepare(request: request, configuration: configuration) expect(request.fetchLimit).to(equal(configuration.request!.limit)) expect(request.fetchOffset).to(equal(configuration.request!.offset)) expect(request.sortDescriptors).to(equal(configuration.request!.sort)) } } fileprivate struct Configuration: BatchRequestConfiguration { fileprivate var request: Request.Configuration? } fileprivate class Model: BatchConstructableModel, Batchable { typealias Batch = Store_Test.Batch public var exists: Bool { (Batch(models: []) as Batch).exist(models: [self]) } } fileprivate class Batch: Store.Batch<Model, Configuration> { }
mit
36671ce7093a3f07f15e6ebc7113eba5
33.333333
164
0.716019
4.494545
false
true
false
false
tinypass/piano-sdk-for-ios
PianoAPI/API/EmailConfirmationAPI.swift
1
1206
import Foundation @objc(PianoAPIEmailConfirmationAPI) public class EmailConfirmationAPI: NSObject { /// Check if user has confirmed email /// - Parameters: /// - aid: Application aid /// - userToken: User token /// - userProvider: User token provider /// - userRef: Encrypted user reference /// - callback: Operation callback @objc public func checkConfirmed( aid: String, userToken: String? = nil, userProvider: String? = nil, userRef: String? = nil, completion: @escaping (OptionalBool?, Error?) -> Void) { guard let client = PianoAPI.shared.client else { completion(nil, PianoAPIError("PianoAPI not initialized")) return } var params = [String:String]() params["aid"] = aid if let v = userToken { params["user_token"] = v } if let v = userProvider { params["user_provider"] = v } if let v = userRef { params["user_ref"] = v } client.request( path: "/api/v3/email/confirmation/check", method: PianoAPI.HttpMethod.from("GET"), params: params, completion: completion ) } }
apache-2.0
ad9db574dfc4b576a8838f1169d3138c
32.5
70
0.58126
4.40146
false
false
false
false
mathiasquintero/Pushie
Pushie/Classes/Grammar.swift
1
3225
// // Grammar.swift // Pods // // Created by Mathias Quintero on 7/10/16. // // import Foundation /// Full Grammar. Consists of a starting Variable public class Grammar<T> { /// Starting Variable. This is where you words will be parsed first. let startVariable: GrammarVariable<T> /** Initializes a new Grammar. - Parameters: - startVariable: Starting Variable for your Grammar. - Returns: An awesome Grammar. Obviously!. ;) */ public init(startVariable: GrammarVariable<T>) { self.startVariable = startVariable } /** Will translate the Grammar into a PDA - Parameters: - start: First Object assigned to the Accumulator of your PDA - Returns: PDA accepting the Language of the Grammar. */ public func automata(start: T) -> Pushie<T>? { let state = State<T>() let finalState = State<T>(final: true) let finalElement = StackElement(identifier: "final") var alreadyReachable = [startVariable] var index = 0 var variablesWithEpsilon = [GrammarVariable<T>]() while index < alreadyReachable.count { for rule in alreadyReachable[index].rules.rules { if let (h, tail) = rule.resolvesTo.match { if let head = h as? Regex { if head.expression != "" { state.when(String(alreadyReachable[index].hashValue)).on(head.expression).change(tail.map({ $0.id }).reverse()) } } else { state.when(String(alreadyReachable[index].hashValue)).change(rule.resolvesTo.map({ $0.id }).reverse()) } } let regex = rule.resolvesTo.flatMap({ $0 as? Regex }) for reg in regex { if reg.expression != "" { state.when(reg.expression).on(reg.expression).pop() } else { variablesWithEpsilon.append(alreadyReachable[index]) } } } let reachableFromCurrent = alreadyReachable[index].rules.rules.flatMap({ $0.resolvesTo.flatMap({ $0 as? GrammarVariable<T> })}) let reachableUnknown = reachableFromCurrent.filter({ !alreadyReachable.contains($0) }) alreadyReachable.appendContentsOf(reachableUnknown) index += 1 } for variable in variablesWithEpsilon { state.when(String(variable.hashValue)).pop() } state.when(finalElement).goTo(finalState) let result = Pushie(start: start, state: state, firstStackElement: finalElement) result.stack.push([StackElement(identifier: startVariable.id)]) return result } /** Will calculate the result of an input - Parameters: - start: Start value of the Accumulator - input: Input that has to be evaluated - Returns: nil when the input is invalid. Result of the evaluation when it's valid. */ public func handle(start: T, input: String) -> T? { return automata(start)?.handle(input) } }
mit
bfb726f05c28fed863aa182f4a82bfe6
34.450549
139
0.572093
4.633621
false
false
false
false
adow/AWebImage
AWebImage/AWebImage.swift
1
7037
// // AWebImage.swift // AWebImage // // Created by 秦 道平 on 16/6/1. // Copyright © 2016年 秦 道平. All rights reserved. // import Foundation import UIKit public typealias AWImageLoaderCallback = (UIImage,URL) -> () public typealias AWImageLoaderCallbackList = [AWImageLoaderCallback] private let emptyImage = UIImage() // MARK: - AWImageLoaderManager private let _sharedManager = AWImageLoaderManager() open class AWImageLoaderManager { /// 用来保存生成好图片 var fastCache : NSCache<NSString, AnyObject>! /// 回调列表 var fetchList:[String:AWImageLoaderCallbackList] = [:] /// 用于操作回调列表的队列 var fetchListOperationQueue:DispatchQueue = DispatchQueue(label: "adow.adimageloader.fetchlist_operation_queue", attributes: DispatchQueue.Attributes.concurrent) /// 用于继续图片编码的队列 var imageDecodeQueue : DispatchQueue = DispatchQueue(label: "adow.awimageloader.decode_queue", attributes: DispatchQueue.Attributes.concurrent) /// http 操作 var sessionConfiguration : URLSessionConfiguration! /// http 队列 var sessionQueue : OperationQueue! /// 共享单个 session lazy var defaultSession : URLSession! = URLSession(configuration: self.sessionConfiguration, delegate: nil, delegateQueue: self.sessionQueue) fileprivate init () { fastCache = NSCache() fastCache.totalCostLimit = 30 * 1024 * 1024 sessionQueue = OperationQueue() sessionQueue.maxConcurrentOperationCount = 6 sessionQueue.name = "adow.adimageloader.session" sessionConfiguration = URLSessionConfiguration.default sessionConfiguration.requestCachePolicy = .useProtocolCachePolicy sessionConfiguration.timeoutIntervalForRequest = 3 sessionConfiguration.urlCache = URLCache(memoryCapacity: 10 * 1024 * 1024, diskCapacity: 30 * 1024 * 1024, diskPath: "adow.adimageloader.urlcache") } open static var sharedManager : AWImageLoaderManager { return _sharedManager } } extension AWImageLoaderManager { func readFetch(_ key:String) -> AWImageLoaderCallbackList? { return fetchList[key] } func addFetch(_ key:String, callback:@escaping AWImageLoaderCallback) -> Bool { var skip = false let f_list = fetchList[key] if f_list != nil { skip = true } fetchListOperationQueue.sync(flags: .barrier, execute: { if var f_list = f_list { f_list.append(callback) self.fetchList[key] = f_list // NSLog("callback list:%d",f_list.count) } else { self.fetchList[key] = [callback,] } }) return skip } func removeFetch(_ key:String) { _ = fetchListOperationQueue.sync(flags: .barrier, execute: { self.fetchList.removeValue(forKey: key) }) } func clearFetch() { fetchListOperationQueue.async(flags: .barrier, execute: { self.fetchList.removeAll() }) } } extension AWImageLoaderManager { public func clearCache() { self.fastCache.removeAllObjects() self.sessionConfiguration.urlCache?.removeAllCachedResponses() } } // MARK: - AWImageLoader open class AWImageLoader : NSObject { var task : URLSessionTask? public override init() { super.init() } } extension AWImageLoader { public func cacheKeyFromUrl(url : URL, andImageProcess imageProcess : AWebImageProcess? = nil) -> String? { let path = url.absoluteString var cache_key = path if let _imageProcess = imageProcess { cache_key = "\(cache_key).\(_imageProcess.cacheKey)" } return cache_key } /// 获取已经处理号的图片 public func imageFromFastCache(cacheKey : String) -> UIImage? { return AWImageLoaderManager.sharedManager.fastCache.object(forKey: cacheKey as NSString) as? UIImage } public func downloadImage(url:URL, withImageProcess imageProcess : AWebImageProcess? = nil, callback : @escaping AWImageLoaderCallback){ guard let fetch_key = self.cacheKeyFromUrl(url: url as URL, andImageProcess: imageProcess) else { return } // debugPrint(fetch_key) if let cached_image = self.imageFromFastCache(cacheKey: fetch_key) { callback(cached_image, url) return } /// 用来将图片返回到所有的回调函数 let f_callback = { (image:UIImage) -> () in if let f_list = AWImageLoaderManager.sharedManager.readFetch(fetch_key) { AWImageLoaderManager.sharedManager.removeFetch(fetch_key) DispatchQueue.main.async { // DispatchQueue.concurrentPerform(iterations: f_list.count, execute: { (i) in // let f = f_list[i] // f(image,url) // }) for f in f_list { f(image,url) } } } } /// origin let skip = AWImageLoaderManager.sharedManager.addFetch(fetch_key, callback: callback) if skip { // NSLog("skip") return } /// request let session = AWImageLoaderManager.sharedManager.defaultSession let request = URLRequest(url: url) self.task = session?.dataTask(with: request, completionHandler: { (data, response, error) in if let error = error { NSLog("error:%@", error.localizedDescription) } /// no data guard let _data = data else { NSLog("no image:\(url.absoluteString)") f_callback(emptyImage) return } AWImageLoaderManager.sharedManager.imageDecodeQueue.async(execute: { // NSLog("origin:%@", url.absoluteString) let image = UIImage(data: _data) ?? emptyImage /// 图像处理 var output_image = image if let _imageProcess = imageProcess { output_image = _imageProcess.make(fromInputImage: image) ?? image } AWImageLoaderManager.sharedManager.fastCache.setObject(output_image, forKey: fetch_key as NSString) /// fastCache f_callback(output_image) return }) }) self.task?.resume() } } extension AWImageLoader { public func cancelTask() { guard let _task = self.task else { return } if _task.state == .running || _task.state == .running { _task.cancel() } } }
mit
66b95e7665cde7ccb0816ec315ef3e03
34.637306
165
0.584618
4.803073
false
true
false
false
newtonstudio/cordova-plugin-device
imgly-sdk-ios-master/imglyKit/Backend/Processing/Response Filters/IMGLYResponseFilter.swift
1
3217
// // IMGLYResponseFilter.swift // imglyKit // // Created by Carsten Przyluczky on 28/01/15. // Copyright (c) 2015 9elements GmbH. All rights reserved. // import Foundation #if os(iOS) import CoreImage #elseif os(OSX) import QuartzCore #endif @objc public protocol IMGLYFilterTypeProtocol { var filterType: IMGLYFilterType { get } } /** A base clase for all response filters. Response filters use a look-up-table to map colors around, and create cool effects. These tables are handed over as image that contains serveral combination of r, g, and b values. Tools like photoshop can be used to create filters, using the identity-image and apply the desired operations onto it. Afterwards the so filtered image may be used as response map, as it represents the response the filter should have. In order to use the filter, the response-image is tranfered into a color-cube-map, that then can be used as input for a 'CIColorCube' filter, provided by core-image. */ public class IMGLYResponseFilter: CIFilter, IMGLYFilterTypeProtocol { /// A CIImage object that serves as input for the filter. public var inputImage: CIImage? public var inputIntensity = NSNumber(float: 1) { didSet { colorCubeData = nil } } public let responseName: String /// Returns the according filter type of the response filter. public var filterType: IMGLYFilterType { return .None } private var _colorCubeData: NSData? private var colorCubeData: NSData? { get { if _colorCubeData == nil { _colorCubeData = LUTToNSDataConverter.colorCubeDataFromLUTNamed(self.responseName, interpolatedWithIdentityLUTNamed: "Identity", withIntensity: self.inputIntensity.floatValue, cacheIdentityLUT: true) } return _colorCubeData } set { _colorCubeData = newValue } } init(responseName: String) { self.responseName = responseName super.init() } required public init(coder aDecoder: NSCoder) { self.responseName = "" super.init(coder: aDecoder) } public override var outputImage: CIImage! { if inputImage == nil { return CIImage.emptyImage() } var outputImage: CIImage? autoreleasepool { if let colorCubeData = colorCubeData { var filter = CIFilter(name: "CIColorCube") filter.setValue(colorCubeData, forKey: "inputCubeData") filter.setValue(64, forKey: "inputCubeDimension") filter.setValue(inputImage, forKey: kCIInputImageKey) outputImage = filter.outputImage } else { outputImage = inputImage } } return outputImage } } extension IMGLYResponseFilter: NSCopying { public override func copyWithZone(zone: NSZone) -> AnyObject { let copy = super.copyWithZone(zone) as! IMGLYResponseFilter copy.inputImage = inputImage?.copyWithZone(zone) as? CIImage copy.inputIntensity = inputIntensity return copy } }
apache-2.0
1bb1cc1f10101626d2b76033a9ca5277
31.17
215
0.64843
4.703216
false
false
false
false
gabrielPeart/SimpleChat
SimpleChat/SwiftViewControllerExample/SwiftExampleViewController.swift
3
2009
// // SwiftExampleViewController.swift // SimpleChat // // Created by Logan Wright on 11/15/14. // Copyright (c) 2014 Logan Wright. All rights reserved. // import UIKit class SwiftExampleViewController: UIViewController, LGChatControllerDelegate { override func viewDidLoad() { super.viewDidLoad() } // func stylizeChatInput() { // LGChatInput.Appearance.backgroundColor = <#UIColor#> // LGChatInput.Appearance.includeBlur = <#Bool#> // LGChatInput.Appearance.textViewFont = <#UIFont#> // LGChatInput.Appearance.textViewTextColor = <#UIColor#> // LGChatInput.Appearance.tintColor = <#UIColor#> // LGChatInput.Appearance.textViewBackgroundColor = <#UIColor#> // } // func stylizeMessageCell() { // LGChatMessageCell.Appearance.font = <#UIFont#> // LGChatMessageCell.Appearance.opponentColor = <#UIColor#> // LGChatMessageCell.Appearance.userColor = <#UIColor#> // } // MARK: Launch Chat Controller func launchChatController() { let chatController = LGChatController() chatController.opponentImage = UIImage(named: "User") chatController.title = "Simple Chat" let helloWorld = LGChatMessage(content: "Hello World!", sentBy: .User) chatController.messages = [helloWorld] chatController.delegate = self self.navigationController?.pushViewController(chatController, animated: true) } // MARK: LGChatControllerDelegate func chatController(chatController: LGChatController, didAddNewMessage message: LGChatMessage) { println("Did Add Message: \(message.content)") } func shouldChatController(chatController: LGChatController, addMessage message: LGChatMessage) -> Bool { /* Use this space to prevent sending a message, or to alter a message. For example, you might want to hold a message until its successfully uploaded to a server. */ return true } }
mpl-2.0
4a733402e7f1d6cd6d32a500df218dd6
33.637931
167
0.673967
4.682984
false
false
false
false
shnhrrsn/ImagePalette
src/ColorCutQuantizer.swift
1
12820
// // ColorCutQuantizer.swift // ImagePalette // // Original created by Google/Android // Ported to Swift/iOS by Shaun Harrison // import Foundation import UIKit import SwiftPriorityQueue private let COMPONENT_RED = -3 private let COMPONENT_GREEN = -2 private let COMPONENT_BLUE = -1 private let BLACK_MAX_LIGHTNESS = CGFloat(0.05) private let WHITE_MIN_LIGHTNESS = CGFloat(0.95) private typealias VboxPriorityQueue = PriorityQueue<Vbox> internal final class ColorCutQuantizer { fileprivate var colors = [Int64]() fileprivate var colorPopulations = [Int64: Int64]() /** list of quantized colors */ private(set) var quantizedColors = [PaletteSwatch]() /** Factory-method to generate a ColorCutQuantizer from a UIImage. :param: image Image to extract the pixel data from :param: maxColors The maximum number of colors that should be in the result palette. */ internal static func from(image: UIImage, maxColors: Int) -> ColorCutQuantizer { let pixels = image.pixels return ColorCutQuantizer(colorHistogram: ColorHistogram(pixels: pixels), maxColors: maxColors) } /** :param: colorHistogram histogram representing an image’s pixel data :param maxColors The maximum number of colors that should be in the result palette. */ private init(colorHistogram: ColorHistogram, maxColors: Int) { let rawColorCount = colorHistogram.numberOfColors let rawColors = colorHistogram.colors let rawColorCounts = colorHistogram.colorCounts // First, lets pack the populations into a SparseIntArray so that they can be easily // retrieved without knowing a color’s index self.colorPopulations = Dictionary(minimumCapacity: rawColorCount) for i in 0 ..< rawColors.count { self.colorPopulations[rawColors[i]] = rawColorCounts[i] } // Now go through all of the colors and keep those which we do not want to ignore var validColorCount = 0 self.colors = [ ] self.colors.reserveCapacity(rawColorCount) for color in rawColors { guard !self.shouldIgnore(color: color) else { continue } self.colors.append(color) validColorCount += 1 } if validColorCount <= maxColors { // The image has fewer colors than the maximum requested, so just return the colors self.quantizedColors = [ ] for color in self.colors { guard let populations = self.colorPopulations[color] else { continue } self.quantizedColors.append(PaletteSwatch(color: HexColor.toUIColor(color), population: populations)) } } else { // We need use quantization to reduce the number of colors self.quantizedColors = self.quantizePixels(maxColorIndex: validColorCount - 1, maxColors: maxColors) } } private func quantizePixels(maxColorIndex: Int, maxColors: Int) -> [PaletteSwatch] { // Create the priority queue which is sorted by volume descending. This means we always // split the largest box in the queue var pq = PriorityQueue<Vbox>(ascending: false, startingValues: Array()) // final PriorityQueue<Vbox> pq = PriorityQueue<Vbox>(maxColors, VBOX_COMPARATOR_VOLUME) // To start, offer a box which contains all of the colors pq.push(Vbox(quantizer: self, lowerIndex: 0, upperIndex: maxColorIndex)) // Now go through the boxes, splitting them until we have reached maxColors or there are no // more boxes to split self.splitBoxes(queue: &pq, maxSize: maxColors) // Finally, return the average colors of the color boxes return generateAverageColors(vboxes: pq) } /** Iterate through the Queue, popping Vbox objects from the queue and splitting them. Once split, the new box and the remaining box are offered back to the queue. :param: queue Priority queue to poll for boxes :param: maxSize Maximum amount of boxes to split */ private func splitBoxes(queue: inout VboxPriorityQueue, maxSize: Int) { while queue.count < maxSize { guard let vbox = queue.pop(), vbox.canSplit else { // If we get here then there are no more boxes to split, so return return } // First split the box, and offer the result queue.push(vbox.splitBox()) // Then offer the box back queue.push(vbox) } } private func generateAverageColors(vboxes: VboxPriorityQueue) -> [PaletteSwatch] { var colors = [PaletteSwatch]() for vbox in vboxes { let color = vbox.averageColor guard !type(of: self).shouldIgnore(color: color) else { continue } // As we’re averaging a color box, we can still get colors which we do not want, so // we check again here colors.append(color) } return colors } /** Modify the significant octet in a packed color int. Allows sorting based on the value of a single color component. */ private func modifySignificantOctet(dimension: Int, lowerIndex: Int, upperIndex: Int) { switch (dimension) { case COMPONENT_RED: // Already in RGB, no need to do anything break case COMPONENT_GREEN: // We need to do a RGB to GRB swap, or vice-versa for i in lowerIndex ... upperIndex { let color = self.colors[i] self.colors[i] = HexColor.fromRGB((color >> 8) & 0xFF, green: (color >> 16) & 0xFF, blue: color & 0xFF) } case COMPONENT_BLUE: // We need to do a RGB to BGR swap, or vice-versa for i in lowerIndex ... upperIndex { let color = self.colors[i] self.colors[i] = HexColor.fromRGB(color & 0xFF, green: (color >> 8) & 0xFF, blue: (color >> 16) & 0xFF) } default: break } } private func shouldIgnore(color: Int64) -> Bool { return HexColor.toHSL(color).shouldIgnore } private static func shouldIgnore(color: PaletteSwatch) -> Bool { return color.hsl.shouldIgnore } } extension HSLColor { fileprivate var shouldIgnore: Bool { return self.isWhite || self.isBlack || self.isNearRedILine } /** :return: true if the color represents a color which is close to black. */ fileprivate var isBlack: Bool { return self.lightness <= BLACK_MAX_LIGHTNESS } /** :return: true if the color represents a color which is close to white. */ fileprivate var isWhite: Bool { return self.lightness >= WHITE_MIN_LIGHTNESS } /** :return: true if the color lies close to the red side of the I line. */ fileprivate var isNearRedILine: Bool { return self.hue >= 10.0 && self.hue <= 37.0 && self.saturation <= 0.82 } } /** Represents a tightly fitting box around a color space. */ private class Vbox: Hashable { // lower and upper index are inclusive private let lowerIndex: Int private var upperIndex: Int private var minRed = Int64(2) private var maxRed = Int64(2) private var minGreen = Int64(0) private var maxGreen = Int64(0) private var minBlue = Int64(2) private var maxBlue = Int64(2) private let quantizer: ColorCutQuantizer private static var ordinal = Int32(0) let hashValue = Int(OSAtomicIncrement32(&Vbox.ordinal)) init(quantizer: ColorCutQuantizer, lowerIndex: Int, upperIndex: Int) { self.quantizer = quantizer self.lowerIndex = lowerIndex self.upperIndex = upperIndex assert(self.lowerIndex <= self.upperIndex, "lowerIndex (\(self.lowerIndex)) can’t be > upperIndex (\(self.upperIndex))") self.fitBox() } var volume: Int64 { let red = Double((self.maxRed - self.minRed) + 1) let green = Double((self.maxGreen - self.minGreen) + 1) let blue = Double((self.maxBlue - self.minBlue) + 1) return Int64(red * green * blue) } var canSplit: Bool { return self.colorCount > 1 } var colorCount: Int { return self.upperIndex - self.lowerIndex + 1 } /** Recomputes the boundaries of this box to tightly fit the colors within the box. */ func fitBox() { // Reset the min and max to opposite values self.minRed = 0xFF self.minGreen = 0xFF self.minBlue = 0xFF self.maxRed = 0x0 self.maxGreen = 0x0 self.maxBlue = 0x0 for i in self.lowerIndex ... self.upperIndex { let color = HexColor.toRGB(self.quantizer.colors[i]) self.maxRed = max(self.maxRed, color.red) self.minRed = min(self.minRed, color.red) self.maxGreen = max(self.maxGreen, color.green) self.minGreen = min(self.minGreen, color.green) self.maxBlue = max(self.maxBlue, color.blue) self.minBlue = min(self.minBlue, color.blue) } } /** Split this color box at the mid-point along it’s longest dimension :return: the new ColorBox */ func splitBox() -> Vbox { guard self.canSplit else { fatalError("Can not split a box with only 1 color") } // find median along the longest dimension let splitPoint = self.findSplitPoint() assert(splitPoint + 1 <= self.upperIndex, "splitPoint (\(splitPoint + 1)) can’t be > upperIndex (\(self.upperIndex)), lowerIndex: \(self.lowerIndex)") let newBox = Vbox(quantizer: self.quantizer, lowerIndex: splitPoint + 1, upperIndex: self.upperIndex) // Now change this box’s upperIndex and recompute the color boundaries self.upperIndex = splitPoint assert(self.lowerIndex <= self.upperIndex, "lowerIndex (\(self.lowerIndex)) can’t be > upperIndex (\(self.upperIndex))") self.fitBox() return newBox } /** :return: the dimension which this box is largest in */ var longestColorDimension: Int { let redLength = self.maxRed - self.minRed let greenLength = self.maxGreen - self.minGreen let blueLength = self.maxBlue - self.minBlue if redLength >= greenLength && redLength >= blueLength { return COMPONENT_RED } else if greenLength >= redLength && greenLength >= blueLength { return COMPONENT_GREEN } else { return COMPONENT_BLUE } } /** Finds the point within this box’s lowerIndex and upperIndex index of where to split. This is calculated by finding the longest color dimension, and then sorting the sub-array based on that dimension value in each color. The colors are then iterated over until a color is found with at least the midpoint of the whole box’s dimension midpoint. :return: the index of the colors array to split from */ func findSplitPoint() -> Int { let longestDimension = self.longestColorDimension // Sort the colors in this box based on the longest color dimension. var sorted = self.quantizer.colors[self.lowerIndex...self.upperIndex] sorted.sort() if longestDimension == COMPONENT_RED { sorted.sort() { HexColor.red($0) < HexColor.red($1) } } else if longestDimension == COMPONENT_GREEN { sorted.sort() { HexColor.green($0) < HexColor.green($1) } } else { sorted.sort() { HexColor.blue($0) < HexColor.blue($1) } } self.quantizer.colors[self.lowerIndex...self.upperIndex] = sorted let dimensionMidPoint = self.midPoint(longestDimension) for i in self.lowerIndex ..< self.upperIndex { let color = self.quantizer.colors[i] switch (longestDimension) { case COMPONENT_RED where HexColor.red(color) >= dimensionMidPoint: return i case COMPONENT_GREEN where HexColor.green(color) >= dimensionMidPoint: return i case COMPONENT_BLUE where HexColor.blue(color) > dimensionMidPoint: return i default: continue } } return self.lowerIndex } /** * @return the average color of this box. */ var averageColor: PaletteSwatch { var redSum = Int64(0) var greenSum = Int64(0) var blueSum = Int64(0) var totalPopulation = Int64(0) for i in self.lowerIndex ... self.upperIndex { let color = self.quantizer.colors[i] guard let colorPopulation = self.quantizer.colorPopulations[color] else { continue } totalPopulation += colorPopulation redSum += colorPopulation * HexColor.red(color) greenSum += colorPopulation * HexColor.green(color) blueSum += colorPopulation * HexColor.blue(color) } let redAverage = Int64(round(Double(redSum) / Double(totalPopulation))) let greenAverage = Int64(round(Double(greenSum) / Double(totalPopulation))) let blueAverage = Int64(round(Double(blueSum) / Double(totalPopulation))) return PaletteSwatch(rgbColor: RGBColor(red: redAverage, green: greenAverage, blue: blueAverage, alpha: 255), population: totalPopulation) } /** * @return the midpoint of this box in the given {@code dimension} */ func midPoint(_ dimension: Int) -> Int64 { switch (dimension) { case COMPONENT_GREEN: return (self.minGreen + self.maxGreen) / Int64(2) case COMPONENT_BLUE: return (self.minBlue + self.maxBlue) / Int64(2) case COMPONENT_RED: return (self.minRed + self.maxRed) / Int64(2) default: return (self.minRed + self.maxRed) / Int64(2) } } } extension Vbox: Comparable { } private func ==(lhs: Vbox, rhs: Vbox) -> Bool { return lhs.hashValue == rhs.hashValue } private func <=(lhs: Vbox, rhs: Vbox) -> Bool { return lhs.volume <= rhs.volume } private func >=(lhs: Vbox, rhs: Vbox) -> Bool { return lhs.volume >= rhs.volume } private func <(lhs: Vbox, rhs: Vbox) -> Bool { return lhs.volume < rhs.volume } private func >(lhs: Vbox, rhs: Vbox) -> Bool { return lhs.volume > rhs.volume }
apache-2.0
f6a69807f8baec520907e41ec7cf9121
28.357798
152
0.710078
3.391627
false
false
false
false
michalciurus/KatanaRouter
Pods/Katana/Katana/Core/Animations/ChildrenAnimations.swift
1
2877
// // ChildrenAnimations.swift // Katana // // Copyright © 2016 Bending Spoons. // Distributed under the MIT License. // See the LICENSE file for more information. import Foundation /** This struct is used as container to define the animations for the children */ public struct ChildrenAnimations<Key> { /// It indicates whether we should perform a 4 step animation or not var shouldAnimate = false /// The animations of the children var animations = [String: Animation]() /// A default that is used for all the children without a specific animation public var allChildren: Animation = .none { didSet { if case .none = self.allChildren.type { return } self.shouldAnimate = true } } /** Gets the `Animation` value relative to a specific key - parameter key: the key of the children to retrieve - returns: the `Animation` value related to the key If the key has not been defined, the `allChildren` value is returned */ public subscript(key: Key) -> Animation { get { return self["\(key)"] } set(newValue) { if case .none = newValue.type { return } self.shouldAnimate = true self.animations["\(key)"] = newValue } } /** - note: This subscript should be used only to set values. It is an helper to specify the same animation for multiple keys */ public subscript(key: [Key]) -> Animation { get { fatalError("This subscript should not be used as a getter") } set(newValue) { for value in key { self[value] = newValue } } } /** Gets the `Animation` value relative to a specific key - parameter key: the key of the children to retrieve - returns: the `Animation` value related to the key If the key has not been defined, the `allChildren` value is returned */ subscript(key: String) -> Animation { return self.animations[key] ?? self.allChildren } } /// Type Erasure for ChildrenAnimations protocol AnyChildrenAnimations { /// It indicates whether we should perform a 4 step animation or not var shouldAnimate: Bool { get } /** Gets the `Animation` value relative to a description - parameter description: the description - returns: the `Animation` value related to the description If the children doesn't have a specific value, the `allChildren` value is returned */ subscript(description: AnyNodeDescription) -> Animation { get } } /// Implementation of AnyChildrenAnimations extension ChildrenAnimations: AnyChildrenAnimations { /** Implementation of the AnyChildrenAnimations protocol. - seeAlso: `AnyChildrenAnimations` */ subscript(description: AnyNodeDescription) -> Animation { if let key = description.anyProps.key { return self[key] } return self.allChildren } }
mit
10e185039769e8227edf77726fe61e0b
24.008696
85
0.670723
4.438272
false
false
false
false
rnystrom/GitHawk
Classes/Utility/AlertAction.swift
1
4754
// // AlertActions.swift // Freetime // // Created by Ivan Magda on 25/09/2017. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import UIKit typealias AlertActionBlock = (UIAlertAction) -> Void // MARK: AlertActions - struct AlertAction { // MARK: Properties let rootViewController: UIViewController? let title: String? let style: UIAlertActionStyle enum AlertShareType { case shareUrl case shareContent case shareFilePath case shareFileName case `default` var localizedString: String { switch self { case .shareUrl: return NSLocalizedString("Share URL", comment: "") case .shareContent: return NSLocalizedString("Share Content", comment: "") case .shareFilePath: return NSLocalizedString("Copy Path", comment: "") case .shareFileName: return NSLocalizedString("Copy Name", comment: "") case .default: return NSLocalizedString("Share", comment: "") } } } // MARK: Init init(_ builder: AlertActionBuilder) { rootViewController = builder.rootViewController title = builder.title style = builder.style ?? .default } // MARK: Public func get(_ handler: AlertActionBlock? = nil) -> UIAlertAction { return UIAlertAction(title: self.title, style: self.style, handler: handler) } func share(_ items: [Any], activities: [UIActivity]?, type: AlertShareType = .default, buildActivityBlock: ((UIActivityViewController) -> Void)?) -> UIAlertAction { return UIAlertAction(title: type.localizedString, style: .default) { _ in let activityController = UIActivityViewController(activityItems: items, applicationActivities: activities) buildActivityBlock?(activityController) self.rootViewController?.present(activityController, animated: trueUnlessReduceMotionEnabled) } } func view(client: GithubClient, repo: RepositoryDetails, icon: UIImage) -> UIAlertAction { return UIAlertAction(title: repo.name, image: icon, style: .default) { _ in self.rootViewController?.route_push(to: RepositoryViewController( client: client, repo: repo )) } } func view(owner: String, icon: UIImage) -> UIAlertAction { return UIAlertAction(title: "@\(owner)", image: icon, style: .default) { _ in guard let url = URLBuilder.github().add(path: owner).url else { return } self.rootViewController?.presentSafari(url: url) } } func newIssue(issueController: NewIssueTableViewController) -> UIAlertAction { return UIAlertAction(title: Constants.Strings.newIssue, style: .default) { _ in let nav = UINavigationController(rootViewController: issueController) nav.modalPresentationStyle = .formSheet self.rootViewController?.route_present(to: nav) } } // MARK: Static static func cancel(_ handler: AlertActionBlock? = nil) -> UIAlertAction { return UIAlertAction(title: Constants.Strings.cancel, style: .cancel, handler: handler) } static func ok(_ handler: AlertActionBlock? = nil) -> UIAlertAction { return UIAlertAction(title: Constants.Strings.ok, style: .default, handler: handler) } static func no(_ handler: AlertActionBlock? = nil) -> UIAlertAction { return UIAlertAction(title: Constants.Strings.no, style: .cancel, handler: handler) } static func yes(_ handler: AlertActionBlock? = nil) -> UIAlertAction { return UIAlertAction(title: Constants.Strings.yes, style: .default, handler: handler) } static func goBack(_ handler: AlertActionBlock? = nil) -> UIAlertAction { return UIAlertAction(title: NSLocalizedString("Go back", comment: ""), style: .cancel, handler: handler) } static func discard(_ handler: AlertActionBlock? = nil) -> UIAlertAction { return UIAlertAction(title: NSLocalizedString("Discard", comment: ""), style: .destructive, handler: handler) } static func delete(_ handler: AlertActionBlock? = nil) -> UIAlertAction { return UIAlertAction(title: NSLocalizedString("Delete", comment: ""), style: .destructive, handler: handler) } static func login(_ handler: AlertActionBlock? = nil) -> UIAlertAction { return UIAlertAction(title: Constants.Strings.signin, style: .default, handler: handler) } static func clearAll(_ handler: AlertActionBlock? = nil) -> UIAlertAction { return UIAlertAction(title: Constants.Strings.clearAll, style: .destructive, handler: handler) } }
mit
caace382910b37546dc226fc50f75157
36.132813
118
0.654955
4.961378
false
false
false
false
Esri/arcgis-runtime-samples-ios
arcgis-ios-sdk-samples/Layers/Select ENC features/SelectENCFeaturesViewController.swift
1
6329
// Copyright 2021 Esri // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit import ArcGIS class SelectENCFeaturesViewController: UIViewController { /// The map view managed by the view controller. @IBOutlet var mapView: AGSMapView! { didSet { mapView.map = AGSMap(basemapStyle: .arcGISOceans) mapView.setViewpoint(AGSViewpoint(latitude: -32.5, longitude: 60.95, scale: 1e5)) mapView.touchDelegate = self mapView.callout.isAccessoryButtonHidden = true } } /// The ENC layer that contains the current selected feature. var currentENCLayer: AGSENCLayer? /// A reference to the cancelable identify layer operation. var identifyOperation: AGSCancelable? /// A URL to the temporary SENC data directory. let temporaryURL: URL = { let directoryURL = FileManager.default.temporaryDirectory.appendingPathComponent(ProcessInfo().globallyUniqueString) // Create and return the full, unique URL to the temporary folder. try? FileManager.default.createDirectory(at: directoryURL, withIntermediateDirectories: true) return directoryURL }() /// Load the ENC dataset and add it to the map view. func addENCExchangeSet() { // Load catalog file in ENC exchange set from bundle. let catalogURL = Bundle.main.url( forResource: "CATALOG", withExtension: "031", subdirectory: "ExchangeSetWithoutUpdates/ENC_ROOT" )! let encExchangeSet = AGSENCExchangeSet(fileURLs: [catalogURL]) // URL to the "hydrography" data folder that contains the "S57DataDictionary.xml" file. let hydrographyDirectory = Bundle.main.url( forResource: "S57DataDictionary", withExtension: "xml", subdirectory: "hydrography" )! .deletingLastPathComponent() // Set environment settings for loading the dataset. let environmentSettings = AGSENCEnvironmentSettings.shared() environmentSettings.resourceDirectory = hydrographyDirectory // The SENC data directory is for temporarily storing generated files. environmentSettings.sencDataDirectory = temporaryURL // Update the display settings to make the chart less cluttered. updateDisplaySettings() encExchangeSet.load { [weak self] error in guard let self = self else { return } if let error = error { self.presentAlert(error: error) } else { // Create a list of ENC layers from datasets. let encLayers = encExchangeSet.datasets.map { AGSENCLayer(cell: AGSENCCell(dataset: $0)) } // Add layers to the map. self.mapView.map?.operationalLayers.addObjects(from: encLayers) } } } /// Update the display settings to make the chart less cluttered. func updateDisplaySettings() { let displaySettings = AGSENCEnvironmentSettings.shared().displaySettings let textGroupVisibilitySettings = displaySettings.textGroupVisibilitySettings textGroupVisibilitySettings.geographicNames = false textGroupVisibilitySettings.natureOfSeabed = false let viewingGroupSettings = displaySettings.viewingGroupSettings viewingGroupSettings.buoysBeaconsAidsToNavigation = false viewingGroupSettings.depthContours = false viewingGroupSettings.spotSoundings = false } override func viewDidLoad() { super.viewDidLoad() // Add the source code button item to the right of navigation bar. (navigationItem.rightBarButtonItem as? SourceCodeBarButtonItem)?.filenames = ["SelectENCFeaturesViewController"] addENCExchangeSet() } deinit { // Recursively remove all files in the sample-specific // temporary folder and the folder itself. try? FileManager.default.removeItem(at: temporaryURL) // Reset ENC environment display settings. let displaySettings = AGSENCEnvironmentSettings.shared().displaySettings displaySettings.textGroupVisibilitySettings.resetToDefaults() displaySettings.viewingGroupSettings.resetToDefaults() } } // MARK: - AGSGeoViewTouchDelegate extension SelectENCFeaturesViewController: AGSGeoViewTouchDelegate { func geoView(_ geoView: AGSGeoView, didTapAtScreenPoint screenPoint: CGPoint, mapPoint: AGSPoint) { // Dismiss any presenting callout. mapView.callout.dismiss() // Clear selection before identifying layers. currentENCLayer?.clearSelection() // Clear in-progress identify operation. identifyOperation?.cancel() // Identify the tapped feature. identifyOperation = mapView.identifyLayers(atScreenPoint: screenPoint, tolerance: 10, returnPopupsOnly: false) { [weak self] identifyResults, _ in guard let self = self else { return } self.identifyOperation = nil guard let results = identifyResults, let firstResult = results.first(where: { $0.layerContent is AGSENCLayer }), let containingLayer = firstResult.layerContent as? AGSENCLayer, let firstFeature = firstResult.geoElements.first as? AGSENCFeature else { return } self.currentENCLayer = containingLayer containingLayer.select(firstFeature) self.mapView.callout.title = firstFeature.acronym self.mapView.callout.detail = firstFeature.featureDescription self.mapView.callout.show(at: mapPoint, screenOffset: .zero, rotateOffsetWithMap: false, animated: true) } } }
apache-2.0
f797177d2aa4e00e37adc638322aa46c
44.207143
154
0.677042
4.967818
false
false
false
false
kenwilcox/Crypticker
CryptoCurrencyKit/CurrencyDataViewController.swift
1
5344
/* * Copyright (c) 2014 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit public class CurrencyDataViewController: UIViewController, JBLineChartViewDataSource, JBLineChartViewDelegate { @IBOutlet public var priceLabel: UILabel! @IBOutlet public var priceChangeLabel: UILabel! @IBOutlet public var dayLabel: UILabel! @IBOutlet public var lineChartView: JBLineChartView! public let dollarNumberFormatter: NSNumberFormatter, prefixedDollarNumberFormatter: NSNumberFormatter public var prices: [BitCoinPrice]? public var priceDifference: NSNumber? { get { var difference: NSNumber? if (stats != nil && prices != nil) { if let yesterdaysPrice = BitCoinService.sharedInstance.yesterdaysPriceUsingPriceHistory(prices!) { difference = NSNumber(float:stats!.marketPriceUSD.floatValue - yesterdaysPrice.value.floatValue) } } return difference } } public var stats: BitCoinStats? public required init(coder aDecoder: NSCoder) { dollarNumberFormatter = NSNumberFormatter() dollarNumberFormatter.numberStyle = .CurrencyStyle dollarNumberFormatter.positivePrefix = "" dollarNumberFormatter.negativePrefix = "" prefixedDollarNumberFormatter = NSNumberFormatter() prefixedDollarNumberFormatter.numberStyle = .CurrencyStyle prefixedDollarNumberFormatter.positivePrefix = "+" prefixedDollarNumberFormatter.negativePrefix = "-" super.init(coder: aDecoder) } public func fetchPrices(completion: (error: NSError?) -> ()) { BitCoinService.sharedInstance.getStats { stats, error in BitCoinService.sharedInstance.getMarketPriceInUSDForPast30Days { prices, error in dispatch_async(dispatch_get_main_queue()) { self.prices = prices self.stats = stats completion(error: error) } } } } public func updatePriceLabel() { self.priceLabel.text = priceLabelString() } public func updatePriceChangeLabel() { let stringAndColor = priceChangeLabelStringAndColor() priceChangeLabel.textColor = stringAndColor.color priceChangeLabel.text = stringAndColor.string } public func updatePriceHistoryLineChart() { if let prices = prices { let pricesNSArray = prices as NSArray let maxPrice = pricesNSArray.valueForKeyPath("@max.value") as! NSNumber lineChartView.maximumValue = CGFloat(maxPrice.floatValue * 1.02) lineChartView.reloadData() } } public func priceLabelString() -> (String) { return dollarNumberFormatter.stringFromNumber(stats?.marketPriceUSD ?? 0)! } public func priceChangeLabelStringAndColor() -> (string: String, color: UIColor) { var string: String? var color: UIColor? if let priceDifference = priceDifference { if (priceDifference.floatValue > 0) { color = UIColor.greenColor() } else { color = UIColor.redColor() } string = prefixedDollarNumberFormatter.stringFromNumber(priceDifference) } return (string ?? "", color ?? UIColor.blueColor()) } // MARK: - JBLineChartViewDataSource & JBLineChartViewDelegate public func numberOfLinesInLineChartView(lineChartView: JBLineChartView!) -> UInt { return 1 } public func lineChartView(lineChartView: JBLineChartView!, numberOfVerticalValuesAtLineIndex lineIndex: UInt) -> UInt { var numberOfValues = 0 if let prices = prices { numberOfValues = prices.count } return UInt(numberOfValues) } public func lineChartView(lineChartView: JBLineChartView!, verticalValueForHorizontalIndex horizontalIndex: UInt, atLineIndex lineIndex: UInt) -> CGFloat { var value: CGFloat = 0.0 if let prices = prices { let price = prices[Int(horizontalIndex)] value = CGFloat(price.value.floatValue) } return value } public func lineChartView(lineChartView: JBLineChartView!, widthForLineAtLineIndex lineIndex: UInt) -> CGFloat { return 2.0 } public func lineChartView(lineChartView: JBLineChartView!, colorForLineAtLineIndex lineIndex: UInt) -> UIColor! { return UIColor.whiteColor() } public func verticalSelectionWidthForLineChartView(lineChartView: JBLineChartView!) -> CGFloat { return 1.0; } }
mit
ca6e72854ef5fd9bde714f4049966365
33.928105
157
0.723615
4.902752
false
false
false
false
ReactiveKit/ReactiveKit
Sources/Subjects.swift
1
7619
// // The MIT License (MIT) // // Copyright (c) 2016 Srdan Rasic (@srdanrasic) // // 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 /// A type that is both a signal and an observer. public protocol SubjectProtocol: SignalProtocol, ObserverProtocol { } /// A type that is both a signal and an observer. open class Subject<Element, Error: Swift.Error>: SubjectProtocol { private typealias Token = Int64 private var nextToken: Token = 0 private var observers: [(Token, Observer<Element, Error>)] = [] public private(set) var isTerminated = false public let observersLock = NSRecursiveLock(name: "reactive_kit.subject.observers_lock") public let dispatchLock = NSRecursiveLock(name: "reactive_kit.subject.dispatch_lock") public let disposeBag = DisposeBag() public init() {} public func on(_ event: Event<Element, Error>) { dispatchLock.lock(); defer { dispatchLock.unlock() } guard !isTerminated else { return } isTerminated = event.isTerminal send(event) } open func send(_ event: Event<Element, Error>) { forEachObserver { $0(event) } } open func observe(with observer: @escaping Observer<Element, Error>) -> Disposable { observersLock.lock(); defer { observersLock.unlock() } willAdd(observer: observer) return add(observer: observer) } open func willAdd(observer: @escaping Observer<Element, Error>) { } private func add(observer: @escaping Observer<Element, Error>) -> Disposable { let token = nextToken nextToken = nextToken + 1 observers.append((token, observer)) return BlockDisposable { [weak self] in guard let me = self else { return } me.observersLock.lock(); defer { me.observersLock.unlock() } guard let index = me.observers.firstIndex(where: { $0.0 == token }) else { return } me.observers.remove(at: index) } } private func forEachObserver(_ execute: (Observer<Element, Error>) -> Void) { for (_, observer) in observers { execute(observer) } } } extension Subject: BindableProtocol { public func bind(signal: Signal<Element, Never>) -> Disposable { return signal .take(until: disposeBag.deallocated) .observeIn(.nonRecursive()) .observeNext { [weak self] element in guard let s = self else { return } s.on(.next(element)) } } } /// A subject that propagates received events to the registered observes. public final class PublishSubject<Element, Error: Swift.Error>: Subject<Element, Error> {} /// A PublishSubject compile-time guaranteed never to emit an error. public typealias SafePublishSubject<Element> = PublishSubject<Element, Never> /// A subject that replies accumulated sequence of events to each observer. public final class ReplaySubject<Element, Error: Swift.Error>: Subject<Element, Error> { private var buffer: ArraySlice<Event<Element, Error>> = [] public let bufferSize: Int public init(bufferSize: Int = Int.max) { if bufferSize < Int.max { self.bufferSize = bufferSize + 1 // plus terminal event } else { self.bufferSize = bufferSize } } public override func send(_ event: Event<Element, Error>) { buffer.append(event) buffer = buffer.suffix(bufferSize) super.send(event) } public override func willAdd(observer: @escaping Observer<Element, Error>) { buffer.forEach(observer) } } /// A ReplaySubject compile-time guaranteed never to emit an error. public typealias SafeReplaySubject<Element> = ReplaySubject<Element, Never> /// A subject that replies latest event to each observer. public final class ReplayOneSubject<Element, Error: Swift.Error>: Subject<Element, Error> { private var lastEvent: Event<Element, Error>? = nil private var terminalEvent: Event<Element, Error>? = nil public override func send(_ event: Event<Element, Error>) { if event.isTerminal { terminalEvent = event } else { lastEvent = event } super.send(event) } public override func willAdd(observer: @escaping Observer<Element, Error>) { if let event = lastEvent { observer(event) } if let event = terminalEvent { observer(event) } } } /// A ReplayOneSubject compile-time guaranteed never to emit an error. public typealias SafeReplayOneSubject<Element> = ReplayOneSubject<Element, Never> /// A subject that replies accumulated sequence of loading values to each observer. public final class ReplayLoadingValueSubject<Val, LoadingError: Swift.Error, Error: Swift.Error>: Subject<LoadingState<Val, LoadingError>, Error> { private enum State { case notStarted case loading case loadedOrFailedAtLeastOnce } private var state: State = .notStarted private var buffer: ArraySlice<LoadingState<Val, LoadingError>> = [] private var terminalEvent: Event<LoadingState<Val, LoadingError>, Error>? = nil public let bufferSize: Int public init(bufferSize: Int = Int.max) { self.bufferSize = bufferSize } public override func send(_ event: Event<LoadingState<Val, LoadingError>, Error>) { switch event { case .next(let loadingState): switch loadingState { case .loading: if state == .notStarted { state = .loading } case .loaded: state = .loadedOrFailedAtLeastOnce buffer.append(loadingState) buffer = buffer.suffix(bufferSize) case .failed: state = .loadedOrFailedAtLeastOnce buffer = [loadingState] } case .failed, .completed: terminalEvent = event } super.send(event) } public override func willAdd(observer: @escaping Observer<LoadingState<Val, LoadingError>, Error>) { switch state { case .notStarted: break case .loading: observer(.next(.loading)) case .loadedOrFailedAtLeastOnce: buffer.forEach { observer(.next($0)) } } if let event = terminalEvent { observer(event) } } }
mit
ec25e83a8dbd9dcac2b0dd0cd9146473
33.949541
147
0.641029
4.674233
false
false
false
false
FrostDigital/PuPageMenu
Classes/CAPSPageMenu.swift
1
54072
// CAPSPageMenu.swift // // Niklas Fahl // // Copyright (c) 2014 The Board of Trustees of The University of Alabama All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // // Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // // Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. // // Neither the name of the University nor the names of the contributors may be used to endorse or promote products derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A // PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import UIKit @objc public protocol CAPSPageMenuDelegate { // MARK: - Delegate functions @objc optional func willMoveToPage(_ controller: UIViewController, index: Int) @objc optional func didMoveToPage(_ controller: UIViewController, index: Int) } class MenuItemView: UIView { // MARK: - Menu item view var titleLabel : UILabel? var menuItemSeparator : UIView? func setUpMenuItemView(_ menuItemWidth: CGFloat, menuScrollViewHeight: CGFloat, indicatorHeight: CGFloat, separatorPercentageHeight: CGFloat, separatorWidth: CGFloat, separatorRoundEdges: Bool, menuItemSeparatorColor: UIColor) { titleLabel = UILabel(frame: CGRect(x: 0.0, y: 0.0, width: menuItemWidth, height: menuScrollViewHeight - indicatorHeight)) menuItemSeparator = UIView(frame: CGRect(x: menuItemWidth - (separatorWidth / 2), y: floor(menuScrollViewHeight * ((1.0 - separatorPercentageHeight) / 2.0)), width: separatorWidth, height: floor(menuScrollViewHeight * separatorPercentageHeight))) menuItemSeparator!.backgroundColor = menuItemSeparatorColor if separatorRoundEdges { menuItemSeparator!.layer.cornerRadius = menuItemSeparator!.frame.width / 2 } menuItemSeparator!.isHidden = true self.addSubview(menuItemSeparator!) self.addSubview(titleLabel!) } func setTitleText(_ text: NSString) { if titleLabel != nil { titleLabel!.text = text as String titleLabel!.numberOfLines = 0 titleLabel!.sizeToFit() } } } public enum CAPSPageMenuOption { case selectionIndicatorHeight(CGFloat) case menuItemSeparatorWidth(CGFloat) case scrollMenuBackgroundColor(UIColor) case viewBackgroundColor(UIColor) case bottomMenuHairlineColor(UIColor) case selectionIndicatorColor(UIColor) case menuItemSeparatorColor(UIColor) case menuMargin(CGFloat) case menuItemMargin(CGFloat) case menuHeight(CGFloat) case selectedMenuItemLabelColor(UIColor) case unselectedMenuItemLabelColor(UIColor) case useMenuLikeSegmentedControl(Bool) case menuItemSeparatorRoundEdges(Bool) case menuItemFont(UIFont) case menuItemSeparatorPercentageHeight(CGFloat) case menuItemWidth(CGFloat) case enableHorizontalBounce(Bool) case addBottomMenuHairline(Bool) case menuItemWidthBasedOnTitleTextWidth(Bool) case titleTextSizeBasedOnMenuItemWidth(Bool) case scrollAnimationDurationOnMenuItemTap(Int) case centerMenuItems(Bool) case hideTopMenuBar(Bool) } open class CAPSPageMenu: UIViewController, UIScrollViewDelegate, UIGestureRecognizerDelegate { // MARK: - Properties let menuScrollView = UIScrollView() let controllerScrollView = UIScrollView() var controllerArray : [UIViewController] = [] var menuItems : [MenuItemView] = [] var menuItemWidths : [CGFloat] = [] open var menuHeight : CGFloat = 34.0 open var menuMargin : CGFloat = 15.0 open var menuItemWidth : CGFloat = 111.0 open var selectionIndicatorHeight : CGFloat = 3.0 var totalMenuItemWidthIfDifferentWidths : CGFloat = 0.0 open var scrollAnimationDurationOnMenuItemTap : Int = 500 // Millisecons var startingMenuMargin : CGFloat = 0.0 var menuItemMargin : CGFloat = 0.0 var selectionIndicatorView : UIView = UIView() var currentPageIndex : Int = 0 var lastPageIndex : Int = 0 open var selectionIndicatorColor : UIColor = UIColor.white open var selectedMenuItemLabelColor : UIColor = UIColor.white open var unselectedMenuItemLabelColor : UIColor = UIColor.lightGray open var scrollMenuBackgroundColor : UIColor = UIColor.black open var viewBackgroundColor : UIColor = UIColor.white open var bottomMenuHairlineColor : UIColor = UIColor.white open var menuItemSeparatorColor : UIColor = UIColor.lightGray open var menuItemFont : UIFont = UIFont.systemFont(ofSize: 15.0) open var menuItemSeparatorPercentageHeight : CGFloat = 0.2 open var menuItemSeparatorWidth : CGFloat = 0.5 open var menuItemSeparatorRoundEdges : Bool = false open var addBottomMenuHairline : Bool = true open var menuItemWidthBasedOnTitleTextWidth : Bool = false open var titleTextSizeBasedOnMenuItemWidth : Bool = false open var useMenuLikeSegmentedControl : Bool = false open var centerMenuItems : Bool = false open var enableHorizontalBounce : Bool = true open var hideTopMenuBar : Bool = false var currentOrientationIsPortrait : Bool = true var pageIndexForOrientationChange : Int = 0 var didLayoutSubviewsAfterRotation : Bool = false var didScrollAlready : Bool = false var lastControllerScrollViewContentOffset : CGFloat = 0.0 var lastScrollDirection : CAPSPageMenuScrollDirection = .other var startingPageForScroll : Int = 0 var didTapMenuItemToScroll : Bool = false var pagesAddedDictionary : [Int : Int] = [:] open weak var delegate : CAPSPageMenuDelegate? var tapTimer : Timer? enum CAPSPageMenuScrollDirection : Int { case left case right case other } // MARK: - View life cycle /** Initialize PageMenu with view controllers :param: viewControllers List of view controllers that must be subclasses of UIViewController :param: frame Frame for page menu view :param: options Dictionary holding any customization options user might want to set */ public init(viewControllers: [UIViewController], frame: CGRect, options: [String: AnyObject]?) { super.init(nibName: nil, bundle: nil) controllerArray = viewControllers self.view.frame = frame } public convenience init(viewControllers: [UIViewController], frame: CGRect, pageMenuOptions: [CAPSPageMenuOption]?) { self.init(viewControllers:viewControllers, frame:frame, options:nil) if let options = pageMenuOptions { for option in options { switch (option) { case let .selectionIndicatorHeight(value): selectionIndicatorHeight = value case let .menuItemSeparatorWidth(value): menuItemSeparatorWidth = value case let .scrollMenuBackgroundColor(value): scrollMenuBackgroundColor = value case let .viewBackgroundColor(value): viewBackgroundColor = value case let .bottomMenuHairlineColor(value): bottomMenuHairlineColor = value case let .selectionIndicatorColor(value): selectionIndicatorColor = value case let .menuItemSeparatorColor(value): menuItemSeparatorColor = value case let .menuMargin(value): menuMargin = value case let .menuItemMargin(value): menuItemMargin = value case let .menuHeight(value): menuHeight = value case let .selectedMenuItemLabelColor(value): selectedMenuItemLabelColor = value case let .unselectedMenuItemLabelColor(value): unselectedMenuItemLabelColor = value case let .useMenuLikeSegmentedControl(value): useMenuLikeSegmentedControl = value case let .menuItemSeparatorRoundEdges(value): menuItemSeparatorRoundEdges = value case let .menuItemFont(value): menuItemFont = value case let .menuItemSeparatorPercentageHeight(value): menuItemSeparatorPercentageHeight = value case let .menuItemWidth(value): menuItemWidth = value case let .enableHorizontalBounce(value): enableHorizontalBounce = value case let .addBottomMenuHairline(value): addBottomMenuHairline = value case let .menuItemWidthBasedOnTitleTextWidth(value): menuItemWidthBasedOnTitleTextWidth = value case let .titleTextSizeBasedOnMenuItemWidth(value): titleTextSizeBasedOnMenuItemWidth = value case let .scrollAnimationDurationOnMenuItemTap(value): scrollAnimationDurationOnMenuItemTap = value case let .centerMenuItems(value): centerMenuItems = value case let .hideTopMenuBar(value): hideTopMenuBar = value } } if hideTopMenuBar { addBottomMenuHairline = false menuHeight = 0.0 } } setUpUserInterface() if menuScrollView.subviews.count == 0 { configureUserInterface() } } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // MARK: - Container View Controller open override var shouldAutomaticallyForwardAppearanceMethods : Bool { return true } open override func shouldAutomaticallyForwardRotationMethods() -> Bool { return true } // MARK: - UI Setup func setUpUserInterface() { let viewsDictionary = ["menuScrollView":menuScrollView, "controllerScrollView":controllerScrollView] // Set up controller scroll view controllerScrollView.isPagingEnabled = true controllerScrollView.translatesAutoresizingMaskIntoConstraints = false controllerScrollView.alwaysBounceHorizontal = enableHorizontalBounce controllerScrollView.bounces = enableHorizontalBounce controllerScrollView.frame = CGRect(x: 0.0, y: menuHeight, width: self.view.frame.width, height: self.view.frame.height) self.view.addSubview(controllerScrollView) let controllerScrollView_constraint_H:Array = NSLayoutConstraint.constraints(withVisualFormat: "H:|[controllerScrollView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDictionary) let controllerScrollView_constraint_V:Array = NSLayoutConstraint.constraints(withVisualFormat: "V:|[controllerScrollView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDictionary) self.view.addConstraints(controllerScrollView_constraint_H) self.view.addConstraints(controllerScrollView_constraint_V) // Set up menu scroll view menuScrollView.translatesAutoresizingMaskIntoConstraints = false menuScrollView.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.width, height: menuHeight) self.view.addSubview(menuScrollView) let menuScrollView_constraint_H:Array = NSLayoutConstraint.constraints(withVisualFormat: "H:|[menuScrollView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDictionary) let menuScrollView_constraint_V:Array = NSLayoutConstraint.constraints(withVisualFormat: "V:[menuScrollView(\(menuHeight))]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDictionary) self.view.addConstraints(menuScrollView_constraint_H) self.view.addConstraints(menuScrollView_constraint_V) // Add hairline to menu scroll view if addBottomMenuHairline { let menuBottomHairline : UIView = UIView() menuBottomHairline.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(menuBottomHairline) let menuBottomHairline_constraint_H:Array = NSLayoutConstraint.constraints(withVisualFormat: "H:|[menuBottomHairline]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["menuBottomHairline":menuBottomHairline]) let menuBottomHairline_constraint_V:Array = NSLayoutConstraint.constraints(withVisualFormat: "V:|-\(menuHeight)-[menuBottomHairline(0.5)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["menuBottomHairline":menuBottomHairline]) self.view.addConstraints(menuBottomHairline_constraint_H) self.view.addConstraints(menuBottomHairline_constraint_V) menuBottomHairline.backgroundColor = bottomMenuHairlineColor } // Disable scroll bars menuScrollView.showsHorizontalScrollIndicator = false menuScrollView.showsVerticalScrollIndicator = false controllerScrollView.showsHorizontalScrollIndicator = false controllerScrollView.showsVerticalScrollIndicator = false // Set background color behind scroll views and for menu scroll view self.view.backgroundColor = viewBackgroundColor menuScrollView.backgroundColor = scrollMenuBackgroundColor } func configureUserInterface() { // Add tap gesture recognizer to controller scroll view to recognize menu item selection let menuItemTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(CAPSPageMenu.handleMenuItemTap(_:))) menuItemTapGestureRecognizer.numberOfTapsRequired = 1 menuItemTapGestureRecognizer.numberOfTouchesRequired = 1 menuItemTapGestureRecognizer.delegate = self menuScrollView.addGestureRecognizer(menuItemTapGestureRecognizer) // Set delegate for controller scroll view controllerScrollView.delegate = self // When the user taps the status bar, the scroll view beneath the touch which is closest to the status bar will be scrolled to top, // but only if its `scrollsToTop` property is YES, its delegate does not return NO from `shouldScrollViewScrollToTop`, and it is not already at the top. // If more than one scroll view is found, none will be scrolled. // Disable scrollsToTop for menu and controller scroll views so that iOS finds scroll views within our pages on status bar tap gesture. menuScrollView.scrollsToTop = false; controllerScrollView.scrollsToTop = false; // Configure menu scroll view if useMenuLikeSegmentedControl { menuScrollView.isScrollEnabled = false menuScrollView.contentSize = CGSize(width: self.view.frame.width, height: menuHeight) menuMargin = 0.0 } else { menuScrollView.contentSize = CGSize(width: (menuItemWidth + menuMargin) * CGFloat(controllerArray.count) + menuMargin, height: menuHeight) } // Configure controller scroll view content size controllerScrollView.contentSize = CGSize(width: self.view.frame.width * CGFloat(controllerArray.count), height: 0.0) var index : CGFloat = 0.0 for controller in controllerArray { if index == 0.0 { // Add first two controllers to scrollview and as child view controller addPageAtIndex(0) } // Set up menu item for menu scroll view var menuItemFrame : CGRect = CGRect() if useMenuLikeSegmentedControl { //**************************拡張************************************* if menuItemMargin > 0 { let marginSum = menuItemMargin * CGFloat(controllerArray.count + 1) let menuItemWidth = (self.view.frame.width - marginSum) / CGFloat(controllerArray.count) menuItemFrame = CGRect(x: CGFloat(menuItemMargin * (index + 1)) + menuItemWidth * CGFloat(index), y: 0.0, width: CGFloat(self.view.frame.width) / CGFloat(controllerArray.count), height: menuHeight) } else { menuItemFrame = CGRect(x: self.view.frame.width / CGFloat(controllerArray.count) * CGFloat(index), y: 0.0, width: CGFloat(self.view.frame.width) / CGFloat(controllerArray.count), height: menuHeight) } //**************************拡張ここまで************************************* } else if menuItemWidthBasedOnTitleTextWidth { let controllerTitle : String? = controller.title let titleText : String = controllerTitle != nil ? controllerTitle! : "Menu \(Int(index) + 1)" let itemWidthRect : CGRect = (titleText as NSString).boundingRect(with: CGSize(width: 1000, height: 1000), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName:menuItemFont], context: nil) menuItemWidth = itemWidthRect.width menuItemFrame = CGRect(x: totalMenuItemWidthIfDifferentWidths + menuMargin + (menuMargin * index), y: 0.0, width: menuItemWidth, height: menuHeight) totalMenuItemWidthIfDifferentWidths += itemWidthRect.width menuItemWidths.append(itemWidthRect.width) } else { if centerMenuItems && index == 0.0 { startingMenuMargin = ((self.view.frame.width - ((CGFloat(controllerArray.count) * menuItemWidth) + (CGFloat(controllerArray.count - 1) * menuMargin))) / 2.0) - menuMargin if startingMenuMargin < 0.0 { startingMenuMargin = 0.0 } menuItemFrame = CGRect(x: startingMenuMargin + menuMargin, y: 0.0, width: menuItemWidth, height: menuHeight) } else { menuItemFrame = CGRect(x: menuItemWidth * index + menuMargin * (index + 1) + startingMenuMargin, y: 0.0, width: menuItemWidth, height: menuHeight) } } let menuItemView : MenuItemView = MenuItemView(frame: menuItemFrame) if useMenuLikeSegmentedControl { //**************************拡張************************************* if menuItemMargin > 0 { let marginSum = menuItemMargin * CGFloat(controllerArray.count + 1) let menuItemWidth = (self.view.frame.width - marginSum) / CGFloat(controllerArray.count) menuItemView.setUpMenuItemView(menuItemWidth, menuScrollViewHeight: menuHeight, indicatorHeight: selectionIndicatorHeight, separatorPercentageHeight: menuItemSeparatorPercentageHeight, separatorWidth: menuItemSeparatorWidth, separatorRoundEdges: menuItemSeparatorRoundEdges, menuItemSeparatorColor: menuItemSeparatorColor) } else { menuItemView.setUpMenuItemView(CGFloat(self.view.frame.width) / CGFloat(controllerArray.count), menuScrollViewHeight: menuHeight, indicatorHeight: selectionIndicatorHeight, separatorPercentageHeight: menuItemSeparatorPercentageHeight, separatorWidth: menuItemSeparatorWidth, separatorRoundEdges: menuItemSeparatorRoundEdges, menuItemSeparatorColor: menuItemSeparatorColor) } //**************************拡張ここまで************************************* } else { menuItemView.setUpMenuItemView(menuItemWidth, menuScrollViewHeight: menuHeight, indicatorHeight: selectionIndicatorHeight, separatorPercentageHeight: menuItemSeparatorPercentageHeight, separatorWidth: menuItemSeparatorWidth, separatorRoundEdges: menuItemSeparatorRoundEdges, menuItemSeparatorColor: menuItemSeparatorColor) } // Configure menu item label font if font is set by user menuItemView.titleLabel!.font = menuItemFont menuItemView.titleLabel!.textAlignment = NSTextAlignment.center menuItemView.titleLabel!.textColor = unselectedMenuItemLabelColor //**************************拡張************************************* menuItemView.titleLabel!.adjustsFontSizeToFitWidth = titleTextSizeBasedOnMenuItemWidth //**************************拡張ここまで************************************* // Set title depending on if controller has a title set if controller.title != nil { menuItemView.titleLabel!.text = controller.title! } else { menuItemView.titleLabel!.text = "Menu \(Int(index) + 1)" } // Add separator between menu items when using as segmented control if useMenuLikeSegmentedControl { if Int(index) < controllerArray.count - 1 { menuItemView.menuItemSeparator!.isHidden = false } } // Add menu item view to menu scroll view menuScrollView.addSubview(menuItemView) menuItems.append(menuItemView) index += 1 } // Set new content size for menu scroll view if needed if menuItemWidthBasedOnTitleTextWidth { menuScrollView.contentSize = CGSize(width: (totalMenuItemWidthIfDifferentWidths + menuMargin) + CGFloat(controllerArray.count) * menuMargin, height: menuHeight) } // Set selected color for title label of selected menu item if menuItems.count > 0 { if menuItems[currentPageIndex].titleLabel != nil { menuItems[currentPageIndex].titleLabel!.textColor = selectedMenuItemLabelColor } } // Configure selection indicator view var selectionIndicatorFrame : CGRect = CGRect() if useMenuLikeSegmentedControl { selectionIndicatorFrame = CGRect(x: 0.0, y: menuHeight - selectionIndicatorHeight, width: self.view.frame.width / CGFloat(controllerArray.count), height: selectionIndicatorHeight) } else if menuItemWidthBasedOnTitleTextWidth { selectionIndicatorFrame = CGRect(x: menuMargin, y: menuHeight - selectionIndicatorHeight, width: menuItemWidths[0], height: selectionIndicatorHeight) } else { if centerMenuItems { selectionIndicatorFrame = CGRect(x: startingMenuMargin + menuMargin, y: menuHeight - selectionIndicatorHeight, width: menuItemWidth, height: selectionIndicatorHeight) } else { selectionIndicatorFrame = CGRect(x: menuMargin, y: menuHeight - selectionIndicatorHeight, width: menuItemWidth, height: selectionIndicatorHeight) } } selectionIndicatorView = UIView(frame: selectionIndicatorFrame) selectionIndicatorView.backgroundColor = selectionIndicatorColor menuScrollView.addSubview(selectionIndicatorView) if menuItemWidthBasedOnTitleTextWidth && centerMenuItems { self.configureMenuItemWidthBasedOnTitleTextWidthAndCenterMenuItems() let leadingAndTrailingMargin = self.getMarginForMenuItemWidthBasedOnTitleTextWidthAndCenterMenuItems() selectionIndicatorView.frame = CGRect(x: leadingAndTrailingMargin, y: menuHeight - selectionIndicatorHeight, width: menuItemWidths[0], height: selectionIndicatorHeight) } } // Adjusts the menu item frames to size item width based on title text width and center all menu items in the center // if the menuItems all fit in the width of the view. Otherwise, it will adjust the frames so that the menu items // appear as if only menuItemWidthBasedOnTitleTextWidth is true. fileprivate func configureMenuItemWidthBasedOnTitleTextWidthAndCenterMenuItems() { // only center items if the combined width is less than the width of the entire view's bounds if menuScrollView.contentSize.width < self.view.bounds.width { // compute the margin required to center the menu items let leadingAndTrailingMargin = self.getMarginForMenuItemWidthBasedOnTitleTextWidthAndCenterMenuItems() // adjust the margin of each menu item to make them centered for (index, menuItem) in menuItems.enumerated() { let controllerTitle = controllerArray[index].title! let itemWidthRect = controllerTitle.boundingRect(with: CGSize(width: 1000, height: 1000), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName:menuItemFont], context: nil) menuItemWidth = itemWidthRect.width var margin: CGFloat if index == 0 { // the first menu item should use the calculated margin margin = leadingAndTrailingMargin } else { // the other menu items should use the menuMargin let previousMenuItem = menuItems[index-1] let previousX = previousMenuItem.frame.maxX margin = previousX + menuMargin } menuItem.frame = CGRect(x: margin, y: 0.0, width: menuItemWidth, height: menuHeight) } } else { // the menuScrollView.contentSize.width exceeds the view's width, so layout the menu items normally (menuItemWidthBasedOnTitleTextWidth) for (index, menuItem) in menuItems.enumerated() { var menuItemX: CGFloat if index == 0 { menuItemX = menuMargin } else { menuItemX = menuItems[index-1].frame.maxX + menuMargin } menuItem.frame = CGRect(x: menuItemX, y: 0.0, width: menuItem.bounds.width, height: menuItem.bounds.height) } } } // Returns the size of the left and right margins that are neccessary to layout the menuItems in the center. fileprivate func getMarginForMenuItemWidthBasedOnTitleTextWidthAndCenterMenuItems() -> CGFloat { let menuItemsTotalWidth = menuScrollView.contentSize.width - menuMargin * 2 let leadingAndTrailingMargin = (self.view.bounds.width - menuItemsTotalWidth) / 2 return leadingAndTrailingMargin } // MARK: - Scroll view delegate open func scrollViewDidScroll(_ scrollView: UIScrollView) { if !didLayoutSubviewsAfterRotation { if scrollView.isEqual(controllerScrollView) { if scrollView.contentOffset.x >= 0.0 && scrollView.contentOffset.x <= (CGFloat(controllerArray.count - 1) * self.view.frame.width) { if (currentOrientationIsPortrait && UIApplication.shared.statusBarOrientation.isPortrait) || (!currentOrientationIsPortrait && UIApplication.shared.statusBarOrientation.isLandscape) { // Check if scroll direction changed if !didTapMenuItemToScroll { if didScrollAlready { var newScrollDirection : CAPSPageMenuScrollDirection = .other if (CGFloat(startingPageForScroll) * scrollView.frame.width > scrollView.contentOffset.x) { newScrollDirection = .right } else if (CGFloat(startingPageForScroll) * scrollView.frame.width < scrollView.contentOffset.x) { newScrollDirection = .left } if newScrollDirection != .other { if lastScrollDirection != newScrollDirection { let index : Int = newScrollDirection == .left ? currentPageIndex + 1 : currentPageIndex - 1 if index >= 0 && index < controllerArray.count { // Check dictionary if page was already added if pagesAddedDictionary[index] != index { addPageAtIndex(index) pagesAddedDictionary[index] = index } } } } lastScrollDirection = newScrollDirection } if !didScrollAlready { if (lastControllerScrollViewContentOffset > scrollView.contentOffset.x) { if currentPageIndex != controllerArray.count - 1 { // Add page to the left of current page let index : Int = currentPageIndex - 1 if pagesAddedDictionary[index] != index && index < controllerArray.count && index >= 0 { addPageAtIndex(index) pagesAddedDictionary[index] = index } lastScrollDirection = .right } } else if (lastControllerScrollViewContentOffset < scrollView.contentOffset.x) { if currentPageIndex != 0 { // Add page to the right of current page let index : Int = currentPageIndex + 1 if pagesAddedDictionary[index] != index && index < controllerArray.count && index >= 0 { addPageAtIndex(index) pagesAddedDictionary[index] = index } lastScrollDirection = .left } } didScrollAlready = true } lastControllerScrollViewContentOffset = scrollView.contentOffset.x } var ratio : CGFloat = 1.0 // Calculate ratio between scroll views ratio = (menuScrollView.contentSize.width - self.view.frame.width) / (controllerScrollView.contentSize.width - self.view.frame.width) if menuScrollView.contentSize.width > self.view.frame.width { var offset : CGPoint = menuScrollView.contentOffset offset.x = controllerScrollView.contentOffset.x * ratio menuScrollView.setContentOffset(offset, animated: false) } // Calculate current page let width : CGFloat = controllerScrollView.frame.size.width; let page : Int = Int((controllerScrollView.contentOffset.x + (0.5 * width)) / width) // Update page if changed if page != currentPageIndex { lastPageIndex = currentPageIndex currentPageIndex = page if pagesAddedDictionary[page] != page && page < controllerArray.count && page >= 0 { addPageAtIndex(page) pagesAddedDictionary[page] = page } if !didTapMenuItemToScroll { // Add last page to pages dictionary to make sure it gets removed after scrolling if pagesAddedDictionary[lastPageIndex] != lastPageIndex { pagesAddedDictionary[lastPageIndex] = lastPageIndex } // Make sure only up to 3 page views are in memory when fast scrolling, otherwise there should only be one in memory let indexLeftTwo : Int = page - 2 if pagesAddedDictionary[indexLeftTwo] == indexLeftTwo { pagesAddedDictionary.removeValue(forKey: indexLeftTwo) removePageAtIndex(indexLeftTwo) } let indexRightTwo : Int = page + 2 if pagesAddedDictionary[indexRightTwo] == indexRightTwo { pagesAddedDictionary.removeValue(forKey: indexRightTwo) removePageAtIndex(indexRightTwo) } } } // Move selection indicator view when swiping moveSelectionIndicator(page) } } else { var ratio : CGFloat = 1.0 ratio = (menuScrollView.contentSize.width - self.view.frame.width) / (controllerScrollView.contentSize.width - self.view.frame.width) if menuScrollView.contentSize.width > self.view.frame.width { var offset : CGPoint = menuScrollView.contentOffset offset.x = controllerScrollView.contentOffset.x * ratio menuScrollView.setContentOffset(offset, animated: false) } } } } else { didLayoutSubviewsAfterRotation = false // Move selection indicator view when swiping moveSelectionIndicator(currentPageIndex) } } open func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { if scrollView.isEqual(controllerScrollView) { // Call didMoveToPage delegate function let currentController = controllerArray[currentPageIndex] delegate?.didMoveToPage?(currentController, index: currentPageIndex) // Remove all but current page after decelerating for key in pagesAddedDictionary.keys { if key != currentPageIndex { removePageAtIndex(key) } } didScrollAlready = false startingPageForScroll = currentPageIndex // Empty out pages in dictionary pagesAddedDictionary.removeAll(keepingCapacity: false) } } func scrollViewDidEndTapScrollingAnimation() { // Call didMoveToPage delegate function let currentController = controllerArray[currentPageIndex] delegate?.didMoveToPage?(currentController, index: currentPageIndex) // Remove all but current page after decelerating for key in pagesAddedDictionary.keys { if key != currentPageIndex { removePageAtIndex(key) } } startingPageForScroll = currentPageIndex didTapMenuItemToScroll = false // Empty out pages in dictionary pagesAddedDictionary.removeAll(keepingCapacity: false) } // MARK: - Handle Selection Indicator func moveSelectionIndicator(_ pageIndex: Int) { if pageIndex >= 0 && pageIndex < controllerArray.count { UIView.animate(withDuration: 0.15, animations: { () -> Void in var selectionIndicatorWidth : CGFloat = self.selectionIndicatorView.frame.width var selectionIndicatorX : CGFloat = 0.0 if self.useMenuLikeSegmentedControl { selectionIndicatorX = CGFloat(pageIndex) * (self.view.frame.width / CGFloat(self.controllerArray.count)) selectionIndicatorWidth = self.view.frame.width / CGFloat(self.controllerArray.count) } else if self.menuItemWidthBasedOnTitleTextWidth { selectionIndicatorWidth = self.menuItemWidths[pageIndex] selectionIndicatorX = self.menuItems[pageIndex].frame.minX } else { if self.centerMenuItems && pageIndex == 0 { selectionIndicatorX = self.startingMenuMargin + self.menuMargin } else { selectionIndicatorX = self.menuItemWidth * CGFloat(pageIndex) + self.menuMargin * CGFloat(pageIndex + 1) + self.startingMenuMargin } } self.selectionIndicatorView.frame = CGRect(x: selectionIndicatorX, y: self.selectionIndicatorView.frame.origin.y, width: selectionIndicatorWidth, height: self.selectionIndicatorView.frame.height) // Switch newly selected menu item title label to selected color and old one to unselected color if self.menuItems.count > 0 { if self.menuItems[self.lastPageIndex].titleLabel != nil && self.menuItems[self.currentPageIndex].titleLabel != nil { self.menuItems[self.lastPageIndex].titleLabel!.textColor = self.unselectedMenuItemLabelColor self.menuItems[self.currentPageIndex].titleLabel!.textColor = self.selectedMenuItemLabelColor } } }) } } // MARK: - Tap gesture recognizer selector func handleMenuItemTap(_ gestureRecognizer : UITapGestureRecognizer) { let tappedPoint : CGPoint = gestureRecognizer.location(in: menuScrollView) if tappedPoint.y < menuScrollView.frame.height { // Calculate tapped page var itemIndex : Int = 0 if useMenuLikeSegmentedControl { itemIndex = Int(tappedPoint.x / (self.view.frame.width / CGFloat(controllerArray.count))) } else if menuItemWidthBasedOnTitleTextWidth { var menuItemLeftBound: CGFloat var menuItemRightBound: CGFloat if centerMenuItems { menuItemLeftBound = menuItems[0].frame.minX menuItemRightBound = menuItems[menuItems.count-1].frame.maxX if (tappedPoint.x >= menuItemLeftBound && tappedPoint.x <= menuItemRightBound) { for (index, _) in controllerArray.enumerated() { menuItemLeftBound = menuItems[index].frame.minX menuItemRightBound = menuItems[index].frame.maxX if tappedPoint.x >= menuItemLeftBound && tappedPoint.x <= menuItemRightBound { itemIndex = index break } } } } else { // Base case being first item menuItemLeftBound = 0.0 menuItemRightBound = menuItemWidths[0] + menuMargin + (menuMargin / 2) if !(tappedPoint.x >= menuItemLeftBound && tappedPoint.x <= menuItemRightBound) { for i in 1...controllerArray.count - 1 { menuItemLeftBound = menuItemRightBound + 1.0 menuItemRightBound = menuItemLeftBound + menuItemWidths[i] + menuMargin if tappedPoint.x >= menuItemLeftBound && tappedPoint.x <= menuItemRightBound { itemIndex = i break } } } } } else { let rawItemIndex : CGFloat = ((tappedPoint.x - startingMenuMargin) - menuMargin / 2) / (menuMargin + menuItemWidth) // Prevent moving to first item when tapping left to first item if rawItemIndex < 0 { itemIndex = -1 } else { itemIndex = Int(rawItemIndex) } } if itemIndex >= 0 && itemIndex < controllerArray.count { // Update page if changed if itemIndex != currentPageIndex { startingPageForScroll = itemIndex lastPageIndex = currentPageIndex currentPageIndex = itemIndex didTapMenuItemToScroll = true // Add pages in between current and tapped page if necessary let smallerIndex : Int = lastPageIndex < currentPageIndex ? lastPageIndex : currentPageIndex let largerIndex : Int = lastPageIndex > currentPageIndex ? lastPageIndex : currentPageIndex if smallerIndex + 1 != largerIndex { for index in (smallerIndex + 1)...(largerIndex - 1) { if pagesAddedDictionary[index] != index { addPageAtIndex(index) pagesAddedDictionary[index] = index } } } addPageAtIndex(itemIndex) // Add page from which tap is initiated so it can be removed after tap is done pagesAddedDictionary[lastPageIndex] = lastPageIndex } // Move controller scroll view when tapping menu item let duration : Double = Double(scrollAnimationDurationOnMenuItemTap) / Double(1000) UIView.animate(withDuration: duration, animations: { () -> Void in let xOffset : CGFloat = CGFloat(itemIndex) * self.controllerScrollView.frame.width self.controllerScrollView.setContentOffset(CGPoint(x: xOffset, y: self.controllerScrollView.contentOffset.y), animated: false) }) if tapTimer != nil { tapTimer!.invalidate() } let timerInterval : TimeInterval = Double(scrollAnimationDurationOnMenuItemTap) * 0.001 tapTimer = Timer.scheduledTimer(timeInterval: timerInterval, target: self, selector: #selector(CAPSPageMenu.scrollViewDidEndTapScrollingAnimation), userInfo: nil, repeats: false) } } } // MARK: - Remove/Add Page func addPageAtIndex(_ index : Int) { // Call didMoveToPage delegate function let currentController = controllerArray[index] delegate?.willMoveToPage?(currentController, index: index) let newVC = controllerArray[index] newVC.willMove(toParentViewController: self) newVC.view.frame = CGRect(x: self.view.frame.width * CGFloat(index), y: menuHeight, width: self.view.frame.width, height: self.view.frame.height - menuHeight) self.addChildViewController(newVC) self.controllerScrollView.addSubview(newVC.view) newVC.didMove(toParentViewController: self) } func removePageAtIndex(_ index : Int) { let oldVC = controllerArray[index] oldVC.willMove(toParentViewController: nil) oldVC.view.removeFromSuperview() oldVC.removeFromParentViewController() } // MARK: - Orientation Change override open func viewDidLayoutSubviews() { // Configure controller scroll view content size controllerScrollView.contentSize = CGSize(width: self.view.frame.width * CGFloat(controllerArray.count), height: self.view.frame.height - menuHeight) let oldCurrentOrientationIsPortrait : Bool = currentOrientationIsPortrait currentOrientationIsPortrait = UIApplication.shared.statusBarOrientation.isPortrait if (oldCurrentOrientationIsPortrait && UIDevice.current.orientation.isLandscape) || (!oldCurrentOrientationIsPortrait && UIDevice.current.orientation.isPortrait) { didLayoutSubviewsAfterRotation = true //Resize menu items if using as segmented control if useMenuLikeSegmentedControl { menuScrollView.contentSize = CGSize(width: self.view.frame.width, height: menuHeight) // Resize selectionIndicator bar let selectionIndicatorX : CGFloat = CGFloat(currentPageIndex) * (self.view.frame.width / CGFloat(self.controllerArray.count)) let selectionIndicatorWidth : CGFloat = self.view.frame.width / CGFloat(self.controllerArray.count) selectionIndicatorView.frame = CGRect(x: selectionIndicatorX, y: self.selectionIndicatorView.frame.origin.y, width: selectionIndicatorWidth, height: self.selectionIndicatorView.frame.height) // Resize menu items var index : Int = 0 for item : MenuItemView in menuItems as [MenuItemView] { item.frame = CGRect(x: self.view.frame.width / CGFloat(controllerArray.count) * CGFloat(index), y: 0.0, width: self.view.frame.width / CGFloat(controllerArray.count), height: menuHeight) item.titleLabel!.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.width / CGFloat(controllerArray.count), height: menuHeight) item.menuItemSeparator!.frame = CGRect(x: item.frame.width - (menuItemSeparatorWidth / 2), y: item.menuItemSeparator!.frame.origin.y, width: item.menuItemSeparator!.frame.width, height: item.menuItemSeparator!.frame.height) index += 1 } } else if menuItemWidthBasedOnTitleTextWidth && centerMenuItems { self.configureMenuItemWidthBasedOnTitleTextWidthAndCenterMenuItems() let selectionIndicatorX = menuItems[currentPageIndex].frame.minX selectionIndicatorView.frame = CGRect(x: selectionIndicatorX, y: menuHeight - selectionIndicatorHeight, width: menuItemWidths[currentPageIndex], height: selectionIndicatorHeight) } else if centerMenuItems { startingMenuMargin = ((self.view.frame.width - ((CGFloat(controllerArray.count) * menuItemWidth) + (CGFloat(controllerArray.count - 1) * menuMargin))) / 2.0) - menuMargin if startingMenuMargin < 0.0 { startingMenuMargin = 0.0 } let selectionIndicatorX : CGFloat = self.menuItemWidth * CGFloat(currentPageIndex) + self.menuMargin * CGFloat(currentPageIndex + 1) + self.startingMenuMargin selectionIndicatorView.frame = CGRect(x: selectionIndicatorX, y: self.selectionIndicatorView.frame.origin.y, width: self.selectionIndicatorView.frame.width, height: self.selectionIndicatorView.frame.height) // Recalculate frame for menu items if centered var index : Int = 0 for item : MenuItemView in menuItems as [MenuItemView] { if index == 0 { item.frame = CGRect(x: startingMenuMargin + menuMargin, y: 0.0, width: menuItemWidth, height: menuHeight) } else { item.frame = CGRect(x: menuItemWidth * CGFloat(index) + menuMargin * CGFloat(index + 1) + startingMenuMargin, y: 0.0, width: menuItemWidth, height: menuHeight) } index += 1 } } for view : UIView in controllerScrollView.subviews { view.frame = CGRect(x: self.view.frame.width * CGFloat(currentPageIndex), y: menuHeight, width: controllerScrollView.frame.width, height: self.view.frame.height - menuHeight) } let xOffset : CGFloat = CGFloat(self.currentPageIndex) * controllerScrollView.frame.width controllerScrollView.setContentOffset(CGPoint(x: xOffset, y: controllerScrollView.contentOffset.y), animated: false) let ratio : CGFloat = (menuScrollView.contentSize.width - self.view.frame.width) / (controllerScrollView.contentSize.width - self.view.frame.width) if menuScrollView.contentSize.width > self.view.frame.width { var offset : CGPoint = menuScrollView.contentOffset offset.x = controllerScrollView.contentOffset.x * ratio menuScrollView.setContentOffset(offset, animated: false) } } // Hsoi 2015-02-05 - Running on iOS 7.1 complained: "'NSInternalInconsistencyException', reason: 'Auto Layout // still required after sending -viewDidLayoutSubviews to the view controller. ViewController's implementation // needs to send -layoutSubviews to the view to invoke auto layout.'" // // http://stackoverflow.com/questions/15490140/auto-layout-error // // Given the SO answer and caveats presented there, we'll call layoutIfNeeded() instead. self.view.layoutIfNeeded() } // MARK: - Move to page index /** Move to page at index :param: index Index of the page to move to */ open func moveToPage(_ index: Int) { if index >= 0 && index < controllerArray.count { // Update page if changed if index != currentPageIndex { startingPageForScroll = index lastPageIndex = currentPageIndex currentPageIndex = index didTapMenuItemToScroll = true // Add pages in between current and tapped page if necessary let smallerIndex : Int = lastPageIndex < currentPageIndex ? lastPageIndex : currentPageIndex let largerIndex : Int = lastPageIndex > currentPageIndex ? lastPageIndex : currentPageIndex if smallerIndex + 1 != largerIndex { for i in (smallerIndex + 1)...(largerIndex - 1) { if pagesAddedDictionary[i] != i { addPageAtIndex(i) pagesAddedDictionary[i] = i } } } addPageAtIndex(index) // Add page from which tap is initiated so it can be removed after tap is done pagesAddedDictionary[lastPageIndex] = lastPageIndex } // Move controller scroll view when tapping menu item let duration : Double = Double(scrollAnimationDurationOnMenuItemTap) / Double(1000) UIView.animate(withDuration: duration, animations: { () -> Void in let xOffset : CGFloat = CGFloat(index) * self.controllerScrollView.frame.width self.controllerScrollView.setContentOffset(CGPoint(x: xOffset, y: self.controllerScrollView.contentOffset.y), animated: false) }) } } }
bsd-3-clause
fd619b4b46630ae7e9ce0c148a259dad
52.542121
392
0.592848
6.566671
false
false
false
false
mrgerych/Cuckoo
Generator/Source/CuckooGeneratorFramework/Tokens/InstanceVariable.swift
1
722
// // InstanceVariable.swift // CuckooGenerator // // Created by Filip Dolnik on 30.05.16. // Copyright © 2016 Brightify. All rights reserved. // public struct InstanceVariable: Token { public var name: String public var type: String public var accessibility: Accessibility public var setterAccessibility: Accessibility? public var range: CountableRange<Int> public var nameRange: CountableRange<Int> public var overriding: Bool public var readOnly: Bool { return setterAccessibility == nil } public func isEqual(to other: Token) -> Bool { guard let other = other as? InstanceVariable else { return false } return self.name == other.name } }
mit
c36aade73df75f66c2779f7e53f71dc6
26.730769
74
0.686546
4.563291
false
false
false
false
edx/edx-app-ios
Source/WhatsNewObject.swift
2
1519
// // WhatsNewObject.swift // edX // // Created by Saeed Bashir on 5/2/17. // Copyright © 2017 edX. All rights reserved. // import Foundation fileprivate enum SupportPlatforms: String { case iOS = "ios" } public struct WhatsNew: Equatable { // itemID is property designated to uniquely identify all objects. It is used to resolve the cyclic behaviour issue on WhatsNew Screen if Multiple objects have same title and message. var itemID = 0 var image: UIImage var title: String var message: String var isLast = false public static func == (left: WhatsNew, right: WhatsNew) -> Bool { return left.title == right.title && left.message == right.message && left.itemID == right.itemID } } extension WhatsNew { init?(json: JSON) { guard let imageName = json["image"].string, let title = json["title"].string, let message = json["message"].string, let platforms = json["platforms"].array else { return nil } var isSupportMessage = false for platform in platforms { if platform.string?.lowercased() == SupportPlatforms.iOS.rawValue { isSupportMessage = true break } } if let image = UIImage(named: imageName), isSupportMessage { self.image = image self.title = title self.message = message } else { return nil } } }
apache-2.0
5f2d45870ec5cebe8e3a9f4feaed9e30
27.111111
187
0.586298
4.642202
false
false
false
false
AliSoftware/SwiftGen
Sources/SwiftGenKit/Parsers/Colors/ColorsCLRFileParser.swift
1
886
// // SwiftGenKit // Copyright © 2020 SwiftGen // MIT Licence // import AppKit import Foundation import PathKit extension Colors { final class CLRFileParser: ColorsFileTypeParser { init(options: ParserOptionValues) throws { } static let extensions = ["clr"] private enum Keys { static let userColors = "UserColors" } func parseFile(at path: Path) throws -> Palette { if let colorsList = NSColorList(name: Keys.userColors, fromFile: path.string) { var colors = [String: UInt32]() for colorName in colorsList.allKeys { colors[colorName] = colorsList.color(withKey: colorName)?.hexValue } let name = path.lastComponentWithoutExtension return Palette(name: name, colors: colors) } else { throw ParserError.invalidFile(path: path, reason: "Invalid color list") } } } }
mit
460504dfdad0b313f99c0ed2afb5b29e
22.918919
85
0.655367
4.338235
false
false
false
false
watson-developer-cloud/ios-sdk
Sources/DiscoveryV2/Models/CollectionEnrichment.swift
1
1962
/** * (C) Copyright IBM Corp. 2020. * * 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 /** An object describing an Enrichment for a collection. */ public struct CollectionEnrichment: Codable, Equatable { /** The unique identifier of this enrichment. */ public var enrichmentID: String? /** An array of field names that the enrichment is applied to. If you apply an enrichment to a field from a JSON file, the data is converted to an array automatically, even if the field contains a single value. */ public var fields: [String]? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case enrichmentID = "enrichment_id" case fields = "fields" } /** Initialize a `CollectionEnrichment` with member variables. - parameter enrichmentID: The unique identifier of this enrichment. - parameter fields: An array of field names that the enrichment is applied to. If you apply an enrichment to a field from a JSON file, the data is converted to an array automatically, even if the field contains a single value. - returns: An initialized `CollectionEnrichment`. */ public init( enrichmentID: String? = nil, fields: [String]? = nil ) { self.enrichmentID = enrichmentID self.fields = fields } }
apache-2.0
ffe164e0bd69e8e9ff51126cfa227da8
31.163934
120
0.687054
4.350333
false
false
false
false
obrichak/discounts
discounts/Classes/BarCodeGenerator/RSCornersLayer.swift
1
1743
// // RSCornersLayer.swift // RSBarcodesSample // // Created by R0CKSTAR on 6/13/14. // Copyright (c) 2014 P.D.Q. All rights reserved. // import UIKit import QuartzCore class RSCornersLayer: CALayer { var strokeColor = UIColor.greenColor().CGColor var strokeWidth: CGFloat = 2 var drawingCornersArray: Array<Array<CGPoint>> = [] var cornersArray: Array<[AnyObject]> = [] { willSet { dispatch_async(dispatch_get_main_queue(), { self.setNeedsDisplay() }) } } override func drawInContext(ctx: CGContext!) { objc_sync_enter(self) CGContextSaveGState(ctx) CGContextSetShouldAntialias(ctx, true) CGContextSetAllowsAntialiasing(ctx, true) CGContextSetFillColorWithColor(ctx, UIColor.clearColor().CGColor) CGContextSetStrokeColorWithColor(ctx, strokeColor) CGContextSetLineWidth(ctx, strokeWidth) for corners in cornersArray { for i in 0...corners.count { var idx = i if i == corners.count { idx = 0 } var dict = corners[idx] as NSDictionary let x = CGFloat((dict.objectForKey("X") as NSNumber).floatValue) let y = CGFloat((dict.objectForKey("Y") as NSNumber).floatValue) if i == 0 { CGContextMoveToPoint(ctx, x, y) } else { CGContextAddLineToPoint(ctx, x, y) } } } CGContextDrawPath(ctx, kCGPathFillStroke) CGContextRestoreGState(ctx) objc_sync_exit(self) } }
gpl-3.0
2a5958240ec81955a05905f8130323a0
28.542373
80
0.546758
5.06686
false
false
false
false
NickEntin/SimPermissions
SimPermissions/SimulatorMenuItem.swift
1
2402
// // SimulatorMenuItem.swift // SimPermissions // // Copyright (c) 2016 Nick Entin // // 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 AppKit class SimulatorMenuItem : NSMenuItem { var simulator: SimulatorModel var simulatorsManager: SimulatorManager var refresh: ()->() init(simulator: SimulatorModel, simulatorsManager: SimulatorManager, refresh: ()->()) { self.simulator = simulator self.simulatorsManager = simulatorsManager self.refresh = refresh super.init(title: " \(simulator.name) (\(simulator.system))", action: #selector(selectSimulator), keyEquivalent: "") self.target = self let menuItemView = SimulatorMenuItemView(simulator: simulator) menuItemView.addGestureRecognizer(NSClickGestureRecognizer(target: self, action: #selector(selectSimulator))) view = menuItemView } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override init(title aString: String, action aSelector: Selector, keyEquivalent charCode: String) { fatalError("init(title:action:keyEquivalent:) has not been implemented") } @objc func selectSimulator(sender: AnyObject) { simulatorsManager.activeSimulator = simulator refresh() } }
mit
d14869bc3efe9585a1926c12fed796ba
39.711864
124
0.710241
4.765873
false
false
false
false
jarjarapps/berrysigner
berrysigner/ImageStatusController.swift
1
1078
// // ImageStatusController.swift // berrysigner // // Created by Maciej Gibas on 1/15/17. // Copyright © 2017 Maciej Gibas. All rights reserved. // import Foundation import UIKit class ImageStatusController{ var undoStack: NSMutableArray = NSMutableArray() var redoStack: NSMutableArray = NSMutableArray() var isUndoAvailable: Bool{ get { return self.undoStack.count>0 } } var isRedoAvailable: Bool{ get { return self.redoStack.count>0 } } func save(image: UIImage){ self.undoStack.add(image) } func undo() -> UIImage{ self.redoStack.add(self.undoStack.lastObject as! UIImage) self.undoStack.removeLastObject() if (self.undoStack.count==0){ return UIImage() } return self.undoStack.lastObject as!UIImage } func redo() -> UIImage{ let result = self.redoStack.lastObject as! UIImage self.redoStack.removeLastObject() self.undoStack.add(result) return result } }
unlicense
ba1acac6d9f12b9ee951f35a5404371a
23.477273
65
0.61467
4.290837
false
false
false
false
s-aska/Justaway-for-iOS
Justaway/TwitterText.swift
1
1044
// // TwitterText.swift // Justaway // // Created by Shinichiro Aska on 4/1/16. // Copyright © 2016 Shinichiro Aska. All rights reserved. // import Foundation class TwitterText { // swiftlint:disable:next force_try static let linkDetector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) class func count(_ text: String, hasImage: Bool) -> Int { let textLength = text.characters.count // 🍣 is 1 let objcLength = text.utf16.count // 🍣 is 2 let objcText = text as NSString let objcRange = NSRange(location: 0, length: objcLength) let matches = linkDetector.matches(in: text, options: [], range: objcRange) let urlLength = matches .map { objcText.substring(with: $0.range) as String } .map { $0.characters.count } .reduce(0, +) let shortURLLength = matches.count * 23 let imageURLLength = hasImage ? 24 : 0 return textLength - urlLength + shortURLLength + imageURLLength } }
mit
05ec4aa5aaf60a25d2ee639db4d2b803
29.5
105
0.644166
4.050781
false
false
false
false
Arty-Maly/Volna
Pods/SwiftMonkey/SwiftMonkey/Monkey.swift
1
12025
// // Monkey.swift // Fleek // // Created by Dag Agren on 16/03/16. // Copyright © 2016 Zalando SE. All rights reserved. // import UIKit import XCTest /** A general-purpose class for implementing randomised UI tests. This class lets you schedule blocks to be run at random or fixed intervals, and provides helper functions to generate random coordinates. It has several extensions that implement actual event generation, using different methods. For normal usage, you will want to look at for instance the XCTest private API based extension. If all you want to do is geneate some events and you do not care about the finer details, you can just use a test case like the following: ``` func testMonkey() { let application = XCUIApplication() // Workaround for bug in Xcode 7.3. Snapshots are not properly updated // when you initially call app.frame, resulting in a zero-sized rect. // Doing a random query seems to update everything properly. // TODO: Remove this when the Xcode bug is fixed! _ = application.descendants(matching: .any).element(boundBy: 0).frame // Initialise the monkey tester with the current device // frame. Giving an explicit seed will make it generate // the same sequence of events on each run, and leaving it // out will generate a new sequence on each run. let monkey = Monkey(frame: application.frame) //let monkey = Monkey(seed: 123, frame: application.frame) // Add actions for the monkey to perform. We just use a // default set of actions for this, which is usually enough. // Use either one of these but maybe not both. // XCTest private actions seem to work better at the moment. // UIAutomation actions seem to work only on the simulator. monkey.addDefaultXCTestPrivateActions() //monkey.addDefaultUIAutomationActions() // Occasionally, use the regular XCTest functionality // to check if an alert is shown, and click a random // button on it. monkey.addXCTestTapAlertAction(interval: 100, application: application) // Run the monkey test indefinitely. monkey.monkeyAround() } ``` */ public class Monkey { public typealias ActionClosure = () -> Void var r: Random let frame: CGRect var randomActions: [(accumulatedWeight: Double, action: ActionClosure)] var totalWeight: Double var regularActions: [(interval: Int, action: ActionClosure)] var actionCounter = 0 /** Create a Monkey object with a randomised seed. This instance will generate a different stream of events each time it is created. There is an XCTest bug to be aware of when finding the frame to use. Here is an example of how to work around this problem: ``` let application = XCUIApplication() // Workaround for bug in Xcode 7.3 and later. Snapshots are not properly // updated when you initially call app.frame, resulting in a zero-sized rect. // Doing a random query seems to update everything properly. _ = application.descendants(matching: .any).element(boundBy: 0).frame let monkey = Monkey(frame: application.frame) ``` - parameter frame: The frame to generate events in. Should be set to the size of the device being tested. */ public convenience init(frame: CGRect) { let time = Date().timeIntervalSinceReferenceDate let seed = UInt32(UInt64(time * 1000) & 0xffffffff) self.init(seed: seed, frame: frame) } /** Create a Monkey object with a fixed seed. This instance will generate the exact same stream of events each time it is created. Create a Monkey object with a randomised seed. This instance will generate a different stream of events each time it is created. There is an XCTest bug to be aware of when finding the frame to use. Here is an example of how to work around this problem: ``` let application = XCUIApplication() // Workaround for bug in Xcode 7.3 and later. Snapshots are not properly // updated when you initially call app.frame, resulting in a zero-sized rect. // Doing a random query seems to update everything properly. _ = application.descendants(matching: .any).element(boundBy: 0).frame let monkey = Monkey(seed: 0, frame: application.frame) ``` - parameter seed: The random seed to use. Each value will generate a different stream of events. - parameter frame: The frame to generate events in. Should be set to the size of the device being tested. */ public init(seed: UInt32, frame: CGRect) { self.r = Random(seed: seed) self.frame = frame self.randomActions = [] self.totalWeight = 0 self.regularActions = [] } /** Generate a number of random events. - Parameter iterations: The number of random events to generate. Does not include any fixed interval events that may also be generated. */ public func monkeyAround(iterations: Int) { for _ in 1 ... iterations { actRandomly() actRegularly() } } /// Generate random events or fixed-interval events based forever, for a specific duration or until the app crashes. /// /// - Parameter duration: The duration for which to generate the random events. /// Set to `.infinity` by default. public func monkeyAround(forDuration duration: TimeInterval = .infinity) { let monkeyTestingTime = Date().timeIntervalSince1970 repeat { actRandomly() actRegularly() } while ((Date().timeIntervalSince1970 - monkeyTestingTime) < duration) } /// Generate one random event. public func actRandomly() { let x = r.randomDouble() * totalWeight for action in randomActions { if x < action.accumulatedWeight { action.action() return } } } /// Generate any pending fixed-interval events. public func actRegularly() { actionCounter += 1 for action in regularActions { if actionCounter % action.interval == 0 { action.action() } } } /** Add a block for generating randomised events. - parameter weight: The relative probability of this event being generated. Can be any value larger than zero. Probabilities will be normalised to the sum of all relative probabilities. - parameter action: The block to run when this event is generated. */ public func addAction(weight: Double, action: @escaping ActionClosure) { totalWeight += weight randomActions.append((accumulatedWeight: totalWeight, action: actInForeground(action))) } /** Add a block for fixed-interval events. - parameter interval: How often to generate this event. One of these events will be generated after this many randomised events have been generated. - parameter action: The block to run when this event is generated. */ public func addAction(interval: Int, action: @escaping ActionClosure) { regularActions.append((interval: interval, action: actInForeground(action))) } /** Wrap your action with this function to make sure your actions are dispatched inside the app under test and not in some other app that the Monkey randomly opened. */ func actInForeground(_ action: @escaping ActionClosure) -> ActionClosure { return { guard #available(iOS 9.0, *) else { action() return } let closure: ActionClosure = { if XCUIApplication().state != .runningForeground { XCUIApplication().activate() } action() } if Thread.isMainThread { closure() } else { DispatchQueue.main.async(execute: closure) } } } /** Generate a random `Int`. - parameter lessThan: The returned value will be less than this value, and greater than or equal to zero. */ public func randomInt(lessThan: Int) -> Int { return r.randomInt(lessThan: lessThan) } /** Generate a random `UInt`. - parameter lessThan: The returned value will be less than this value, and greater than or equal to zero. */ public func randomUInt(lessThan: UInt) -> UInt { return r.randomUInt(lessThan: lessThan) } /** Generate a random `CGFloat`. - parameter lessThan: The returned value will be less than this value, and greater than or equal to zero. */ public func randomCGFloat(lessThan: CGFloat = 1) -> CGFloat { return CGFloat(r.randomDouble(lessThan: Double(lessThan))) } /// Generate a random `CGPoint` inside the frame of the app. public func randomPoint() -> CGPoint { return randomPoint(inRect: frame) } /** Generate a random `CGPoint` inside the frame of the app, avoiding the areas at the top and bottom of the screen that trigger a panel pull-out. */ public func randomPointAvoidingPanelAreas() -> CGPoint { let topHeight: CGFloat = 20 let bottomHeight: CGFloat = 20 let frameWithoutTopAndBottom = CGRect(x: 0, y: topHeight, width: frame.width, height: frame.height - topHeight - bottomHeight) return randomPoint(inRect: frameWithoutTopAndBottom) } /** Generate a random `CGPoint` inside the given `CGRect`. - parameter inRect: The rect within which to pick the point. */ public func randomPoint(inRect rect: CGRect) -> CGPoint { return CGPoint(x: rect.origin.x + randomCGFloat(lessThan: rect.size.width), y: rect.origin.y + randomCGFloat(lessThan: rect.size.height)) } /// Generate a random `CGRect` inside the frame of the app. public func randomRect() -> CGRect { return rect(around: randomPoint(), inRect: frame) } /** Generate a random `CGRect` inside the frame of the app, sized to a given fraction of the whole frame. - parameter sizeFraction: The fraction of the size of the frame to use as the of the area for generated points. */ public func randomRect(sizeFraction: CGFloat) -> CGRect { return rect(around: randomPoint(), sizeFraction: sizeFraction, inRect: frame) } /** Generate an array of random `CGPoints` in a loose cluster. - parameter count: Number of points to generate. */ public func randomClusteredPoints(count: Int) -> [CGPoint] { let centre = randomPoint() let clusterRect = rect(around: centre, inRect: frame) var points = [ centre ] for _ in 1..<count { points.append(randomPoint(inRect: clusterRect)) } return points } func rect(around point: CGPoint, sizeFraction: CGFloat = 3, inRect: CGRect) -> CGRect { let size: CGFloat = min(frame.size.width, frame.size.height) / sizeFraction let x0: CGFloat = (point.x - frame.origin.x) * (frame.size.width - size) / frame.size.width + frame.origin.x let y0: CGFloat = (point.y - frame.origin.y) * (frame.size.height - size) / frame.size.width + frame.origin.y return CGRect(x: x0, y: y0, width: size, height: size) } func sleep(_ seconds: Double) { if seconds>0 { usleep(UInt32(seconds * 1000000.0)) } } }
gpl-3.0
906b5b3ee78afcd0f7b2b99e8d778f8e
34.157895
146
0.62658
4.756329
false
true
false
false
Cereopsis/Doodles
Graph.swift
1
3786
/* The MIT License (MIT) Copyright (c) 2015 Cereopsis 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 enum Node { case Leaf(Int) indirect case Fork(Node, Node) /// Return the value of the first leaf /// /// e.g .Fork(.Leaf(1), .Fork(.Leaf(2), .Leaf(3))) -> 1 func head() -> Int { switch self { case .Leaf(let i): return i case .Fork(let leaf, _): return leaf.head() } } /// Return the value of the last leaf /// /// e.g .Fork(.Leaf(1), .Fork(.Leaf(2), .Leaf(3))) -> 3 func tail() -> Int { switch self { case .Leaf(let i): return i case .Fork(_, let fork): return fork.tail() } } /// Return the set of all integers in this node func vertices() -> Set<Int> { switch self { case .Leaf(let i): return Set([i]) case .Fork(let a, let b): return a.vertices().union(b.vertices()) } } /// Return a count of nodes func depth() -> Int { switch self { case .Leaf(_): return 1 case .Fork(let a, let b): return a.depth() + b.depth() } } } class Edge { let vertex: Int var connections: [Int] = [] init(vertex: Int) { self.vertex = vertex } /// Connect two vertices. `self` is considered the owner, which makes this a directed graph? func addConnection(connection: Int) { if connection != vertex && !connections.contains(connection) { connections.append(connection) } } /// Returns an enumeration of all connected vertices in Node.Fork(.Leaf(_), .Leaf(_)) format func connectionsTo(vertices: Set<Int>) -> [Node] { return vertices .intersect(connections) .map{ Node.Fork(.Leaf(vertex), .Leaf($0)) } } /// Returns true if `vertex` is contained in `connections` func isConnected(vertex: Int) -> Bool { return connections.contains(vertex) } } class Graph { let vertices: Range<Int> var edges: [Int: Edge] = [:] init(vertices: Range<Int>) { self.vertices = vertices } subscript(key: Int) -> Edge? { return edges[key] } /// Create an Edge object for each connected pair func connect(src: Int, dest: Int) { if vertices.contains(src) && vertices.contains(dest) { if let edge = edges[src] { edge.addConnection(dest) } else { let edge = Edge(vertex: src) edge.addConnection(dest) edges[src] = edge } } } }
mit
1f1e6caf688c97e4455304b71d970292
27.253731
96
0.583201
4.282805
false
false
false
false
WLChopSticks/weibo-swift-
weibo(swift)/weibo(swift)/Classes/Model/CHSStatus.swift
2
2095
// // CHSStatus.swift // weibo(swift) // // Created by 王 on 15/12/18. // Copyright © 2015年 王. All rights reserved. // import UIKit class CHSStatus: NSObject { //微博创建时间 var created_at: String? //微博ID var id:Int64 = 0 //微博信息内容 var text: String? //微博来源 var source: String? //缩略图片地址,没有时不返回此字段 var thumbnail_pic: String? //用户信息模型 var user: CHSUser? //每个状态的配图 var pic_urls: [[String : String]]? { didSet { guard let urls = pic_urls else { print("图片的URL为空") return } imageURL = [NSURL]() for URLDict in urls { let URLString = URLDict["thumbnail_pic"]! let url = NSURL(string: URLString)! imageURL?.append(url) } } } var imageURL: [NSURL]? //转发微博的内容 var retweeted_status: CHSStatus? //字典转模型 init(dict: [String: AnyObject]) { super.init() setValuesForKeysWithDictionary(dict) } //在字典转模型的过程中,筛选出用户的模型再转一次 override func setValue(value: AnyObject?, forKey key: String) { super.setValue(value, forKey: key) if key == "user" { guard let dict = value as? [String : AnyObject] else { return } user = CHSUser(dict: dict) } if key == "retweeted_status" { guard let dict = value as? [String : AnyObject] else { return } retweeted_status = CHSStatus(dict: dict) } } //为没有属性的键值对的方法 override func setValue(value: AnyObject?, forUndefinedKey key: String) { } //重写description方法 override var description:String { let key = ["user"] return dictionaryWithValuesForKeys(key).description } }
mit
dd1c5766ed72a2e720a0c06cd8d7adf2
21.428571
79
0.518577
4.113537
false
false
false
false
2RKowski/two-blobs
TwoBlobs/AVPlayerItem+Extensions.swift
1
1579
// // AVPlayerItem+Extensions.swift // TwoBlobs // // Created by Lësha Turkowski on 18/01/2017. // Copyright © 2017 Amblyofetus. All rights reserved. // import AVFoundation import RxSwift import RxCocoa enum AVPlayerItemError: Error { case preparationError } extension AVPlayerItem { func prepare() -> Observable<Void> { switch status { case .failed: return .error(AVPlayerItemError.preparationError) case .readyToPlay: return .justCompleted() default: break } // FIXME: // Using unowned here may be potentially dangerous... // Although! prepare() will always be called on an existing instance, so it's kind of okay?? return Observable<Void>.create { [unowned self] o in _ = self .rx.observe(AVPlayerItemStatus.self, "status") .filter { $0 == .readyToPlay || $0 == .failed } .take(1) // FIXME: should I pass observer as weak here or something?? .subscribe(onNext: { status in // FIXME: I hate explicit unwrapping, but filter function makes sure it's not nil switch status! { case .failed: o.onError(AVPlayerItemError.preparationError) default: o.onCompleted() } }) return Disposables.create() } } }
mit
d9d830ed0e9a62ae64e1e03477167d6b
28.203704
101
0.518706
5.136808
false
false
false
false
n-miyo/SwiftTableViewSample
SwiftTableViewSample/TableViewController.swift
1
3681
// -*- mode:swift -*- import UIKit class TableViewController: UITableViewController { let CellIdentifier = "Cell" let SectionHeaderHeight : CGFloat = 40.0 let SectionFooterHeight : CGFloat = 20.0 let SectionDelimiterMargin : CGFloat = 10.0 lazy var objects: Array<(String, Array<String>, String)> = { var a0 = ("Apple", ["AppleII", "Macintosh", "iMac"], "Desktop") var a1 = ("NEC", ["PC-2001", "PC-8201", "PC-98HA"], "Handheld") var a2 = ("CASIO", ["PB-100", "PB-120", "PB-1000C"], "Pocket") return [a0, a1, a2] }() override init(style: UITableViewStyle) { super.init(style: style) } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func awakeFromNib() { super.awakeFromNib() } override func viewDidLoad() { super.viewDidLoad() tableView.registerClass( UITableViewCell.self, forCellReuseIdentifier:CellIdentifier) edgesForExtendedLayout = .None; extendedLayoutIncludesOpaqueBars = false; automaticallyAdjustsScrollViewInsets = false; } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // #pragma mark - Table view data source override func numberOfSectionsInTableView(tableView: UITableView?) -> Int { return objects.count } override func tableView( tableView: UITableView?, numberOfRowsInSection section: Int) -> Int { let (_, d, _) = objects[section] return d.count } override func tableView( tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier( CellIdentifier, forIndexPath:indexPath) as UITableViewCell let (_, d, _) = objects[indexPath.section] cell.textLabel.text = d[indexPath.row] return cell } // #pragma mark - Table view delegate override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return SectionHeaderHeight } override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return SectionFooterHeight } override func tableView( tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let (h, _, _) = objects[section] // create the label var headerLabel = UILabel(frame:CGRectZero) headerLabel.backgroundColor = UIColor.clearColor() headerLabel.font = UIFont(name:"HelveticaNeue-Light", size:14.0) headerLabel.frame = CGRectMake(0, 0, tableView.frame.width-SectionDelimiterMargin, SectionHeaderHeight) headerLabel.textAlignment = .Right headerLabel.text = h headerLabel.textColor = UIColor.darkGrayColor() // create the parent view that will hold header Label var customView = UIView(frame:headerLabel.frame) customView.addSubview(headerLabel) return customView } override func tableView( tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { let (_, _, f) = objects[section] // create the label var footerLabel = UILabel(frame:CGRectZero) footerLabel.backgroundColor = UIColor.clearColor() footerLabel.font = UIFont(name:"HelveticaNeue-Light", size:12.0) footerLabel.frame = CGRectMake(0, 0, tableView.frame.width-SectionDelimiterMargin, SectionFooterHeight) footerLabel.textAlignment = .Right footerLabel.text = f footerLabel.textColor = UIColor.lightGrayColor() // create the parent view that will hold header Label var customView = UIView(frame:footerLabel.frame) customView.addSubview(footerLabel) return customView } } // EOF
mit
c1f7fd6d6a615e3f062eecb364dc6642
27.984252
77
0.701168
4.63602
false
false
false
false
or1onsli/Fou.run-
MusicRun/AudioAnalysis.swift
1
10810
// // AudioAnalysisLite.swift // Fou.run() // // Copyright © 2016 Shock&Awe. All rights reserved. // import Foundation import AudioKit func fftAnalysis() { // Quante classi di frequenze vogliamo considerare nel nostro calcolo e su quanti istanti precedenti al corrente vogliamo mediare per ottenere una soglia let totalFrequencies = 20 let numerosita = 400 //Da qui, tutto codice per istanziare e far partire il player var file: AKAudioFile var player1: AKAudioPlayer? do { file = try AKAudioFile.init(readFileName: "daft.mp3") do{ player1 = try AKAudioPlayer(file: file) }catch{} } catch {} if let player = player1 { let variatore = AKVariSpeed(player) player.looping = false variatore.rate = 1.0 AudioKit.output = variatore AudioKit.start() player.play() print(player.duration) print("musica!") let fft = AKFFTTap(player) // medie ha la stessa dimensione di "totalfrequencies". I suoi valori, ad ogni istante, corrisponderanno alla media di un numero di campionamenti precedenti pari a "numerosita" var medie = [Double]() // un contatore solo per vedere quante volte viene ripetuto il loop var counter: Int = 0 // in questo vettore, ad ogni istante, vengono registrati i valori delle singole frequenze, ai fini di calcolare le medie. Ad ogni loop viene poi scritto in "tabellaMedie" e ripulito non appena ne inizia un altro. var colonnaIstante = [Double]() // come il precedente, ma finalizzato a registrare tutti i dati del pezzo. Il primo elemento sarà il tempo in secondi all'interno della canzone var colonnaIstanteConIndice = [Double]() // in tabellaMedie, il primo indice corrisponde al numero del campionamento (quindi al tempo nella canzone), e ad ogni indice corrisponde un vettore colonnaIstante. A differenza di tabellaValori, il numero di istanti considerati è fissato a "numerosita", e ad ogni loop viene eliminato il più vecchio ed introdotto il più recente. var tabellaMedie = [[Double]]() //questo è il modello della struttura dati definitiva. Ad ogni indice corrisponde un dictionary dove gli elementi sono time, low, mid e high. Alla classe di frequenza corrisponde un intero arbitrario vagamente proporzionale all'intensità. var tabellaDictionary = [NSMutableDictionary]() // In queste tabelle i valori sono direttamente i tempi in cui nella canzone si verificano gli eventi. var tabellaLow = [Double]() var tabellaMid = [Double]() var tabellaHigh = [Double]() for _ in 0..<totalFrequencies { medie.append(0) colonnaIstante.append(0) } for _ in 0...numerosita { tabellaMedie.append(colonnaIstante) } Timer.scheduledTimer(withTimeInterval: 0.01, repeats: true, block: { (timer) in counter += 1 //Svuotiamo l'array con le informazioni sull'istante corrente colonnaIstanteConIndice.removeAll() //Per prima cosa, gli aggiungiamo il currentTime nella canzone colonnaIstanteConIndice.append(player.currentTime) //Aggiorniamo la tabella per calcolare le medie, togliendo la più vecchia ed aggiungendo la più nuova tabellaMedie.remove(at: numerosita) tabellaMedie.insert(colonnaIstante, at: 0) // Qui stiamo ciclando tra tutte le frequenze. Cancelliamo il precedente valore della media e lo ricalcoliamo, andando nella tabellaMedie, fissando il secondo indice che corrisponde alla frequenza e variando il primo, che invece corrisponde al tempo. Ricordiamoci che la tabellaMedie ha grandezza fissata e che i suoi vettori vengono continuamente aggiornati, quindi quando si parla di tempo si fa riferimento sempre agli ultimi "numerosita" campionamenti. for index in 0..<totalFrequencies { medie[index] = 0 colonnaIstante[index] = fft.fftData[index] // la riga seguente è commentata perchè, ovviamente, alternativa ad append[1] // colonnaIstanteConIndice.append(fft.fftData[index]) for k in 0...numerosita { medie[index] += tabellaMedie[k][index]/numerosita } //Dunque, se il valore corrente per la determinata frequenza è maggiore della media degli ultimi "numerosita" valori, allore registriamo l'evento. Come sempre, ignoriamo le immagini. if fft.fftData[index] > medie[index]{ colonnaIstanteConIndice.append(1) } else { colonnaIstanteConIndice.append(0) } } // La nostra colonnaIstanteConIndice ora è completa (primo elemento tempo + tanti elementi quanto totalFrequencies) e la possiamo aggiungere alla tabellaDictionary. // Nelle tabelle Low, Mid e High, se le funzioni di verifica restituiscono true, aggiungiamo il tempo. // Tutto questo, se la canzone non è finita; altrimenti, se la canzone è finita, vediamo un attimo al terminale cosa ne è uscito. if player.endTime - player.currentTime > 0.3 { tabellaDictionary.append(fillDictionary(items: colonnaIstanteConIndice)) // print(player.endTime - player.currentTime) if fillLows(items: colonnaIstanteConIndice) { tabellaLow.append(player.currentTime) } if fillMids(items: colonnaIstanteConIndice) { tabellaMid.append(player.currentTime) } if fillHighs(items: colonnaIstanteConIndice){ tabellaHigh.append(player.currentTime) } } else { minchia(tab: tabellaDictionary) print(tabellaDictionary.count) print(tabellaLow.count) print(tabellaMid.count) print(tabellaHigh.count) timer.invalidate() player.stop() } }) } else { print("somehow player not init")} } func fillDictionary(items: [Double], elements: Int) -> NSMutableDictionary { let dict = NSMutableDictionary() for i in 0..<elements { if i == 0 { dict.setObject(items[i], forKey: "time" as NSCopying) } else { dict.setObject(items[i], forKey: "f\(i)" as NSCopying) } } return dict } func fillDictionaryNoTime(items:[Double]) -> NSMutableDictionary { let dict = NSMutableDictionary() var bassi: Double = 0 var medi: Double = 0 var alti: Double = 0 for i in 1...3 { bassi += items[i] } for i in 4...10 { medi += items[i] } for i in 11...20 { alti += items[i] } dict.setObject(bassi, forKey: "low" as NSCopying) dict.setObject(medi, forKey: "mid" as NSCopying) dict.setObject(alti, forKey: "high" as NSCopying) return dict } func fillDictionary(items: [Double]) -> NSMutableDictionary { let dict = NSMutableDictionary() var bassi: Double = 0 var medi: Double = 0 var alti: Double = 0 for i in 1...3 { bassi += items[i] } for i in 4...10 { medi += items[i] } for i in 11...20 { alti += items[i] } dict.setObject(items[0], forKey: "time" as NSCopying) dict.setObject(bassi, forKey: "low" as NSCopying) dict.setObject(medi, forKey: "mid" as NSCopying) dict.setObject(alti, forKey: "high" as NSCopying) return dict } func fillLows(items: [Double]) -> Bool { var bassi: Double = 0 for i in 1...3 { bassi += items[i] } if bassi > 2 { return true } else { return false} } func fillMids(items: [Double]) -> Bool { var medi: Double = 0 for i in 4...10 { medi += items[i] } if medi > 5 { return true } else { return false} } func fillHighs(items: [Double]) -> Bool { var alti: Double = 0 for i in 11...20 { alti += items[i]} if alti > 7 { return true } else { return false} } func minchia(tab: [NSMutableDictionary]) { do { let minchia = FileManager() let documentUrl = try minchia.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) let jsonPath = documentUrl.appendingPathComponent("json.json") let jsonHandle = documentUrl.appendingPathComponent("jsonHandle.json") minchia.createFile(atPath: jsonPath.relativePath, contents: nil, attributes: nil) minchia.createFile(atPath: jsonHandle.relativePath, contents: nil, attributes: nil) print(jsonPath.relativePath) print(jsonHandle.relativePath) let file = FileHandle(forWritingAtPath: jsonHandle.relativePath) let parsed = try JSONSerialization.data(withJSONObject: tab, options: .prettyPrinted) file?.write(parsed) let stream = OutputStream(toFileAtPath: jsonPath.relativePath, append: true) stream?.open() JSONSerialization.writeJSONObject(tab, to: stream!, options: .prettyPrinted, error: nil) stream?.close() } catch { print("errore") } } func minchia(tab: NSMutableDictionary) { do { let minchia = FileManager() let documentUrl = try minchia.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) let jsonPath = documentUrl.appendingPathComponent("json.json") let jsonHandle = documentUrl.appendingPathComponent("jsonHandle.json") minchia.createFile(atPath: jsonPath.relativePath, contents: nil, attributes: nil) minchia.createFile(atPath: jsonHandle.relativePath, contents: nil, attributes: nil) print(jsonPath.relativePath) print(jsonHandle.relativePath) let file = FileHandle(forWritingAtPath: jsonHandle.relativePath) let parsed = try JSONSerialization.data(withJSONObject: tab, options: .prettyPrinted) file?.write(parsed) let stream = OutputStream(toFileAtPath: jsonPath.relativePath, append: true) stream?.open() JSONSerialization.writeJSONObject(tab, to: stream!, options: .prettyPrinted, error: nil) stream?.close() } catch { print("errore") } }
mit
9c259261bca0ff00e6008c1f27ba746d
35.83959
471
0.618862
3.856377
false
false
false
false
sharath-cliqz/browser-ios
Storage/Bookmarks/Trees.swift
2
11425
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared private let log = Logger.syncLogger // MARK: - Defining a tree structure for syncability. public enum BookmarkTreeNode: Equatable { indirect case folder(guid: GUID, children: [BookmarkTreeNode]) case nonFolder(guid: GUID) case unknown(guid: GUID) // Because shared associated values between enum cases aren't possible. public var recordGUID: GUID { switch self { case let .folder(guid, _): return guid case let .nonFolder(guid): return guid case let .unknown(guid): return guid } } public var isRoot: Bool { return BookmarkRoots.All.contains(self.recordGUID) } public var isUnknown: Bool { if case .unknown = self { return true } return false } public var children: [BookmarkTreeNode]? { if case let .folder(_, children) = self { return children } return nil } public func hasChildList(_ nodes: [BookmarkTreeNode]) -> Bool { if case let .folder(_, ours) = self { return ours.elementsEqual(nodes, by: { $0.recordGUID == $1.recordGUID }) } return false } public func hasSameChildListAs(_ other: BookmarkTreeNode) -> Bool { if case let .folder(_, ours) = self { if case let .folder(_, theirs) = other { return ours.elementsEqual(theirs, by: { $0.recordGUID == $1.recordGUID }) } } return false } // Returns false for unknowns. public func isSameTypeAs(_ other: BookmarkTreeNode) -> Bool { switch self { case .folder: if case .folder = other { return true } case .nonFolder: if case .nonFolder = other { return true } default: return false } return false } } public func == (lhs: BookmarkTreeNode, rhs: BookmarkTreeNode) -> Bool { switch lhs { case let .folder(guid, children): if case let .folder(rguid, rchildren) = rhs { return guid == rguid && children == rchildren } return false case let .nonFolder(guid): if case let .nonFolder(rguid) = rhs { return guid == rguid } return false case let .unknown(guid): if case let .unknown(rguid) = rhs { return guid == rguid } return false } } typealias StructureRow = (parent: GUID, child: GUID, type: BookmarkNodeType?) // This is really a forest, not a tree: it can have multiple 'subtrees' // and carries a collection of associated values. public struct BookmarkTree { // Records with no parents. public let subtrees: [BookmarkTreeNode] // Record GUID -> record. public let lookup: [GUID: BookmarkTreeNode] // Child GUID -> parent GUID. public let parents: [GUID: GUID] // Records that appear in 'lookup' because they're modified, but aren't present // in 'subtrees' because their parent didn't change. public let orphans: Set<GUID> // Records that have been deleted. public let deleted: Set<GUID> // Every record that's changed but not deleted. public let modified: Set<GUID> // Nodes that are present in this tree but aren't present in the source. // In practical terms, this will be roots that we pretend exist in // the mirror for purposes of three-way merging. public let virtual: Set<GUID> // Accessor for all top-level folders' GUIDs. public var subtreeGUIDs: Set<GUID> { return Set(self.subtrees.map { $0.recordGUID }) } public var isEmpty: Bool { return self.subtrees.isEmpty && self.deleted.isEmpty } public static func emptyTree() -> BookmarkTree { return BookmarkTree(subtrees: [], lookup: [:], parents: [:], orphans: Set<GUID>(), deleted: Set<GUID>(), modified: Set<GUID>(), virtual: Set<GUID>()) } public static func emptyMirrorTree() -> BookmarkTree { return mappingsToTreeForStructureRows([], withNonFoldersAndEmptyFolders: [], withDeletedRecords: Set(), modifiedRecords: Set(), alwaysIncludeRoots: true) } public func includesOrDeletesNode(_ node: BookmarkTreeNode) -> Bool { return self.includesOrDeletesGUID(node.recordGUID) } public func includesNode(_ node: BookmarkTreeNode) -> Bool { return self.includesGUID(node.recordGUID) } public func includesOrDeletesGUID(_ guid: GUID) -> Bool { return self.includesGUID(guid) || self.deleted.contains(guid) } public func includesGUID(_ guid: GUID) -> Bool { return self.lookup[guid] != nil } public func find(_ guid: GUID) -> BookmarkTreeNode? { return self.lookup[guid] } public func find(_ node: BookmarkTreeNode) -> BookmarkTreeNode? { return self.find(node.recordGUID) } /** * True if there is one subtree, and it's the Root, when overlayed. * We assume that the mirror will always be consistent, so what * this really means is that every subtree in this tree is *present* * in the comparison tree, or is itself rooted in a known root. * * In a fully rooted tree there can be no orphans; if our partial tree * includes orphans, they must be known by the comparison tree. */ public func isFullyRootedIn(_ tree: BookmarkTree) -> Bool { // We don't compare against tree.deleted, because you can't *undelete*. return self.orphans.every(tree.includesGUID) && self.subtrees.every { subtree in tree.includesNode(subtree) || subtree.isRoot } } // If this tree contains the root, return it. public var root: BookmarkTreeNode? { return self.find(BookmarkRoots.RootGUID) } // Recursively process an input set of structure pairs to yield complete subtrees, // assembling those subtrees to make a minimal set of trees. static func mappingsToTreeForStructureRows(_ mappings: [StructureRow], withNonFoldersAndEmptyFolders nonFoldersAndEmptyFolders: [BookmarkTreeNode], withDeletedRecords deleted: Set<GUID>, modifiedRecords modified: Set<GUID>, alwaysIncludeRoots: Bool) -> BookmarkTree { // Accumulate. var nodes: [GUID: BookmarkTreeNode] = [:] var parents: [GUID: GUID] = [:] var remainingFolders = Set<GUID>() // `tops` is the collection of things that we think are the roots of subtrees (until // we're proved wrong). We add GUIDs here when we don't know their parents; if we get to // the end and they're still here, they're roots. var tops = Set<GUID>() var notTops = Set<GUID>() var orphans = Set<GUID>() var virtual = Set<GUID>() // We can't immediately build the final tree, because we need to do it bottom-up! // So store structure, which we can figure out flat. var pseudoTree: [GUID: [GUID]] = mappings.groupBy({ $0.parent }, transformer: { $0.child }) // Deal with the ones that are non-structural first. nonFoldersAndEmptyFolders.forEach { node in let guid = node.recordGUID nodes[guid] = node switch node { case .folder: // If we end up here, it's because this folder is empty, and it won't // appear in structure. Assert to make sure that's true! assert(pseudoTree[guid] == nil) pseudoTree[guid] = [] // It'll be a top unless we find it as a child in the structure somehow. tops.insert(guid) default: orphans.insert(guid) } } // Precompute every leaf node. mappings.forEach { row in parents[row.child] = row.parent remainingFolders.insert(row.parent) tops.insert(row.parent) // None of the children we've seen can be top, so remove them. notTops.insert(row.child) if let type = row.type { switch type { case .folder: // The child is itself a folder. remainingFolders.insert(row.child) default: nodes[row.child] = BookmarkTreeNode.nonFolder(guid: row.child) } } else { // This will be the case if we've shadowed a folder; we indirectly reference the original rows. nodes[row.child] = BookmarkTreeNode.unknown(guid: row.child) } } // When we build the mirror, we always want to pretend it has our stock roots. // This gives us our shared basis from which to merge. // Doing it here means we don't need to protect the mirror database table. if alwaysIncludeRoots { func setVirtual(_ guid: GUID) { if !remainingFolders.contains(guid) && nodes[guid] == nil { virtual.insert(guid) } } // Note that we don't check whether the input already contained the roots; we // never change them, so it's safe to do this unconditionally. setVirtual(BookmarkRoots.RootGUID) BookmarkRoots.RootChildren.forEach { setVirtual($0) } pseudoTree[BookmarkRoots.RootGUID] = BookmarkRoots.RootChildren tops.insert(BookmarkRoots.RootGUID) notTops.formUnion(BookmarkRoots.RootChildren) remainingFolders.formUnion(BookmarkRoots.All) BookmarkRoots.RootChildren.forEach { parents[$0] = BookmarkRoots.RootGUID } } tops.subtract(notTops) orphans.subtract(notTops) // Recursive. (Not tail recursive, but trees shouldn't be deep enough to blow the stack….) func nodeForGUID(_ guid: GUID) -> BookmarkTreeNode { if let already = nodes[guid] { return already } if !remainingFolders.contains(guid) { let node = BookmarkTreeNode.unknown(guid: guid) nodes[guid] = node return node } // Removing these eagerly prevents infinite recursion in the case of a cycle. let childGUIDs = pseudoTree[guid] ?? [] pseudoTree.removeValue(forKey: guid) remainingFolders.remove(guid) let node = BookmarkTreeNode.folder(guid: guid, children: childGUIDs.map(nodeForGUID)) nodes[guid] = node return node } // Process every record. // Do the not-tops first: shallower recursion. notTops.forEach({ nodeForGUID($0) }) let subtrees = tops.map(nodeForGUID) // These will all be folders. // Whatever we're left with in `tops` is the set of records for which we // didn't process a parent. return BookmarkTree(subtrees: subtrees, lookup: nodes, parents: parents, orphans: orphans, deleted: deleted, modified: modified, virtual: virtual) } }
mpl-2.0
8f6e043f8fa9418e4eca607a1ddc99a9
35.0347
271
0.603519
4.635958
false
false
false
false
panjinqiang11/Swift-WeiBo
WeiBo/WeiBo/Class/View/Main/PJTabBar.swift
1
2655
// // PJTabBar.swift // WeiBo // // Created by 潘金强 on 16/7/9. // Copyright © 2016年 潘金强. All rights reserved. // import UIKit protocol PJTabBarDelegate :NSObjectProtocol { func didSelectComposeButton() } class PJTabBar: UITabBar { var block :(() -> ())? //定义代理对象 weak var pjdelegate:PJTabBarDelegate? private lazy var composeButton :UIButton = { let button = UIButton() //设置图片和高亮图片 button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: .Normal) button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: .Highlighted) //设置背景图片 button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: .Normal) button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: .Highlighted) button.sizeToFit() button.addTarget(self, action: "clikButton", forControlEvents: .TouchUpInside) return button }() // MARK: - 点击按钮实现代理方法 @objc private func clikButton() { pjdelegate?.didSelectComposeButton() block?() } override init(frame: CGRect) { super.init(frame: frame) setUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //添加button private func setUI(){ addSubview(composeButton) } // 调整子控件的frame override func layoutSubviews() { super.layoutSubviews() // 设置按钮的中心点 composeButton.centerX = width * 0.5 composeButton.centerY = height * 0.5 // 设置按钮的宽度 let itemWidth = width / 5 // 记录遍历到第几个系统的按钮 var index = 0 // 调整系统控件的位置及大小 for value in subviews { //UITabBarButton 系统私有的类,不能直接使用 if value.isKindOfClass(NSClassFromString("UITabBarButton")!) { value.width = itemWidth value.x = CGFloat(index) * itemWidth index++ // 将要显示搜索按钮的时候多加一个宽度,隔过去中间的加号按钮 if index == 2 { index++ } } } } }
mit
335d85ae5b6e751aafc2ac062514159f
21.222222
110
0.52875
4.6875
false
false
false
false
PureSwift/Bluetooth
Sources/BluetoothHCI/HCILEEnhancedReceiverTest.swift
1
2328
// // HCILEEnhancedReceiverTest.swift // Bluetooth // // Created by Alsey Coleman Miller on 6/14/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation // MARK: - Method public extension BluetoothHostControllerInterface { /// LE Enhanced Receiver Test Command /// /// This command is used to start a test where the DUT receives test /// reference packets at a fixed interval. The tester generates the test /// reference packets. func lowEnergyEnhancedReceiverTest(rxChannel: LowEnergyRxChannel, phy: HCILEEnhancedReceiverTest.Phy, modulationIndex: HCILEEnhancedReceiverTest.ModulationIndex, timeout: HCICommandTimeout = .default) async throws { let parameters = HCILEEnhancedReceiverTest(rxChannel: rxChannel, phy: phy, modulationIndex: modulationIndex) try await deviceRequest(parameters, timeout: timeout) } } // MARK: - Command /// LE Enhanced Receiver Test Command /// /// This command is used to start a test where the DUT receives test reference packets at a /// fixed interval. The tester generates the test reference packets. @frozen public struct HCILEEnhancedReceiverTest: HCICommandParameter { public static let command = HCILowEnergyCommand.enhancedReceiverTest //0x0033 public let rxChannel: LowEnergyRxChannel public let phy: Phy public let modulationIndex: ModulationIndex public init(rxChannel: LowEnergyRxChannel, phy: Phy, modulationIndex: ModulationIndex) { self.rxChannel = rxChannel self.phy = phy self.modulationIndex = modulationIndex } public var data: Data { return Data([rxChannel.rawValue, phy.rawValue, modulationIndex.rawValue]) } public enum Phy: UInt8 { /// Receiver set to use the LE 1M PHY case le1MPhy = 0x01 /// Receiver set to use the LE 2M PHY case le2MPhy = 0x02 /// Receiver set to use the LE Coded PHY case leCodedPhy = 0x03 } public enum ModulationIndex: UInt8 { /// Assume transmitter will have a standard modulation index case standard = 0x00 /// Assume transmitter will have a stable modulation index case stable = 0x01 } }
mit
fb6abb32bef867d0be6885df52e60b78
30.876712
219
0.673829
4.626243
false
true
false
false
stephenjwatkins/turtle-smash
Turtle Smash/Game.swift
1
2225
import Foundation import UIKit import AudioToolbox class Game { typealias onOverResponder = () -> () var score: Int = 0 var smashersGrid: SmashersGrid? var view: GameView var round: Round? var onOverFn: onOverResponder? var isPendingOver: Bool = false init(view: GameView) { self.view = view } func start() { self.isPendingOver = false Round.Intervals.Current = Round.Intervals.Start self.newRound() } func press(smasher: Smasher) { self.scored() let highlightedSmashers = self.smashersGrid!.getSmashersWithState(Smasher.States.Highlighted) if highlightedSmashers.count == 0 { for smasher in self.smashersGrid!.getSmashersWithState(Smasher.States.Pressed) { smasher.blinkHighlight() } self.stopRound() delay(0.73) { self.newRound() } } } func stopRound() { if self.round == nil { return } self.round!.done() self.round = nil } func newRound() { if self.round != nil { return } self.round = Round(game: self) self.round!.start() } func scored() { score++ self.view.scoreLabel.update(self.score) } func invalidPress() { AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate)) for smasher in self.smashersGrid!.getSmashersWithState(Smasher.States.Highlighted) { let turtleSmasher = (smasher.layers["TurtleHead"]! as SmasherTurtleHead) turtleSmasher.imageNode!.texture = turtleSmasher.turtleHappyTexture! } self.isPendingOver = true self.round!.done() } func over() { self.isPendingOver = true self.round!.done() ScoreManager.saveNewScore(score) self.view.progressView!.stopProgress() self.doOnOver() } func doOnOver() { if self.onOverFn != nil { self.onOverFn!() } } func onOver(success:()->()) { self.onOverFn = success } }
mit
796648bbfae64731e85d63c1cd0a4fa5
23.195652
101
0.556404
4.230038
false
false
false
false
apple/swift-package-manager
Sources/PackageCollectionsSigning/Key/ASN1/Types/ASN1OctetString.swift
2
1967
//===----------------------------------------------------------------------===// // // This source file is part of the Swift open source project // // Copyright (c) 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// // // This source file is part of the SwiftCrypto open source project // // Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors // Licensed under Apache License v2.0 // // See http://swift.org/LICENSE.txt for license information // See CONTRIBUTORS.md for the list of SwiftCrypto project authors // //===----------------------------------------------------------------------===// import Foundation // Source: https://github.com/apple/swift-crypto/blob/main/Sources/Crypto/ASN1/Basic%20ASN1%20Types/ASN1OctetString.swift extension ASN1 { /// An octet string is a representation of a string of octets. struct ASN1OctetString: ASN1Parseable { var bytes: ArraySlice<UInt8> init(asn1Encoded node: ASN1.ASN1Node) throws { guard node.identifier == .primitiveOctetString else { throw ASN1Error.unexpectedFieldType } guard case .primitive(let content) = node.content else { preconditionFailure("ASN.1 parser generated primitive node with constructed content") } self.bytes = content } } } extension ASN1.ASN1OctetString: Hashable {} extension ASN1.ASN1OctetString: ContiguousBytes { func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R { return try self.bytes.withUnsafeBytes(body) } }
apache-2.0
1840cd3995ff54917b33b350e82e94f5
35.425926
121
0.585155
4.739759
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureSettings/Sources/FeatureSettingsUI/PaymentMethods/RemovePaymentMethod/RemovePaymentMethodScreenPresenter.swift
1
3028
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import DIKit import PlatformKit import PlatformUIKit import RxCocoa import RxRelay import RxSwift final class RemovePaymentMethodScreenPresenter { // MARK: - Types typealias AccessibilityIDs = Accessibility.Identifier.Settings.RemovePaymentMethodScreen // MARK: - Public Properties let badgeImageViewModel: BadgeImageViewModel let titleLabelContent: LabelContent let descriptionLabelContent: LabelContent let removeButtonViewModel: ButtonViewModel var dismissal: Signal<Void> { dismissalRelay.asSignal() } // MARK: - Private Properties private let loadingViewPresenter: LoadingViewPresenting private let interactor: RemovePaymentMethodScreenInteractor private let dismissalRelay = PublishRelay<Void>() private let disposeBag = DisposeBag() init( buttonLocalizedString: String, interactor: RemovePaymentMethodScreenInteractor, loadingViewPresenter: LoadingViewPresenting = resolve() ) { self.loadingViewPresenter = loadingViewPresenter self.interactor = interactor titleLabelContent = LabelContent( text: interactor.data.title, font: .main(.semibold, 20), color: .titleText, alignment: .center, accessibility: .id(AccessibilityIDs.title) ) descriptionLabelContent = LabelContent( text: interactor.data.description, font: .main(.medium, 14), color: .descriptionText, alignment: .center, accessibility: .id(AccessibilityIDs.description) ) let imageResource: ImageResource switch interactor.data.type { case .beneficiary: imageResource = .local(name: "icon-bank", bundle: .platformUIKit) case .card(let type): imageResource = type.thumbnail ?? .local(name: "icon-card", bundle: .platformUIKit) } badgeImageViewModel = BadgeImageViewModel.default( image: imageResource, accessibilityIdSuffix: AccessibilityIDs.badge ) badgeImageViewModel.marginOffsetRelay.accept(Spacing.standard) removeButtonViewModel = .destructive(with: buttonLocalizedString) } func viewDidLoad() { interactor.state .map(\.isCalculating) .bindAndCatch(weak: self) { (self, isCalculating) in if isCalculating { self.loadingViewPresenter.show(with: .circle, text: nil) } else { self.loadingViewPresenter.hide() } } .disposed(by: disposeBag) interactor.state .filter(\.isValue) .mapToVoid() .bindAndCatch(to: dismissalRelay) .disposed(by: disposeBag) removeButtonViewModel.tapRelay .bindAndCatch(to: interactor.triggerRelay) .disposed(by: disposeBag) } }
lgpl-3.0
53b7f85472a5c99daa064c106ed06ba0
30.206186
95
0.64189
5.473779
false
false
false
false
proxpero/Placeholder
Placeholder/Webservice.swift
1
2482
// // Webservice.swift // Placeholder // // Created by Todd Olsen on 4/6/17. // Copyright © 2017 proxpero. All rights reserved. // import Foundation extension URLRequest { /// Initialize a URLRequest with a `Resource`. fileprivate init<A>(resource: Resource<A>) { self.init(url: resource.url) self.httpMethod = resource.method.method if case .post(let data) = resource.method { httpBody = data } } } /// An `Error` type to describe bad states of a `Webservice`. public enum WebserviceError: Error { case notAuthenticated case other } public protocol NetworkEngine { typealias Handler = (Data?, URLResponse?, Error?) -> () func request<A>(resource: Resource<A>, handler: @escaping Handler) } extension URLSession: NetworkEngine { public typealias Handler = NetworkEngine.Handler public func request<A>(resource: Resource<A>, handler: @escaping Handler) { let task = dataTask(with: URLRequest(resource: resource), completionHandler: handler) task.resume() } } public final class Webservice { /// Shared instance (singleton) of a Webservice. static let shared = Webservice() // The `NetworkEngine` to use for making URLRequests, probably the // URLSession.shared singleton, but possibly a mock during testing. private let engine: NetworkEngine /// Initialize a `Webservice` with an optional `NetworkEngine` which defaults /// to `URLSession.shared`. Using an alternate engine is useful for testing. public init(engine: NetworkEngine = URLSession.shared) { self.engine = engine } /// Loads a resource. The completion handler is always called on the main queue. /// /// - Parameter resource: A `Resource` of `A` /// - Returns: A `Future` of `A` public func load<A>(_ resource: Resource<A>) -> Future<A> { return Future { completion in engine.request(resource: resource) { (data, response, _) in let result: Result<A> if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 401 { result = Result.error(WebserviceError.notAuthenticated) } else { let parsed = data.flatMap(resource.parse) result = Result(parsed, or: WebserviceError.other) } DispatchQueue.main.async { completion(result) } } } } }
mit
92d25035f0d4d682e1c3b5a775d612eb
30.405063
100
0.635631
4.486438
false
false
false
false
CoderFeiSu/FFCategoryHUD
FFCategoryHUD/FFKeyboardBarStyle.swift
1
1453
// // FFKeyboardBarStyle.swift // FFCategoryHUDExample // // Created by Freedom on 2017/5/12. // Copyright © 2017年 Freedom. All rights reserved. // import UIKit public class FFKeyboardBarStyle: NSObject { /** 文字标题是否是在显示内容上面 */ public var isTitleOnTop: Bool = true /** pageControl高度 */ public var pageControlHeight: CGFloat = 20 public var pageControlAlignment: FFKeyboardBarAlignment = .top /** 文字视图高度 */ public var height: CGFloat = 44 /** 普通文字颜色 */ public var normalColor: UIColor = .black /** 选中文字颜色 */ public var selectColor: UIColor = .red public var normalFont: UIFont = UIFont.systemFont(ofSize: 13.0) /** 文字区背景颜色 */ public var barColor: UIColor = UIColor.lightGray /** 内容背景颜色 */ public var contentColor: UIColor = UIColor.groupTableViewBackground /** 默认文字之间的间距是10 */ public var margin: CGFloat = 10 /** 默认文字到屏幕左边的间距是5 */ public var leftMargin: CGFloat = 5 /** 默认文字到屏幕右边的间距是5 */ public var rightMargin: CGFloat = 5 /** 是否显示底部指示条 */ public var isShowBottomLine: Bool = false public var bottomLineHeight: CGFloat = 2.0 public var bottomLineColor: UIColor = UIColor.blue } public enum FFKeyboardBarAlignment { case top case bottom }
mit
5c50aacbf84c3ec5453d6fba5658f22b
26.521739
71
0.672986
4.057692
false
false
false
false
borglab/SwiftFusion
Sources/SwiftFusion/Inference/ChordalInitialization.swift
1
8578
// 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 PenguinStructures import TensorFlow /// A relaxed version of the Rot3 between that uses the Chordal (Frobenious) norm on rotation /// Please refer to Carlone15icra (Initialization Techniques for 3D SLAM: a Survey on Rotation Estimation and its Use in Pose Graph Optimization) /// for explanation. public struct RelaxedRotationFactorRot3: LinearizableFactor2 { public let edges: Variables.Indices public let difference: Matrix3 public init(_ id1: TypedID<Matrix3>, _ id2: TypedID<Matrix3>, _ difference: Matrix3) { self.edges = Tuple2(id1, id2) self.difference = difference } public typealias ErrorVector = Vector9 @differentiable public func errorVector(_ R1: Matrix3, _ R2: Matrix3) -> ErrorVector { let R12 = difference let R1h = matmul(R12, R2.transposed()).transposed() return ErrorVector(R1h - R1) } } /// A factor for the anchor in chordal initialization public struct RelaxedAnchorFactorRot3: LinearizableFactor1 { public let edges: Variables.Indices public let prior: Matrix3 public init(_ id: TypedID<Matrix3>, _ prior: Matrix3) { self.edges = Tuple1(id) self.prior = prior } public typealias ErrorVector = Vector9 @differentiable public func errorVector(_ val: Matrix3) -> ErrorVector { ErrorVector(val - prior) } } /// Type shorthands used in the relaxed pose graph /// NOTE: Specializations are added in `FactorsStorage.swift` public typealias Jacobian9x3x3_1 = Array<Tuple1<Matrix3>> public typealias Jacobian9x3x3_2 = Array<Tuple2<Matrix3, Matrix3>> public typealias JacobianFactor9x3x3_1 = JacobianFactor<Jacobian9x3x3_1, Vector9> public typealias JacobianFactor9x3x3_2 = JacobianFactor<Jacobian9x3x3_2, Vector9> /// Chordal Initialization for Pose3s public struct ChordalInitialization { /// ID of the anchor used in chordal initialization, should only be used if not using `GetInitializations`. public var anchorId: TypedID<Pose3> public init() { anchorId = TypedID<Pose3>(0) } /// Extract a subgraph of the original graph with only Pose3s. public func buildPose3graph(graph: FactorGraph) -> FactorGraph { var pose3Graph = FactorGraph() for factor in graph.factors(type: BetweenFactor<Pose3>.self) { pose3Graph.store(factor) } for factor in graph.factors(type: PriorFactor<Pose3>.self) { pose3Graph.store(BetweenFactor(anchorId, factor.edges.head, factor.prior)) } return pose3Graph } /// Solves the unconstrained chordal graph given the original Pose3 graph. /// - Parameters: /// - g: The factor graph with only `BetweenFactor<Pose3>` and `PriorFactor<Pose3>` /// - v: the current pose priors /// - ids: the `TypedID`s of the poses public func solveOrientationGraph( g: FactorGraph, v: VariableAssignments, ids: Array<TypedID<Pose3>> ) -> VariableAssignments { /// The orientation graph, with only unconstrained rotation factors var orientationGraph = FactorGraph() /// orientation storage var orientations = VariableAssignments() /// association to lookup the vector-based storage from the pose3 ID var associations = Dictionary<Int, TypedID<Matrix3>>() // allocate the space for solved rotations, and memorize the assocation for i in ids { associations[i.perTypeID] = orientations.store(Matrix3.zero) } // allocate the space for anchor associations[anchorId.perTypeID] = orientations.store(Matrix3.zero) // iterate the pose3 graph and make corresponding relaxed factors for factor in g.factors(type: BetweenFactor<Pose3>.self) { let R = factor.difference.rot.coordinate.R let frob_factor = RelaxedRotationFactorRot3( associations[factor.edges.head.perTypeID]!, associations[factor.edges.tail.head.perTypeID]!, R) orientationGraph.store(frob_factor) } // make the anchor factor orientationGraph.store(RelaxedAnchorFactorRot3(associations[anchorId.perTypeID]!, Matrix3.identity)) // optimize var optimizer = GenericCGLS() let linearGraph = orientationGraph.linearized(at: orientations) optimizer.optimize(gfg: linearGraph, initial: &orientations) return normalizeRelaxedRotations(orientations, associations: associations, ids: ids) } /// This function finds the closest Rot3 to the unconstrained 3x3 matrix with SVD. /// - Parameters: /// - relaxedRot3: the results of the unconstrained chordal optimization /// - associations: mapping from the index of the pose to the index of the corresponding rotation /// - ids: the IDs of the poses /// /// TODO(fan): replace this with a 3x3 specialized SVD instead of this generic SVD (slow) public func normalizeRelaxedRotations( _ relaxedRot3: VariableAssignments, associations: Dictionary<Int, TypedID<Matrix3>>, ids: Array<TypedID<Pose3>>) -> VariableAssignments { var validRot3 = VariableAssignments() for v in ids { let M: Matrix3 = relaxedRot3[associations[v.perTypeID]!] let initRot = Rot3.ClosestTo(mat: M) // TODO(fan): relies on the assumption of continuous and ordered allocation let _ = validRot3.store(initRot) } let M_anchor: Matrix3 = relaxedRot3[associations[anchorId.perTypeID]!] let initRot_anchor = Rot3.ClosestTo(mat: M_anchor) // TODO(fan): relies on the assumption of continous and ordered allocation let _ = validRot3.store(initRot_anchor) return validRot3; } /// This function computes the inital poses given the chordal initialized rotations. /// - Parameters: /// - graph: The factor graph with only `BetweenFactor<Pose3>` and `PriorFactor<Pose3>` /// - orientations: The orientations returned by the chordal initialization for `Rot3`s /// - ids: the `TypedID`s of the poses public func computePoses(graph: FactorGraph, orientations: VariableAssignments, ids: Array<TypedID<Pose3>>) -> VariableAssignments { var val = VariableAssignments() var g = graph for v in ids { let _ = val.store(Pose3(orientations[TypedID<Rot3>(v.perTypeID)], Vector3(0,0,0))) } g.store(PriorFactor(anchorId, Pose3())) let anchor_id = val.store(Pose3(Rot3(), Vector3(0,0,0))) assert(anchor_id == anchorId) // optimize for 1 G-N iteration for _ in 0..<1 { let gfg = g.linearized(at: val) var dx = val.tangentVectorZeros var optimizer = GenericCGLS(precision: 1e-1, max_iteration: 100) optimizer.optimize(gfg: gfg, initial: &dx) val.move(along: dx) } return val } /// This function computes the chordal initialization. Normally this is what the user needs to call. /// - Parameters: /// - graph: The factor graph with only `BetweenFactor<Pose3>` and `PriorFactor<Pose3>` /// - ids: the `TypedID`s of the poses /// /// NOTE: This function builds upon the assumption that all variables stored are Pose3s, will fail if that is not the case. public static func GetInitializations(graph: FactorGraph, ids: Array<TypedID<Pose3>>) -> VariableAssignments { var ci = ChordalInitialization() var val = VariableAssignments() for _ in ids { let _ = val.store(Pose3()) } ci.anchorId = val.store(Pose3()) // We "extract" the Pose3 subgraph of the original graph: this // is done to properly model priors and avoiding operating on a larger graph // TODO(fan): This does not work yet as we have not yet reached concensus on how should we // handle associations let pose3Graph = ci.buildPose3graph(graph: graph) // Get orientations from relative orientation measurements let orientations = ci.solveOrientationGraph(g: pose3Graph, v: val, ids: ids) // Compute the full poses (1 GN iteration on full poses) return ci.computePoses(graph: pose3Graph, orientations: orientations, ids: ids) } }
apache-2.0
afcd341d693e40832777742314fbaaa2
37.81448
145
0.707158
3.952995
false
false
false
false
ambientlight/GithubIssuesExtension
GithubIssueEditorExtension/EditIssueCommand.swift
1
2655
// // EditIssueCommand.swift // GithubIssuesExtension // // Created by Taras Vozniuk on 23/11/2016. // Copyright © 2016 Ambientlight. 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 Foundation import XcodeKit import OctoKit import RequestKit /// Handles insertion of new issue template into source buffer class EditIssueCommand: NSObject, XCSourceEditorCommand { func perform(with invocation: XCSourceEditorCommandInvocation, completionHandler: @escaping (Error?) -> Void ) -> Void { let (derivedOwnerº, derivedRepositoryº) = GithubIssuesExtension.deriveOwnerAndRepository(fromHeaderIn: invocation.buffer) let sourceEditSession = SourceEditSession(sourceBuffer: invocation.buffer) let selection = invocation.buffer.selections.firstObject as! XCSourceTextRange let newIssueBody = [ "// \(GithubIssuesExtension.Literal.editIssueKey): <#Issue Number#>", "//", "// - \(GithubIssuesExtension.Parameter.owner.rawValue): \(derivedOwnerº ?? "<#owner#>")", "// - \(GithubIssuesExtension.Parameter.repository.rawValue): \(derivedRepositoryº ?? "<#repository#>")", "// - \(GithubIssuesExtension.Parameter.title.rawValue): <#title#>", "// - \(GithubIssuesExtension.Parameter.assignee.rawValue): <#assignee#>", "// - \(GithubIssuesExtension.Parameter.status.rawValue): <#open or closed#>", "// - \(GithubIssuesExtension.Parameter.shouldOverrideDescription.rawValue): <#true or false#>", "//", "// <#Description#>" ] let targetError: NSError? = (!sourceEditSession.insert(strings: newIssueBody, withPreservedIndentationAfter: selection.end.line - 1)) ? NSError(domain: GithubIssuesExtension.Literal.errorDomainIdentifier, code: GithubIssuesExtension.ErrorCode.insertionFailed.rawValue, userInfo: [NSLocalizedDescriptionKey: "Couldn't insert. Please submit an issues on https://github.com/ambientlight/GithubIssuesExtension/issues if it is not there already"]) : nil completionHandler(targetError) } }
apache-2.0
7060e4b73d45dd6d9759b0c720b8af75
49
456
0.706038
4.681979
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/ViewRelated/Me/Me Main/MeViewController.swift
1
19714
import UIKit import CocoaLumberjack import WordPressShared import Gridicons import WordPressAuthenticator class MeViewController: UITableViewController { var handler: ImmuTableViewHandler! // MARK: - Table View Controller override init(style: UITableView.Style) { super.init(style: style) navigationItem.title = NSLocalizedString("Me", comment: "Me page title") MeViewController.configureRestoration(on: self) clearsSelectionOnViewWillAppear = false } required convenience init() { self.init(style: .grouped) let notificationCenter = NotificationCenter.default notificationCenter.addObserver(self, selector: #selector(refreshModelWithNotification(_:)), name: .ZendeskPushNotificationReceivedNotification, object: nil) notificationCenter.addObserver(self, selector: #selector(refreshModelWithNotification(_:)), name: .ZendeskPushNotificationClearedNotification, object: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() // Preventing MultiTouch Scenarios view.isExclusiveTouch = true ImmuTable.registerRows([ NavigationItemRow.self, IndicatorNavigationItemRow.self, ButtonRow.self, DestructiveButtonRow.self ], tableView: self.tableView) handler = ImmuTableViewHandler(takeOver: self) WPStyleGuide.configureAutomaticHeightRows(for: tableView) NotificationCenter.default.addObserver(self, selector: #selector(MeViewController.accountDidChange), name: NSNotification.Name.WPAccountDefaultWordPressComAccountChanged, object: nil) WPStyleGuide.configureColors(view: view, tableView: tableView) tableView.accessibilityIdentifier = "Me Table" reloadViewModel() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() tableView.layoutHeaderView() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) refreshAccountDetails() if splitViewControllerIsHorizontallyCompact { animateDeselectionInteractively() } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) registerUserActivity() } @objc fileprivate func accountDidChange() { reloadViewModel() } @objc fileprivate func reloadViewModel() { let account = defaultAccount() let loggedIn = account != nil // Warning: If you set the header view after the table model, the // table's top margin will be wrong. // // My guess is the table view adjusts the height of the first section // based on if there's a header or not. tableView.tableHeaderView = account.map { headerViewForAccount($0) } // Then we'll reload the table view model (prompting a table reload) handler.viewModel = tableViewModel(loggedIn) } fileprivate func headerViewForAccount(_ account: WPAccount) -> MeHeaderView { headerView.displayName = account.displayName headerView.username = account.username headerView.gravatarEmail = account.email return headerView } private var appSettingsRow: NavigationItemRow { let accessoryType: UITableViewCell.AccessoryType = .disclosureIndicator return NavigationItemRow( title: RowTitles.appSettings, icon: .gridicon(.phone), accessoryType: accessoryType, action: pushAppSettings(), accessibilityIdentifier: "appSettings") } fileprivate func tableViewModel(_ loggedIn: Bool) -> ImmuTable { let accessoryType: UITableViewCell.AccessoryType = .disclosureIndicator let myProfile = NavigationItemRow( title: RowTitles.myProfile, icon: .gridicon(.user), accessoryType: accessoryType, action: pushMyProfile(), accessibilityIdentifier: "myProfile") let accountSettings = NavigationItemRow( title: RowTitles.accountSettings, icon: .gridicon(.cog), accessoryType: accessoryType, action: pushAccountSettings(), accessibilityIdentifier: "accountSettings") let helpAndSupportIndicator = IndicatorNavigationItemRow( title: RowTitles.support, icon: .gridicon(.help), showIndicator: ZendeskUtils.showSupportNotificationIndicator, accessoryType: accessoryType, action: pushHelp()) let logIn = ButtonRow( title: RowTitles.logIn, action: presentLogin()) let logOut = DestructiveButtonRow( title: RowTitles.logOut, action: logoutRowWasPressed(), accessibilityIdentifier: "logOutFromWPcomButton") let wordPressComAccount = HeaderTitles.wpAccount return ImmuTable(sections: [ // first section .init(rows: { var rows: [ImmuTableRow] = [appSettingsRow] if loggedIn { rows = [myProfile, accountSettings] + rows } return rows }()), // middle section .init(rows: { var rows: [ImmuTableRow] = [helpAndSupportIndicator] if isRecommendAppRowEnabled { rows.append(NavigationItemRow(title: ShareAppContentPresenter.RowConstants.buttonTitle, icon: ShareAppContentPresenter.RowConstants.buttonIconImage, accessoryType: accessoryType, action: displayShareFlow(), loading: sharePresenter.isLoading)) } return rows }()), // last section .init(headerText: wordPressComAccount, rows: { return [loggedIn ? logOut : logIn] }()) ]) } // MARK: - UITableViewDelegate override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { let isNewSelection = (indexPath != tableView.indexPathForSelectedRow) if isNewSelection { return indexPath } else { return nil } } // MARK: - Actions fileprivate var myProfileViewController: UIViewController? { guard let account = self.defaultAccount() else { let error = "Tried to push My Profile without a default account. This shouldn't happen" assertionFailure(error) DDLogError(error) return nil } return MyProfileViewController(account: account) } fileprivate func pushMyProfile() -> ImmuTableAction { return { [unowned self] row in if let myProfileViewController = self.myProfileViewController { WPAppAnalytics.track(.openedMyProfile) self.navigationController?.pushViewController(myProfileViewController, animated: true, rightBarButton: self.navigationItem.rightBarButtonItem) } } } fileprivate func pushAccountSettings() -> ImmuTableAction { return { [unowned self] row in if let account = self.defaultAccount() { WPAppAnalytics.track(.openedAccountSettings) guard let controller = AccountSettingsViewController(account: account) else { return } self.navigationController?.pushViewController(controller, animated: true, rightBarButton: self.navigationItem.rightBarButtonItem) } } } func pushAppSettings() -> ImmuTableAction { return { [unowned self] row in WPAppAnalytics.track(.openedAppSettings) let controller = AppSettingsViewController() self.navigationController?.pushViewController(controller, animated: true, rightBarButton: self.navigationItem.rightBarButtonItem) } } func pushHelp() -> ImmuTableAction { return { [unowned self] row in let controller = SupportTableViewController() self.navigationController?.pushViewController(controller, animated: true, rightBarButton: self.navigationItem.rightBarButtonItem) } } func displayShareFlow() -> ImmuTableAction { return { [unowned self] row in defer { self.tableView.deselectSelectedRowWithAnimation(true) } guard let selectedIndexPath = self.tableView.indexPathForSelectedRow, let selectedCell = self.tableView.cellForRow(at: selectedIndexPath) else { return } self.sharePresenter.present(for: .wordpress, in: self, source: .me, sourceView: selectedCell) } } fileprivate func presentLogin() -> ImmuTableAction { return { [unowned self] row in self.tableView.deselectSelectedRowWithAnimation(true) self.promptForLoginOrSignup() } } fileprivate func logoutRowWasPressed() -> ImmuTableAction { return { [unowned self] row in self.tableView.deselectSelectedRowWithAnimation(true) self.displayLogOutAlert() } } /// Selects the My Profile row and pushes the Support view controller /// @objc public func navigateToMyProfile() { navigateToTarget(for: RowTitles.myProfile) } /// Selects the Account Settings row and pushes the Account Settings view controller /// @objc public func navigateToAccountSettings() { navigateToTarget(for: RowTitles.accountSettings) } /// Selects the App Settings row and pushes the App Settings view controller /// @objc public func navigateToAppSettings() { navigateToTarget(for: appSettingsRow.title) } /// Selects the Help & Support row and pushes the Support view controller /// @objc public func navigateToHelpAndSupport() { navigateToTarget(for: RowTitles.support) } fileprivate func navigateToTarget(for rowTitle: String) { let matchRow: ((ImmuTableRow) -> Bool) = { row in if let row = row as? NavigationItemRow { return row.title == rowTitle } else if let row = row as? IndicatorNavigationItemRow { return row.title == rowTitle } return false } if let sections = handler?.viewModel.sections, let section = sections.firstIndex(where: { $0.rows.contains(where: matchRow) }), let row = sections[section].rows.firstIndex(where: matchRow) { let indexPath = IndexPath(row: row, section: section) tableView.selectRow(at: indexPath, animated: true, scrollPosition: .middle) handler.tableView(self.tableView, didSelectRowAt: indexPath) } } // MARK: - Helpers // FIXME: (@koke 2015-12-17) Not cool. Let's stop passing managed objects // and initializing stuff with safer values like userID fileprivate func defaultAccount() -> WPAccount? { let context = ContextManager.sharedInstance().mainContext let service = AccountService(managedObjectContext: context) let account = service.defaultWordPressComAccount() return account } fileprivate func refreshAccountDetails() { guard let account = defaultAccount() else { reloadViewModel() return } let context = ContextManager.sharedInstance().mainContext let service = AccountService(managedObjectContext: context) service.updateUserDetails(for: account, success: { [weak self] in self?.reloadViewModel() }, failure: { error in DDLogError(error.localizedDescription) }) } // MARK: - LogOut private func displayLogOutAlert() { let alert = UIAlertController(title: logOutAlertTitle, message: nil, preferredStyle: .alert) alert.addActionWithTitle(LogoutAlert.cancelAction, style: .cancel) alert.addActionWithTitle(LogoutAlert.logoutAction, style: .destructive) { [weak self] _ in self?.dismiss(animated: true) { AccountHelper.logOutDefaultWordPressComAccount() } } present(alert, animated: true) } private var logOutAlertTitle: String { let context = ContextManager.sharedInstance().mainContext let service = PostService(managedObjectContext: context) let count = service.countPostsWithoutRemote() guard count > 0 else { return LogoutAlert.defaultTitle } let format = count > 1 ? LogoutAlert.unsavedTitlePlural : LogoutAlert.unsavedTitleSingular return String(format: format, count) } // MARK: - Private Properties fileprivate lazy var headerView: MeHeaderView = { let headerView = MeHeaderView() headerView.onGravatarPress = { [weak self] in guard let strongSelf = self else { return } strongSelf.presentGravatarPicker(from: strongSelf) } headerView.onDroppedImage = { [weak self] image in let imageCropViewController = ImageCropViewController(image: image) imageCropViewController.maskShape = .square imageCropViewController.shouldShowCancelButton = true imageCropViewController.onCancel = { [weak self] in self?.dismiss(animated: true) self?.updateGravatarStatus(.idle) } imageCropViewController.onCompletion = { [weak self] image, _ in self?.dismiss(animated: true) self?.uploadGravatarImage(image) } let navController = UINavigationController(rootViewController: imageCropViewController) navController.modalPresentationStyle = .formSheet self?.present(navController, animated: true) } return headerView }() /// Shows an actionsheet with options to Log In or Create a WordPress site. /// This is a temporary stop-gap measure to preserve for users only logged /// into a self-hosted site the ability to create a WordPress.com account. /// fileprivate func promptForLoginOrSignup() { WordPressAuthenticator.showLogin(from: self, animated: true, showCancel: true, restrictToWPCom: true) } /// Convenience property to determine whether the recomend app row should be displayed or not. private var isRecommendAppRowEnabled: Bool { FeatureFlag.recommendAppToOthers.enabled && !AppConfiguration.isJetpack } private lazy var sharePresenter: ShareAppContentPresenter = { let presenter = ShareAppContentPresenter(account: defaultAccount()) presenter.delegate = self return presenter }() } // MARK: - SearchableActivity Conformance extension MeViewController: SearchableActivityConvertable { var activityType: String { return WPActivityType.me.rawValue } var activityTitle: String { return NSLocalizedString("Me", comment: "Title of the 'Me' tab - used for spotlight indexing on iOS.") } var activityKeywords: Set<String>? { let keyWordString = NSLocalizedString("wordpress, me, settings, account, notification log out, logout, log in, login, help, support", comment: "This is a comma separated list of keywords used for spotlight indexing of the 'Me' tab.") let keywordArray = keyWordString.arrayOfTags() guard !keywordArray.isEmpty else { return nil } return Set(keywordArray) } } // MARK: - Gravatar uploading // extension MeViewController: GravatarUploader { /// Update the UI based on the status of the gravatar upload func updateGravatarStatus(_ status: GravatarUploaderStatus) { switch status { case .uploading(image: let newGravatarImage): headerView.showsActivityIndicator = true headerView.isUserInteractionEnabled = false headerView.overrideGravatarImage(newGravatarImage) case .finished: reloadViewModel() fallthrough default: headerView.showsActivityIndicator = false headerView.isUserInteractionEnabled = true } } } // MARK: - Constants private extension MeViewController { enum RowTitles { static let appSettings = NSLocalizedString("App Settings", comment: "Link to App Settings section") static let myProfile = NSLocalizedString("My Profile", comment: "Link to My Profile section") static let accountSettings = NSLocalizedString("Account Settings", comment: "Link to Account Settings section") static let support = NSLocalizedString("Help & Support", comment: "Link to Help section") static let logIn = NSLocalizedString("Log In", comment: "Label for logging in to WordPress.com account") static let logOut = NSLocalizedString("Log Out", comment: "Label for logging out from WordPress.com account") } enum HeaderTitles { static let wpAccount = NSLocalizedString("WordPress.com Account", comment: "WordPress.com sign-in/sign-out section header title") } enum LogoutAlert { static let defaultTitle = AppConstants.Logout.alertTitle static let unsavedTitleSingular = NSLocalizedString("You have changes to %d post that hasn't been uploaded to your site. Logging out now will delete those changes. Log out anyway?", comment: "Warning displayed before logging out. The %d placeholder will contain the number of local posts (SINGULAR!)") static let unsavedTitlePlural = NSLocalizedString("You have changes to %d posts that haven’t been uploaded to your site. Logging out now will delete those changes. Log out anyway?", comment: "Warning displayed before logging out. The %d placeholder will contain the number of local posts (PLURAL!)") static let cancelAction = NSLocalizedString("Cancel", comment: "Verb. A button title. Tapping cancels an action.") static let logoutAction = NSLocalizedString("Log Out", comment: "Button for confirming logging out from WordPress.com account") } } // MARK: - Private Extension for Notification handling private extension MeViewController { @objc func refreshModelWithNotification(_ notification: Foundation.Notification) { reloadViewModel() } } // MARK: - ShareAppContentPresenterDelegate extension MeViewController: ShareAppContentPresenterDelegate { func didUpdateLoadingState(_ loading: Bool) { guard isRecommendAppRowEnabled else { return } reloadViewModel() } }
gpl-2.0
b435aa6c0a3ddf3e785b7237910a0989
37.275728
191
0.630327
5.702054
false
false
false
false
jish/twitter
twitter/User.swift
1
2175
// // User.swift // twitter // // Created by Josh Lubaway on 2/21/15. // Copyright (c) 2015 Frustrated Inc. All rights reserved. // import UIKit var _currentUser: User? let currentUserKey = "current_user_json" let userLogoutEvent = "user_logout_event" class User: NSObject { let name: String let screenName: String let profileImageUrl: NSURL let bannerImageUrl: NSURL? let bio: String let followers: Int let following: Int let numTweets: Int init(dict: NSDictionary) { let profileImageString = (dict["profile_image_url_https"] as String).stringByReplacingOccurrencesOfString("_normal.png", withString: "_bigger.png") if let bannerImageString = dict["profile_banner_url"] as? String { bannerImageUrl = NSURL(string: bannerImageString)! } name = dict["name"] as String screenName = dict["screen_name"] as String profileImageUrl = NSURL(string: profileImageString)! bio = dict["description"] as String followers = dict["followers_count"] as Int following = dict["friends_count"] as Int numTweets = dict["statuses_count"] as Int } class var currentUser: User? { if _currentUser == nil { if let data = defaults.objectForKey(currentUserKey) as? NSData { let dict = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as NSDictionary _currentUser = User(dict: dict) } } return _currentUser } class var defaults: NSUserDefaults { return NSUserDefaults.standardUserDefaults() } class func storeCurrentUserData(dict: NSDictionary) { let data = NSJSONSerialization.dataWithJSONObject(dict, options: nil, error: nil) defaults.setObject(data, forKey: currentUserKey) defaults.synchronize() } class func logout() { _currentUser = nil defaults.setObject(nil, forKey: currentUserKey) defaults.synchronize() TwitterClient.sharedInstance.logout() NSNotificationCenter.defaultCenter().postNotificationName(userLogoutEvent, object: nil) } }
mit
1dcadb810f795ae41770445f7cbde2df
28.794521
155
0.655172
4.637527
false
false
false
false
lemberg/connfa-ios
Pods/SwiftDate/Sources/SwiftDate/Formatters/DotNetParserFormatter.swift
1
2187
// // DotNetParserFormatter.swift // SwiftDate // // Created by Daniele Margutti on 06/06/2018. // Copyright © 2018 SwiftDate. All rights reserved. // import Foundation public class DOTNETParser: StringToDateTransformable { internal static let pattern = "\\/Date\\((-?\\d+)((?:[\\+\\-]\\d+)?)\\)\\/" public static func parse(_ string: String) -> (seconds: TimeInterval, tz: TimeZone)? { do { let parser = try NSRegularExpression(pattern: DOTNETParser.pattern, options: .caseInsensitive) guard let match = parser.firstMatch(in: string, options: .reportCompletion, range: NSRange(location: 0, length: string.count)) else { return nil } guard let milliseconds = TimeInterval((string as NSString).substring(with: match.range(at: 1))) else { return nil } // Parse timezone let raw_tz = ((string as NSString).substring(with: match.range(at: 2)) as NSString) guard raw_tz.length > 1 else { return nil } let tz_sign: String = raw_tz.substring(to: 1) if tz_sign != "+" && tz_sign != "-" { return nil } let tz_hours: String = raw_tz.substring(with: NSRange(location: 1, length: 2)) let tz_minutes: String = raw_tz.substring(with: NSRange(location: 3, length: 2)) let tz_offset = (Int(tz_hours)! * 60 * 60) + ( Int(tz_minutes)! * 60 ) guard let tz_obj = TimeZone(secondsFromGMT: tz_offset) else { return nil } return ( (milliseconds / 1000), tz_obj ) } catch { return nil } } public static func parse(_ string: String, region: Region, options: Any?) -> DateInRegion? { guard let result = DOTNETParser.parse(string) else { return nil } let adaptedRegion = Region(calendar: region.calendar, zone: result.tz, locale: region.locale) return DateInRegion(seconds: result.seconds, region: adaptedRegion) } } public class DOTNETFormatter: DateToStringTrasformable { public static func format(_ date: DateRepresentable, options: Any?) -> String { let milliseconds = (date.date.timeIntervalSince1970 * 1000.0) let tzOffsets = (date.region.timeZone.secondsFromGMT(for: date.date) / 3600) let formattedStr = String(format: "/Date(%.0f%+03d00)/", milliseconds, tzOffsets) return formattedStr } }
apache-2.0
c0eccd089b7f5282ff7a8b7cb40a5376
33.15625
136
0.683898
3.44795
false
false
false
false
ImperialCollegeDocWebappGroup/webappProject
webapp/SettingModelVC.swift
1
13171
// // SettingModelVC.swift // webapp // // Created by Timeless on 03/06/2015. // Copyright (c) 2015 Shan, Jinyi. All rights reserved. // import UIKit class SettingModelVC: UIViewController,UIImagePickerControllerDelegate, UINavigationControllerDelegate { let heightMin = 120 let heightMax = 220 let weightMin = 30 let weightMax = 200 let heightInit = 160 let weightInit = 50 // input values var maleUser: Bool = true var skinColour: Int = 0 var height: Int = 160 var weight: Int = 50 var imagePicker: UIImagePickerController! var modelImage: UIImage = UIImage(named: "defaultM")! // false if user just registered, and setting for the 1st time var resetModel: Bool = false @IBOutlet weak var cameraButt: UIButton! @IBOutlet weak var FemaleButt: UIButton! @IBOutlet weak var MaleButt: UIButton! @IBOutlet weak var txtHeight: UITextField! @IBOutlet weak var txtWeight: UITextField! @IBOutlet weak var SkinColourSlider: UISlider! @IBOutlet weak var saveButt: UIButton! @IBOutlet weak var faceview: UIImageView! let link : String = "http://www.doc.ic.ac.uk/~jl6613/" let fileName : String = "serverIp.txt" var serverIp : String = "" override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = "Set My Model" self.navigationController?.navigationBar.tintColor = UIColor.whiteColor() // ??????????? //self.navigationController?.navigationBarHidden = true /* if let previousVC = backViewController { if previousVC -------> distinguish previous view controller, to hide back button when pushed from registerVC }*/ if (self.navigationController != nil) { // pushed resetModel = true } else { resetModel = false } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } var backViewController : UIViewController? { var stack = self.navigationController!.viewControllers as Array for (var i = stack.count-1 ; i > 0; --i) { if (stack[i] as! UIViewController == self) { return stack[i-1] as? UIViewController } } return nil } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { println("saved") if segue.identifier == "saved" { println(segue.destinationViewController.description) println(segue.sourceViewController.description) println(segue.identifier) //var svc = segue.destinationViewController as! MainFeaturesVC; //svc.shirt = modelImage } } @IBAction func MaleTapped(sender: UIButton) { maleUser = true selectGender(sender) deselectGender(FemaleButt) modelImage = UIImage(named: "defaultM")! } @IBAction func FemaleTapped(sender: UIButton) { maleUser = false selectGender(sender) deselectGender(MaleButt) modelImage = UIImage(named: "defaultF")! } func selectGender(butt: UIButton) { butt.selected = true if butt == MaleButt { butt.setImage(UIImage(named: "colour1"), forState: .Selected) } else { butt.setImage(UIImage(named: "colour2"), forState: .Selected) } } func deselectGender(butt: UIButton) { butt.selected = false if butt == MaleButt { butt.setImage(UIImage(named: "black1"), forState: .Normal) } else { butt.setImage(UIImage(named: "black2"), forState: .Normal) } } @IBAction func skinColourChanged(sender: UISlider) { skinColour = Int(sender.value) } @IBAction func cameraTapped(sender: UIButton) { /* if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) { let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.sourceType = UIImagePickerControllerSourceType.Camera imagePicker.mediaTypes = [kUTTypeImage as NSString] imagePicker.allowsEditing = false self.presentedViewController(imagePicker, animated:true, completion: nil) newMedia = true }*/ } @IBAction func saveTapped(sender: AnyObject) { println("resetModel is \(resetModel)") // check height and weight value let a:Int? = txtHeight.text.toInt() let b:Int? = txtWeight.text.toInt() var error_msg:NSString = " " var invalidInput: Bool = false if a != nil && b != nil { height = a! weight = b! if height < heightMin || height > heightMax { invalidInput = true error_msg = "Invalid height, use default value?" } else if weight < weightMin || weight > weightMax { invalidInput = true error_msg = "Invalid weight, use default value?" } } else { invalidInput = true error_msg = "Input values are not all integers, use default value?" } if invalidInput { var invalidInputAlert = UIAlertController(title: "Invalid inputs", message: error_msg as String, preferredStyle: .Alert ) invalidInputAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: processAlert)) invalidInputAlert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)) self.presentViewController(invalidInputAlert, animated: true, completion: nil) } else { var confirmAlert = UIAlertController(title: "Valid inputs", message: "Do you confirm your information?", preferredStyle: .Alert ) confirmAlert.addAction(UIAlertAction(title: "Yes", style: .Default, handler: processConfirmAlert)) confirmAlert.addAction(UIAlertAction(title: "Wait a sec", style: .Cancel, handler: nil)) self.presentViewController(confirmAlert, animated: true, completion: nil) } } func processAlert(alert: UIAlertAction!) { // use default values of height and weight height = heightInit weight = weightInit if (postToDB()) { if (resetModel) { self.dismissViewControllerAnimated(true, completion: nil) } else { self.performSegueWithIdentifier("saved", sender: self) } } else { var nerworkErrorAlert = UIAlertController(title: "Network error", message: "Network error, please try again", preferredStyle: .Alert ) nerworkErrorAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil)) self.presentViewController(nerworkErrorAlert, animated: true, completion: nil) } // navigationController?.popViewControllerAnimated(true) } func processConfirmAlert(alert: UIAlertAction!) { if (postToDB()) { if (resetModel) { self.dismissViewControllerAnimated(true, completion: nil) } else { self.performSegueWithIdentifier("saved", sender: self) } } else { var nerworkErrorAlert = UIAlertController(title: "Network error", message: "Network error, please try again", preferredStyle: .Alert ) nerworkErrorAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil)) self.presentViewController(nerworkErrorAlert, animated: true, completion: nil) } //navigationController?.popViewControllerAnimated(true) } func postToDB() -> Bool { getServerIp() // post user information to database let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults() let logname = (prefs.valueForKey("USERNAME") as! NSString as String) var gender = "false" if (maleUser) { gender = "true" } var info = [gender, String(height), String(weight), String(skinColour)] if resetModel { // reset var requestLine = "UPDATE userprofile SET gender = " + info[0] + ", height = " + info[1] + ", weight = " + info[2] + ", skincolour = " + info[3] + " WHERE login = '" + logname + "';\n" if query(requestLine) { return true } } else { // insert var requestLine = ("INSERT INTO userprofile VALUES ('" + logname + "', '") requestLine += (logname + "', " + info[0] + ", 20, " + info[1] + ", ") requestLine += (info[2] + ", " + info[3] + ", ARRAY[]::text[], ARRAY['http://www.selfridges.com/en/givenchy-amerika-cuban-fit-cotton-jersey-t-shirt_242-3000831-15S73176511/?previewAttribute=Black'],") var s1 = requestLine + "'',ARRAY[]::text[]);\n" // after new user var s2 = "INSERT INTO publishs VALUES ('" + logname + "',ARRAY[]::publishitem[]);\n" var s3 = "INSERT INTO friendlist VALUES ('" + logname + "',ARRAY['" + logname + "']);\n" if query(s1) { if query(s2) { if query(s3) { return true } } } } return false } func getServerIp() { let reallink = link + fileName let url = NSURL(string: reallink) if let data1 = NSData(contentsOfURL: url!) { println("!!!!!") var datastring = NSString(data:data1, encoding:NSUTF8StringEncoding) as! String println(datastring) serverIp = datastring } } func query(query : String) -> Bool { println("posting") // post user information to database let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults() let logname = (prefs.valueForKey("USERNAME") as! NSString as String) var client:TCPClient = TCPClient(addr: serverIp, port: 1111) var (success,errmsg)=client.connect(timeout: 10) if success{ println("Connection success!") var (success,errmsg)=client.send(str: query) var i: Int = 0 var dd : Bool = false while true { if success && i < 10 { println("sent success!") var data=client.read(1024*10) if let d = data { if let str1 = NSString(bytes: d, length: d.count, encoding: NSUTF8StringEncoding) { println("read success") println(str1) println("----") var str = str1.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) println(str) if (str == "ERROR") { println("--ERROR") client.close() return false } else if (str == "NOERROR"){ // NOERROR println("--NOERROR") (success,errmsg)=client.send(str: "GOOD\n") } else if (str == "NOR") { println("--NOR") client.close() return true } else if (str == "YESR") { println("--YESR") dd = true (success,errmsg)=client.send(str: "GOOD\n") } else if dd && str.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) != 0 { //data println("this is data") println(str) return true } else { println("er...") (success,errmsg)=client.send(str: "GOOD\n") } } } i+=1 } else { client.close() println(errmsg) return false } } }else{ client.close() println(errmsg) return false } } override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { self.view.endEditing(true) } }
gpl-3.0
8dfd4dc6368104a50394506a637eb639
36.739255
212
0.533217
5.059931
false
false
false
false
zehrer/SOGraphDB
Sources/SOGraphDB_old/Stores_OLD/CacheObjectStore.swift
1
1502
// // CacheObjectStore.swift // SOGraphDB // // Created by Stephan Zehrer on 25.06.14. // Copyright (c) 2014 Stephan Zehrer. All rights reserved. // import Foundation class CacheObjectStore<O: PersistentObject>: ObjectDataStore<O> { //let cache = NSCache(); /** override func createObject() -> O { let result = super.createObject() let uid: NSNumber = result.uid! self.cache.setObject(result, forKey: uid) return result } override func addObject(aObj: O) -> UID { aObj.uid = self.create(aObj.encodeData()) self.cache .setObject(aObj, forKey: aObj.uid) return aObj.uid! } override func readObject(aID: UID) -> O? { var result = self.cache.objectForKey(aID) as O? if !result { result = super.readObject(aID) if result { self.cache.setObject(result, forKey: aID) } } return result } // version with cache support override func deleteObject(aObj: O) { self.cache.removeObjectForKey(aObj.uid) super.deleteObject(aObj) } override func registerObject(aObj: O) -> UID? { var result = super.registerObject(aObj) if result { self.cache.setObject(aObj, forKey: result) } return result } */ }
mit
b1c26eccf85d852b0b48e680706c2866
18.763158
66
0.527963
4.537764
false
false
false
false
omgpuppy/TouchSparks
TouchSparks/GameScene.swift
1
5951
// // GameScene.swift // TouchSparks // // Created by Alan Browning on 10/10/15. // Copyright (c) 2015 Garbanzo. All rights reserved. // import SpriteKit import CoreMotion extension CGVector { mutating func rotateRad(rad: Float) { let x = Float(self.dx); let y = Float(self.dy); self.dx = CGFloat(x * cosf(rad) - y * sinf(rad)); self.dy = CGFloat(x * sinf(rad) + y * cosf(rad)); } mutating func rotateDeg(deg: Float) { let rad = Double(deg) * M_PI / 180.0; rotateRad(Float(rad)); } } extension CGPoint { mutating func rotateRad(rad: Float) { let x = Float(self.x); let y = Float(self.y); self.x = CGFloat(x * cosf(rad) - y * sinf(rad)); self.y = CGFloat(x * sinf(rad) + y * cosf(rad)); } mutating func rotateDeg(deg: Float) { let rad = Double(deg) * M_PI / 180.0; rotateRad(Float(rad)); } } class GameScene: SKScene { /// MARK: Member variables var instruction_label: SKLabelNode?; var shapes_being_added: [Int: SKNode] = [:]; var motion_manager = CMMotionManager(); var palette: [UIColor] = []; /// MARK: Scene contents func createSceneContents() { let myLabel = SKLabelNode(fontNamed:"AvenirNextCondensed-DemiBold"); myLabel.text = "Tap to make a shape."; myLabel.fontSize = 45 myLabel.fontColor = UIColor(white: 0.15, alpha: 1.0); //myLabel.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame)); myLabel.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMaxY(self.frame) - myLabel.frame.height); self.addChild(myLabel); instruction_label = myLabel; palette.append(UIColor(red: 0.984, green: 0.278, blue: 0.031, alpha: 1.0)); palette.append(UIColor(hue: 314.0/360.0, saturation: 0.25, brightness: 0.20, alpha: 1.0)); palette.append(UIColor(hue: 86/360, saturation: 0.88, brightness: 0.35, alpha: 1.0)); palette.append(UIColor(hue: 51/360, saturation: 1.0, brightness: 0.5, alpha: 1.0)); palette.append(UIColor(hue: 357/360, saturation: 0.73, brightness: 0.62, alpha: 1.0)); for idx in 0..<palette.count { var h, s, b, a: CGFloat; (h,s,b,a) = (0,0,0,0); palette[idx].getHue(&h, saturation: &s, brightness: &b, alpha: &a); palette[idx] = UIColor(hue: h, saturation: s-0.5*s, brightness: 1.0/*b+0.5*(1.0-b)*/, alpha: a); } } override func didMoveToView(view: SKView) { /* Setup your scene here */ self.backgroundColor = SKColor(white: 0.1, alpha: 1.0); self.physicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame); createSceneContents(); motion_manager.deviceMotionUpdateInterval = 1.0 / 30; motion_manager.startDeviceMotionUpdates(); } /// MARK: Gravity logic func changeGravityVector() { self.physicsWorld.gravity.rotateDeg(90.0); } /// MARK: Touch logic override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { /* Called when a touch begins */ for touch in touches { var shape = SKShapeNode(); let size = max(15.0, touch.majorRadius); let sample = arc4random_uniform(3); if (sample == 0) { let rad = size + 5.0; var points: [CGPoint] = []; for _ in 1...4 { points.append(CGPoint(x: 0.0, y: rad)); } points[1].rotateDeg(120.0); points[2].rotateDeg(-120.0); let path = CGPathCreateMutable() CGPathMoveToPoint(path, nil, points[0].x, points[0].y) for p in points { CGPathAddLineToPoint(path, nil, p.x, p.y) } CGPathCloseSubpath(path) shape = SKShapeNode(path: path); shape.physicsBody = SKPhysicsBody(polygonFromPath: path); } else if (sample == 1) { shape = SKShapeNode(rect: CGRect(origin: CGPoint(x: -size/2.0, y: -size/2.0), size: CGSize(width: size, height: size)), cornerRadius: 5.0); shape.physicsBody = SKPhysicsBody(rectangleOfSize: CGSize(width: size, height: size), center: CGPoint(x: 0, y: 0)); } else { shape = SKShapeNode(circleOfRadius: size/2.0); shape.physicsBody = SKPhysicsBody(circleOfRadius: size/2.0); shape.physicsBody?.restitution = 1; } //shape.fillColor = UIColor(white: 1.0, alpha: 0.5); let color_idx = arc4random_uniform(UInt32(palette.count)); shape.fillColor = palette[Int(color_idx)]; shape.strokeColor = UIColor(white: 1.0, alpha: 0.0); shape.position = touch.locationInNode(self); shape.runAction(SKAction.fadeInWithDuration(0.5), completion: { () -> Void in print("shape fade in complete") }); self.addChild(shape); shapes_being_added[touch.hashValue] = shape; } } override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { for touch in touches { if let shape = shapes_being_added[touch.hashValue] { shape.position = touch.locationInNode(self); } } } override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { print("touches ended"); instruction_label?.runAction(SKAction.fadeOutWithDuration(0.5)); // if ((instruction_label) != nil) { // instruction_label?.runAction(SKAction.fadeOutWithDuration(0.5)); // } // remove entry in shapes_being_added for this touch for touch in touches { shapes_being_added.removeValueForKey(touch.hashValue); } } override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) { print("touches cancelled"); } override func update(currentTime: CFTimeInterval) { /* Called before each frame is rendered */ let grav = motion_manager.deviceMotion?.gravity; if (grav != nil) { let scale = 100.0; self.physicsWorld.gravity.dx = CGFloat(grav!.x * scale); self.physicsWorld.gravity.dy = CGFloat(grav!.y * scale); } } }
cc0-1.0
dc8f57fa3aeed101c88d7b249ad9a993
31.167568
147
0.624097
3.657652
false
false
false
false
kristorres/Sakura
Sources/NumericalAnalysis.swift
1
18061
// Sources/NumericalAnalysis.swift - Numerical analysis library // // This source file is part of the Sakura open source project // // Copyright (c) 2018 Kris Torres // Licensed under the MIT License // // See https://opensource.org/licenses/MIT for license information // // ----------------------------------------------------------------------------- /// /// This file contains all the implemented algorithms used in numerical analysis /// as global functions. All the algorithms are from *Numerical Analysis, Ninth /// Edition* by Richard L. Burden and J. Douglas Faires. /// // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // MARK:- Root-finding methods // ----------------------------------------------------------------------------- /// Finds a solution *p* to *f*(*x*) = 0 given the continuous function *f* on /// the interval [*a*, *b*], where *f*(*a*) and *f*(*b*) have opposite signs. /// /// The **bisection method** is a root-finding method that repeatedly bisects /// subintervals of [*a*, *b*] and, at each step, locates the half containing /// the solution *p*. /// /// Algorithm /// --------- /// /// ``` /// INPUT: Continuous function f; endpoints a, b; tolerance TOL; /// maximum number of iterations N₀. /// OUTPUT: Approximate solution p, or nil. /// /// Step 1: Set i = 0. /// Step 2: While i < N₀ do Steps 3–6. /// Step 3: Set p = (a + b) / 2; FA = f(a); FP = f(p). /// (Compute pᵢ as the midpoint of aᵢ and bᵢ.) /// Step 4: If FP = 0 or (b - a) / 2 < TOL, then OUTPUT p; STOP. /// (The procedure completed successfully.) /// Step 5: Set i = i + 1. /// Step 6: If FA · FP > 0, then set a = p. (Compute aᵢ and bᵢ.) /// Step 7: OUTPUT nil; STOP. (The procedure was unsuccessful.) /// ``` /// /// Example /// ------- /// /// Use the bisection method to determine an approximation to the root of the /// polynomial function *f*(*x*) = *x*³ + 4*x*² − 10 that is accurate to at /// least within 10⁻⁴. /// /// **Solution:** *f*(1) = -5 and *f*(2) = 14. Thus, by the Intermediate Value /// Theorem, *f*(*x*) has a root in [1, 2]. /// /// In iteration 0, the function value at the midpoint is *f*(1.5) = 2.375 > 0. /// This indicates that the interval [1, 1.5] is used for iteration 1 to ensure /// that *f*(*a*) and *f*(*b*) have opposite signs. Continuing in this manner /// gives the values in the table below. The subintervals between *a* and *b* /// become increasingly smaller, converging on the root *p* of the function *f*. /// After 14 iterations, *p*₁₃ = 1.36517333984375 approximates *p* with an error /// /// |*p* − *p*₁₃| < |*b*₁₄ − *a*₁₄| = |1.365234375 − 1.36517333984375| ≈ 0.00006103515625 /// /// ``` /// ------------------------------------------------------------- /// n a_n b_n p_n f(p_n) /// ------------------------------------------------------------- /// 0 1 2 1.5 2.375 /// 1 1 1.5 1.25 -1.796875 /// 2 1.25 1.5 1.375 0.162109 /// 3 1.25 1.375 1.3125 -0.848389 /// 4 1.3125 1.375 1.34375 -0.350983 /// 5 1.34375 1.375 1.359375 -0.096409 /// 6 1.359375 1.375 1.3671875 0.032356 /// 7 1.359375 1.3671875 1.36328125 -0.032150 /// 8 1.36328125 1.3671875 1.365234375 0.000072 /// 9 1.36328125 1.365234375 1.3642578125 -0.016047 /// 10 1.3642578125 1.365234375 1.36474609375 -0.007989 /// 11 1.36474609375 1.365234375 1.364990234375 -0.003959 /// 12 1.364990234375 1.365234375 1.3651123046875 -0.001944 /// 13 1.3651123046875 1.365234375 1.36517333984375 -0.000936 /// ------------------------------------------------------------- /// ``` /// /// Analysis /// -------- /// /// Since the absolute error is halved at each step, the method converges /// linearly, which is comparatively slow. /// /// Usage /// ----- /// /// ``` /// // f(x) = x³ + 4x² − 10 /// func f(_ x: Double) -> Double { return pow(x, 3) + 4 * pow(x, 2) - 10 } /// /// // Prints "x = 1.36517333984375". /// if let x = bisection(f: f, a: 1, b: 2, tol: 1.0e-4) { print("x = \(x)") } /// else { print("The method failed after 100 iterations.") } /// ``` /// /// **Source:** Burden, Richard L. and Faires, J. Douglas. /// *Numerical Analysis, Ninth Edition* (2010), pp. 49. /// /// - Author: Kris Torres /// /// - Requires: *a* < *b*; and either *f*(*a*) < 0 and *f*(*b*) > 0, or /// *f*(*a*) > 0 and *f*(*b*) < 0. Also, `tol` > 0 and `n` > 0. /// /// - Complexity: *O*(*n*) /// /// - Parameter f: The continuous function *f*(*x*). /// - Parameter a: The initial left endpoint. /// - Parameter b: The initial right endpoint. /// - Parameter tol: The error tolerance of the approximation. The default is /// 10⁻⁴ (`1.0e-4`). /// - Parameter n: The maximum number of iterations to perform. The default is /// `100`. /// /// - Returns: An *optional* that contains the approximate solution *p*, or /// `nil` if the bisection method fails. public func bisection(f: (Double) -> Double, a: Double, b: Double, tol: Double = 1.0e-4, n: Int = 100) -> Double? { // The procedure requires a < b, TOL > 0, and n > 0. if a > b || tol <= 0.0 || n <= 0 { return nil } // Create mutable copies of a and b. var a = a var b = b for _ in 0 ..< n { let p = (a + b) / 2 // Compute pᵢ as the midpoint of aᵢ and bᵢ. let f_a = f(a) let f_p = f(p) // The procedure completed successfully. if f_p == 0.0 || (b - a) / 2 < tol { return p } // Compute aᵢ₊₁ and bᵢ₊₁. if f_a * f_p > 0.0 { a = p } else { b = p } } // The procedure was unsuccessful. return nil } /// Finds a solution *p* to *f*(*x*) = *x* − *g*(*x*) = 0, given the continuous /// functions *f* and *g*, and an initial approximation *p*₀. /// /// The **fixed-point iteration method** is a root-finding method that generates /// the sequence {*pᵢ*} by letting *pᵢ* = *g*(*pᵢ*₋₁), for each *i* ≥ 1. If the /// sequence converges to *p*, then a solution *p* is obtained. /// /// Algorithm /// --------- /// /// ``` /// INPUT: Continuous function g; initial approximation p₀; tolerance TOL; /// maximum number of iterations N₀. /// OUTPUT: Approximate solution p, or nil. /// /// Step 1: Set i = 0. /// Step 2: While i < N₀ do Steps 3–5. /// Step 3: Set p = g(p₀). (Compute pᵢ.) /// Step 4: If |p − p₀| < TOL, then OUTPUT p; STOP. /// (The procedure completed successfully.) /// Step 5: Set i = i + 1; p₀ = p. (Update p₀.) /// Step 6: OUTPUT nil; STOP. (The procedure was unsuccessful.) /// ``` /// /// Example /// ------- /// /// Use the fixed-point iteration method to determine an approximation to the /// root of the polynomial function *f*(*x*) = *x*³ + 4*x*² − 10 that is /// accurate to at least within 10⁻⁴. /// /// **Solution:** *f*(*x*) has a unique root in [1, 2]. We can change the /// equation *f*(*x*) = 0 to the fixed-point form *x* = *g*(*x*) as follows: /// /// 1. *f*(*x*) = *x*³ + 4*x*² − 10 = 0 /// 2. 4*x*² = 10 − *x*³ /// 3. *x*² = (10 − *x*³)/4 /// 4. *x* = ±√(10 − *x*³)/2 /// /// Since the solution is positive, *g*(*x*) = √(10 − *x*³)/2. With *p*₀ = 1.5, /// the table below lists the values of the fixed-point iteration. After 14 /// iterations, *p*₁₃ ≈ 1.36520585029705 approximates the root *p* of the /// function *f*. /// /// ``` /// -------------------- /// n p_n /// -------------------- /// 0 1.5 /// 1 1.28695376762338 /// 2 1.40254080353958 /// 3 1.34545837402329 /// 4 1.37517025281604 /// 5 1.36009419276173 /// 6 1.36784696759213 /// 7 1.36388700388402 /// 8 1.36591673339004 /// 9 1.36487821719368 /// 10 1.36541006116996 /// 11 1.36513782066921 /// 12 1.36527720852448 /// 13 1.36520585029705 /// -------------------- /// ``` /// /// Analysis /// -------- /// /// In general, the method converges linearly, which is comparatively slow. /// /// Usage /// ----- /// /// ``` /// // f(x) = x³ + 4x² − 10 → g(x) = √(10 − x³)/2 /// func g(_ x: Double) -> Double { return sqrt(10 - pow(x, 3)) / 2 } /// /// // Prints "x = 1.36520585029705". /// if let x = fixedPointIteration(g: g, p0: 1.5, tol: 1.0e-4) { /// print("x = \(x)") /// } else { /// print("The method failed after 100 iterations.") /// } /// ``` /// /// **Source:** Burden, Richard L. and Faires, J. Douglas. /// *Numerical Analysis, Ninth Edition* (2010), pp. 60–61. /// /// - Author: Kris Torres /// /// - Requires: `tol` > 0 and `n` > 0. /// /// - Complexity: *O*(*n*) /// /// - Parameter g: The continuous function *g*(*x*). /// - Parameter p0: The initial approximation. /// - Parameter tol: The error tolerance of the approximation. The default is /// 10⁻⁴ (`1.0e-4`). /// - Parameter n: The maximum number of iterations to perform. The default is /// `100`. /// /// - Returns: An *optional* that contains the approximate solution *p*, or /// `nil` if the fixed-point iteration method fails. public func fixedPointIteration(g: (Double) -> Double, p0: Double, tol: Double = 1.0e-4, n: Int = 100) -> Double? { // The procedure requires TOL > 0 and n > 0. if tol <= 0.0 || n <= 0 { return nil } var pᵢ = p0 for _ in 0 ..< n { let p = g(pᵢ) // Compute pᵢ. // The procedure completed successfully. if abs(p - pᵢ) < tol { return p } pᵢ = p // Compute pᵢ₊₁. } // The procedure was unsuccessful. return nil } /// Finds a solution *p* to *f*(*x*) = 0 given the continuously differentiable /// function *f* of class *C*² and an initial approximation *p*₀. /// /// **Newton’s method** is a root-finding method that generates the sequence /// {*pᵢ*} by letting *pᵢ* = *pᵢ*₋₁ − *f*(*pᵢ*₋₁) / *f*′(*pᵢ*₋₁), for each /// *i* ≥ 1. If the sequence converges to *p*, then a solution *p* is obtained. /// /// Algorithm /// --------- /// /// ``` /// INPUT: Continuously differentiable function f; initial approximation p₀; /// tolerance TOL; maximum number of iterations N₀. /// OUTPUT: Approximate solution p, or nil. /// /// Step 1: Set i = 0. /// Step 2: While i < N₀ do Steps 3–5. /// Step 3: Set p = p₀ − f(p₀) / f′(p₀). (Compute pᵢ.) /// Step 4: If |p − p₀| < TOL, then OUTPUT p; STOP. /// (The procedure completed successfully.) /// Step 5: Set i = i + 1; p₀ = p. (Update p₀.) /// Step 6: OUTPUT nil; STOP. (The procedure was unsuccessful.) /// ``` /// /// Example /// ------- /// /// Use Newton’s method to determine an approximation to the root of the /// function *f*(*x*) = cos *x* − *x* that is accurate to at least within 10⁻⁴. /// /// **Solution:** Since *f*(*x*) = cos *x* − *x*, we have /// *f*′(*x*) = -sin *x* − 1. With *p*₀ = π/4, we generate the sequence {*pᵢ*} /// defined by /// /// *pᵢ* = *pᵢ*₋₁ − *f*(*pᵢ*₋₁) / *f*′(*pᵢ*₋₁) = *pᵢ*₋₁ − (cos *pᵢ*₋₁ − *pᵢ*₋₁) / (-sin *pᵢ*₋₁ − 1) /// /// for each *i* ≥ 1. This gives the values in the table below. After 4 /// iterations, *p*₃ ≈ 0.739085133215161 approximates the root *p* of the /// function *f*. /// /// ``` /// --------------------- /// n p_n /// --------------------- /// 0 0.7853981633974483 /// 1 0.739536133515238 /// 2 0.73908517810601 /// 3 0.739085133215161 /// --------------------- /// ``` /// /// Analysis /// -------- /// /// Since the absolute error is squared (the number of accurate digits roughly /// doubles) at each step, the method converges quadratically, which is /// considerably fast. /// /// Usage /// ----- /// /// ``` /// // f(x) = cos x − x ⇒ f′(x) = -sin x − 1 /// func f(_ x: Double) -> Double { return cos(x) - x } /// func df(_ x: Double) -> Double { return -sin(x) - 1 } /// /// // Prints "x = 0.739085133215161". /// if let x = newton(f: f, df: df, p0: .pi / 4, tol: 1.0e-4) { /// print("x = \(x)") /// } else { /// print("The method failed after 100 iterations.") /// } /// ``` /// /// **Source:** Burden, Richard L. and Faires, J. Douglas. /// *Numerical Analysis, Ninth Edition* (2010), pp. 68. /// /// - Author: Kris Torres /// /// - Requires: `tol` > 0 and `n` > 0. /// /// - Complexity: *O*(*n*) /// /// - Parameter f: The continuously differentiable function *f*(*x*) of class /// *C*². /// - Parameter df: The first derivative *f*′(*x*). /// - Parameter p0: The initial approximation. /// - Parameter tol: The error tolerance of the approximation. The default is /// 10⁻⁴ (`1.0e-4`). /// - Parameter n: The maximum number of iterations to perform. The default is /// `100`. /// /// - Returns: An *optional* that contains the approximate solution *p*, or /// `nil` if Newton’s method fails. public func newton(f: (Double) -> Double, df: (Double) -> Double, p0: Double, tol: Double = 1.0e-4, n: Int = 100) -> Double? { // The procedure requires TOL > 0 and n > 0. if tol <= 0.0 || n <= 0 { return nil } var pᵢ = p0 for _ in 0 ..< n { let p = pᵢ - f(pᵢ) / df(pᵢ) // Compute pᵢ. // The procedure completed successfully. if abs(p - pᵢ) < tol { return p } pᵢ = p // Compute pᵢ₊₁. } // The procedure was unsuccessful. return nil } /// Finds a solution *p* to *f*(*x*) = 0 given the continuous function *f* and /// initial approximations *p*₀ and *p*₁. /// /// The **secant method** is a root-finding method that uses a succession of /// roots of secant lines to better approximate *p*. It can be thought of as a /// finite difference approximation of Newton’s method. /// /// The method generates the sequence {*pᵢ*} by letting /// *pᵢ* = *pᵢ*₋₁ − *f*(*pᵢ*₋₁)(*pᵢ*₋₁ − *pᵢ*₋₂) / (*f*(*pᵢ*₋₁) − *f*(*pᵢ*₋₂)), /// for each *i* ≥ 2. If the sequence converges to *p*, then a solution *p* is /// obtained. /// /// Algorithm /// --------- /// /// ``` /// INPUT: Continuous function f; initial approximations p₀, p₁; tolerance TOL; /// maximum number of iterations N₀. /// OUTPUT: Approximate solution p, or nil. /// /// Step 1: Set i = 1. /// Step 2: While i < N₀ do Steps 3–5. /// Step 3: Set q₀ = f(p₀); q₁ = f(p₁); p = p₁ − q₁(p₁ − p₀) / (q₁ − q₀). /// (Compute pᵢ.) /// Step 4: If |p − p₁| < TOL, then OUTPUT p; STOP. /// (The procedure completed successfully.) /// Step 5: Set i = i + 1; p₀ = p₁; p₁ = p. (Update p₀ and p₁.) /// Step 6: OUTPUT nil; STOP. (The procedure was unsuccessful.) /// ``` /// /// Example /// ------- /// /// Use the secant method to determine an approximation to the root of the /// function *f*(*x*) = cos *x* − *x* that is accurate to at least within 10⁻⁴. /// /// **Solution:** Suppose we use *p*₀ = 0.5 and *p*₁ = π/4. We then generate the /// sequence {*pᵢ*} defined by /// /// *pᵢ* = *pᵢ*₋₁ − (cos *pᵢ*₋₁ − *pᵢ*₋₁)(*pᵢ*₋₁ − *pᵢ*₋₂) / ((cos *pᵢ*₋₁ − *pᵢ*₋₁) − (cos *pᵢ*₋₂ − *pᵢ*₋₂)) /// /// for each *i* ≥ 2. These give the values in the table below. After 5 /// iterations, *p*₄ ≈ 0.739085149337276 approximates the root *p* of the /// function *f*. /// /// ``` /// --------------------- /// n p_n /// --------------------- /// 0 0.5 /// 1 0.7853981633974483 /// 2 0.736384138836582 /// 3 0.73905813921389 /// 4 0.739085149337276 /// --------------------- /// ``` /// /// Analysis /// -------- /// /// The order of convergence is the golden ratio φ = (1 + √(5)) / 2 ≈ 1.618. /// Thus, the convergence is superlinear, but not quite quadratic. /// /// Usage /// ----- /// /// ``` /// // f(x) = cos x − x /// func f(_ x: Double) -> Double { return cos(x) - x } /// /// // Prints "x = 0.739085149337276". /// if let x = secant(f: f, p0: 0.5, p1: .pi / 4, tol: 1.0e-4) { /// print("x = \(x)") /// } else { /// print("The method failed after 100 iterations.") /// } /// ``` /// /// **Source:** Burden, Richard L. and Faires, J. Douglas. /// *Numerical Analysis, Ninth Edition* (2010), pp. 72. /// /// - Author: Kris Torres /// /// - Requires: `tol` > 0 and `n` > 0. /// /// - Complexity: *O*(*n*) /// /// - SeeAlso: `newton(f:df:p0:tol:n:)` /// /// - Parameter f: The continuous function *f*(*x*). /// - Parameter p0: The first initial approximation. /// - Parameter p1: The second initial approximation. /// - Parameter tol: The error tolerance of the approximation. The default is /// 10⁻⁴ (`1.0e-4`). /// - Parameter n: The maximum number of iterations to perform. The default is /// `100`. /// /// - Returns: An *optional* that contains the approximate solution *p*, or /// `nil` if the secant method fails. public func secant(f: (Double) -> Double, p0: Double, p1: Double, tol: Double = 1.0e-4, n: Int = 100) -> Double? { // The procedure requires TOL > 0 and n > 0. if tol <= 0.0 || n <= 0 { return nil } // Create mutable copies of p₀ and p₁. var p₀ = p0 var p₁ = p1 for _ in 1 ..< n { let q₀ = f(p₀) let q₁ = f(p₁) let p = p₁ - q₁ * (p₁ - p₀) / (q₁ - q₀) // Compute p. // The procedure completed successfully. if abs(p - p₁) < tol { return p } // Update p₀ and p₁. p₀ = p₁ p₁ = p } // The procedure was unsuccessful. return nil }
mit
e467c5c3c45a31d8fbbb4b0bcb34d345
32.506718
108
0.525978
2.834389
false
false
false
false
roambotics/swift
test/Generics/issue-52042.swift
2
1418
// RUN: %target-swift-frontend -debug-generic-signatures -typecheck %s 2>&1 | %FileCheck %s // https://github.com/apple/swift/issues/52042 protocol R {} protocol Q { associatedtype Assoc } // CHECK-LABEL: .P1@ // CHECK-LABEL: Requirement signature: <Self where Self.[P1]T == Self.[P1]U.[P1]U, Self.[P1]U : P1, Self.[P1]U : Q, Self.[P1]U == Self.[P1]T.[P1]U, Self.[P1]U.[Q]Assoc : R> protocol P1 { associatedtype T where T == U.U associatedtype U : P1, Q where U.Assoc : R, U == T.U } // CHECK-LABEL: .P2@ // CHECK-LABEL: Requirement signature: <Self where Self.[P2]T == Self.[P2]U.[P2]U, Self.[P2]U : P2, Self.[P2]U : Q, Self.[P2]U == Self.[P2]T.[P2]U, Self.[P2]U.[Q]Assoc : R> protocol P2 { associatedtype T : P2 where T == U.U associatedtype U : P2, Q where U.Assoc : R, U == T.U } // CHECK-LABEL: .P3@ // CHECK-LABEL: Requirement signature: <Self where Self.[P3]T : Q, Self.[P3]T == Self.[P3]U.[P3]U, Self.[P3]U : P3, Self.[P3]U == Self.[P3]T.[P3]U, Self.[P3]T.[Q]Assoc : R> protocol P3 { associatedtype T : Q where T.Assoc : R, T == U.U associatedtype U : P3 where U == T.U } // CHECK-LABEL: .P4@ // CHECK-LABEL: Requirement signature: <Self where Self.[P4]T : Q, Self.[P4]T == Self.[P4]U.[P4]U, Self.[P4]U : P4, Self.[P4]U == Self.[P4]T.[P4]U, Self.[P4]T.[Q]Assoc : R> protocol P4 { associatedtype T : P4, Q where T.Assoc : R, T == U.U associatedtype U : P4 where U.Assoc : R, U == T.U }
apache-2.0
dbb1471750470a8ad5dd3b10d9dc0129
37.324324
172
0.618477
2.411565
false
false
false
false
xuzhuoxi/SearchKit
Source/cs/cache/valuecoding/PinyinWordsStrategyImpl.swift
1
5298
// // PinyinWordsStrategyImpl.swift // SearchKit // // Created by 许灼溪 on 15/12/16. // // import Foundation /** * * @author xuzhuoxi * */ class PinyinWordsStrategyImpl : AbstractValueCoding , ValueCodingStrategyProtocol, ReflectionProtocol { /** * 单声母 */ fileprivate let danshengmu:[Character] = ["b", "p", "m", "f", "d", "t", "n", "l", "g", "k", "h", "j", "q", "x", "r", "z", "c", "s", "w", "y" ] /** * 空格 */ fileprivate let space : Character = " " /** * 从头开始遍历<br> * 遇到以下情况则加入到返回字符串中:<br> * 1.第一个字符<br> * 2.空格后的第一个字符<br> * 3.声母字符<br> * 把以上得到的字符按遍历顺序组成字符串返回<br> */ final func getSimplifyValue(_ value: String) -> String { if value.isEmpty { return "" } sb.removeAll(keepingCapacity: true) var add : Bool = false var first = true for c in value.characters { if c != space { if add || first || danshengmu.contains(c) { sb.append(c) add = false } }else{ add = true } first = false } return sb } final func getDimensionKeys(_ simplifyValue: String) ->[String] { return abstractGetDimensionKeys(simplifyValue) } /** * 过滤输入字符串,保留中文字符、拼音字符及空格<br> */ final func filter(_ input: String) -> String { if input.isEmpty { return input } sb.removeAll(keepingCapacity: true) for c in input.characters { if ChineseUtils.isChinese(c) || ChineseUtils.isPinyinChar(c) { sb.append(c) } } return sb } /** * 翻译过程:<br> * 1.对字符串的中文进行翻译,前后以空格相隔,对于多音字,则进行自由组合<br> * 2.对上面的每一个字符串进行简化{@link #getSimplifyValue(String)}<br> * 3.返回上一步字符串组成的非重复数组<br> * * @see #getSimplifyValue(String) */ final func translate(_ filteredInput : String) ->[String] { var rs : [String] if ChineseUtils.hasChinese(filteredInput) { let wordPinyinMap = CachePool.instance.getCache(CacheNames.PINYIN_WORD) as! CharacterLibraryProtocol let indexs = ChineseUtils.getChineseIndexs(filteredInput) var values = [[String]]() var system = [Int](repeating: 0, count: indexs.count) var maxValue = 1 for i in 0..<indexs.count { let key: String = filteredInput[indexs[i]]! let keyChar = Character(key) if wordPinyinMap.isKey(keyChar) { values[i] = wordPinyinMap.getValues(keyChar)! }else{ values[i] = [""] } system[i] = values[i].count maxValue *= system[i] } rs = [String]() for i in 0 ..< maxValue { sb.removeAll(keepingCapacity: true) sb.append(filteredInput) let temp = MathUtils.tenToCustomSystem(i, system) for j in (0..<(indexs.count-1)).reversed() { let sourceIndex = indexs[j] let valueIndex = temp[j] let index = sb.characters.index(sb.startIndex, offsetBy: sourceIndex) sb.remove(at: index) sb.insert(contentsOf: (" " + values[j][valueIndex] + " ").characters, at: index) } rs[i] = sb.trim() } }else{ rs = [filteredInput] } if !rs.isEmpty { for i in 0..<rs.count { rs[i] = getSimplifyValue(rs[i]) } ArrayUtils.cleanRepeat(&rs) } return rs } /** * 简化编码的计算过程:<br> * 1.截取第二位开始的字符中进行无重复基于顺序的自由组合,详细请看{@link StringCombination}<br> * 2.第一位分别拼接上面得的到字符串数组<br> * 3.返回第一位字符以及上面的字符串数组组成的数组<br> * * @see StringCombination */ override final func computeDimensionKeys(_ simplifyValue : String) ->[String] { if simplifyValue.isEmpty { return [] } if 1 == simplifyValue.length { return [simplifyValue] } let maxDimension = 2 let source = simplifyValue.explode() let subSource = [String](source[1..<source.count]) let subRs = StringCombination.getDimensionCombinationArray(subSource, dimensionValue: maxDimension - 1, isRepeat: false)! var rs : [String] = [String](repeating: "", count: subRs.count+1) rs[0] = source[0] for i in 1 ..< rs.count { rs[i] = rs[0] + subRs[i-1] } return rs } static func newInstance() -> ReflectionProtocol { return PinyinWordsStrategyImpl() } }
mit
8f104a7ae3b13a1340c1363ae1201769
29.327044
147
0.509747
3.802839
false
false
false
false
JohnSansoucie/MyProject2
BlueCap/Central/PeripheralServiceCharacteristicEditValueViewController.swift
1
4548
// // PeripheralServiceCharacteristicEditValueViewController.swift // BlueCap // // Created by Troy Stribling on 7/20/14. // Copyright (c) 2014 gnos.us. All rights reserved. // import UIKit import BlueCapKit class PeripheralServiceCharacteristicEditValueViewController : UIViewController, UITextFieldDelegate { @IBOutlet var valueTextField : UITextField! var characteristic : Characteristic! var peripheralViewController : PeripheralViewController? var valueName : String? var progressView = ProgressView() required init(coder aDecoder:NSCoder) { super.init(coder:aDecoder) } override func viewDidLoad() { super.viewDidLoad() if let valueName = self.valueName { self.navigationItem.title = valueName if let value = self.characteristic.stringValue?[valueName] { self.valueTextField.text = value } } self.navigationItem.backBarButtonItem = UIBarButtonItem(title:"", style:.Bordered, target:nil, action:nil) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) NSNotificationCenter.defaultCenter().addObserver(self, selector:"peripheralDisconnected", name:BlueCapNotification.peripheralDisconnected, object:self.characteristic.service.peripheral) NSNotificationCenter.defaultCenter().addObserver(self, selector:"didBecomeActive", name:BlueCapNotification.didBecomeActive, object:nil) NSNotificationCenter.defaultCenter().addObserver(self, selector:"didResignActive", name:BlueCapNotification.didResignActive, object:nil) } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) NSNotificationCenter.defaultCenter().removeObserver(self) } func peripheralDisconnected() { Logger.debug("PeripheralServiceCharacteristicEditValueViewController#peripheralDisconnected") if let peripheralViewController = self.peripheralViewController { if peripheralViewController.peripehealConnected { self.presentViewController(UIAlertController.alertWithMessage("Peripheral disconnected") {(action) in peripheralViewController.peripehealConnected = false self.navigationController?.popViewControllerAnimated(true) }, animated:true, completion:nil) } } } func didResignActive() { self.navigationController?.popToRootViewControllerAnimated(false) Logger.debug("PeripheralServiceCharacteristicEditValueViewController#didResignActive") } func didBecomeActive() { Logger.debug("PeripheralServiceCharacteristicEditValueViewController#didBecomeActive") } // UITextFieldDelegate func textFieldShouldReturn(textField: UITextField!) -> Bool { if let newValue = self.valueTextField.text { let afterWriteSuceses = {(characteristic:Characteristic) -> Void in self.progressView.remove() self.navigationController?.popViewControllerAnimated(true) return } let afterWriteFailed = {(error:NSError) -> Void in self.progressView.remove() self.presentViewController(UIAlertController.alertOnError(error) {(action) in self.navigationController?.popViewControllerAnimated(true) return } , animated:true, completion:nil) } self.progressView.show() if let valueName = self.valueName { if var values = self.characteristic.stringValue { values[valueName] = newValue let write = characteristic.writeString(values) write.onSuccess(afterWriteSuceses) write.onFailure(afterWriteFailed) } else { let write = characteristic.writeData(newValue.dataFromHexString()) write.onSuccess(afterWriteSuceses) write.onFailure(afterWriteFailed) } } else { Logger.debug("VALUE: \(newValue.dataFromHexString())") let write = characteristic.writeData(newValue.dataFromHexString()) write.onSuccess(afterWriteSuceses) write.onFailure(afterWriteFailed) } } return true } }
mit
ba1c8852cbad05bb94b056c5ada32f10
41.90566
193
0.648637
6.015873
false
false
false
false
CalQL8ed-K-OS/SwiftProceduralLevelGeneration
Procedural/Code/ViewController.swift
1
1633
// // ViewController.swift // Procedural // // Created by Xavi on 2/16/15. // Copyright (c) 2015 Xavi. All rights reserved. // import UIKit import SpriteKit import AVFoundation class ViewController: UIViewController { @IBOutlet var skView:SKView! { get { return view as! SKView } set { view = newValue } } private var didLayoutSubviews:Bool = false private var bgmPlayer = ViewController.createBackgroundMusicPlayer() override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() if didLayoutSubviews { return } didLayoutSubviews = true skView.showsFPS = true skView.showsNodeCount = true skView.showsDrawCount = true bgmPlayer.play() let scene = Scene(size: skView.bounds.size) scene.scaleMode = SKSceneScaleMode.AspectFill skView.presentScene(scene) } override func shouldAutorotate() -> Bool { return true } override func supportedInterfaceOrientations() -> Int { return Int(UIInterfaceOrientationMask.Landscape.rawValue) } } private extension ViewController { class func createBackgroundMusicPlayer() -> AVAudioPlayer { var error:NSError? let url = NSBundle.mainBundle().URLForResource("SillyFun", withExtension: "mp3") let player = AVAudioPlayer(contentsOfURL: url, error: &error) if let error = error { println(error) } player.numberOfLoops = -1 player.volume = 0.2 player.prepareToPlay() return player } }
mit
e5400ff50c08e79fd06734142014fc12
26.216667
119
0.633803
5.040123
false
false
false
false
kingwangboss/OneJWeiBo
OneJWeiBo/OneJWeiBo/Classes/Main/OAuth/OAurhViewController.swift
1
6523
// // OAurhViewController.swift // OneJWeiBo // // Created by One'J on 16/4/6. // Copyright © 2016年 One'J. All rights reserved. // import UIKit import SVProgressHUD class OAurhViewController: UIViewController { // MARK:- 控件属性 @IBOutlet weak var webView: UIWebView! @IBOutlet weak var OJbtn: UIButton! // MARK:- 系统回调函数 override func viewDidLoad() { super.viewDidLoad() //设置导航栏内容 setNavigationBar() //加载网页 loadPage() //设置按钮(获取用户账号密码的隐藏按钮,可以通过执行js代码转发用户账号密码到个人服务器) setupBtn() } } // MARK:- 设置UI相关 extension OAurhViewController { ///设置导航栏内容 private func setNavigationBar() { navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: #selector(OAurhViewController.closeItemClick)) navigationItem.rightBarButtonItem = UIBarButtonItem(title: "填充", style: .Plain, target: self, action: #selector(OAurhViewController.fillItemClick)) title = "登录页面" } ///加载网页 private func loadPage() { //获取登录页面的URL let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(app_key)&redirect_uri=\(redirect_uri)" //创建对应的NSUrl guard let url = NSURL(string: urlStr) else { return } //创建NSURLRequest对象 let request = NSURLRequest(URL: url) //加载request对象 webView.loadRequest(request) } ///设置按钮 private func setupBtn() { let btn = OJbtn btn.addTarget(self, action: #selector(OAurhViewController.click(_:)), forControlEvents: .TouchUpInside) } } // MARK:- 事件监听 extension OAurhViewController { @objc private func closeItemClick() { dismissViewControllerAnimated(true, completion: nil) SVProgressHUD.dismiss() } @objc private func fillItemClick() { //JS代码 let jsCode = "document.getElementById('userId').value='[email protected]';document.getElementById('passwd').value='haomage';" //执行JS代码 webView.stringByEvaluatingJavaScriptFromString(jsCode) } @objc private func click(btn : UIButton) { let js = "alert('账号:'+userId.value+'\\n密码:'+passwd.value)" webView.stringByEvaluatingJavaScriptFromString(js) btn.hidden = true } } // MARK:- UIWebView的代理方法 extension OAurhViewController : UIWebViewDelegate{ ///开始加载网页 func webViewDidStartLoad(webView: UIWebView) { SVProgressHUD.showWithStatus("哥正在为你加载") } ///网页加载完成 func webViewDidFinishLoad(webView: UIWebView) { SVProgressHUD.showSuccessWithStatus("加载成功") SVProgressHUD.dismiss() } ///加载网页失败 func webView(webView: UIWebView, didFailLoadWithError error: NSError?) { SVProgressHUD.showErrorWithStatus("加载失败") SVProgressHUD.dismiss() } ///准备加载一个页面的时候执行(true继续加载页面,false不会继续加载页面) func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { //获取加载网页的Url guard let url = request.URL else { return true } //获取NSUrl let urlStr = url.absoluteString //判断urlStr是否包含code= guard urlStr.containsString("code=") else { return true } //截取code=后面的字符串 let code = urlStr.componentsSeparatedByString("code=").last! //请求accessToken loadAccessToken(code) return false } } // MARK:- 请求数据 extension OAurhViewController { ///请求accessToken private func loadAccessToken(code:String) { NetworkTools.shareInstance.loadAccessToken(code) { (result, error) in //错误验校 if error != nil { print(error) return } //拿到结果 guard let accountDict = result else { print("没有获取授权后的数据") return } //将字典转成模型对象 let account = Useraccout(dict: accountDict) //请求用户信息 self.loadUserInfo(account) } } private func loadUserInfo(account : Useraccout) { //获得AccessToken guard let accessToken = account.access_token else { return } //获取uid guard let uid = account.uid else { return } //发送网络请求 NetworkTools.shareInstance.loadUserInfo(accessToken, uid: uid) { (result, error) in //错误验校 if error != nil { print(error) return } //拿到用户信息结果 guard let userInfoDict = result else { return } // 从字典中取出昵称和用户头像地址 account.screen_name = userInfoDict["screen_name"] as? String account.avatar_large = userInfoDict["avatar_large"] as? String //将account对象保存到沙盒 var accountPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! accountPath = (accountPath as NSString).stringByAppendingPathComponent("accout.plist") print(accountPath) //保存对象 NSKeyedArchiver.archiveRootObject(account, toFile: accountPath) //将account对象设置到单例对象中 UserAccountViewModel.shareIntance.account = account //退出当前控制器 self.dismissViewControllerAnimated(false, completion: { UIApplication.sharedApplication().keyWindow?.rootViewController = WelcomeViewController() }) } } }
apache-2.0
fbf9e32b47b07e77d8bb8d242308dc00
25.963303
155
0.574345
4.914716
false
false
false
false
wuzhenli/MyDailyTestDemo
navigationTitle_bug/navigationTitle_bug/ViewController.swift
1
1103
// // ViewController.swift // navigationTitle_bug // // Created by kfz on 16/11/12. // Copyright © 2016年 kongfz. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() title = NSStringFromClass(self.classForCoder) title = NSStringFromClass(self.classForCoder) let appName: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as! String print(appName) // let c: = NSClassFromString(appName+".BViewController") } @IBAction func pushToAVC(_ sender: Any) { let avc = AViewController() navigationController?.pushViewController(avc, animated: true) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.isNavigationBarHidden = true } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) navigationController?.isNavigationBarHidden = false } }
apache-2.0
f16575858e7b1ead50704736918c738b
24
97
0.65
5.140187
false
false
false
false
MadArkitekt/Swift_Tutorials_And_Demos
WorldWeather/WorldWeather/MasterView/MasterViewController.swift
1
3791
/* * Copyright (c) 2014 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit class MasterViewController: UITableViewController { var detailViewController: DetailViewController? = nil let weatherData = WeatherData() override func awakeFromNib() { super.awakeFromNib() if UIDevice.current.userInterfaceIdiom == .pad { self.clearsSelectionOnViewWillAppear = false self.preferredContentSize = CGSize(width: 320.0, height: 600.0) } prepareNavigationBarAppearance() } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. if let split = self.splitViewController { let controllers = split.viewControllers detailViewController = controllers[controllers.count-1].topViewController as? DetailViewController if let detailViewController = detailViewController { detailViewController.cityWeather = weatherData.cities[0] } } self.title = "Cities" tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 100 } // MARK: - Segues override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showDetail" { if let indexPath = self.tableView.indexPathForSelectedRow() { let controller = (segue.destinationViewController as UINavigationController).topViewController as DetailViewController controller.cityWeather = weatherData.cities[indexPath.row] controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem() } } } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return weatherData.cities.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("CityCell", forIndexPath: indexPath) as CityTableViewCell let city = weatherData.cities[indexPath.row] cell.cityWeather = city return cell } private func prepareNavigationBarAppearance() { let font = UIFont(name:"HelveticaNeue-Light", size:30) let regularVertical = UITraitCollection(verticalSizeClass: .Regular) UINavigationBar.appearanceForTraitCollection(regularVertical).titleTextAttributes = [NSFontAttributeName: font] let compactVertical = UITraitCollection(verticalSizeClass: .Compact) UINavigationBar.appearanceForTraitCollection(compactVertical).titleTextAttributes = [NSFontAttributeName:font.fontWithSize(20)] } }
gpl-2.0
de6d73aa151449369ef189a8271cc597
41.122222
135
0.752044
5.331927
false
false
false
false
davidjinhan/ButtonMenuPopup
ButtonMenuPopup/Presentables.swift
1
7081
// // Presentables.swift // ButtonMenuPopup // // Created by HanJin on 2017. 3. 27.. // Copyright © 2017년 DavidJinHan. All rights reserved. // import UIKit protocol TableViewCellPresentable { func configure(withPresenter presenter: Presentable) } protocol Presentable { } protocol LabelPresentable: Presentable { var text: String? { get } var textColor: UIColor { get } var fontSize: CGFloat { get } var fontWeight: CGFloat { get } var labelBackgroundColor: UIColor { get } var alignment: NSTextAlignment { get } var numberOfLines: Int { get } var lineBreakMode: NSLineBreakMode { get } var lineHeightMultiple: CGFloat { get } } extension LabelPresentable { var text: String? { return nil } var textColor: UIColor { return .black } var fontSize: CGFloat { return 14 } var fontWeight: CGFloat { return UIFontWeightMedium } var labelBackgroundColor: UIColor { return .clear } var alignment: NSTextAlignment { return .center } var numberOfLines: Int { return 1 } var lineBreakMode: NSLineBreakMode { return .byTruncatingTail } var lineHeightMultiple: CGFloat { return 1.0 } } protocol LabelTextChangablePresentable: LabelPresentable { var text: String? { get set } } extension LabelTextChangablePresentable { var text: String? { return nil } } protocol LabelColorChangablePresentable: LabelPresentable { var text: String? { get set } var textColor: UIColor { get set } } extension LabelColorChangablePresentable { var text: String? { return nil } var textColor: UIColor { return .black } } extension UILabel { func configure(withPresenter presenter: Presentable) { if let presenter = presenter as? LabelPresentable { backgroundColor = presenter.labelBackgroundColor if let text = presenter.text { numberOfLines = presenter.numberOfLines let nsText = text as NSString let textRange = NSRange(location: 0, length: nsText.length) let attributedString = NSMutableAttributedString(string: text) let style = NSMutableParagraphStyle() style.alignment = presenter.alignment style.lineHeightMultiple = presenter.lineHeightMultiple style.lineBreakMode = presenter.lineBreakMode attributedString.addAttributes([ NSParagraphStyleAttributeName: style, NSForegroundColorAttributeName: presenter.textColor, NSFontAttributeName: UIFont.systemFont(ofSize: presenter.fontSize, weight: presenter.fontWeight), ], range: textRange) attributedText = attributedString } } } } protocol ImageButtonPresentable: Presentable { var buttonImage: UIImage { get set } var buttonBackgroundColor: UIColor { get set } var buttonTintColor: UIColor? { get } var cornerRadius: CGFloat? { get } } extension ImageButtonPresentable { var buttonBackgroundColor: UIColor { return .white } var buttonTintColor: UIColor? { return nil } var cornerRadius: CGFloat? { return nil } } protocol ImageWithTitleButtonPresentable: Presentable { var buttonImage: UIImage { get set } var buttonTitle: String { get set } var buttonTitleColor: UIColor { get } var buttonTitleFontSize: CGFloat { get } var buttonTitleFontWeight: CGFloat { get } var buttonBackgroundColor: UIColor { get } var buttonTintColor: UIColor? { get } var cornerRadius: CGFloat? { get } var borderWidth: CGFloat? { get } var borderColor: UIColor? { get } } extension ImageWithTitleButtonPresentable { var buttonTitleColor: UIColor { return .black } var buttonTitleFontSize: CGFloat { return 14 } var buttonTitleFontWeight: CGFloat { return UIFontWeightMedium } var buttonBackgroundColor: UIColor { return .white } var buttonTintColor: UIColor? { return nil } var cornerRadius: CGFloat? { return nil } var borderWidth: CGFloat? { return nil } var borderColor: UIColor? { return nil } } extension UIButton { func configure(withPresenter presenter: Presentable) { if let presenter = presenter as? ImageButtonPresentable { setImage(presenter.buttonImage, for: .normal) setTitle(nil, for: .normal) backgroundColor = presenter.buttonBackgroundColor if let buttonTintColor = presenter.buttonTintColor { tintColor = buttonTintColor } if let cornerRadius = presenter.cornerRadius { layer.masksToBounds = true layer.cornerRadius = cornerRadius } } if let presenter = presenter as? ImageWithTitleButtonPresentable { setImage(presenter.buttonImage, for: .normal) setTitle(presenter.buttonTitle, for: .normal) setTitleColor(presenter.buttonTitleColor, for: .normal) titleLabel?.font = UIFont.systemFont(ofSize: presenter.buttonTitleFontSize, weight: presenter.buttonTitleFontWeight) backgroundColor = presenter.buttonBackgroundColor if let buttonTintColor = presenter.buttonTintColor { tintColor = buttonTintColor } if let cornerRadius = presenter.cornerRadius { layer.masksToBounds = true layer.cornerRadius = cornerRadius } if let borderWidth = presenter.borderWidth { layer.borderWidth = borderWidth } if let borderColor = presenter.borderColor { layer.borderColor = borderColor.cgColor } } } } protocol ImagePresentable: Presentable { var image: UIImage { get set } var imageBackgroundColor: UIColor { get set } var cornerRadius: CGFloat? { get set } var imageTintColor: UIColor? { get } } extension ImagePresentable { var imageBackgroundColor: UIColor { return .white } var cornerRadius: CGFloat? { return nil } var imageTintColor: UIColor? { return nil } } extension UIImageView { func configure(withPresenter presenter: Presentable) { if let presenter = presenter as? ImagePresentable { image = presenter.image backgroundColor = presenter.imageBackgroundColor if let cornerRadius = presenter.cornerRadius { layer.masksToBounds = true layer.cornerRadius = cornerRadius } if let imageTintColor = presenter.imageTintColor { tintColor = imageTintColor } } } }
mit
910dcde1b1888dd7da70a70a43ed98b6
26.434109
128
0.621786
5.499611
false
false
false
false
AdaptiveMe/adaptive-arp-api-lib-darwin
Pod/Classes/Sources.Api/AppContextWebviewBridge.swift
1
11109
/** --| ADAPTIVE RUNTIME PLATFORM |---------------------------------------------------------------------------------------- (C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>. 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 appli- -cable 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. Original author: * Carlos Lozano Diez <http://github.com/carloslozano> <http://twitter.com/adaptivecoder> <mailto:[email protected]> Contributors: * Ferran Vila Conesa <http://github.com/fnva> <http://twitter.com/ferran_vila> <mailto:[email protected]> * See source code files for contributors. Release: * @version v2.2.15 -------------------------------------------| aut inveniam viam aut faciam |-------------------------------------------- */ import Foundation /** Interface for webview context management purposes Auto-generated implementation of IAppContextWebview specification. */ public class AppContextWebviewBridge : IAppContextWebview { /** Group of API. */ private var apiGroup : IAdaptiveRPGroup = IAdaptiveRPGroup.Kernel public func getAPIGroup() -> IAdaptiveRPGroup? { return self.apiGroup } /** API Delegate. */ private var delegate : IAppContextWebview? = nil /** Constructor with delegate. @param delegate The delegate implementing platform specific functions. */ public init(delegate : IAppContextWebview?) { self.delegate = delegate } /** Get the delegate implementation. @return IAppContextWebview delegate that manages platform specific functions.. */ public final func getDelegate() -> IAppContextWebview? { return self.delegate } /** Set the delegate implementation. @param delegate The delegate implementing platform specific functions. */ public final func setDelegate(delegate : IAppContextWebview) { self.delegate = delegate; } /** Additional views may be added to an application - a separate activity - and if these will make calls to the ARP methods, they must be registered by adding them to the context. When they are added to the context, ARP methods are bound to the webview so that they're callable from the HTML application. The primary webview should not be added using this method. @param webView Platform specific webview reference (WebView, UIWebView, WKWebView,etc.) @since v2.0 */ public func addWebview(webView : AnyObject ) { // Start logging elapsed time. let tIn : NSTimeInterval = NSDate.timeIntervalSinceReferenceDate() let logger : ILogging? = AppRegistryBridge.sharedInstance.getLoggingBridge() if (logger != nil) { logger!.log(ILoggingLogLevel.Debug, category: getAPIGroup()!.toString(), message: "AppContextWebviewBridge executing addWebview...") } if (self.delegate != nil) { self.delegate!.addWebview(webView) if (logger != nil) { logger!.log(ILoggingLogLevel.Debug, category: getAPIGroup()!.toString(), message: "AppContextWebviewBridge executed 'addWebview' in \(UInt(tIn.distanceTo(NSDate.timeIntervalSinceReferenceDate())*1000)) ms.") } } else { if (logger != nil) { logger!.log(ILoggingLogLevel.Error, category: getAPIGroup()!.toString(), message: "AppContextWebviewBridge no delegate for 'addWebview'.") } } } /** Evaluate the specified javascript on the main webview of the application. @param javaScriptText The javascript expression to execute on the webview. */ public func executeJavaScript(javaScriptText : String ) { // Start logging elapsed time. let tIn : NSTimeInterval = NSDate.timeIntervalSinceReferenceDate() let logger : ILogging? = AppRegistryBridge.sharedInstance.getLoggingBridge() if (logger != nil) { logger!.log(ILoggingLogLevel.Debug, category: getAPIGroup()!.toString(), message: "AppContextWebviewBridge executing executeJavaScript...") } if (self.delegate != nil) { self.delegate!.executeJavaScript(javaScriptText) if (logger != nil) { logger!.log(ILoggingLogLevel.Debug, category: getAPIGroup()!.toString(), message: "AppContextWebviewBridge executed 'executeJavaScript' in \(UInt(tIn.distanceTo(NSDate.timeIntervalSinceReferenceDate())*1000)) ms.") } } else { if (logger != nil) { logger!.log(ILoggingLogLevel.Error, category: getAPIGroup()!.toString(), message: "AppContextWebviewBridge no delegate for 'executeJavaScript'.") } } } /** Evaluate the specified javascript on the specified webview of the application. @param javaScriptText The javascript expression to execute on the webview. @param webViewReference The target webview on which to execute the expression. */ public func executeJavaScript(javaScriptText : String , webViewReference : AnyObject ) { // Start logging elapsed time. let tIn : NSTimeInterval = NSDate.timeIntervalSinceReferenceDate() let logger : ILogging? = AppRegistryBridge.sharedInstance.getLoggingBridge() if (logger != nil) { logger!.log(ILoggingLogLevel.Debug, category: getAPIGroup()!.toString(), message: "AppContextWebviewBridge executing executeJavaScript...") } if (self.delegate != nil) { self.delegate!.executeJavaScript(javaScriptText, webViewReference: webViewReference) if (logger != nil) { logger!.log(ILoggingLogLevel.Debug, category: getAPIGroup()!.toString(), message: "AppContextWebviewBridge executed 'executeJavaScript' in \(UInt(tIn.distanceTo(NSDate.timeIntervalSinceReferenceDate())*1000)) ms.") } } else { if (logger != nil) { logger!.log(ILoggingLogLevel.Error, category: getAPIGroup()!.toString(), message: "AppContextWebviewBridge no delegate for 'executeJavaScript'.") } } } /** Returns a reference to the main application webview. This is the first application webview and can not be removed with the removeWebview method. The object returned should be cast to the platform specific implementation WebView, WKWebView, etc. @return Object representing the specific and primary webview instance of the application. @since v2.0 */ public func getWebviewPrimary() -> AnyObject? { // Start logging elapsed time. let tIn : NSTimeInterval = NSDate.timeIntervalSinceReferenceDate() let logger : ILogging? = AppRegistryBridge.sharedInstance.getLoggingBridge() if (logger != nil) { logger!.log(ILoggingLogLevel.Debug, category: getAPIGroup()!.toString(), message: "AppContextWebviewBridge executing getWebviewPrimary...") } var result : AnyObject? = nil if (self.delegate != nil) { result = self.delegate!.getWebviewPrimary() if (logger != nil) { logger!.log(ILoggingLogLevel.Debug, category: getAPIGroup()!.toString(), message: "AppContextWebviewBridge executed 'getWebviewPrimary' in \(UInt(tIn.distanceTo(NSDate.timeIntervalSinceReferenceDate())*1000)) ms.") } } else { if (logger != nil) { logger!.log(ILoggingLogLevel.Error, category: getAPIGroup()!.toString(), message: "AppContextWebviewBridge no delegate for 'getWebviewPrimary'.") } } return result } /** Returns an array of webviews currently managed by the context - composed of primary and the list of those added. This method will always return at least one element; the primary webview. @return Array with all the Webview instances being managed by ARP. @since v2.0 */ public func getWebviews() -> [AnyObject]? { // Start logging elapsed time. let tIn : NSTimeInterval = NSDate.timeIntervalSinceReferenceDate() let logger : ILogging? = AppRegistryBridge.sharedInstance.getLoggingBridge() if (logger != nil) { logger!.log(ILoggingLogLevel.Debug, category: getAPIGroup()!.toString(), message: "AppContextWebviewBridge executing getWebviews...") } var result : [AnyObject]? = nil if (self.delegate != nil) { result = self.delegate!.getWebviews() if (logger != nil) { logger!.log(ILoggingLogLevel.Debug, category: getAPIGroup()!.toString(), message: "AppContextWebviewBridge executed 'getWebviews' in \(UInt(tIn.distanceTo(NSDate.timeIntervalSinceReferenceDate())*1000)) ms.") } } else { if (logger != nil) { logger!.log(ILoggingLogLevel.Error, category: getAPIGroup()!.toString(), message: "AppContextWebviewBridge no delegate for 'getWebviews'.") } } return result } /** When a webview is disposed - no longer in use from an external activity - the webview should be removed to unbind ARP functions and release resources. The primary webview can not be removed. @param webView The instance of the webview to be removed from the binding. @since v2.0 */ public func removeWebview(webView : AnyObject ) { // Start logging elapsed time. let tIn : NSTimeInterval = NSDate.timeIntervalSinceReferenceDate() let logger : ILogging? = AppRegistryBridge.sharedInstance.getLoggingBridge() if (logger != nil) { logger!.log(ILoggingLogLevel.Debug, category: getAPIGroup()!.toString(), message: "AppContextWebviewBridge executing removeWebview...") } if (self.delegate != nil) { self.delegate!.removeWebview(webView) if (logger != nil) { logger!.log(ILoggingLogLevel.Debug, category: getAPIGroup()!.toString(), message: "AppContextWebviewBridge executed 'removeWebview' in \(UInt(tIn.distanceTo(NSDate.timeIntervalSinceReferenceDate())*1000)) ms.") } } else { if (logger != nil) { logger!.log(ILoggingLogLevel.Error, category: getAPIGroup()!.toString(), message: "AppContextWebviewBridge no delegate for 'removeWebview'.") } } } } /** ------------------------------------| Engineered with ♥ in Barcelona, Catalonia |-------------------------------------- */
apache-2.0
2b6f4ab7f0d1d132d620e4abb63a68ed
41.719231
230
0.642928
5.234213
false
false
false
false
Artilles/FloppyCows
Floppy Cows/GameViewController.swift
1
3565
// // GameViewController.swift // Floppy Cows // // Created by Jon Bergen on 2014-09-20. // Copyright (c) 2014 Velocitrix. All rights reserved. // import UIKit import SpriteKit import AVFoundation var backgroundMusicPlayer:AVAudioPlayer = AVAudioPlayer() extension SKNode { class func unarchiveFromFile(file : NSString) -> SKNode? { if let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks") { var sceneData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)! var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData) archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene") let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as MenuScene archiver.finishDecoding() return scene } else { return nil } } } class GameViewController: UIViewController { //var Score = HighScore() override func viewDidLoad() { super.viewDidLoad() /*if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene { // Configure the view. let skView = self.view as SKView skView.showsFPS = true skView.showsNodeCount = true /* Sprite Kit applies additional optimizations to improve rendering performance */ skView.ignoresSiblingOrder = true /* Set the scale mode to scale to fit the window */ scene.scaleMode = .AspectFill skView.presentScene(scene) }*/ let skView = self.view as SKView let scene = MenuScene(size: CGSize(width: 1024, height: 768)) // DEBUG //skView.showsFPS = true //skView.showsNodeCount = true //skView.showsPhysics = true // SpriteKit applies additional optimizations to improve rendering performance skView.ignoresSiblingOrder = true // Set the scale mode to scale to fit the window scene.scaleMode = .AspectFill skView.presentScene(scene) } override func viewWillLayoutSubviews() { var bgMusicURL:NSURL = NSBundle.mainBundle().URLForResource("menuMusic", withExtension: "mp3")! backgroundMusicPlayer = AVAudioPlayer(contentsOfURL: bgMusicURL, error: nil) backgroundMusicPlayer.numberOfLoops = -1 backgroundMusicPlayer.prepareToPlay() backgroundMusicPlayer.play() /*var skView:SKView = self.view as SKView skView.showsFPS = true skView.showsNodeCount = true var scene:SKScene = GameScene.sceneWithSize(skView.bounds.size) scene.scaleMode = SKSceneScaleMode.AspectFill skView.presentScene(scene)*/ } override func shouldAutorotate() -> Bool { return true } override func supportedInterfaceOrientations() -> Int { if UIDevice.currentDevice().userInterfaceIdiom == .Phone { return Int(UIInterfaceOrientationMask.AllButUpsideDown.rawValue) } else { return Int(UIInterfaceOrientationMask.All.rawValue) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } override func prefersStatusBarHidden() -> Bool { return true } }
gpl-2.0
1c899435e3f229e33b8f8206816ea796
30.27193
104
0.618513
5.685805
false
false
false
false
bazelbuild/tulsi
src/TulsiGenerator/BazelXcodeProjectPatcher.swift
1
5427
// Copyright 2017 The Tulsi 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 Foundation // Provides methods to patch up Bazel specific PBX objects and references before project generation. // This will remove any invalid .xcassets in order to make Xcode happy, as well as apply a // BazelPBXReferencePatcher to any files that can't be found. As a backup, paths are set to be // relative to the Bazel exec root for non-generated files. final class BazelXcodeProjectPatcher { // FileManager used to check for presence of PBXFileReferences when patching. let fileManager: FileManager init(fileManager: FileManager) { self.fileManager = fileManager } // Rewrites the path for file references that it believes to be relative to Bazel's exec root. // This should be called before patching external references. private func patchFileReference(xcodeProject: PBXProject, file: PBXFileReference, url: URL, workspaceRootURL: URL) { // We only want to modify the path if the current path doesn't point to a valid file. guard !fileManager.fileExists(atPath: url.path) else { return } // Don't patch anything that isn't group relative. guard file.sourceTree == .Group else { return } // Guaranteed to have parent bc that's how we accessed it. // Parent guaranteed to be PBXGroup because it's a PBXFileReference let parent = file.parent as! PBXGroup // Just remove .xcassets that are not present. Unfortunately, Xcode's handling of .xcassets has // quite a number of issues with Tulsi and readonly files. // // .xcassets references in a project that are not present on disk will present a warning after // opening the main target. // // Readonly (not writeable) .xcassets that contain an .appiconset with a Contents.json will // trigger Xcode into an endless loop of // "You don’t have permission to save the file “Contents.json” in the folder <X>." // This is present in Xcode 8.3.3 and Xcode 9b2. guard !url.path.hasSuffix(".xcassets") else { parent.removeChild(file) return } // Default to be relative to the bazel exec root // This is for both source files as well as generated files (which always need to be relative // to the bazel exec root). let newPath = "\(xcodeProject.name).xcodeproj/\(PBXTargetGenerator.TulsiExecutionRootSymlinkPath)/\(file.path!)" parent.updatePathForChildFile(file, toPath: newPath, sourceTree: .SourceRoot) } // Handles patching PBXFileReferences that are not present on disk. This should be called before // calling patchExternalRepositoryReferences. func patchBazelRelativeReferences(_ xcodeProject: PBXProject, _ workspaceRootURL : URL) { // Exclude external references that have yet to be patched in. var queue = xcodeProject.mainGroup.children.filter{ $0.name != "external" } while !queue.isEmpty { let ref = queue.remove(at: 0) if let group = ref as? PBXGroup { // Queue up all children of the group so we can find all of their FileReferences. queue.append(contentsOf: group.children) } else if let file = ref as? PBXFileReference, let fileURL = URL(string: file.path!, relativeTo: workspaceRootURL) { self.patchFileReference(xcodeProject: xcodeProject, file: file, url: fileURL, workspaceRootURL: workspaceRootURL) } } } // Handles patching any groups that were generated under Bazel's magical "external" container to // proper filesystem references. This should be called after patchBazelRelativeReferences. func patchExternalRepositoryReferences(_ xcodeProject: PBXProject) { let mainGroup = xcodeProject.mainGroup guard let externalGroup = mainGroup.childGroupsByName["external"] else { return } // The external directory may contain files such as a WORKSPACE file, but we only patch folders let childGroups = externalGroup.children.filter { $0 is PBXGroup } as! [PBXGroup] for child in childGroups { // Resolve external workspaces via their more stable location in output base // <output base>/external remains between builds and contains all external workspaces // <execution root>/external is instead torn down on each build, breaking the paths to any // external workspaces not used in the particular target being built let resolvedPath = "\(xcodeProject.name).xcodeproj/\(PBXTargetGenerator.TulsiOutputBaseSymlinkPath)/external/\(child.name)" let newChild = mainGroup.getOrCreateChildGroupByName("@\(child.name)", path: resolvedPath, sourceTree: .SourceRoot) newChild.migrateChildrenOfGroup(child) } mainGroup.removeChild(externalGroup) } }
apache-2.0
747fa705e01973b9f3c6adb3666122ba
49.663551
129
0.707803
4.755263
false
false
false
false
superk589/DereGuide
DereGuide/Model/Favorite/FavoriteCard.swift
2
2058
// // FavoriteCard.swift // DereGuide // // Created by zzk on 2017/7/26. // Copyright © 2017 zzk. All rights reserved. // import Foundation import CoreData import CloudKit public class FavoriteCard: NSManagedObject { @nonobjc public class func fetchRequest() -> NSFetchRequest<FavoriteCard> { return NSFetchRequest<FavoriteCard>(entityName: "FavoriteCard") } @NSManaged public var cardID: Int32 @NSManaged public var createdAt: Date @NSManaged fileprivate var primitiveCreatedAt: Date public override func awakeFromInsert() { super.awakeFromInsert() primitiveCreatedAt = Date() } @discardableResult static func insert(into moc: NSManagedObjectContext, cardID: Int) -> FavoriteCard { let favoriteCard: FavoriteCard = moc.insertObject() favoriteCard.cardID = Int32(cardID) return favoriteCard } } extension FavoriteCard: Managed { public static var entityName: String { return "FavoriteCard" } public static var defaultSortDescriptors: [NSSortDescriptor] { return [NSSortDescriptor(key: #keyPath(FavoriteCard.cardID), ascending: false)] } public static var defaultPredicate: NSPredicate { return notMarkedForDeletionPredicate } } extension FavoriteCard: IDSearchable { var searchedID: Int { return Int(cardID) } } extension FavoriteCard: DelayedDeletable { @NSManaged public var markedForDeletionDate: Date? } extension FavoriteCard: RemoteDeletable { @NSManaged public var markedForRemoteDeletion: Bool @NSManaged public var remoteIdentifier: String? } extension FavoriteCard: UserOwnable { @NSManaged public var creatorID: String? } extension FavoriteCard: RemoteUploadable { public func toCKRecord() -> CKRecord { let record = CKRecord(recordType: RemoteFavoriteCard.recordType) record["cardID"] = cardID as CKRecordValue record["localCreatedAt"] = createdAt as NSDate return record } }
mit
3933e4d41009de03d50226fb5b15c257
24.395062
87
0.695673
4.739631
false
false
false
false
isaced/NSPress
Sources/App/Controllers/AdminController.swift
1
3486
import Vapor import HTTP import Routing import AuthProvider final class AdminController { func addRoutes(_ drop: Droplet) { // let router = drop.grouped("admin") router.get("login", handler: loginView) router.post("login", handler: login) // let protect = PasswordAuthenticationMiddleware(User.self) let routerSecure = router.grouped(protect) routerSecure.get("", handler: index) routerSecure.get("write-post", handler: writePostView) routerSecure.post("write-post", handler: writePost) // routerSecure.get("edit-post", Post.self, handler: editPostView) // routerSecure.post("edit-post", Post.self, handler: editPost) routerSecure.get("posts", handler: postsView) routerSecure.get("logout", handler: logout) } func index(_ request: Request) throws -> ResponseRepresentable { let postcCount = try Post.all().count return try drop.view.make("admin/index.leaf", ["postCount":postcCount]) } func loginView(_ request: Request) throws -> ResponseRepresentable { if request.auth.isAuthenticated(User.self) { return Response(redirect: "/admin/") } else { return try drop.view.make("admin/login.leaf") } } func login(_ request: Request) throws -> ResponseRepresentable { if request.auth.isAuthenticated(User.self) { return Response(redirect: "/admin/") }else{ do { // let ident = password // try request.auth.login(ident) return Response(redirect: "/admin/") } catch { return try drop.view.make("admin/login.leaf") } } } func logout(_ request: Request) throws -> ResponseRepresentable { if request.auth.isAuthenticated(User.self) { return Response(redirect: "/") } else { return Response(redirect: "/admin") } } func writePostView(_ request: Request) throws -> ResponseRepresentable { return try drop.view.make("/admin/write-post.leaf") } func writePost(_ request: Request) throws -> ResponseRepresentable { if let title = request.data["title"]?.string, let text = request.data["text"]?.string { let post = Post(title: title, text:text) do { try post.save() return Response(redirect: "/admin/posts") } } return try drop.view.make("/admin/write-post.leaf") } func postsView(_ request: Request) throws -> ResponseRepresentable { let posts = try Post.all() return try drop.view.make("admin/posts.leaf", ["posts":posts]) } func editPostView(_ request: Request, post: Post) throws -> ResponseRepresentable { return try drop.view.make("/admin/write-post.leaf", ["post": post]) } func editPost(_ request: Request, post: Post) throws -> ResponseRepresentable { guard let title = request.data["title"]?.string, let text = request.data["text"]?.string else { throw Abort(.noContent) } // if var p = try Post.query().filter("id", post.id!).first() { // p.title = title // p.text = text // try p.save() // } return Response(redirect: "/admin/posts") } }
mit
28537891dba7ee39be7240b7083a0ea4
33.514851
104
0.57315
4.515544
false
false
false
false
telldus/telldus-live-mobile-v3
ios/HomescreenWidget/UIViews/SensorWidget/Preview/SWPreviewSmallUIView.swift
1
3253
// // SWPreviewSmallUIView.swift // HomescreenWidgetExtension // // Created by Rimnesh Fernandez on 22/10/20. // Copyright © 2020 Telldus Technologies AB. All rights reserved. // import SwiftUI struct SWPreviewSmallUIView: View { let sensorWidgetStructure: SensorWidgetStructure var body: some View { let name = sensorWidgetStructure.name let label = sensorWidgetStructure.label let icon = sensorWidgetStructure.icon let value = sensorWidgetStructure.value let unit = sensorWidgetStructure.unit let luTime = SensorUtilities().getLastUpdatedDate(lastUpdated: sensorWidgetStructure.luTime) let luTimeString = SensorUtilities().getLastUpdatedString(lastUpdated: sensorWidgetStructure.luTime, timezone: sensorWidgetStructure.timezone) let isLarge = SensorUtilities().isValueLarge(value: value) let isUpdateTimeOld = SensorUtilities().isTooOld(lastUpdated: sensorWidgetStructure.luTime) let sensorLastUpdatedMode = SharedModule().getUserDefault(key: "sensorLastUpdatedModeKey") return VStack(spacing: 0) { VStack(alignment: .center, spacing: 0) { Text("\u{e911}") .foregroundColor(Color("widgetTextColorOne")) .font(.custom("telldusicons", size: 30)) .padding(.bottom, 2) Text(name) .foregroundColor(Color("widgetTextColorOne")) .font(.system(size: 14)) .lineLimit(1) .padding(.bottom, 2) if luTime != nil, sensorLastUpdatedMode == "0" { Text(luTime!, style: .relative) .foregroundColor(isUpdateTimeOld ? Color.red : Color("widgetTextColorTwo")) .font(.system(size: 12)) .multilineTextAlignment(.center) } if luTime != nil, sensorLastUpdatedMode == "1" { Text(luTimeString) .foregroundColor(isUpdateTimeOld ? Color.red : Color("widgetTextColorTwo")) .font(.system(size: 12)) } } .padding(.horizontal, 8) .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity) .background(Color("widgetTopBGC")) HStack (spacing: 0) { if !isLarge { Text(icon) .foregroundColor(Color("widgetTextColorThree")) .font(.custom("telldusicons", size: 40)) } VStack (alignment: .leading) { HStack (alignment: .lastTextBaseline) { Text(value) .foregroundColor(Color("widgetTextColorThree")) .font(.system(size: 26)) .lineLimit(1) Text(unit) .foregroundColor(Color("widgetTextColorThree")) .font(.system(size: 16)) .padding(.leading, -5) } Text(label) .foregroundColor(Color("widgetTextColorThree")) .font(.system(size: 12)) } .padding(.leading, 10) } .padding(.horizontal, 10) .padding(.vertical, 8) .clipShape(ContainerRelativeShapeSpecificCorner(corner: .bottomLeft, .bottomRight)) .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, alignment: .leading) .background(Color("widgetBottomBGC")) } .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity) } }
gpl-3.0
a269dcab86dc4931c6b33280425f2d53
37.714286
146
0.633149
4.312997
false
false
false
false
doctorn/hac-website
Sources/HaCWebsiteLib/Events/WorkshopEvent.swift
1
1364
import Foundation struct WorkshopEvent : Event { let title : String let time : DateInterval let tagLine : String let eventDescription : Text let color : String let hypePeriod : DateInterval let tags : [String] let workshop : Workshop let imageURL : String? let location : Location? let facebookEventID : String? var shouldShowAsUpdate: Bool { get { return self.hypePeriod.contains(Date()) } } var postCardRepresentation : PostCard { return PostCard( title: self.title, category: .workshop, description: self.tagLine, backgroundColor: self.color, //TODO imageURL: self.imageURL ) } init(title: String, time: DateInterval, tagLine : String, description: Text, color: String, hypePeriod: DateInterval, tags: [String], workshop: Workshop, imageURL: String? = nil, location: Location? = nil, facebookEventID : String? = nil) { self.title = title self.time = time self.tagLine = tagLine self.eventDescription = description self.color = color self.hypePeriod = hypePeriod self.tags = tags self.workshop = workshop self.imageURL = imageURL self.location = location self.facebookEventID = facebookEventID } }
mit
0feb6b08ce747b03165bc9cf78aa36f0
28.652174
95
0.620968
4.546667
false
false
false
false
pidjay/SideMenu
Pod/Classes/SideMenuManager.swift
1
13498
// // SideMenuManager.swift // // Created by Jon Kent on 12/6/15. // Copyright © 2015 Jon Kent. All rights reserved. // /* Example usage: // Define the menus SideMenuManager.menuLeftNavigationController = storyboard!.instantiateViewController(withIdentifier: "LeftMenuNavigationController") as? UISideMenuNavigationController SideMenuManager.menuRightNavigationController = storyboard!.instantiateViewController(withIdentifier: "RightMenuNavigationController") as? UISideMenuNavigationController // Enable gestures. The left and/or right menus must be set up above for these to work. // Note that these continue to work on the Navigation Controller independent of the View Controller it displays! SideMenuManager.menuAddPanGestureToPresent(toView: self.navigationController!.navigationBar) SideMenuManager.menuAddScreenEdgePanGesturesToPresent(toView: self.navigationController!.view) */ open class SideMenuManager : NSObject { @objc public enum MenuPresentMode : Int { case menuSlideIn case viewSlideOut case viewSlideInOut case menuDissolveIn } // Bounds which has been allocated for the app on the whole device screen internal static var appScreenRect: CGRect { let appWindowRect = UIApplication.shared.keyWindow?.bounds ?? UIWindow().bounds return appWindowRect } /** The presentation mode of the menu. There are four modes in MenuPresentMode: - menuSlideIn: Menu slides in over of the existing view. - viewSlideOut: The existing view slides out to reveal the menu. - viewSlideInOut: The existing view slides out while the menu slides in. - menuDissolveIn: The menu dissolves in over the existing view controller. */ open static var menuPresentMode: MenuPresentMode = .viewSlideOut /// Prevents the same view controller (or a view controller of the same class) from being pushed more than once. Defaults to true. open static var menuAllowPushOfSameClassTwice = true /// Pops to any view controller already in the navigation stack instead of the view controller being pushed if they share the same class. Defaults to false. open static var menuAllowPopIfPossible = false /// Width of the menu when presented on screen, showing the existing view controller in the remaining space. Default is 75% of the screen width. open static var menuWidth: CGFloat = max(round(min((appScreenRect.width), (appScreenRect.height)) * 0.75), 240) /// Duration of the animation when the menu is presented without gestures. Default is 0.35 seconds. open static var menuAnimationPresentDuration = 0.35 /// Duration of the animation when the menu is dismissed without gestures. Default is 0.35 seconds. open static var menuAnimationDismissDuration = 0.35 /// Amount to fade the existing view controller when the menu is presented. Default is 0 for no fade. Set to 1 to fade completely. open static var menuAnimationFadeStrength: CGFloat = 0 /// The amount to scale the existing view controller or the menu view controller depending on the `menuPresentMode`. Default is 1 for no scaling. Less than 1 will shrink, greater than 1 will grow. open static var menuAnimationTransformScaleFactor: CGFloat = 1 /// The background color behind menu animations. Depending on the animation settings this may not be visible. If `menuFadeStatusBar` is true, this color is used to fade it. Default is black. open static var menuAnimationBackgroundColor: UIColor? /// The shadow opacity around the menu view controller or existing view controller depending on the `menuPresentMode`. Default is 0.5 for 50% opacity. open static var menuShadowOpacity: Float = 0.5 /// The shadow color around the menu view controller or existing view controller depending on the `menuPresentMode`. Default is black. open static var menuShadowColor = UIColor.black /// The radius of the shadow around the menu view controller or existing view controller depending on the `menuPresentMode`. Default is 5. open static var menuShadowRadius: CGFloat = 5 /// The left menu swipe to dismiss gesture. open static weak var menuLeftSwipeToDismissGesture: UIPanGestureRecognizer? /// The right menu swipe to dismiss gesture. open static weak var menuRightSwipeToDismissGesture: UIPanGestureRecognizer? /// Enable or disable gestures that would swipe to present or dismiss the menu. Default is true. open static var menuEnableSwipeGestures: Bool = true /// Enable or disable interaction with the presenting view controller while the menu is displayed. Enabling may make it difficult to dismiss the menu or cause exceptions if the user tries to present and already presented menu. Default is false. open static var menuPresentingViewControllerUserInteractionEnabled: Bool = false /// The strength of the parallax effect on the existing view controller. Does not apply to `menuPresentMode` when set to `ViewSlideOut`. Default is 0. open static var menuParallaxStrength: Int = 0 /// Draws the `menuAnimationBackgroundColor` behind the status bar. Default is true. open static var menuFadeStatusBar = true /// When true, pushViewController called within the menu it will push the new view controller inside of the menu. Otherwise, it is pushed on the menu's presentingViewController. Default is false. open static var menuAllowSubmenus: Bool = false /// -Warning: Deprecated. Use `menuAnimationTransformScaleFactor` instead. @available(*, deprecated, renamed: "menuAnimationTransformScaleFactor") open static var menuAnimationShrinkStrength: CGFloat { get { return menuAnimationTransformScaleFactor } set { menuAnimationTransformScaleFactor = newValue } } // prevent instantiation fileprivate override init() {} /** The blur effect style of the menu if the menu's root view controller is a UITableViewController or UICollectionViewController. - Note: If you want cells in a UITableViewController menu to show vibrancy, make them a subclass of UITableViewVibrantCell. */ open static var menuBlurEffectStyle: UIBlurEffectStyle? { didSet { if oldValue != menuBlurEffectStyle { updateMenuBlurIfNecessary() } } } /// The left menu. open static var menuLeftNavigationController: UISideMenuNavigationController? { willSet { if menuLeftNavigationController?.presentingViewController == nil { removeMenuBlurForMenu(menuLeftNavigationController) } } didSet { guard oldValue?.presentingViewController == nil else { print("SideMenu Warning: menuLeftNavigationController cannot be modified while it's presented.") menuLeftNavigationController = oldValue return } setupNavigationController(menuLeftNavigationController, leftSide: true) } } /// The right menu. open static var menuRightNavigationController: UISideMenuNavigationController? { willSet { if menuRightNavigationController?.presentingViewController == nil { removeMenuBlurForMenu(menuRightNavigationController) } } didSet { guard oldValue?.presentingViewController == nil else { print("SideMenu Warning: menuRightNavigationController cannot be modified while it's presented.") menuRightNavigationController = oldValue return } setupNavigationController(menuRightNavigationController, leftSide: false) } } fileprivate class func setupNavigationController(_ forMenu: UISideMenuNavigationController?, leftSide: Bool) { guard let forMenu = forMenu else { return } let exitPanGesture = UIPanGestureRecognizer() exitPanGesture.addTarget(SideMenuTransition.self, action:#selector(SideMenuTransition.handleHideMenuPan(_:))) forMenu.view.addGestureRecognizer(exitPanGesture) forMenu.transitioningDelegate = SideMenuTransition.singleton forMenu.modalPresentationStyle = .overFullScreen forMenu.leftSide = leftSide if leftSide { menuLeftSwipeToDismissGesture = exitPanGesture } else { menuRightSwipeToDismissGesture = exitPanGesture } updateMenuBlurIfNecessary() } fileprivate class func updateMenuBlurIfNecessary() { let menuBlurBlock = { (forMenu: UISideMenuNavigationController?) in if let forMenu = forMenu { setupMenuBlurForMenu(forMenu) } } menuBlurBlock(menuLeftNavigationController) menuBlurBlock(menuRightNavigationController) } fileprivate class func setupMenuBlurForMenu(_ forMenu: UISideMenuNavigationController?) { removeMenuBlurForMenu(forMenu) guard let forMenu = forMenu, let menuBlurEffectStyle = menuBlurEffectStyle, let view = forMenu.visibleViewController?.view , !UIAccessibilityIsReduceTransparencyEnabled() else { return } if forMenu.originalMenuBackgroundColor == nil { forMenu.originalMenuBackgroundColor = view.backgroundColor } let blurEffect = UIBlurEffect(style: menuBlurEffectStyle) let blurView = UIVisualEffectView(effect: blurEffect) view.backgroundColor = UIColor.clear if let tableViewController = forMenu.visibleViewController as? UITableViewController { tableViewController.tableView.backgroundView = blurView tableViewController.tableView.separatorEffect = UIVibrancyEffect(blurEffect: blurEffect) tableViewController.tableView.reloadData() } else { blurView.autoresizingMask = [.flexibleHeight, .flexibleWidth] blurView.frame = view.bounds view.insertSubview(blurView, at: 0) } } fileprivate class func removeMenuBlurForMenu(_ forMenu: UISideMenuNavigationController?) { guard let forMenu = forMenu, let originalMenuBackgroundColor = forMenu.originalMenuBackgroundColor, let view = forMenu.visibleViewController?.view else { return } view.backgroundColor = originalMenuBackgroundColor forMenu.originalMenuBackgroundColor = nil if let tableViewController = forMenu.visibleViewController as? UITableViewController { tableViewController.tableView.backgroundView = nil tableViewController.tableView.separatorEffect = nil tableViewController.tableView.reloadData() } else if let blurView = view.subviews[0] as? UIVisualEffectView { blurView.removeFromSuperview() } } /** Adds screen edge gestures to a view to present a menu. - Parameter toView: The view to add gestures to. - Parameter forMenu: The menu (left or right) you want to add a gesture for. If unspecified, gestures will be added for both sides. - Returns: The array of screen edge gestures added to `toView`. */ @discardableResult open class func menuAddScreenEdgePanGesturesToPresent(toView: UIView, forMenu:UIRectEdge? = nil) -> [UIScreenEdgePanGestureRecognizer] { var array = [UIScreenEdgePanGestureRecognizer]() if forMenu != .right { let leftScreenEdgeGestureRecognizer = UIScreenEdgePanGestureRecognizer() leftScreenEdgeGestureRecognizer.addTarget(SideMenuTransition.self, action:#selector(SideMenuTransition.handlePresentMenuLeftScreenEdge(_:))) leftScreenEdgeGestureRecognizer.edges = .left leftScreenEdgeGestureRecognizer.cancelsTouchesInView = true toView.addGestureRecognizer(leftScreenEdgeGestureRecognizer) array.append(leftScreenEdgeGestureRecognizer) } if forMenu != .left { let rightScreenEdgeGestureRecognizer = UIScreenEdgePanGestureRecognizer() rightScreenEdgeGestureRecognizer.addTarget(SideMenuTransition.self, action:#selector(SideMenuTransition.handlePresentMenuRightScreenEdge(_:))) rightScreenEdgeGestureRecognizer.edges = .right rightScreenEdgeGestureRecognizer.cancelsTouchesInView = true toView.addGestureRecognizer(rightScreenEdgeGestureRecognizer) array.append(rightScreenEdgeGestureRecognizer) } return array } /** Adds a pan edge gesture to a view to present menus. - Parameter toView: The view to add a pan gesture to. - Returns: The pan gesture added to `toView`. */ @discardableResult open class func menuAddPanGestureToPresent(toView: UIView) -> UIPanGestureRecognizer { let panGestureRecognizer = UIPanGestureRecognizer() panGestureRecognizer.addTarget(SideMenuTransition.self, action:#selector(SideMenuTransition.handlePresentMenuPan(_:))) toView.addGestureRecognizer(panGestureRecognizer) return panGestureRecognizer } }
mit
c52b638b18ad31fe543290ac8003badb
46.69258
248
0.702601
5.850455
false
false
false
false
MukeshKumarS/Swift
test/SILGen/super.swift
1
2980
// RUN: rm -rf %t // RUN: mkdir %t // RUN: %target-swift-frontend -emit-module -emit-module-path=%t/resilient_class.swiftmodule -module-name resilient_class %S/../Inputs/resilient_class.swift // RUN: %target-swift-frontend -use-native-super-method -emit-silgen -parse-as-library -I %t %s | FileCheck %s import resilient_class public class Parent { public final var finalProperty: String { return "Parent.finalProperty" } public var property: String { return "Parent.property" } public final class var finalClassProperty: String { return "Parent.finalProperty" } public class var classProperty: String { return "Parent.property" } public func methodOnlyInParent() {} public final func finalMethodOnlyInParent() {} public func method() {} public final class func finalClassMethodOnlyInParent() {} public class func classMethod() {} } public class Child : Parent { // CHECK-LABEL: sil @_TFC5super5Childg8propertySS // CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $Child to $Parent // CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method %0 : $Child, #Parent.property!getter.1 public override var property: String { return super.property } // CHECK-LABEL: sil @_TFC5super5Childg13otherPropertySS // CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $Child to $Parent // CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @_TFC5super6Parentg13finalPropertySS public var otherProperty: String { return super.finalProperty } } public class Grandchild : Child { // CHECK-LABEL: sil @_TFC5super10Grandchild16onlyInGrandchildfT_T_ public func onlyInGrandchild() { // CHECK: super_method %0 : $Grandchild, #Parent.methodOnlyInParent!1 : Parent -> () -> () super.methodOnlyInParent() // CHECK: function_ref @_TFC5super6Parent23finalMethodOnlyInParentfT_T_ super.finalMethodOnlyInParent() } // CHECK-LABEL: sil @_TFC5super10Grandchild6methodfT_T_ public override func method() { // CHECK: super_method %0 : $Grandchild, #Parent.method!1 : Parent -> () -> () super.method() } } public class GreatGrandchild : Grandchild { // CHECK-LABEL: sil @_TFC5super15GreatGrandchild6methodfT_T_ public override func method() { // CHECK: super_method {{%[0-9]+}} : $GreatGrandchild, #Grandchild.method!1 : Grandchild -> () -> () , $@convention(method) (@guaranteed Grandchild) -> () super.method() } } public class ChildToResilientParent : ResilientOutsideParent { public override func method() { super.method() } public override class func classMethod() { super.classMethod() } } public class ChildToFixedParent : OutsideParent { public override func method() { super.method() } public override class func classMethod() { super.classMethod() } } public extension ResilientOutsideChild { public func callSuperMethod() { super.method() } public class func callSuperClassMethod() { super.classMethod() } }
apache-2.0
55b60db820f106f1997fb81ff943b7f4
28.50495
158
0.68557
3.805875
false
false
false
false
mozilla-mobile/firefox-ios
ThirdParty/UIImageColors.swift
2
11699
// // UIImageColors.swift // https://github.com/jathu/UIImageColors // // Created by Jathu Satkunarajah (@jathu) on 2015-06-11 - Toronto // Original Cocoa version by Panic Inc. - Portland // import UIKit public struct UIImageColors { public var background: UIColor! public var primary: UIColor! public var secondary: UIColor! public var detail: UIColor! } class PCCountedColor { let color: UIColor let count: Int init(color: UIColor, count: Int) { self.color = color self.count = count } } extension CGColor { var components: [CGFloat] { get { var red = CGFloat() var green = CGFloat() var blue = CGFloat() var alpha = CGFloat() UIColor(cgColor: self).getRed(&red, green: &green, blue: &blue, alpha: &alpha) return [red,green,blue,alpha] } } } extension UIColor { var isDarkColor: Bool { let RGB = self.cgColor.components return (0.2126 * RGB[0] + 0.7152 * RGB[1] + 0.0722 * RGB[2]) < 0.5 } var isBlackOrWhite: Bool { let RGB = self.cgColor.components return (RGB[0] > 0.91 && RGB[1] > 0.91 && RGB[2] > 0.91) || (RGB[0] < 0.09 && RGB[1] < 0.09 && RGB[2] < 0.09) } func isDistinct(compareColor: UIColor) -> Bool { let bg = self.cgColor.components let fg = compareColor.cgColor.components let threshold: CGFloat = 0.25 if abs(bg[0] - fg[0]) > threshold || abs(bg[1] - fg[1]) > threshold || abs(bg[2] - fg[2]) > threshold { if abs(bg[0] - bg[1]) < 0.03 && abs(bg[0] - bg[2]) < 0.03 { if abs(fg[0] - fg[1]) < 0.03 && abs(fg[0] - fg[2]) < 0.03 { return false } } return true } return false } func colorWithMinimumSaturation(minSaturation: CGFloat) -> UIColor { var hue: CGFloat = 0.0 var saturation: CGFloat = 0.0 var brightness: CGFloat = 0.0 var alpha: CGFloat = 0.0 self.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) if saturation < minSaturation { return UIColor(hue: hue, saturation: minSaturation, brightness: brightness, alpha: alpha) } else { return self } } func isContrastingColor(compareColor: UIColor) -> Bool { let bg = self.cgColor.components let fg = compareColor.cgColor.components let bgLum = 0.2126 * bg[0] + 0.7152 * bg[1] + 0.0722 * bg[2] let fgLum = 0.2126 * fg[0] + 0.7152 * fg[1] + 0.0722 * fg[2] let bgGreater = bgLum > fgLum let nom = bgGreater ? bgLum : fgLum let denom = bgGreater ? fgLum : bgLum let contrast = (nom + 0.05) / (denom + 0.05) return 1.6 < contrast } } extension UIImage { private func resizeForUIImageColors(newSize: CGSize) -> UIImage { UIGraphicsBeginImageContextWithOptions(newSize, false, 0) defer { UIGraphicsEndImageContext() } self.draw(in: CGRect(width: newSize.width, height: newSize.height)) guard let result = UIGraphicsGetImageFromCurrentImageContext() else { fatalError("UIImageColors.resizeForUIImageColors failed: UIGraphicsGetImageFromCurrentImageContext returned nil") } return result } /** Get `UIImageColors` from the image asynchronously (in background thread). Discussion: Use smaller sizes for better performance at the cost of quality colors. Use larger sizes for better color sampling and quality at the cost of performance. - parameter scaleDownSize: Downscale size of image for sampling, if `CGSize.zero` is provided, the sample image is rescaled to a width of 250px and the aspect ratio height. - parameter completionHandler: `UIImageColors` for this image. */ public func getColors(scaleDownSize: CGSize = .zero, completionHandler: @escaping (UIImageColors) -> Void) { DispatchQueue.global().async { let result = self.getColors(scaleDownSize: scaleDownSize) DispatchQueue.main.async { completionHandler(result) } } } /** Get `UIImageColors` from the image synchronously (in main thread). Discussion: Use smaller sizes for better performance at the cost of quality colors. Use larger sizes for better color sampling and quality at the cost of performance. - parameter scaleDownSize: Downscale size of image for sampling, if `CGSize.zero` is provided, the sample image is rescaled to a width of 250px and the aspect ratio height. - returns: `UIImageColors` for this image. */ public func getColors(scaleDownSize: CGSize = .zero) -> UIImageColors { var scaleDownSize = scaleDownSize if scaleDownSize == .zero { let ratio = self.size.width/self.size.height let r_width: CGFloat = 250 scaleDownSize = CGSize(width: r_width, height: r_width/ratio) } var result = UIImageColors() let cgImage = self.resizeForUIImageColors(newSize: scaleDownSize).cgImage! let width: Int = cgImage.width let height: Int = cgImage.height let blackColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1) let whiteColor = UIColor(red: 1, green: 1, blue: 1, alpha: 1) let randomColorsThreshold = Int(CGFloat(height)*0.01) let sortedColorComparator: Comparator = { (main, other) -> ComparisonResult in let m = main as! PCCountedColor, o = other as! PCCountedColor if m.count < o.count { return .orderedDescending } else if m.count == o.count { return .orderedSame } else { return .orderedAscending } } guard let data = CFDataGetBytePtr(cgImage.dataProvider!.data) else { fatalError("UIImageColors.getColors failed: could not get cgImage data") } // Filter out and collect pixels from image let imageColors = NSCountedSet(capacity: width * height) for x in 0..<width { for y in 0..<height { let pixel: Int = ((width * y) + x) * 4 // Only consider pixels with 50% opacity or higher if 127 <= data[pixel+3] { imageColors.add(UIColor( red: CGFloat(data[pixel+2])/255, green: CGFloat(data[pixel+1])/255, blue: CGFloat(data[pixel])/255, alpha: 1.0 )) } } } // Get background color var enumerator = imageColors.objectEnumerator() var sortedColors = NSMutableArray(capacity: imageColors.count) while let kolor = enumerator.nextObject() as? UIColor { let colorCount = imageColors.count(for: kolor) if randomColorsThreshold < colorCount { sortedColors.add(PCCountedColor(color: kolor, count: colorCount)) } } sortedColors.sort(comparator: sortedColorComparator) var proposedEdgeColor: PCCountedColor if 0 < sortedColors.count { proposedEdgeColor = sortedColors.object(at: 0) as! PCCountedColor } else { proposedEdgeColor = PCCountedColor(color: blackColor, count: 1) } if proposedEdgeColor.color.isBlackOrWhite && 0 < sortedColors.count { for i in 1..<sortedColors.count { let nextProposedEdgeColor = sortedColors.object(at: i) as! PCCountedColor if (CGFloat(nextProposedEdgeColor.count)/CGFloat(proposedEdgeColor.count)) > 0.3 { if !nextProposedEdgeColor.color.isBlackOrWhite { proposedEdgeColor = nextProposedEdgeColor break } } else { break } } } result.background = proposedEdgeColor.color // Get foreground colors enumerator = imageColors.objectEnumerator() sortedColors.removeAllObjects() sortedColors = NSMutableArray(capacity: imageColors.count) let findDarkTextColor = !result.background.isDarkColor while var kolor = enumerator.nextObject() as? UIColor { kolor = kolor.colorWithMinimumSaturation(minSaturation: 0.15) if kolor.isDarkColor == findDarkTextColor { let colorCount = imageColors.count(for: kolor) sortedColors.add(PCCountedColor(color: kolor, count: colorCount)) } } sortedColors.sort(comparator: sortedColorComparator) for curContainer in sortedColors { let kolor = (curContainer as! PCCountedColor).color if result.primary == nil { if kolor.isContrastingColor(compareColor: result.background) { result.primary = kolor } } else if result.secondary == nil { if !result.primary.isDistinct(compareColor: kolor) || !kolor.isContrastingColor(compareColor: result.background) { continue } result.secondary = kolor } else if result.detail == nil { if !result.secondary.isDistinct(compareColor: kolor) || !result.primary.isDistinct(compareColor: kolor) || !kolor.isContrastingColor(compareColor: result.background) { continue } result.detail = kolor break } } let isDarkBackgound = result.background.isDarkColor if result.primary == nil { result.primary = isDarkBackgound ? whiteColor:blackColor } if result.secondary == nil { result.secondary = isDarkBackgound ? whiteColor:blackColor } if result.detail == nil { result.detail = isDarkBackgound ? whiteColor:blackColor } return result } // Courtesy: https://www.hackingwithswift.com/example-code/media/how-to-read-the-average-color-of-a-uiimage-using-ciareaaverage public func averageColor(completion: @escaping (UIColor?) -> Void) { guard let inputImage = CIImage(image: self) else { completion(nil) return } let extentVector = CIVector(x: inputImage.extent.origin.x, y: inputImage.extent.origin.y, z: inputImage.extent.size.width, w: inputImage.extent.size.height) // core image filter that resamples an image down to 1x1 pixels // so you can read the most dominant color in an imagage guard let filter = CIFilter( name: "CIAreaAverage", parameters: [kCIInputImageKey: inputImage, kCIInputExtentKey: extentVector]), let outputImage = filter.outputImage else { completion(nil) return } // reads each of the color values into a UIColor, and sends it back var bitmap = [UInt8](repeating: 0, count: 4) guard let kCFNull = kCFNull else { completion(nil) return } let context = CIContext(options: [.workingColorSpace: kCFNull]) context.render(outputImage, toBitmap: &bitmap, rowBytes: 4, bounds: CGRect(x: 0, y: 0, width: 1, height: 1), format: .RGBA8, colorSpace: nil) completion(UIColor(red: CGFloat(bitmap[0]) / 255, green: CGFloat(bitmap[1]) / 255, blue: CGFloat(bitmap[2]) / 255, alpha: CGFloat(bitmap[3]) / 255)) } }
mpl-2.0
084b1eaeb2df4bf3c324c332f8a55430
36.73871
183
0.593726
4.589643
false
false
false
false
benlangmuir/swift
test/NameLookup/name_lookup.swift
7
30248
// RUN: %target-typecheck-verify-swift -typo-correction-limit 100 class ThisBase1 { init() { } var baseInstanceVar: Int var baseProp : Int { get { return 42 } set {} } func baseFunc0() {} func baseFunc1(_ a: Int) {} subscript(i: Int) -> Double { get { return Double(i) } set { baseInstanceVar = i } } class var baseStaticVar: Int = 42 // expected-error {{class stored properties not supported}} class var baseStaticProp: Int { get { return 42 } set {} } class func baseStaticFunc0() {} struct BaseNestedStruct {} // expected-note {{did you mean 'BaseNestedStruct'?}} class BaseNestedClass { init() { } } enum BaseNestedUnion { case BaseUnionX(Int) } typealias BaseNestedTypealias = Int // expected-note {{did you mean 'BaseNestedTypealias'?}} } class ThisDerived1 : ThisBase1 { override init() { super.init() } var derivedInstanceVar: Int var derivedProp : Int { get { return 42 } set {} } func derivedFunc0() {} func derivedFunc1(_ a: Int) {} subscript(i: Double) -> Int { get { return Int(i) } set { baseInstanceVar = Int(i) } } class var derivedStaticVar: Int = 42// expected-error {{class stored properties not supported}} class var derivedStaticProp: Int { get { return 42 } set {} } class func derivedStaticFunc0() {} struct DerivedNestedStruct {} class DerivedNestedClass { init() { } } enum DerivedNestedUnion { // expected-note {{did you mean 'DerivedNestedUnion'?}} case DerivedUnionX(Int) } typealias DerivedNestedTypealias = Int func testSelf1() { self.baseInstanceVar = 42 self.baseProp = 42 self.baseFunc0() self.baseFunc1(42) self[0] = 42.0 self.baseStaticVar = 42 // expected-error {{static member 'baseStaticVar' cannot be used on instance of type 'ThisDerived1'}} self.baseStaticProp = 42 // expected-error {{static member 'baseStaticProp' cannot be used on instance of type 'ThisDerived1'}} self.baseStaticFunc0() // expected-error {{static member 'baseStaticFunc0' cannot be used on instance of type 'ThisDerived1'}} self.baseExtProp = 42 self.baseExtFunc0() self.baseExtStaticVar = 42 self.baseExtStaticProp = 42 self.baseExtStaticFunc0() // expected-error {{static member 'baseExtStaticFunc0' cannot be used on instance of type 'ThisDerived1'}} var bs1 : BaseNestedStruct var bc1 : BaseNestedClass var bo1 : BaseNestedUnion = .BaseUnionX(42) var bt1 : BaseNestedTypealias var bs2 = self.BaseNestedStruct() // expected-error{{static member 'BaseNestedStruct' cannot be used on instance of type 'ThisDerived1'}} var bc2 = self.BaseNestedClass() // expected-error{{static member 'BaseNestedClass' cannot be used on instance of type 'ThisDerived1'}} var bo2 = self.BaseUnionX(24) // expected-error {{value of type 'ThisDerived1' has no member 'BaseUnionX'}} var bo3 = self.BaseNestedUnion.BaseUnionX(24) // expected-error{{static member 'BaseNestedUnion' cannot be used on instance of type 'ThisDerived1'}} var bt2 = self.BaseNestedTypealias(42) // expected-error{{static member 'BaseNestedTypealias' cannot be used on instance of type 'ThisDerived1'}} var bes1 : BaseExtNestedStruct var bec1 : BaseExtNestedClass var beo1 : BaseExtNestedUnion = .BaseExtUnionX(42) var bet1 : BaseExtNestedTypealias var bes2 = self.BaseExtNestedStruct() // expected-error{{static member 'BaseExtNestedStruct' cannot be used on instance of type 'ThisDerived1'}} var bec2 = self.BaseExtNestedClass() // expected-error{{static member 'BaseExtNestedClass' cannot be used on instance of type 'ThisDerived1'}} var beo2 = self.BaseExtUnionX(24) // expected-error {{value of type 'ThisDerived1' has no member 'BaseExtUnionX'}} var beo3 = self.BaseExtNestedUnion.BaseExtUnionX(24) // expected-error{{static member 'BaseExtNestedUnion' cannot be used on instance of type 'ThisDerived1'}} var bet2 = self.BaseExtNestedTypealias(42) // expected-error{{static member 'BaseExtNestedTypealias' cannot be used on instance of type 'ThisDerived1'}} self.derivedInstanceVar = 42 self.derivedProp = 42 self.derivedFunc0() self.derivedStaticVar = 42 // expected-error {{static member 'derivedStaticVar' cannot be used on instance of type 'ThisDerived1'}} self.derivedStaticProp = 42 // expected-error {{static member 'derivedStaticProp' cannot be used on instance of type 'ThisDerived1'}} self.derivedStaticFunc0() // expected-error {{static member 'derivedStaticFunc0' cannot be used on instance of type 'ThisDerived1'}} self.derivedExtProp = 42 self.derivedExtFunc0() self.derivedExtStaticVar = 42 self.derivedExtStaticProp = 42 self.derivedExtStaticFunc0() // expected-error {{static member 'derivedExtStaticFunc0' cannot be used on instance of type 'ThisDerived1'}} var ds1 : DerivedNestedStruct var dc1 : DerivedNestedClass var do1 : DerivedNestedUnion = .DerivedUnionX(42) var dt1 : DerivedNestedTypealias var ds2 = self.DerivedNestedStruct() // expected-error{{static member 'DerivedNestedStruct' cannot be used on instance of type 'ThisDerived1'}} var dc2 = self.DerivedNestedClass() // expected-error{{static member 'DerivedNestedClass' cannot be used on instance of type 'ThisDerived1'}} var do2 = self.DerivedUnionX(24) // expected-error {{value of type 'ThisDerived1' has no member 'DerivedUnionX'}} var do3 = self.DerivedNestedUnion.DerivedUnionX(24) // expected-error{{static member 'DerivedNestedUnion' cannot be used on instance of type 'ThisDerived1'}} var dt2 = self.DerivedNestedTypealias(42) // expected-error{{static member 'DerivedNestedTypealias' cannot be used on instance of type 'ThisDerived1'}} var des1 : DerivedExtNestedStruct var dec1 : DerivedExtNestedClass var deo1 : DerivedExtNestedUnion = .DerivedExtUnionX(42) var det1 : DerivedExtNestedTypealias var des2 = self.DerivedExtNestedStruct() // expected-error{{static member 'DerivedExtNestedStruct' cannot be used on instance of type 'ThisDerived1'}} var dec2 = self.DerivedExtNestedClass() // expected-error{{static member 'DerivedExtNestedClass' cannot be used on instance of type 'ThisDerived1'}} var deo2 = self.DerivedExtUnionX(24) // expected-error {{value of type 'ThisDerived1' has no member 'DerivedExtUnionX'}} var deo3 = self.DerivedExtNestedUnion.DerivedExtUnionX(24) // expected-error{{static member 'DerivedExtNestedUnion' cannot be used on instance of type 'ThisDerived1'}} var det2 = self.DerivedExtNestedTypealias(42) // expected-error{{static member 'DerivedExtNestedTypealias' cannot be used on instance of type 'ThisDerived1'}} self.Type // expected-error {{value of type 'ThisDerived1' has no member 'Type'}} } func testSuper1() { super.baseInstanceVar = 42 super.baseProp = 42 super.baseFunc0() super.baseFunc1(42) super[0] = 42.0 super.baseStaticVar = 42 // expected-error {{static member 'baseStaticVar' cannot be used on instance of type 'ThisBase1'}} super.baseStaticProp = 42 // expected-error {{static member 'baseStaticProp' cannot be used on instance of type 'ThisBase1'}} super.baseStaticFunc0() // expected-error {{static member 'baseStaticFunc0' cannot be used on instance of type 'ThisBase1'}} super.baseExtProp = 42 super.baseExtFunc0() super.baseExtStaticVar = 42 super.baseExtStaticProp = 42 super.baseExtStaticFunc0() // expected-error {{static member 'baseExtStaticFunc0' cannot be used on instance of type 'ThisBase1'}} var bs2 = super.BaseNestedStruct() // expected-error{{static member 'BaseNestedStruct' cannot be used on instance of type 'ThisBase1'}} var bc2 = super.BaseNestedClass() // expected-error{{static member 'BaseNestedClass' cannot be used on instance of type 'ThisBase1'}} var bo2 = super.BaseUnionX(24) // expected-error {{value of type 'ThisBase1' has no member 'BaseUnionX'}} var bo3 = super.BaseNestedUnion.BaseUnionX(24) // expected-error{{static member 'BaseNestedUnion' cannot be used on instance of type 'ThisBase1'}} var bt2 = super.BaseNestedTypealias(42) // expected-error{{static member 'BaseNestedTypealias' cannot be used on instance of type 'ThisBase1'}} var bes2 = super.BaseExtNestedStruct() // expected-error{{static member 'BaseExtNestedStruct' cannot be used on instance of type 'ThisBase1'}} var bec2 = super.BaseExtNestedClass() // expected-error{{static member 'BaseExtNestedClass' cannot be used on instance of type 'ThisBase1'}} var beo2 = super.BaseExtUnionX(24) // expected-error {{value of type 'ThisBase1' has no member 'BaseExtUnionX'}} var beo3 = super.BaseExtNestedUnion.BaseExtUnionX(24) // expected-error{{static member 'BaseExtNestedUnion' cannot be used on instance of type 'ThisBase1'}} var bet2 = super.BaseExtNestedTypealias(42) // expected-error{{static member 'BaseExtNestedTypealias' cannot be used on instance of type 'ThisBase1'}} super.derivedInstanceVar = 42 // expected-error {{value of type 'ThisBase1' has no member 'derivedInstanceVar'}} super.derivedProp = 42 // expected-error {{value of type 'ThisBase1' has no member 'derivedProp'}} super.derivedFunc0() // expected-error {{value of type 'ThisBase1' has no member 'derivedFunc0'}} super.derivedStaticVar = 42 // expected-error {{value of type 'ThisBase1' has no member 'derivedStaticVar'}} super.derivedStaticProp = 42 // expected-error {{value of type 'ThisBase1' has no member 'derivedStaticProp'}} super.derivedStaticFunc0() // expected-error {{value of type 'ThisBase1' has no member 'derivedStaticFunc0'}} super.derivedExtProp = 42 // expected-error {{value of type 'ThisBase1' has no member 'derivedExtProp'}} super.derivedExtFunc0() // expected-error {{value of type 'ThisBase1' has no member 'derivedExtFunc0'}} super.derivedExtStaticVar = 42 // expected-error {{value of type 'ThisBase1' has no member 'derivedExtStaticVar'; did you mean 'baseExtStaticVar'?}} super.derivedExtStaticProp = 42 // expected-error {{value of type 'ThisBase1' has no member 'derivedExtStaticProp'; did you mean 'baseExtStaticProp'?}} super.derivedExtStaticFunc0() // expected-error {{value of type 'ThisBase1' has no member 'derivedExtStaticFunc0'}} var ds2 = super.DerivedNestedStruct() // expected-error {{value of type 'ThisBase1' has no member 'DerivedNestedStruct'}} var dc2 = super.DerivedNestedClass() // expected-error {{value of type 'ThisBase1' has no member 'DerivedNestedClass'}} var do2 = super.DerivedUnionX(24) // expected-error {{value of type 'ThisBase1' has no member 'DerivedUnionX'}} var do3 = super.DerivedNestedUnion.DerivedUnionX(24) // expected-error {{value of type 'ThisBase1' has no member 'DerivedNestedUnion'}} var dt2 = super.DerivedNestedTypealias(42) // expected-error {{value of type 'ThisBase1' has no member 'DerivedNestedTypealias'}} var des2 = super.DerivedExtNestedStruct() // expected-error {{value of type 'ThisBase1' has no member 'DerivedExtNestedStruct'}} var dec2 = super.DerivedExtNestedClass() // expected-error {{value of type 'ThisBase1' has no member 'DerivedExtNestedClass'}} var deo2 = super.DerivedExtUnionX(24) // expected-error {{value of type 'ThisBase1' has no member 'DerivedExtUnionX'}} var deo3 = super.DerivedExtNestedUnion.DerivedExtUnionX(24) // expected-error {{value of type 'ThisBase1' has no member 'DerivedExtNestedUnion'}} var det2 = super.DerivedExtNestedTypealias(42) // expected-error {{value of type 'ThisBase1' has no member 'DerivedExtNestedTypealias'}} super.Type // expected-error {{value of type 'ThisBase1' has no member 'Type'}} } class func staticTestSelf1() { self.baseInstanceVar = 42 // expected-error {{member 'baseInstanceVar' cannot be used on type 'ThisDerived1'}} self.baseProp = 42 // expected-error {{member 'baseProp' cannot be used on type 'ThisDerived1'}} self.baseFunc0() // expected-error {{instance member 'baseFunc0' cannot be used on type 'ThisDerived1'}} self.baseFunc0(ThisBase1())() // expected-error {{cannot convert value of type 'ThisBase1' to expected argument type 'ThisDerived1'}} self.baseFunc0(ThisDerived1())() self.baseFunc1(42) // expected-error {{instance member 'baseFunc1' cannot be used on type 'ThisDerived1'}} self.baseFunc1(ThisBase1())(42) // expected-error {{cannot convert value of type 'ThisBase1' to expected argument type 'ThisDerived1'}} self.baseFunc1(ThisDerived1())(42) self[0] = 42.0 // expected-error {{instance member 'subscript' cannot be used on type 'ThisDerived1'}} self.baseStaticVar = 42 self.baseStaticProp = 42 self.baseStaticFunc0() self.baseExtProp = 42 // expected-error {{member 'baseExtProp' cannot be used on type 'ThisDerived1'}} self.baseExtFunc0() // expected-error {{instance member 'baseExtFunc0' cannot be used on type 'ThisDerived1'}} self.baseExtStaticVar = 42 // expected-error {{instance member 'baseExtStaticVar' cannot be used on type 'ThisDerived1'}} self.baseExtStaticProp = 42 // expected-error {{member 'baseExtStaticProp' cannot be used on type 'ThisDerived1'}} self.baseExtStaticFunc0() var bs1 : BaseNestedStruct var bc1 : BaseNestedClass var bo1 : BaseNestedUnion = .BaseUnionX(42) var bt1 : BaseNestedTypealias var bs2 = self.BaseNestedStruct() var bc2 = self.BaseNestedClass() var bo2 = self.BaseUnionX(24) // expected-error {{type 'ThisDerived1' has no member 'BaseUnionX'}} var bo3 = self.BaseNestedUnion.BaseUnionX(24) var bt2 = self.BaseNestedTypealias() self.derivedInstanceVar = 42 // expected-error {{member 'derivedInstanceVar' cannot be used on type 'ThisDerived1'}} self.derivedProp = 42 // expected-error {{member 'derivedProp' cannot be used on type 'ThisDerived1'}} self.derivedFunc0() // expected-error {{instance member 'derivedFunc0' cannot be used on type 'ThisDerived1'}} self.derivedFunc0(ThisBase1())() // expected-error {{cannot convert value of type 'ThisBase1' to expected argument type 'ThisDerived1'}} self.derivedFunc0(ThisDerived1())() self.derivedStaticVar = 42 self.derivedStaticProp = 42 self.derivedStaticFunc0() self.derivedExtProp = 42 // expected-error {{member 'derivedExtProp' cannot be used on type 'ThisDerived1'}} self.derivedExtFunc0() // expected-error {{instance member 'derivedExtFunc0' cannot be used on type 'ThisDerived1'}} self.derivedExtStaticVar = 42 // expected-error {{instance member 'derivedExtStaticVar' cannot be used on type 'ThisDerived1'}} self.derivedExtStaticProp = 42 // expected-error {{member 'derivedExtStaticProp' cannot be used on type 'ThisDerived1'}} self.derivedExtStaticFunc0() var ds1 : DerivedNestedStruct var dc1 : DerivedNestedClass var do1 : DerivedNestedUnion = .DerivedUnionX(42) var dt1 : DerivedNestedTypealias var ds2 = self.DerivedNestedStruct() var dc2 = self.DerivedNestedClass() var do2 = self.DerivedUnionX(24) // expected-error {{type 'ThisDerived1' has no member 'DerivedUnionX'}} var do3 = self.DerivedNestedUnion.DerivedUnionX(24) var dt2 = self.DerivedNestedTypealias() var des1 : DerivedExtNestedStruct var dec1 : DerivedExtNestedClass var deo1 : DerivedExtNestedUnion = .DerivedExtUnionX(42) var det1 : DerivedExtNestedTypealias var des2 = self.DerivedExtNestedStruct() var dec2 = self.DerivedExtNestedClass() var deo2 = self.DerivedExtUnionX(24) // expected-error {{type 'ThisDerived1' has no member 'DerivedExtUnionX'}} var deo3 = self.DerivedExtNestedUnion.DerivedExtUnionX(24) var det2 = self.DerivedExtNestedTypealias() self.Type // expected-error {{type 'ThisDerived1' has no member 'Type'}} } // FIXME(SR-15250): Partial application diagnostic is applied incorrectly for some test cases. class func staticTestSuper1() { super.baseInstanceVar = 42 // expected-error {{member 'baseInstanceVar' cannot be used on type 'ThisBase1'}} super.baseProp = 42 // expected-error {{member 'baseProp' cannot be used on type 'ThisBase1'}} super.baseFunc0() // expected-error {{instance member 'baseFunc0' cannot be used on type 'ThisBase1'}} // expected-error@-1 {{cannot reference 'super' instance method with metatype base as function value}} super.baseFunc0(ThisBase1())() // expected-error {{cannot reference 'super' instance method with metatype base as function value}} super.baseFunc1(42) // expected-error {{instance member 'baseFunc1' cannot be used on type 'ThisBase1'}} // expected-error@-1 {{cannot reference 'super' instance method with metatype base as function value}} super.baseFunc1(ThisBase1())(42) // expected-error {{cannot reference 'super' instance method with metatype base as function value}} super[0] = 42.0 // expected-error {{instance member 'subscript' cannot be used on type 'ThisBase1'}} super.baseStaticVar = 42 super.baseStaticProp = 42 super.baseStaticFunc0() super.baseExtProp = 42 // expected-error {{member 'baseExtProp' cannot be used on type 'ThisBase1'}} super.baseExtFunc0() // expected-error {{instance member 'baseExtFunc0' cannot be used on type 'ThisBase1'}} // expected-error@-1 {{cannot reference 'super' instance method with metatype base as function value}} super.baseExtStaticVar = 42 // expected-error {{instance member 'baseExtStaticVar' cannot be used on type 'ThisBase1'}} super.baseExtStaticProp = 42 // expected-error {{member 'baseExtStaticProp' cannot be used on type 'ThisBase1'}} super.baseExtStaticFunc0() var bs2 = super.BaseNestedStruct() var bc2 = super.BaseNestedClass() var bo2 = super.BaseUnionX(24) // expected-error {{type 'ThisBase1' has no member 'BaseUnionX'}} var bo3 = super.BaseNestedUnion.BaseUnionX(24) var bt2 = super.BaseNestedTypealias() super.derivedInstanceVar = 42 // expected-error {{type 'ThisBase1' has no member 'derivedInstanceVar'}} super.derivedProp = 42 // expected-error {{type 'ThisBase1' has no member 'derivedProp'}} super.derivedFunc0() // expected-error {{type 'ThisBase1' has no member 'derivedFunc0'}} super.derivedStaticVar = 42 // expected-error {{type 'ThisBase1' has no member 'derivedStaticVar'}} super.derivedStaticProp = 42 // expected-error {{type 'ThisBase1' has no member 'derivedStaticProp'}} super.derivedStaticFunc0() // expected-error {{type 'ThisBase1' has no member 'derivedStaticFunc0'}} super.derivedExtProp = 42 // expected-error {{type 'ThisBase1' has no member 'derivedExtProp'}} super.derivedExtFunc0() // expected-error {{type 'ThisBase1' has no member 'derivedExtFunc0'}} super.derivedExtStaticVar = 42 // expected-error {{type 'ThisBase1' has no member 'derivedExtStaticVar'; did you mean 'baseExtStaticVar'?}} super.derivedExtStaticProp = 42 // expected-error {{type 'ThisBase1' has no member 'derivedExtStaticProp'; did you mean 'baseExtStaticProp'?}} super.derivedExtStaticFunc0() // expected-error {{type 'ThisBase1' has no member 'derivedExtStaticFunc0'; did you mean 'baseExtStaticFunc0'?}} var ds2 = super.DerivedNestedStruct() // expected-error {{type 'ThisBase1' has no member 'DerivedNestedStruct'}} var dc2 = super.DerivedNestedClass() // expected-error {{type 'ThisBase1' has no member 'DerivedNestedClass'}} var do2 = super.DerivedUnionX(24) // expected-error {{type 'ThisBase1' has no member 'DerivedUnionX'}} var do3 = super.DerivedNestedUnion.DerivedUnionX(24) // expected-error {{type 'ThisBase1' has no member 'DerivedNestedUnion'}} var dt2 = super.DerivedNestedTypealias(42) // expected-error {{type 'ThisBase1' has no member 'DerivedNestedTypealias'}} var des2 = super.DerivedExtNestedStruct() // expected-error {{type 'ThisBase1' has no member 'DerivedExtNestedStruct'; did you mean 'BaseExtNestedStruct'?}} var dec2 = super.DerivedExtNestedClass() // expected-error {{type 'ThisBase1' has no member 'DerivedExtNestedClass'; did you mean 'BaseExtNestedClass'?}} var deo2 = super.DerivedExtUnionX(24) // expected-error {{type 'ThisBase1' has no member 'DerivedExtUnionX'}} var deo3 = super.DerivedExtNestedUnion.DerivedExtUnionX(24) // expected-error {{type 'ThisBase1' has no member 'DerivedExtNestedUnion'; did you mean 'BaseExtNestedUnion'?}} var det2 = super.DerivedExtNestedTypealias(42) // expected-error {{type 'ThisBase1' has no member 'DerivedExtNestedTypealias'; did you mean 'BaseExtNestedTypealias'?}} super.Type // expected-error {{type 'ThisBase1' has no member 'Type'}} } } protocol Crawlable {} extension Crawlable { static func crawl() {} } struct GenericChameleon<U>: Crawlable { static func chameleon() {} func testStaticOnInstance(arg: GenericChameleon<Never>) { arg.chameleon() // expected-error {{static member 'chameleon' cannot be used on instance of type 'GenericChameleon<Never>'}} {{5-8=GenericChameleon<Never>}} arg.crawl() // expected-error {{static member 'crawl' cannot be used on instance of type 'GenericChameleon<Never>'}} {{5-8=GenericChameleon<Never>}} } } extension ThisBase1 { var baseExtProp : Int { get { return 42 } set {} } func baseExtFunc0() {} var baseExtStaticVar: Int // expected-error {{extensions must not contain stored properties}} // expected-note 2 {{'baseExtStaticVar' declared here}} var baseExtStaticProp: Int { // expected-note 2 {{'baseExtStaticProp' declared here}} get { return 42 } set {} } class func baseExtStaticFunc0() {} // expected-note {{'baseExtStaticFunc0' declared here}} struct BaseExtNestedStruct {} // expected-note {{did you mean 'BaseExtNestedStruct'?}} // expected-note {{'BaseExtNestedStruct' declared here}} class BaseExtNestedClass { // expected-note {{'BaseExtNestedClass' declared here}} init() { } } enum BaseExtNestedUnion { // expected-note {{'BaseExtNestedUnion' declared here}} case BaseExtUnionX(Int) } typealias BaseExtNestedTypealias = Int // expected-note {{did you mean 'BaseExtNestedTypealias'?}} // expected-note {{'BaseExtNestedTypealias' declared here}} } extension ThisDerived1 { var derivedExtProp : Int { get { return 42 } set {} } func derivedExtFunc0() {} var derivedExtStaticVar: Int // expected-error {{extensions must not contain stored properties}} var derivedExtStaticProp: Int { get { return 42 } set {} } class func derivedExtStaticFunc0() {} struct DerivedExtNestedStruct {} class DerivedExtNestedClass { init() { } } enum DerivedExtNestedUnion { // expected-note {{did you mean 'DerivedExtNestedUnion'?}} case DerivedExtUnionX(Int) } typealias DerivedExtNestedTypealias = Int } // <rdar://problem/11554141> func shadowbug() { let Foo = 10 func g() { struct S { var x : Foo typealias Foo = Int } } _ = Foo } func scopebug() { let Foo = 10 struct S { typealias Foo = Int } _ = Foo } struct Ordering { var x : Foo typealias Foo = Int } // <rdar://problem/12202655> class Outer { class Inner {} class MoreInner : Inner {} } func makeGenericStruct<S>(_ x: S) -> GenericStruct<S> { return GenericStruct<S>() } struct GenericStruct<T> {} // <rdar://problem/13952064> extension Outer { class ExtInner {} } // <rdar://problem/14149537> func useProto<R : MyProto>(_ value: R) -> R.Element { return value.get() } protocol MyProto { associatedtype Element func get() -> Element } // <rdar://problem/14488311> struct DefaultArgumentFromExtension { func g(_ x: @escaping (DefaultArgumentFromExtension) -> () -> () = f) { let f = 42 var x2 = x x2 = f // expected-error{{cannot assign value of type 'Int' to type '(DefaultArgumentFromExtension) -> () -> ()'}} _ = x2 } var x : (DefaultArgumentFromExtension) -> () -> () = f } extension DefaultArgumentFromExtension { func f() {} } struct MyStruct { var state : Bool init() { state = true } mutating func mod() {state = false} // expected-note @+1 {{mark method 'mutating' to make 'self' mutable}} {{3-3=mutating }} func foo() { mod() } // expected-error {{cannot use mutating member on immutable value: 'self' is immutable}} } // <rdar://problem/19935319> QoI: poor diagnostic initializing a variable with a non-class func class Test19935319 { let i = getFoo() // expected-error {{cannot use instance member 'getFoo' within property initializer; property initializers run before 'self' is available}} func getFoo() -> Int {} } class Test19935319G<T> { let i = getFoo() // expected-error@-1 {{cannot use instance member 'getFoo' within property initializer; property initializers run before 'self' is available}} func getFoo() -> Int { return 42 } } // <rdar://problem/27013358> Crash using instance member as default parameter class rdar27013358 { let defaultValue = 1 func returnTwo() -> Int { return 2 } init(defaulted value: Int = defaultValue) {} // expected-error {{cannot use instance member 'defaultValue' as a default parameter}} init(another value: Int = returnTwo()) {} // expected-error {{cannot use instance member 'returnTwo' as a default parameter}} } class rdar27013358G<T> { let defaultValue = 1 func returnTwo() -> Int { return 2 } init(defaulted value: Int = defaultValue) {} // expected-error {{cannot use instance member 'defaultValue' as a default parameter}} init(another value: Int = returnTwo()) {} // expected-error {{cannot use instance member 'returnTwo' as a default parameter}} } // <rdar://problem/23904262> QoI: ivar default initializer cannot reference other default initialized ivars? class r23904262 { let x = 1 let y = x // expected-error {{cannot use instance member 'x' within property initializer; property initializers run before 'self' is available}} } // <rdar://problem/21677702> Static method reference in static var doesn't work class r21677702 { static func method(value: Int) -> Int { return value } static let x = method(value: 123) static let y = method(123) // expected-error {{missing argument label 'value:' in call}} } // <rdar://problem/31762378> lazy properties don't have to use "self." in their initializers. class r16954496 { func bar() {} lazy var x: Array<() -> Void> = [bar] } // <rdar://problem/27413116> [Swift] Using static constant defined in enum when in switch statement doesn't compile enum MyEnum { case one case two case oneTwoThree static let kMyConstant = "myConstant" } switch "someString" { case MyEnum.kMyConstant: // this causes a compiler error print("yay") case MyEnum.self.kMyConstant: // this works fine print("hmm") default: break } func foo() { _ = MyEnum.One // expected-error {{enum type 'MyEnum' has no case 'One'; did you mean 'one'?}}{{14-17=one}} _ = MyEnum.Two // expected-error {{enum type 'MyEnum' has no case 'Two'; did you mean 'two'?}}{{14-17=two}} _ = MyEnum.OneTwoThree // expected-error {{enum type 'MyEnum' has no case 'OneTwoThree'; did you mean 'oneTwoThree'?}}{{14-25=oneTwoThree}} } enum MyGenericEnum<T> { case one(T) case oneTwo(T) } func foo1() { _ = MyGenericEnum<Int>.One // expected-error {{enum type 'MyGenericEnum<Int>' has no case 'One'; did you mean 'one'?}}{{26-29=one}} _ = MyGenericEnum<Int>.OneTwo // expected-error {{enum type 'MyGenericEnum<Int>' has no case 'OneTwo'; did you mean 'oneTwo'?}}{{26-32=oneTwo}} } // SR-4082 func foo2() { let x = 5 if x < 0, let x = Optional(1) { } // expected-warning {{immutable value 'x' was never used; consider replacing with '_' or removing it}} } struct Person { let name: String? } struct Company { // expected-note 2{{'Company' declared here}} let owner: Person? } func test1() { let example: Company? = Company(owner: Person(name: "Owner")) if let person = aCompany.owner, // expected-error {{cannot find 'aCompany' in scope; did you mean 'Company'?}} let aCompany = example { _ = person } } func test2() { let example: Company? = Company(owner: Person(name: "Owner")) guard let person = aCompany.owner, // expected-error {{cannot find 'aCompany' in scope; did you mean 'Company'?}} let aCompany = example else { return } } func test3() { var c: String? = "c" // expected-note {{'c' declared here}} if let a = b = c, let b = c { // expected-error {{cannot find 'b' in scope; did you mean 'c'?}} _ = b } } // rdar://problem/22587551 class ShadowingGenericParameter<T> { typealias T = Int func foo (t : T) {} } ShadowingGenericParameter<String>().foo(t: "hi") // rdar://problem/51266778 struct PatternBindingWithTwoVars1 { var x = 3, y = x } // expected-error@-1 {{cannot use instance member 'x' within property initializer; property initializers run before 'self' is available}} struct PatternBindingWithTwoVars2 { var x = y, y = 3 } // expected-error@-1 {{cannot use instance member 'y' within property initializer; property initializers run before 'self' is available}} struct PatternBindingWithTwoVars3 { var x = y, y = x } // expected-error@-1 {{circular reference}} // expected-note@-2 {{through reference here}} // expected-note@-3 {{through reference here}} // expected-note@-4 {{through reference here}} // expected-note@-5 {{through reference here}} // expected-note@-6 {{through reference here}} // expected-error@-7 {{circular reference}} // expected-note@-8 {{through reference here}} // expected-note@-9 {{through reference here}} // expected-note@-10 {{through reference here}} // expected-note@-11 {{through reference here}} // expected-note@-12 {{through reference here}} // https://bugs.swift.org/browse/SR-9015 func sr9015() { let closure1 = { closure2() } // expected-error {{circular reference}} expected-note {{through reference here}} expected-note {{through reference here}} let closure2 = { closure1() } // expected-note {{through reference here}} expected-note {{through reference here}} expected-note {{through reference here}} } func color(with value: Int) -> Int { return value } func useColor() { let color = color(with: 123) _ = color }
apache-2.0
e96640e533678dd03092e298292555ba
44.485714
176
0.71251
3.905992
false
false
false
false
prolificinteractive/Marker
Marker/Marker/Utility/Extensions/TextView/UITextViewExtension.swift
1
1586
// // UITextViewExtension.swift // Marker // // Created by Htin Linn on 5/4/16. // Copyright © 2016 Prolific Interactive. All rights reserved. // #if os(iOS) || os(tvOS) import UIKit public extension UITextView { /// Sets the text view text to an attributed string created from the specified string and text style. /// /// - Parameters: /// - text: The text to be displayed in the text view. /// - textStyle: Text style object containing style information. /// - markups: Custom markup if there is any. Defaults to zero custom markup. func setText(_ text: String, using textStyle: TextStyle, customMarkup markups: Markup = [:]) { attributedText = attributedMarkupString(from: text, using: textStyle, customMarkup: markups) } /// Sets the text view text to an attributed string created from the specified string and text style. /// This function treats the specified string as a Markdown formatted string and applies appropriate styling to it. /// Refer to MarkerdownElement for a list of supported Markdown tags. /// /// - Parameters: /// - markdownText: The Markdown text to be displayed in the text view. /// - textStyle: Text style object containing style information. func setMarkdownText(_ markdownText: String, using textStyle: TextStyle) { if let linkColor = textStyle.linkColor { linkTextAttributes = [AttributedStringKey.foregroundColor: linkColor] } attributedText = attributedMarkdownString(from: markdownText, using: textStyle) } } #endif
mit
6d046a3bba02a09204dea02a57099f9f
36.738095
119
0.693375
4.594203
false
false
false
false
accepton/accepton-apple
Pod/Vendor/Alamofire/Validation.swift
1
7063
// Validation.swift // // Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation extension Request { /** Used to represent whether validation was successful or encountered an error resulting in a failure. - Success: The validation was successful. - Failure: The validation failed encountering the provided error. */ enum ValidationResult { case Success case Failure(NSError) } /** A closure used to validate a request that takes a URL request and URL response, and returns whether the request was valid. */ typealias Validation = (NSURLRequest?, NSHTTPURLResponse) -> ValidationResult /** Validates the request, using the specified closure. If validation fails, subsequent calls to response handlers will have an associated error. - parameter validation: A closure to validate the request. - returns: The request. */ func validate(validation: Validation) -> Self { delegate.queue.addOperationWithBlock { if let response = self.response where self.delegate.error == nil, case let .Failure(error) = validation(self.request, response) { self.delegate.error = error } } return self } // MARK: - Status Code /** Validates that the response has a status code in the specified range. If validation fails, subsequent calls to response handlers will have an associated error. - parameter range: The range of acceptable status codes. - returns: The request. */ func validate<S: SequenceType where S.Generator.Element == Int>(statusCode acceptableStatusCode: S) -> Self { return validate { _, response in if acceptableStatusCode.contains(response.statusCode) { return .Success } else { let failureReason = "Response status code was unacceptable: \(response.statusCode)" return .Failure(Error.errorWithCode(.StatusCodeValidationFailed, failureReason: failureReason)) } } } // MARK: - Content-Type private struct MIMEType { let type: String let subtype: String init?(_ string: String) { let components: [String] = { let stripped = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) let split = stripped.substringToIndex(stripped.rangeOfString(";")?.startIndex ?? stripped.endIndex) return split.componentsSeparatedByString("/") }() if let type = components.first, subtype = components.last { self.type = type self.subtype = subtype } else { return nil } } func matches(MIME: MIMEType) -> Bool { switch (type, subtype) { case (MIME.type, MIME.subtype), (MIME.type, "*"), ("*", MIME.subtype), ("*", "*"): return true default: return false } } } /** Validates that the response has a content type in the specified array. If validation fails, subsequent calls to response handlers will have an associated error. - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. - returns: The request. */ func validate<S : SequenceType where S.Generator.Element == String>(contentType acceptableContentTypes: S) -> Self { return validate { _, response in guard let validData = self.delegate.data where validData.length > 0 else { return .Success } if let responseContentType = response.MIMEType, responseMIMEType = MIMEType(responseContentType) { for contentType in acceptableContentTypes { if let acceptableMIMEType = MIMEType(contentType) where acceptableMIMEType.matches(responseMIMEType) { return .Success } } } else { for contentType in acceptableContentTypes { if let MIMEType = MIMEType(contentType) where MIMEType.type == "*" && MIMEType.subtype == "*" { return .Success } } } let failureReason: String if let responseContentType = response.MIMEType { failureReason = ( "Response content type \"\(responseContentType)\" does not match any acceptable " + "content types: \(acceptableContentTypes)" ) } else { failureReason = "Response content type was missing and acceptable content type does not match \"*/*\"" } return .Failure(Error.errorWithCode(.ContentTypeValidationFailed, failureReason: failureReason)) } } // MARK: - Automatic /** Validates that the response has a status code in the default acceptable range of 200...299, and that the content type matches any specified in the Accept HTTP header field. If validation fails, subsequent calls to response handlers will have an associated error. - returns: The request. */ func validate() -> Self { let acceptableStatusCodes: Range<Int> = 200..<300 let acceptableContentTypes: [String] = { if let accept = request?.valueForHTTPHeaderField("Accept") { return accept.componentsSeparatedByString(",") } return ["*/*"] }() return validate(statusCode: acceptableStatusCodes).validate(contentType: acceptableContentTypes) } }
mit
caca59d57f061a3047abd8c3836e0459
36.359788
122
0.616343
5.621815
false
false
false
false
ZackKingS/Tasks
task/Classes/LoginRegist/Controller/ZBForgotPwdController.swift
1
3114
// // ZBForgotPwdController.swift // task // // Created by 柏超曾 on 2017/9/26. // Copyright © 2017年 柏超曾. All rights reserved. // import Foundation import UIKit import SVProgressHUD class ZBForgotPwdController: UIViewController ,UITextFieldDelegate{ typealias Tomato = (Int, Int) -> Int @IBOutlet weak var phoneL: UITextField! @IBOutlet weak var smsL: UITextField! @IBOutlet weak var nextBtn: UIButton! @IBOutlet weak var bottomCons: NSLayoutConstraint! var count = 1 override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) let image = UIImage.init(named: "tintColor") navigationController?.navigationBar.setBackgroundImage(image, for: .default) //会有黑线 navigationController?.navigationBar.shadowImage = UIImage() } override func viewDidLoad() { super.viewDidLoad() setConfig() phoneL.delegate = self smsL.delegate = self smsL.delegate = self } func textFieldDidBeginEditing(_ textField: UITextField) { if count != 1 { return } if isIPhone6 { UIView.animate(withDuration: 0.3, animations: { self.bottomCons.constant = self.bottomCons.constant + 200 }) }else if isIPhone6P{ UIView.animate(withDuration: 0.3, animations: { self.bottomCons.constant = self.bottomCons.constant + 150 }) } count = count + 1 } @IBOutlet weak var sentSMS: UIButton! @IBAction func sentSMS(_ sender: CountDownBtn) { // todo 手机号正则过滤 if phoneL.text!.characters.count < 10 { self.showHint(hint: "请输入手机号") return } sender.startCountDown() let str = API_GETSMS_URL + "?tel=\(phoneL.text!)&action=1" NetworkTool.getMesa( url: str ){ (result) in SVProgressHUD.showSuccess(withStatus: "") SVProgressHUD.dismiss(withDelay: TimeInterval.init(1)) print(result ?? "213") } } @IBAction func next(_ sender: Any) { let pwd = ZBSetPwdController() pwd.typecase = 2 pwd.phone = phoneL.text! pwd.sms = smsL.text! navigationController?.pushViewController(pwd, animated: true) } func setConfig(){ navigationController?.navigationBar.titleTextAttributes = [ NSForegroundColorAttributeName: UIColor.white, NSFontAttributeName: UIFont.systemFont(ofSize: 18) ] //UIFont(name: "Heiti SC", size: 24.0)! navigationItem.title = "找回密码"; nextBtn.layer.cornerRadius = kLcornerRadius nextBtn.layer.masksToBounds = true } }
apache-2.0
d79c00547bde2ad3869edd106bd344fc
22.882813
92
0.546287
4.978827
false
false
false
false
hq7781/MoneyBook
Pods/ChartsRealm/ChartsRealm/Classes/Data/RealmBarDataSet.swift
2
11992
// // RealmBarDataSet.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics import Charts import Realm import RealmSwift import Realm.Dynamic open class RealmBarDataSet: RealmBarLineScatterCandleBubbleDataSet, IBarChartDataSet { open override func initialize() { self.highlightColor = NSUIColor.black } public required init() { super.init() } public override init(results: RLMResults<RLMObject>?, xValueField: String?, yValueField: String, label: String?) { super.init(results: results, xValueField: xValueField, yValueField: yValueField, label: label) } public init(results: RLMResults<RLMObject>?, xValueField: String?, yValueField: String, stackValueField: String, label: String?) { _stackValueField = stackValueField super.init(results: results, xValueField: xValueField, yValueField: yValueField, label: label) } public convenience init(results: Results<Object>?, xValueField: String?, yValueField: String, stackValueField: String, label: String?) { var converted: RLMResults<RLMObject>? if results != nil { converted = ObjectiveCSupport.convert(object: results!) } self.init(results: converted, xValueField: xValueField, yValueField: yValueField, stackValueField: stackValueField, label: label) } public convenience init(results: RLMResults<RLMObject>?, xValueField: String?, yValueField: String, stackValueField: String) { self.init(results: results, xValueField: xValueField, yValueField: yValueField, stackValueField: stackValueField, label: "DataSet") } public convenience init(results: Results<Object>?, xValueField: String?, yValueField: String, stackValueField: String) { var converted: RLMResults<RLMObject>? if results != nil { converted = ObjectiveCSupport.convert(object: results!) } self.init(results: converted, xValueField: xValueField, yValueField: yValueField, stackValueField: stackValueField, label: "DataSet") } public convenience init(results: RLMResults<RLMObject>?, yValueField: String, stackValueField: String, label: String) { self.init(results: results, xValueField: nil, yValueField: yValueField, stackValueField: stackValueField, label: label) } public convenience init(results: Results<Object>?, yValueField: String, stackValueField: String, label: String) { var converted: RLMResults<RLMObject>? if results != nil { converted = ObjectiveCSupport.convert(object: results!) } self.init(results: converted, yValueField: yValueField, stackValueField: stackValueField, label: label) } public convenience init(results: RLMResults<RLMObject>?, yValueField: String, stackValueField: String) { self.init(results: results, xValueField: nil, yValueField: yValueField, stackValueField: stackValueField) } public convenience init(results: Results<Object>?, yValueField: String, stackValueField: String) { var converted: RLMResults<RLMObject>? if results != nil { converted = ObjectiveCSupport.convert(object: results!) } self.init(results: converted, yValueField: yValueField, stackValueField: stackValueField) } public override init(realm: RLMRealm?, modelName: String, resultsWhere: String, xValueField: String?, yValueField: String, label: String?) { super.init(realm: realm, modelName: modelName, resultsWhere: resultsWhere, xValueField: xValueField, yValueField: yValueField, label: label) } public init(realm: RLMRealm?, modelName: String, resultsWhere: String, xValueField: String?, yValueField: String, stackValueField: String, label: String?) { _stackValueField = stackValueField super.init(realm: realm, modelName: modelName, resultsWhere: resultsWhere, xValueField: xValueField, yValueField: yValueField, label: label) } public convenience init(realm: Realm?, modelName: String, resultsWhere: String, xValueField: String?, yValueField: String, stackValueField: String, label: String?) { var converted: RLMRealm? if realm != nil { converted = ObjectiveCSupport.convert(object: realm!) } self.init(realm: converted, modelName: modelName, resultsWhere: resultsWhere, xValueField: xValueField, yValueField: yValueField, label: label) } public convenience init(realm: RLMRealm?, modelName: String, resultsWhere: String, xValueField: String?, yValueField: String, stackValueField: String) { self.init(realm: realm, modelName: modelName, resultsWhere: resultsWhere, xValueField: nil, yValueField: yValueField, stackValueField: stackValueField) } public convenience init(realm: Realm?, modelName: String, resultsWhere: String, xValueField: String?, yValueField: String, stackValueField: String) { var converted: RLMRealm? if realm != nil { converted = ObjectiveCSupport.convert(object: realm!) } self.init(realm: converted, modelName: modelName, resultsWhere: resultsWhere, xValueField: nil, yValueField: yValueField, stackValueField: stackValueField) } public convenience init(realm: RLMRealm?, modelName: String, resultsWhere: String, yValueField: String, stackValueField: String, label: String?) { self.init(realm: realm, modelName: modelName, resultsWhere: resultsWhere, xValueField: nil, yValueField: yValueField, stackValueField: stackValueField, label: label) } public convenience init(realm: Realm?, modelName: String, resultsWhere: String, yValueField: String, stackValueField: String, label: String?) { var converted: RLMRealm? if realm != nil { converted = ObjectiveCSupport.convert(object: realm!) } self.init(realm: converted, modelName: modelName, resultsWhere: resultsWhere, xValueField: nil, yValueField: yValueField, stackValueField: stackValueField, label: label) } public convenience init(realm: RLMRealm?, modelName: String, resultsWhere: String, yValueField: String, stackValueField: String) { self.init(realm: realm, modelName: modelName, resultsWhere: resultsWhere, xValueField: nil, yValueField: yValueField, stackValueField: stackValueField, label: nil) } public convenience init(realm: Realm?, modelName: String, resultsWhere: String, yValueField: String, stackValueField: String) { var converted: RLMRealm? if realm != nil { converted = ObjectiveCSupport.convert(object: realm!) } self.init(realm: converted, modelName: modelName, resultsWhere: resultsWhere, xValueField: nil, yValueField: yValueField, stackValueField: stackValueField, label: nil) } open override func notifyDataSetChanged() { super.notifyDataSetChanged() self.calcStackSize(entries: _cache as! [BarChartDataEntry]) } // MARK: - Data functions and accessors internal var _stackValueField: String? /// the maximum number of bars that are stacked upon each other, this value /// is calculated from the Entries that are added to the DataSet fileprivate var _stackSize = 1 internal override func buildEntryFromResultObject(_ object: RLMObject, x: Double) -> ChartDataEntry { let value = object[_yValueField!] let entry: BarChartDataEntry if value is RLMArray { var values = [Double]() let iterator = NSFastEnumerationIterator(value as! RLMArray) while let val = iterator.next() { values.append((val as! RLMObject)[_stackValueField!] as! Double) } entry = BarChartDataEntry(x: _xValueField == nil ? x : object[_xValueField!] as! Double, yValues: values) } else { entry = BarChartDataEntry(x: _xValueField == nil ? x : object[_xValueField!] as! Double, y: value as! Double) } return entry } /// calculates the maximum stacksize that occurs in the Entries array of this DataSet fileprivate func calcStackSize(entries: [BarChartDataEntry]) { for i in 0 ..< entries.count { if let vals = entries[i].yValues { if vals.count > _stackSize { _stackSize = vals.count } } } } open override func calcMinMax() { if _cache.count == 0 { return } _yMax = -Double.greatestFiniteMagnitude _yMin = Double.greatestFiniteMagnitude _xMax = -Double.greatestFiniteMagnitude _xMin = Double.greatestFiniteMagnitude for e in _cache as! [BarChartDataEntry] { if !e.y.isNaN { if e.yValues == nil { if e.y < _yMin { _yMin = e.y } if e.y > _yMax { _yMax = e.y } } else { if -e.negativeSum < _yMin { _yMin = -e.negativeSum } if e.positiveSum > _yMax { _yMax = e.positiveSum } } if e.x < _xMin { _xMin = e.x } if e.x > _xMax { _xMax = e.x } } } } /// - returns: The maximum number of bars that can be stacked upon another in this DataSet. open var stackSize: Int { return _stackSize } /// - returns: `true` if this DataSet is stacked (stacksize > 1) or not. open var isStacked: Bool { return _stackSize > 1 ? true : false } /// array of labels used to describe the different values of the stacked bars open var stackLabels: [String] = ["Stack"] // MARK: - Styling functions and accessors /// the color used for drawing the bar-shadows. The bar shadows is a surface behind the bar that indicates the maximum value open var barShadowColor = NSUIColor(red: 215.0/255.0, green: 215.0/255.0, blue: 215.0/255.0, alpha: 1.0) /// the width used for drawing borders around the bars. If borderWidth == 0, no border will be drawn. open var barBorderWidth : CGFloat = 0.0 /// the color drawing borders around the bars. open var barBorderColor = NSUIColor(red: 0.0/255.0, green: 0.0/255.0, blue: 0.0/255.0, alpha: 1.0) /// the alpha value (transparency) that is used for drawing the highlight indicator bar. min = 0.0 (fully transparent), max = 1.0 (fully opaque) open var highlightAlpha = CGFloat(120.0 / 255.0) // MARK: - NSCopying open override func copyWithZone(_ zone: NSZone?) -> AnyObject { let copy = super.copyWithZone(zone) as! RealmBarDataSet copy._stackSize = _stackSize copy.stackLabels = stackLabels copy.barShadowColor = barShadowColor copy.highlightAlpha = highlightAlpha return copy } }
mit
914bc8ac30d91078a524ce73ee3e79dc
35.785276
177
0.614159
5.218451
false
false
false
false
akabekobeko/examples-ios-fmdb
UsingFMDB-Swift/UsingFMDB-Swift/Book.swift
1
906
// // Book.swift // UsingFMDB-Swift // // Created by akabeko on 2016/12/17. // Copyright © 2016年 akabeko. All rights reserved. // import UIKit /// Represents a book. class Book: NSObject { /// Invalid book identifier. static let BookIdNone = 0 /// Identifier. private(set) var bookId: Int /// Title. private(set) var title: String /// Author. private(set) var author: String /// Release date. private(set) var releaseDate: Date /// Initialize the instance. /// /// - Parameters: /// - bookId: Identifier /// - author: Author. /// - title: Title. /// - releaseDate: Release Date init(bookId: Int, author: String, title: String, releaseDate: Date) { self.bookId = bookId self.author = author self.title = title self.releaseDate = releaseDate } }
mit
d918ed27b60f655d1664a28a6db8fb2c
21.02439
73
0.571429
3.977974
false
false
false
false
kean/Nuke
Sources/Nuke/Internal/RateLimiter.swift
1
4285
// The MIT License (MIT) // // Copyright (c) 2015-2022 Alexander Grebenyuk (github.com/kean). import Foundation /// Controls the rate at which the work is executed. Uses the classic [token /// bucket](https://en.wikipedia.org/wiki/Token_bucket) algorithm. /// /// The main use case for rate limiter is to support large (infinite) collections /// of images by preventing trashing of underlying systems, primary URLSession. /// /// The implementation supports quick bursts of requests which can be executed /// without any delays when "the bucket is full". This is important to prevent /// rate limiter from affecting "normal" requests flow. final class RateLimiter: @unchecked Sendable { // This type isn't really Sendable and requires the caller to use the same // queue as it does for synchronization. private let bucket: TokenBucket private let queue: DispatchQueue private var pending = LinkedList<Work>() // fast append, fast remove first private var isExecutingPendingTasks = false typealias Work = () -> Bool /// Initializes the `RateLimiter` with the given configuration. /// - parameters: /// - queue: Queue on which to execute pending tasks. /// - rate: Maximum number of requests per second. 80 by default. /// - burst: Maximum number of requests which can be executed without any /// delays when "bucket is full". 25 by default. init(queue: DispatchQueue, rate: Int = 80, burst: Int = 25) { self.queue = queue self.bucket = TokenBucket(rate: Double(rate), burst: Double(burst)) #if TRACK_ALLOCATIONS Allocations.increment("RateLimiter") #endif } deinit { #if TRACK_ALLOCATIONS Allocations.decrement("RateLimiter") #endif } /// - parameter closure: Returns `true` if the close was executed, `false` /// if the work was cancelled. func execute( _ work: @escaping Work) { if !pending.isEmpty || !bucket.execute(work) { pending.append(work) setNeedsExecutePendingTasks() } } private func setNeedsExecutePendingTasks() { guard !isExecutingPendingTasks else { return } isExecutingPendingTasks = true // Compute a delay such that by the time the closure is executed the // bucket is refilled to a point that is able to execute at least one // pending task. With a rate of 80 tasks we expect a refill every ~26 ms // or as soon as the new tasks are added. let bucketRate = 1000.0 / bucket.rate let delay = Int(2.1 * bucketRate) // 14 ms for rate 80 (default) let bounds = min(100, max(15, delay)) queue.asyncAfter(deadline: .now() + .milliseconds(bounds)) { self.executePendingTasks() } } private func executePendingTasks() { while let node = pending.first, bucket.execute(node.value) { pending.remove(node) } isExecutingPendingTasks = false if !pending.isEmpty { // Not all pending items were executed setNeedsExecutePendingTasks() } } } private final class TokenBucket { let rate: Double private let burst: Double // maximum bucket size private var bucket: Double private var timestamp: TimeInterval // last refill timestamp /// - parameter rate: Rate (tokens/second) at which bucket is refilled. /// - parameter burst: Bucket size (maximum number of tokens). init(rate: Double, burst: Double) { self.rate = rate self.burst = burst self.bucket = burst self.timestamp = CFAbsoluteTimeGetCurrent() } /// Returns `true` if the closure was executed, `false` if dropped. func execute(_ work: () -> Bool) -> Bool { refill() guard bucket >= 1.0 else { return false // bucket is empty } if work() { bucket -= 1.0 // work was cancelled, no need to reduce the bucket } return true } private func refill() { let now = CFAbsoluteTimeGetCurrent() bucket += rate * max(0, now - timestamp) // rate * (time delta) timestamp = now if bucket > burst { // prevent bucket overflow bucket = burst } } }
mit
08b8cb0d875a8970ea295a528b1d992a
35.313559
97
0.636639
4.524815
false
false
false
false
buyiyang/iosstar
iOSStar/Scenes/News/Controller/NewsDetailViewController.swift
3
1615
// // NewsDetailViewController.swift // iOSStar // // Created by J-bb on 17/4/25. // Copyright © 2017年 YunDian. All rights reserved. // import UIKit import WebKit import Kingfisher class NewsDetailViewController: UIViewController { @IBOutlet var shareActionTitlt: UIBarButtonItem! var newsModel:NewsModel? var urlString:String? var shareImage:UIImage? override func viewDidLoad() { super.viewDidLoad() setCustomTitle(title: "资讯详情") // shareActionTitlt.tintColor = UIColor.init(hexString: AppConst.Color.main) let webView = WKWebView(frame: CGRect(x: 0, y: 44, width: kScreenWidth, height: kScreenHeight - 44)) UIApplication.shared.statusBarStyle = .default; let url = URL(string:ShareDataModel.share().qiniuHeader + newsModel!.link_url) let request = URLRequest(url: url!) webView.load(request) view.addSubview(webView) } @IBAction func shareAction(_ sender: Any) { let view : ShareView = Bundle.main.loadNibNamed("ShareView", owner: self, options: nil)?.last as! ShareView view.title = "星享时光" view.thumbImage = "QQ" view.descr = "关于星享时光" view.webpageUrl = "http://www.baidu.com" view.shareViewController(viewController: self) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(false, animated: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
gpl-3.0
73ca4bf45950eac5818b5ae529975d5e
28.333333
115
0.666035
4.363636
false
false
false
false
wl879/SwiftyCss
SwiftyCss/SwiftyNode/Selector/SelectRule.swift
1
4128
// Created by Wang Liang on 2017/4/8. // Copyright © 2017年 Wang Liang. All rights reserved. import Foundation import SwiftyBox class SelectRule: CustomStringConvertible { private static let _lexer = Re( "(^|[#.&])([\\w\\-]+)|" + "(\\[)((?:\\[[^\\]]*\\]|[^\\]])*)\\]|" + "(::|:)([\\w\\-]+)(?:\\(([^)]*)\\))?|" + "([>+~*])" ) // MARK: - let hash :Int? let tag :String? let id :String? let clas :Set<String> let pseudo :Pseudo? let combinator :String? let conditions :[Expression]? let attributes :[String]? public let description :String init(_ text: String, byCreater: Bool = false) { var hash:Int? = nil var tag:String? = nil var id:String? = nil var clas:Set<String> = [] var pseudo:Pseudo? = nil var combinator:String? = nil var conditions:[Expression] = [] var attributes:[String] = [] var offset = 0 while let m = SelectRule._lexer.match(text, offset: offset) { offset = m.lastIndex + 1 switch m[1]! + m[3]! + m[5]! + m[8]! { case ">", "+", "~": combinator = m[8]! case "#": id = m[2]! case "&": hash = Int(m[2]!) case ".": clas.insert(m[2]!) case "::", ":": pseudo = Pseudo(name: m[6]!, params: m[7]!.isEmpty ? nil : m[7] ) case "[": if byCreater { attributes.append( m[4]! ) }else{ conditions.append( Expression(m[4]!) ) } case "*": tag = m[8]! default: tag = m[2]! } } self.hash = hash self.tag = tag self.id = id self.clas = clas self.pseudo = pseudo self.combinator = combinator self.conditions = conditions.isEmpty ? nil : conditions self.attributes = attributes.isEmpty ? nil : attributes var desc = (self.combinator ?? "") + (self.tag ?? "") if self.hash != nil { desc += "&" + self.hash!.description } if self.id != nil { desc += "#" + self.id! } if !self.clas.isEmpty { desc += "." + self.clas.joined(separator:".") } if self.conditions != nil { for c in self.conditions! { desc += "[" + c.description + "]" } } if self.attributes != nil { for c in self.attributes! { desc += "[" + c + "]" } } if self.pseudo != nil { desc += self.pseudo!.description } self.description = desc } public final func check(_ node: NodeProtocol, nonPseudo: Bool = false ) -> Bool { guard self.hash == nil || self.hash == node.hash else { return false } guard self.tag == nil || self.tag == "*" || self.tag == node.tagName else { return false } guard self.id == nil || self.id == node.idName else { return false } if self.clas.count > 0 { let node_class = node.classNames if node_class.isEmpty { return false } for name in self.clas { if node_class.contains(name) == false { return false } } } if nonPseudo == false && self.pseudo != nil { if self.pseudo!.run(with: node) == false { return false } } if self.conditions != nil { for e in 0 ..< self.conditions!.count { if Bool(self.conditions![e].run(with: node)) == false { return false } } } return true } }
mit
d4db6fa178fd2aff7a76b8ebfaae82e4
29.109489
85
0.415515
4.342105
false
false
false
false
Drusy/auvergne-webcams-ios
Carthage/Checkouts/SwiftyUserDefaults/Tests/SwiftyUserDefaultsTests/TestHelpers/TestHelper.swift
1
3233
import Foundation import Quick import SwiftyUserDefaults func given(_ description: String, closure: @escaping () -> Void) { describe(description, closure: closure) } func when(_ description: String, closure: @escaping () -> Void) { context(description, closure: closure) } func then(_ description: String, closure: @escaping () -> Void) { it(description, closure: closure) } extension UserDefaults { func cleanObjects() { for (key, _) in dictionaryRepresentation() { removeObject(forKey: key) } } } struct FrogCodable: Codable, Equatable, DefaultsSerializable { let name: String init(name: String = "Froggy") { self.name = name } } final class FrogSerializable: NSObject, DefaultsSerializable, NSCoding { typealias T = FrogSerializable let name: String init(name: String = "Froggy") { self.name = name } init?(coder aDecoder: NSCoder) { guard let name = aDecoder.decodeObject(forKey: "name") as? String else { return nil } self.name = name } func encode(with aCoder: NSCoder) { aCoder.encode(name, forKey: "name") } override func isEqual(_ object: Any?) -> Bool { guard let rhs = object as? FrogSerializable else { return false } return name == rhs.name } } enum BestFroggiesEnum: String, DefaultsSerializable { case Andy case Dandy } final class DefaultsFrogBridge: DefaultsBridge<FrogCustomSerializable> { override func get(key: String, userDefaults: UserDefaults) -> FrogCustomSerializable? { let name = userDefaults.string(forKey: key) return name.map(FrogCustomSerializable.init) } override func save(key: String, value: FrogCustomSerializable?, userDefaults: UserDefaults) { userDefaults.set(value?.name, forKey: key) } public override func isSerialized() -> Bool { return true } public override func deserialize(_ object: Any) -> FrogCustomSerializable? { guard let name = object as? String else { return nil } return FrogCustomSerializable(name: name) } } final class DefaultsFrogArrayBridge: DefaultsBridge<[FrogCustomSerializable]> { override func get(key: String, userDefaults: UserDefaults) -> [FrogCustomSerializable]? { return userDefaults.array(forKey: key)? .compactMap { $0 as? String } .map(FrogCustomSerializable.init) } override func save(key: String, value: [FrogCustomSerializable]?, userDefaults: UserDefaults) { let values = value?.map { $0.name } userDefaults.set(values, forKey: key) } public override func isSerialized() -> Bool { return true } public override func deserialize(_ object: Any) -> [FrogCustomSerializable]? { guard let names = object as? [String] else { return nil } return names.map(FrogCustomSerializable.init) } } struct FrogCustomSerializable: DefaultsSerializable, Equatable { static var _defaults: DefaultsBridge<FrogCustomSerializable> { return DefaultsFrogBridge() } static var _defaultsArray: DefaultsBridge<[FrogCustomSerializable]> { return DefaultsFrogArrayBridge() } let name: String }
apache-2.0
6fab3d5dd08d05c8fc34dc37f6ddd467
26.398305
108
0.671513
4.339597
false
false
false
false
GreatfeatServices/gf-mobile-app
olivin-esguerra/ios-exam/Pods/RxSwift/RxSwift/Observables/Implementations/ElementAt.swift
11
2111
// // ElementAt.swift // RxSwift // // Created by Junior B. on 21/10/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation class ElementAtSink<O: ObserverType> : Sink<O>, ObserverType { typealias SourceType = O.E typealias Parent = ElementAt<SourceType> let _parent: Parent var _i: Int init(parent: Parent, observer: O, cancel: Cancelable) { _parent = parent _i = parent._index super.init(observer: observer, cancel: cancel) } func on(_ event: Event<SourceType>) { switch event { case .next(_): if (_i == 0) { forwardOn(event) forwardOn(.completed) self.dispose() } do { let _ = try decrementChecked(&_i) } catch(let e) { forwardOn(.error(e)) dispose() return } case .error(let e): forwardOn(.error(e)) self.dispose() case .completed: if (_parent._throwOnEmpty) { forwardOn(.error(RxError.argumentOutOfRange)) } else { forwardOn(.completed) } self.dispose() } } } class ElementAt<SourceType> : Producer<SourceType> { let _source: Observable<SourceType> let _throwOnEmpty: Bool let _index: Int init(source: Observable<SourceType>, index: Int, throwOnEmpty: Bool) { if index < 0 { rxFatalError("index can't be negative") } self._source = source self._index = index self._throwOnEmpty = throwOnEmpty } override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == SourceType { let sink = ElementAtSink(parent: self, observer: observer, cancel: cancel) let subscription = _source.subscribeSafe(sink) return (sink: sink, subscription: subscription) } }
apache-2.0
eb28880fb7bae934f106c2aac6f3fa76
25.375
147
0.531754
4.606987
false
false
false
false
flodolo/firefox-ios
Client/Frontend/Intro/OnboardingCardViewController.swift
1
13701
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/ import UIKit protocol OnboardingCardDelegate: AnyObject { func showNextPage(_ cardType: IntroViewModel.InformationCards) func primaryAction(_ cardType: IntroViewModel.InformationCards) func pageChanged(_ cardType: IntroViewModel.InformationCards) } class OnboardingCardViewController: UIViewController { struct UX { static let stackViewSpacing: CGFloat = 16 static let stackViewSpacingButtons: CGFloat = 40 static let buttonHeight: CGFloat = 45 static let buttonCornerRadius: CGFloat = 13 static let stackViewPadding: CGFloat = 20 static let scrollViewVerticalPadding: CGFloat = 62 static let buttonVerticalInset: CGFloat = 12 static let buttonHorizontalInset: CGFloat = 16 static let buttonFontSize: CGFloat = 16 static let titleFontSize: CGFloat = 34 static let descriptionBoldFontSize: CGFloat = 20 static let descriptionFontSize: CGFloat = 17 static let imageViewSize = CGSize(width: 240, height: 300) // small device static let smallStackViewSpacing: CGFloat = 8 static let smallStackViewSpacingButtons: CGFloat = 16 static let smallScrollViewVerticalPadding: CGFloat = 20 static let smallImageViewSize = CGSize(width: 240, height: 300) } var viewModel: OnboardingCardProtocol weak var delegate: OnboardingCardDelegate? // Adjusting layout for devices with height lower than 667 // including now iPhone SE 2nd generation and iPad var shouldUseSmallDeviceLayout: Bool { return view.frame.height <= 667 || UIDevice.current.userInterfaceIdiom == .pad } private lazy var scrollView: UIScrollView = .build { view in view.backgroundColor = .clear } lazy var containerView: UIView = .build { view in view.backgroundColor = .clear } lazy var contentContainerView: UIView = .build { stack in stack.backgroundColor = .clear } lazy var contentStackView: UIStackView = .build { stack in stack.backgroundColor = .clear stack.alignment = .center stack.distribution = .fill stack.spacing = UX.stackViewSpacing stack.axis = .vertical } lazy var imageView: UIImageView = .build { imageView in imageView.contentMode = .scaleAspectFit imageView.accessibilityIdentifier = "\(self.viewModel.infoModel.a11yIdRoot)ImageView" } private lazy var titleLabel: UILabel = .build { label in label.numberOfLines = 0 label.textAlignment = .center label.font = DynamicFontHelper.defaultHelper.preferredBoldFont(withTextStyle: .largeTitle, size: UX.titleFontSize) label.adjustsFontForContentSizeCategory = true label.accessibilityIdentifier = "\(self.viewModel.infoModel.a11yIdRoot)TitleLabel" } // Only available for Welcome card and default cases private lazy var descriptionBoldLabel: UILabel = .build { label in label.numberOfLines = 0 label.textAlignment = .center label.font = DynamicFontHelper.defaultHelper.preferredBoldFont(withTextStyle: .title3, size: UX.descriptionBoldFontSize) label.isHidden = true label.adjustsFontForContentSizeCategory = true label.accessibilityIdentifier = "\(self.viewModel.infoModel.a11yIdRoot)DescriptionBoldLabel" } private lazy var descriptionLabel: UILabel = .build { label in label.numberOfLines = 0 label.textAlignment = .center label.font = DynamicFontHelper.defaultHelper.preferredFont(withTextStyle: .body, size: UX.descriptionFontSize) label.adjustsFontForContentSizeCategory = true label.accessibilityIdentifier = "\(self.viewModel.infoModel.a11yIdRoot)DescriptionLabel" } lazy var buttonStackView: UIStackView = .build { stack in stack.backgroundColor = .clear stack.distribution = .fill stack.spacing = UX.stackViewSpacing stack.axis = .vertical } private lazy var primaryButton: ResizableButton = .build { button in button.titleLabel?.font = DynamicFontHelper.defaultHelper.preferredBoldFont( withTextStyle: .callout, size: UX.buttonFontSize) button.layer.cornerRadius = UX.buttonCornerRadius button.backgroundColor = UIColor.Photon.Blue50 button.setTitleColor(UIColor.Photon.LightGrey05, for: .normal) button.titleLabel?.textAlignment = .center button.addTarget(self, action: #selector(self.primaryAction), for: .touchUpInside) button.titleLabel?.adjustsFontForContentSizeCategory = true button.accessibilityIdentifier = "\(self.viewModel.infoModel.a11yIdRoot)PrimaryButton" button.contentEdgeInsets = UIEdgeInsets(top: UX.buttonVerticalInset, left: UX.buttonHorizontalInset, bottom: UX.buttonVerticalInset, right: UX.buttonHorizontalInset) } private lazy var secondaryButton: ResizableButton = .build { button in button.titleLabel?.font = DynamicFontHelper.defaultHelper.preferredBoldFont( withTextStyle: .callout, size: UX.buttonFontSize) button.layer.cornerRadius = UX.buttonCornerRadius button.backgroundColor = UIColor.Photon.LightGrey30 button.setTitleColor(UIColor.Photon.DarkGrey90, for: .normal) button.titleLabel?.textAlignment = .center button.addTarget(self, action: #selector(self.secondaryAction), for: .touchUpInside) button.accessibilityIdentifier = "\(self.viewModel.infoModel.a11yIdRoot)SecondaryButton" button.titleLabel?.adjustsFontForContentSizeCategory = true button.contentEdgeInsets = UIEdgeInsets(top: UX.buttonVerticalInset, left: UX.buttonHorizontalInset, bottom: UX.buttonVerticalInset, right: UX.buttonHorizontalInset) } init(viewModel: OnboardingCardProtocol, delegate: OnboardingCardDelegate?) { self.viewModel = viewModel self.delegate = delegate super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() setupView() updateLayout() applyTheme() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) delegate?.pageChanged(viewModel.cardType) viewModel.sendCardViewTelemetry() } func setupView() { view.backgroundColor = .clear contentStackView.addArrangedSubview(imageView) contentStackView.addArrangedSubview(titleLabel) contentStackView.addArrangedSubview(descriptionBoldLabel) contentStackView.addArrangedSubview(descriptionLabel) contentContainerView.addSubviews(contentStackView) buttonStackView.addArrangedSubview(primaryButton) buttonStackView.addArrangedSubview(secondaryButton) containerView.addSubviews(contentContainerView) containerView.addSubviews(buttonStackView) scrollView.addSubviews(containerView) view.addSubview(scrollView) // Adapt layout for smaller screens let scrollViewVerticalPadding = shouldUseSmallDeviceLayout ? UX.smallScrollViewVerticalPadding : UX.scrollViewVerticalPadding let stackViewSpacingButtons = shouldUseSmallDeviceLayout ? UX.smallStackViewSpacingButtons : UX.stackViewSpacingButtons let imageViewHeight = shouldUseSmallDeviceLayout ? UX.imageViewSize.height : UX.smallImageViewSize.height NSLayoutConstraint.activate([ scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor), scrollView.topAnchor.constraint(equalTo: view.topAnchor, constant: scrollViewVerticalPadding), scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor), scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -scrollViewVerticalPadding), scrollView.frameLayoutGuide.leadingAnchor.constraint(equalTo: view.leadingAnchor), scrollView.frameLayoutGuide.topAnchor.constraint(equalTo: view.topAnchor, constant: scrollViewVerticalPadding), scrollView.frameLayoutGuide.trailingAnchor.constraint(equalTo: view.trailingAnchor), scrollView.frameLayoutGuide.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -scrollViewVerticalPadding), scrollView.frameLayoutGuide.heightAnchor.constraint(equalTo: containerView.heightAnchor).priority(.defaultLow), scrollView.contentLayoutGuide.leadingAnchor.constraint(equalTo: containerView.leadingAnchor), scrollView.contentLayoutGuide.topAnchor.constraint(equalTo: containerView.topAnchor), scrollView.contentLayoutGuide.trailingAnchor.constraint(equalTo: containerView.trailingAnchor), scrollView.contentLayoutGuide.bottomAnchor.constraint(equalTo: containerView.bottomAnchor), scrollView.contentLayoutGuide.widthAnchor.constraint(equalTo: scrollView.frameLayoutGuide.widthAnchor), // Content view wrapper around text contentContainerView.topAnchor.constraint(equalTo: containerView.topAnchor), contentContainerView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: UX.stackViewPadding), contentContainerView.bottomAnchor.constraint(equalTo: buttonStackView.topAnchor, constant: -stackViewSpacingButtons), contentContainerView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -UX.stackViewPadding), contentStackView.topAnchor.constraint(greaterThanOrEqualTo: contentContainerView.topAnchor, constant: UX.stackViewPadding), contentStackView.leadingAnchor.constraint(equalTo: contentContainerView.leadingAnchor), contentStackView.bottomAnchor.constraint(greaterThanOrEqualTo: contentContainerView.bottomAnchor, constant: -UX.stackViewPadding).priority(.defaultLow), contentStackView.trailingAnchor.constraint(equalTo: contentContainerView.trailingAnchor), contentStackView.centerYAnchor.constraint(equalTo: contentContainerView.centerYAnchor), buttonStackView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: UX.stackViewPadding), buttonStackView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: -UX.stackViewPadding), buttonStackView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -UX.stackViewPadding), imageView.heightAnchor.constraint(equalToConstant: imageViewHeight) ]) contentStackView.spacing = shouldUseSmallDeviceLayout ? UX.smallStackViewSpacing : UX.stackViewSpacing buttonStackView.spacing = shouldUseSmallDeviceLayout ? UX.smallStackViewSpacing : UX.stackViewSpacing } private func updateLayout() { titleLabel.text = viewModel.infoModel.title descriptionBoldLabel.isHidden = !viewModel.shouldShowDescriptionBold descriptionBoldLabel.text = .Onboarding.IntroDescriptionPart1 descriptionLabel.isHidden = viewModel.infoModel.description?.isEmpty ?? true descriptionLabel.text = viewModel.infoModel.description imageView.image = viewModel.infoModel.image primaryButton.setTitle(viewModel.infoModel.primaryAction, for: .normal) handleSecondaryButton() } private func handleSecondaryButton() { // To keep Title, Description aligned between cards we don't hide the button // we clear the background and make disabled guard let buttonTitle = viewModel.infoModel.secondaryAction else { secondaryButton.isUserInteractionEnabled = false secondaryButton.backgroundColor = .clear return } secondaryButton.setTitle(buttonTitle, for: .normal) } func applyTheme() { let theme = BuiltinThemeName(rawValue: LegacyThemeManager.instance.current.name) ?? .normal if theme == .dark { titleLabel.textColor = .white descriptionLabel.textColor = .white descriptionBoldLabel.textColor = .white primaryButton.setTitleColor(.black, for: .normal) primaryButton.backgroundColor = UIColor.theme.homePanel.activityStreamHeaderButton } else { titleLabel.textColor = .black descriptionLabel.textColor = .black descriptionBoldLabel.textColor = .black primaryButton.setTitleColor(UIColor.Photon.LightGrey05, for: .normal) primaryButton.backgroundColor = UIColor.Photon.Blue50 } } @objc func primaryAction() { viewModel.sendTelemetryButton(isPrimaryAction: true) delegate?.primaryAction(viewModel.cardType) } @objc func secondaryAction() { viewModel.sendTelemetryButton(isPrimaryAction: false) delegate?.showNextPage(viewModel.cardType) } }
mpl-2.0
6a7118dff6823e9932b3ad6bec5660e1
47.585106
164
0.700314
5.685062
false
false
false
false
ta2yak/loqui
Pods/SimpleTab/Pod/Classes/SimpleTabBarController.swift
2
2889
// // SimpleTabBarController.swift // XStreet // // Created by azfx on 07/20/2015. // Copyright (c) 2015 azfx. 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 open class SimpleTabBarController: UITabBarController { var _tabBar:SimpleTabBar? ///Tab Bar Component override open var tabBar:SimpleTabBar { get { return super.tabBar as! SimpleTabBar } set { } } ///View Transitioning Object open var viewTransition:UIViewControllerAnimatedTransitioning? { didSet { tabBar.transitionObject = self.viewTransition } } ///Tab Bar Style ( with animation control for tab switching ) open var tabBarStyle:SimpleTabBarStyle? { didSet { self.tabBarStyle?.refresh() } } /** Set or Get Selected Index */ override open var selectedIndex:Int { get { return super.selectedIndex } set { super.selectedIndex = newValue self.tabBar.selectedIndex = newValue } } override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) //Initial setup tabBar.selectedIndex = self.selectedIndex tabBar.transitionObject = self.viewTransition ?? CrossFadeViewTransition() tabBar.tabBarStyle = self.tabBarStyle ?? ElegantTabBarStyle(tabBar: tabBar) tabBar.tabBarCtrl = self self.delegate = tabBar //Let the style object know when things are loaded self.tabBarStyle?.tabBarCtrlLoaded(tabBarCtrl: self, tabBar: tabBar, selectedIndex: tabBar.selectedIndex) } override open func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
14935febf5d63b786e2764e2cfbc5b88
31.829545
113
0.683281
4.888325
false
false
false
false