repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
lieonCX/Live
Live/View/Home/Room/RoomBottomView.swift
1
2671
// // RoomBottomView.swift // Live // // Created by lieon on 2017/7/4. // Copyright © 2017年 ChengDuHuanLeHui. All rights reserved. // import UIKit class RoomBottomView: UIView { let chattap: UITapGestureRecognizer = UITapGestureRecognizer() lazy var zanBtn: UIButton = { let btn = UIButton(type: .custom) btn.setImage(UIImage(named: "zan_normal"), for: .normal) btn.setImage(UIImage(named: "zan_hightlighted"), for: .highlighted) return btn }() lazy var shopingBtn: UIButton = { let btn = UIButton() btn.setImage(UIImage(named: "shopping_tie"), for: .normal) btn.setImage(UIImage(named: "shopping_tie"), for: .highlighted) return btn }() lazy var shareBtn: UIButton = { let btn = UIButton() btn.setImage(UIImage(named: "play_share"), for: .normal) btn.setImage(UIImage(named: "play_share"), for: .highlighted) return btn }() override init(frame: CGRect) { super.init(frame: frame) addSubview(zanBtn) addSubview(shopingBtn) addSubview(shareBtn) let view = UIView() // view.backgroundColor = UIColor(hex: 0x605c56, alpha: 0.5) // view.layer.cornerRadius = 17 // view.layer.masksToBounds = true addSubview(view) zanBtn.snp.makeConstraints { (maker) in maker.centerY.equalTo(self.snp.centerY) maker.right.equalTo(-12) } shopingBtn.snp.makeConstraints { (maker) in maker.centerY.equalTo(self.snp.centerY) maker.right.equalTo(zanBtn.snp.left).offset(-20) } shareBtn.snp.makeConstraints { (maker) in maker.centerY.equalTo(self.snp.centerY) maker.right.equalTo(shopingBtn.snp.left).offset(-20) } view.snp.makeConstraints { (maker) in maker.left.equalTo(12) maker.centerY.equalTo(self.snp.centerY) maker.height.equalTo(34) maker.width.equalTo(140) } let textLabel = UILabel() textLabel.textColor = .white textLabel.text = "想说点什么..." textLabel.font = UIFont(name: "Helvetica-Bold", size: CGFloat(14)) view.addSubview(textLabel) textLabel.snp.makeConstraints { (maker) in maker.left.equalTo(0) maker.centerY.equalTo(view.snp.centerY) } textLabel.isUserInteractionEnabled = true textLabel.addGestureRecognizer(chattap) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
9b3346e4d540bc1f58d86be0621f4d91
32.225
75
0.600075
4.140187
false
false
false
false
niunaruto/DeDaoAppSwift
testSwift/Pods/YPImagePicker/Source/Helpers/Extensions/AVFoundation+Extensions.swift
2
2801
// // AVCaptureDevice+Extensions.swift // YPImagePicker // // Created by Nik Kov on 09.04.18. // Copyright © 2018 Yummypets. All rights reserved. // import UIKit import Foundation import AVFoundation // MARK: - Global functions func deviceForPosition(_ p: AVCaptureDevice.Position) -> AVCaptureDevice? { for device in AVCaptureDevice.devices(for: AVMediaType.video) where device.position == p { return device } return nil } func thumbnailFromVideoPath(_ path: URL) -> UIImage { let asset = AVURLAsset(url: path, options: nil) let gen = AVAssetImageGenerator(asset: asset) gen.appliesPreferredTrackTransform = true let time = CMTimeMakeWithSeconds(0.0, preferredTimescale: 600) var actualTime = CMTimeMake(value: 0, timescale: 0) let image: CGImage do { image = try gen.copyCGImage(at: time, actualTime: &actualTime) let thumbnail = UIImage(cgImage: image) return thumbnail } catch { } return UIImage() } func setFocusPointOnDevice(device: AVCaptureDevice, point: CGPoint) { do { try device.lockForConfiguration() if device.isFocusModeSupported(AVCaptureDevice.FocusMode.autoFocus) { device.focusMode = AVCaptureDevice.FocusMode.autoFocus device.focusPointOfInterest = point } if device.isExposureModeSupported(AVCaptureDevice.ExposureMode.continuousAutoExposure) { device.exposureMode = AVCaptureDevice.ExposureMode.continuousAutoExposure device.exposurePointOfInterest = point } device.unlockForConfiguration() } catch _ { return } } func setFocusPointOnCurrentDevice(_ point: CGPoint) { if let device = AVCaptureDevice.default(for: AVMediaType.video) { do { try device.lockForConfiguration() if device.isFocusModeSupported(AVCaptureDevice.FocusMode.autoFocus) == true { device.focusMode = AVCaptureDevice.FocusMode.autoFocus device.focusPointOfInterest = point } if device.isExposureModeSupported(AVCaptureDevice.ExposureMode.continuousAutoExposure) == true { device.exposureMode = AVCaptureDevice.ExposureMode.continuousAutoExposure device.exposurePointOfInterest = point } } catch _ { return } device.unlockForConfiguration() } } func toggledPositionForDevice(_ device: AVCaptureDevice) -> AVCaptureDevice.Position { return (device.position == .front) ? .back : .front } func flippedDeviceInputForInput(_ input: AVCaptureDeviceInput) -> AVCaptureDeviceInput? { let p = toggledPositionForDevice(input.device) let aDevice = deviceForPosition(p) return try? AVCaptureDeviceInput(device: aDevice!) }
mit
3f5f919b0ceb842fed4f5fe106de606e
33.567901
108
0.687143
5.147059
false
false
false
false
atuooo/notGIF
notGIF/Extensions/Realm+NG.swift
1
941
// // Realm+NG.swift // notGIF // // Created by Atuooo on 18/06/2017. // Copyright © 2017 xyz. All rights reserved. // import Foundation import RealmSwift public extension List { func add(object: Element, update: Bool) { if update { if !contains(object) { append(object) } } else { append(object) } } func add<S: Sequence>(objectsIn objects: S, update: Bool) where S.Iterator.Element == T { if update { objects.forEach{ add(object: $0, update: true) } } else { append(objectsIn: objects) } } func remove(_ object: Element) { if let index = index(of: object) { remove(objectAtIndex: index) } } func remove<S: Sequence>(objectsIn objects: S) where S.Iterator.Element == T { objects.forEach { remove($0) } } }
mit
ba6f444fed55e34fc41555e3c5ad5173
21.380952
93
0.52234
3.983051
false
false
false
false
fortmarek/Supl
Supl/SafariViewController.swift
1
1555
// // SafariViewController.swift // Supl // // Created by Marek Fořt on 16.02.16. // Copyright © 2016 Marek Fořt. All rights reserved. // import UIKit class SafariViewController: UIViewController { @IBOutlet weak var openSafariButton: UIButton! @IBOutlet weak var heightConstraint: NSLayoutConstraint! @IBOutlet weak var widthConstraint: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() openSafariButton.backgroundColor = UIColor.clear openSafariButton.layer.cornerRadius = 25 openSafariButton.layer.borderWidth = 1 openSafariButton.layer.borderColor = UIColor.white.cgColor let heightPageVC = CGFloat(55) //55 is height of PageVC elements var bottomOfButton = openSafariButton.frame.origin.y + openSafariButton.frame.height while self.view.frame.size.height - bottomOfButton < heightPageVC { bottomOfButton -= heightConstraint.constant * 0.3 heightConstraint.constant = heightConstraint.constant * 0.7 widthConstraint.constant = widthConstraint.constant * 0.7 } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func openSafariButtonTapped(_ sender: UIButton) { let safariUrl = URL(string:"http://old.gjk.cz/suplovani.php") if let url = safariUrl { UIApplication.shared.openURL(url) } } }
mit
1effbe497cb34f6319ef23877e766b15
29.431373
92
0.668814
4.926984
false
false
false
false
Keanyuan/SwiftContact
SwiftContent/Pods/Kingfisher/Sources/KingfisherOptionsInfo.swift
2
13671
// // KingfisherOptionsInfo.swift // Kingfisher // // Created by Wei Wang on 15/4/23. // // Copyright (c) 2017 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 /** * KingfisherOptionsInfo is a typealias for [KingfisherOptionsInfoItem]. You can use the enum of option item with value to control some behaviors of Kingfisher. */ public typealias KingfisherOptionsInfo = [KingfisherOptionsInfoItem] let KingfisherEmptyOptionsInfo = [KingfisherOptionsInfoItem]() /** Items could be added into KingfisherOptionsInfo. */ public enum KingfisherOptionsInfoItem { /// The associated value of this member should be an ImageCache object. Kingfisher will use the specified /// cache object when handling related operations, including trying to retrieve the cached images and store /// the downloaded image to it. case targetCache(ImageCache) /// The associated value of this member should be an ImageDownloader object. Kingfisher will use this /// downloader to download the images. case downloader(ImageDownloader) /// Member for animation transition when using UIImageView. Kingfisher will use the `ImageTransition` of /// this enum to animate the image in if it is downloaded from web. The transition will not happen when the /// image is retrieved from either memory or disk cache by default. If you need to do the transition even when /// the image being retrieved from cache, set `ForceTransition` as well. case transition(ImageTransition) /// Associated `Float` value will be set as the priority of image download task. The value for it should be /// between 0.0~1.0. If this option not set, the default value (`NSURLSessionTaskPriorityDefault`) will be used. case downloadPriority(Float) /// If set, `Kingfisher` will ignore the cache and try to fire a download task for the resource. case forceRefresh /// If set, setting the image to an image view will happen with transition even when retrieved from cache. /// See `Transition` option for more. case forceTransition /// If set, `Kingfisher` will only cache the value in memory but not in disk. case cacheMemoryOnly /// If set, `Kingfisher` will only try to retrieve the image from cache not from network. case onlyFromCache /// Decode the image in background thread before using. case backgroundDecode /// The associated value of this member will be used as the target queue of dispatch callbacks when /// retrieving images from cache. If not set, `Kingfisher` will use main quese for callbacks. case callbackDispatchQueue(DispatchQueue?) /// The associated value of this member will be used as the scale factor when converting retrieved data to an image. /// It is the image scale, instead of your screen scale. You may need to specify the correct scale when you dealing /// with 2x or 3x retina images. case scaleFactor(CGFloat) /// Whether all the animated image data should be preloaded. Default it false, which means following frames will be /// loaded on need. If true, all the animated image data will be loaded and decoded into memory. This option is mainly /// used for back compatibility internally. You should not set it directly. `AnimatedImageView` will not preload /// all data, while a normal image view (`UIImageView` or `NSImageView`) will load all data. Choose to use /// corresponding image view type instead of setting this option. case preloadAllAnimationData /// The `ImageDownloadRequestModifier` contained will be used to change the request before it being sent. /// This is the last chance you can modify the request. You can modify the request for some customizing purpose, /// such as adding auth token to the header, do basic HTTP auth or something like url mapping. The original request /// will be sent without any modification by default. case requestModifier(ImageDownloadRequestModifier) /// Processor for processing when the downloading finishes, a processor will convert the downloaded data to an image /// and/or apply some filter on it. If a cache is connected to the downloader (it happenes when you are using /// KingfisherManager or the image extension methods), the converted image will also be sent to cache as well as the /// image view. `DefaultImageProcessor.default` will be used by default. case processor(ImageProcessor) /// Supply an `CacheSerializer` to convert some data to an image object for /// retrieving from disk cache or vice versa for storing to disk cache. /// `DefaultCacheSerializer.default` will be used by default. case cacheSerializer(CacheSerializer) /// Keep the existing image while setting another image to an image view. /// By setting this option, the placeholder image parameter of imageview extension method /// will be ignored and the current image will be kept while loading or downloading the new image. case keepCurrentImageWhileLoading /// If set, Kingfisher will only load the first frame from a animated image data file as a single image. /// Loading a lot of animated images may take too much memory. It will be useful when you want to display a /// static preview of the first frame from a animated image. /// This option will be ignored if the target image is not animated image data. case onlyLoadFirstFrame } precedencegroup ItemComparisonPrecedence { associativity: none higherThan: LogicalConjunctionPrecedence } infix operator <== : ItemComparisonPrecedence // This operator returns true if two `KingfisherOptionsInfoItem` enum is the same, without considering the associated values. func <== (lhs: KingfisherOptionsInfoItem, rhs: KingfisherOptionsInfoItem) -> Bool { switch (lhs, rhs) { case (.targetCache(_), .targetCache(_)): return true case (.downloader(_), .downloader(_)): return true case (.transition(_), .transition(_)): return true case (.downloadPriority(_), .downloadPriority(_)): return true case (.forceRefresh, .forceRefresh): return true case (.forceTransition, .forceTransition): return true case (.cacheMemoryOnly, .cacheMemoryOnly): return true case (.onlyFromCache, .onlyFromCache): return true case (.backgroundDecode, .backgroundDecode): return true case (.callbackDispatchQueue(_), .callbackDispatchQueue(_)): return true case (.scaleFactor(_), .scaleFactor(_)): return true case (.preloadAllAnimationData, .preloadAllAnimationData): return true case (.requestModifier(_), .requestModifier(_)): return true case (.processor(_), .processor(_)): return true case (.cacheSerializer(_), .cacheSerializer(_)): return true case (.keepCurrentImageWhileLoading, .keepCurrentImageWhileLoading): return true case (.onlyLoadFirstFrame, .onlyLoadFirstFrame): return true default: return false } } extension Array where Element == KingfisherOptionsInfoItem { func lastMatchIgnoringAssociatedValue(_ target: Element) -> Element? { return reversed().index { $0 <== target } .flatMap { self[self.count - $0 - 1] } } func removeAllMatchesIgnoringAssociatedValue(_ target: Element) -> [Element] { return filter { !($0 <== target) } } } public extension Array where Element == KingfisherOptionsInfoItem { /// The target `ImageCache` which is used. public var targetCache: ImageCache { if let item = lastMatchIgnoringAssociatedValue(.targetCache(.default)), case .targetCache(let cache) = item { return cache } return ImageCache.default } /// The `ImageDownloader` which is specified. public var downloader: ImageDownloader { if let item = lastMatchIgnoringAssociatedValue(.downloader(.default)), case .downloader(let downloader) = item { return downloader } return ImageDownloader.default } /// Member for animation transition when using UIImageView. public var transition: ImageTransition { if let item = lastMatchIgnoringAssociatedValue(.transition(.none)), case .transition(let transition) = item { return transition } return ImageTransition.none } /// A `Float` value set as the priority of image download task. The value for it should be /// between 0.0~1.0. public var downloadPriority: Float { if let item = lastMatchIgnoringAssociatedValue(.downloadPriority(0)), case .downloadPriority(let priority) = item { return priority } return URLSessionTask.defaultPriority } /// Whether an image will be always downloaded again or not. public var forceRefresh: Bool { return contains{ $0 <== .forceRefresh } } /// Whether the transition should always happen or not. public var forceTransition: Bool { return contains{ $0 <== .forceTransition } } /// Whether cache the image only in memory or not. public var cacheMemoryOnly: Bool { return contains{ $0 <== .cacheMemoryOnly } } /// Whether only load the images from cache or not. public var onlyFromCache: Bool { return contains{ $0 <== .onlyFromCache } } /// Whether the image should be decoded in background or not. public var backgroundDecode: Bool { return contains{ $0 <== .backgroundDecode } } /// Whether the image data should be all loaded at once if it is an animated image. public var preloadAllAnimationData: Bool { return contains { $0 <== .preloadAllAnimationData } } /// The queue of callbacks should happen from Kingfisher. public var callbackDispatchQueue: DispatchQueue { if let item = lastMatchIgnoringAssociatedValue(.callbackDispatchQueue(nil)), case .callbackDispatchQueue(let queue) = item { return queue ?? DispatchQueue.main } return DispatchQueue.main } /// The scale factor which should be used for the image. public var scaleFactor: CGFloat { if let item = lastMatchIgnoringAssociatedValue(.scaleFactor(0)), case .scaleFactor(let scale) = item { return scale } return 1.0 } /// The `ImageDownloadRequestModifier` will be used before sending a download request. public var modifier: ImageDownloadRequestModifier { if let item = lastMatchIgnoringAssociatedValue(.requestModifier(NoModifier.default)), case .requestModifier(let modifier) = item { return modifier } return NoModifier.default } /// `ImageProcessor` for processing when the downloading finishes. public var processor: ImageProcessor { if let item = lastMatchIgnoringAssociatedValue(.processor(DefaultImageProcessor.default)), case .processor(let processor) = item { return processor } return DefaultImageProcessor.default } /// `CacheSerializer` to convert image to data for storing in cache. public var cacheSerializer: CacheSerializer { if let item = lastMatchIgnoringAssociatedValue(.cacheSerializer(DefaultCacheSerializer.default)), case .cacheSerializer(let cacheSerializer) = item { return cacheSerializer } return DefaultCacheSerializer.default } /// Keep the existing image while setting another image to an image view. /// Or the placeholder will be used while downloading. public var keepCurrentImageWhileLoading: Bool { return contains { $0 <== .keepCurrentImageWhileLoading } } public var onlyLoadFirstFrame: Bool { return contains { $0 <== .onlyLoadFirstFrame } } } // MARK: - Deprecated. Only for back compatibility. public extension Array where Element == KingfisherOptionsInfoItem { /// Whether the image data should be all loaded at once if it is a GIF. @available(*, deprecated, renamed: "preloadAllAnimationData") public var preloadAllGIFData: Bool { return preloadAllAnimationData } } public extension KingfisherOptionsInfoItem { @available(*, deprecated, renamed: "preloadAllAnimationData") static let preloadAllGIFData = KingfisherOptionsInfoItem.preloadAllAnimationData }
mit
466949dd32e0c3ded1069616ef881c30
42.677316
159
0.70068
5.422848
false
false
false
false
Palleas/Batman
ColorDump/main.swift
1
2259
import Foundation func main(argv: [String]) { guard argv.count > 1 else { fatalError("Usage ColorDump file.sketch") } let sketchFile = CommandLine.arguments[1] let filename = UUID().uuidString let path = (NSTemporaryDirectory() as NSString).appendingPathComponent(filename) print("Temoporary dir is \(path)") // Open Sketch file let t = Process() t.arguments = [sketchFile, "-d", path] t.launchPath = "/usr/bin/unzip" t.launch() t.waitUntilExit() // Retrieve the `Documents.json` let document = (path as NSString).appendingPathComponent("document.json") guard FileManager.default.fileExists(atPath: document) else { fatalError("Unable to parse Sketch file (no documents.json)") } // Extract content from document.json let content = try! Data(contentsOf: URL(fileURLWithPath: document)) // swiftlint:disable:this force_try var payload = try! JSONSerialization.jsonObject(with: content, options: .allowFragments) as! [AnyHashable: Any] // swiftlint:disable:this force_try force_cast // Extract colors let colors: [[String: Any]] = ProjectColor.all.map { color in var red: CGFloat = 0 var green: CGFloat = 0 var blue: CGFloat = 0 var alpha: CGFloat = 0 color.raw.getRed(&red, green: &green, blue: &blue, alpha: &alpha) return ["_class": "color", "alpha": alpha, "blue": blue, "green": green, "red": red] } // Update "document.json" var assets = payload["assets"] as! [AnyHashable: Any] // swiftlint:disable:this force_cast assets["colors"] = colors payload["assets"] = assets // Serialize and store! let newContent = try! JSONSerialization.data(withJSONObject: payload, options: .prettyPrinted) // swiftlint:disable:this force_try try! newContent.write(to: URL(fileURLWithPath: document)) // swiftlint:disable:this force_try // Close Sketch file let close = Process() close.launchPath = "/usr/bin/zip" close.currentDirectoryPath = path close.arguments = ["-r", sketchFile, "*"] close.launch() close.waitUntilExit() } //CommandLine.arguments main(argv: CommandLine.arguments)
mit
86062d6fa78e7995039fe3e1c9f4a5d0
32.220588
162
0.648074
4.22243
false
false
false
false
dimitris-c/Omicron
Tests/APIServiceSpec.swift
1
11580
// // APIServiceSpec.swift // Omicron // // Created by Dimitris C. on 19/06/2017. // Copyright © 2017 Decimal. All rights reserved. // import Quick import Nimble import Alamofire import SwiftyJSON import OHHTTPStubs @testable import Omicron class APIServiceSpec: QuickSpec { override func spec() { beforeEach { OHHTTPStubs.removeAllStubs() } describe("APIService") { it("takes an APIRequest and makes a call") { let service = APIService<HTTPBin>() var apiResult: JSON? var apiResponse: URLResponse? waitUntil(timeout: 30, action: { done in service.call(with: .get, parse: JSONResponse(), { (success, result, response) in apiResult = result.value apiResponse = response done() }) }) expect(service).toNot(beNil()) expect(apiResult).toNot(beNil()) expect(apiResult).to(beAKindOf(JSON.self)) expect(apiResponse).toNot(beNil()) expect(apiResponse).to(beAKindOf(URLResponse.self)) } it("can make a request and call a json response using callJSON") { let service = APIService<HTTPBin>() var apiResult: JSON? var apiResponse: URLResponse? waitUntil(timeout: 30, action: { done in service.callJSON(with: .get) { (success, result, response) in apiResult = result.value apiResponse = response done() } }) expect(service).toNot(beNil()) expect(apiResult).toNot(beNil()) expect(apiResult).to(beAKindOf(JSON.self)) expect(apiResponse).toNot(beNil()) expect(apiResponse).to(beAKindOf(URLResponse.self)) } it("returns its completion on the MainThread") { let service = APIService<HTTPBin>() var expectedMainThread: Bool = false service.call(with: .get, parse: JSONResponse(), { (success, result, response) in expectedMainThread = Thread.current.isMainThread }) expect(service).toNot(beNil()) expect(expectedMainThread).toEventually(beTrue()) } it("returns a failure and an error") { let service = APIService<HTTPBin>() var apiResult: Any? var apiSuccess: Bool = true var error: Error? service.call(with: .nonExistingPath, parse: JSONResponse(), { (success, result, response) in apiSuccess = success apiResult = result.value error = result.error }) expect(apiSuccess).toEventually(beFalse()) expect(apiResult).toEventually(beNil()) expect(error).toEventuallyNot(beNil()) } it("returns the parsed model") { let userJSON: String = "{\"name\":\"Dimitris\"}" let service = APIService<HTTPBin>() var apiSuccess: Bool = false var user: User? service.call(with: .anything(value: userJSON), parse: UserResponseFromHTTPBin(), { (success, result, response) in apiSuccess = success user = result.value }) expect(apiSuccess).toEventually(beTrue()) expect(user).toEventuallyNot(beNil()) expect(user).toEventually(beAKindOf(User.self)) expect(user!.name).toEventually(equal("Dimitris")) } it("returns an Alamofire Request") { let service = APIService<HTTPBin>() let dataRequest = service.call(with: .get, parse: JSONResponse(), { (success, result, response) in }) dataRequest.cancel() expect(dataRequest).toNot(beNil()) } it("returns an Error when the request is canceled") { var receivedError: Error? waitUntil(timeout: 30, action: { done in let service = APIService<HTTPBin>() let dataRequest = service.call(with: .get, parse: JSONResponse(), { (success, result, response) in receivedError = result.error done() }) dataRequest.cancel() }) expect(receivedError).toNot(beNil()) } it("can call rawData") { let service = APIService<HTTPBin>() var data: Data? waitUntil(timeout: 30, action: { done in service.callData(with: .get) { (success, result, response) in if success { data = result.value } done() } }) expect(data).toNot(beNil()) } it("can call rawData and can fail") { let service = APIService<HTTPBin>() var data: Data? var error: Error? waitUntil(timeout: 30, action: { done in let request = service.callData(with: .get) { (success, result, response) in data = result.value error = result.error done() } request.cancel() }) expect(data).to(beNil()) expect(error).toNot(beNil()) } it("completion when calling rawData should be returned on the main thread") { let service = APIService<HTTPBin>() var isMainThread: Bool = false waitUntil(timeout: 30, action: { done in service.callData(with: .get) { (success, result, response) in isMainThread = Thread.current.isMainThread done() } }) expect(isMainThread).to(beTrue()) } context("APIService with stubs", { beforeEach { OHHTTPStubs.setEnabled(true) } afterEach { OHHTTPStubs.removeAllStubs() } it("returns a model") { stub(condition: isHost("httpbin.org"), response: { _ -> OHHTTPStubsResponse in let stubPath = OHPathForFile("user.json", type(of: self)) return fixture(filePath: stubPath!, headers: ["Content-Type":"application/json"]) }) let service = APIService<HTTPBin>() var user: User? waitUntil(timeout: 30, action: { done in service.call(with: .get, parse: UserReponse(), { (success, result, response) in if success { user = result.value } done() }) }) expect(request).toNot(beNil()) expect(user).toNot(beNil()) expect(user!.name).to(equal("Dimitris")) expect(user!.lastname).to(equal("Chatzieleftheriou")) } it("returns an array of model") { stub(condition: isHost("httpbin.org"), response: { _ -> OHHTTPStubsResponse in let stubPath = OHPathForFile("users.json", type(of: self)) return fixture(filePath: stubPath!, headers: ["Content-Type":"application/json"]) }) let service = APIService<HTTPBin>() var user: [User]? waitUntil(timeout: 30, action: { done in service.call(with: .get, parse: UsersResponse(), { (success, result, response) in if success { user = result.value } done() }) }) expect(request).toNot(beNil()) expect(user).toNot(beNil()) expect(user!.count).to(equal(2)) expect(user!.first!.name).to(equal("Dimitris")) expect(user!.first!.lastname).to(equal("Chatzieleftheriou")) } it("can make a call for a plain string response") { stub(condition: isHost("httpbin.org"), response: { _ -> OHHTTPStubsResponse in let stubPath = OHPathForFile("text.txt", type(of: self)) return fixture(filePath: stubPath!, headers: ["Content-Type":"application/text"]) }) let service = APIService<HTTPBin>() var text: String? waitUntil(timeout: 30.0, action: { done in service.callString(with: .get) { (success, result, response) in text = result.value done() } }) expect(request).toNot(beNil()) expect(text).toNot(beNil()) expect(text!).to(contain("Imagination")) } }) } describe("APIService Github Service") { it("returns JSON response") { let service = APIService<GithubService>() var userJSON: JSON? waitUntil(timeout: 30.0, action: { (done) in service.callJSON(with: .user(name: "dimitris-c"), { (success, result, response) in userJSON = result.value done() }) }) expect(userJSON).toNot(beNil()) } it("returns the appropriate response model") { let service = APIService<GithubService>() var user: GithubUser? waitUntil(timeout: 30.0, action: { (done) in service.call(with: .user(name: "dimitris-c"), parse: GithubUserResponse(), { (success, result, response) in if success { user = result.value } done() }) }) expect(user).toNot(beNil()) } } } }
mit
138245bbfab6248f5a0987a03c627c17
40.060284
129
0.434925
5.990171
false
false
false
false
dfsilva/actor-platform
actor-sdk/sdk-core-ios/ActorApp/AppDelegate.swift
1
3430
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import Foundation import ActorSDK open class AppDelegate : ActorApplicationDelegate { override init() { super.init() ActorSDK.sharedActor().inviteUrlHost = "quit.email" ActorSDK.sharedActor().inviteUrlScheme = "actor" let style = ActorSDK.sharedActor().style // Default Status Bar style style.vcStatusBarStyle = .lightContent // Navigation colors style.navigationBgColor = UIColor(rgb: 0xA43436) style.dialogStatusActive = UIColor(rgb: 0xff5882) style.welcomeBgColor = UIColor(rgb: 0xA43436) ActorSDK.sharedActor().style.welcomeSignupTextColor = UIColor(rgb: 0xA43436) ActorSDK.sharedActor().style.nextBarColor = UIColor(rgb: 0xA43436) style.navigationTintColor = UIColor.white style.navigationTitleColor = UIColor.white style.navigationSubtitleColor = UIColor.white.alpha(0.64) style.navigationSubtitleActiveColor = UIColor.white // style.navigationHairlineHidden = true // Full screen placeholder. Set here value that matches UINavigationBar color style.placeholderBgColor = UIColor(rgb: 0x528dbe) // Override User's online/offline statuses in navigation color style.userOfflineNavigationColor = UIColor.white.alpha(0.64) style.userOnlineNavigationColor = UIColor.white // Override search status bar style style.searchStatusBarStyle = .default // Enabling experimental features ActorSDK.sharedActor().enableExperimentalFeatures = true ActorSDK.sharedActor().enableCalls = true ActorSDK.sharedActor().enableVideoCalls = false // Setting Development Push Id ActorSDK.sharedActor().apiPushId = 868547 ActorSDK.sharedActor().autoPushMode = .afterLogin ActorSDK.sharedActor().authStrategy = .phoneEmail ActorSDK.sharedActor().style.dialogAvatarSize = 58 // ActorSDK.sharedActor().autoJoinGroups = ["canalxloto"] // ActorSDK.sharedActor().endpoints = ["tcp://api-mtproto.im.xloto.com.br:9070"] ActorSDK.sharedActor().endpoints = ["tcp://192.168.1.3:9070"] // ActorSDK.sharedActor().endpoints = ["tcp://api-mtproto.actor.diegosilva.com.br:9070"] //AppCocoaHttpRuntime.getMethod("") // Creating Actor ActorSDK.sharedActor().createActor() } open override func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]?) -> Bool { super.application(application, didFinishLaunchingWithOptions: launchOptions) ActorSDK.sharedActor().presentMessengerInNewWindow() return true } open override func actorRootControllers() -> [UIViewController]? { return [AAContactsViewController(), AARecentViewController(), AASettingsViewController()] } open override func actorRootInitialControllerIndex() -> Int? { return 1 } open override func showStickersButton() -> Bool{ return false } open override func useOnClientPrivacy() -> Bool{ return true } }
agpl-3.0
5503624f626edf9b76ab4335b6a5b6aa
33.646465
159
0.643732
5.181269
false
false
false
false
mikaoj/BSImagePicker
Sources/Controller/ImagePickerController.swift
1
6585
// The MIT License (MIT) // // Copyright (c) 2019 Joakim Gyllström // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit import Photos // MARK: ImagePickerController @objc(BSImagePickerController) @objcMembers open class ImagePickerController: UINavigationController { // MARK: Public properties public weak var imagePickerDelegate: ImagePickerControllerDelegate? public var settings: Settings = Settings() public var doneButton: UIBarButtonItem = UIBarButtonItem(title: "", style: .done, target: nil, action: nil) public var cancelButton: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: nil, action: nil) public var albumButton: UIButton = UIButton(type: .custom) public var selectedAssets: [PHAsset] { get { return assetStore.assets } } /// Title to use for button public var doneButtonTitle = Bundle(for: UIBarButtonItem.self).localizedString(forKey: "Done", value: "Done", table: "") // MARK: Internal properties var assetStore: AssetStore var onSelection: ((_ asset: PHAsset) -> Void)? var onDeselection: ((_ asset: PHAsset) -> Void)? var onCancel: ((_ assets: [PHAsset]) -> Void)? var onFinish: ((_ assets: [PHAsset]) -> Void)? let assetsViewController: AssetsViewController let albumsViewController = AlbumsViewController() let dropdownTransitionDelegate = DropdownTransitionDelegate() let zoomTransitionDelegate = ZoomTransitionDelegate() lazy var albums: [PHAssetCollection] = { // We don't want collections without assets. // I would like to do that with PHFetchOptions: fetchOptions.predicate = NSPredicate(format: "estimatedAssetCount > 0") // But that doesn't work... // This seems suuuuuper ineffective... let fetchOptions = settings.fetch.assets.options.copy() as! PHFetchOptions fetchOptions.fetchLimit = 1 return settings.fetch.album.fetchResults.filter { $0.count > 0 }.flatMap { $0.objects(at: IndexSet(integersIn: 0..<$0.count)) }.filter { // We can't use estimatedAssetCount on the collection // It returns NSNotFound. So actually fetch the assets... let assetsFetchResult = PHAsset.fetchAssets(in: $0, options: fetchOptions) return assetsFetchResult.count > 0 } }() public init(selectedAssets: [PHAsset] = []) { assetStore = AssetStore(assets: selectedAssets) assetsViewController = AssetsViewController(store: assetStore) super.init(nibName: nil, bundle: nil) } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override func viewDidLoad() { super.viewDidLoad() // Sync settings albumsViewController.settings = settings assetsViewController.settings = settings // Setup view controllers albumsViewController.delegate = self assetsViewController.delegate = self viewControllers = [assetsViewController] view.backgroundColor = settings.theme.backgroundColor // Setup delegates delegate = zoomTransitionDelegate presentationController?.delegate = self // Turn off translucency so drop down can match its color navigationBar.isTranslucent = false navigationBar.isOpaque = true // Setup buttons let firstViewController = viewControllers.first albumButton.setTitleColor(albumButton.tintColor, for: .normal) albumButton.titleLabel?.font = .systemFont(ofSize: 16) albumButton.titleLabel?.adjustsFontSizeToFitWidth = true let arrowView = ArrowView(frame: CGRect(x: 0, y: 0, width: 8, height: 8)) arrowView.backgroundColor = .clear arrowView.strokeColor = albumButton.tintColor let image = arrowView.asImage albumButton.setImage(image, for: .normal) albumButton.semanticContentAttribute = .forceRightToLeft // To set image to the right without having to calculate insets/constraints. albumButton.addTarget(self, action: #selector(ImagePickerController.albumsButtonPressed(_:)), for: .touchUpInside) firstViewController?.navigationItem.titleView = albumButton doneButton.target = self doneButton.action = #selector(doneButtonPressed(_:)) firstViewController?.navigationItem.rightBarButtonItem = doneButton cancelButton.target = self cancelButton.action = #selector(cancelButtonPressed(_:)) firstViewController?.navigationItem.leftBarButtonItem = cancelButton updatedDoneButton() updateAlbumButton() // We need to have some color to be able to match with the drop down if navigationBar.barTintColor == nil { navigationBar.barTintColor = .systemBackgroundColor } if let firstAlbum = albums.first { select(album: firstAlbum) } } public func deselect(asset: PHAsset) { assetStore.remove(asset) assetsViewController.unselect(asset: asset) updatedDoneButton() } func updatedDoneButton() { doneButton.title = assetStore.count > 0 ? doneButtonTitle + " (\(assetStore.count))" : doneButtonTitle doneButton.isEnabled = assetStore.count >= settings.selection.min } func updateAlbumButton() { albumButton.isHidden = albums.count < 2 } }
mit
0a8252c5b56270fb777429075c734426
40.15
141
0.687728
5.305399
false
false
false
false
themonki/onebusaway-iphone
OBAKit/Services/PromisedModelService.swift
1
9080
// // PromisedModelService.swift // OBAKit // // Created by Aaron Brethorst on 11/5/17. // Copyright © 2017 OneBusAway. All rights reserved. // import PromiseKit // swiftlint:disable force_cast // MARK: Stop -> OBAArrivalAndDepartureV2 @objc public class PromisedModelService: OBAModelService { @objc public func requestStopArrivalsAndDepartures(withID stopID: String, minutesBefore: UInt, minutesAfter: UInt) -> PromiseWrapper { let request = buildURLRequestForStopArrivalsAndDepartures(withID: stopID, minutesBefore: minutesBefore, minutesAfter: minutesAfter) let promiseWrapper = PromiseWrapper.init(request: request) promiseWrapper.promise = promiseWrapper.promise.then { networkResponse -> NetworkResponse in let arrivals = try self.decodeStopArrivals(json: networkResponse.object) return NetworkResponse.init(object: arrivals, URLResponse: networkResponse.URLResponse, urlRequest: networkResponse.urlRequest) } return promiseWrapper } @objc public func buildURLRequestForStopArrivalsAndDepartures(withID stopID: String, minutesBefore: UInt, minutesAfter: UInt) -> OBAURLRequest { let args = ["minutesBefore": minutesBefore, "minutesAfter": minutesAfter] let escapedStopID = OBAURLHelpers.escapePathVariable(stopID) let path = String.init(format: "/api/where/arrivals-and-departures-for-stop/%@.json", escapedStopID) return obaJsonDataSource.buildGETRequest(withPath: path, queryParameters: args) } private func decodeStopArrivals(json: Any) throws -> OBAArrivalsAndDeparturesForStopV2 { var error: NSError? let modelObjects = modelFactory.getArrivalsAndDeparturesForStopV2(fromJSON: json as! [AnyHashable: Any], error: &error) if let error = error { throw error } return modelObjects } } // MARK: - Trip Details @objc extension PromisedModelService { /// Trip details for the specified OBATripInstanceRef /// /// - Parameter tripInstance: The trip instance reference /// - Returns: A PromiseWrapper that resolves to an instance of OBATripDetailsV2 public func requestTripDetails(tripInstance: OBATripInstanceRef) -> PromiseWrapper { let request = self.buildTripDetailsRequest(tripInstance: tripInstance) let wrapper = PromiseWrapper.init(request: request) wrapper.promise = wrapper.promise.then { networkResponse -> NetworkResponse in let tripDetails = try self.decodeTripDetails(json: networkResponse.object as! [AnyHashable: Any]) return NetworkResponse.init(object: tripDetails, URLResponse: networkResponse.URLResponse, urlRequest: networkResponse.urlRequest) } return wrapper } @nonobjc private func decodeTripDetails(json: [AnyHashable: Any]) throws -> OBATripDetailsV2 { var error: NSError? let model = modelFactory.getTripDetailsV2(fromJSON: json, error: &error) if let error = error { throw error } let entry = model.entry as! OBATripDetailsV2 return entry } @nonobjc private func buildTripDetailsRequest(tripInstance: OBATripInstanceRef) -> OBAURLRequest { var args: [String: Any] = [:] if tripInstance.serviceDate > 0 { args["serviceDate"] = tripInstance.serviceDate } if tripInstance.vehicleId != nil { args["vehicleId"] = tripInstance.vehicleId } let escapedTripID = OBAURLHelpers.escapePathVariable(tripInstance.tripId) return obaJsonDataSource.buildGETRequest(withPath: "/api/where/trip-details/\(escapedTripID).json", queryParameters: args) } /// Returns a PromiseWrapper that resolves to an OBATripDetailsV2 object. /// /// - Parameter vehicleID: The vehicle for which to retrieve trip details. /// - Returns: a PromiseWrapper that resolves to trip details. public func requestVehicleTrip(_ vehicleID: String) -> PromiseWrapper { let request = buildTripForVehicleRequest(vehicleID) let wrapper = PromiseWrapper(request: request) wrapper.promise = wrapper.promise.then { response -> NetworkResponse in var error: NSError? // swiftlint:disable force_cast let entryWithRefs = self.modelFactory.getTripDetailsV2(fromJSON: response.object as! [AnyHashable: Any], error: &error) // swiftlint:enable force_cast if let error = error { throw error } // swiftlint:disable force_cast let tripDetails = entryWithRefs.entry as! OBATripDetailsV2 // swiftlint:enable force_cast return NetworkResponse.init(object: tripDetails, response: response) } return wrapper } private func buildTripForVehicleRequest(_ vehicleID: String) -> OBAURLRequest { let encodedID = OBAURLHelpers.escapePathVariable(vehicleID) let path = "/api/where/trip-for-vehicle/\(encodedID).json" return obaJsonDataSource.buildGETRequest(withPath: path, queryParameters: nil) } } // MARK: - Agencies with Coverage @objc extension PromisedModelService { public func requestAgenciesWithCoverage() -> PromiseWrapper { let request = buildRequest() let wrapper = PromiseWrapper.init(request: request) wrapper.promise = wrapper.promise.then { networkResponse -> NetworkResponse in // swiftlint:disable force_cast let agencies = try self.decodeData(json: networkResponse.object as! [AnyHashable: Any]) // swiftlint:enable force_cast return NetworkResponse.init(object: agencies, URLResponse: networkResponse.URLResponse, urlRequest: networkResponse.urlRequest) } return wrapper } @nonobjc private func buildRequest() -> OBAURLRequest { return obaJsonDataSource.buildGETRequest(withPath: "/api/where/agencies-with-coverage.json", queryParameters: nil) } @nonobjc private func decodeData(json: [AnyHashable: Any]) throws -> [OBAAgencyWithCoverageV2] { var error: NSError? let listWithRange = modelFactory.getAgenciesWithCoverageV2(fromJson: json, error: &error) if let error = error { throw error } // swiftlint:disable force_cast let entries = listWithRange.values as! [OBAAgencyWithCoverageV2] // swiftlint:enable force_cast return entries } } // MARK: - Regional Alerts extension PromisedModelService { public func requestRegionalAlerts() -> Promise<[AgencyAlert]> { return requestAgenciesWithCoverage().promise.then { networkResponse -> Promise<[AgencyAlert]> in // swiftlint:disable force_cast let agencies = networkResponse.object as! [OBAAgencyWithCoverageV2] // swiftlint:enable force_cast var requests = agencies.map { self.buildRequest(agency: $0) } let obacoRequest = self.buildObacoRequest(region: self.modelDAO.currentRegion!) requests.append(obacoRequest) let promises = requests.map { request -> Promise<[TransitRealtime_FeedEntity]> in return CancellablePromise.go(request: request).then { networkResponse -> Promise<[TransitRealtime_FeedEntity]> in // swiftlint:disable force_cast let data = networkResponse.object as! Data // swiftlint:enable force_cast let message = try TransitRealtime_FeedMessage(serializedData: data) return Promise(value: message.entity) } } return when(fulfilled: promises).then { nestedEntities in let allAlerts: [AgencyAlert] = nestedEntities.reduce(into: [], { (acc, entities) in let alerts = entities.filter { (entity) -> Bool in return entity.hasAlert && AgencyAlert.isAgencyWideAlert(alert: entity.alert) }.compactMap { try? AgencyAlert(feedEntity: $0, agencies: agencies) } acc.append(contentsOf: alerts) }) return Promise(value: allAlerts) } } } private func buildObacoRequest(region: OBARegionV2) -> OBAURLRequest { var params: [String: Any]? if OBAApplication.shared().userDefaults.bool(forKey: OBAShowTestAlertsDefaultsKey) { params = ["test": "1"] } let url = obacoJsonDataSource.constructURL(fromPath: "/api/v1/regions/\(region.identifier)/alerts.pb", params: params) let obacoRequest = OBAURLRequest.init(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10) return obacoRequest } private func buildRequest(agency: OBAAgencyWithCoverageV2) -> OBAURLRequest { let encodedID = OBAURLHelpers.escapePathVariable(agency.agencyId) let path = "/api/gtfs_realtime/alerts-for-agency/\(encodedID).pb" return unparsedDataSource.buildGETRequest(withPath: path, queryParameters: nil) } }
apache-2.0
a11d8de3905e9bac0b2f5a759b3445dc
42.649038
148
0.677387
4.889068
false
false
false
false
anas10/Monumap
Monumap/ViewControllers/SearchViewController.swift
1
5586
// // SearchViewController.swift // Monumap // // Created by Anas Ait Ali on 12/03/2017. // Copyright © 2017 Anas Ait Ali. All rights reserved. // import UIKit import RxSwift class SearchViewController: UIViewController { @IBOutlet weak var tableViewResults: UITableView! @IBOutlet weak var searchBar: UISearchBar! var viewModel: SearchViewModelType! var viewModelConstructor: SearchViewModelConstructorType! var shownData : Variable<[Monument]> = Variable([]) private var disposeBag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() viewModel = viewModelConstructor(self) self.shownData.value = viewModel.dataManager.monuments.value self.shownData .asObservable() .bind(to: tableViewResults.rx.items)(cellFactory) .disposed(by: disposeBag) self.searchBar .rx.text .orEmpty .debounce(0.2, scheduler: MainScheduler.instance) .distinctUntilChanged() .filter { if !$0.isEmpty { return true } else { self.shownData.value = self.viewModel.dataManager.monuments.value return false } } .subscribe(onNext: { query in let q = query.cleanForSearch() self.shownData.value = self.viewModel .dataManager .monuments .value .filter { $0.site.cleanForSearch().index(of: q) != nil || $0.states?.cleanForSearch().index(of: q) != nil } }) .disposed(by: disposeBag) } func cellFactory(_ tableView: UITableView, i: Int, monument: Monument) -> UITableViewCell { let cellIdentifier = "MonumentDefaultCell" let currentCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: IndexPath(item: i, section: 0)) as! MonumentTableViewCell currentCell.configure(monument: monument) return currentCell } } extension String { func cleanForSearch() -> String { return self .folding(options: [.diacriticInsensitive, .widthInsensitive, .caseInsensitive], locale: nil) .removeCharacters(from: " -_/\\'") } func removeCharacters(from forbiddenChars: CharacterSet) -> String { let passed = self.unicodeScalars.filter { !forbiddenChars.contains($0) } return String(String.UnicodeScalarView(passed)) } func removeCharacters(from: String) -> String { return removeCharacters(from: CharacterSet(charactersIn: from)) } } extension String { func index(of pattern: String) -> Index? { // Cache the length of the search pattern because we're going to // use it a few times and it's expensive to calculate. let patternLength = pattern.count guard patternLength > 0, patternLength <= self.count else { return nil } // Make the skip table. This table determines how far we skip ahead // when a character from the pattern is found. var skipTable = [Character: Int]() for (i, c) in pattern.enumerated() { skipTable[c] = patternLength - i - 1 } // This points at the last character in the pattern. let p = pattern.index(before: pattern.endIndex) let lastChar = pattern[p] // The pattern is scanned right-to-left, so skip ahead in the string by // the length of the pattern. (Minus 1 because startIndex already points // at the first character in the source string.) var i = index(startIndex, offsetBy: patternLength - 1) // This is a helper function that steps backwards through both strings // until we find a character that doesn’t match, or until we’ve reached // the beginning of the pattern. func backwards() -> Index? { var q = p var j = i while q > pattern.startIndex { j = index(before: j) q = index(before: q) if self[j] != pattern[q] { return nil } } return j } // The main loop. Keep going until the end of the string is reached. while i < endIndex { let c = self[i] // Does the current character match the last character from the pattern? if c == lastChar { // There is a possible match. Do a brute-force search backwards. if let k = backwards() { return k } // Ensure to jump at least one character (this is needed because the first // character is in the skipTable, and `skipTable[lastChar] = 0`) let jumpOffset = max(skipTable[c] ?? patternLength, 1) i = index(i, offsetBy: jumpOffset, limitedBy: endIndex) ?? endIndex } else { // The characters are not equal, so skip ahead. The amount to skip is // determined by the skip table. If the character is not present in the // pattern, we can skip ahead by the full pattern length. However, if // the character *is* present in the pattern, there may be a match up // ahead and we can't skip as far. i = index(i, offsetBy: skipTable[c] ?? patternLength, limitedBy: endIndex) ?? endIndex } } return nil } }
apache-2.0
464fca024ff880ad8ef85103b71fc0e2
35.24026
150
0.583587
4.891323
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/EmptyChatViewController.swift
1
8879
// // EmptyChatViewController.swift // Telegram-Mac // // Created by keepcoder on 13/10/2016. // Copyright © 2016 Telegram. All rights reserved. // import Cocoa import TGUIKit import TelegramCore import SwiftSignalKit class EmptyChatView : View { private let containerView: View = View() private let label:TextView = TextView() private let imageView:ImageView = ImageView() let toggleTips: ImageButton = ImageButton() private var cards: NSView? func toggleTips(_ isEnabled: Bool, animated: Bool, view: NSView) { if isEnabled { addSubview(view) self.cards = view view.frame = NSMakeRect(0, 0, frame.width, 370) view.center() if animated { view.layer?.animateAlpha(from: 0, to: 1, duration: 0.3, timingFunction: .spring) view.layer?.animateScaleSpring(from: 0.1, to: 1, duration: 0.3) } } else { performSubviewRemoval(view, animated: animated, duration: 0.3, timingFunction: .spring, checkCompletion: true) if animated { view.layer?.animateScaleSpring(from: 1, to: 0.1, duration: 0.3, bounce: false) } self.cards = nil } containerView.change(opacity: isEnabled ? 0 : 1, animated: animated) toggleTips.set(image: isEnabled ? theme.empty_chat_hidetips : theme.empty_chat_showtips, for: .Normal) } required init(frame frameRect: NSRect) { super.init(frame: frameRect) self.layer = CAGradientLayer() self.layer?.disableActions() toggleTips.set(image: theme.empty_chat_showtips, for: .Normal) toggleTips.setFrameSize(NSMakeSize(30, 30)) toggleTips.set(background: .clear, for: .Normal) toggleTips.blurBackground = theme.chatServiceItemColor toggleTips.autohighlight = false toggleTips.scaleOnClick = true toggleTips.layer?.cornerRadius = 15 addSubview(containerView) containerView.addSubview(imageView) containerView.addSubview(label) addSubview(toggleTips) label.userInteractionEnabled = false label.isSelectable = false updateLocalizationAndTheme(theme: theme) } override func updateLocalizationAndTheme(theme: PresentationTheme) { super.updateLocalizationAndTheme(theme: theme) let theme = (theme as! TelegramPresentationTheme) imageView.image = theme.icons.chatEmpty switch theme.controllerBackgroundMode { case .plain: imageView.isHidden = false default: imageView.isHidden = true } toggleTips.set(image: cards != nil ? theme.empty_chat_hidetips : theme.empty_chat_showtips, for: .Normal) if theme.shouldBlurService { toggleTips.set(background: .clear, for: .Normal) toggleTips.blurBackground = theme.chatServiceItemColor } else { toggleTips.set(background: theme.chatServiceItemColor, for: .Normal) toggleTips.blurBackground = nil } imageView.sizeToFit() label.disableBackgroundDrawing = true if imageView.isHidden && theme.bubbled { label.blurBackground = theme.chatServiceItemColor } else { label.blurBackground = nil label.backgroundColor = theme.chatBackground } label.update(TextViewLayout(.initialize(string: strings().emptyPeerDescription, color: imageView.isHidden ? theme.chatServiceItemTextColor : theme.colors.grayText, font: .medium(imageView.isHidden ? .text : .header)), maximumNumberOfLines: 1, alignment: .center)) needsLayout = true } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layout() { super.layout() label.textLayout?.measure(width: frame.size.width - 20) label.update(label.textLayout) cards?.frame = NSMakeRect(0, 0, frame.width, 370) cards?.center() if imageView.isHidden { label.setFrameSize(label.frame.width + 16, label.frame.height + 6) containerView.setFrameSize(label.frame.width + 20, 24) containerView.center() label.center() label.layer?.cornerRadius = label.frame.height / 2 containerView.layer?.cornerRadius = containerView.frame.height / 2 } else { containerView.setFrameSize(max(imageView.frame.width, label.frame.width) + 40, imageView.frame.size.height + label.frame.size.height + 70) imageView.centerX(y: 20) containerView.center() label.centerX(y: imageView.frame.maxY + 30) containerView.layer?.cornerRadius = 0 } toggleTips.setFrameOrigin(NSMakePoint(frame.width - toggleTips.frame.width - 10, 10)) } } class EmptyChatViewController: TelegramGenericViewController<EmptyChatView> { private let cards: WidgetController override init(_ context: AccountContext) { cards = WidgetController(context) super.init(context) self.bar = NavigationBarStyle(height:0) } private var temporaryTouchBar: Any? @available(OSX 10.12.2, *) override func makeTouchBar() -> NSTouchBar? { if temporaryTouchBar == nil { temporaryTouchBar = ChatListTouchBar(context: self.context, search: { [weak self] in self?.context.bindings.globalSearch("") }, newGroup: { [weak self] in self?.context.composeCreateGroup() }, newSecretChat: { [weak self] in self?.context.composeCreateSecretChat() }, newChannel: { [weak self] in self?.context.composeCreateChannel() }) } return temporaryTouchBar as? NSTouchBar } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) (navigationController as? MajorNavigationController)?.closeSidebar() } override func escapeKeyAction() -> KeyHandlerResult { return .rejected } override func updateLocalizationAndTheme(theme: PresentationTheme) { super.updateLocalizationAndTheme(theme: theme) let theme = (theme as! TelegramPresentationTheme) updateBackgroundColor(theme.controllerBackgroundMode) } override func updateBackgroundColor(_ backgroundMode: TableBackgroundMode) { super.updateBackgroundColor(backgroundMode) var containerBg = self.backgroundColor if theme.bubbled { switch theme.backgroundMode { case .background, .tiled, .gradient: containerBg = .clear case .plain: if theme.colors.chatBackground == theme.colors.background { containerBg = theme.colors.border } else { containerBg = .clear } case let .color(color): if color == theme.colors.background { containerBg = theme.colors.border } else { containerBg = .clear } } } else { if theme.colors.chatBackground == theme.colors.background { containerBg = theme.colors.border } else { containerBg = .clear } } self.backgroundColor = containerBg } override public var isOpaque: Bool { return false } override var responderPriority: HandlerPriority { return .medium } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) context.globalPeerHandler.set(.single(nil)) } override func backKeyAction() -> KeyHandlerResult { return cards.backKeyAction() } override func nextKeyAction() -> KeyHandlerResult { return cards.nextKeyAction() } private let disposable = MetaDisposable() deinit { disposable.dispose() } override func viewDidLoad() { super.viewDidLoad() // readyOnce() self.ready.set(cards.ready.get()) self.genericView.toggleTips(FastSettings.emptyTips, animated: false, view: cards.view) self.genericView.toggleTips.set(handler: { [weak self] _ in guard let cards = self?.cards.view else { return } FastSettings.updateEmptyTips(!FastSettings.emptyTips) self?.genericView.toggleTips(FastSettings.emptyTips, animated: true, view: cards) }, for: .Click) } }
gpl-2.0
a1975a8d4edbfe691ca18efbc3143662
33.679688
271
0.607119
5.044318
false
false
false
false
q231950/road-to-bishkek
Bish/WeatherProvider.swift
1
1160
// // WeatherProvider.swift // Bish // // Created by Martin Kim Dung-Pham on 27.05.17. // Copyright © 2017 elbedev.com. All rights reserved. // import Foundation class WeatherProvider { public func weather(in city:City, completion: @escaping ((WeatherViewModel?, Error?) -> Swift.Void)) { if let url = URL(string: "https://api.apixu.com/v1/current.json?key=\(ApiKey.weather.rawValue)&q=\(city.location.coordinate.latitude),\(city.location.coordinate.longitude)") { let dataTask = URLSession.shared.dataTask(with: url, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) in if let data = data { do { let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) let viewModel = WeatherViewModel(json:json) completion(viewModel, nil) } catch let error { completion(nil, error) } } }) dataTask.resume() } } }
mit
5efaa351eff6dd176f0450381ea4c441
34.121212
183
0.537532
4.673387
false
false
false
false
ReactiveCocoa/ReactiveSwift
Sources/FoundationExtensions.swift
1
4875
// // FoundationExtensions.swift // ReactiveSwift // // Created by Justin Spahr-Summers on 2014-10-19. // Copyright (c) 2014 GitHub. All rights reserved. // import Foundation #if canImport(FoundationNetworking) import FoundationNetworking #endif import Dispatch #if os(Linux) import let CDispatch.NSEC_PER_USEC import let CDispatch.NSEC_PER_SEC #endif extension NotificationCenter: ReactiveExtensionsProvider {} extension Reactive where Base: NotificationCenter { /// Returns a Signal to observe posting of the specified notification. /// /// - parameters: /// - name: name of the notification to observe /// - object: an instance which sends the notifications /// /// - returns: A Signal of notifications posted that match the given criteria. /// /// - note: The signal does not terminate naturally. Observers must be /// explicitly disposed to avoid leaks. public func notifications(forName name: Notification.Name?, object: AnyObject? = nil) -> Signal<Notification, Never> { return Signal { [base = self.base] observer, lifetime in let notificationObserver = base.addObserver(forName: name, object: object, queue: nil) { notification in observer.send(value: notification) } lifetime.observeEnded { base.removeObserver(notificationObserver) } } } } private let defaultSessionError = NSError(domain: "org.reactivecocoa.ReactiveSwift.Reactivity.URLSession.dataWithRequest", code: 1, userInfo: nil) extension URLSession: ReactiveExtensionsProvider {} extension Reactive where Base: URLSession { /// Returns a SignalProducer which performs the work associated with an /// `NSURLSession` /// /// - parameters: /// - request: A request that will be performed when the producer is /// started /// /// - returns: A producer that will execute the given request once for each /// invocation of `start()`. /// /// - note: This method will not send an error event in the case of a server /// side error (i.e. when a response with status code other than /// 200...299 is received). public func data(with request: URLRequest) -> SignalProducer<(Data, URLResponse), Error> { return SignalProducer { [base = self.base] observer, lifetime in let task = base.dataTask(with: request) { data, response, error in if let data = data, let response = response { observer.send(value: (data, response)) observer.sendCompleted() } else { observer.send(error: error ?? defaultSessionError) } } lifetime.observeEnded(task.cancel) task.resume() } } } extension Date { internal func addingTimeInterval(_ interval: DispatchTimeInterval) -> Date { return addingTimeInterval(interval.timeInterval) } } extension DispatchTimeInterval { internal var timeInterval: TimeInterval { switch self { case let .seconds(s): return TimeInterval(s) case let .milliseconds(ms): return TimeInterval(TimeInterval(ms) / 1000.0) case let .microseconds(us): return TimeInterval(Int64(us)) * TimeInterval(NSEC_PER_USEC) / TimeInterval(NSEC_PER_SEC) case let .nanoseconds(ns): return TimeInterval(ns) / TimeInterval(NSEC_PER_SEC) case .never: return .infinity @unknown default: return .infinity } } // This was added purely so that our test scheduler to "go backwards" in // time. See `TestScheduler.rewind(by interval: DispatchTimeInterval)`. internal static prefix func -(lhs: DispatchTimeInterval) -> DispatchTimeInterval { switch lhs { case let .seconds(s): return .seconds(-s) case let .milliseconds(ms): return .milliseconds(-ms) case let .microseconds(us): return .microseconds(-us) case let .nanoseconds(ns): return .nanoseconds(-ns) case .never: return .never @unknown default: return .never } } /// Scales a time interval by the given scalar specified in `rhs`. /// /// - returns: Scaled interval in minimal appropriate unit internal static func *(lhs: DispatchTimeInterval, rhs: Double) -> DispatchTimeInterval { let seconds = lhs.timeInterval * rhs var result: DispatchTimeInterval = .never if let integerTimeInterval = Int(exactly: (seconds * 1000 * 1000 * 1000).rounded()) { result = .nanoseconds(integerTimeInterval) } else if let integerTimeInterval = Int(exactly: (seconds * 1000 * 1000).rounded()) { result = .microseconds(integerTimeInterval) } else if let integerTimeInterval = Int(exactly: (seconds * 1000).rounded()) { result = .milliseconds(integerTimeInterval) } else if let integerTimeInterval = Int(exactly: (seconds).rounded()) { result = .seconds(integerTimeInterval) } return result } } extension TimeInterval { internal var dispatchTimeInterval: DispatchTimeInterval { .nanoseconds(Int(self * TimeInterval(NSEC_PER_SEC))) } }
mit
57a34ba0109c7fcbe8dfba9690d971c1
31.5
122
0.701333
4.012346
false
false
false
false
dusanIntellex/backend-operation-layer
Example/BackendServiceAdapter/BackendLayerAdapter/BackendOperationHandleSuccess.swift
1
1614
// // BackendOperationHandleSuccess.swift // BackendServiceAdapter_Example // // Created by Apple on 3/11/19. // Copyright © 2019 CocoaPods. All rights reserved. // import Foundation import BackendServiceAdapter extension BackendOperation{ //MARK:- Custom handler response @objc func customHandleResponseData(data: Any?, statusCode: NSInteger){ if self.onSuccess != nil{ if 200 ... 299 ~= statusCode{ self.onSuccess!(data, statusCode) } else{ self.onFailure?(ResponseError.unknownError, statusCode) } } self.finish() } //MARK:- Refresh token private func refreshToken(){ // TODO: You can add this funciton on any status code and recall previous request if everything is ok } //MARK:- Siwzzle method // Init swizzling public static func swizzleHandleSuccess(){ _ = self.swizzleHandleSuccessOperation } private static let swizzleHandleSuccessOperation : Void = { let originalSelector = #selector(handleData(data:statusCode:)) let swizzleSelector = #selector(customHandleResponseData(data:statusCode:)) let originalMethod = class_getInstanceMethod(BackendOperation.self, originalSelector) let swizzleMethod = class_getInstanceMethod(BackendOperation.self, swizzleSelector) if let originalMethod = originalMethod, let swizzledMethod = swizzleMethod { method_exchangeImplementations(originalMethod, swizzledMethod) } }() }
mit
8ded794d4eda06a8817456e008a31636
30.019231
109
0.649721
5.305921
false
false
false
false
daher-alfawares/model
Model/Model/Notifier.swift
1
1501
// // ModelNotifier.swift // Model // // Created by Brandon Chow on 5/13/16. // Copyright © 2016 Brandon Chow, 2016 Daher Alfawares. All rights reserved. // import Foundation public class Notifier { static let sharedInstance = Notifier() private var listenerGroups = [String : WeakRef<ListenerGroup>]() public func notify(newModel model: Model) { listenerGroups[model.key()]?.reference?.notify(newModel: model) } internal func addListener(listener: Listener, forModelType modelType: Model.Type){ let modelTypeKey = "\(modelType)" let group = groupFor(modelTypeKey) group.add(listener) listener.group = group } private func groupFor(modelTypeKey: String) -> ListenerGroup { if let group = listenerGroups[modelTypeKey]?.reference { return group } else { let group = ListenerGroup(key: modelTypeKey) listenerGroups[modelTypeKey] = WeakRef<ListenerGroup>(ref: group) return group } } private func addListenerToNewGroup(newListener: Listener, forModelTypeKey modelTypeKey: String){ let group = ListenerGroup(key: modelTypeKey) newListener.group = group listenerGroups[modelTypeKey] = WeakRef<ListenerGroup>(ref: group) group.add(newListener) } internal func remove(listenerGroup : ListenerGroup) { listenerGroups.removeValueForKey(listenerGroup.key) } }
apache-2.0
048f4f0484abfcfd341988c02f59096c
29
100
0.653333
4.731861
false
false
false
false
CoderST/XMLYDemo
XMLYDemo/XMLYDemo/Class/Home/Controller/SubViewController/PopularViewController/Controller/PopularViewController.swift
1
9144
// // PopularViewController.swift // XMLYDemo // // Created by xiudou on 2016/12/21. // Copyright © 2016年 CoderST. All rights reserved. // 热门 import UIKit /// 头部 private let reuseIdentifier = "reuseIdentifier" /// 猜你喜欢 private let GuessYouLikeCellIdentifier = "GuessYouLikeCellIdentifier" /// 普通 private let normalCellIdentifier = "normalCellIdentifier" /// 现场直播 private let nowLiveCellIdentifier = "nowLiveCellIdentifier" /// 推广 private let promotionCellIdentifier = "promotionCellIdentifier" /// 精品听单 private let fineListenCellIdentifier = "fineListenCellIdentifier" class PopularViewController: UIViewController { // MARK:- 变量 var collectionView : UICollectionView! // MARK:- 懒加载 fileprivate lazy var popularViewModel : PopularViewModel = PopularViewModel() // 轮播图的view fileprivate lazy var rotationMapView : RotationMapView = { let rotationMapView = RotationMapView() rotationMapView.frame = CGRect(x: 0, y: -(sRotationMapViewHeight + sRecommendHeight), width: stScreenW, height: sRotationMapViewHeight) return rotationMapView }() // 推荐的view fileprivate lazy var recommendView : RecommendView = RecommendView() // ReusableView fileprivate lazy var reusableView : PopularReusableView = PopularReusableView() // MARK:- 生命周期 override func viewDidLoad() { super.viewDidLoad() // 1 设置UI setupUI() // 2 网络请求 // getPopularData() } } // MARK:- 设置UI extension PopularViewController { fileprivate func setupUI() { setupCollectionView() setupRotationMapView() setupRecommendView() // 设置collectionView的内边距 collectionView.contentInset = UIEdgeInsets(top: sRotationMapViewHeight + sRecommendHeight, left: 0, bottom: 0, right: 0) } fileprivate func setupCollectionView() { // 设置layout属性 let layout = UICollectionViewFlowLayout() layout.headerReferenceSize = CGSize(width: stScreenW, height: sHeaderReferenceHeight) layout.minimumInteritemSpacing = sMargin layout.minimumLineSpacing = sMargin layout.sectionInset = UIEdgeInsets(top: sMargin, left: sMargin, bottom: sMargin, right: sMargin) // 创建UICollectionView collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: stScreenH - 64 - 44 - 49), collectionViewLayout: layout) // 设置数据源 collectionView.dataSource = self collectionView.delegate = self collectionView.backgroundColor = UIColor(r: 245, g: 245, b: 245) // 注册PopularReusableView collectionView.register(PopularReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: reuseIdentifier) // 注册猜你喜欢cell collectionView.register(GuessYouLikeCell.self, forCellWithReuseIdentifier: GuessYouLikeCellIdentifier) // 注册精品,小编推荐类似的cell(普通的cell) collectionView.register(NormalCell.self, forCellWithReuseIdentifier: normalCellIdentifier) // 注册现场直播 collectionView.register(NowLiveCell.self, forCellWithReuseIdentifier: nowLiveCellIdentifier) // 精品听单 FineListenCell collectionView.register(FineListenCell.self, forCellWithReuseIdentifier: fineListenCellIdentifier) // 注册推广 PromotionCell collectionView.register(PromotionCell.self, forCellWithReuseIdentifier: promotionCellIdentifier) view.addSubview(collectionView) // 设置刷新 let refresh = STRefreshHeader(refreshingTarget: self, refreshingAction: #selector(refreshHeaderAction)) collectionView.mj_header = refresh refresh!.ignoredScrollViewContentInsetTop = sRotationMapViewHeight + sRecommendHeight collectionView.mj_header.beginRefreshing() } fileprivate func setupRotationMapView() { collectionView.addSubview(rotationMapView) } fileprivate func setupRecommendView() { collectionView.addSubview(recommendView) recommendView.frame = CGRect(x: 0, y: -sRecommendHeight, width: stScreenW, height: sRecommendHeight) } } // MARK:- 获取网络数据 extension PopularViewController { func getPopularData() { popularViewModel.getData { // self.rotationMapView.focusImagesItems = self.popularViewModel.rotationMapModels // self.recommendView.discoveryColumns = self.popularViewModel.discoveryColumnsSubItem self.collectionView.reloadData() self.collectionView.mj_header.endRefreshing() } } } // MARK:- 刷新相关 extension PopularViewController { func refreshHeaderAction() { getPopularData() } } extension PopularViewController : UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int{ return popularViewModel.popularModels.count } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return popularViewModel.popularModels[section].list.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let model = popularViewModel.popularModels[indexPath.section] if model.title == "猜你喜欢"{ // 猜你喜欢 let guessYouLikeCell = collectionView.dequeueReusableCell(withReuseIdentifier: GuessYouLikeCellIdentifier, for: indexPath) as! GuessYouLikeCell guessYouLikeCell.guessItem = popularViewModel.caiNiXiHuanModels.first?.list[indexPath.item] return guessYouLikeCell }else if model.title == "精品听单"{ // 精品听单 let fineListenCell = collectionView.dequeueReusableCell(withReuseIdentifier: fineListenCellIdentifier, for: indexPath) as! FineListenCell fineListenCell.fineListenSubItem = popularViewModel.jingPingTingDanModels.first?.list[indexPath.item] return fineListenCell }else if model.title == "现场直播"{ // 现场直播 let nowLiveCell = collectionView.dequeueReusableCell(withReuseIdentifier: nowLiveCellIdentifier, for: indexPath) as! NowLiveCell nowLiveCell.nowLiveSubItem = popularViewModel.xianChagnZhiBoModels.first?.list return nowLiveCell }else if (model.title == "推广"){ // 推广 let promotionCell = collectionView.dequeueReusableCell(withReuseIdentifier: promotionCellIdentifier, for: indexPath) as! PromotionCell promotionCell.promotionSubItem = popularViewModel.popularModels[indexPath.section].list.first return promotionCell }else{ let normalCell = collectionView.dequeueReusableCell(withReuseIdentifier: normalCellIdentifier, for: indexPath) as! NormalCell if indexPath.section == 2 { normalCell.hotRecommendsSubItem = popularViewModel.popularModels[indexPath.section].list[indexPath.item] return normalCell }else{ normalCell.hotRecommendsSubItem = popularViewModel.popularModels[indexPath.section].list[indexPath.item] return normalCell } } } } extension PopularViewController : UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize { let model = popularViewModel.popularModels[indexPath.section] if model.title == "猜你喜欢"{ // 猜你喜欢 return CGSize(width: sItemWidth, height: sGuessYouLikeItemHeight) }else if model.title == "精品听单"{ // 精品听单 return CGSize(width: stScreenW, height: sTingDanItemHeight) }else if model.title == "推广"{ // 推广 return CGSize(width: stScreenW, height: sNormalItemHeight) }else if model.title == "现场直播"{ // 现场直播 return CGSize(width: stScreenW, height: sNormalItemHeight) } else{ return CGSize(width: sItemWidth, height: sNormalItemHeight) } } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { // 1.取出section的HeaderView let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: reuseIdentifier, for: indexPath) as!PopularReusableView headerView.title = popularViewModel.popularModels[indexPath.section].title return headerView } }
mit
db31b6c3604ca500f86844f7732ef0b0
39.74537
169
0.688672
5.559697
false
false
false
false
paoloq/LWTableViewCell
Example/LWTableViewCell/ViewController.swift
1
3340
// // ViewController.swift // LWTableViewCell // // Created by Paolo Arduin on 08/06/2017. // Copyright (c) 2017 Paolo Arduin. All rights reserved. // import UIKit class ViewController: UIViewController { lazy var tableView: UITableView = { let tableView = UITableView.init(frame: CGRect.zero, style: .plain) tableView.separatorStyle = .none tableView.backgroundColor = .white tableView.tableFooterView = UIView() tableView.dataSource = self tableView.delegate = self tableView.register(ExampleCell.self, forCellReuseIdentifier: ExampleCell.identifier) return tableView }() fileprivate var elements: [ExampleElement] = [] // MARK: - override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = .white let statusBarHeight = UIApplication.shared.statusBarFrame.height self.tableView.frame = self.view.bounds self.tableView.frame.origin.y += statusBarHeight self.tableView.frame.size.height -= statusBarHeight self.view.addSubview(self.tableView) self.popolate() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - fileprivate func popolate() { if let url = Bundle.main.url(forResource: "icon-names", withExtension: nil) { let dataString = try! String.init(contentsOf: url, encoding: .utf8) let imageNames = dataString.components(separatedBy: "\n") imageNames.forEach { if let image = UIImage.init(named: $0) { let title = $0.replacingOccurrences(of: "icon-", with: "") let element = ExampleElement.init(image: image, title: title) self.elements.append(element) } } self.tableView.reloadData() } } } // MARK: - UITableViewDataSource extension ViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.elements.count } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return tableView.dequeueReusableCell(withIdentifier: ExampleCell.identifier, for: indexPath) } } // MARK: - UITableViewDelegate extension ViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return ExampleCell.estimatedHeight() } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { if let exampleCell = cell as? ExampleCell { exampleCell.element = self.elements[indexPath.row] } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } }
mit
a7757f529f043cfba37b45074bbf5539
30.509434
112
0.612275
5.335463
false
false
false
false
tompiking/shop_ke
shop_ke/ActivityViewController.swift
1
7454
// // ActivityViewController.swift // shop_ke // // Created by mac on 16/2/29. // Copyright © 2016年 peraytech. All rights reserved. // import UIKit import Alamofire class ActivityViewController: UIViewController,UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate { @IBOutlet weak var bannerSv: UIScrollView! @IBOutlet weak var pageControl: UIPageControl! @IBOutlet weak var activityTableView: UITableView! var activities:[Activity] = [] //获取到的定时跳转的图片数据形成一个数组 var showBannerActivities:[Activity] = [] //从数据中取出三个形成一个固定的数组 var bannerTime:NSTimer? = nil var shops = [ActivityShop]() //商店数据 override func viewDidLoad() { super.viewDidLoad() self.tabBarController?.tabBar.tintColor = UIColor.redColor() activityTableView.registerNib(UINib(nibName: "ActivityTableViewCell", bundle: nil), forCellReuseIdentifier: "cell") // Do any additional setup after loading the view. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) bannerTime = NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: #selector(ActivityViewController.loopBannerImage), userInfo: nil, repeats: true) loadData() } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) bannerTime?.invalidate() bannerTime = nil; } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //当scrollcView的contentOffset发生变化时候开始调用 func scrollViewDidScroll(scrollView: UIScrollView) { if scrollView != self.bannerSv{ return } let x = scrollView.contentOffset.x; let currentPage = self.pageControl.currentPage //下一张 if (x >= 2 * scrollView.frame.size.width) { if(currentPage==self.activities.count-1){ self.pageControl.currentPage = 0; }else{ self.pageControl.currentPage += 1 } self.refreshBannerDatas() } //上一张 if (x <= 0) { if(currentPage==0){ self.pageControl.currentPage = self.activities.count-1; }else{ self.pageControl.currentPage -= 1 } self.refreshBannerDatas() } } //加载数据 func loadData() { var params = [String : AnyObject]() params["client_type"] = "iphone" params["num"] = "4" params["pa"] = "pa" HttpManager.httpGetRequest(.GET, api_url: API_URL+"/brand_theme_index", params: params, onSuccess: { (successData) -> Void in self.activities = Activity.saveDataToModel(successData) self.loadBanner() self.shops = ActivityShop.getActivityShop(successData) //存商品数据 self.activityTableView.reloadData() //渲染表格 }) { (failData) -> Void in print(failData) } } //第一次加载banner数据 func loadBanner() { //将scrollView里的所有组件移除 for image in self.bannerSv.subviews{ image.removeFromSuperview() } self.pageControl.numberOfPages = self.activities.count //设置page的总数量 self.bannerSv.contentSize = CGSizeMake(self.bannerSv.frame.width*CGFloat(self.activities.count), self.bannerSv.frame.height)//设置scrollView滚动区域的大小 self.changeBunnerShowDatas() for (pic_index,activity) in self.showBannerActivities.enumerate(){ let image = UIImageView.init(frame: CGRectMake(self.bannerSv.frame.width*CGFloat(pic_index), 0, self.bannerSv.frame.width, self.bannerSv.frame.height)) if let activityImageUrl = activity.image_path { image.setWebImage(activityImageUrl , placeHolder: UIImage.init(named: "w_icon")) } self.bannerSv.addSubview(image) } print(bannerSv.subviews.count) self.bannerSv.setContentOffset(CGPointMake(self.bannerSv.frame.size.width, 0), animated: false) //判断定时器是否释放 if ((bannerTime) != nil) { bannerTime!.invalidate() bannerTime = nil } bannerTime = NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: #selector(ActivityViewController.loopBannerImage), userInfo: nil, repeats: true) } //bunner滚动定时器 func loopBannerImage() { UIView.animateWithDuration(0.5, animations: { () -> Void in self.bannerSv.setContentOffset(CGPointMake(self.bannerSv.frame.size.width*CGFloat(2), 0), animated: true) }) { (result) -> Void in print("buner定时滚动:\(result)") } } //滚动到scrollView的端点后刷新bunner func refreshBannerDatas() { self.changeBunnerShowDatas() var scrollImages = self.bannerSv.subviews as! [UIImageView] for (index,activity) in self.showBannerActivities.enumerate() { if let activityImageUrl = activity.image_path { scrollImages[index].setWebImage(activityImageUrl , placeHolder: UIImage.init(named: "w_icon")) } } self.bannerSv.setContentOffset(CGPointMake(self.bannerSv.frame.size.width,0), animated: false) } //根据当前的page改变要显示的bunner数据 func changeBunnerShowDatas() { let currentPage = self.pageControl.currentPage switch currentPage{ case 0: self.setShowActivities(self.activities.count-1, currentIndex: currentPage, lastIndex: currentPage+1) case self.activities.count-1: self.setShowActivities(currentPage-1, currentIndex: currentPage, lastIndex: 0) default: self.setShowActivities(currentPage-1, currentIndex: currentPage, lastIndex: currentPage+1) } } //重置bunner显示的活动数组 func setShowActivities(firstIndex:Int,currentIndex:Int,lastIndex:Int) { print(self.activities.count) self.showBannerActivities.removeAll() self.showBannerActivities.append(self.activities[firstIndex]) self.showBannerActivities.append(self.activities[currentIndex]) self.showBannerActivities.append(self.activities[lastIndex]) } //设置cell的行数 func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return shops.count } //设置cell的内容 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! ActivityTableViewCell let image = UIImage(named: "zpzk") let shop = shops[indexPath.row] cell.shopImage.setWebImage(shop.image_url, placeHolder: image) cell.shopDiscount.text = String(shop.discount)+"折起" cell.shopName.text = shop.name return cell } //cell行高 func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 170 } }
apache-2.0
5f83288c78646f55e58d4f4199e8a912
37.912568
167
0.64373
4.681788
false
false
false
false
eure/ReceptionApp
iOS/Pods/CoreStore/CoreStore/Saving and Processing/UnsafeDataTransaction.swift
1
5940
// // UnsafeDataTransaction.swift // CoreStore // // Copyright © 2015 John Rommel Estropia // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation import CoreData #if USE_FRAMEWORKS import GCDKit #endif @available(*, deprecated=1.3.1, renamed="UnsafeDataTransaction") public typealias DetachedDataTransaction = UnsafeDataTransaction // MARK: - UnsafeDataTransaction /** The `UnsafeDataTransaction` provides an interface for non-contiguous `NSManagedObject` creates, updates, and deletes. This is useful for making temporary changes, such as partially filled forms. An unsafe transaction object should typically be only used from the main queue. */ public final class UnsafeDataTransaction: BaseDataTransaction { /** Saves the transaction changes asynchronously. For a `UnsafeDataTransaction`, multiple commits are allowed, although it is the developer's responsibility to ensure a reasonable leeway to prevent blocking the main thread. - parameter completion: the block executed after the save completes. Success or failure is reported by the `SaveResult` argument of the block. */ public func commit(completion: (result: SaveResult) -> Void) { self.context.saveAsynchronouslyWithCompletion { (result) -> Void in self.result = result completion(result: result) } } /** Saves the transaction changes and waits for completion synchronously. For a `UnsafeDataTransaction`, multiple commits are allowed, although it is the developer's responsibility to ensure a reasonable leeway to prevent blocking the main thread. - returns: a `SaveResult` containing the success or failure information */ public func commitAndWait() -> SaveResult { let result = self.context.saveSynchronously() self.result = result return result } /** Rolls back the transaction. */ public func rollback() { CoreStore.assert( self.supportsUndo, "Attempted to rollback a \(typeName(self)) with Undo support disabled." ) self.context.rollback() } /** Undo's the last change made to the transaction. */ public func undo() { CoreStore.assert( self.supportsUndo, "Attempted to undo a \(typeName(self)) with Undo support disabled." ) self.context.undo() } /** Redo's the last undone change to the transaction. */ public func redo() { CoreStore.assert( self.supportsUndo, "Attempted to redo a \(typeName(self)) with Undo support disabled." ) self.context.redo() } /** Begins a child transaction where `NSManagedObject` creates, updates, and deletes can be made. This is useful for making temporary changes, such as partially filled forms. - prameter supportsUndo: `undo()`, `redo()`, and `rollback()` methods are only available when this parameter is `true`, otherwise those method will raise an exception. Defaults to `false`. Note that turning on Undo support may heavily impact performance especially on iOS or watchOS where memory is limited. - returns: a `UnsafeDataTransaction` instance where creates, updates, and deletes can be made. */ @warn_unused_result public func beginUnsafe(supportsUndo supportsUndo: Bool = false) -> UnsafeDataTransaction { return UnsafeDataTransaction( mainContext: self.context, queue: self.transactionQueue, supportsUndo: supportsUndo ) } /** Returns the `NSManagedObjectContext` for this unsafe transaction. Use only for cases where external frameworks need an `NSManagedObjectContext` instance to work with. Note that it is the developer's responsibility to ensure the following: - that the `UnsafeDataTransaction` that owns this context should be strongly referenced and prevented from being deallocated during the context's lifetime - that all saves will be done either through the `UnsafeDataTransaction`'s `commit(...)` method, or by calling `save()` manually on the context, its parent, and all other ancestor contexts if there are any. */ public var internalContext: NSManagedObjectContext { return self.context } @available(*, deprecated=1.3.1, renamed="beginUnsafe") @warn_unused_result public func beginDetached() -> UnsafeDataTransaction { return self.beginUnsafe() } // MARK: Internal internal init(mainContext: NSManagedObjectContext, queue: GCDQueue, supportsUndo: Bool) { super.init(mainContext: mainContext, queue: queue, supportsUndo: supportsUndo, bypassesQueueing: true) } }
mit
6f695605e8fc6aa90cd42415e831e3c7
39.128378
312
0.689847
5.159861
false
false
false
false
jpush/jchat-swift
JChat/Src/Utilites/3rdParty/RecordVoice/JCAudioPlayerHelper.swift
1
2323
// // JCAudioPlayerHelper.swift // JChatSwift // // Created by oshumini on 16/2/26. // Copyright © 2016年 HXHG. All rights reserved. // import UIKit import AVFoundation protocol JCAudioPlayerHelperDelegate: NSObjectProtocol { func didAudioPlayerBeginPlay(_ AudioPlayer: AVAudioPlayer) func didAudioPlayerStopPlay(_ AudioPlayer: AVAudioPlayer) func didAudioPlayerPausePlay(_ AudioPlayer: AVAudioPlayer) } final class JCAudioPlayerHelper: NSObject { var player: AVAudioPlayer! weak var delegate: JCAudioPlayerHelperDelegate? static let sharedInstance = JCAudioPlayerHelper() private override init() { super.init() } func managerAudioWithData(_ data:Data, toplay:Bool) { if toplay { playAudioWithData(data) } else { pausePlayingAudio() } } func playAudioWithData(_ voiceData:Data) { do { //AVAudioSessionCategoryPlayback if #available(iOS 10.0, *) { try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback, mode: AVAudioSession.Mode.default, options: AVAudioSession.CategoryOptions.defaultToSpeaker) } else { // Fallback on earlier versions } } catch let error as NSError { print("set category fail \(error)") } if player != nil { player.stop() player = nil } do { let pl: AVAudioPlayer = try AVAudioPlayer(data: voiceData) pl.delegate = self pl.play() player = pl } catch let error as NSError { print("alloc AVAudioPlayer with voice data fail with error \(error)") } UIDevice.current.isProximityMonitoringEnabled = true } func pausePlayingAudio() { player?.pause() } func stopAudio() { if player != nil && player.isPlaying { player.stop() } UIDevice.current.isProximityMonitoringEnabled = false delegate?.didAudioPlayerStopPlay(player) } } extension JCAudioPlayerHelper: AVAudioPlayerDelegate { func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) { stopAudio() } }
mit
2eb9712db6afe44952c74088686e8acd
26.951807
190
0.613362
5.272727
false
false
false
false
leizh007/HiPDA
HiPDA/HiPDA/General/Views/PickerActionSheetController.swift
1
4606
// // PickerActionSheetController.swift // HiPDA // // Created by leizh007 on 16/9/11. // Copyright © 2016年 HiPDA. All rights reserved. // import UIKit import RxSwift import RxCocoa /// 选择结束的block typealias PickerSelectedCompletionHandler = (Int?) -> Void /// 包含Picker选择器的ActionSheetController /// /// 在present的时候animation请用false! class PickerActionSheetController: BaseViewController, StoryboardLoadable { /// 选择结束时的CompletionHandler var selectedCompletionHandler: PickerSelectedCompletionHandler? /// picker的标题数组 var pickerTitles: [String]! /// 初始的选择下标 var initialSelelctionIndex: Int! /// 容器视图的底constraint @IBOutlet weak var containerStackViewBottomConstraint: NSLayoutConstraint! /// 容器视图的高度constraint @IBOutlet weak var containerStackViewHeightConstraint: NSLayoutConstraint! /// pickerView @IBOutlet weak var pickerView: UIPickerView! /// 分割线的高度constraint @IBOutlet weak var seperatorHeightConstraint: NSLayoutConstraint! /// 背景被点击 @IBOutlet var tapBackground: UITapGestureRecognizer! /// 取消按钮 @IBOutlet weak var cancelBarButtonItem: UIBarButtonItem! /// 确定按钮 @IBOutlet weak var submitBarButtonItem: UIBarButtonItem! // MARK: - life cycle override func viewDidLoad() { super.viewDidLoad() useCustomViewControllerTransitioningAnimator = false pickerView.selectRow(initialSelelctionIndex ?? 0, inComponent: 0, animated: true) let commands: [Observable<Bool>] = [ tapBackground.rx.event.map { _ in false }, cancelBarButtonItem.rx.tap.map { _ in false }, submitBarButtonItem.rx.tap.map { _ in true } ] Observable.from(commands).merge().subscribe(onNext: { [weak self] submit in guard let `self` = self, let selectedCompletionHandler = self.selectedCompletionHandler else { return } self.containerStackViewBottomConstraint.constant = -self.containerStackViewHeightConstraint.constant UIView.animate(withDuration: C.UI.animationDuration, animations: { self.view.backgroundColor = UIColor.clear self.view.layoutIfNeeded() }, completion: { _ in if submit { selectedCompletionHandler(self.pickerView.selectedRow(inComponent: 0)) } else { selectedCompletionHandler(nil) } }) }).addDisposableTo(disposeBag) } override func setupConstraints() { seperatorHeightConstraint.constant = 1.0 / UIScreen.main.scale containerStackViewHeightConstraint.constant -= 1.0 / UIScreen.main.scale containerStackViewBottomConstraint.constant = -containerStackViewHeightConstraint.constant } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) containerStackViewBottomConstraint.constant = 0.0 UIView.animate(withDuration: C.UI.animationDuration) { self.view.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.2) self.view.layoutIfNeeded() } } override var preferredStatusBarStyle: UIStatusBarStyle { return presentingViewController?.preferredStatusBarStyle ?? .lightContent } } // MARK: - UIPickerViewDataSource extension PickerActionSheetController: UIPickerViewDataSource { func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return pickerTitles.count } } // MARK: - UIPickerViewDelegate extension PickerActionSheetController: UIPickerViewDelegate { func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return pickerTitles.safe[row] } func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView { let label: UILabel if let view = view as? UILabel { label = view } else { label = UILabel() } label.text = pickerTitles.safe[row] label.textAlignment = .center label.font = UIFont.systemFont(ofSize: 17.0) return label } }
mit
f6243342b5e087f8d7ebb8ce5898a101
32.586466
132
0.657712
5.343301
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureNotificationPreferences/Sources/FeatureNotificationPreferencesMocks/MockGenerator.swift
1
3807
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine import Errors import FeatureNotificationPreferencesDomain import Foundation public enum MockGenerator { static let emailMethod = NotificationMethodInfo( id: UUID(), method: .email, title: "E-Mail", configured: true, verified: true ) static let inAppMethod = NotificationMethodInfo( id: UUID(), method: .inApp, title: "In-App", configured: true, verified: true ) static let smsMethod = NotificationMethodInfo( id: UUID(), method: .sms, title: "SMS", configured: true, verified: true ) static let pushMethod = NotificationMethodInfo( id: UUID(), method: .push, title: "Push", configured: true, verified: true ) static let requiredMethods = [ emailMethod ] static let optionalMethods = [ emailMethod, inAppMethod, smsMethod ] static let enabledMethods = [ inAppMethod, emailMethod ] public static let priceAlertNotificationPreference = NotificationPreference( id: UUID(), type: .priceAlert, title: "Price alerts", subtitle: "Push & Email", preferenceDescription: "Sent when a particular asset increases or decreases in price", requiredMethods: requiredMethods, optionalMethods: optionalMethods, enabledMethods: enabledMethods ) public static let transactionalNotificationPreference = NotificationPreference( id: UUID(), type: .transactional, title: "Transactional notifications", subtitle: "Push & Email", preferenceDescription: "Sent when a particular asset increases or decreases in price", requiredMethods: requiredMethods, optionalMethods: optionalMethods, enabledMethods: enabledMethods ) public static let securityNotificationPreference = NotificationPreference( id: UUID(), type: .security, title: "Security notifications", subtitle: "Push & Email", preferenceDescription: "Sent when a particular asset increases or decreases in price", requiredMethods: requiredMethods, optionalMethods: optionalMethods, enabledMethods: enabledMethods ) public static let marketingNotificationPreference = NotificationPreference( id: UUID(), type: .marketing, title: "Marketing notifications", subtitle: "Push & Email", preferenceDescription: "Sent when a particular asset increases or decreases in price", requiredMethods: requiredMethods, optionalMethods: optionalMethods, enabledMethods: enabledMethods ) public static let updatedNotificationPreference = UpdatedNotificationPreference( contactMethod: NotificationMethod.inApp.rawValue, channel: PreferenceType.marketing.rawValue, action: "ENABLE" ) static let updatedPreferencesBundle = [ UpdatedNotificationPreference( contactMethod: NotificationMethod.inApp.rawValue, channel: PreferenceType.marketing.rawValue, action: "ENABLE" ), UpdatedNotificationPreference( contactMethod: NotificationMethod.sms.rawValue, channel: PreferenceType.marketing.rawValue, action: "ENABLE" ), UpdatedNotificationPreference( contactMethod: NotificationMethod.push.rawValue, channel: PreferenceType.marketing.rawValue, action: "ENABLE" ) ] public static let updatedPreferences = UpdatedPreferences(preferences: updatedPreferencesBundle) }
lgpl-3.0
d221892d70dae73d4e350d2338edf203
29.693548
100
0.650552
5.638519
false
false
false
false
tingxins/InputKit
InputKitSwift/LimitedTextView.swift
1
11747
// // LimitedTextView.swift // InputKitDemo_Swift // // Created by tingxins on 06/06/2017. // Copyright © 2017 tingxins. All rights reserved. // import UIKit open class LimitedTextView: UITextView { //MARK: - Property defines private var selectionRange: NSRange = NSMakeRange(0, 0) private var historyText: String? open var limitedType: LimitedType = .normal @IBInspectable var _limitedType: Int { get { return limitedType.rawValue } set { limitedType = LimitedType(rawValue: newValue) ?? .normal } } @IBInspectable open var limitedNumber: Int = Int(MAX_INPUT) @objc @IBInspectable open var limitedPrefix: Int = Int(MAX_INPUT) @objc @IBInspectable open var limitedSuffix: Int = Int(MAX_INPUT) @IBInspectable open var isTextSelecting: Bool = false @IBInspectable open var limitedRegEx: String? { didSet { if let regEx = limitedRegEx, regEx.count > 0 { limitedRegExs = [regEx] } } } open var limitedRegExs: [String]? { didSet { var realRegEx: String = "" var realRegExs: [String] = [] limitedRegExs?.forEach({ (regEx) in realRegEx = regEx.replacingOccurrences(of: "\\\\", with: "\\") if realRegEx.count != 0 { realRegExs.append(realRegEx) } }) limitedRegExs = realRegExs clearCache() } } public override init(frame: CGRect, textContainer: NSTextContainer?) { super.init(frame: frame, textContainer: textContainer) addNotifications() addConfigs() if self.delegate == nil { addDelegate() } } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } open override func awakeFromNib() { super.awakeFromNib() addNotifications() addConfigs() if self.delegate == nil { addDelegate() } } private var limitedDelegate: LimitedTextViewDelegate? override open var delegate: UITextViewDelegate? { get { return super.delegate } set { let limitedDelegate = LimitedTextViewDelegate(realDelegate: newValue) super.delegate = limitedDelegate self.limitedDelegate = limitedDelegate } } //MARK: - Deinitialized deinit { NotificationCenter.default.removeObserver(self) } } extension LimitedTextView { //MARK: - Config Methods private func addNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(textViewTextDidChange(notification:)), name: UITextView.textDidChangeNotification, object: nil) } private func addDelegate() { delegate = nil } private func addConfigs() { autocorrectionType = .no } private func clearCache() { historyText = nil } } //MARK: - @objc Methods extension LimitedTextView { //MARK: - Notifications @objc private func textViewTextDidChange(notification: Notification) { let textView = notification.object as? UITextView if self != textView { return } let currentText = textView?.text let maxLength = self.limitedNumber var position: UITextPosition? if let markedTextRange = textView?.markedTextRange { position = textView?.position(from: markedTextRange.start, offset: 0) } var isMatch = true switch self.limitedType { case .normal: break case .price: isMatch = MatchManager.matchLimitedTextTypePrice(component: textView!, value: currentText!) case .custom: isMatch = MatchManager.matchLimitedTextTypeCustom(regExs: self.limitedRegExs, component: textView!, value: currentText!) } if isMatch { self.historyText = textView?.text } if position == nil { var flag = false if let count = currentText?.count, count > maxLength { textView?.text = String(currentText!.dropLast(count - maxLength)) flag = true } if self.isTextSelecting && !isMatch { flag = true if let hisText = self.historyText, let curText = textView?.text, hisText.count <= curText.count { textView?.text = hisText }else { textView?.text = "" } } let text: NSString = currentText! as NSString if ((self.selectionRange.length > 0) && !isMatch && (self.selectionRange.length + self.selectionRange.location <= text.length)) { let limitedText = text.substring(with: self.selectionRange) textView?.text = textView?.text.replacingOccurrences(of: limitedText, with: "") self.selectionRange = NSMakeRange(0, 0) if limitedText.count > 0 { flag = true } } if flag { // Send limits msg sendIllegalMsgToObject() } } else { guard let markedTextRange = textView?.markedTextRange else { return } self.selectionRange = range(from: markedTextRange) } sendDidChangeMsgToObject() } } extension LimitedTextView { fileprivate func range(from textRange: UITextRange) -> NSRange { let location = offset(from: beginningOfDocument, to: textRange.start) let length = offset(from: textRange.start, to: textRange.end) return NSMakeRange(location, length) } fileprivate func sendIllegalMsgToObject() { guard let delegate = self.limitedDelegate, let realDelegate = delegate.realDelegate else { return } delegate.sendMsgTo(obj: realDelegate, with: self, sel: InputKitMessage.Name.inputKitDidLimitedIllegalInputText) } fileprivate func sendDidChangeMsgToObject() { guard let delegate = self.limitedDelegate, let realDelegate = delegate.realDelegate else { return } delegate.sendMsgTo(obj: realDelegate, with: self, sel: InputKitMessage.Name.inputKitDidChangeInputText) } fileprivate func resetSelectionTextRange() { selectionRange = NSMakeRange(0, 0) } } fileprivate class LimitedTextViewDelegate: LimitedDelegate, UITextViewDelegate { @available(iOS 2.0, *) func textViewShouldBeginEditing(_ textView: UITextView) -> Bool { guard let realDelegate = self.realDelegate as? UITextViewDelegate, let shouldBeginEditing = realDelegate.textViewShouldBeginEditing?(textView) else { return true } return shouldBeginEditing } @available(iOS 2.0, *) func textViewShouldEndEditing(_ textView: UITextView) -> Bool { guard let realDelegate = self.realDelegate as? UITextViewDelegate, let shouldEndEditing = realDelegate.textViewShouldEndEditing?(textView) else { return true } return shouldEndEditing } @available(iOS 2.0, *) func textViewDidBeginEditing(_ textView: UITextView) { guard let realDelegate = self.realDelegate as? UITextViewDelegate else { return } realDelegate.textViewDidBeginEditing?(textView) } @available(iOS 2.0, *) func textViewDidEndEditing(_ textView: UITextView) { guard let realDelegate = self.realDelegate as? UITextViewDelegate else { return } realDelegate.textViewDidEndEditing?(textView) } @available(iOS 2.0, *) func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { var flag = true if let realDelegate = self.realDelegate as? UITextViewDelegate, let shouldChange = realDelegate.textView?(textView, shouldChangeTextIn: range, replacementText: text) { flag = shouldChange } var matchResult = true let limitedTextView = textView as! LimitedTextView if textView.isKind(of: LimitedTextView.self) { limitedTextView.resetSelectionTextRange() let matchStr = MatchManager.getMatchContentWithOriginalText(originalText: textView.text!, replaceText: text, range: range) let isDeleteOperation = (range.length > 0 && text.count == 0) ? true : false switch limitedTextView.limitedType { case .normal: break case .price: matchResult = MatchManager.matchLimitedTextTypePrice(component: textView, value: matchStr) case .custom: if limitedTextView.isTextSelecting { matchResult = true } else { matchResult = MatchManager.matchLimitedTextTypeCustom(regExs: limitedTextView.limitedRegExs, component: textView, value: matchStr) } } let result = flag && (matchResult || isDeleteOperation) if !result { limitedTextView.sendIllegalMsgToObject() } limitedTextView.sendDidChangeMsgToObject() return result } limitedTextView.sendDidChangeMsgToObject() return matchResult && flag } @available(iOS 2.0, *) func textViewDidChange(_ textView: UITextView) { guard let realDelegate = self.realDelegate as? UITextViewDelegate else { return } realDelegate.textViewDidChange?(textView) } @available(iOS 2.0, *) func textViewDidChangeSelection(_ textView: UITextView) { guard let realDelegate = self.realDelegate as? UITextViewDelegate else { return } realDelegate.textViewDidChangeSelection?(textView) } @available(iOS 10.0, *) func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool { guard let realDelegate = self.realDelegate as? UITextViewDelegate, let shouldInteract = realDelegate.textView?(textView, shouldInteractWith: URL, in: characterRange, interaction: interaction) else { return true } return shouldInteract } @available(iOS 10.0, *) func textView(_ textView: UITextView, shouldInteractWith textAttachment: NSTextAttachment, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool { guard let realDelegate = self.realDelegate as? UITextViewDelegate, let shouldInteract = realDelegate.textView?(textView, shouldInteractWith: textAttachment, in: characterRange, interaction: interaction) else { return true } return shouldInteract } @available(iOS, introduced: 7.0, deprecated: 10.0, message: "Use textView:shouldInteractWithURL:inRange:forInteractionType: instead") func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool { guard let realDelegate = self.realDelegate as? UITextViewDelegate, let shouldInteract = realDelegate.textView?(textView, shouldInteractWith: URL, in: characterRange) else { return true } return shouldInteract } @available(iOS, introduced: 7.0, deprecated: 10.0, message: "Use textView:shouldInteractWithTextAttachment:inRange:forInteractionType: instead") func textView(_ textView: UITextView, shouldInteractWith textAttachment: NSTextAttachment, in characterRange: NSRange) -> Bool { guard let realDelegate = self.realDelegate as? UITextViewDelegate, let shouldInteract = realDelegate.textView?(textView, shouldInteractWith: textAttachment, in: characterRange) else { return true } return shouldInteract } }
mit
fb4604f2ab8abace7cbb061d55719c72
33.345029
166
0.643879
5.229742
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/Mobile/Mobile_Error.swift
1
3719
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore /// Error enum for Mobile public struct MobileErrorType: AWSErrorType { enum Code: String { case accountActionRequiredException = "AccountActionRequiredException" case badRequestException = "BadRequestException" case internalFailureException = "InternalFailureException" case limitExceededException = "LimitExceededException" case notFoundException = "NotFoundException" case serviceUnavailableException = "ServiceUnavailableException" case tooManyRequestsException = "TooManyRequestsException" case unauthorizedException = "UnauthorizedException" } private let error: Code public let context: AWSErrorContext? /// initialize Mobile public init?(errorCode: String, context: AWSErrorContext) { guard let error = Code(rawValue: errorCode) else { return nil } self.error = error self.context = context } internal init(_ error: Code) { self.error = error self.context = nil } /// return error code string public var errorCode: String { self.error.rawValue } /// Account Action is required in order to continue the request. public static var accountActionRequiredException: Self { .init(.accountActionRequiredException) } /// The request cannot be processed because some parameter is not valid or the project state prevents the operation from being performed. public static var badRequestException: Self { .init(.badRequestException) } /// The service has encountered an unexpected error condition which prevents it from servicing the request. public static var internalFailureException: Self { .init(.internalFailureException) } /// There are too many AWS Mobile Hub projects in the account or the account has exceeded the maximum number of resources in some AWS service. You should create another sub-account using AWS Organizations or remove some resources and retry your request. public static var limitExceededException: Self { .init(.limitExceededException) } /// No entity can be found with the specified identifier. public static var notFoundException: Self { .init(.notFoundException) } /// The service is temporarily unavailable. The request should be retried after some time delay. public static var serviceUnavailableException: Self { .init(.serviceUnavailableException) } /// Too many requests have been received for this AWS account in too short a time. The request should be retried after some time delay. public static var tooManyRequestsException: Self { .init(.tooManyRequestsException) } /// Credentials of the caller are insufficient to authorize the request. public static var unauthorizedException: Self { .init(.unauthorizedException) } } extension MobileErrorType: Equatable { public static func == (lhs: MobileErrorType, rhs: MobileErrorType) -> Bool { lhs.error == rhs.error } } extension MobileErrorType: CustomStringConvertible { public var description: String { return "\(self.error.rawValue): \(self.message ?? "")" } }
apache-2.0
95bc0ef8c2a55f20a4182545d8890f85
46.679487
258
0.703684
5.32808
false
false
false
false
vector-im/vector-ios
Riot/Managers/Theme/Themes/BlackTheme.swift
1
940
/* Copyright 2019 New Vector Ltd 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 class BlackTheme: DarkTheme { override init() { super.init() self.identifier = ThemeIdentifier.black.rawValue self.backgroundColor = UIColor(rgb: 0x000000) self.baseColor = UIColor(rgb: 0x000000) self.headerBackgroundColor = UIColor(rgb: 0x000000) self.headerBorderColor = UIColor(rgb: 0x15191E) } }
apache-2.0
3a6d4088a00181631e976b50c4394f32
31.413793
73
0.732979
4.311927
false
false
false
false
bppr/Swiftest
src/Swiftest/Client/Listeners/Printer.swift
1
509
public class Printer { public var out: (String, Bool) -> Void = { str, newline in let msg = newline ? str + "\n" : str fputs(msg, OS.stdout) } public var indentLevel = 0 func call(output: String, newline: Bool = true) { var indentation = "" if(indentLevel > 0) { for _ in 1...indentLevel { indentation += " " } } out(indentation + output, newline) } func lineBreak() { out("", true) } func indent() { indentLevel += 1 } func dedent() { indentLevel -= 1 } }
mit
5b725b868b44ca0c893907f3ed7beb53
22.136364
60
0.579568
3.661871
false
false
false
false
manfengjun/KYMart
Section/Order/Controller/KYOrderMenuUtil.swift
1
2204
// // KYOrderMenuUtil.swift // KYMart // // Created by JUN on 2017/7/12. // Copyright © 2017年 JUN. All rights reserved. // import UIKit class KYOrderMenuUtil: NSObject { /// 删除订单 /// /// - Parameters: /// - order_id: order_id description /// - completion: completion description class func delOrder(order_id:String,completion:@escaping (Bool) -> Void) { let params = ["order_id":order_id] SJBRequestModel.push_fetchDelOrderData(params: params as [String : AnyObject]) { (response, status) in if status == 1 { self.Toast(content: "删除成功") completion(true) } else { self.Toast(content: response as! String) completion(false) } } } /// 支付订单 /// /// - Parameters: /// - order_id: order_id description /// - order_money: order_money description /// - target: target description class func payOrder(order_id:String,order_money:String,target:UIViewController) { let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main) let orderPayVC = storyboard.instantiateViewController(withIdentifier: "OrderPayVC") as! KYOrderPayViewController orderPayVC.isCart = false orderPayVC.orderID = order_id orderPayVC.orderMoney = order_money target.navigationController?.pushViewController(orderPayVC, animated: true) } /// 确认收货 /// /// - Parameters: /// - order_id: order_id description /// - completion: completion description class func confirmOrder(order_id:String,completion:@escaping (Bool) -> Void) { let params = ["order_id":order_id] SJBRequestModel.push_fetchConfirmOrderData(params: params as [String : AnyObject]) { (response, status) in if status == 1 { self.Toast(content: "确认收货成功") completion(true) } else { self.Toast(content:response as! String) completion(false) } } } }
mit
4d765947fcdfd003331a6f990f451021
29.814286
120
0.568846
4.314
false
false
false
false
JohnCoates/Aerial
Aerial/Source/Views/Layers/Weather/ForecastLayer.swift
1
19397
// // ForecastLayer.swift // Aerial // // Created by Guillaume Louel on 23/03/2021. // Copyright © 2021 Guillaume Louel. All rights reserved. // import Foundation import AVKit // swiftlint:disable:next type_body_length class ForecastLayer: CALayer { var condition: ForecastElement? // swiftlint:disable:next cyclomatic_complexity init(condition: ForecastElement, scale: CGFloat) { self.condition = condition super.init() // backgroundColor = .init(gray: 0.2, alpha: 0.2) contentsScale = scale let size = PrefsInfo.weather.fontSize // We have daily forecasts, and hourly forecasts available (woo) if PrefsInfo.weather.mode == .forecast3days || PrefsInfo.weather.mode == .forecast5days { // How many days to display, currently we do 3 and 5 var days = 5 if PrefsInfo.weather.mode == .forecast3days { days = 3 } if let flist = condition.list { let breakIndex = detectDayChange(list: flist) if flist.count >= 40 { var height: CGFloat = 0 for dayidx in 0 ..< days { let start = breakIndex + (8 * (dayidx-1)) var day: CALayer if dayidx == 0 { day = makeDayBlock(slice: flist[0..<breakIndex], size: size*2) } else { day = makeDayBlock(slice: flist[start..<(start+8)], size: size*2) } day.anchorPoint = CGPoint(x: 0, y: 0) day.position = CGPoint(x: Int(size * 2) * dayidx, y: 0) self.addSublayer(day) if day.frame.height > height { height = day.frame.height } } let legend = makeLegendBlock(size: size*2) legend.anchorPoint = CGPoint(x: 0, y: 0) legend.position = CGPoint(x: Int(size*2) * days, y: 0) self.addSublayer(legend) self.frame = CGRect(x: 0, y: 0, width: CGFloat(Double((days + 1)) * (size * 2)), height: height) } } } else { // Hourly forecast, we do 6 hours if let flist = condition.list { // Just in case if flist.count > 5 { var height: CGFloat = 0 for houridx in 0 ..< 6 { let day = makeHourBlock(hour: flist[houridx], size: size*2) day.anchorPoint = CGPoint(x: 0, y: 0) day.position = CGPoint(x: Int(size * 2) * houridx, y: 0) self.addSublayer(day) if day.frame.height > height { height = day.frame.height } } let legend = makeLegendBlock(size: size*2) legend.anchorPoint = CGPoint(x: 0, y: 0) legend.position = CGPoint(x: Int(size*2) * 6, y: 0) self.addSublayer(legend) self.frame = CGRect(x: 0, y: 0, width: CGFloat(7 * (size * 2)), height: height) } } } } func detectDayChange(list: [FList]) -> Int { var firstDay: String? var index = 0 for day in list { if firstDay == nil { firstDay = dayStringFromTimeStamp(timeStamp: Double(day.dt!)) } else { if firstDay != dayStringFromTimeStamp(timeStamp: Double(day.dt!)) { return index } } index += 1 } // fallback, uh... return 1 } override init(layer: Any) { super.init(layer: layer) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func makeDayBlock(slice: ArraySlice<FList>, size: Double) -> CALayer { // This is ugly but we try and do the best from the data we get... var tmin, tmax: Double? var day: Int? let array = Array(slice) for element in array { if day == nil { day = element.dt } if tmin == nil { tmin = element.main!.tempMin } else { if element.main!.tempMin! < tmin! { tmin = element.main!.tempMin } } if tmax == nil { tmax = element.main!.tempMax } else { if element.main!.tempMax! > tmax! { tmax = element.main!.tempMax } } } let list = array[array.count/2] let weather = list.weather![0] let windSpeed = list.wind!.speed! let windDeg = list.wind!.deg! let whumidity = list.main!.humidity let mainLayer = CALayer() // First create the symbol let imglayer = ConditionSymbolLayer(weather: weather, dt: day!, isNight: false, size: Int(size), square: true) let windLayer = makeWindBlock(speed: windSpeed, degree: windDeg, size: size/4) let max = CAVCTextLayer() max.string = "\(String(format: "%.0f", tmax!))°" (max.font, max.fontSize) = max.makeFont(name: PrefsInfo.weather.fontName, size: size/4) // ReRect the temperature let rect = max.calculateRect(string: max.string as! String, font: max.font as! NSFont) max.frame = rect max.contentsScale = self.contentsScale max.alignmentMode = .center let min = CAVCTextLayer() min.string = "\(String(format: "%.0f", tmin!))°" (min.font, min.fontSize) = min.makeFont(name: PrefsInfo.weather.fontName, size: size/4) // ReRect the temperature let rect2 = min.calculateRect(string: min.string as! String, font: min.font as! NSFont) min.frame = rect2 min.contentsScale = self.contentsScale min.alignmentMode = .center let humidity = CAVCTextLayer() humidity.string = "\(whumidity!)%" (humidity.font, humidity.fontSize) = humidity.makeFont(name: PrefsInfo.weather.fontName, size: size/4) // ReRect the temperature let recth = humidity.calculateRect(string: humidity.string as! String, font: humidity.font as! NSFont) humidity.frame = recth humidity.contentsScale = self.contentsScale humidity.alignmentMode = .center let dayi = CAVCTextLayer() dayi.string = dayStringFromTimeStamp(timeStamp: Double(day!)) (dayi.font, dayi.fontSize) = dayi.makeFont(name: PrefsInfo.weather.fontName, size: size/4) // ReRect the temperature let rect4 = dayi.calculateRect(string: dayi.string as! String, font: dayi.font as! NSFont) dayi.frame = rect4 dayi.contentsScale = self.contentsScale dayi.alignmentMode = .center // Then we draw bottom to top dayi.anchorPoint = CGPoint(x: 0.5, y: 0) dayi.position = CGPoint(x: size/2, y: 0) mainLayer.addSublayer(dayi) var offset = dayi.frame.height if PrefsInfo.weather.showWind { windLayer.anchorPoint = CGPoint(x: 0.5, y: 0) windLayer.position = CGPoint(x: CGFloat(size)/2, y: offset) mainLayer.addSublayer(windLayer) offset += windLayer.frame.height } if PrefsInfo.weather.showHumidity { humidity.anchorPoint = CGPoint(x: 0.5, y: 0) humidity.position = CGPoint(x: CGFloat(size)/2, y: offset) mainLayer.addSublayer(humidity) offset += humidity.frame.height } min.anchorPoint = CGPoint(x: 0.5, y: 0) min.position = CGPoint(x: CGFloat(size)/2, y: offset) mainLayer.addSublayer(min) offset += min.frame.height max.anchorPoint = CGPoint(x: 0.5, y: 0) max.position = CGPoint(x: CGFloat(size) / 2, y: offset) mainLayer.addSublayer(max) offset += max.frame.height imglayer.anchorPoint = CGPoint(x: 0.5, y: 0.5) imglayer.position = CGPoint(x: Double(size) / 2, y: Double(offset) + size/2) mainLayer.addSublayer(imglayer) mainLayer.frame = CGRect(x: 0, y: 0, width: CGFloat(size), height: offset + imglayer.frame.height) return mainLayer } func makeHourBlock(hour: FList, size: Double) -> CALayer { let mainLayer = CALayer() let isNight = hour.sys!.pod! == "n" ? true : false // First create the symbol let imglayer = ConditionSymbolLayer(weather: hour.weather![0], dt: hour.dt!, isNight: isNight, size: Int(size), square: true) let windLayer = makeWindBlock(speed: hour.wind!.speed!, degree: hour.wind!.deg!, size: size/4) let temp = CAVCTextLayer() temp.string = "\(String(format: "%.0f", hour.main!.temp!))°" (temp.font, temp.fontSize) = temp.makeFont(name: PrefsInfo.weather.fontName, size: size/4) // ReRect the temperature let rect = temp.calculateRect(string: temp.string as! String, font: temp.font as! NSFont) temp.frame = rect temp.contentsScale = self.contentsScale temp.alignmentMode = .center let feelsLike = CAVCTextLayer() feelsLike.string = "\(String(format: "%.0f", hour.main!.feelsLike!))°" (feelsLike.font, feelsLike.fontSize) = feelsLike.makeFont(name: PrefsInfo.weather.fontName, size: size/4) // ReRect the temperature let rect2 = feelsLike.calculateRect(string: feelsLike.string as! String, font: feelsLike.font as! NSFont) feelsLike.frame = rect2 feelsLike.contentsScale = self.contentsScale feelsLike.alignmentMode = .center let humidity = CAVCTextLayer() humidity.string = "\(hour.main!.humidity!)%" (humidity.font, humidity.fontSize) = humidity.makeFont(name: PrefsInfo.weather.fontName, size: size/4) // ReRect the temperature let recth = humidity.calculateRect(string: humidity.string as! String, font: humidity.font as! NSFont) humidity.frame = recth humidity.contentsScale = self.contentsScale humidity.alignmentMode = .center let dayi = CAVCTextLayer() dayi.string = hourStringFromTimeStamp(timeStamp: Double(hour.dt!)) (dayi.font, dayi.fontSize) = dayi.makeFont(name: PrefsInfo.weather.fontName, size: size/4) // ReRect the temperature let rect4 = dayi.calculateRect(string: dayi.string as! String, font: dayi.font as! NSFont) dayi.frame = rect4 dayi.contentsScale = self.contentsScale dayi.alignmentMode = .center // Then we draw bottom to top dayi.anchorPoint = CGPoint(x: 0.5, y: 0) dayi.position = CGPoint(x: size/2, y: 0) mainLayer.addSublayer(dayi) var offset = dayi.frame.height if PrefsInfo.weather.showWind { windLayer.anchorPoint = CGPoint(x: 0.5, y: 0) windLayer.position = CGPoint(x: CGFloat(size)/2, y: offset) mainLayer.addSublayer(windLayer) offset += windLayer.frame.height } if PrefsInfo.weather.showHumidity { humidity.anchorPoint = CGPoint(x: 0.5, y: 0) humidity.position = CGPoint(x: CGFloat(size)/2, y: offset) mainLayer.addSublayer(humidity) offset += humidity.frame.height } feelsLike.anchorPoint = CGPoint(x: 0.5, y: 0) feelsLike.position = CGPoint(x: CGFloat(size)/2, y: offset) mainLayer.addSublayer(feelsLike) offset += feelsLike.frame.height temp.anchorPoint = CGPoint(x: 0.5, y: 0) temp.position = CGPoint(x: CGFloat(size) / 2, y: offset) mainLayer.addSublayer(temp) offset += temp.frame.height imglayer.anchorPoint = CGPoint(x: 0.5, y: 0.5) imglayer.position = CGPoint(x: Double(size) / 2, y: Double(offset) + size/2) mainLayer.addSublayer(imglayer) mainLayer.frame = CGRect(x: 0, y: 0, width: CGFloat(size), height: offset + imglayer.frame.height) return mainLayer } func makeLegendBlock(size: Double) -> CALayer { let mainLayer = CALayer() // Make a vertically centered layer for t° let windLayer = CAVCTextLayer() if PrefsInfo.weather.degree == .celsius { windLayer.string = "km/h" } else { windLayer.string = "mph" } // Get something large first (windLayer.font, windLayer.fontSize) = windLayer.makeFont(name: PrefsInfo.weather.fontName, size: size/4) // ReRect the temperature let rect2 = windLayer.calculateRect(string: windLayer.string as! String, font: windLayer.font as! NSFont) windLayer.frame = rect2 windLayer.contentsScale = self.contentsScale windLayer.alignmentMode = .center let max = CAVCTextLayer() if PrefsInfo.weather.mode == .forecast6hours { max.string = "Temperature" } else { max.string = "Max" } (max.font, max.fontSize) = max.makeFont(name: PrefsInfo.weather.fontName, size: size/4) // ReRect the temperature let rect = max.calculateRect(string: max.string as! String, font: max.font as! NSFont) max.frame = rect max.contentsScale = self.contentsScale max.alignmentMode = .center let min = CAVCTextLayer() min.string = "Min" if PrefsInfo.weather.mode == .forecast6hours { min.string = "Feels Like" } else { min.string = "Min" } (min.font, min.fontSize) = min.makeFont(name: PrefsInfo.weather.fontName, size: size/4) // ReRect the temperature let rect3 = min.calculateRect(string: min.string as! String, font: min.font as! NSFont) min.frame = rect3 min.contentsScale = self.contentsScale min.alignmentMode = .center let humidity = CAVCTextLayer() humidity.string = "Humidity" (humidity.font, humidity.fontSize) = humidity.makeFont(name: PrefsInfo.weather.fontName, size: size/4) // ReRect the temperature let recth = humidity.calculateRect(string: humidity.string as! String, font: humidity.font as! NSFont) humidity.frame = recth humidity.contentsScale = self.contentsScale humidity.alignmentMode = .center // Then we draw bottom to top, we skip the first which shows the hour/day var offset: CGFloat = min.frame.height if PrefsInfo.weather.showWind { windLayer.anchorPoint = CGPoint(x: 0.5, y: 0) windLayer.position = CGPoint(x: CGFloat(size)/2, y: offset) mainLayer.addSublayer(windLayer) offset += windLayer.frame.height } if PrefsInfo.weather.showHumidity { humidity.anchorPoint = CGPoint(x: 0.5, y: 0) humidity.position = CGPoint(x: CGFloat(size)/2, y: offset) mainLayer.addSublayer(humidity) offset += humidity.frame.height } min.anchorPoint = CGPoint(x: 0.5, y: 0) min.position = CGPoint(x: CGFloat(size)/2, y: offset) mainLayer.addSublayer(min) offset += min.frame.height max.anchorPoint = CGPoint(x: 0.5, y: 0) max.position = CGPoint(x: CGFloat(size) / 2, y: offset) mainLayer.addSublayer(max) // offset += max.frame.height return mainLayer } func makeWindBlock(speed: Double, degree: Int, size: Double) -> CALayer { let windLayer = CALayer() // Make a vertically centered layer for t° let wind = CAVCTextLayer() if PrefsInfo.weatherWindMode == .kph && PrefsInfo.weather.degree == .celsius { wind.string = String(format: "%.0f", speed * 3.6) } else { wind.string = String(format: "%.0f", speed) } // Get something large first (wind.font, wind.fontSize) = wind.makeFont(name: PrefsInfo.weather.fontName, size: size) // ReRect the temperature let rect2 = wind.calculateRect(string: wind.string as! String, font: wind.font as! NSFont) wind.frame = rect2 wind.contentsScale = self.contentsScale // Create the wind indicator let imglayer = WindDirectionLayer(direction: 225, size: CGFloat(size/1.27)) imglayer.contentsScale = self.contentsScale imglayer.transform = CATransform3DMakeRotation(CGFloat((180 + degree)) / 180.0 * .pi, 0.0, 0.0, -1.0) imglayer.anchorPoint = CGPoint(x: 0.5, y: 0.5) imglayer.position = CGPoint(x: imglayer.frame.width/2, y: wind.frame.height/2) windLayer.addSublayer(imglayer) // We put the temperature at the right of the weather icon wind.anchorPoint = CGPoint(x: 0, y: 0) wind.position = CGPoint(x: imglayer.frame.width + 3, y: 0) windLayer.addSublayer(wind) // Reset the container frame windLayer.frame = CGRect(x: 0, y: 0, width: imglayer.frame.width + wind.frame.width + 3, height: wind.frame.height) return windLayer } func dayStringFromTimeStamp(timeStamp: Double) -> String { let date = Date(timeIntervalSince1970: timeStamp) let dateFormatter = DateFormatter() var locale = Locale(identifier: Locale.preferredLanguages[0]) if PrefsAdvanced.ciOverrideLanguage != "" { locale = Locale(identifier: PrefsAdvanced.ciOverrideLanguage) } dateFormatter.locale = locale dateFormatter.dateFormat = "E" return dateFormatter.string(from: date) } func hourStringFromTimeStamp(timeStamp: Double) -> String { let date = Date(timeIntervalSince1970: timeStamp) let dateFormatter = DateFormatter() var locale = Locale(identifier: Locale.preferredLanguages[0]) if PrefsAdvanced.ciOverrideLanguage != "" { locale = Locale(identifier: PrefsAdvanced.ciOverrideLanguage) } dateFormatter.locale = locale dateFormatter.dateFormat = "HH" return dateFormatter.string(from: date) + "h" } } extension Double { func roundTemp() -> Double { if PrefsInfo.weather.degree == .celsius { return self.rounded(toPlaces: 0) // rounded(toPlaces: 1) } else { return self.rounded() } } }
mit
50e47bed82b92798c52e5c30a1741aae
35.654064
123
0.559051
4.468772
false
false
false
false
nathawes/swift
test/SILGen/ivar_destroyer.swift
22
3195
// RUN: %target-swift-emit-silgen -parse-as-library %s | %FileCheck %s // Only derived classes with non-trivial ivars need an ivar destroyer. struct TrivialStruct {} class RootClassWithoutProperties {} class RootClassWithTrivialProperties { var x: Int = 0 var y: TrivialStruct = TrivialStruct() } class Canary {} class RootClassWithNonTrivialProperties { var x: Canary = Canary() } class DerivedClassWithTrivialProperties : RootClassWithoutProperties { var z: Int = 12 } class DerivedClassWithNonTrivialProperties : RootClassWithoutProperties { var z: Canary = Canary() } // CHECK-LABEL: sil hidden [ossa] @$s14ivar_destroyer36DerivedClassWithNonTrivialPropertiesCfE // CHECK: bb0(%0 : @guaranteed $DerivedClassWithNonTrivialProperties): // CHECK-NEXT: debug_value %0 // CHECK-NEXT: [[Z_ADDR:%.*]] = ref_element_addr %0 // CHECK-NEXT: [[Z_ADDR_DEINIT_ACCESS:%.*]] = begin_access [deinit] [static] [[Z_ADDR]] // CHECK-NEXT: destroy_addr [[Z_ADDR_DEINIT_ACCESS]] // CHECK-NEXT: end_access [[Z_ADDR_DEINIT_ACCESS]] // CHECK-NEXT: [[RESULT:%.*]] = tuple () // CHECK-NEXT: return [[RESULT]] // CHECK-LABEL: sil_vtable RootClassWithoutProperties { // CHECK-NEXT: #RootClassWithoutProperties.init!allocator // CHECK-NEXT: #RootClassWithoutProperties.deinit!deallocator // CHECK-NEXT: } // CHECK-LABEL: sil_vtable RootClassWithTrivialProperties { // CHECK-NEXT: #RootClassWithTrivialProperties.x!getter // CHECK-NEXT: #RootClassWithTrivialProperties.x!setter // CHECK-NEXT: #RootClassWithTrivialProperties.x!modify // CHECK-NEXT: #RootClassWithTrivialProperties.y!getter // CHECK-NEXT: #RootClassWithTrivialProperties.y!setter // CHECK-NEXT: #RootClassWithTrivialProperties.y!modify // CHECK-NEXT: #RootClassWithTrivialProperties.init!allocator // CHECK-NEXT: #RootClassWithTrivialProperties.deinit!deallocator // CHECK-NEXT: } // CHECK-LABEL: sil_vtable RootClassWithNonTrivialProperties { // CHECK-NEXT: #RootClassWithNonTrivialProperties.x!getter // CHECK-NEXT: #RootClassWithNonTrivialProperties.x!setter // CHECK-NEXT: #RootClassWithNonTrivialProperties.x!modify // CHECK-NEXT: #RootClassWithNonTrivialProperties.init!allocator // CHECK-NEXT: #RootClassWithNonTrivialProperties.deinit!deallocator // CHECK-NEXT: } // CHECK-LABEL: sil_vtable DerivedClassWithTrivialProperties { // CHECK-NEXT: #RootClassWithoutProperties.init!allocator // CHECK-NEXT: #DerivedClassWithTrivialProperties.z!getter // CHECK-NEXT: #DerivedClassWithTrivialProperties.z!setter // CHECK-NEXT: #DerivedClassWithTrivialProperties.z!modify // CHECK-NEXT: #DerivedClassWithTrivialProperties.deinit!deallocator // CHECK-NEXT: } // CHECK-LABEL: sil_vtable DerivedClassWithNonTrivialProperties { // CHECK-NEXT: #RootClassWithoutProperties.init!allocator // CHECK-NEXT: #DerivedClassWithNonTrivialProperties.z!getter // CHECK-NEXT: #DerivedClassWithNonTrivialProperties.z!setter // CHECK-NEXT: #DerivedClassWithNonTrivialProperties.z!modify // CHECK-NEXT: #DerivedClassWithNonTrivialProperties.deinit!deallocator // CHECK-NEXT: #DerivedClassWithNonTrivialProperties!ivardestroyer // CHECK-NEXT: }
apache-2.0
d7fb16a5b81b8f2df1219652a51eb814
40.493506
94
0.757746
4.352861
false
false
false
false
xuzhuoxi/SearchKit
Source/cs/search/SearchKeyResult.swift
1
4761
// // SearchKeyResult.swift // SearchKit // // Created by 许灼溪 on 15/12/21. // // import Foundation /** * 单个汉字(词)的检索结果 别名:键结果 * * @author xuzhuoxi * */ public struct SearchKeyResult: Comparable { fileprivate var resultArr = [SearchTypeResult]() public let key: String public let weight: Double /** * 计算是否有完整匹配情况<br> * * @return 有完整匹配true否false */ public var hasFullMatching: Bool { for str in resultArr { if str.isFullMatching { return true } } return false } /** * 计算匹配度<br> * 把各个检索类别的结果相加<br> * * @return 匹配度 */ public var totalValue : Double { var value:Double=0 for str in resultArr { value+=str.value } return value * weight } /** * 取得全部的检索类别 {@link SearchType}<br> * * @return 全部的检索类别 */ public var searchTypes: [SearchType] { var rs = [SearchType]() resultArr.each { (str :SearchTypeResult) -> () in rs.append(str.searchType) } return rs } /** * 取得全部的检索可用关联信息 {@link SearchType}<br> * * @return 全部的可用关联信息 */ public var associatedNames: [String] { var rs = [String]() resultArr.each { (str :SearchTypeResult) -> () in if let name = str.searchType.associatedName { rs.append(name) } } ArrayUtils.cleanRepeat(&rs) return rs } /** * 取得全部的检索结果 {@link SearchTypeResult}<br> * * @return 全部的检索结果 */ public var searchTypeResults: [SearchTypeResult] { return resultArr } public init(_ key: String, _ weightCache : WeightCacheProtocol?){ self.key = key self.weight = nil == weightCache ? 1.0 : weightCache!.getValues(key) } /** * 更新单个检索类别的匹配值,存储更大的<br> * * @param searchType * 检索类别 * @param value * 匹配值 */ mutating public func updateBiggerValue(_ searchType: SearchType, _ value:Double) { if let index = getIndex(searchType) { resultArr[index].updateBiggerValue(value) }else{ var str = SearchTypeResult(searchType) str.updateBiggerValue(value) resultArr.append(str) } sort() } /** * 更新单个字(词)的单个检索类型结果,存储更大的<br> * * @param str * 单个字(词)的单个检索类型结果 */ mutating public func updateTypeValue(_ str:SearchTypeResult) { if let index = resultArr.index(of: str) { if str > resultArr[index] { resultArr[index] = str } }else{ resultArr.append(str) } sort() } /** * 取得指定检索类别的匹配度<br> * * @param searchType * 检索类别 * @return 匹配度 */ public func getValue(_ searchType: SearchType) ->Double { if let index = getIndex(searchType) { return resultArr[index].value }else{ return 0 } } /** * 当相加的SearchKeyResult实例的key{@link #key}与当前相同时,<br> * 遍历全部的检索类别和值,进行更新{@link #updateBiggerValue(SearchType, double)}<br> * * @param skr * 单个字(词)的检索结果 * @return 键相同true否false */ mutating public func addSearchKeyResult(_ skr:SearchKeyResult) { for result in skr.searchTypeResults { updateTypeValue(result) } sort() } fileprivate func getIndex(_ searchType: SearchType) ->Int? { for (index, st) in resultArr.enumerated() { if st.searchType == searchType { return index } } return nil } mutating fileprivate func sort() { resultArr.sort(by: >) } } public func ==(lhs: SearchKeyResult, rhs: SearchKeyResult) -> Bool { return (lhs.hasFullMatching == rhs.hasFullMatching) && (lhs.totalValue == rhs.totalValue) } public func <(lhs: SearchKeyResult, rhs: SearchKeyResult) -> Bool { if lhs.hasFullMatching != rhs.hasFullMatching { return lhs.hasFullMatching ? false : true } else { return lhs.totalValue < rhs.totalValue } }
mit
e3085d10a26e96b7ce64075f5de3dffd
21.989305
94
0.529425
4.078748
false
false
false
false
doncl/shortness-of-pants
BBPDropDown/BBPDropDown/ViewController.swift
1
2287
// // ViewController.swift // BBPDropDown // // Created by Don Clore on 3/5/16. // Copyright © 2016 Beer Barrel Poker Studios. All rights reserved. // import Foundation import UIKit import Darwin class ViewController: UIViewController, BBPDropDownDelegate { let data = ["Beatles", "Rolling Stones", "Jimi Hendrix", "King Crimson", "Emerson, Lake and Palmer", "Gentle Giant", "Yes", "Jethro Tull", "Genesis", "The Grateful Dead", "Jefferson Airplane"] var dropDownPopup: BBPDropDownPopup? @IBOutlet var selectedBandNames : UILabel! @IBOutlet var bbpDropDownSingle: BBPDropdown! @IBOutlet var bbpDropDownSingleHeightConstraint: NSLayoutConstraint! @IBOutlet var bbpDropDownMulti: BBPDropdown! @IBOutlet var bbpDropDownMultiHeightConstraint: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() bbpDropDownMulti.delegate = self bbpDropDownMulti.data = data bbpDropDownMulti.isMultiple = true bbpDropDownSingle.delegate = self bbpDropDownSingle.data = data bbpDropDownSingle.isMultiple = false } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) bbpDropDownMulti.readjustHeight() bbpDropDownSingle.readjustHeight() } // MARK: - BBPDropDownDelegate implementation func requestNewHeight(_ dropDown: BBPDropdown, newHeight: CGFloat) { UIView.animate(withDuration: 0.6, delay:0.2, options:UIView.AnimationOptions(), animations: { if dropDown === self.bbpDropDownMulti { self.bbpDropDownMultiHeightConstraint.constant = newHeight } else { self.bbpDropDownSingleHeightConstraint.constant = newHeight } }, completion: nil) } func dropDownView(_ dropDown: BBPDropdown, didSelectedItem item: String) { // DO nothing for this example. print("single select item selected \(item)") } func dropDownView(_ dropDown: BBPDropdown, dataList: [String]) { // DO nothing for this example. print("multi-select items selected \(dataList)") } func dropDownWillAppear(_ dropDown: BBPDropdown) { print("dropdown will appear") } }
mit
386983133b6a90373b5ff750d4b4c9a1
30.75
101
0.671916
4.969565
false
false
false
false
syd24/DouYuZB
DouYu/Pods/Kingfisher/Sources/Image.swift
2
29407
// // Image.swift // Kingfisher // // Created by Wei Wang on 16/1/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 public typealias Image = NSImage public typealias Color = NSColor private var imagesKey: Void? private var durationKey: Void? #else import UIKit import MobileCoreServices public typealias Image = UIImage public typealias Color = UIColor private var imageSourceKey: Void? private var animatedImageDataKey: Void? #endif import ImageIO import CoreGraphics #if !os(watchOS) import Accelerate import CoreImage #endif // MARK: - Image Properties extension Image { #if os(macOS) var cgImage: CGImage? { return cgImage(forProposedRect: nil, context: nil, hints: nil) } var kf_scale: CGFloat { return 1.0 } fileprivate(set) var kf_images: [Image]? { get { return objc_getAssociatedObject(self, &imagesKey) as? [Image] } set { objc_setAssociatedObject(self, &imagesKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } fileprivate(set) var kf_duration: TimeInterval { get { return objc_getAssociatedObject(self, &durationKey) as? TimeInterval ?? 0.0 } set { objc_setAssociatedObject(self, &durationKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } var kf_size: CGSize { return representations.reduce(CGSize.zero, { size, rep in return CGSize(width: max(size.width, CGFloat(rep.pixelsWide)), height: max(size.height, CGFloat(rep.pixelsHigh))) }) } #else var kf_scale: CGFloat { return scale } var kf_images: [Image]? { return images } var kf_duration: TimeInterval { return duration } fileprivate(set) var kf_imageSource: ImageSource? { get { return objc_getAssociatedObject(self, &imageSourceKey) as? ImageSource } set { objc_setAssociatedObject(self, &imageSourceKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } fileprivate(set) var kf_animatedImageData: Data? { get { return objc_getAssociatedObject(self, &animatedImageDataKey) as? Data } set { objc_setAssociatedObject(self, &animatedImageDataKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } var kf_size: CGSize { return size } #endif } // MARK: - Image Conversion extension Image { #if os(macOS) static func kf_image(cgImage: CGImage, scale: CGFloat, refImage: Image?) -> Image { return Image(cgImage: cgImage, size: CGSize.zero) } /** Normalize the image. This method does nothing in OS X. - returns: The image itself. */ public func kf_normalized() -> Image { return self } static func kf_animated(with images: [Image], forDuration forDurationduration: TimeInterval) -> Image? { return nil } #else static func kf_image(cgImage: CGImage, scale: CGFloat, refImage: Image?) -> Image { if let refImage = refImage { return Image(cgImage: cgImage, scale: scale, orientation: refImage.imageOrientation) } else { return Image(cgImage: cgImage, scale: scale, orientation: .up) } } /** Normalize the image. This method will try to redraw an image with orientation and scale considered. - returns: The normalized image with orientation set to up and correct scale. */ public func kf_normalized() -> Image { // prevent animated image (GIF) lose it's images guard images == nil else { return self } // No need to do anything if already up guard imageOrientation != .up else { return self } return draw(cgImage: nil, to: size) { draw(in: CGRect(origin: CGPoint.zero, size: size)) } } static func kf_animated(with images: [Image], forDuration duration: TimeInterval) -> Image? { return .animatedImage(with: images, duration: duration) } #endif } // MARK: - Image Representation extension Image { // MARK: - PNG func pngRepresentation() -> Data? { #if os(macOS) guard let cgimage = cgImage else { return nil } let rep = NSBitmapImageRep(cgImage: cgimage) return rep.representation(using: .PNG, properties: [:]) #else return UIImagePNGRepresentation(self) #endif } // MARK: - JPEG func jpegRepresentation(compressionQuality: CGFloat) -> Data? { #if os(macOS) guard let cgImage = cgImage else { return nil } let rep = NSBitmapImageRep(cgImage: cgImage) return rep.representation(using:.JPEG, properties: [NSImageCompressionFactor: compressionQuality]) #else return UIImageJPEGRepresentation(self, compressionQuality) #endif } // MARK: - GIF func gifRepresentation() -> Data? { #if os(macOS) return gifRepresentation(duration: 0.0, repeatCount: 0) #else return kf_animatedImageData #endif } #if os(macOS) func gifRepresentation(duration: TimeInterval, repeatCount: Int) -> Data? { guard let images = kf_images else { return nil } let frameCount = images.count let gifDuration = duration <= 0.0 ? kf_duration / Double(frameCount) : duration / Double(frameCount) let frameProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFDelayTime as String: gifDuration]] let imageProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFLoopCount as String: repeatCount]] let data = NSMutableData() guard let destination = CGImageDestinationCreateWithData(data, kUTTypeGIF, frameCount, nil) else { return nil } CGImageDestinationSetProperties(destination, imageProperties as CFDictionary) for image in images { CGImageDestinationAddImage(destination, image.cgImage!, frameProperties as CFDictionary) } return CGImageDestinationFinalize(destination) ? data.copy() as? Data : nil } #endif } // MARK: - Create images from data extension Image { static func kf_animated(with data: Data, scale: CGFloat = 1.0, duration: TimeInterval = 0.0, preloadAll: Bool) -> Image? { func decode(from imageSource: CGImageSource, for options: NSDictionary) -> ([Image], TimeInterval)? { //Calculates frame duration for a gif frame out of the kCGImagePropertyGIFDictionary dictionary func frameDuration(from gifInfo: NSDictionary) -> Double { let gifDefaultFrameDuration = 0.100 let unclampedDelayTime = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as? NSNumber let delayTime = gifInfo[kCGImagePropertyGIFDelayTime as String] as? NSNumber let duration = unclampedDelayTime ?? delayTime guard let frameDuration = duration else { return gifDefaultFrameDuration } return frameDuration.doubleValue > 0.011 ? frameDuration.doubleValue : gifDefaultFrameDuration } let frameCount = CGImageSourceGetCount(imageSource) var images = [Image]() var gifDuration = 0.0 for i in 0 ..< frameCount { guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, i, options) else { return nil } if frameCount == 1 { // Single frame gifDuration = Double.infinity } else { // Animated GIF guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil), let gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary else { return nil } gifDuration += frameDuration(from: gifInfo) } images.append(Image.kf_image(cgImage: imageRef, scale: scale, refImage: nil)) } return (images, gifDuration) } // Start of kf_animatedImageWithGIFData let options: NSDictionary = [kCGImageSourceShouldCache as String: true, kCGImageSourceTypeIdentifierHint as String: kUTTypeGIF] guard let imageSource = CGImageSourceCreateWithData(data as CFData, options) else { return nil } #if os(macOS) guard let (images, gifDuration) = decode(from: imageSource, for: options) else { return nil } let image = Image(data: data) image?.kf_images = images image?.kf_duration = gifDuration return image #else if preloadAll { guard let (images, gifDuration) = decode(from: imageSource, for: options) else { return nil } let image = Image.kf_animated(with: images, forDuration: duration <= 0.0 ? gifDuration : duration) image?.kf_animatedImageData = data return image } else { let image = Image(data: data) image?.kf_animatedImageData = data image?.kf_imageSource = ImageSource(ref: imageSource) return image } #endif } static func kf_image(data: Data, scale: CGFloat, preloadAllGIFData: Bool) -> Image? { var image: Image? #if os(macOS) switch data.kf_imageFormat { case .JPEG: image = Image(data: data) case .PNG: image = Image(data: data) case .GIF: image = Image.kf_animated(with: data, scale: scale, duration: 0.0, preloadAll: preloadAllGIFData) case .unknown: image = Image(data: data) } #else switch data.kf_imageFormat { case .JPEG: image = Image(data: data, scale: scale) case .PNG: image = Image(data: data, scale: scale) case .GIF: image = Image.kf_animated(with: data, scale: scale, duration: 0.0, preloadAll: preloadAllGIFData) case .unknown: image = Image(data: data, scale: scale) } #endif return image } } // MARK: - Image Transforming extension Image { // MARK: - Round Corner /// Create a round corner image based on `self`. /// /// - parameter radius: The round corner radius of creating image. /// - parameter size: The target size of creating image. /// - parameter scale: The image scale of creating image. /// /// - returns: An image with round corner of `self`. /// /// - Note: This method only works for CG-based image. public func kf_image(withRoundRadius radius: CGFloat, fit size: CGSize, scale: CGFloat) -> Image { guard let cgImage = cgImage else { assertionFailure("[Kingfisher] Round corder image only works for CG-based image.") return self } let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size) return draw(cgImage: cgImage, to: size) { #if os(macOS) let path = NSBezierPath(roundedRect: rect, xRadius: radius, yRadius: radius) path.windingRule = .evenOddWindingRule path.addClip() draw(in: rect) #else guard let context = UIGraphicsGetCurrentContext() else { assertionFailure("[Kingfisher] Failed to create CG context for image.") return } let path = UIBezierPath(roundedRect: rect, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: radius, height: radius)).cgPath context.addPath(path) context.clip() draw(in: rect) #endif } } #if os(iOS) || os(tvOS) func kf_resize(to size: CGSize, for contentMode: UIViewContentMode) -> Image { switch contentMode { case .scaleAspectFit: let newSize = self.size.kf_constrained(size) return kf_resize(to: newSize) case .scaleAspectFill: let newSize = self.size.kf_filling(size) return kf_resize(to: newSize) default: return kf_resize(to: size) } } #endif // MARK: - Resize /// Resize `self` to an image of new size. /// /// - parameter size: The target size. /// /// - returns: An image with new size. /// /// - Note: This method only works for CG-based image. public func kf_resize(to size: CGSize) -> Image { guard let cgImage = cgImage?.fixed else { assertionFailure("[Kingfisher] Resize only works for CG-based image.") return self } let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size) return draw(cgImage: cgImage, to: size) { #if os(macOS) draw(in: rect, from: NSRect.zero, operation: .copy, fraction: 1.0) #else draw(in: rect) #endif } } // MARK: - Blur /// Create an image with blur effect based on `self`. /// /// - parameter radius: The blur radius should be used when creating blue. /// /// - returns: An image with blur effect applied. /// /// - Note: This method only works for CG-based image. public func kf_blurred(withRadius radius: CGFloat) -> Image { #if os(watchOS) return self #else guard let cgImage = cgImage else { assertionFailure("[Kingfisher] Blur only works for CG-based image.") return self } // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5) // if d is odd, use three box-blurs of size 'd', centered on the output pixel. let s = max(radius, 2.0) // We will do blur on a resized image (*0.5), so the blur radius could be half as well. var targetRadius = floor((Double(s * 3.0) * sqrt(2 * M_PI) / 4.0 + 0.5)) if targetRadius.isEven { targetRadius += 1 } let iterations: Int if radius < 0.5 { iterations = 1 } else if radius < 1.5 { iterations = 2 } else { iterations = 3 } let w = Int(kf_size.width) let h = Int(kf_size.height) let rowBytes = Int(CGFloat(cgImage.bytesPerRow)) let inDataPointer = UnsafeMutablePointer<UInt8>.allocate(capacity: rowBytes * Int(h)) inDataPointer.initialize(to: 0) defer { inDataPointer.deinitialize() inDataPointer.deallocate(capacity: rowBytes * Int(h)) } let bitmapInfo = cgImage.bitmapInfo.fixed guard let context = CGContext(data: inDataPointer, width: w, height: h, bitsPerComponent: cgImage.bitsPerComponent, bytesPerRow: rowBytes, space: cgImage.colorSpace ?? CGColorSpaceCreateDeviceRGB(), bitmapInfo: bitmapInfo.rawValue) else { assertionFailure("[Kingfisher] Failed to create CG context for blurring image.") return self } context.draw(cgImage, in: CGRect(x: 0, y: 0, width: w, height: h)) var inBuffer = vImage_Buffer(data: inDataPointer, height: vImagePixelCount(h), width: vImagePixelCount(w), rowBytes: rowBytes) let outDataPointer = UnsafeMutablePointer<UInt8>.allocate(capacity: rowBytes * Int(h)) outDataPointer.initialize(to: 0) defer { outDataPointer.deinitialize() outDataPointer.deallocate(capacity: rowBytes * Int(h)) } var outBuffer = vImage_Buffer(data: outDataPointer, height: vImagePixelCount(h), width: vImagePixelCount(w), rowBytes: rowBytes) for _ in 0 ..< iterations { vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, nil, 0, 0, UInt32(targetRadius), UInt32(targetRadius), nil, vImage_Flags(kvImageEdgeExtend)) (inBuffer, outBuffer) = (outBuffer, inBuffer) } guard let outContext = CGContext(data: inDataPointer, width: w, height: h, bitsPerComponent: cgImage.bitsPerComponent, bytesPerRow: rowBytes, space: cgImage.colorSpace ?? CGColorSpaceCreateDeviceRGB(), bitmapInfo: bitmapInfo.rawValue) else { assertionFailure("[Kingfisher] Failed to create CG context for blurring image.") return self } #if os(macOS) let result = outContext.makeImage().flatMap { kf_fixedForRetinaPixel(cgImage: $0, to: kf_size) } #else let result = outContext.makeImage().flatMap { Image(cgImage: $0) } #endif guard let blurredImage = result else { assertionFailure("[Kingfisher] Can not make an blurred image within this context.") return self } return blurredImage #endif } // MARK: - Overlay /// Create an image from `self` with a color overlay layer. /// /// - parameter color: The color should be use to overlay. /// - parameter fraction: Fraction of input color. From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay. /// /// - returns: An image with a color overlay applied. /// /// - Note: This method only works for CG-based image. public func kf_overlaying(with color: Color, fraction: CGFloat) -> Image { guard let cgImage = cgImage?.fixed else { assertionFailure("[Kingfisher] Overlaying only works for CG-based image.") return self } let rect = CGRect(x: 0, y: 0, width: kf_size.width, height: kf_size.height) return draw(cgImage: cgImage, to: rect.size) { #if os(macOS) draw(in: rect) if fraction > 0 { color.withAlphaComponent(1 - fraction).set() NSRectFillUsingOperation(rect, .sourceAtop) } #else color.set() UIRectFill(rect) draw(in: rect, blendMode: .destinationIn, alpha: 1.0) if fraction > 0 { draw(in: rect, blendMode: .sourceAtop, alpha: fraction) } #endif } } // MARK: - Tint /// Create an image from `self` with a color tint. /// /// - parameter color: The color should be used to tint `self` /// /// - returns: An image with a color tint applied. public func kf_tinted(with color: Color) -> Image { #if os(watchOS) return self #else return kf_apply(.tint(color)) #endif } // MARK: - Color Control /// Create an image from `self` with color control. /// /// - parameter brightness: Brightness changing to image. /// - parameter contrast: Contrast changing to image. /// - parameter saturation: Saturation changing to image. /// - parameter inputEV: InputEV changing to image. /// /// - returns: An image with color control applied. public func kf_adjusted(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) -> Image { #if os(watchOS) return self #else return kf_apply(.colorControl(brightness, contrast, saturation, inputEV)) #endif } } // MARK: - Decode extension Image { func kf_decoded() -> Image? { return self.kf_decoded(scale: kf_scale) } func kf_decoded(scale: CGFloat) -> Image { // prevent animated image (GIF) lose it's images #if os(iOS) if kf_imageSource != nil { return self } #else if kf_images != nil { return self } #endif guard let imageRef = self.cgImage else { assertionFailure("[Kingfisher] Decoding only works for CG-based image.") return self } let colorSpace = CGColorSpaceCreateDeviceRGB() let bitmapInfo = imageRef.bitmapInfo.fixed guard let context = CGContext(data: nil, width: imageRef.width, height: imageRef.height, bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue) else { assertionFailure("[Kingfisher] Decoding fails to create a valid context.") return self } let rect = CGRect(x: 0, y: 0, width: imageRef.width, height: imageRef.height) context.draw(imageRef, in: rect) let decompressedImageRef = context.makeImage() return Image.kf_image(cgImage: decompressedImageRef!, scale: scale, refImage: self) } } /// Reference the source image reference class ImageSource { var imageRef: CGImageSource? init(ref: CGImageSource) { self.imageRef = ref } } // MARK: - Image format private struct ImageHeaderData { static var PNG: [UInt8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A] static var JPEG_SOI: [UInt8] = [0xFF, 0xD8] static var JPEG_IF: [UInt8] = [0xFF] static var GIF: [UInt8] = [0x47, 0x49, 0x46] } enum ImageFormat { case unknown, PNG, JPEG, GIF } // MARK: - Misc Helpers extension Data { var kf_imageFormat: ImageFormat { var buffer = [UInt8](repeating: 0, count: 8) (self as NSData).getBytes(&buffer, length: 8) if buffer == ImageHeaderData.PNG { return .PNG } else if buffer[0] == ImageHeaderData.JPEG_SOI[0] && buffer[1] == ImageHeaderData.JPEG_SOI[1] && buffer[2] == ImageHeaderData.JPEG_IF[0] { return .JPEG } else if buffer[0] == ImageHeaderData.GIF[0] && buffer[1] == ImageHeaderData.GIF[1] && buffer[2] == ImageHeaderData.GIF[2] { return .GIF } return .unknown } } extension CGSize { func kf_constrained(_ size: CGSize) -> CGSize { let aspectWidth = round(kf_aspectRatio * size.height) let aspectHeight = round(size.width / kf_aspectRatio) return aspectWidth > size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height) } func kf_filling(_ size: CGSize) -> CGSize { let aspectWidth = round(kf_aspectRatio * size.height) let aspectHeight = round(size.width / kf_aspectRatio) return aspectWidth < size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height) } private var kf_aspectRatio: CGFloat { return height == 0.0 ? 1.0 : width / height } } extension CGImage { var isARGB8888: Bool { return bitsPerPixel == 32 && bitsPerComponent == 8 && bitmapInfo.contains(.alphaInfoMask) } var fixed: CGImage { if isARGB8888 { return self } // Convert to ARGB if it isn't guard let context = CGContext.createARGBContext(from: self) else { assertionFailure("[Kingfisher] Failed to create CG context when converting non ARGB image.") return self } context.draw(self, in: CGRect(x: 0, y: 0, width: width, height: height)) guard let r = context.makeImage() else { assertionFailure("[Kingfisher] Failed to create CG image when converting non ARGB image.") return self } return r } } extension CGBitmapInfo { var fixed: CGBitmapInfo { var fixed = self let alpha = (rawValue & CGBitmapInfo.alphaInfoMask.rawValue) if alpha == CGImageAlphaInfo.none.rawValue { fixed.remove(.alphaInfoMask) fixed = CGBitmapInfo(rawValue: fixed.rawValue | CGImageAlphaInfo.noneSkipFirst.rawValue) } else if !(alpha == CGImageAlphaInfo.noneSkipFirst.rawValue) || !(alpha == CGImageAlphaInfo.noneSkipLast.rawValue) { fixed.remove(.alphaInfoMask) fixed = CGBitmapInfo(rawValue: fixed.rawValue | CGImageAlphaInfo.premultipliedFirst.rawValue) } return fixed } } extension Image { func draw(cgImage: CGImage?, to size: CGSize, draw: ()->()) -> Image { #if os(macOS) guard let rep = NSBitmapImageRep( bitmapDataPlanes: nil, pixelsWide: Int(size.width), pixelsHigh: Int(size.height), bitsPerSample: cgImage?.bitsPerComponent ?? 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSCalibratedRGBColorSpace, bytesPerRow: 0, bitsPerPixel: 0) else { assertionFailure("[Kingfisher] Image representation cannot be created.") return self } rep.size = size NSGraphicsContext.saveGraphicsState() let context = NSGraphicsContext(bitmapImageRep: rep) NSGraphicsContext.setCurrent(context) draw() NSGraphicsContext.restoreGraphicsState() let outputImage = Image(size: size) outputImage.addRepresentation(rep) return outputImage #else UIGraphicsBeginImageContextWithOptions(size, false, scale) defer { UIGraphicsEndImageContext() } draw() return UIGraphicsGetImageFromCurrentImageContext() ?? self #endif } #if os(macOS) func kf_fixedForRetinaPixel(cgImage: CGImage, to size: CGSize) -> Image { let image = Image(cgImage: cgImage, size: self.size) let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size) return draw(cgImage: cgImage, to: kf_size) { image.draw(in: rect, from: NSRect.zero, operation: .copy, fraction: 1.0) } } #endif } extension CGContext { static func createARGBContext(from imageRef: CGImage) -> CGContext? { let w = imageRef.width let h = imageRef.height let bytesPerRow = w * 4 let colorSpace = CGColorSpaceCreateDeviceRGB() let data = malloc(bytesPerRow * h) defer { free(data) } let bitmapInfo = imageRef.bitmapInfo.fixed // Create the bitmap context. We want pre-multiplied ARGB, 8-bits // per component. Regardless of what the source image format is // (CMYK, Grayscale, and so on) it will be converted over to the format // specified here. return CGContext(data: data, width: w, height: h, bitsPerComponent: imageRef.bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo.rawValue) } } extension Double { var isEven: Bool { return truncatingRemainder(dividingBy: 2.0) == 0 } }
mit
c176c71ca3125557b0e79b36fca0979e
34.558646
192
0.57806
4.893012
false
false
false
false
theMatys/myWatch
myWatch/Source/UI/Controllers/First Launch/MWAppleHealthViewController.swift
1
2892
// // MWAppleHealthViewController.swift // myWatch // // Created by Máté on 2017. 07. 16. // Copyright © 2017. theMatys. All rights reserved. // import UIKit /// A view controller which asks the user to enable/disable exporting application data to Apple Health. class MWAppleHealthViewController: MWViewController { //MARK: Outlets @IBOutlet weak var labelTitle: UILabel! @IBOutlet weak var labelDescription: UILabel! @IBOutlet weak var labelDescription_1: UILabel! @IBOutlet weak var labelDescription_2: UILabel! @IBOutlet weak var buttonYes: MWButton! @IBOutlet weak var buttonNo: MWButton! //MARK: Instance variables private var navigationBarTintColor: UIColor? //MARK: - Inherited funtions from: MWViewController override func viewDidLoad() { super.viewDidLoad() //Check if the controller has a navigation controller self.navigationController ?! { //Store the navigation bar's tint color navigationBarTintColor = self.navigationController!.navigationBar.tintColor } } override func viewWillAppear(_ animated: Bool) { //Supercall super.viewWillAppear(animated) //Check if we have a stored navigation bar tint color navigationBarTintColor ?! { UIView.transition(with: self.navigationController!.navigationBar, duration: 0.2, options: .transitionCrossDissolve, animations: { //Set a custom navigation bar tint color self.navigationController!.navigationBar.tintColor = self.labelTitle.textColor }, completion: nil) } } override func viewWillDisappear(_ animated: Bool) { //Supercall super.viewWillDisappear(animated) //Check if we have a stored navigation bar tint color navigationBarTintColor ?! { UIView.transition(with: self.navigationController!.navigationBar, duration: 0.2, options: .transitionCrossDissolve, animations: { //Restore the navigation bar's tint color self.navigationController!.navigationBar.tintColor = self.navigationBarTintColor! }, completion: nil) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } //MARK: Action functions @IBAction func buttonPressed_buttonYes(_ sender: MWButton) { MWSettings.shared.exportToAppleHealth = true self.performSegue(withIdentifier: MWIdentifiers.SegueIdentifiers.appleHealthToFirstLaunchLast, sender: self) } @IBAction func buttonPressed_buttonNo(_ sender: MWButton) { MWSettings.shared.exportToAppleHealth = false self.performSegue(withIdentifier: MWIdentifiers.SegueIdentifiers.appleHealthToFirstLaunchLast, sender: self) } }
gpl-3.0
fd997dd0d87d93101db3c14c1655ba2e
33.807229
142
0.674628
5.35
false
false
false
false
takev/DimensionsCAM
DimensionsCAM/Tetrahedron.swift
1
2658
// DimensionsCAM - A multi-axis tool path generator for a milling machine // Copyright (C) 2015 Take Vos // // 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/>. /// A /// /.\ /// / . \ /// / . \ /// / . \ /// / . \ /// / . \ /// / . \ /// / . D . \ /// / . . \ /// / . . \ /// / . . \ /// / . . \ /// /. .\ /// B --------------------------- C /// /// /// class Tetrahedron: CollectionType, Hashable { typealias Index = Int typealias Element = Vector3Fix10 let A: Vector3Fix10 let B: Vector3Fix10 let C: Vector3Fix10 let D: Vector3Fix10 var a: Triangle { return Triangle(D, C, B) } var b: Triangle { return Triangle(A, C, D) } var c: Triangle { return Triangle(A, D, B) } var d: Triangle { return Triangle(A, B, C) } var triangles: [Triangle] { return [a, b, c, d] } var centroid: Vector3Fix10 { return (A + B + C + D) / 4 } var count: Int { return 4 } var endIndex: Int { return 4 } var startIndex: Int { return 0 } var isEmpty: Bool { return false } var id: UInt64 { return centroid.id } var hashValue: Int { return id.hashValue } init(_ A: Vector3Fix10, _ B: Vector3Fix10, _ C: Vector3Fix10, _ D: Vector3Fix10) { self.A = A self.B = B self.C = C self.D = D } subscript(index: Int) -> Vector3Fix10 { switch index { case 0: return A case 1: return B case 2: return C case 3: return D default: preconditionFailure("Triangle only has three vertice.") } } } func ==(lhs: Tetrahedron, rhs: Tetrahedron) -> Bool { return lhs.id == rhs.id }
gpl-3.0
fb197af1b2ffb321919f165d9923ac38
31.814815
86
0.494733
3.791726
false
false
false
false
vczhou/flicks
Flicks/AppDelegate.swift
1
3547
// // AppDelegate.swift // Flicks // // Created by Victoria Zhou on 1/28/17. // Copyright (c) 2017 Victoria Zhou. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. window = UIWindow(frame: UIScreen.main.bounds) let storyboard = UIStoryboard(name: "Main", bundle: nil) let nowPlayingNavigationController = storyboard.instantiateViewController(withIdentifier: "MoviesNavigationController") as! UINavigationController let nowPlayingViewController = nowPlayingNavigationController.topViewController as! MoviesViewController nowPlayingViewController.endPoint = "now_playing" nowPlayingNavigationController.tabBarItem.title = "Now Playing" nowPlayingNavigationController.tabBarItem.image = UIImage(named: "nowPlaying") let topRatedNavigationController = storyboard.instantiateViewController(withIdentifier: "MoviesNavigationController") as! UINavigationController let topRatedViewController = topRatedNavigationController.topViewController as! MoviesViewController topRatedViewController.endPoint = "top_rated" topRatedNavigationController.tabBarItem.title = "Top Rated" topRatedNavigationController.tabBarItem.image = UIImage(named: "topRated") let tabBarController = UITabBarController() tabBarController.viewControllers = [nowPlayingNavigationController, topRatedNavigationController] window?.rootViewController = tabBarController window?.makeKeyAndVisible() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
apache-2.0
1d6b535e92793d0376464e3cc40d0404
51.161765
285
0.751621
6.07363
false
false
false
false
ajthom90/FontAwesome.swift
FontAwesomeTests/FontAwesomeTests.swift
1
3141
// FontAwesomeTests.swift // // Copyright (c) 2014-present FontAwesome.swift contributors // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import XCTest @testable import FontAwesome class FontAwesomeTests: XCTestCase { func testIconFontShouldBeRegisted() { let label = UILabel() label.font = UIFont.fontAwesome(ofSize: 200) XCTAssertNotNil(label.font, "Icon font should not be nil.") } func testLabelText() { let label = UILabel() label.font = UIFont.fontAwesome(ofSize: 200) label.text = String.fontAwesomeIcon(name: FontAwesome.github) XCTAssertEqual(label.text, "\u{f09b}") } func testLabelTextFromCode() { let label = UILabel() label.font = UIFont.fontAwesome(ofSize: 200) label.text = String.fontAwesomeIcon(code: "fa-github") XCTAssertEqual(label.text, "\u{f09b}") } func testButtonTitle() { let button = UIButton() button.titleLabel?.font = UIFont.fontAwesome(ofSize: 30) button.setTitle(String.fontAwesomeIcon(name: .github), for: UIControlState()) XCTAssertEqual(button.titleLabel?.text, "\u{f09b}") } func testBarItemTitle() { let barItem = UIBarButtonItem() let attributes = [NSAttributedStringKey.font: UIFont.fontAwesome(ofSize: 20)] as Dictionary! barItem.setTitleTextAttributes(attributes, for: UIControlState()) barItem.title = String.fontAwesomeIcon(name: .github) XCTAssertEqual(barItem.title, "\u{f09b}") } func testIconImage() { let barItem = UIBarButtonItem() barItem.image = UIImage.fontAwesomeIcon(name: FontAwesome.github, textColor: UIColor.blue, size: CGSize(width: 4000, height: 4000), backgroundColor: UIColor.red) XCTAssertNotNil(barItem.image) } func testIconImageFromCode() { let barItem = UIBarButtonItem() barItem.image = UIImage.fontAwesomeIcon(code: "fa-github", textColor: UIColor.blue, size: CGSize(width: 4000, height: 4000), backgroundColor: UIColor.red) XCTAssertNotNil(barItem.image) } }
mit
e688ab791bc7dd620249daf910ef4b7d
40.88
169
0.7071
4.545586
false
true
false
false
callam/Moya
Demo/Tests/Observable+MoyaSpec.swift
4
11132
import Quick import Moya import RxSwift import Nimble #if os(iOS) || os(watchOS) || os(tvOS) private func ImageJPEGRepresentation(image: ImageType, _ compression: CGFloat) -> NSData? { return UIImageJPEGRepresentation(image, compression) } #elseif os(OSX) private func ImageJPEGRepresentation(image: ImageType, _ compression: CGFloat) -> NSData? { var imageRect: CGRect = CGRectMake(0, 0, image.size.width, image.size.height) let imageRep = NSBitmapImageRep(CGImage: image.CGImageForProposedRect(&imageRect, context: nil, hints: nil)!) return imageRep.representationUsingType(.NSJPEGFileType, properties:[:]) } #endif // Necessary since Image(named:) doesn't work correctly in the test bundle private extension ImageType { class func testPNGImage(named name: String) -> ImageType { class TestClass { } let bundle = NSBundle(forClass: TestClass().dynamicType) let path = bundle.pathForResource(name, ofType: "png") return Image(contentsOfFile: path!)! } } private func observableSendingData(data: NSData, statusCode: Int = 200) -> Observable<Response> { return Observable.just(Response(statusCode: statusCode, data: data, response: nil)) } class ObservableMoyaSpec: QuickSpec { override func spec() { describe("status codes filtering") { it("filters out unrequested status codes") { let data = NSData() let observable = observableSendingData(data, statusCode: 10) var errored = false _ = observable.filterStatusCodes(0...9).subscribe { (event) -> Void in switch event { case .Next(let object): fail("called on non-correct status code: \(object)") case .Error: errored = true default: break } } expect(errored).to(beTruthy()) } it("filters out non-successful status codes") { let data = NSData() let observable = observableSendingData(data, statusCode: 404) var errored = false _ = observable.filterSuccessfulStatusCodes().subscribe { (event) -> Void in switch event { case .Next(let object): fail("called on non-success status code: \(object)") case .Error: errored = true default: break } } expect(errored).to(beTruthy()) } it("passes through correct status codes") { let data = NSData() let observable = observableSendingData(data) var called = false _ = observable.filterSuccessfulStatusCodes().subscribeNext { (object) -> Void in called = true } expect(called).to(beTruthy()) } it("filters out non-successful status and redirect codes") { let data = NSData() let observable = observableSendingData(data, statusCode: 404) var errored = false _ = observable.filterSuccessfulStatusAndRedirectCodes().subscribe { (event) -> Void in switch event { case .Next(let object): fail("called on non-success status code: \(object)") case .Error: errored = true default: break } } expect(errored).to(beTruthy()) } it("passes through correct status codes") { let data = NSData() let observable = observableSendingData(data) var called = false _ = observable.filterSuccessfulStatusAndRedirectCodes().subscribeNext { (object) -> Void in called = true } expect(called).to(beTruthy()) } it("passes through correct redirect codes") { let data = NSData() let observable = observableSendingData(data, statusCode: 304) var called = false _ = observable.filterSuccessfulStatusAndRedirectCodes().subscribeNext { (object) -> Void in called = true } expect(called).to(beTruthy()) } it("knows how to filter individual status code") { let data = NSData() let observable = observableSendingData(data, statusCode: 42) var called = false _ = observable.filterStatusCode(42).subscribeNext { (object) -> Void in called = true } expect(called).to(beTruthy()) } it("filters out different individual status code") { let data = NSData() let observable = observableSendingData(data, statusCode: 43) var errored = false _ = observable.filterStatusCode(42).subscribe { (event) -> Void in switch event { case .Next(let object): fail("called on non-success status code: \(object)") case .Error: errored = true default: break } } expect(errored).to(beTruthy()) } } describe("image maping") { it("maps data representing an image to an image") { let image = Image.testPNGImage(named: "testImage") let data = ImageJPEGRepresentation(image, 0.75) let observable = observableSendingData(data!) var size: CGSize? _ = observable.mapImage().subscribeNext { (image) -> Void in size = image.size } expect(size).to(equal(image.size)) } it("ignores invalid data") { let data = NSData() let observable = observableSendingData(data) var receivedError: Error? _ = observable.mapImage().subscribe { (event) -> Void in switch event { case .Next: fail("next called for invalid data") case .Error(let error): receivedError = error as? Error default: break } } expect(receivedError).toNot(beNil()) let expectedError = Error.ImageMapping(Response(statusCode: 200, data: NSData(), response: nil)) expect(receivedError).to(beOfSameErrorType(expectedError)) } } describe("JSON mapping") { it("maps data representing some JSON to that JSON") { let json = ["name": "John Crighton", "occupation": "Astronaut"] let data = try! NSJSONSerialization.dataWithJSONObject(json, options: .PrettyPrinted) let observable = observableSendingData(data) var receivedJSON: [String: String]? _ = observable.mapJSON().subscribeNext { (json) -> Void in if let json = json as? [String: String] { receivedJSON = json } } expect(receivedJSON?["name"]).to(equal(json["name"])) expect(receivedJSON?["occupation"]).to(equal(json["occupation"])) } it("returns a Cocoa error domain for invalid JSON") { let json = "{ \"name\": \"john }" let data = json.dataUsingEncoding(NSUTF8StringEncoding) let observable = observableSendingData(data!) var receivedError: Error? _ = observable.mapJSON().subscribe { (event) -> Void in switch event { case .Next: fail("next called for invalid data") case .Error(let error): receivedError = error as? Error default: break } } expect(receivedError).toNot(beNil()) switch receivedError { case .Some(.Underlying(let error as NSError)): expect(error.domain).to(equal("\(NSCocoaErrorDomain)")) default: fail("expected NSError with \(NSCocoaErrorDomain) domain") } } } describe("string mapping") { it("maps data representing a string to a string") { let string = "You have the rights to the remains of a silent attorney." let data = string.dataUsingEncoding(NSUTF8StringEncoding) let observable = observableSendingData(data!) var receivedString: String? _ = observable.mapString().subscribeNext { (string) -> Void in receivedString = string } expect(receivedString).to(equal(string)) } it("ignores invalid data") { let data = NSData(bytes: [0x11FFFF] as [UInt32], length: 1) //Byte exceeding UTF8 let observable = observableSendingData(data) var receivedError: Error? _ = observable.mapString().subscribe { (event) -> Void in switch event { case .Next: fail("next called for invalid data") case .Error(let error): receivedError = error as? Error default: break } } expect(receivedError).toNot(beNil()) let expectedError = Error.StringMapping(Response(statusCode: 200, data: NSData(), response: nil)) expect(receivedError).to(beOfSameErrorType(expectedError)) } } } }
mit
d96f9f54952ab4b7274a30154c882626
39.187726
117
0.470805
6.29638
false
false
false
false
diegosanchezr/Chatto
ChattoAdditions/Source/Chat Items/BaseMessage/Views/BaseMessageCollectionViewCellDefaultSyle.swift
1
3305
/* The MIT License (MIT) Copyright (c) 2015-present Badoo Trading Limited. 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 BaseMessageCollectionViewCellDefaultSyle: BaseMessageCollectionViewCellStyleProtocol { public init () {} lazy var baseColorIncoming = UIColor.bma_color(rgb: 0xE6ECF2) lazy var baseColorOutgoing = UIColor.bma_color(rgb: 0x3D68F5) lazy var borderIncomingTail: UIImage = { return UIImage(named: "bubble-incoming-border-tail", inBundle: NSBundle(forClass: self.dynamicType), compatibleWithTraitCollection: nil)! }() lazy var borderIncomingNoTail: UIImage = { return UIImage(named: "bubble-incoming-border", inBundle: NSBundle(forClass: self.dynamicType), compatibleWithTraitCollection: nil)! }() lazy var borderOutgoingTail: UIImage = { return UIImage(named: "bubble-outgoing-border-tail", inBundle: NSBundle(forClass: self.dynamicType), compatibleWithTraitCollection: nil)! }() lazy var borderOutgoingNoTail: UIImage = { return UIImage(named: "bubble-outgoing-border", inBundle: NSBundle(forClass: self.dynamicType), compatibleWithTraitCollection: nil)! }() public lazy var failedIcon: UIImage = { return UIImage(named: "base-message-failed-icon", inBundle: NSBundle(forClass: self.dynamicType), compatibleWithTraitCollection: nil)! }() public lazy var failedIconHighlighted: UIImage = { return self.failedIcon.bma_blendWithColor(UIColor.blackColor().colorWithAlphaComponent(0.10)) }() private lazy var dateFont = { return UIFont.systemFontOfSize(12.0) }() public func attributedStringForDate(date: String) -> NSAttributedString { let attributes = [NSFontAttributeName : self.dateFont] return NSAttributedString(string: date, attributes: attributes) } func borderImage(viewModel viewModel: MessageViewModelProtocol) -> UIImage? { switch (viewModel.isIncoming, viewModel.showsTail) { case (true, true): return self.borderIncomingTail case (true, false): return self.borderIncomingNoTail case (false, true): return self.borderOutgoingTail case (false, false): return self.borderOutgoingNoTail } } }
mit
caed814d5a546a1d1a02ac82a33e2453
40.835443
145
0.732224
4.860294
false
false
false
false
diegosanchezr/Chatto
Chatto/Source/ChatController/ChatViewController.swift
1
13054
/* The MIT License (MIT) Copyright (c) 2015-present Badoo Trading Limited. 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 protocol ChatItemsDecoratorProtocol { func decorateItems(chatItems: [ChatItemProtocol]) -> [DecoratedChatItem] } public struct DecoratedChatItem { public let chatItem: ChatItemProtocol public let decorationAttributes: ChatItemDecorationAttributesProtocol? public init(chatItem: ChatItemProtocol, decorationAttributes: ChatItemDecorationAttributesProtocol?) { self.chatItem = chatItem self.decorationAttributes = decorationAttributes } } public class ChatViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate { public struct Constants { var updatesAnimationDuration: NSTimeInterval = 0.33 var defaultContentInsets = UIEdgeInsets(top: 10, left: 0, bottom: 10, right: 0) var defaultScrollIndicatorInsets = UIEdgeInsetsZero var preferredMaxMessageCount: Int? = 500 // It not nil, will ask data source to reduce number of messages when limit is reached. @see ChatDataSourceDelegateProtocol var preferredMaxMessageCountAdjustment: Int = 400 // When the above happens, will ask to adjust with this value. It may be wise for this to be smaller to reduce number of adjustments var autoloadingFractionalThreshold: CGFloat = 0.05 // in [0, 1] } public var constants = Constants() public private(set) var collectionView: UICollectionView! var decoratedChatItems = [DecoratedChatItem]() public var chatDataSource: ChatDataSourceProtocol? { didSet { self.chatDataSource?.delegate = self self.enqueueModelUpdate(context: .Reload) } } deinit { self.collectionView.delegate = nil self.collectionView.dataSource = nil } override public func viewDidLoad() { super.viewDidLoad() self.addCollectionView() self.addInputViews() } public override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.keyboardTracker.startTracking() } public override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) self.keyboardTracker.stopTracking() } private func addCollectionView() { self.collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: self.createCollectionViewLayout) self.collectionView.contentInset = self.constants.defaultContentInsets self.collectionView.scrollIndicatorInsets = self.constants.defaultScrollIndicatorInsets self.collectionView.alwaysBounceVertical = true self.collectionView.backgroundColor = UIColor.clearColor() self.collectionView.keyboardDismissMode = .Interactive self.collectionView.showsVerticalScrollIndicator = true self.collectionView.showsHorizontalScrollIndicator = false self.collectionView.allowsSelection = false self.collectionView.translatesAutoresizingMaskIntoConstraints = false self.collectionView.autoresizingMask = .None self.view.addSubview(self.collectionView) self.view.addConstraint(NSLayoutConstraint(item: self.view, attribute: .Top, relatedBy: .Equal, toItem: self.collectionView, attribute: .Top, multiplier: 1, constant: 0)) self.view.addConstraint(NSLayoutConstraint(item: self.view, attribute: .Leading, relatedBy: .Equal, toItem: self.collectionView, attribute: .Leading, multiplier: 1, constant: 0)) self.view.addConstraint(NSLayoutConstraint(item: self.view, attribute: .Bottom, relatedBy: .Equal, toItem: self.collectionView, attribute: .Bottom, multiplier: 1, constant: 0)) self.view.addConstraint(NSLayoutConstraint(item: self.view, attribute: .Trailing, relatedBy: .Equal, toItem: self.collectionView, attribute: .Trailing, multiplier: 1, constant: 0)) self.collectionView.dataSource = self self.collectionView.delegate = self self.accessoryViewRevealer = AccessoryViewRevealer(collectionView: self.collectionView) self.presenterBuildersByType = self.createPresenterBuilders() for presenterBuilder in self.presenterBuildersByType.flatMap({ $0.1 }) { presenterBuilder.presenterType.registerCells(self.collectionView) } DummyChatItemPresenter.registerCells(self.collectionView) } private var inputContainerBottomConstraint: NSLayoutConstraint! private func addInputViews() { self.inputContainer = UIView(frame: CGRect.zero) self.inputContainer.autoresizingMask = .None self.inputContainer.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(self.inputContainer) self.view.addConstraint(NSLayoutConstraint(item: self.inputContainer, attribute: .Top, relatedBy: .GreaterThanOrEqual, toItem: self.topLayoutGuide, attribute: .Bottom, multiplier: 1, constant: 0)) self.view.addConstraint(NSLayoutConstraint(item: self.view, attribute: .Leading, relatedBy: .Equal, toItem: self.inputContainer, attribute: .Leading, multiplier: 1, constant: 0)) self.view.addConstraint(NSLayoutConstraint(item: self.view, attribute: .Trailing, relatedBy: .Equal, toItem: self.inputContainer, attribute: .Trailing, multiplier: 1, constant: 0)) self.inputContainerBottomConstraint = NSLayoutConstraint(item: self.view, attribute: .Bottom, relatedBy: .Equal, toItem: self.inputContainer, attribute: .Bottom, multiplier: 1, constant: 0) self.view.addConstraint(self.inputContainerBottomConstraint) let inputView = self.createChatInputView() self.inputContainer.addSubview(inputView) self.inputContainer.addConstraint(NSLayoutConstraint(item: self.inputContainer, attribute: .Top, relatedBy: .Equal, toItem: inputView, attribute: .Top, multiplier: 1, constant: 0)) self.inputContainer.addConstraint(NSLayoutConstraint(item: self.inputContainer, attribute: .Leading, relatedBy: .Equal, toItem: inputView, attribute: .Leading, multiplier: 1, constant: 0)) self.inputContainer.addConstraint(NSLayoutConstraint(item: self.inputContainer, attribute: .Bottom, relatedBy: .Equal, toItem: inputView, attribute: .Bottom, multiplier: 1, constant: 0)) self.inputContainer.addConstraint(NSLayoutConstraint(item: self.inputContainer, attribute: .Trailing, relatedBy: .Equal, toItem: inputView, attribute: .Trailing, multiplier: 1, constant: 0)) self.keyboardTracker = KeyboardTracker(viewController: self, inputContainer: self.inputContainer, inputContainerBottomContraint: self.inputContainerBottomConstraint, notificationCenter: self.notificationCenter) } var notificationCenter = NSNotificationCenter.defaultCenter() var keyboardTracker: KeyboardTracker! public override var inputAccessoryView: UIView { return self.keyboardTracker.trackingView } public var isFirstLayout: Bool = true override public func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() self.adjustCollectionViewInsets() self.keyboardTracker.layoutTrackingViewIfNeeded() if self.isFirstLayout { self.updateQueue.start() self.isFirstLayout = false } } private func adjustCollectionViewInsets() { let isInteracting = self.collectionView.panGestureRecognizer.numberOfTouches() > 0 let isBouncingAtTop = isInteracting && self.collectionView.contentOffset.y < -self.collectionView.contentInset.top if isBouncingAtTop { return } let inputHeightWithKeyboard = self.view.bounds.height - self.inputContainer.frame.minY let newInsetBottom = self.constants.defaultContentInsets.bottom + inputHeightWithKeyboard let insetBottomDiff = newInsetBottom - self.collectionView.contentInset.bottom let contentSize = self.collectionView.collectionViewLayout.collectionViewContentSize() let allContentFits = self.collectionView.bounds.height - newInsetBottom - (contentSize.height + self.collectionView.contentInset.top) >= 0 let currentDistanceToBottomInset = max(0, self.collectionView.bounds.height - self.collectionView.contentInset.bottom - (contentSize.height - self.collectionView.contentOffset.y)) let newContentOffsetY = self.collectionView.contentOffset.y + insetBottomDiff - currentDistanceToBottomInset self.collectionView.contentInset.bottom = newInsetBottom self.collectionView.scrollIndicatorInsets.bottom = self.constants.defaultScrollIndicatorInsets.bottom + inputHeightWithKeyboard let inputIsAtBottom = self.view.bounds.maxY - self.inputContainer.frame.maxY <= 0 if allContentFits { self.collectionView.contentOffset.y = -self.collectionView.contentInset.top } else if !isInteracting || inputIsAtBottom { self.collectionView.contentOffset.y = newContentOffsetY } self.workaroundContentInsetBugiOS_9_0_x() } func workaroundContentInsetBugiOS_9_0_x() { // Fix for http://www.openradar.me/22106545 self.collectionView.contentInset.top = self.topLayoutGuide.length + self.constants.defaultContentInsets.top self.collectionView.scrollIndicatorInsets.top = self.topLayoutGuide.length + self.constants.defaultScrollIndicatorInsets.top } func rectAtIndexPath(indexPath: NSIndexPath?) -> CGRect? { if let indexPath = indexPath { return self.collectionView.collectionViewLayout.layoutAttributesForItemAtIndexPath(indexPath)?.frame } return nil } var autoLoadingEnabled: Bool = false var accessoryViewRevealer: AccessoryViewRevealer! var inputContainer: UIView! var presenterBuildersByType = [ChatItemType: [ChatItemPresenterBuilderProtocol]]() var presenters = [ChatItemPresenterProtocol]() let presentersByChatItem = NSMapTable(keyOptions: .WeakMemory, valueOptions: .StrongMemory) let presentersByCell = NSMapTable(keyOptions: .WeakMemory, valueOptions: .WeakMemory) var updateQueue: SerialTaskQueueProtocol = SerialTaskQueue() public func createPresenterBuilders() -> [ChatItemType: [ChatItemPresenterBuilderProtocol]] { assert(false, "Override in subclass") return [ChatItemType: [ChatItemPresenterBuilderProtocol]]() } public func createChatInputView() -> UIView { assert(false, "Override in subclass") return UIView() } /** - You can use a decorator to: - Provide the ChatCollectionViewLayout with margins between messages - Provide to your pressenters additional attributes to help them configure their cells (for instance if a bubble should show a tail) - You can also add new items (for instance time markers or failed cells) */ public var chatItemsDecorator: ChatItemsDecoratorProtocol? public var createCollectionViewLayout: UICollectionViewLayout { let layout = ChatCollectionViewLayout() layout.delegate = self return layout } var layoutModel = ChatCollectionViewLayoutModel.createModel(0, itemsLayoutData: []) } extension ChatViewController { // Rotation public override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) let shouldScrollToBottom = self.isScrolledAtBottom() let referenceIndexPath = self.collectionView.indexPathsForVisibleItems().first let oldRect = self.rectAtIndexPath(referenceIndexPath) coordinator.animateAlongsideTransition({ (context) -> Void in if shouldScrollToBottom { self.scrollToBottom(animated: false) } else { let newRect = self.rectAtIndexPath(referenceIndexPath) self.scrollToPreservePosition(oldRefRect: oldRect, newRefRect: newRect) } }, completion: nil) } }
mit
ead76d0707a0c1a976631988ef978565
52.065041
218
0.744599
5.323817
false
false
false
false
piglikeYoung/iOS8-day-by-day
17-live-rendering/LiveKnobControl/LiveKnobControl/RotationGestureRecognizer.swift
20
1759
// // Copyright 2014 Scott Logic // // 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 class RotationGestureRecognizer : UIPanGestureRecognizer { var touchAngle: CGFloat override init(target: AnyObject, action: Selector) { self.touchAngle = 0 super.init(target: target, action: action) self.maximumNumberOfTouches = 1; self.minimumNumberOfTouches = 1; } override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent!) { super.touchesBegan(touches, withEvent: event) updateTouchAngleWithTouches(touches) } override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent!) { super.touchesMoved(touches, withEvent: event) updateTouchAngleWithTouches(touches) } func updateTouchAngleWithTouches(touches: NSSet) { if let touch = touches.anyObject() as? UITouch { let touchPoint = touch.locationInView(self.view) self.touchAngle = self.calculateAngleToPoint(touchPoint) } } func calculateAngleToPoint(point: CGPoint) -> CGFloat { // Offset by the center let centerOffset = CGPointMake(point.x - CGRectGetMidX(self.view!.bounds), point.y - CGRectGetMidY(self.view!.bounds)) return atan2(centerOffset.y, centerOffset.x) } }
apache-2.0
deb2a9d16e3e7aa4ef8e0e4eb806ea18
31.574074
81
0.734508
4.311275
false
false
false
false
apstrand/loggy
LoggyTools/MapTracks.swift
1
5763
// // MapTrack.swift // Loggy // // Created by Peter Strand on 2017-07-12. // Copyright © 2017 Peter Strand. All rights reserved. // import Foundation import CoreLocation import MapKit public class MapTracks { public class LoggyAnnotation: NSObject, MKAnnotation { public var coordinate: CLLocationCoordinate2D public init(coordinate: CLLocationCoordinate2D) { self.coordinate = coordinate } } public class WaypointAnnotation: LoggyAnnotation { static let identifier = "waypoint" } public class TrackAnnotation: LoggyAnnotation { static let identifier = "track" let isStart: Bool public init(coordinate: CLLocationCoordinate2D, isStart: Bool) { self.isStart = isStart super.init(coordinate: coordinate) } } let MinLatSpan: CLLocationDegrees = 0.02 let MinLonSpan: CLLocationDegrees = 0.02 let MaxLatSpan: CLLocationDegrees = 2 let MaxLonSpan: CLLocationDegrees = 2 var min_lat: CLLocationDegrees = 0 var max_lat: CLLocationDegrees = 0 var min_lon: CLLocationDegrees = 0 var max_lon: CLLocationDegrees = 0 var trackPolys: [MKPolyline] = [] var currentPoly: MKPolyline? = nil var mapView: MKMapView var mapDelegate: MapDelegate? public var gpx: GPXData public var coordCache: [CLLocationCoordinate2D] = [] public var isTracking: Bool = false public var isStartingSegment: Bool = false public init(_ mapView: MKMapView, _ gpx: GPXData) { self.mapView = mapView self.gpx = gpx self.mapDelegate = MapDelegate(self) self.mapView.delegate = self.mapDelegate } public func handleNewLocation(point pt: TrackPoint, isMajor: Bool) { if self.isTracking && isMajor { self.add(pt.location) if self.isStartingSegment { let ann = TrackAnnotation(coordinate: pt.location, isStart: true) self.mapView.addAnnotation(ann) self.isStartingSegment = false } let newPoly = MKPolyline(coordinates: &self.coordCache, count: self.coordCache.count) if let poly = self.currentPoly { self.mapView.remove(poly) } else { self.trackPolys.append(newPoly) } self.mapView.add(newPoly) self.currentPoly = newPoly } self.mapView.setRegion(region(center:pt.location), animated: true) } public func startNewSegment() { currentPoly = nil coordCache.removeAll() min_lat = Double.greatestFiniteMagnitude max_lat = -Double.greatestFiniteMagnitude min_lon = Double.greatestFiniteMagnitude max_lon = -Double.greatestFiniteMagnitude isTracking = true isStartingSegment = true } public func endSegment(_ pt: TrackPoint?) { isTracking = false if let pt = pt { let place = TrackAnnotation(coordinate: pt.location, isStart: false) self.mapView.addAnnotation(place) } } public func storeWaypoint(_ waypoint: GPXData.Waypoint) { let ann = WaypointAnnotation(coordinate: waypoint.point.location) self.mapView.addAnnotation(ann) } public func add(_ coord : CLLocationCoordinate2D) { min_lat = min(min_lat, coord.latitude) max_lat = max(min_lat, coord.latitude) min_lon = min(min_lon, coord.longitude) max_lon = max(min_lon, coord.longitude) coordCache.append(coord) } public func region(center: CLLocationCoordinate2D) -> MKCoordinateRegion { var span: MKCoordinateSpan if coordCache.count > 1 { span = MKCoordinateSpan( latitudeDelta: min(MaxLatSpan, max(MinLatSpan, 3*(max_lat - min_lat))), longitudeDelta: min(MaxLonSpan, max(MinLonSpan, 3*(max_lon - min_lon)))) } else { span = MKCoordinateSpan(latitudeDelta: MinLatSpan, longitudeDelta: MinLonSpan) } return MKCoordinateRegion(center: center, span: span) } class MapDelegate : NSObject, MKMapViewDelegate { let parent : MapTracks init(_ p : MapTracks) { parent = p } func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) { } func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer { if overlay is MKPolyline { let polyLine = overlay let polyLineRenderer = MKPolylineRenderer(overlay: polyLine) polyLineRenderer.strokeColor = UIColor.black polyLineRenderer.lineWidth = 2.0 return polyLineRenderer } fatalError("mapView: Unknown overlay") } func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { if let _ = annotation as? WaypointAnnotation { var pin: MKPinAnnotationView! if let view = mapView.dequeueReusableAnnotationView(withIdentifier: WaypointAnnotation.identifier) { pin = view as! MKPinAnnotationView pin.annotation = annotation } else { pin = MKPinAnnotationView(annotation: annotation, reuseIdentifier: WaypointAnnotation.identifier) } pin.pinTintColor = UIColor.blue return pin } if let track = annotation as? TrackAnnotation { var pin: MKPinAnnotationView! if let view = mapView.dequeueReusableAnnotationView(withIdentifier: TrackAnnotation.identifier) { pin = view as! MKPinAnnotationView pin.annotation = annotation } else { pin = MKPinAnnotationView(annotation: annotation, reuseIdentifier: TrackAnnotation.identifier) } pin.pinTintColor = track.isStart ? UIColor.green : UIColor.red return pin } return nil } func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) { // print("mapView changed: \(mapView.visibleMapRect)") } } }
mit
640a24648b6119539ee530eb23a1223c
29.486772
108
0.67546
4.628112
false
false
false
false
shiwwgis/MyDiaryForEvernote
MyDiraryForEvernote/SetCurrentCityController.swift
1
1692
// // SetCurrentCityController.swift // MyDiaryForEvernote // // Created by shiweiwei on 16/2/27. // Copyright © 2016年 shiww. All rights reserved. // import UIKit //设置当前所在城市 class SetCurrentCityController: UIViewController { @IBOutlet weak var textCity: UITextField! var mainViewController:ViewController?; @IBAction func doSetCity(sender: UIButton) { let cityname=textCity.text!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())//"!去掉两边的空格 print(cityname); let weather=BaseFunction.getCityWeather(cityname); if weather.characters.count==0 { textCity.text=BaseFunction.getIntenetString("INPUT_AGAIN"); } else { mainViewController?.city=cityname; mainViewController?.saveSystemPara(); self.dismissViewControllerAnimated(true, completion: nil); } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. textCity.text=mainViewController?.city; } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
04c935f4046ada52c2eaf061ac2c831f
28.105263
119
0.661242
4.908284
false
false
false
false
tutsplus/iOS-GameplayKit-StarterProject
GameplayKit Introduction/PlayerNode.swift
1
736
// // PlayerNode.swift // GameplayKit Introduction // // Created by Davis Allie on 19/07/2015. // Copyright © 2015 Davis Allie. All rights reserved. // import UIKit import SpriteKit import GameplayKit class PlayerNode: SKShapeNode { var enabled = true { didSet { if self.enabled == false { self.alpha = 0.1 self.runAction(SKAction.customActionWithDuration(2.0, actionBlock: { (node, elapsedTime) -> Void in if elapsedTime == 2.0 { self.enabled = true } })) self.runAction(SKAction.fadeInWithDuration(2.0)) } } } }
bsd-2-clause
906b7cdddaef51fe6d700e63b2d4daf7
23.5
115
0.510204
4.741935
false
false
false
false
sharath-cliqz/browser-ios
SyncTests/TestBookmarkModel.swift
2
10271
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Deferred import Foundation import Shared @testable import Storage @testable import Sync import XCTest // Thieved mercilessly from TestSQLiteBookmarks. private func getBrowserDBForFile(filename: String, files: FileAccessor) -> BrowserDB? { let db = BrowserDB(filename: filename, files: files) // BrowserTable exists only to perform create/update etc. operations -- it's not // a queryable thing that needs to stick around. if db.createOrUpdate(BrowserTable()) != .Success { return nil } return db } class TestBookmarkModel: FailFastTestCase { let files = MockFiles() override func tearDown() { do { try self.files.removeFilesInDirectory() } catch { } super.tearDown() } private func getBrowserDB(name: String) -> BrowserDB? { let file = "TBookmarkModel\(name).db" print("DB file named: \(file)") return getBrowserDBForFile(file, files: self.files) } func getSyncableBookmarks(name: String) -> MergedSQLiteBookmarks? { guard let db = self.getBrowserDB(name) else { XCTFail("Couldn't get prepared DB.") return nil } return MergedSQLiteBookmarks(db: db) } func testBookmarkEditableIfNeverSyncedAndEmptyBuffer() { guard let bookmarks = self.getSyncableBookmarks("A") else { XCTFail("Couldn't get bookmarks.") return } // Set a local bookmark let bookmarkURL = "http://AAA.com".asURL! bookmarks.local.insertBookmark(bookmarkURL, title: "AAA", favicon: nil, intoFolder: BookmarkRoots.MenuFolderGUID, withTitle: "").succeeded() XCTAssertTrue(bookmarks.isMirrorEmpty().value.successValue!) XCTAssertTrue(bookmarks.buffer.isEmpty().value.successValue!) let menuFolder = bookmarks.menuFolder() XCTAssertEqual(menuFolder.current.count, 1) XCTAssertTrue(menuFolder.current[0]!.isEditable) } func testBookmarkEditableIfNeverSyncedWithBufferedChanges() { guard let bookmarks = self.getSyncableBookmarks("B") else { XCTFail("Couldn't get bookmarks.") return } let bookmarkURL = "http://AAA.com".asURL! bookmarks.local.insertBookmark(bookmarkURL, title: "AAA", favicon: nil, intoFolder: BookmarkRoots.MenuFolderGUID, withTitle: "").succeeded() // Add a buffer into the buffer let mirrorDate = NSDate.now() - 100000 bookmarks.applyRecords([ BookmarkMirrorItem.folder(BookmarkRoots.MenuFolderGUID, modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "Bookmarks Menu", description: "", children: ["BBB"]), BookmarkMirrorItem.bookmark("BBB", modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.MenuFolderGUID, parentName: "Bookmarks Menu", title: "BBB", description: nil, URI: "http://BBB.com", tags: "", keyword: nil) ]).succeeded() XCTAssertFalse(bookmarks.buffer.isEmpty().value.successValue!) XCTAssertTrue(bookmarks.isMirrorEmpty().value.successValue!) // Check to see if we're editable let menuFolder = bookmarks.menuFolder() XCTAssertEqual(menuFolder.current.count, 1) XCTAssertTrue(menuFolder.current[0]!.isEditable) } func testBookmarksEditableWithEmptyBufferAndRemoteBookmark() { guard let bookmarks = self.getSyncableBookmarks("C") else { XCTFail("Couldn't get bookmarks.") return } // Add a bookmark to the menu folder in our mirror let mirrorDate = NSDate.now() - 100000 bookmarks.populateMirrorViaBuffer([ BookmarkMirrorItem.folder(BookmarkRoots.RootGUID, modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "", description: "", children: BookmarkRoots.RootChildren), BookmarkMirrorItem.folder(BookmarkRoots.MenuFolderGUID, modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "Bookmarks Menu", description: "", children: ["CCC"]), BookmarkMirrorItem.bookmark("CCC", modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.MenuFolderGUID, parentName: "Bookmarks Menu", title: "CCC", description: nil, URI: "http://CCC.com", tags: "", keyword: nil) ], atDate: mirrorDate) // Set a local bookmark let bookmarkURL = "http://AAA.com".asURL! bookmarks.local.insertBookmark(bookmarkURL, title: "AAA", favicon: nil, intoFolder: BookmarkRoots.MenuFolderGUID, withTitle: "").succeeded() XCTAssertTrue(bookmarks.buffer.isEmpty().value.successValue!) XCTAssertFalse(bookmarks.isMirrorEmpty().value.successValue!) // Check to see if we're editable let menuFolder = bookmarks.menuFolder() XCTAssertEqual(menuFolder.current.count, 2) XCTAssertTrue(menuFolder.current[0]!.isEditable) XCTAssertTrue(menuFolder.current[1]!.isEditable) } func testBookmarksNotEditableForUnmergedChanges() { guard let bookmarks = self.getSyncableBookmarks("D") else { XCTFail("Couldn't get bookmarks.") return } // Add a bookmark to the menu folder in our mirror let mirrorDate = NSDate.now() - 100000 bookmarks.populateMirrorViaBuffer([ BookmarkMirrorItem.folder(BookmarkRoots.RootGUID, modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "", description: "", children: BookmarkRoots.RootChildren), BookmarkMirrorItem.folder(BookmarkRoots.MenuFolderGUID, modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "Bookmarks Menu", description: "", children: ["EEE"]), BookmarkMirrorItem.bookmark("EEE", modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.MenuFolderGUID, parentName: "Bookmarks Menu", title: "EEE", description: nil, URI: "http://EEE.com", tags: "", keyword: nil) ], atDate: mirrorDate) bookmarks.local.insertBookmark("http://AAA.com".asURL!, title: "AAA", favicon: nil, intoFolder: BookmarkRoots.MobileFolderGUID, withTitle: "Bookmarks Menu").succeeded() // Add some unmerged bookmarks into the menu folder in the buffer. bookmarks.applyRecords([ BookmarkMirrorItem.folder(BookmarkRoots.MenuFolderGUID, modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "Bookmarks Menu", description: "", children: ["EEE", "FFF"]), BookmarkMirrorItem.bookmark("FFF", modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.MenuFolderGUID, parentName: "Bookmarks Menu", title: "FFF", description: nil, URI: "http://FFF.com", tags: "", keyword: nil) ]).succeeded() XCTAssertFalse(bookmarks.buffer.isEmpty().value.successValue!) XCTAssertFalse(bookmarks.isMirrorEmpty().value.successValue!) // Check to see that we can't edit these bookmarks let menuFolder = bookmarks.menuFolder() XCTAssertEqual(menuFolder.current.count, 1) XCTAssertFalse(menuFolder.current[0]!.isEditable) } func testLocalBookmarksEditableWhileHavingUnmergedChangesAndEmptyMirror() { guard let bookmarks = self.getSyncableBookmarks("D") else { XCTFail("Couldn't get bookmarks.") return } bookmarks.local.insertBookmark("http://AAA.com".asURL!, title: "AAA", favicon: nil, intoFolder: BookmarkRoots.MobileFolderGUID, withTitle: "Bookmarks Menu").succeeded() // Add some unmerged bookmarks into the menu folder in the buffer. let mirrorDate = NSDate.now() - 100000 bookmarks.applyRecords([ BookmarkMirrorItem.folder(BookmarkRoots.MenuFolderGUID, modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.RootGUID, parentName: "", title: "Bookmarks Menu", description: "", children: ["EEE", "FFF"]), BookmarkMirrorItem.bookmark("FFF", modified: mirrorDate, hasDupe: false, parentID: BookmarkRoots.MenuFolderGUID, parentName: "Bookmarks Menu", title: "FFF", description: nil, URI: "http://FFF.com", tags: "", keyword: nil) ]).succeeded() // Local bookmark should be editable let mobileFolder = bookmarks.mobileFolder() XCTAssertEqual(mobileFolder.current.count, 2) XCTAssertTrue(mobileFolder.current[1]!.isEditable) } } private extension MergedSQLiteBookmarks { func isMirrorEmpty() -> Deferred<Maybe<Bool>> { return self.local.db.queryReturnsNoResults("SELECT 1 FROM \(TableBookmarksMirror)") } func wipeLocal() { self.local.db.run(["DELETE FROM \(TableBookmarksLocalStructure)", "DELETE FROM \(TableBookmarksLocal)"]).succeeded() } func populateMirrorViaBuffer(items: [BookmarkMirrorItem], atDate mirrorDate: Timestamp) { self.applyRecords(items).succeeded() // … and add the root relationships that will be missing (we don't do those for the buffer, // so we need to manually add them and move them across). self.buffer.db.run([ "INSERT INTO \(TableBookmarksBufferStructure) (parent, child, idx) VALUES", "('\(BookmarkRoots.RootGUID)', '\(BookmarkRoots.MenuFolderGUID)', 0),", "('\(BookmarkRoots.RootGUID)', '\(BookmarkRoots.ToolbarFolderGUID)', 1),", "('\(BookmarkRoots.RootGUID)', '\(BookmarkRoots.UnfiledFolderGUID)', 2),", "('\(BookmarkRoots.RootGUID)', '\(BookmarkRoots.MobileFolderGUID)', 3)", ].joined(" ")).succeeded() // Move it all to the mirror. self.local.db.moveBufferToMirrorForTesting() } func menuFolder() -> BookmarksModel { return modelFactory.value.successValue!.modelForFolder(BookmarkRoots.MenuFolderGUID).value.successValue! } func mobileFolder() -> BookmarksModel { return modelFactory.value.successValue!.modelForFolder(BookmarkRoots.MobileFolderGUID).value.successValue! } }
mpl-2.0
43c64825c8c6244dc70820b72b7b54c3
48.370192
233
0.681858
5.006826
false
true
false
false
benlangmuir/swift
test/AutoDiff/TBD/derivative_symbols.swift
7
4020
// RUN: %target-swift-frontend -emit-ir -o/dev/null -Xllvm -sil-disable-pass=cmo -parse-as-library -module-name test -validate-tbd-against-ir=all %s // RUN: %target-swift-frontend -emit-ir -o/dev/null -Xllvm -sil-disable-pass=cmo -parse-as-library -module-name test -validate-tbd-against-ir=all %s -O // RUN: %target-swift-frontend -emit-ir -o/dev/null -parse-as-library -module-name test -validate-tbd-against-ir=missing %s -enable-testing // RUN: %target-swift-frontend -emit-ir -o/dev/null -parse-as-library -module-name test -validate-tbd-against-ir=missing %s -enable-testing -O import _Differentiation @differentiable(reverse) public func topLevelDifferentiable(_ x: Float, _ y: Float) -> Float { x } public func topLevelHasDerivative<T: Differentiable>(_ x: T) -> T { x } @derivative(of: topLevelHasDerivative) public func topLevelDerivative<T: Differentiable>(_ x: T) -> ( value: T, pullback: (T.TangentVector) -> T.TangentVector ) { fatalError() } public struct Struct: Differentiable { var stored: Float // Test property: getter and setter. public var property: Float { @differentiable(reverse) get { stored } @differentiable(reverse) set { stored = newValue } } // Test initializer. @differentiable(reverse) public init(_ x: Float) { stored = x.squareRoot() } // Test delegating initializer. @differentiable(reverse) public init(blah x: Float) { self.init(x) } // Test method. public func method(_ x: Float, _ y: Float) -> Float { x } @derivative(of: method) public func jvpMethod(_ x: Float, _ y: Float) -> ( value: Float, differential: (TangentVector, Float, Float) -> Float ) { fatalError() } // Test subscript: getter and setter. public subscript(_ x: Float) -> Float { @differentiable(reverse) get { x } @differentiable(reverse) set { stored = newValue } } @derivative(of: subscript) public func vjpSubscript(_ x: Float) -> ( value: Float, pullback: (Float) -> (TangentVector, Float) ) { fatalError() } @derivative(of: subscript.set) public mutating func vjpSubscriptSetter(_ x: Float, _ newValue: Float) -> ( value: (), pullback: (inout TangentVector) -> (Float, Float) ) { fatalError() } } extension Array where Element == Struct { @differentiable(reverse) public func sum() -> Float { return 0 } } // SR-13866: Dispatch thunks and method descriptor mangling. public protocol P: Differentiable { @differentiable(reverse, wrt: self) @differentiable(reverse, wrt: (self, x)) func method(_ x: Float) -> Float @differentiable(reverse, wrt: self) var property: Float { get set } @differentiable(reverse, wrt: self) @differentiable(reverse, wrt: (self, x)) subscript(_ x: Float) -> Float { get set } } public final class Class: Differentiable { var stored: Float // Test initializer. // FIXME(rdar://74380324) // @differentiable(reverse) public init(_ x: Float) { stored = x } // Test delegating initializer. // FIXME(rdar://74380324) // @differentiable(reverse) // public convenience init(blah x: Float) { // self.init(x) // } // Test method. public func method(_ x: Float, _ y: Float) -> Float { x } @derivative(of: method) public func jvpMethod(_ x: Float, _ y: Float) -> ( value: Float, differential: (TangentVector, Float, Float) -> Float ) { fatalError() } // Test subscript: getter and setter. public subscript(_ x: Float) -> Float { @differentiable(reverse) get { x } // FIXME(SR-13096) // @differentiable(reverse) // set { stored = newValue } } @derivative(of: subscript) public func vjpSubscript(_ x: Float) -> ( value: Float, pullback: (Float) -> (TangentVector, Float) ) { fatalError() } // FIXME(SR-13096) // @derivative(of: subscript.set) // public func vjpSubscriptSetter(_ x: Float, _ newValue: Float) -> ( // value: (), pullback: (inout TangentVector) -> (Float, Float) // ) { // fatalError() // } }
apache-2.0
2bc4e2541e1bdf7b448d0140e972eff5
25.622517
151
0.65199
3.576512
false
true
false
false
blitzagency/amigo-swift
Amigo/ForeignKey.swift
1
738
// // ForeignKey.swift // Amigo // // Created by Adam Venturella on 7/3/15. // Copyright © 2015 BLITZ. All rights reserved. // import Foundation public struct ForeignKey{ public let relatedColumn: Column public var column: Column! public init(_ relatedColumn: Column, column: Column){ self.relatedColumn = relatedColumn self.column = column } public init(_ relatedColumn: Column){ self.relatedColumn = relatedColumn } public init(_ table: Table){ self.relatedColumn = table.primaryKey! } public init(_ model: ORMModel){ self.relatedColumn = model.table.primaryKey! } public var relatedTable: Table{ return relatedColumn.table! } }
mit
941dfda3d3b0c6f62688364deac066d8
20.085714
57
0.649932
4.284884
false
false
false
false
weby/Stencil
Tests/TokenSpec.swift
1
1011
import Spectre import Stencil func testToken() { describe("Token") { $0.it("can split the contents into components") { let token = Token.Text(value: "hello world") let components = token.components() try expect(components.count) == 2 try expect(components[0]) == "hello" try expect(components[1]) == "world" } $0.it("can split the contents into components with single quoted strings") { let token = Token.Text(value: "hello 'kyle fuller'") let components = token.components() try expect(components.count) == 2 try expect(components[0]) == "hello" try expect(components[1]) == "'kyle fuller'" } $0.it("can split the contents into components with double quoted strings") { let token = Token.Text(value: "hello \"kyle fuller\"") let components = token.components() try expect(components.count) == 2 try expect(components[0]) == "hello" try expect(components[1]) == "\"kyle fuller\"" } } }
bsd-2-clause
367121d2e38f53a76a3112be1e54e527
28.735294
80
0.624135
4.011905
false
false
false
false
danpratt/Simply-Zen
Simply Zen/Model/OpenMeditationsExtension.swift
1
1402
// // OpenMeditationsExtension.swift // Simply Zen // // Created by Daniel Pratt on 5/25/17. // Copyright © 2017 Daniel Pratt. All rights reserved. // import Foundation // MARK: - SZCourse Extension for Open Meditations extension SZCourse { // Build the open meditation courses for different bell types static func openMeditationCourses() -> SZCourse { // Create the lessons for "course" var openLessons = [SZLesson]() let burmeseBells = SZLesson(addLesson: "burmese", withFilename: "burmese-bell", level: 0) let kyotoTempleBells = SZLesson(addLesson: "kyoto", withFilename: "kyoto-temple-bell", level: 0) let thaiBells = SZLesson(addLesson: "thai", withFilename: "thai-bell", level: 0) let tibetanBells = SZLesson(addLesson: "tibetan", withFilename: "tibetan-bell", level: 0) let relaxingBells = SZLesson(addLesson: "relaxing", withFilename: "relaxing-bell", level: 0) let noBells = SZLesson(addLesson: "none", withFilename: "none", level: 0) // Add lessons openLessons.append(burmeseBells) openLessons.append(kyotoTempleBells) openLessons.append(thaiBells) openLessons.append(tibetanBells) openLessons.append(relaxingBells) openLessons.append(noBells) return SZCourse(named: "Open Meditation", withlessons: openLessons) } }
apache-2.0
01f37aac447dc0543cabbe15d149d6c4
36.864865
104
0.673091
4.108504
false
false
false
false
ndagrawal/MovieFeed
MovieFeed/DVDListViewController.swift
1
8175
// // DVDListViewController.swift // MovieFeed // // Created by Nilesh Agrawal on 9/17/15. // Copyright © 2015 Nilesh Agrawal. All rights reserved. // import UIKit class DVDListViewController: UIViewController,UICollectionViewDelegateFlowLayout,UICollectionViewDelegate,UICollectionViewDataSource { @IBOutlet weak var DVDListCollectionView:UICollectionView! var DVDCollectionArray:[DVD] = [DVD]() var refreshControl:UIRefreshControl! var tumblrHud:AMTumblrHud = AMTumblrHud() var errorLabel:UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.setUpView() self.setUpInitialValues() self.setUpDelegate() } func setUpCollectionViewFlowLayout(){ let width:CGFloat = (CGRectGetWidth(view.frame)) let flowLayout:UICollectionViewFlowLayout = UICollectionViewFlowLayout.init() flowLayout.itemSize = CGSizeMake(width,CGRectGetHeight(view.frame)/5) flowLayout.scrollDirection = UICollectionViewScrollDirection.Vertical flowLayout.minimumInteritemSpacing = 0.0 flowLayout.minimumLineSpacing = 0.0 DVDListCollectionView.setCollectionViewLayout(flowLayout,animated:false) DVDListCollectionView.backgroundColor = UIColor.whiteColor() } func setUpNavigationBar(){ self.navigationController?.navigationBar.barTintColor = UIColor(red:0.00, green:0.48, blue:1.00, alpha:1.0) self.navigationController?.navigationBar.tintColor = UIColor.whiteColor() self.navigationItem.title = "DVD" self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.whiteColor()] } func setUpLoadingView(){ tumblrHud = AMTumblrHud.init(frame: CGRectMake(100, 100, 55, 20)) tumblrHud.hudColor = UIColor .grayColor()//UIColorFromRGB(0xF1F2F3) self.view.addSubview(tumblrHud) tumblrHud.showAnimated(true) } func addErrorView(){ errorLabel = UILabel.init(frame:CGRectMake(0, 0, self.view.frame.size.width, 30)) errorLabel.backgroundColor = UIColor.redColor() errorLabel.textColor = UIColor.grayColor() errorLabel.text = "Unable to load" DVDListCollectionView.insertSubview(errorLabel,atIndex:0) } func setUpView(){ setUpCollectionViewFlowLayout() setUpNavigationBar() addRefreshControl() } func addRefreshControl(){ refreshControl = UIRefreshControl.init() refreshControl.addTarget(self, action:"setUpInitialValues", forControlEvents:UIControlEvents.ValueChanged) DVDListCollectionView.insertSubview(refreshControl, atIndex: 0) } func setUpDelegate(){ DVDListCollectionView.delegate = self; DVDListCollectionView.dataSource = self; } func setUpInitialValues(){ //let clientId = "e2478f1f8c53474cb6a50ef0387f9756" let requestedURL = NSURL(string:"https://gist.githubusercontent.com/timothy1ee/d1778ca5b944ed974db0/raw/489d812c7ceeec0ac15ab77bf7c47849f2d1eb2b/gistfile1.json")! let session = NSURLSession.sharedSession() let task = session.dataTaskWithURL(requestedURL, completionHandler: {data, response, error in // First, make sure we have real data, and handle the error if not. // (That's a better use of the API contract than checking the error parameter, because the error parameter is not guaranteed to be non-nil in all cases where correct data is received.) // Use a guard clause to keep the "good path" less indented. guard let actualData = data else { // self.responseText.text = "Response status: \(error!.description)" return } do { // Use do/try/catch to call the new throwing API. // Use the new OptionSetType syntax, too. let dataDictionary = try NSJSONSerialization.JSONObjectWithData(actualData, options: []) print(dataDictionary); dispatch_async(dispatch_get_main_queue(), { let movies = dataDictionary["movies"] as! NSArray for(var i=0;i<movies.count;i++){ let responseDictionary = movies[i] as! NSDictionary let posters = responseDictionary["posters"] as! NSDictionary let movieName = responseDictionary["title"] as! String let movieRating = responseDictionary["mpaa_rating"] as! String let movieTime = responseDictionary["runtime"] as! Int let ratings = responseDictionary["ratings"] as!NSDictionary let moviePercentage=ratings["audience_score"] as! Int let movieImageURL = posters["original"] as! String let casts = responseDictionary["abridged_cast"] as! NSArray let summary = responseDictionary["synopsis"] as! String var movieCasts:String = String() for(var k=0;k<casts.count;k++){ let individualCast = casts[k] as! NSDictionary let actor = individualCast["name"] as! String movieCasts = movieCasts + actor + " " } print("movieImageURL \(movieImageURL) , movieName \(movieName), movieRatings \(movieRating) movieTime \(movieTime) moviePercentage \(moviePercentage) movieCasts \(movieCasts) summary\(summary)") let currentMovie:DVD = DVD.init(DVDImageURL: movieImageURL, DVDName: movieName, DVDRating: movieRating, DVDMinute: movieTime, DVDPercentage: moviePercentage, DVDCasts: movieCasts, DVDSummary: summary) self.DVDCollectionArray.append(currentMovie) } self.tumblrHud.showAnimated(false); self.DVDListCollectionView.reloadData() self.refreshControl.endRefreshing() }) } catch let parseError { // No need to treat as NSError and call description here, because ErrorTypes are guaranteed to be describable. NSLog("Response status: \(parseError)") } }) task.resume() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{ return DVDCollectionArray.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{ let cell:DVDCollectionViewCell = DVDListCollectionView.dequeueReusableCellWithReuseIdentifier("DVDCollectionViewCell", forIndexPath: indexPath) as! DVDCollectionViewCell cell.setDVDCell(DVDCollectionArray[indexPath.row]) return cell } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. if(segue.identifier == "DVDPushSegue"){ let detailViewController:DVDDetailViewController = segue.destinationViewController as! DVDDetailViewController let cell = sender as! UICollectionViewCell let indexPath = DVDListCollectionView!.indexPathForCell(cell) as NSIndexPath! let selectedDVDColleciton:DVD = DVDCollectionArray[indexPath.row] detailViewController.selectedCurrentMovie = selectedDVDColleciton } } }
mit
58994e84016233188d458df5062391e1
46.248555
218
0.646318
5.530447
false
false
false
false
CoderJackyHuang/ITClient-Swift
ITClient-Swift/Controller/Profile/ProfileController.swift
1
4280
// // ProfileController.swift // ITClient-Swift // // Created by huangyibiao on 15/9/24. // Copyright © 2015年 huangyibiao. All rights reserved. // import Foundation import UIKit import SnapKit import SwiftExtensionCodes import MessageUI /// My Profile /// /// Author: 黄仪标 /// Blog: http://www.hybblog.com/ /// Github: http://github.com/CoderJackyHuang/ /// Email: [email protected] /// Weibo: JackyHuang(标哥) class ProfileController: BaseController, MFMailComposeViewControllerDelegate { private var tableView: UITableView! private var dataSource: [[String]] = [] override func viewDidLoad() { super.viewDidLoad() hyb_navWithTitle("我的江湖") self.tableView = createTableView(.Grouped) self.tableView.separatorStyle = .SingleLine self.dataSource.append(["我的账号", "我的收藏"]) self.dataSource.append(["我去好评", "我去吐槽"]) self.dataSource.append(["关注我们", "关于我们"]) } // MARK: UITableViewDataSource override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier) if cell == nil { cell = UITableViewCell(style: .Default, reuseIdentifier: CellIdentifier) } var found = false if indexPath.section == 0 && indexPath.row == 0 { // log in if UserManager.sharedInstance.userClientId != 0 { cell?.imageView?.hyb_setImageUrl(UserManager.sharedInstance.face) cell?.textLabel?.text = UserManager.sharedInstance.nickname found = true } } if !found { cell?.textLabel?.text = self.dataSource[indexPath.section][indexPath.row] cell?.imageView?.image = nil } return cell! } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return self.dataSource.count } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.dataSource[section].count } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) switch indexPath.section { case 0: if indexPath.row == 0 { LoginController.showInController(self, success: { () -> Void in tableView.reloadData() }) } case 1: if indexPath.row == 0 {// To evaluate let url = "http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=946717730&pageNumber=0&sortOrdering=2&type=Purple+Software&mt=8" UIApplication.sharedApplication().openURL(NSURL(string: url)!) } else {// To send email self.sendEmail(["[email protected]"], subject: "我要吐槽") } default: let controller = indexPath.row == 0 ? FollowUsController() : AboutUsController() self.navigationController?.pushViewController(controller, animated: true) } } // MARK: MFMailComposeViewControllerDelegate func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) { controller.dismissViewControllerAnimated(true, completion: nil) } // MARK: Private private func sendEmail(receiver: [String], subject: String, isHTML: Bool = false) { let mail = MFMailComposeViewController() mail.mailComposeDelegate = self // set delegate // set the email receiver mail.setToRecipients(receiver) // set the subject of email mail.setSubject(subject) // set the body of email let info:Dictionary = NSBundle.mainBundle().infoDictionary! let appName = info["CFBundleName"] as! String let appVersion = info["CFBundleVersion"] as! String mail.setMessageBody("</br></br></br></br></br>基本信息:</br></br>AppName:\(appName)</br>DeviceName: \(UIDevice.currentDevice().name)</br>DeviceVersion: iOS \(UIDevice.currentDevice().systemVersion) </br>AppVersion: \(appVersion)", isHTML: true) if MFMailComposeViewController.canSendMail() { dispatch_async(App.mainQueue, { () -> Void in self.presentViewController(mail, animated: true, completion: nil) }) } } }
mit
30511ffa7e3e2b3b13a469fed8910ea6
33.628099
244
0.691573
4.543384
false
false
false
false
simonorlovsky/Energy
Energy/DetailConsumptionViewController.swift
2
4073
// // DetailConsumptionViewController.swift // Carleton Energy App // 6/8/2015 // // By Hami Abdi, Caleb Braun, and Simon Orlovsky – // import UIKit class DetailConsumptionViewController: UIViewController { // Label outlets @IBOutlet weak var barGraphView: BarGraphView! @IBOutlet weak var energyTypeLabel: UILabel! @IBOutlet weak var energyUnitsLabel: UILabel! // For implementing changing time values var timePeriod = "this year" // An array of raw building data var buildingsDictionaries = [] var selectedBuildings = [String]() let energyTypeArray = ["Electricity", "Water", "Natural Gas", "Steam"] let timePeriodArray = ["today", "month", "year"] override func viewDidLoad() { super.viewDidLoad() // The default is total energy getGraphData("total energy", resolution: "month") } // Loops through the list of selected buildings and creates the data request for each building func getGraphData(type:String, resolution:String) { let startDate = getStartDate() let endDate = NSDate() let data : DataRetreiver = DataRetreiver() var meterType = type // fix this later if type.lowercaseString == "total energy" { meterType = "Electricity" } data.fetch(self.selectedBuildings, meterType: meterType, startDate: startDate, endDate: endDate, resolution: resolution, callback: setupGraphDisplay) } //Add building data to the graph func setupGraphDisplay(results:[String:[Double]]) { self.barGraphView.loadData(results) //Indicate that the graph needs to be redrawn on the main queue dispatch_async(dispatch_get_main_queue()) { self.barGraphView.setNeedsDisplay() } } func getStartDate() -> NSDate { let date = NSDate() let calendar = NSCalendar.currentCalendar() let components = calendar.components(.CalendarUnitYear | .CalendarUnitHour | .CalendarUnitMinute, fromDate: date) let dateComponents = NSDateComponents() // For implementing changing time values switch self.timePeriod { case "today": println("Showing data for today!") case "this month": dateComponents.day = 01 case "this year": dateComponents.year = components.year dateComponents.month = 01 dateComponents.day = 01 default: dateComponents.day = 01 } let startDate = NSCalendar.currentCalendar().dateFromComponents(dateComponents)! return startDate } func updateGraphEnergyData() { getGraphData(self.energyTypeLabel.text!, resolution: "month") switch self.energyTypeLabel.text! { case "Electricity": self.energyUnitsLabel.text = "total kWh" case "Water": self.energyUnitsLabel.text = "total gal" case "Steam": self.energyUnitsLabel.text = "total kBTU" default: self.energyUnitsLabel.text = "total kWh" } self.energyTypeLabel.sizeToFit() } @IBAction func energyTypeBackButtonPressed(sender: AnyObject) { if var currentEnergyTypeIndex = find(self.energyTypeArray, self.energyTypeLabel.text!) { if currentEnergyTypeIndex == 0 { currentEnergyTypeIndex = energyTypeArray.count } self.energyTypeLabel.text = self.energyTypeArray[currentEnergyTypeIndex-1] updateGraphEnergyData() } } @IBAction func energyTypeForwardButtonPressed(sender: AnyObject) { if var currentEnergyTypeIndex = find(self.energyTypeArray, self.energyTypeLabel.text!) { if currentEnergyTypeIndex == energyTypeArray.count-1 { currentEnergyTypeIndex = -1 } self.energyTypeLabel.text = self.energyTypeArray[currentEnergyTypeIndex+1] updateGraphEnergyData() } } }
mit
f357ed19e066d4a89e81b4ea5627df73
33.794872
157
0.632768
5.069738
false
false
false
false
zneak/swift-chess
chess/main.swift
1
889
// // main.swift // chess // // Created by Félix on 16-02-12. // Copyright © 2016 Félix Cloutier. All rights reserved. // let session = PlaySession() session.xtermPrint() var winner: Player? = nil while winner == nil { print("(\(session.turn)) ", terminator: "") var optMove = readLine(stripNewline: true) guard let move = optMove else { continue } switch session.interpret(move) { case .SelfCheck: print("move would put king in check") case .ParseError: print("move is not algebraic notation") case .Illegal: print("no piece can make that move") case .Ambiguous: print("move is ambiguous") case .Success(let special): session.xtermPrint() switch special { case .Check(let player): print("\(player) is checked!") case .Checkmate(let player): print("\(player) is checkmate!") winner = player.opponent default: break } } } print("\(winner!) wins")
gpl-3.0
1990090d7fdb768a153a9abbd143d51c
22.342105
58
0.680587
3.318352
false
false
false
false
steve-whitney/spt-ios-sdk-issue409
Issue409/DefaultSpotifyPlaylistManager.swift
1
1003
import Foundation protocol IPlaylistManager { func start() -> Void } class DefaultSpotifyPlaylistManager : IPlaylistManager { let spotifyProxy: ISpotifyProxy private(set) var playlistSnapshot: SPTPlaylistSnapshot? init(spotifyProxy: ISpotifyProxy) { self.spotifyProxy = spotifyProxy } func start() { recallPlaylistPagination() } private func recallPlaylistPagination() { let lambda = self.generateCallbackFor_playlistsForUserWithSession(__FUNCTION__, msg: "looking for playlist names") spotifyProxy.sptPlaylistList_playlistsForUserWithSession(callback: lambda) } private func generateCallbackFor_playlistsForUserWithSession(fn: String, msg: String) -> (NSError?, AnyObject?) -> Void { let _fn = fn let _msg = msg func rv(error: NSError?, object: AnyObject?) -> Void { assert(false,"OOPS, Issue409 REPRODUCTION FAILED: error=\(error) object=\(object)") } return rv } }
apache-2.0
142d355cf6a7fa297d0d4066606f979c
28.5
125
0.680957
4.457778
false
false
false
false
cruisediary/Diving
Diving/Scenes/UserList/UserListRouter.swift
1
2141
// // UserListRouter.swift // Diving // // Created by CruzDiary on 5/23/16. // Copyright (c) 2016 DigitalNomad. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so you can apply // clean architecture to your iOS and Mac projects, see http://clean-swift.com // import UIKit protocol UserListRouterInput { func navigateToSomewhere() } class UserListRouter { weak var viewController: UserListViewController! // MARK: Navigation func navigateToSomewhere() { // NOTE: Teach the router how to navigate to another scene. Some examples follow: // 1. Trigger a storyboard segue // viewController.performSegueWithIdentifier("ShowSomewhereScene", sender: nil) // 2. Present another view controller programmatically // viewController.presentViewController(someWhereViewController, animated: true, completion: nil) // 3. Ask the navigation controller to push another view controller onto the stack // viewController.navigationController?.pushViewController(someWhereViewController, animated: true) // 4. Present a view controller from a different storyboard // let storyboard = UIStoryboard(name: "OtherThanMain", bundle: nil) // let someWhereViewController = storyboard.instantiateInitialViewController() as! SomeWhereViewController // viewController.navigationController?.pushViewController(someWhereViewController, animated: true) } // MARK: Communication func passDataToNextScene(segue: UIStoryboardSegue) { // NOTE: Teach the router which scenes it can communicate with if segue.identifier == "ShowSomewhereScene" { passDataToSomewhereScene(segue) } } func passDataToSomewhereScene(segue: UIStoryboardSegue) { // NOTE: Teach the router how to pass data to the next scene // let someWhereViewController = segue.destinationViewController as! SomeWhereViewController // someWhereViewController.output.name = viewController.output.name } }
mit
4f308fc13b9898b8baaaf2d6ecc205e8
36.561404
114
0.698739
5.739946
false
false
false
false
JudoPay/JudoKit
Example-Swift/JudoKitSwiftExample/DetailViewController.swift
1
3648
// // DetailViewController.swift // JudoPayDemoSwift // // Copyright (c) 2016 Alternative Payments Ltd // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit import JudoKit class DetailViewController: UIViewController { @IBOutlet var dateStampLabel: UILabel! @IBOutlet var amountLabel: UILabel! @IBOutlet var resolutionLabel: UILabel! var response: Response? let inputDateFormatter: DateFormatter = { let inputDateFormatter = DateFormatter() let enUSPOSIXLocale = Locale(identifier: "en_US_POSIX") inputDateFormatter.locale = enUSPOSIXLocale inputDateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSZZZZZ" return inputDateFormatter }() let outputDateFormatter: DateFormatter = { let outputDateFormatter = DateFormatter() outputDateFormatter.dateFormat = "yyyy-MM-dd, HH:mm" return outputDateFormatter }() let currencyFormatter: NumberFormatter = { let numberFormatter = NumberFormatter() numberFormatter.numberStyle = .currency return numberFormatter }() override func viewDidLoad() { super.viewDidLoad() self.title = "Payment receipt" self.navigationItem.hidesBackButton = true if let response = self.response, let transaction = response.items.first { self.dateStampLabel.text = self.outputDateFormatter.string(from: transaction.createdAt) self.currencyFormatter.currencyCode = transaction.amount.currency.rawValue self.amountLabel.text = transaction.amount.amount.stringValue + " " + transaction.amount.currency.rawValue self.resolutionLabel.text = transaction.result.rawValue } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if let response = self.response, let transaction = response.items.first { self.dateStampLabel.text = self.outputDateFormatter.string(from: transaction.createdAt) self.currencyFormatter.currencyCode = transaction.amount.currency.rawValue self.amountLabel.text = transaction.amount.amount.stringValue + " " + transaction.amount.currency.rawValue } } @IBAction func homeButtonHandler(_ sender: AnyObject) { if UIApplication.shared.keyWindow?.rootViewController is UINavigationController { _=self.navigationController?.popViewController(animated: true) } else { self.dismiss(animated: true, completion: nil) } } }
mit
a95f8421031c729eb34452effc36fa3e
40.454545
118
0.700384
5.017882
false
false
false
false
iwasrobbed/LazyObject
Tests/ErrorTests.swift
1
2641
// // ErrorTests.swift // LazyObject // // Created by Rob Phillips on 5/21/16. // Copyright © 2016 Glazed Donut, LLC. All rights reserved. // import XCTest @testable import LazyObject final class ErrorTests: XCTestCase { func testKeyPathValueNotFoundError() { class Object: LazyObject { var missingKey: String? { return try? objectFor("missing_key") } } let object = Object(dictionary: [:]) do { let _: String = try object.objectFor("missing_key") XCTFail() } catch LazyMappingError.keyPathValueNotFoundError(_) { XCTAssertNil(object.missingKey) } catch let e { XCTFail("Test failed for an unexpected reason: \(e)") } } /** Essentially, test a scenario where a custom convertible wasn't created yet */ func testConversionError() { class Object: LazyObject { var badType: URLRequest? { return try? objectFor("key") } } let object = Object(dictionary: ["key": 42]) do { let _: URLRequest = try object.objectFor("key") XCTFail() } catch LazyMappingError.conversionError(_, _, _) { XCTAssertNil(object.badType) } catch let e { XCTFail("Test failed for an unexpected reason: \(e)") } } func testUnexpectedTypeError() { class Object: LazyObject { var badType: NSNumber? { return try? objectFor("number_from_string") } } // NSNumber expects string (representing a number) or number inputs let object = Object(dictionary: ["number_from_string": ["blah": "blerp"]]) do { let _: NSNumber = try object.objectFor("number_from_string") XCTFail() } catch LazyMappingError.unexpectedTypeError(_, _) { XCTAssertNil(object.badType) } catch let e { XCTFail("Test failed for an unexpected reason: \(e)") } } func testCustomError() { class Object: LazyObject { var badNumberValue: NSNumber? { return try? objectFor("number_from_string") } } // NSNumber expects string (representing a number) or number inputs let object = Object(dictionary: ["number_from_string": "this is not a number"]) do { let _: NSNumber = try object.objectFor("number_from_string") XCTFail() } catch LazyMappingError.customError(_) { XCTAssertNil(object.badNumberValue) } catch let e { XCTFail("Test failed for an unexpected reason: \(e)") } } }
mit
33c1c0c917aabf4f1d353bf078ecf754
30.807229
89
0.580303
4.808743
false
true
false
false
ejensen/cleartext-mac
Simpler/SimplerTextView.swift
1
2382
// // SimplerTextView.swift // Simpler // // Created by Morten Just Petersen on 11/21/15. // Copyright © 2015 Morten Just Petersen. All rights reserved. // import Cocoa import Quartz protocol SimplerTextViewDelegate { func simplerTextViewKeyUp(character:String) func simplerTextViewGotComplexWord() } class SimplerTextView: NSTextView, SimplerTextStorageDelegate { var simplerDelegate:SimplerTextViewDelegate! var simplerStorage: SimplerTextStorage! required init?(coder: NSCoder) { super.init(coder: coder) wantsLayer = true simplerStorage = SimplerTextStorage() simplerStorage.simpleDelegate = self simplerStorage.addLayoutManager(layoutManager!) layoutManager?.replaceTextStorage(simplerStorage) resetFormatting() NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(SimplerTextView.selectionDidChange(_:)), name: NSTextViewDidChangeSelectionNotification, object: nil) } func selectionDidChange(n:NSNotification){ // Swift.print("view:selectiondidchange") // Swift.print("---inwhich the selected range is \(self.selectedRange())") simplerStorage.selectionDidChange(self.selectedRange()) } func simplerTextStorageGotComplexWord() { simplerDelegate.simplerTextViewGotComplexWord() } func simplerTextStorageGotComplexWordAtRange(range:NSRange) { simplerDelegate.simplerTextViewGotComplexWord() if(NSUserDefaults.standardUserDefaults().boolForKey(C.PREF_FORCESELECT)){ setSelectedRange(range) } } func simplerTextStorageShouldChangeAtts(atts: [String : AnyObject]) { } override func shouldChangeTextInRange(affectedCharRange: NSRange, replacementString: String?) -> Bool { return true } override func shouldChangeTextInRanges(affectedRanges: [NSValue], replacementStrings: [String]?) -> Bool { return true } func resetFormatting(){ font = C.editorFont backgroundColor = C.editorBackgroundColor textColor = C.editorTextColor } override func didChangeText() { super.didChangeText() } override func drawRect(dirtyRect: NSRect) { super.drawRect(dirtyRect) // Drawing code here. } }
gpl-3.0
4e1656d181fb823daee3f25917c31389
28.7625
184
0.685846
5.164859
false
false
false
false
e78l/swift-corelibs-foundation
Foundation/URLComponents.swift
2
26980
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // /// A structure designed to parse URLs based on RFC 3986 and to construct URLs from their constituent parts. /// /// Its behavior differs subtly from the `URL` struct, which conforms to older RFCs. However, you can easily obtain a `URL` based on the contents of a `URLComponents` or vice versa. public struct URLComponents : ReferenceConvertible, Hashable, Equatable, _MutableBoxing { public typealias ReferenceType = NSURLComponents internal var _handle: _MutableHandle<NSURLComponents> /// Initialize with all components undefined. public init() { _handle = _MutableHandle(adoptingReference: NSURLComponents()) } /// Initialize with the components of a URL. /// /// If resolvingAgainstBaseURL is `true` and url is a relative URL, the components of url.absoluteURL are used. If the url string from the URL is malformed, nil is returned. public init?(url: URL, resolvingAgainstBaseURL resolve: Bool) { guard let result = NSURLComponents(url: url, resolvingAgainstBaseURL: resolve) else { return nil } _handle = _MutableHandle(adoptingReference: result) } /// Initialize with a URL string. /// /// If the URLString is malformed, nil is returned. public init?(string: String) { guard let result = NSURLComponents(string: string) else { return nil } _handle = _MutableHandle(adoptingReference: result) } /// Returns a URL created from the URLComponents. /// /// If the URLComponents has an authority component (user, password, host or port) and a path component, then the path must either begin with "/" or be an empty string. If the URLComponents does not have an authority component (user, password, host or port) and has a path component, the path component must not start with "//". If those requirements are not met, nil is returned. public var url: URL? { return _handle.map { $0.url } } /// Returns a URL created from the URLComponents relative to a base URL. /// /// If the URLComponents has an authority component (user, password, host or port) and a path component, then the path must either begin with "/" or be an empty string. If the URLComponents does not have an authority component (user, password, host or port) and has a path component, the path component must not start with "//". If those requirements are not met, nil is returned. public func url(relativeTo base: URL?) -> URL? { return _handle.map { $0.url(relativeTo: base) } } // Returns a URL string created from the URLComponents. If the URLComponents has an authority component (user, password, host or port) and a path component, then the path must either begin with "/" or be an empty string. If the URLComponents does not have an authority component (user, password, host or port) and has a path component, the path component must not start with "//". If those requirements are not met, nil is returned. public var string: String? { return _handle.map { $0.string } } /// The scheme subcomponent of the URL. /// /// The getter for this property removes any percent encoding this component may have (if the component allows percent encoding). Setting this property assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding). /// Attempting to set the scheme with an invalid scheme string will cause an exception. public var scheme: String? { get { return _handle.map { $0.scheme } } set { _applyMutation { $0.scheme = newValue } } } /// The user subcomponent of the URL. /// /// The getter for this property removes any percent encoding this component may have (if the component allows percent encoding). Setting this property assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding). /// /// Warning: IETF STD 66 (rfc3986) says the use of the format "user:password" in the userinfo subcomponent of a URI is deprecated because passing authentication information in clear text has proven to be a security risk. However, there are cases where this practice is still needed, and so the user and password components and methods are provided. public var user: String? { get { return _handle.map { $0.user } } set { _applyMutation { $0.user = newValue } } } /// The password subcomponent of the URL. /// /// The getter for this property removes any percent encoding this component may have (if the component allows percent encoding). Setting this property assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding). /// /// Warning: IETF STD 66 (rfc3986) says the use of the format "user:password" in the userinfo subcomponent of a URI is deprecated because passing authentication information in clear text has proven to be a security risk. However, there are cases where this practice is still needed, and so the user and password components and methods are provided. public var password: String? { get { return _handle.map { $0.password } } set { _applyMutation { $0.password = newValue } } } /// The host subcomponent. /// /// The getter for this property removes any percent encoding this component may have (if the component allows percent encoding). Setting this property assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding). public var host: String? { get { return _handle.map { $0.host } } set { _applyMutation { $0.host = newValue } } } /// The port subcomponent. /// /// The getter for this property removes any percent encoding this component may have (if the component allows percent encoding). Setting this property assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding). /// Attempting to set a negative port number will cause a fatal error. public var port: Int? { get { return _handle.map { $0.port?.intValue } } set { _applyMutation { $0.port = newValue != nil ? NSNumber(value: newValue!) : nil as NSNumber?} } } /// The path subcomponent. /// /// The getter for this property removes any percent encoding this component may have (if the component allows percent encoding). Setting this property assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding). public var path: String { get { return _handle.map { $0.path } ?? "" } set { _applyMutation { $0.path = newValue } } } /// The query subcomponent. /// /// The getter for this property removes any percent encoding this component may have (if the component allows percent encoding). Setting this property assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding). public var query: String? { get { return _handle.map { $0.query } } set { _applyMutation { $0.query = newValue } } } /// The fragment subcomponent. /// /// The getter for this property removes any percent encoding this component may have (if the component allows percent encoding). Setting this property assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding). public var fragment: String? { get { return _handle.map { $0.fragment } } set { _applyMutation { $0.fragment = newValue } } } /// The user subcomponent, percent-encoded. /// /// The getter for this property retains any percent encoding this component may have. Setting this properties assumes the component string is already correctly percent encoded. Attempting to set an incorrectly percent encoded string will cause a `fatalError`. Although ';' is a legal path character, it is recommended that it be percent-encoded for best compatibility with `URL` (`String.addingPercentEncoding(withAllowedCharacters:)` will percent-encode any ';' characters if you pass `CharacterSet.urlUserAllowed`). public var percentEncodedUser: String? { get { return _handle.map { $0.percentEncodedUser } } set { _applyMutation { $0.percentEncodedUser = newValue } } } /// The password subcomponent, percent-encoded. /// /// The getter for this property retains any percent encoding this component may have. Setting this properties assumes the component string is already correctly percent encoded. Attempting to set an incorrectly percent encoded string will cause a `fatalError`. Although ';' is a legal path character, it is recommended that it be percent-encoded for best compatibility with `URL` (`String.addingPercentEncoding(withAllowedCharacters:)` will percent-encode any ';' characters if you pass `CharacterSet.urlPasswordAllowed`). public var percentEncodedPassword: String? { get { return _handle.map { $0.percentEncodedPassword } } set { _applyMutation { $0.percentEncodedPassword = newValue } } } /// The host subcomponent, percent-encoded. /// /// The getter for this property retains any percent encoding this component may have. Setting this properties assumes the component string is already correctly percent encoded. Attempting to set an incorrectly percent encoded string will cause a `fatalError`. Although ';' is a legal path character, it is recommended that it be percent-encoded for best compatibility with `URL` (`String.addingPercentEncoding(withAllowedCharacters:)` will percent-encode any ';' characters if you pass `CharacterSet.urlHostAllowed`). public var percentEncodedHost: String? { get { return _handle.map { $0.percentEncodedHost } } set { _applyMutation { $0.percentEncodedHost = newValue } } } /// The path subcomponent, percent-encoded. /// /// The getter for this property retains any percent encoding this component may have. Setting this properties assumes the component string is already correctly percent encoded. Attempting to set an incorrectly percent encoded string will cause a `fatalError`. Although ';' is a legal path character, it is recommended that it be percent-encoded for best compatibility with `URL` (`String.addingPercentEncoding(withAllowedCharacters:)` will percent-encode any ';' characters if you pass `CharacterSet.urlPathAllowed`). public var percentEncodedPath: String { get { return _handle.map { $0.percentEncodedPath } ?? "" } set { _applyMutation { $0.percentEncodedPath = newValue } } } /// The query subcomponent, percent-encoded. /// /// The getter for this property retains any percent encoding this component may have. Setting this properties assumes the component string is already correctly percent encoded. Attempting to set an incorrectly percent encoded string will cause a `fatalError`. Although ';' is a legal path character, it is recommended that it be percent-encoded for best compatibility with `URL` (`String.addingPercentEncoding(withAllowedCharacters:)` will percent-encode any ';' characters if you pass `CharacterSet.urlQueryAllowed`). public var percentEncodedQuery: String? { get { return _handle.map { $0.percentEncodedQuery } } set { _applyMutation { $0.percentEncodedQuery = newValue } } } /// The fragment subcomponent, percent-encoded. /// /// The getter for this property retains any percent encoding this component may have. Setting this properties assumes the component string is already correctly percent encoded. Attempting to set an incorrectly percent encoded string will cause a `fatalError`. Although ';' is a legal path character, it is recommended that it be percent-encoded for best compatibility with `URL` (`String.addingPercentEncoding(withAllowedCharacters:)` will percent-encode any ';' characters if you pass `CharacterSet.urlFragmentAllowed`). public var percentEncodedFragment: String? { get { return _handle.map { $0.percentEncodedFragment } } set { _applyMutation { $0.percentEncodedFragment = newValue } } } private func _toStringRange(_ r : NSRange) -> Range<String.Index>? { guard r.location != NSNotFound else { return nil } let utf16Start = String.UTF16View.Index(encodedOffset: r.location) let utf16End = String.UTF16View.Index(encodedOffset: r.location + r.length) guard let s = self.string else { return nil } guard let start = String.Index(utf16Start, within: s) else { return nil } guard let end = String.Index(utf16End, within: s) else { return nil } return start..<end } /// Returns the character range of the scheme in the string returned by `var string`. /// /// If the component does not exist, nil is returned. /// - note: Zero length components are legal. For example, the URL string "scheme://:@/?#" has a zero length user, password, host, query and fragment; the URL strings "scheme:" and "" both have a zero length path. public var rangeOfScheme: Range<String.Index>? { return _toStringRange(_handle.map { $0.rangeOfScheme }) } /// Returns the character range of the user in the string returned by `var string`. /// /// If the component does not exist, nil is returned. /// - note: Zero length components are legal. For example, the URL string "scheme://:@/?#" has a zero length user, password, host, query and fragment; the URL strings "scheme:" and "" both have a zero length path. public var rangeOfUser: Range<String.Index>? { return _toStringRange(_handle.map { $0.rangeOfUser}) } /// Returns the character range of the password in the string returned by `var string`. /// /// If the component does not exist, nil is returned. /// - note: Zero length components are legal. For example, the URL string "scheme://:@/?#" has a zero length user, password, host, query and fragment; the URL strings "scheme:" and "" both have a zero length path. public var rangeOfPassword: Range<String.Index>? { return _toStringRange(_handle.map { $0.rangeOfPassword}) } /// Returns the character range of the host in the string returned by `var string`. /// /// If the component does not exist, nil is returned. /// - note: Zero length components are legal. For example, the URL string "scheme://:@/?#" has a zero length user, password, host, query and fragment; the URL strings "scheme:" and "" both have a zero length path. public var rangeOfHost: Range<String.Index>? { return _toStringRange(_handle.map { $0.rangeOfHost}) } /// Returns the character range of the port in the string returned by `var string`. /// /// If the component does not exist, nil is returned. /// - note: Zero length components are legal. For example, the URL string "scheme://:@/?#" has a zero length user, password, host, query and fragment; the URL strings "scheme:" and "" both have a zero length path. public var rangeOfPort: Range<String.Index>? { return _toStringRange(_handle.map { $0.rangeOfPort}) } /// Returns the character range of the path in the string returned by `var string`. /// /// If the component does not exist, nil is returned. /// - note: Zero length components are legal. For example, the URL string "scheme://:@/?#" has a zero length user, password, host, query and fragment; the URL strings "scheme:" and "" both have a zero length path. public var rangeOfPath: Range<String.Index>? { return _toStringRange(_handle.map { $0.rangeOfPath}) } /// Returns the character range of the query in the string returned by `var string`. /// /// If the component does not exist, nil is returned. /// - note: Zero length components are legal. For example, the URL string "scheme://:@/?#" has a zero length user, password, host, query and fragment; the URL strings "scheme:" and "" both have a zero length path. public var rangeOfQuery: Range<String.Index>? { return _toStringRange(_handle.map { $0.rangeOfQuery}) } /// Returns the character range of the fragment in the string returned by `var string`. /// /// If the component does not exist, nil is returned. /// - note: Zero length components are legal. For example, the URL string "scheme://:@/?#" has a zero length user, password, host, query and fragment; the URL strings "scheme:" and "" both have a zero length path. public var rangeOfFragment: Range<String.Index>? { return _toStringRange(_handle.map { $0.rangeOfFragment}) } /// Returns an array of query items for this `URLComponents`, in the order in which they appear in the original query string. /// /// Each `URLQueryItem` represents a single key-value pair, /// /// Note that a name may appear more than once in a single query string, so the name values are not guaranteed to be unique. If the `URLComponents` has an empty query component, returns an empty array. If the `URLComponents` has no query component, returns nil. /// /// The setter combines an array containing any number of `URLQueryItem`s, each of which represents a single key-value pair, into a query string and sets the `URLComponents` query property. Passing an empty array sets the query component of the `URLComponents` to an empty string. Passing nil removes the query component of the `URLComponents`. /// /// - note: If a name-value pair in a query is empty (i.e. the query string starts with '&', ends with '&', or has "&&" within it), you get a `URLQueryItem` with a zero-length name and and a nil value. If a query's name-value pair has nothing before the equals sign, you get a zero-length name. If a query's name-value pair has nothing after the equals sign, you get a zero-length value. If a query's name-value pair has no equals sign, the query name-value pair string is the name and you get a nil value. public var queryItems: [URLQueryItem]? { get { return _handle.map { $0.queryItems } } set { _applyMutation { $0.queryItems = newValue } } } public func hash(into hasher: inout Hasher) { hasher.combine(_handle.map { $0 }) } // MARK: - Bridging fileprivate init(reference: NSURLComponents) { _handle = _MutableHandle(reference: reference) } public static func ==(lhs: URLComponents, rhs: URLComponents) -> Bool { // Don't copy references here; no one should be storing anything return lhs._handle._uncopiedReference().isEqual(rhs._handle._uncopiedReference()) } } extension URLComponents : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable { public var description: String { if let u = url { return u.description } else { return self.customMirror.children.reduce("") { $0.appending("\($1.label ?? ""): \($1.value) ") } } } public var debugDescription: String { return self.description } public var customMirror: Mirror { var c: [(label: String?, value: Any)] = [] if let s = self.scheme { c.append((label: "scheme", value: s)) } if let u = self.user { c.append((label: "user", value: u)) } if let pw = self.password { c.append((label: "password", value: pw)) } if let h = self.host { c.append((label: "host", value: h)) } if let p = self.port { c.append((label: "port", value: p)) } c.append((label: "path", value: self.path)) if #available(macOS 10.10, iOS 8.0, *) { if let qi = self.queryItems { c.append((label: "queryItems", value: qi )) } } if let f = self.fragment { c.append((label: "fragment", value: f)) } let m = Mirror(self, children: c, displayStyle: .struct) return m } } /// A single name-value pair, for use with `URLComponents`. public struct URLQueryItem : ReferenceConvertible, Hashable, Equatable { public typealias ReferenceType = NSURLQueryItem fileprivate var _queryItem : NSURLQueryItem public init(name: String, value: String?) { _queryItem = NSURLQueryItem(name: name, value: value) } fileprivate init(reference: NSURLQueryItem) { _queryItem = reference.copy() as! NSURLQueryItem } fileprivate var reference : NSURLQueryItem { return _queryItem } public var name: String { get { return _queryItem.name } set { _queryItem = NSURLQueryItem(name: newValue, value: value) } } public var value: String? { get { return _queryItem.value } set { _queryItem = NSURLQueryItem(name: name, value: newValue) } } public func hash(into hasher: inout Hasher) { hasher.combine(_queryItem) } public static func ==(lhs: URLQueryItem, rhs: URLQueryItem) -> Bool { return lhs._queryItem.isEqual(rhs._queryItem) } } extension URLQueryItem : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable { public var description: String { if let v = value { return "\(name)=\(v)" } else { return name } } public var debugDescription: String { return self.description } public var customMirror: Mirror { var c: [(label: String?, value: Any)] = [] c.append((label: "name", value: name)) c.append((label: "value", value: value as Any)) return Mirror(self, children: c, displayStyle: .struct) } } extension NSURLComponents : _SwiftBridgeable { typealias SwiftType = URLComponents internal var _swiftObject: SwiftType { return URLComponents(reference: self) } } extension URLComponents : _NSBridgeable { typealias NSType = NSURLComponents internal var _nsObject: NSType { return _handle._copiedReference() } } extension NSURLQueryItem : _SwiftBridgeable { typealias SwiftType = URLQueryItem internal var _swiftObject: SwiftType { return URLQueryItem(reference: self) } } extension URLQueryItem : _NSBridgeable { typealias NSType = NSURLQueryItem internal var _nsObject: NSType { return _queryItem } } extension URLComponents : _ObjectiveCBridgeable { public typealias _ObjectType = NSURLComponents public static func _getObjectiveCType() -> Any.Type { return NSURLComponents.self } @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSURLComponents { return _handle._copiedReference() } public static func _forceBridgeFromObjectiveC(_ x: NSURLComponents, result: inout URLComponents?) { if !_conditionallyBridgeFromObjectiveC(x, result: &result) { fatalError("Unable to bridge \(_ObjectType.self) to \(self)") } } public static func _conditionallyBridgeFromObjectiveC(_ x: NSURLComponents, result: inout URLComponents?) -> Bool { result = URLComponents(reference: x) return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSURLComponents?) -> URLComponents { var result: URLComponents? = nil _forceBridgeFromObjectiveC(source!, result: &result) return result! } } extension URLQueryItem : _ObjectiveCBridgeable { public typealias _ObjectType = NSURLQueryItem public static func _getObjectiveCType() -> Any.Type { return NSURLQueryItem.self } @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSURLQueryItem { return _queryItem } public static func _forceBridgeFromObjectiveC(_ x: NSURLQueryItem, result: inout URLQueryItem?) { if !_conditionallyBridgeFromObjectiveC(x, result: &result) { fatalError("Unable to bridge \(_ObjectType.self) to \(self)") } } public static func _conditionallyBridgeFromObjectiveC(_ x: NSURLQueryItem, result: inout URLQueryItem?) -> Bool { result = URLQueryItem(reference: x) return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSURLQueryItem?) -> URLQueryItem { var result: URLQueryItem? = nil _forceBridgeFromObjectiveC(source!, result: &result) return result! } } extension URLComponents : Codable { private enum CodingKeys : Int, CodingKey { case scheme case user case password case host case port case path case query case fragment } public init(from decoder: Decoder) throws { self.init() let container = try decoder.container(keyedBy: CodingKeys.self) self.scheme = try container.decodeIfPresent(String.self, forKey: .scheme) self.user = try container.decodeIfPresent(String.self, forKey: .user) self.password = try container.decodeIfPresent(String.self, forKey: .password) self.host = try container.decodeIfPresent(String.self, forKey: .host) self.port = try container.decodeIfPresent(Int.self, forKey: .port) self.path = try container.decode(String.self, forKey: .path) self.query = try container.decodeIfPresent(String.self, forKey: .query) self.fragment = try container.decodeIfPresent(String.self, forKey: .fragment) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(self.scheme, forKey: .scheme) try container.encodeIfPresent(self.user, forKey: .user) try container.encodeIfPresent(self.password, forKey: .password) try container.encodeIfPresent(self.host, forKey: .host) try container.encodeIfPresent(self.port, forKey: .port) try container.encode(self.path, forKey: .path) try container.encodeIfPresent(self.query, forKey: .query) try container.encodeIfPresent(self.fragment, forKey: .fragment) } }
apache-2.0
087a32648da6d0b4610ffd129d737827
53.285714
526
0.685804
4.84033
false
false
false
false
MaxHasADHD/TraktKit
Common/Wrapper/CompletionHandlers.swift
1
20557
// // CompletionHandlers.swift // TraktKit // // Created by Maximilian Litteral on 10/29/16. // Copyright © 2016 Maximilian Litteral. All rights reserved. // import Foundation /// Generic result type public enum ObjectResultType<T: Codable> { case success(object: T) case error(error: Error?) } /// Generic results type public enum ObjectsResultType<T: Codable> { case success(objects: [T]) case error(error: Error?) } /// Generic results type + Pagination public enum ObjectsResultTypePagination<T: Codable> { case success(objects: [T], currentPage: Int, limit: Int) case error(error: Error?) } extension TraktManager { // MARK: - Result Types public enum DataResultType { case success(data: Data) case error(error: Error?) } public enum SuccessResultType { case success case fail } public enum ProgressResultType { case success case fail(Int) } public enum WatchingResultType { case checkedIn(watching: TraktWatching) case notCheckedIn case error(error: Error?) } public enum CheckinResultType { case success(checkin: TraktCheckinResponse) case checkedIn(expiration: Date) case error(error: Error?) } public enum TraktKitError: Error { case couldNotParseData case handlingRetry } public enum TraktError: Error { /// Bad Request - request couldn't be parsed case badRequest /// Oauth must be provided case unauthorized /// Forbidden - invalid API key or unapproved app case forbidden /// Not Found - method exists, but no record found case noRecordFound /// Method Not Found - method doesn't exist case noMethodFound /// Conflict - resource already created case resourceAlreadyCreated /// Account Limit Exceeded - list count, item count, etc case accountLimitExceeded /// Locked User Account - have the user contact support case accountLocked /// VIP Only - user must upgrade to VIP case vipOnly /// Rate Limit Exceeded case rateLimitExceeded(HTTPURLResponse) /// Service Unavailable - server overloaded (try again in 30s) case serverOverloaded /// Service Unavailable - Cloudflare error case cloudflareError /// Full url response case unhandled(HTTPURLResponse) } // MARK: - Completion handlers // MARK: Common public typealias ObjectCompletionHandler<T: Codable> = (_ result: ObjectResultType<T>) -> Void public typealias ObjectsCompletionHandler<T: Codable> = (_ result: ObjectsResultType<T>) -> Void public typealias paginatedCompletionHandler<T: Codable> = (_ result: ObjectsResultTypePagination<T>) -> Void public typealias DataResultCompletionHandler = (_ result: DataResultType) -> Void public typealias SuccessCompletionHandler = (_ result: SuccessResultType) -> Void public typealias ProgressCompletionHandler = (_ result: ProgressResultType) -> Void public typealias CommentsCompletionHandler = paginatedCompletionHandler<Comment> // public typealias CastCrewCompletionHandler = ObjectCompletionHandler<CastAndCrew> public typealias SearchCompletionHandler = ObjectsCompletionHandler<TraktSearchResult> public typealias statsCompletionHandler = ObjectCompletionHandler<TraktStats> // MARK: Shared public typealias UpdateCompletionHandler = paginatedCompletionHandler<Update> public typealias AliasCompletionHandler = ObjectsCompletionHandler<Alias> public typealias RatingDistributionCompletionHandler = ObjectCompletionHandler<RatingDistribution> // MARK: Calendar public typealias dvdReleaseCompletionHandler = ObjectsCompletionHandler<TraktDVDReleaseMovie> // MARK: Checkin public typealias checkinCompletionHandler = (_ result: CheckinResultType) -> Void // MARK: Shows public typealias TrendingShowsCompletionHandler = paginatedCompletionHandler<TraktTrendingShow> public typealias MostShowsCompletionHandler = paginatedCompletionHandler<TraktMostShow> public typealias AnticipatedShowCompletionHandler = paginatedCompletionHandler<TraktAnticipatedShow> public typealias ShowTranslationsCompletionHandler = ObjectsCompletionHandler<TraktShowTranslation> public typealias SeasonsCompletionHandler = ObjectsCompletionHandler<TraktSeason> public typealias WatchedShowsCompletionHandler = ObjectsCompletionHandler<TraktWatchedShow> public typealias ShowWatchedProgressCompletionHandler = ObjectCompletionHandler<TraktShowWatchedProgress> // MARK: Episodes public typealias EpisodeCompletionHandler = ObjectCompletionHandler<TraktEpisode> public typealias EpisodesCompletionHandler = ObjectsCompletionHandler<TraktEpisode> // MARK: Movies public typealias MovieCompletionHandler = ObjectCompletionHandler<TraktMovie> public typealias MoviesCompletionHandler = ObjectsCompletionHandler<TraktMovie> public typealias TrendingMoviesCompletionHandler = paginatedCompletionHandler<TraktTrendingMovie> public typealias MostMoviesCompletionHandler = paginatedCompletionHandler<TraktMostMovie> public typealias AnticipatedMovieCompletionHandler = paginatedCompletionHandler<TraktAnticipatedMovie> public typealias MovieTranslationsCompletionHandler = ObjectsCompletionHandler<TraktMovieTranslation> public typealias WatchedMoviesCompletionHandler = paginatedCompletionHandler<TraktWatchedMovie> public typealias BoxOfficeMoviesCompletionHandler = ObjectsCompletionHandler<TraktBoxOfficeMovie> // MARK: Sync public typealias LastActivitiesCompletionHandler = ObjectCompletionHandler<TraktLastActivities> public typealias RatingsCompletionHandler = ObjectsCompletionHandler<TraktRating> public typealias HistoryCompletionHandler = paginatedCompletionHandler<TraktHistoryItem> public typealias CollectionCompletionHandler = ObjectsCompletionHandler<TraktCollectedItem> // MARK: Users public typealias ListCompletionHandler = ObjectCompletionHandler<TraktList> public typealias ListsCompletionHandler = ObjectsCompletionHandler<TraktList> public typealias ListItemCompletionHandler = ObjectsCompletionHandler<TraktListItem> public typealias WatchlistCompletionHandler = paginatedCompletionHandler<TraktListItem> public typealias HiddenItemsCompletionHandler = paginatedCompletionHandler<HiddenItem> public typealias UserCommentsCompletionHandler = ObjectsCompletionHandler<UsersComments> public typealias AddListItemCompletion = ObjectCompletionHandler<ListItemPostResult> public typealias RemoveListItemCompletion = ObjectCompletionHandler<RemoveListItemResult> public typealias FollowUserCompletion = ObjectCompletionHandler<FollowUserResult> public typealias FollowersCompletion = ObjectsCompletionHandler<FollowResult> public typealias FriendsCompletion = ObjectsCompletionHandler<Friend> public typealias WatchingCompletion = (_ result: WatchingResultType) -> Void public typealias UserStatsCompletion = ObjectCompletionHandler<UserStats> public typealias UserWatchedCompletion = ObjectsCompletionHandler<TraktWatchedItem> // MARK: - Error handling private func handleResponse(response: URLResponse?, retry: @escaping (() -> Void)) throws { guard let httpResponse = response as? HTTPURLResponse else { throw TraktKitError.couldNotParseData } guard 200...299 ~= httpResponse.statusCode else { switch httpResponse.statusCode { case StatusCodes.BadRequest: throw TraktError.badRequest case StatusCodes.Unauthorized: throw TraktError.unauthorized case StatusCodes.Forbidden: throw TraktError.forbidden case StatusCodes.NotFound: throw TraktError.noRecordFound case StatusCodes.MethodNotFound: throw TraktError.noMethodFound case StatusCodes.Conflict: throw TraktError.resourceAlreadyCreated case StatusCodes.AccountLimitExceeded: throw TraktError.accountLimitExceeded case StatusCodes.acountLocked: throw TraktError.accountLocked case StatusCodes.vipOnly: throw TraktError.vipOnly case StatusCodes.RateLimitExceeded: if let retryAfter = httpResponse.allHeaderFields["retry-after"] as? String, let retryInterval = TimeInterval(retryAfter) { DispatchQueue.main.asyncAfter(deadline: .now() + retryInterval) { retry() } /// To ensure completionHandler isn't called when retrying. throw TraktKitError.handlingRetry } else { throw TraktError.rateLimitExceeded(httpResponse) } case 503, 504: throw TraktError.serverOverloaded case 500...600: throw TraktError.cloudflareError default: throw TraktError.unhandled(httpResponse) } } } // MARK: - Perform Requests func perform<T: Codable>(request: URLRequest) async throws -> T { let (data, _) = try await session.data(for: request) let decoder = JSONDecoder() decoder.dateDecodingStrategy = .custom(customDateDecodingStrategy) let object = try decoder.decode(T.self, from: data) return object } /// Data func performRequest(request: URLRequest, completion: @escaping DataResultCompletionHandler) -> URLSessionDataTaskProtocol? { let datatask = session._dataTask(with: request) { [weak self] data, response, error in guard let self = self else { return } guard error == nil else { completion(.error(error: error)) return } // Check response do { try self.handleResponse(response: response, retry: { _ = self.performRequest(request: request, completion: completion) }) } catch { switch error { case TraktKitError.handlingRetry: break default: completion(.error(error: error)) } return } // Check data guard let data = data else { completion(.error(error: TraktKitError.couldNotParseData)) return } completion(.success(data: data)) } datatask.resume() return datatask } /// Success / Failure func performRequest(request: URLRequest, completion: @escaping SuccessCompletionHandler) -> URLSessionDataTaskProtocol? { let datatask = session._dataTask(with: request) { [weak self] data, response, error in guard let self = self else { return } guard error == nil else { completion(.fail) return } // Check response do { try self.handleResponse(response: response, retry: { _ = self.performRequest(request: request, completion: completion) }) } catch { switch error { case TraktKitError.handlingRetry: break default: completion(.fail) } return } completion(.success) } datatask.resume() return datatask } /// Checkin func performRequest(request: URLRequest, completion: @escaping checkinCompletionHandler) -> URLSessionDataTaskProtocol? { let datatask = session._dataTask(with: request) { [weak self] data, response, error in guard let self = self else { return } guard error == nil else { completion(.error(error: error)) return } // Check data guard let data = data else { completion(.error(error: TraktKitError.couldNotParseData)) return } let decoder = JSONDecoder() decoder.dateDecodingStrategy = .custom(customDateDecodingStrategy) if let checkin = try? decoder.decode(TraktCheckinResponse.self, from: data) { completion(.success(checkin: checkin)) return } else if let jsonObject = try? JSONSerialization.jsonObject(with: data, options: .allowFragments), let jsonDictionary = jsonObject as? RawJSON, let expirationDateString = jsonDictionary["expires_at"] as? String, let expirationDate = try? Date.dateFromString(expirationDateString) { completion(.checkedIn(expiration: expirationDate)) return } // Check response do { try self.handleResponse(response: response, retry: { _ = self.performRequest(request: request, completion: completion) }) } catch { switch error { case TraktKitError.handlingRetry: break default: completion(.error(error: error)) } return } completion(.error(error: nil)) } datatask.resume() return datatask } // Generic array of Trakt objects func performRequest<T>(request: URLRequest, completion: @escaping ((_ result: ObjectResultType<T>) -> Void)) -> URLSessionDataTaskProtocol? { let aCompletion: DataResultCompletionHandler = { (result) -> Void in switch result { case .success(let data): let decoder = JSONDecoder() decoder.dateDecodingStrategy = .custom(customDateDecodingStrategy) do { let object = try decoder.decode(T.self, from: data) completion(.success(object: object)) } catch { completion(.error(error: error)) } case .error(let error): completion(.error(error: error)) } } let dataTask = performRequest(request: request, completion: aCompletion) return dataTask } /// Array of TraktProtocol objects func performRequest<T: Decodable>(request: URLRequest, completion: @escaping ((_ result: ObjectsResultType<T>) -> Void)) -> URLSessionDataTaskProtocol? { let dataTask = session._dataTask(with: request) { [weak self] data, response, error in guard let self = self else { return } guard error == nil else { completion(.error(error: error)) return } // Check response do { try self.handleResponse(response: response, retry: { _ = self.performRequest(request: request, completion: completion) }) } catch { switch error { case TraktKitError.handlingRetry: break default: completion(.error(error: error)) } return } // Check data guard let data = data else { completion(.error(error: TraktKitError.couldNotParseData)) return } let decoder = JSONDecoder() decoder.dateDecodingStrategy = .custom(customDateDecodingStrategy) do { let array = try decoder.decode([T].self, from: data) completion(.success(objects: array)) } catch { completion(.error(error: error)) } } dataTask.resume() return dataTask } /// Array of ObjectsResultTypePagination objects func performRequest<T>(request: URLRequest, completion: @escaping ((_ result: ObjectsResultTypePagination<T>) -> Void)) -> URLSessionDataTaskProtocol? { let dataTask = session._dataTask(with: request) { [weak self] data, response, error in guard let self = self else { return } guard error == nil else { completion(.error(error: error)) return } guard let httpResponse = response as? HTTPURLResponse else { return completion(.error(error: nil)) } // Check response do { try self.handleResponse(response: response, retry: { _ = self.performRequest(request: request, completion: completion) }) } catch { switch error { case TraktKitError.handlingRetry: break default: completion(.error(error: error)) } return } var pageCount: Int = 0 if let pCount = httpResponse.allHeaderFields["x-pagination-page-count"] as? String, let pCountInt = Int(pCount) { pageCount = pCountInt } var currentPage: Int = 0 if let cPage = httpResponse.allHeaderFields["x-pagination-page"] as? String, let cPageInt = Int(cPage) { currentPage = cPageInt } // Check data guard let data = data else { completion(.error(error: TraktKitError.couldNotParseData)) return } let decoder = JSONDecoder() decoder.dateDecodingStrategy = .custom(customDateDecodingStrategy) do { let array = try decoder.decode([T].self, from: data) completion(.success(objects: array, currentPage: currentPage, limit: pageCount)) } catch { completion(.error(error: error)) } } dataTask.resume() return dataTask } // Watching func performRequest(request: URLRequest, completion: @escaping WatchingCompletion) -> URLSessionDataTaskProtocol? { let dataTask = session._dataTask(with: request) { [weak self] data, response, error in guard let self = self else { return } guard error == nil else { completion(.error(error: error)) return } guard let httpResponse = response as? HTTPURLResponse else { return completion(.error(error: nil)) } // Check response do { try self.handleResponse(response: response, retry: { _ = self.performRequest(request: request, completion: completion) }) } catch { switch error { case TraktKitError.handlingRetry: break default: completion(.error(error: error)) } return } if httpResponse.statusCode == StatusCodes.SuccessNoContentToReturn { completion(.notCheckedIn) return } // Check data guard let data = data else { completion(.error(error: TraktKitError.couldNotParseData)) return } let decoder = JSONDecoder() decoder.dateDecodingStrategy = .custom(customDateDecodingStrategy) do { let watching = try decoder.decode(TraktWatching.self, from: data) completion(.checkedIn(watching: watching)) } catch { completion(.error(error: error)) } } dataTask.resume() return dataTask } }
mit
49e488f3744d72c41224e5c81bbe16c9
39.148438
157
0.604933
6.126975
false
false
false
false
ben-ng/swift
test/SILGen/collection_subtype_downcast.swift
7
1885
// RUN: %target-swift-frontend -emit-silgen -sdk %S/Inputs %s | %FileCheck %s struct S { var x, y: Int } // CHECK-LABEL: sil hidden @_TF27collection_subtype_downcast14array_downcastFT5arrayGSaP___GSqGSaVS_1S__ : // CHECK: bb0([[ARG:%.*]] : $Array<Any>): // CHECK-NEXT: debug_value [[ARG]] // CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[FN:%.*]] = function_ref @_TFs21_arrayConditionalCastu0_rFGSax_GSqGSaq___ // CHECK-NEXT: [[RESULT:%.*]] = apply [[FN]]<Any, S>([[ARG_COPY]]) : $@convention(thin) <τ_0_0, τ_0_1> (@owned Array<τ_0_0>) -> @owned Optional<Array<τ_0_1>> // CHECK-NEXT: destroy_value [[ARG]] // CHECK-NEXT: return [[RESULT]] func array_downcast(array: [Any]) -> [S]? { return array as? [S] } extension S : Hashable { var hashValue : Int { return x + y } } func ==(lhs: S, rhs: S) -> Bool { return true } // FIXME: This entrypoint name should not be bridging-specific // CHECK-LABEL: sil hidden @_TF27collection_subtype_downcast13dict_downcastFT4dictGVs10DictionaryVS_1SP___GSqGS0_S1_Si__ : // CHECK: bb0([[ARG:%.*]] : $Dictionary<S, Any>): // CHECK-NEXT: debug_value [[ARG]] // CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[FN:%.*]] = function_ref @_TFs30_dictionaryDownCastConditionalu2_Rxs8Hashable0_S_rFGVs10Dictionaryxq__GSqGS0_q0_q1___ // CHECK-NEXT: [[RESULT:%.*]] = apply [[FN]]<S, Any, S, Int>([[ARG_COPY]]) : $@convention(thin) <τ_0_0, τ_0_1, τ_0_2, τ_0_3 where τ_0_0 : Hashable, τ_0_2 : Hashable> (@owned Dictionary<τ_0_0, τ_0_1>) -> @owned Optional<Dictionary<τ_0_2, τ_0_3>> // CHECK-NEXT: destroy_value [[ARG]] // CHECK-NEXT: return [[RESULT]] func dict_downcast(dict: [S: Any]) -> [S: Int]? { return dict as? [S: Int] } // It's not actually possible to test this for Sets independent of // the bridging rules.
apache-2.0
8fc96887f581f4fcdbdf6ade03f82fea
43.547619
244
0.633351
2.83915
false
false
false
false
PhillipEnglish/TIY-Assignments
DudeWheresMyCar/Forecaster/CityAPIController.swift
1
2055
// // CityAPIController.swift // Forecaster // // Created by Phillip English on 11/1/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import Foundation class CityAPIController { var delegate: CityAPIControllerProtocol? //var task: NSURLSessionDataTask! init(cityDelegate: CityAPIControllerProtocol) { self.delegate = cityDelegate } func searchGoogleForCity(searchTerm: String) { // let googleSearchTerm = searchTerm //let urlPath = "http://maps.googleapis.com/maps/api/geocode/json?&components=postal_code:\(googleSearchTerm)&sensor=false" //let url = NSURL(string: "https://maps.googleapis.com/maps/api/geocode/json?address=santa+cruz&components=postal_code:\(searchTerm)&sensor=false") //NSURL(string: urlPath) let urlPath = "https://maps.googleapis.com/maps/api/geocode/json?address=santa+cruz&components=postal_code:\(searchTerm)&sensor=false" let url = NSURL(string: urlPath) let session = NSURLSession.sharedSession() let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in //print("Task completed") if error != nil { print(error!.localizedDescription) } else { if let dictionary = self.parseJSON(data!) { if let results: NSArray = dictionary["results"] as? NSArray { self.delegate?.didReceiveMapsAPIResults(results) } } } }) task.resume() } func parseJSON(data: NSData) -> NSDictionary? { do { let dictionary: NSDictionary! = try NSJSONSerialization.JSONObjectWithData(data, options: []) as! NSDictionary return dictionary } catch let error as NSError { print(error) return nil } } }
cc0-1.0
3de3e334678bf33836b84c08a68c6db1
29.205882
185
0.574002
4.867299
false
false
false
false
Decybel07/L10n-swift
Source/Core/Resource/Resource/DictionaryResource.swift
1
2352
// // DictionaryResource.swift // L10n_swift // // Created by Adrian Bobrowski on 09.11.2017. // Copyright © 2017 Adrian Bobrowski (Decybel07), [email protected]. All rights reserved. // internal struct DictionaryResource: Resource { private let values: [String: Resource] private let fittingWidths: [Int] subscript(_ key: String) -> Resource { return self.values[key] ?? EmptyResource() } subscript(_ fittingWidth: Int?) -> Resource { if self.fittingWidths.isEmpty { return self } guard let fittingWidth = fittingWidth else { return self.fittingWidths.last.flatMap { self.values[$0.description] }.unsafelyUnwrapped } var width = self.fittingWidths[0] for current in self.fittingWidths.dropFirst() where current <= fittingWidth { width = current } return self.values[width.description].unsafelyUnwrapped } var isEmpty: Bool { return self.values.isEmpty } func text() -> String? { return self.values["value"]?.text() } func merging(_ other: Resource) -> Resource { let otherValues = (other as? DictionaryResource)?.values ?? ["value": other] return DictionaryResource(self.values.merging(otherValues) { $0.merging($1) }) } init(_ dictionary: [String: Any]) { self.init(dictionary.reduce(into: [String: Resource]()) { result, pair in var resource: Resource! let keys = pair.key.components(separatedBy: ".") if keys.count > 1 { resource = DictionaryResource([keys.dropFirst().joined(separator: "."): pair.value]) } else if let value = pair.value as? [String: Any] { resource = DictionaryResource(value) } else if let value = pair.value as? String { resource = StringResource(value) } else { return } result[keys[0]] = (result[keys[0]] ?? EmptyResource()).merging(resource) }) } init(_ values: [String: Resource]) { self.values = values #if swift(>=4.1) self.fittingWidths = values.keys.compactMap { Int($0) }.sorted() #else self.fittingWidths = values.keys.flatMap { Int($0) }.sorted() #endif } }
mit
b39fe992743286c362564014e5a0e863
31.205479
100
0.587835
4.478095
false
false
false
false
frootloops/swift
test/stdlib/Dispatch.swift
4
19073
// RUN: rm -rf %t // RUN: mkdir -p %t // RUN: %target-build-swift %s -o %t/a.out_swift3 -swift-version 3 // RUN: %target-build-swift %s -o %t/a.out_swift4 -swift-version 4 // // RUN: %target-run %t/a.out_swift3 // RUN: %target-run %t/a.out_swift4 // REQUIRES: executable_test // REQUIRES: objc_interop import Dispatch import Foundation import StdlibUnittest defer { runAllTests() } var DispatchAPI = TestSuite("DispatchAPI") DispatchAPI.test("constants") { expectEqual(2147483648, DispatchSource.ProcessEvent.exit.rawValue) expectEqual(0, DispatchData.empty.endIndex) // This is a lousy test, but really we just care that // DISPATCH_QUEUE_CONCURRENT comes through at all. _ = DispatchQueue.Attributes.concurrent } DispatchAPI.test("OS_OBJECT support") { let mainQueue = DispatchQueue.main as AnyObject expectTrue(mainQueue is DispatchQueue) // This should not be optimized out, and should succeed. expectNotNil(mainQueue as? DispatchQueue) } DispatchAPI.test("DispatchGroup creation") { let group = DispatchGroup() expectNotNil(group) } DispatchAPI.test("Dispatch sync return value") { let value = 24; let q = DispatchQueue(label: "Test") let result = q.sync() { return 24 } expectEqual(value, result) } DispatchAPI.test("dispatch_block_t conversions") { var counter = 0 let closure = { () -> Void in counter += 1 } typealias Block = @convention(block) () -> () let block = closure as Block block() expectEqual(1, counter) let closureAgain = block as () -> Void closureAgain() expectEqual(2, counter) } if #available(OSX 10.10, iOS 8.0, *) { DispatchAPI.test("dispatch_block_t identity") { let block = DispatchWorkItem(flags: .inheritQoS) { _ = 1 } DispatchQueue.main.async(execute: block) // This will trap if the block's pointer identity is not preserved. block.cancel() } } DispatchAPI.test("dispatch_data_t enumeration") { // Ensure we can iterate the empty iterator for _ in DispatchData.empty { _ = 1 } } DispatchAPI.test("dispatch_data_t deallocator") { let q = DispatchQueue(label: "dealloc queue") var t = 0 autoreleasepool { let size = 1024 let p = UnsafeMutablePointer<UInt8>.allocate(capacity: size) let _ = DispatchData(bytesNoCopy: UnsafeBufferPointer(start: p, count: size), deallocator: .custom(q, { t = 1 })) } q.sync { expectEqual(1, t) } } DispatchAPI.test("DispatchTime comparisons") { do { let now = DispatchTime.now() checkComparable([now, now + .milliseconds(1), .distantFuture], oracle: { return $0 < $1 ? .lt : $0 == $1 ? .eq : .gt }) } do { let now = DispatchWallTime.now() checkComparable([now, now + .milliseconds(1), .distantFuture], oracle: { return $0 < $1 ? .lt : $0 == $1 ? .eq : .gt }) } } DispatchAPI.test("DispatchTime.create") { var info = mach_timebase_info_data_t(numer: 1, denom: 1) mach_timebase_info(&info) let scales = info.numer != info.denom // Simple tests for non-overflow behavior var time = DispatchTime(uptimeNanoseconds: 0) expectEqual(time.uptimeNanoseconds, 0) time = DispatchTime(uptimeNanoseconds: 15 * NSEC_PER_SEC) expectEqual(time.uptimeNanoseconds, 15 * NSEC_PER_SEC) // On platforms where the timebase scale is not 1, the next two cases // overflow and become DISPATCH_TIME_FOREVER (UInt64.max) instead of trapping. time = DispatchTime(uptimeNanoseconds: UInt64.max - 1) expectEqual(time.uptimeNanoseconds, scales ? UInt64.max : UInt64.max - UInt64(1)) time = DispatchTime(uptimeNanoseconds: UInt64.max / 2) expectEqual(time.uptimeNanoseconds, scales ? UInt64.max : UInt64.max / 2) // UInt64.max must always be returned as UInt64.max. time = DispatchTime(uptimeNanoseconds: UInt64.max) expectEqual(time.uptimeNanoseconds, UInt64.max) } DispatchAPI.test("DispatchTime.addSubtract") { var then = DispatchTime.now() + Double.infinity expectEqual(DispatchTime.distantFuture, then) then = DispatchTime.now() + Double.nan expectEqual(DispatchTime.distantFuture, then) then = DispatchTime.now() - Double.infinity expectEqual(DispatchTime(uptimeNanoseconds: 1), then) then = DispatchTime.now() - Double.nan expectEqual(DispatchTime.distantFuture, then) then = DispatchTime.now() + Date.distantFuture.timeIntervalSinceNow expectEqual(DispatchTime(uptimeNanoseconds: UInt64.max), then) then = DispatchTime.now() + Date.distantPast.timeIntervalSinceNow expectEqual(DispatchTime(uptimeNanoseconds: 1), then) then = DispatchTime.now() - Date.distantFuture.timeIntervalSinceNow expectEqual(DispatchTime(uptimeNanoseconds: 1), then) then = DispatchTime.now() - Date.distantPast.timeIntervalSinceNow expectEqual(DispatchTime(uptimeNanoseconds: UInt64.max), then) } DispatchAPI.test("DispatchWallTime.addSubtract") { let distantPastRawValue = DispatchWallTime.distantFuture.rawValue - UInt64(1) var then = DispatchWallTime.now() + Double.infinity expectEqual(DispatchWallTime.distantFuture, then) then = DispatchWallTime.now() + Double.nan expectEqual(DispatchWallTime.distantFuture, then) then = DispatchWallTime.now() - Double.infinity expectEqual(distantPastRawValue, then.rawValue) then = DispatchWallTime.now() - Double.nan expectEqual(DispatchWallTime.distantFuture, then) then = DispatchWallTime.now() + Date.distantFuture.timeIntervalSinceNow expectEqual(DispatchWallTime.distantFuture, then) then = DispatchWallTime.now() + Date.distantPast.timeIntervalSinceNow expectEqual(distantPastRawValue, then.rawValue) then = DispatchWallTime.now() - Date.distantFuture.timeIntervalSinceNow expectEqual(distantPastRawValue, then.rawValue) then = DispatchWallTime.now() - Date.distantPast.timeIntervalSinceNow expectEqual(DispatchWallTime.distantFuture, then) } DispatchAPI.test("DispatchTime.uptimeNanos") { let seconds = 1 let nowMach = DispatchTime.now() let oneSecondFromNowMach = nowMach + .seconds(seconds) let nowNanos = nowMach.uptimeNanoseconds let oneSecondFromNowNanos = oneSecondFromNowMach.uptimeNanoseconds let diffNanos = oneSecondFromNowNanos - nowNanos expectEqual(NSEC_PER_SEC, diffNanos) } DispatchAPI.test("DispatchData.copyBytes") { let source1: [UInt8] = [0, 1, 2, 3] let srcPtr1 = UnsafeBufferPointer(start: source1, count: source1.count) var dest: [UInt8] = [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF] let destPtr = UnsafeMutableBufferPointer(start: UnsafeMutablePointer(&dest), count: dest.count) var dispatchData = DispatchData(bytes: srcPtr1) // Copy from offset 0 var count = dispatchData.copyBytes(to: destPtr, from: 0..<2) expectEqual(count, 2) expectEqual(destPtr[0], 0) expectEqual(destPtr[1], 1) expectEqual(destPtr[2], 0xFF) expectEqual(destPtr[3], 0xFF) expectEqual(destPtr[4], 0xFF) expectEqual(destPtr[5], 0xFF) // Copy from offset 2 count = dispatchData.copyBytes(to: destPtr, from: 2..<4) expectEqual(count, 2) expectEqual(destPtr[0], 2) expectEqual(destPtr[1], 3) expectEqual(destPtr[2], 0xFF) expectEqual(destPtr[3], 0xFF) expectEqual(destPtr[4], 0xFF) expectEqual(destPtr[5], 0xFF) // Add two more regions let source2: [UInt8] = [0x10, 0x11, 0x12, 0x13] let srcPtr2 = UnsafeBufferPointer(start: source2, count: source2.count) dispatchData.append(DispatchData(bytes: srcPtr2)) let source3: [UInt8] = [0x14, 0x15, 0x16] let srcPtr3 = UnsafeBufferPointer(start: source3, count: source3.count) dispatchData.append(DispatchData(bytes: srcPtr3)) // Copy from offset 0. Copies across the first two regions count = dispatchData.copyBytes(to: destPtr, from: 0..<6) expectEqual(count, 6) expectEqual(destPtr[0], 0) expectEqual(destPtr[1], 1) expectEqual(destPtr[2], 2) expectEqual(destPtr[3], 3) expectEqual(destPtr[4], 0x10) expectEqual(destPtr[5], 0x11) // Copy from offset 2. Copies across the first two regions count = dispatchData.copyBytes(to: destPtr, from: 2..<8) expectEqual(count, 6) expectEqual(destPtr[0], 2) expectEqual(destPtr[1], 3) expectEqual(destPtr[2], 0x10) expectEqual(destPtr[3], 0x11) expectEqual(destPtr[4], 0x12) expectEqual(destPtr[5], 0x13) // Copy from offset 3. Copies across all three regions count = dispatchData.copyBytes(to: destPtr, from: 3..<9) expectEqual(count, 6) expectEqual(destPtr[0], 3) expectEqual(destPtr[1], 0x10) expectEqual(destPtr[2], 0x11) expectEqual(destPtr[3], 0x12) expectEqual(destPtr[4], 0x13) expectEqual(destPtr[5], 0x14) // Copy from offset 5. Skips the first region and the first byte of the second count = dispatchData.copyBytes(to: destPtr, from: 5..<11) expectEqual(count, 6) expectEqual(destPtr[0], 0x11) expectEqual(destPtr[1], 0x12) expectEqual(destPtr[2], 0x13) expectEqual(destPtr[3], 0x14) expectEqual(destPtr[4], 0x15) expectEqual(destPtr[5], 0x16) // Copy from offset 8. Skips the first two regions destPtr[3] = 0xFF destPtr[4] = 0xFF destPtr[5] = 0xFF count = dispatchData.copyBytes(to: destPtr, from: 8..<11) expectEqual(count, 3) expectEqual(destPtr[0], 0x14) expectEqual(destPtr[1], 0x15) expectEqual(destPtr[2], 0x16) expectEqual(destPtr[3], 0xFF) expectEqual(destPtr[4], 0xFF) expectEqual(destPtr[5], 0xFF) // Copy from offset 9. Skips the first two regions and the first byte of the third destPtr[2] = 0xFF destPtr[3] = 0xFF destPtr[4] = 0xFF destPtr[5] = 0xFF count = dispatchData.copyBytes(to: destPtr, from: 9..<11) expectEqual(count, 2) expectEqual(destPtr[0], 0x15) expectEqual(destPtr[1], 0x16) expectEqual(destPtr[2], 0xFF) expectEqual(destPtr[3], 0xFF) expectEqual(destPtr[4], 0xFF) expectEqual(destPtr[5], 0xFF) // Copy from offset 9, but only 1 byte. Ends before the end of the data destPtr[1] = 0xFF destPtr[2] = 0xFF destPtr[3] = 0xFF destPtr[4] = 0xFF destPtr[5] = 0xFF count = dispatchData.copyBytes(to: destPtr, from: 9..<10) expectEqual(count, 1) expectEqual(destPtr[0], 0x15) expectEqual(destPtr[1], 0xFF) expectEqual(destPtr[2], 0xFF) expectEqual(destPtr[3], 0xFF) expectEqual(destPtr[4], 0xFF) expectEqual(destPtr[5], 0xFF) // Copy from offset 2, but only 1 byte. This copy is bounded within the // first region. destPtr[1] = 0xFF destPtr[2] = 0xFF destPtr[3] = 0xFF destPtr[4] = 0xFF destPtr[5] = 0xFF count = dispatchData.copyBytes(to: destPtr, from: 2..<3) expectEqual(count, 1) expectEqual(destPtr[0], 2) expectEqual(destPtr[1], 0xFF) expectEqual(destPtr[2], 0xFF) expectEqual(destPtr[3], 0xFF) expectEqual(destPtr[4], 0xFF) expectEqual(destPtr[5], 0xFF) } DispatchAPI.test("DispatchData.copyBytesUnsafeRawBufferPointer") { let source1: [UInt8] = [0, 1, 2, 3] let srcPtr1 = UnsafeRawBufferPointer(start: source1, count: source1.count) var dest: [UInt8] = [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF] let destPtr = UnsafeMutableRawBufferPointer(start: UnsafeMutablePointer(&dest), count: dest.count) var dispatchData = DispatchData(bytes: srcPtr1) // Copy from offset 0 dispatchData.copyBytes(to: destPtr, from: 0..<2) expectEqual(destPtr[0], 0) expectEqual(destPtr[1], 1) expectEqual(destPtr[2], 0xFF) expectEqual(destPtr[3], 0xFF) expectEqual(destPtr[4], 0xFF) expectEqual(destPtr[5], 0xFF) // Copy from offset 2 dispatchData.copyBytes(to: destPtr, from: 2..<4) expectEqual(destPtr[0], 2) expectEqual(destPtr[1], 3) expectEqual(destPtr[2], 0xFF) expectEqual(destPtr[3], 0xFF) expectEqual(destPtr[4], 0xFF) expectEqual(destPtr[5], 0xFF) // Add two more regions let source2: [UInt8] = [0x10, 0x11, 0x12, 0x13] let srcPtr2 = UnsafeRawBufferPointer(start: source2, count: source2.count) dispatchData.append(DispatchData(bytes: srcPtr2)) let source3: [UInt8] = [0x14, 0x15, 0x16] let srcPtr3 = UnsafeRawBufferPointer(start: source3, count: source3.count) dispatchData.append(DispatchData(bytes: srcPtr3)) // Copy from offset 0. Copies across the first two regions dispatchData.copyBytes(to: destPtr, from: 0..<6) expectEqual(destPtr[0], 0) expectEqual(destPtr[1], 1) expectEqual(destPtr[2], 2) expectEqual(destPtr[3], 3) expectEqual(destPtr[4], 0x10) expectEqual(destPtr[5], 0x11) // Copy from offset 2. Copies across the first two regions dispatchData.copyBytes(to: destPtr, from: 2..<8) expectEqual(destPtr[0], 2) expectEqual(destPtr[1], 3) expectEqual(destPtr[2], 0x10) expectEqual(destPtr[3], 0x11) expectEqual(destPtr[4], 0x12) expectEqual(destPtr[5], 0x13) // Copy from offset 3. Copies across all three regions dispatchData.copyBytes(to: destPtr, from: 3..<9) expectEqual(destPtr[0], 3) expectEqual(destPtr[1], 0x10) expectEqual(destPtr[2], 0x11) expectEqual(destPtr[3], 0x12) expectEqual(destPtr[4], 0x13) expectEqual(destPtr[5], 0x14) // Copy from offset 5. Skips the first region and the first byte of the second dispatchData.copyBytes(to: destPtr, from: 5..<11) expectEqual(destPtr[0], 0x11) expectEqual(destPtr[1], 0x12) expectEqual(destPtr[2], 0x13) expectEqual(destPtr[3], 0x14) expectEqual(destPtr[4], 0x15) expectEqual(destPtr[5], 0x16) // Copy from offset 8. Skips the first two regions destPtr[3] = 0xFF destPtr[4] = 0xFF destPtr[5] = 0xFF dispatchData.copyBytes(to: destPtr, from: 8..<11) expectEqual(destPtr[0], 0x14) expectEqual(destPtr[1], 0x15) expectEqual(destPtr[2], 0x16) expectEqual(destPtr[3], 0xFF) expectEqual(destPtr[4], 0xFF) expectEqual(destPtr[5], 0xFF) // Copy from offset 9. Skips the first two regions and the first byte of the third destPtr[2] = 0xFF destPtr[3] = 0xFF destPtr[4] = 0xFF destPtr[5] = 0xFF dispatchData.copyBytes(to: destPtr, from: 9..<11) expectEqual(destPtr[0], 0x15) expectEqual(destPtr[1], 0x16) expectEqual(destPtr[2], 0xFF) expectEqual(destPtr[3], 0xFF) expectEqual(destPtr[4], 0xFF) expectEqual(destPtr[5], 0xFF) // Copy from offset 9, but only 1 byte. Ends before the end of the data destPtr[1] = 0xFF destPtr[2] = 0xFF destPtr[3] = 0xFF destPtr[4] = 0xFF destPtr[5] = 0xFF dispatchData.copyBytes(to: destPtr, from: 9..<10) expectEqual(destPtr[0], 0x15) expectEqual(destPtr[1], 0xFF) expectEqual(destPtr[2], 0xFF) expectEqual(destPtr[3], 0xFF) expectEqual(destPtr[4], 0xFF) expectEqual(destPtr[5], 0xFF) // Copy from offset 2, but only 1 byte. This copy is bounded within the // first region. destPtr[1] = 0xFF destPtr[2] = 0xFF destPtr[3] = 0xFF destPtr[4] = 0xFF destPtr[5] = 0xFF dispatchData.copyBytes(to: destPtr, from: 2..<3) expectEqual(destPtr[0], 2) expectEqual(destPtr[1], 0xFF) expectEqual(destPtr[2], 0xFF) expectEqual(destPtr[3], 0xFF) expectEqual(destPtr[4], 0xFF) expectEqual(destPtr[5], 0xFF) } DispatchAPI.test("DispatchData.buffers") { let bytes = [UInt8(0), UInt8(1), UInt8(2), UInt8(2)] var ptr = UnsafeBufferPointer<UInt8>(start: bytes, count: bytes.count) var data = DispatchData(bytes: ptr) expectEqual(bytes.count, data.count) for i in 0..<data.count { expectEqual(data[i], bytes[i]) } data = DispatchData(bytesNoCopy: ptr, deallocator: .custom(nil, {})) expectEqual(bytes.count, data.count) for i in 0..<data.count { expectEqual(data[i], bytes[i]) } ptr = UnsafeBufferPointer<UInt8>(start: nil, count: 0) data = DispatchData(bytes: ptr) expectEqual(data.count, 0) data = DispatchData(bytesNoCopy: ptr, deallocator: .custom(nil, {})) expectEqual(data.count, 0) } DispatchAPI.test("DispatchData.bufferUnsafeRawBufferPointer") { let bytes = [UInt8(0), UInt8(1), UInt8(2), UInt8(2)] var ptr = UnsafeRawBufferPointer(start: bytes, count: bytes.count) var data = DispatchData(bytes: ptr) expectEqual(bytes.count, data.count) for i in 0..<data.count { expectEqual(data[i], bytes[i]) } data = DispatchData(bytesNoCopy: ptr, deallocator: .custom(nil, {})) expectEqual(bytes.count, data.count) for i in 0..<data.count { expectEqual(data[i], bytes[i]) } ptr = UnsafeRawBufferPointer(start: nil, count: 0) data = DispatchData(bytes: ptr) expectEqual(data.count, 0) data = DispatchData(bytesNoCopy: ptr, deallocator: .custom(nil, {})) expectEqual(data.count, 0) } DispatchAPI.test("DispatchIO.initRelativePath") { let q = DispatchQueue(label: "initRelativePath queue") #if swift(>=4.0) let chan = DispatchIO(type: .random, path: "_REL_PATH_", oflag: O_RDONLY, mode: 0, queue: q, cleanupHandler: { (error) in }) expectEqual(chan, nil) #else expectCrashLater() let chan = DispatchIO(type: .random, path: "_REL_PATH_", oflag: O_RDONLY, mode: 0, queue: q, cleanupHandler: { (error) in }) chan.setInterval(interval: .seconds(1)) // Dereference of unexpected nil should crash #endif } if #available(OSX 10.13, iOS 11.0, watchOS 4.0, tvOS 11.0, *) { var block = DispatchWorkItem(qos: .unspecified, flags: .assignCurrentContext) {} DispatchAPI.test("DispatchSource.replace") { let g = DispatchGroup() let q = DispatchQueue(label: "q") let ds = DispatchSource.makeUserDataReplaceSource(queue: q) var lastValue = UInt(0) var nextValue = UInt(1) let maxValue = UInt(1 << 24) ds.setEventHandler() { let value = ds.data; expectTrue(value > lastValue) // Values must increase expectTrue((value & (value - 1)) == 0) // Must be power of two lastValue = value if value == maxValue { g.leave() } } ds.activate() g.enter() block = DispatchWorkItem(qos: .unspecified, flags: .assignCurrentContext) { ds.replace(data: nextValue) nextValue <<= 1 if nextValue <= maxValue { q.asyncAfter( deadline: DispatchTime.now() + DispatchTimeInterval.milliseconds(1), execute: block) } } q.asyncAfter( deadline: DispatchTime.now() + DispatchTimeInterval.milliseconds(1), execute: block) let result = g.wait(timeout: DispatchTime.now() + .seconds(30)) expectTrue(result == .success) } } DispatchAPI.test("DispatchTimeInterval") { // Basic tests that the correct value is stored and the == method works for i in stride(from:1, through: 100, by: 5) { expectEqual(DispatchTimeInterval.seconds(i), DispatchTimeInterval.milliseconds(i * 1000)) expectEqual(DispatchTimeInterval.milliseconds(i), DispatchTimeInterval.microseconds(i * 1000)) expectEqual(DispatchTimeInterval.microseconds(i), DispatchTimeInterval.nanoseconds(i * 1000)) } // Check some cases that used to cause arithmetic overflow when evaluating the rawValue for == var t = DispatchTimeInterval.seconds(Int.max) expectTrue(t == t) // This would crash. t = DispatchTimeInterval.seconds(-Int.max) expectTrue(t == t) // This would crash. t = DispatchTimeInterval.milliseconds(Int.max) expectTrue(t == t) // This would crash. t = DispatchTimeInterval.milliseconds(-Int.max) expectTrue(t == t) // This would crash. t = DispatchTimeInterval.microseconds(Int.max) expectTrue(t == t) // This would crash. t = DispatchTimeInterval.microseconds(-Int.max) expectTrue(t == t) // This would crash. } #if swift(>=4.0) DispatchAPI.test("DispatchTimeInterval.never.equals") { expectTrue(DispatchTimeInterval.never == DispatchTimeInterval.never) expectTrue(DispatchTimeInterval.seconds(10) != DispatchTimeInterval.never); expectTrue(DispatchTimeInterval.never != DispatchTimeInterval.seconds(10)); expectTrue(DispatchTimeInterval.seconds(10) == DispatchTimeInterval.seconds(10)); } #endif
apache-2.0
80e02c6162b8a0e9840bca23759c5d7b
30.473597
125
0.724322
3.304973
false
false
false
false
Wakup/Wakup-iOS-SDK
Wakup/CompanyCategory.swift
1
647
// // CompanyCategory.swift // Wakup // // Created by Guillermo Gutiérrez Doral on 14/12/18. // Copyright © 2018 Yellow Pineapple. All rights reserved. // import Foundation open class CompanyCategory: Equatable { public let id: Int public let name: String public let tags: [String] public let companies: [CompanyWithCount] init(id: Int, name: String, tags: [String], companies: [CompanyWithCount]) { self.id = id self.name = name self.tags = tags self.companies = companies } } public func ==(lhs: CompanyCategory, rhs: CompanyCategory) -> Bool { return lhs.id == rhs.id }
mit
9e07db388b2be11db0bf4711240e8572
22.888889
80
0.649612
3.816568
false
false
false
false
alexrson/jCal
jCal/DateViewController.swift
1
971
// // DateViewController.swift // jCal // // Created by Alexander Robertson on 1/12/15. // Copyright (c) 2015 Alexander Robertson. All rights reserved. // import UIKit class DateViewController: UIViewController { var timer = NSTimer() @IBOutlet var DateLabel : UILabel? @IBOutlet var dateTabItem: UITabBarItem! override func viewDidLoad() { super.viewDidLoad() update() let aSelector : Selector = "update" timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: aSelector, userInfo: nil, repeats: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func update() { // Date let today = get_today_fdate(0) self.DateLabel?.text = (today.french_date as String) + "\n" + (today.french_name as String) } override func prefersStatusBarHidden() -> Bool { return true } }
mit
27914604718a2ada0f2ad5e542348f09
24.552632
99
0.630278
4.43379
false
false
false
false
toco/Intro-to-tvOS
FocusDemo/FocusDemo/ViewController.swift
1
1115
// // ViewController.swift // FocusDemo // // Created by Tobias Conradi on 05.11.15. // Copyright © 2015 Tobias Conradi. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var button4: UIButton! @IBOutlet weak var button7: UIButton! @IBOutlet weak var bottomStack: UIStackView! override func viewDidLoad() { super.viewDidLoad() addFocousGuide() } override func didUpdateFocusInContext(context: UIFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) { super.didUpdateFocusInContext(context, withAnimationCoordinator: coordinator) } func addFocousGuide() { let focusGuide = UIFocusGuide() view.addLayoutGuide(focusGuide) focusGuide.leftAnchor.constraintEqualToAnchor(button4.leftAnchor).active = true focusGuide.topAnchor.constraintEqualToAnchor(button7.topAnchor).active = true focusGuide.widthAnchor.constraintEqualToAnchor(button4.widthAnchor).active = true focusGuide.heightAnchor.constraintEqualToAnchor(button7.heightAnchor).active = true focusGuide.preferredFocusedView = button7 } }
mit
1254f2952e2050f4619a34b3a32de3f7
24.318182
138
0.792639
4.420635
false
false
false
false
NUKisZ/TestKitchen_1606
TestKitchen/TestKitchen/classes/cookbook/recommend/view/CBRecommendNewCell.swift
1
3377
// // CBRecommendNewCell.swift // TestKitchen // // Created by NUK on 16/8/19. // Copyright © 2016年 NUK. All rights reserved. // import UIKit class CBRecommendNewCell: UITableViewCell { @IBAction func clickBtn(sender: UIButton) { } //播放视频 @IBAction func playAction(sender: UIButton) { } var model:CBRecommendWidgetListModel?{ didSet{ showData() } } func showData(){ //按照三列来遍历 for i in 0..<3{ //图片 // if model?.widget_data?.count > i * 4{ let imageModel = model?.widget_data![i*4] if imageModel?.type == "image"{ let url = NSURL(string: (imageModel?.content)!) let dImage = UIImage(named: "sdefaultImage") let subView = contentView.viewWithTag(200+i) if subView?.isKindOfClass(UIImageView.self) == true{ let imageView = subView as! UIImageView imageView.kf_setImageWithURL(url, placeholderImage: dImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil) } } } //视频 //标题 if model?.widget_data?.count > i*4 + 2{ let titleModel = model?.widget_data![i*4+2] if titleModel?.type == "text"{ //获取标题的Label let subView = contentView.viewWithTag(400+i) if subView?.isKindOfClass(UILabel.self) == true{ let titleLabel = subView as! UILabel titleLabel.text = titleModel?.content! } } } //描述 if model?.widget_data?.count > i*4 + 3{ let descModel = model?.widget_data![i*4+3] if descModel?.type == "text"{ //获取标题的Label let subView = contentView.viewWithTag(500+i) if subView?.isKindOfClass(UILabel.self) == true{ let descLabel = subView as! UILabel descLabel.text = descModel?.content! } } } } } //创建cell的方法 class func createNewCellFor(tableView:UITableView,atIndexPath indexPath:NSIndexPath,withListModel listModel:CBRecommendWidgetListModel)->CBRecommendNewCell{ let cellId = "recommendNewCellId" var cell = tableView.dequeueReusableCellWithIdentifier(cellId)as? CBRecommendNewCell if cell == nil { cell = NSBundle.mainBundle().loadNibNamed("CBRecommendNewCell", owner: nil, options: nil).last as? CBRecommendNewCell } cell?.model = listModel return cell! } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
2f4ce12e6f2a9dd761a3c531c648608b
29.330275
160
0.497278
5.340872
false
false
false
false
TouchInstinct/LeadKit
Sources/Extensions/UIKit/UIWindow/UIWindow+Extensions.swift
1
2776
// // Copyright (c) 2017 Touch Instinct // // 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 extension UIWindow { /// default scale static let snapshotScale: CGFloat = 1.5 /// default root controller animation duration static let snapshotAnimationDuration = 0.5 /// Method changes root controller in window. /// /// - Parameter controller: New root controller. /// - Parameter animated: Indicates whether to use animation or not. func changeRootController(controller: UIViewController, animated: Bool = true) { if animated { animateRootViewControllerChanging(controller: controller) } let previousRoot = rootViewController previousRoot?.dismiss(animated: false) { previousRoot?.view.removeFromSuperview() } rootViewController = controller makeKeyAndVisible() } /** method animates changing root controller - parameter controller: new root controller */ private func animateRootViewControllerChanging(controller: UIViewController) { if let snapshot = snapshotView(afterScreenUpdates: true) { controller.view.addSubview(snapshot) UIView.animate(withDuration: UIWindow.snapshotAnimationDuration, animations: { snapshot.layer.opacity = 0.0 snapshot.layer.transform = CATransform3DMakeScale(UIWindow.snapshotScale, UIWindow.snapshotScale, UIWindow.snapshotScale) }, completion: { _ in snapshot.removeFromSuperview() }) } } }
apache-2.0
b8f138e9aa9bb6727034daaa22cc892d
39.823529
90
0.669308
5.29771
false
false
false
false
cuappdev/podcast-ios
Recast/Utilities/NavigationController.swift
1
1040
// // NavigationController.swift // Recast // // Created by Jack Thompson on 11/17/18. // Copyright © 2018 Cornell AppDev. All rights reserved. // import UIKit class NavigationController: UINavigationController { override init(rootViewController: UIViewController) { super.init(rootViewController: rootViewController) navigationBar.prefersLargeTitles = true navigationBar.barTintColor = .black navigationBar.tintColor = .white navigationBar.isOpaque = true navigationBar.isTranslucent = false let textAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white] navigationBar.titleTextAttributes = textAttributes navigationBar.largeTitleTextAttributes = textAttributes } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
67a57210be3cfe423e3b8afcf386fb63
29.558824
84
0.717036
5.439791
false
false
false
false
scinfu/SwiftSoup
Tests/SwiftSoupTests/XmlTreeBuilderTest.swift
1
9149
// // XmlTreeBuilderTest.swift // SwiftSoup // // Created by Nabil Chatbi on 14/10/16. // Copyright © 2016 Nabil Chatbi.. All rights reserved. // import XCTest import SwiftSoup class XmlTreeBuilderTest: XCTestCase { func testLinuxTestSuiteIncludesAllTests() { #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) let thisClass = type(of: self) let linuxCount = thisClass.allTests.count let darwinCount = Int(thisClass.defaultTestSuite.testCaseCount) XCTAssertEqual(linuxCount, darwinCount, "\(darwinCount - linuxCount) tests are missing from allTests") #endif } func testSimpleXmlParse()throws { let xml = "<doc id=2 href='/bar'>Foo <br /><link>One</link><link>Two</link></doc>" let treeBuilder: XmlTreeBuilder = XmlTreeBuilder() let doc: Document = try treeBuilder.parse(xml, "http://foo.com/") XCTAssertEqual("<doc id=\"2\" href=\"/bar\">Foo <br /><link>One</link><link>Two</link></doc>", try TextUtil.stripNewlines(doc.html())) XCTAssertEqual(try doc.getElementById("2")?.absUrl("href"), "http://foo.com/bar") } func testPopToClose()throws { // test: </val> closes Two, </bar> ignored let xml = "<doc><val>One<val>Two</val></bar>Three</doc>" let treeBuilder: XmlTreeBuilder = XmlTreeBuilder() let doc = try treeBuilder.parse(xml, "http://foo.com/") XCTAssertEqual("<doc><val>One<val>Two</val>Three</val></doc>", try TextUtil.stripNewlines(doc.html())) } func testCommentAndDocType()throws { let xml = "<!DOCTYPE HTML><!-- a comment -->One <qux />Two" let treeBuilder: XmlTreeBuilder = XmlTreeBuilder() let doc = try treeBuilder.parse(xml, "http://foo.com/") XCTAssertEqual("<!DOCTYPE HTML><!-- a comment -->One <qux />Two", try TextUtil.stripNewlines(doc.html())) } func testSupplyParserToJsoupClass()throws { let xml = "<doc><val>One<val>Two</val></bar>Three</doc>" let doc = try SwiftSoup.parse(xml, "http://foo.com/", Parser.xmlParser()) try XCTAssertEqual("<doc><val>One<val>Two</val>Three</val></doc>", TextUtil.stripNewlines(doc.html())) } //TODO: nabil // public void testSupplyParserToConnection() throws IOException { // String xmlUrl = "http://direct.infohound.net/tools/jsoup-xml-test.xml"; // // // parse with both xml and html parser, ensure different // Document xmlDoc = Jsoup.connect(xmlUrl).parser(Parser.xmlParser()).get(); // Document htmlDoc = Jsoup.connect(xmlUrl).parser(Parser.htmlParser()).get(); // Document autoXmlDoc = Jsoup.connect(xmlUrl).get(); // check connection auto detects xml, uses xml parser // // XCTAssertEqual("<doc><val>One<val>Two</val>Three</val></doc>", // TextUtil.stripNewlines(xmlDoc.html())); // assertFalse(htmlDoc.equals(xmlDoc)); // XCTAssertEqual(xmlDoc, autoXmlDoc); // XCTAssertEqual(1, htmlDoc.select("head").size()); // html parser normalises // XCTAssertEqual(0, xmlDoc.select("head").size()); // xml parser does not // XCTAssertEqual(0, autoXmlDoc.select("head").size()); // xml parser does not // } //TODO: nabil // func testSupplyParserToDataStream()throws { // let testBundle = Bundle(for: type(of: self)) // let fileURL = testBundle.url(forResource: "xml-test", withExtension: "xml") // File xmlFile = new File(XmlTreeBuilder.class.getResource("/htmltests/xml-test.xml").toURI()); // InputStream inStream = new FileInputStream(xmlFile); // let doc = Jsoup.parse(inStream, null, "http://foo.com", Parser.xmlParser()); // XCTAssertEqual("<doc><val>One<val>Two</val>Three</val></doc>", // TextUtil.stripNewlines(doc.html())); // } func testDoesNotForceSelfClosingKnownTags()throws { // html will force "<br>one</br>" to logically "<br />One<br />". // XML should be stay "<br>one</br> -- don't recognise tag. let htmlDoc = try SwiftSoup.parse("<br>one</br>") XCTAssertEqual("<br>one\n<br>", try htmlDoc.body()?.html()) let xmlDoc = try SwiftSoup.parse("<br>one</br>", "", Parser.xmlParser()) XCTAssertEqual("<br>one</br>", try xmlDoc.html()) } func testHandlesXmlDeclarationAsDeclaration()throws { let html = "<?xml encoding='UTF-8' ?><body>One</body><!-- comment -->" let doc = try SwiftSoup.parse(html, "", Parser.xmlParser()) try XCTAssertEqual("<?xml encoding=\"UTF-8\"?> <body> One </body> <!-- comment -->", StringUtil.normaliseWhitespace(doc.outerHtml())) XCTAssertEqual("#declaration", doc.childNode(0).nodeName()) XCTAssertEqual("#comment", doc.childNode(2).nodeName()) } func testXmlFragment()throws { let xml = "<one src='/foo/' />Two<three><four /></three>" let nodes: [Node] = try Parser.parseXmlFragment(xml, "http://example.com/") XCTAssertEqual(3, nodes.count) try XCTAssertEqual("http://example.com/foo/", nodes[0].absUrl("src")) XCTAssertEqual("one", nodes[0].nodeName()) XCTAssertEqual("Two", (nodes[1] as? TextNode)?.text()) } func testXmlParseDefaultsToHtmlOutputSyntax()throws { let doc = try SwiftSoup.parse("x", "", Parser.xmlParser()) XCTAssertEqual(OutputSettings.Syntax.xml, doc.outputSettings().syntax()) } func testDoesHandleEOFInTag()throws { let html = "<img src=asdf onerror=\"alert(1)\" x=" let xmlDoc = try SwiftSoup.parse(html, "", Parser.xmlParser()) try XCTAssertEqual("<img src=\"asdf\" onerror=\"alert(1)\" x=\"\" />", xmlDoc.html()) } //todo: // func testDetectCharsetEncodingDeclaration()throws{ // File xmlFile = new File(XmlTreeBuilder.class.getResource("/htmltests/xml-charset.xml").toURI()); // InputStream inStream = new FileInputStream(xmlFile); // let doc = Jsoup.parse(inStream, null, "http://example.com/", Parser.xmlParser()); // XCTAssertEqual("ISO-8859-1", doc.charset().name()); // XCTAssertEqual("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?> <data>äöåéü</data>", // TextUtil.stripNewlines(doc.html())); // } func testParseDeclarationAttributes()throws { let xml = "<?xml version='1' encoding='UTF-8' something='else'?><val>One</val>" let doc = try SwiftSoup.parse(xml, "", Parser.xmlParser()) guard let decl: XmlDeclaration = doc.childNode(0) as? XmlDeclaration else { XCTAssertTrue(false) return } try XCTAssertEqual("1", decl.attr("version")) try XCTAssertEqual("UTF-8", decl.attr("encoding")) try XCTAssertEqual("else", decl.attr("something")) try XCTAssertEqual("version=\"1\" encoding=\"UTF-8\" something=\"else\"", decl.getWholeDeclaration()) try XCTAssertEqual("<?xml version=\"1\" encoding=\"UTF-8\" something=\"else\"?>", decl.outerHtml()) } func testCaseSensitiveDeclaration()throws { let xml = "<?XML version='1' encoding='UTF-8' something='else'?>" let doc = try SwiftSoup.parse(xml, "", Parser.xmlParser()) try XCTAssertEqual("<?XML version=\"1\" encoding=\"UTF-8\" something=\"else\"?>", doc.outerHtml()) } func testCreatesValidProlog()throws { let document = Document.createShell("") document.outputSettings().syntax(syntax: OutputSettings.Syntax.xml) try document.charset(String.Encoding.utf8) try XCTAssertEqual("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<html>\n" + " <head></head>\n" + " <body></body>\n" + "</html>", document.outerHtml()) } func testPreservesCaseByDefault()throws { let xml = "<TEST ID=1>Check</TEST>" let doc = try SwiftSoup.parse(xml, "", Parser.xmlParser()) try XCTAssertEqual("<TEST ID=\"1\">Check</TEST>", TextUtil.stripNewlines(doc.html())) } func testCanNormalizeCase()throws { let xml = "<TEST ID=1>Check</TEST>" let doc = try SwiftSoup.parse(xml, "", Parser.xmlParser().settings(ParseSettings.htmlDefault)) try XCTAssertEqual("<test id=\"1\">Check</test>", TextUtil.stripNewlines(doc.html())) } func testNilReplaceInQueue()throws { let html: String = "<TABLE><TBODY><TR><TD></TD><TD><FONT color=#000000 size=1><I><FONT size=5><P align=center></FONT></I></FONT>&nbsp;</P></TD></TR></TBODY></TABLE></TD></TR></TBODY></TABLE></DIV></DIV></DIV><BLOCKQUOTE></BLOCKQUOTE><DIV style=\"FONT: 10pt Courier New\"><BR><BR>&nbsp;</DIV></BODY></HTML>" _ = try SwiftSoup.parse(html) } static var allTests = { return [ ("testLinuxTestSuiteIncludesAllTests", testLinuxTestSuiteIncludesAllTests), ("testSimpleXmlParse", testSimpleXmlParse), ("testPopToClose", testPopToClose), ("testCommentAndDocType", testCommentAndDocType), ("testSupplyParserToJsoupClass", testSupplyParserToJsoupClass), ("testDoesNotForceSelfClosingKnownTags", testDoesNotForceSelfClosingKnownTags), ("testHandlesXmlDeclarationAsDeclaration", testHandlesXmlDeclarationAsDeclaration), ("testXmlFragment", testXmlFragment), ("testXmlParseDefaultsToHtmlOutputSyntax", testXmlParseDefaultsToHtmlOutputSyntax), ("testDoesHandleEOFInTag", testDoesHandleEOFInTag), ("testParseDeclarationAttributes", testParseDeclarationAttributes), ("testCaseSensitiveDeclaration", testCaseSensitiveDeclaration), ("testCreatesValidProlog", testCreatesValidProlog), ("testPreservesCaseByDefault", testPreservesCaseByDefault), ("testCanNormalizeCase", testCanNormalizeCase), ("testNilReplaceInQueue", testNilReplaceInQueue) ] }() }
mit
1a0202c7abb950d84bc86d3685e80ff0
44.715
314
0.681942
3.625297
false
true
false
false
swizzlr/Moya
Demo/DemoTests/Observable+MoyaSpec.swift
2
8050
import Quick import Moya import RxSwift import Nimble // Necessary since UIImage(named:) doesn't work correctly in the test bundle private extension UIImage { class func testPNGImage(named name: String) -> UIImage { class TestClass { } let bundle = NSBundle(forClass: TestClass().dynamicType) let path = bundle.pathForResource(name, ofType: "png") return UIImage(contentsOfFile: path!)! } } private func observableSendingData(data: NSData, statusCode: Int = 200) -> Observable<MoyaResponse> { return just(MoyaResponse(statusCode: statusCode, data: data, response: nil)) } class ObservableMoyaSpec: QuickSpec { override func spec() { describe("status codes filtering") { it("filters out unrequested status codes") { let data = NSData() let observable = observableSendingData(data, statusCode: 10) var errored = false _ = observable.filterStatusCodes(0...9).subscribe { (event) -> Void in switch event { case .Next(let object): XCTFail("called on non-correct status code: \(object)") case .Error: errored = true default: break } } expect(errored).to(beTruthy()) } it("filters out non-successful status codes") { let data = NSData() let observable = observableSendingData(data, statusCode: 404) var errored = false _ = observable.filterSuccessfulStatusCodes().subscribe { (event) -> Void in switch event { case .Next(let object): XCTFail("called on non-success status code: \(object)") case .Error: errored = true default: break } } expect(errored).to(beTruthy()) } it("passes through correct status codes") { let data = NSData() let observable = observableSendingData(data) var called = false _ = observable.filterSuccessfulStatusCodes().subscribeNext { (object) -> Void in called = true } expect(called).to(beTruthy()) } it("filters out non-successful status and redirect codes") { let data = NSData() let observable = observableSendingData(data, statusCode: 404) var errored = false _ = observable.filterSuccessfulStatusAndRedirectCodes().subscribe { (event) -> Void in switch event { case .Next(let object): XCTFail("called on non-success status code: \(object)") case .Error: errored = true default: break } } expect(errored).to(beTruthy()) } it("passes through correct status codes") { let data = NSData() let observable = observableSendingData(data) var called = false _ = observable.filterSuccessfulStatusAndRedirectCodes().subscribeNext { (object) -> Void in called = true } expect(called).to(beTruthy()) } it("passes through correct redirect codes") { let data = NSData() let observable = observableSendingData(data, statusCode: 304) var called = false _ = observable.filterSuccessfulStatusAndRedirectCodes().subscribeNext { (object) -> Void in called = true } expect(called).to(beTruthy()) } } describe("image maping") { it("maps data representing an image to an image") { let image = UIImage.testPNGImage(named: "testImage") let data = UIImageJPEGRepresentation(image, 0.75) let observable = observableSendingData(data!) var size: CGSize? _ = observable.mapImage().subscribeNext { (image) -> Void in size = image.size } expect(size).to(equal(image.size)) } it("ignores invalid data") { let data = NSData() let observable = observableSendingData(data) var receivedError: NSError? _ = observable.mapImage().subscribe { (event) -> Void in switch event { case .Next: XCTFail("next called for invalid data") case .Error(let error): receivedError = error as NSError default: break } } expect(receivedError?.code).to(equal(MoyaErrorCode.ImageMapping.rawValue)) } } describe("JSON mapping") { it("maps data representing some JSON to that JSON") { let json = ["name": "John Crighton", "occupation": "Astronaut"] let data = try! NSJSONSerialization.dataWithJSONObject(json, options: .PrettyPrinted) let observable = observableSendingData(data) var receivedJSON: [String: String]? _ = observable.mapJSON().subscribeNext { (json) -> Void in if let json = json as? [String: String] { receivedJSON = json } } expect(receivedJSON?["name"]).to(equal(json["name"])) expect(receivedJSON?["occupation"]).to(equal(json["occupation"])) } it("returns a Cocoa error domain for invalid JSON") { let json = "{ \"name\": \"john }" let data = json.dataUsingEncoding(NSUTF8StringEncoding) let observable = observableSendingData(data!) var receivedError: NSError? _ = observable.mapJSON().subscribe { (event) -> Void in switch event { case .Next: XCTFail("next called for invalid data") case .Error(let error): receivedError = error as NSError default: break } } expect(receivedError).toNot(beNil()) expect(receivedError?.domain).to(equal("\(NSCocoaErrorDomain)")) } } describe("string mapping") { it("maps data representing a string to a string") { let string = "You have the rights to the remains of a silent attorney." let data = string.dataUsingEncoding(NSUTF8StringEncoding) let observable = observableSendingData(data!) var receivedString: String? _ = observable.mapString().subscribeNext { (string) -> Void in receivedString = string return } expect(receivedString).to(equal(string)) } } } }
mit
93770bde98dd60496d838dcbc8b49e17
38.07767
107
0.46236
6.450321
false
false
false
false
ermalkaleci/CarbonCardView
Sources/CarbonCardViewItem.swift
1
6215
// The MIT License (MIT) // // Copyright (c) 2016 Ermal Kaleci // // 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 @IBDesignable public class CarbonCardViewItem: UIView { public var distanceToSplit: CGFloat = 0 public var cornerRadius: CGFloat = 0 public var shadowOffset: CGSize = CGSizeZero public var shadowRadius: CGFloat = 0 public var shadowOpacity: Float = 0 public var shadowColor: UIColor = UIColor.clearColor() public weak var delegate: CarbonCardViewItemDelegate? public private(set) var isSplitted = false public private(set) var isDragging = false private var beginPoint: CGPoint? private var angle: CGFloat? private func updateCard() { layer.shadowOffset = shadowOffset layer.shadowOpacity = shadowOpacity layer.shadowRadius = shadowRadius layer.shadowPath = UIBezierPath(roundedRect: self.bounds, cornerRadius: self.cornerRadius).CGPath layer.cornerRadius = cornerRadius if let sublayer: CALayer = layer.sublayers?.first { sublayer.cornerRadius = cornerRadius } } override public func layoutSubviews() { super.layoutSubviews() updateCard() } public override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { beginPoint = touches.first?.locationInView(superview) if let point = touches.first?.locationInView(self) { angle = (point.x - center.x) / CGRectGetWidth(bounds) * 4 } } public override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { if let beginPoint = beginPoint, point = touches.first?.locationInView(superview) { let movedByX = point.x - beginPoint.x let movedByY = point.y - beginPoint.y let rotationAngle = movedByX / CGRectGetWidth(bounds) * 0.5 let rotate = CGAffineTransformMakeRotation(rotationAngle) let translate = CGAffineTransformMakeTranslation(movedByX, movedByY) transform = CGAffineTransformConcat(rotate, translate) if sqrt(pow(movedByX, 2) + pow(movedByY, 2)) > distanceToSplit { isSplitted = true delegate?.carbonCardViewItemSplited(self) } else if isSplitted == false { delegate?.translateCarbonCardViewItem(self, point: CGPointMake(movedByX, movedByY), angle: rotationAngle) } } // Set dragging: true after calling delegate to animate first movement isDragging = true } public override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { isDragging = false if let beginPoint = beginPoint, point = touches.first?.locationInView(superview) { let movedByX = point.x - beginPoint.x let movedByY = point.y - beginPoint.y let direction: CarbonCardViewItemRemoveDirection = movedByX < 0 ? .Left : .Right if sqrt(pow(movedByX, 2) + pow(movedByY, 2)) > distanceToSplit { delegate?.removeCarbonCardViewItem(self, direction: direction) } else { reset() } } } public override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) { isDragging = false if let beginPoint = beginPoint, point = touches?.first?.locationInView(superview) { let movedByX = point.x - beginPoint.x let movedByY = point.y - beginPoint.y let direction: CarbonCardViewItemRemoveDirection = movedByX < 0 ? .Left : .Right if sqrt(pow(movedByX, 2) + pow(movedByY, 2)) > distanceToSplit { self.userInteractionEnabled = false delegate?.removeCarbonCardViewItem(self, direction: direction) return } } reset() } private func reset() { delegate?.translateCarbonCardViewItem(self, point: CGPointMake(0, 0), angle: 0) let rotate = CGAffineTransformMakeRotation(0) let translate = CGAffineTransformMakeTranslation(0, 0) springAnimation({ () -> Void in self.transform = CGAffineTransformConcat(rotate, translate) }) { (Bool) -> Void in self.isSplitted = false } } } /** Remove with moving direction - Left: Move left - Right: Move right */ public enum CarbonCardViewItemRemoveDirection { case Left, Right } public protocol CarbonCardViewItemDelegate: NSObjectProtocol { func removeCarbonCardViewItem(carbonCardViewItem: CarbonCardViewItem, direction: CarbonCardViewItemRemoveDirection) func translateCarbonCardViewItem(carbonCardViewItem: CarbonCardViewItem, point: CGPoint, angle: CGFloat) func carbonCardViewItemSplited(carbonCardViewItem: CarbonCardViewItem) }
mit
d556fc66975984f92db1e871cc90b5ea
36.439759
121
0.640386
5.218304
false
false
false
false
linchaosheng/CSSwiftWB
SwiftCSWB 3/SwiftCSWB/Class/Home/C/WBPresentationController.swift
1
1507
// // WBPresentationController.swift // SwiftCSWB // // Created by LCS on 16/4/24. // Copyright © 2016年 Apple. All rights reserved. // import UIKit class WBPresentationController: UIPresentationController { override init(presentedViewController: UIViewController, presenting presentingViewController: UIViewController?) { super.init(presentedViewController: presentedViewController, presenting: presentingViewController) } /* containerView : 容器视图 (存放被展示的视图) presentedView : 被展示的视图 (modal出来的控制器view) */ override func containerViewWillLayoutSubviews(){ let W = CGFloat(100) let H = CGFloat(200) let X = UIScreen.main.bounds.size.width * 0.5 - W * 0.5 let Y = CGFloat(64) presentedView?.frame = CGRect(x: X, y: Y, width: W, height: H) // 创建蒙板 let maskView = UIView() maskView.backgroundColor = UIColor.black maskView.alpha = 0.1 maskView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height) let tap = UITapGestureRecognizer(target: self, action: #selector(WBPresentationController.maskViewOnClick)) maskView.addGestureRecognizer(tap) containerView?.insertSubview(maskView, belowSubview: presentedView!) } func maskViewOnClick(){ presentedViewController.dismiss(animated: true, completion: nil) } }
apache-2.0
9631ca9c9535c6aab7c45dbd413157b7
33.47619
118
0.672652
4.641026
false
false
false
false
wenghengcong/Coderpursue
BeeFun/BeeFun/SystemManager/Network/BFStatusCode.swift
1
3727
// // BFResponseStatusCode.swift // BeeFun // // Created by WengHengcong on 2018/5/5. // Copyright © 2018年 JungleSong. All rights reserved. // import UIKit public enum BFStatusCode: Int { case bfOk = 0 // Informational case `continue` = 100 case switchingProtocols = 101 case processing = 102 // Success case ok = 200 case created = 201 case accepted = 202 case nonAuthoritativeInformation = 203 case noContent = 204 case resetContent = 205 case partialContent = 206 case multiStatus = 207 case alreadyReported = 208 case imUsed = 226 // Redirections case multipleChoices = 300 case movedPermanently = 301 case found = 302 case seeOther = 303 case notModified = 304 case useProxy = 305 case switchProxy = 306 case temporaryRedirect = 307 case permanentRedirect = 308 // Client Errors case badRequest = 400 case unauthorized = 401 case paymentRequired = 402 case forbidden = 403 case notFound = 404 case methodNotAllowed = 405 case notAcceptable = 406 case proxyAuthenticationRequired = 407 case requestTimeout = 408 case conflict = 409 case gone = 410 case lengthRequired = 411 case preconditionFailed = 412 case requestEntityTooLarge = 413 case requestURITooLong = 414 case unsupportedMediaType = 415 case requestedRangeNotSatisfiable = 416 case expectationFailed = 417 case imATeapot = 418 case authenticationTimeout = 419 case unprocessableEntity = 422 case locked = 423 case failedDependency = 424 case upgradeRequired = 426 case preconditionRequired = 428 case tooManyRequests = 429 case requestHeaderFieldsTooLarge = 431 case loginTimeout = 440 case noResponse = 444 case retryWith = 449 case unavailableForLegalReasons = 451 case requestHeaderTooLarge = 494 case certError = 495 case noCert = 496 case httpToHTTPS = 497 case tokenExpired = 498 case clientClosedRequest = 499 // Server Errors case internalServerError = 500 case notImplemented = 501 case badGateway = 502 case serviceUnavailable = 503 case gatewayTimeout = 504 case httpVersionNotSupported = 505 case variantAlsoNegotiates = 506 case insufficientStorage = 507 case loopDetected = 508 case bandwidthLimitExceeded = 509 case notExtended = 510 case networkAuthenticationRequired = 511 case networkTimeoutError = 599 //以下是BeeFun api特俗定义的 case addTagWhenExist = 1102 } public extension BFStatusCode { /// Informational - Request received, continuing process. public var isInformational: Bool { return inRange( (100...199) ) } /// Success - The action was successfully received, understood, and accepted. public var isSuccess: Bool { return inRange( (200...299) ) } /// Redirection - Further action must be taken in order to complete the request. public var isRedirection: Bool { return inRange( (300...399) ) } /// Client Error - The request contains bad syntax or cannot be fulfilled. public var isClientError: Bool { return inRange(400...499) } /// Server Error - The server failed to fulfill an apparently valid request. public var isServerError: Bool { return inRange(500...599) } /// - returns: `true` if the status code is in the provided range, false otherwise. //see http://stackoverflow.com/questions/25308978/what-are-intervals-in-swift-ranges fileprivate func inRange(_ range: ClosedRange<Int>) -> Bool { return range.contains(rawValue) } }
mit
378d6c9567903635fc9fab2d08d6e4a7
27.744186
88
0.679612
4.711563
false
false
false
false
acumen1005/iSwfit
ACCycleScrollView/ACCycleScrollView/AppDelegate.swift
1
2497
// // AppDelegate.swift // ACCycleScrollView // // Created by acumen on 16/11/28. // Copyright © 2016年 acumen. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. window = UIWindow() window?.backgroundColor = UIColor.white let nav: UINavigationController = UINavigationController(rootViewController: ViewController()) window?.rootViewController = nav window?.makeKeyAndVisible() nav.navigationBar.isTranslucent = false return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
6080bdf28764136d50f722d8f3caab11
45.185185
285
0.741379
5.81352
false
false
false
false
shorlander/firefox-ios
Sync/Synchronizers/ClientsSynchronizer.swift
2
17389
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import Storage import XCGLogger import Deferred import SwiftyJSON private let log = Logger.syncLogger let ClientsStorageVersion = 1 // TODO public protocol Command { static func fromName(_ command: String, args: [JSON]) -> Command? func run(_ synchronizer: ClientsSynchronizer) -> Success static func commandFromSyncCommand(_ syncCommand: SyncCommand) -> Command? } // Shit. // We need a way to wipe or reset engines. // We need a way to log out the account. // So when we sync commands, we're gonna need a delegate of some kind. open class WipeCommand: Command { public init?(command: String, args: [JSON]) { return nil } open class func fromName(_ command: String, args: [JSON]) -> Command? { return WipeCommand(command: command, args: args) } open func run(_ synchronizer: ClientsSynchronizer) -> Success { return succeed() } open static func commandFromSyncCommand(_ syncCommand: SyncCommand) -> Command? { let json = JSON(parseJSON: syncCommand.value) if let name = json["command"].string, let args = json["args"].array { return WipeCommand.fromName(name, args: args) } return nil } } open class DisplayURICommand: Command { let uri: URL let title: String let sender: String public init?(command: String, args: [JSON]) { if let uri = args[0].string?.asURL, let sender = args[1].string, let title = args[2].string { self.uri = uri self.sender = sender self.title = title } else { // Oh, Swift. self.uri = "http://localhost/".asURL! self.title = "" return nil } } open class func fromName(_ command: String, args: [JSON]) -> Command? { return DisplayURICommand(command: command, args: args) } open func run(_ synchronizer: ClientsSynchronizer) -> Success { func display(_ deviceName: String? = nil) -> Success { synchronizer.delegate.displaySentTab(for: uri, title: title, from: deviceName) return succeed() } guard let getClientWithId = synchronizer.localClients?.getClientWithId(sender) else { return display() } return getClientWithId >>== { client in return display(client?.name) } } open static func commandFromSyncCommand(_ syncCommand: SyncCommand) -> Command? { let json = JSON(parseJSON: syncCommand.value) if let name = json["command"].string, let args = json["args"].array { return DisplayURICommand.fromName(name, args: args) } return nil } } open class RepairResponseCommand: Command { let repairResponse: RepairResponse public init(command: String, args: [JSON]) { self.repairResponse = RepairResponse.fromJSON(args: args[0]) } open class func fromName(_ command: String, args: [JSON]) -> Command? { return RepairResponseCommand(command: command, args: args) } open func run(_ synchronizer: ClientsSynchronizer) -> Success { let repairer = BookmarksRepairRequestor(scratchpad: synchronizer.scratchpad, basePrefs: synchronizer.basePrefs, remoteClients: synchronizer.localClients!) return repairer.continueRepairs(response: self.repairResponse) >>> succeed } open static func commandFromSyncCommand(_ syncCommand: SyncCommand) -> Command? { let json = JSON(parseJSON: syncCommand.value) if let name = json["command"].string, let args = json["args"].array { return RepairResponseCommand.fromName(name, args: args) } return nil } } let Commands: [String: (String, [JSON]) -> Command?] = [ "wipeAll": WipeCommand.fromName, "wipeEngine": WipeCommand.fromName, // resetEngine // resetAll // logout "displayURI": DisplayURICommand.fromName, "repairResponse": RepairResponseCommand.fromName ] open class ClientsSynchronizer: TimestampedSingleCollectionSynchronizer, Synchronizer { public required init(scratchpad: Scratchpad, delegate: SyncDelegate, basePrefs: Prefs, why: SyncReason) { super.init(scratchpad: scratchpad, delegate: delegate, basePrefs: basePrefs, why: why, collection: "clients") } var localClients: RemoteClientsAndTabs? override var storageVersion: Int { return ClientsStorageVersion } var clientRecordLastUpload: Timestamp { set(value) { self.prefs.setLong(value, forKey: "lastClientUpload") } get { return self.prefs.unsignedLongForKey("lastClientUpload") ?? 0 } } // Sync Object Format (Version 1) for Form Factors: http://docs.services.mozilla.com/sync/objectformats.html#id2 fileprivate enum SyncFormFactorFormat: String { case phone = "phone" case tablet = "tablet" } open func getOurClientRecord() -> Record<ClientPayload> { let guid = self.scratchpad.clientGUID let formfactor = formFactorString() let json = JSON(object: [ "id": guid, "fxaDeviceId": self.scratchpad.fxaDeviceId, "version": AppInfo.appVersion, "protocols": ["1.5"], "name": self.scratchpad.clientName, "os": "iOS", "commands": [JSON](), "type": "mobile", "appPackage": AppInfo.baseBundleIdentifier, "application": AppInfo.displayName, "device": DeviceInfo.deviceModel(), "formfactor": formfactor]) let payload = ClientPayload(json) return Record(id: guid, payload: payload, ttl: ThreeWeeksInSeconds) } fileprivate func formFactorString() -> String { let userInterfaceIdiom = UIDevice.current.userInterfaceIdiom var formfactor: String switch userInterfaceIdiom { case .phone: formfactor = SyncFormFactorFormat.phone.rawValue case .pad: formfactor = SyncFormFactorFormat.tablet.rawValue default: formfactor = SyncFormFactorFormat.phone.rawValue } return formfactor } fileprivate func clientRecordToLocalClientEntry(_ record: Record<ClientPayload>) -> RemoteClient { let modified = record.modified let payload = record.payload return RemoteClient(json: payload.json, modified: modified) } // If this is a fresh start, do a wipe. // N.B., we don't wipe outgoing commands! (TODO: check this when we implement commands!) // N.B., but perhaps we should discard outgoing wipe/reset commands! fileprivate func wipeIfNecessary(_ localClients: RemoteClientsAndTabs) -> Success { if self.lastFetched == 0 { return localClients.wipeClients() } return succeed() } /** * Returns whether any commands were found (and thus a replacement record * needs to be uploaded). Also returns the commands: we run them after we * upload a replacement record. */ fileprivate func processCommandsFromRecord(_ record: Record<ClientPayload>?, withServer storageClient: Sync15CollectionClient<ClientPayload>) -> Deferred<Maybe<(Bool, [Command])>> { log.debug("Processing commands from downloaded record.") // TODO: short-circuit based on the modified time of the record we uploaded, so we don't need to skip ahead. if let record = record { let commands = record.payload.commands if !commands.isEmpty { func parse(_ json: JSON) -> Command? { if let name = json["command"].string, let args = json["args"].array, let constructor = Commands[name] { return constructor(name, args) } return nil } // TODO: can we do anything better if a command fails? return deferMaybe((true, optFilter(commands.map(parse)))) } } return deferMaybe((false, [])) } fileprivate func uploadClientCommands(toLocalClients localClients: RemoteClientsAndTabs, withServer storageClient: Sync15CollectionClient<ClientPayload>) -> Success { return localClients.getCommands() >>== { clientCommands in return clientCommands.map { (clientGUID, commands) -> Success in self.syncClientCommands(clientGUID, commands: commands, clientsAndTabs: localClients, withServer: storageClient) }.allSucceed() } } fileprivate func syncClientCommands(_ clientGUID: GUID, commands: [SyncCommand], clientsAndTabs: RemoteClientsAndTabs, withServer storageClient: Sync15CollectionClient<ClientPayload>) -> Success { let deleteCommands: () -> Success = { return clientsAndTabs.deleteCommands(clientGUID).bind({ x in return succeed() }) } log.debug("Fetching current client record for client \(clientGUID).") let fetch = storageClient.get(clientGUID) return fetch.bind() { result in if let response = result.successValue, response.value.payload.isValid() { let record = response.value if var clientRecord = record.payload.json.dictionary { clientRecord["commands"] = JSON(record.payload.commands + commands.map { JSON(parseJSON: $0.value) }) let uploadRecord = Record(id: clientGUID, payload: ClientPayload(JSON(clientRecord)), ttl: ThreeWeeksInSeconds) return storageClient.put(uploadRecord, ifUnmodifiedSince: record.modified) >>== { resp in log.debug("Client \(clientGUID) commands upload succeeded.") // Always succeed, even if we couldn't delete the commands. return deleteCommands() } } } else { if let failure = result.failureValue { log.warning("Failed to fetch record with GUID \(clientGUID).") if failure is NotFound<HTTPURLResponse> { log.debug("Not waiting to see if the client comes back.") // TODO: keep these around and retry, expiring after a while. // For now we just throw them away so we don't fail every time. return deleteCommands() } if failure is BadRequestError<HTTPURLResponse> { log.debug("We made a bad request. Throwing away queued commands.") return deleteCommands() } } } log.error("Client \(clientGUID) commands upload failed: No remote client for GUID") return deferMaybe(UnknownError()) } } /** * Upload our record if either (a) we know we should upload, or (b) * our own notes tell us we're due to reupload. */ fileprivate func maybeUploadOurRecord(_ should: Bool, ifUnmodifiedSince: Timestamp?, toServer storageClient: Sync15CollectionClient<ClientPayload>) -> Success { let lastUpload = self.clientRecordLastUpload let expired = lastUpload < (Date.now() - (2 * OneDayInMilliseconds)) log.debug("Should we upload our client record? Caller = \(should), expired = \(expired).") if !should && !expired { return succeed() } let iUS: Timestamp? = ifUnmodifiedSince ?? ((lastUpload == 0) ? nil : lastUpload) var uploadStats = SyncUploadStats() return storageClient.put(getOurClientRecord(), ifUnmodifiedSince: iUS) >>== { resp in if let ts = resp.metadata.lastModifiedMilliseconds { // Protocol says this should always be present for success responses. log.debug("Client record upload succeeded. New timestamp: \(ts).") self.clientRecordLastUpload = ts uploadStats.sent += 1 } else { uploadStats.sentFailed += 1 } self.statsSession.recordUpload(stats: uploadStats) return succeed() } } fileprivate func applyStorageResponse(_ response: StorageResponse<[Record<ClientPayload>]>, toLocalClients localClients: RemoteClientsAndTabs, withServer storageClient: Sync15CollectionClient<ClientPayload>) -> Success { log.debug("Applying clients response.") var downloadStats = SyncDownloadStats() let records = response.value let responseTimestamp = response.metadata.lastModifiedMilliseconds log.debug("Got \(records.count) client records.") let ourGUID = self.scratchpad.clientGUID var toInsert = [RemoteClient]() var ours: Record<ClientPayload>? = nil for (rec) in records { guard rec.payload.isValid() else { log.warning("Client record \(rec.id) is invalid. Skipping.") continue } if rec.id == ourGUID { if rec.modified == self.clientRecordLastUpload { log.debug("Skipping our own unmodified record.") } else { log.debug("Saw our own record in response.") ours = rec } } else { toInsert.append(self.clientRecordToLocalClientEntry(rec)) } } downloadStats.applied += toInsert.count // Apply remote changes. // Collect commands from our own record and reupload if necessary. // Then run the commands and return. return localClients.insertOrUpdateClients(toInsert) >>== { succeeded in downloadStats.succeeded += succeeded downloadStats.failed += (toInsert.count - succeeded) self.statsSession.recordDownload(stats: downloadStats) return succeed() } >>== { self.processCommandsFromRecord(ours, withServer: storageClient) } >>== { (shouldUpload, commands) in return self.maybeUploadOurRecord(shouldUpload || self.why == .didLogin, ifUnmodifiedSince: ours?.modified, toServer: storageClient) >>> { self.uploadClientCommands(toLocalClients: localClients, withServer: storageClient) } >>> { log.debug("Running \(commands.count) commands.") for command in commands { _ = command.run(self) } self.lastFetched = responseTimestamp! return succeed() } } } open func synchronizeLocalClients(_ localClients: RemoteClientsAndTabs, withServer storageClient: Sync15StorageClient, info: InfoCollections) -> SyncResult { log.debug("Synchronizing clients.") self.localClients = localClients // Store for later when we process a repairResponse command if let reason = self.reasonToNotSync(storageClient) { switch reason { case .engineRemotelyNotEnabled: // This is a hard error for us. return deferMaybe(FatalError(message: "clients not mentioned in meta/global. Server wiped?")) default: return deferMaybe(SyncStatus.notStarted(reason)) } } let keys = self.scratchpad.keys?.value let encoder = RecordEncoder<ClientPayload>(decode: { ClientPayload($0) }, encode: { $0.json }) let encrypter = keys?.encrypter(self.collection, encoder: encoder) if encrypter == nil { log.error("Couldn't make clients encrypter.") return deferMaybe(FatalError(message: "Couldn't make clients encrypter.")) } let clientsClient = storageClient.clientForCollection(self.collection, encrypter: encrypter!) // TODO: some of the commands we process might involve wiping collections or the // entire profile. We should model this as an explicit status, and return it here // instead of .completed. statsSession.start() // XXX: This is terrible. We always force a re-sync of the clients to work around // the fact that `fxaDeviceId` may not have been populated if the list of clients // hadn't changed since before the update to v8.0. To force a re-sync, we get all // clients since the beginning of time instead of looking at `self.lastFetched`. return clientsClient.getSince(0) >>== { response in return self.wipeIfNecessary(localClients) >>> { self.applyStorageResponse(response, toLocalClients: localClients, withServer: clientsClient) } } >>> { deferMaybe(self.completedWithStats) } } }
mpl-2.0
11c1da28043805d8ceec14b5597aaab6
39.723653
224
0.609121
5.298294
false
false
false
false
AimobierCocoaPods/OddityUI
Classes/DetailAndCommitViewController/CommitViewController/Extension/CommDataSource.swift
1
3712
// // CommentDataSource.swift // Journalism // // Created by Mister on 16/6/1. // Copyright © 2016年 aimobier. All rights reserved. // import UIKit extension CommitViewController{ func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0 } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { guard let hot = hotResults,let normal = normalResults else{ return 0 } if section == 0 && hot.count <= 0 { return 0 } if section == 1 && normal.count <= 0 { return 40 } return 40 } func tableView(_ tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: IndexPath) -> CGFloat { return 100 } // 返回有几个 Section func numberOfSectionsInTableView(_ tableView: UITableView) -> Int { return 2 } // 设置每一个Section 的 返回个数 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if hotResults.count <= 0 && normalResults.count <= 0 { return section == 0 ? 0 : 1 } guard let hot = hotResults,let noraml = normalResults else{ return 0} if section == 0 { return hot.count } if section == 1 && noraml.count > 0 { return noraml.count } return 0 } func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell { if hotResults.count <= 0 && normalResults.count <= 0 { let cell = tableView.dequeueReusableCell(withIdentifier: "nocell")! as UITableViewCell return cell } var comment:Comment! if hotResults.count > 0 && (indexPath as NSIndexPath).section == 0{ comment = hotResults[(indexPath as NSIndexPath).item] }else if normalResults.count > 0 && (indexPath as NSIndexPath).section == 1{ comment = normalResults[(indexPath as NSIndexPath).item] } let cell = tableView.dequeueReusableCell(withIdentifier: "comments") as! CommentsTableViewCell cell.setCommentMethod(comment, tableView: tableView, indexPath: indexPath) cell.setNeedsDisplay() return cell } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard let _ = hotResults,let _ = normalResults else{ return nil } if hotResults.count <= 0 && normalResults.count <= 0 && section == 0 { return nil } if hotResults.count > 0 && normalResults.count <= 0 && section == 1 {return nil } let cell = tableView.dequeueReusableCell(withIdentifier: "newcomments") as! CommentsTableViewHeader if section == 0 { let text = hotResults.count > 0 ? "(\(hotResults.count))" : "" cell.titleLabel.text = "最热评论\(text)" }else{ let text = (new?.comment ?? 0) > 0 ? "(\((new?.comment ?? 0)-hotResults.count))" : "" cell.titleLabel.text = "最新评论\(text)" } let containerView = UIView(frame:cell.frame) cell.autoresizingMask = [.flexibleWidth, .flexibleHeight] containerView.addSubview(cell) return containerView } }
mit
27b27d859c50df16acaa9bdaf24fd3ae
28.304
112
0.549823
5.434718
false
false
false
false
Roommate-App/roomy
roomy/Pods/IBAnimatable/Sources/Views/AnimatableActivityIndicatorView.swift
5
772
// // AnimatableIndicatorView.swift // IBAnimatableApp // // Created by Tom Baranes on 21/08/16. // Copyright © 2016 IBAnimatable. All rights reserved. // import UIKit @IBDesignable open class AnimatableActivityIndicatorView: UIView, ActivityIndicatorAnimatable { // MARK: ActivityIndicatorAnimatable open var animationType: ActivityIndicatorType = .none @IBInspectable var _animationType: String? { didSet { if let type = _animationType, let animationType = ActivityIndicatorType(string: type) { self.animationType = animationType } else { animationType = .none } } } @IBInspectable open var color: UIColor = .black @IBInspectable open var hidesWhenStopped: Bool = true open var isAnimating: Bool = false }
mit
9150a458b74885bd7fe57897213e905b
26.535714
93
0.71725
4.78882
false
false
false
false
stephentyrone/swift
test/IRGen/prespecialized-metadata/struct-inmodule-1argument-1conformance-1distinct_use.swift
1
3970
// RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment // REQUIRES: OS=macosx || OS=ios || OS=tvos || OS=watchos || OS=linux-gnu // UNSUPPORTED: CPU=i386 && OS=ios // UNSUPPORTED: CPU=armv7 && OS=ios // UNSUPPORTED: CPU=armv7s && OS=ios // CHECK: @"$sytN" = external{{( dllimport)?}} global %swift.full_type // CHECK: @"$s4main5ValueVySiGMf" = linkonce_odr hidden constant <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: i8**, // CHECK-SAME: i32{{(, \[4 x i8\])?}}, // CHECK-SAME: i64 // CHECK-SAME: }> <{ // i8** @"$sB[[INT]]_WV", // i8** getelementptr inbounds (%swift.vwtable, %swift.vwtable* @"$s4main5ValueVySiGWV", i32 0, i32 0), // CHECK-SAME: [[INT]] 512, // CHECK-SAME: %swift.type_descriptor* bitcast ({{.+}}$s4main5ValueVMn{{.+}} to %swift.type_descriptor*), // CHECK-SAME: %swift.type* @"$sSiN", // CHECK-SAME: i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$sSi4main1PAAWP", i32 0, i32 0), // CHECK-SAME: i32 0{{(, \[4 x i8\] zeroinitializer)?}}, // CHECK-SAME: i64 3 // CHECK-SAME: }>, align [[ALIGNMENT]] protocol P {} extension Int : P {} struct Value<First : P> { let first: First } @inline(never) func consume<T>(_ t: T) { withExtendedLifetime(t) { t in } } // CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} { // CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture %{{[0-9]+}}, %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, i8**, i32{{(, \[4 x i8\])?}}, i64 }>* @"$s4main5ValueVySiGMf" to %swift.full_type*), i32 0, i32 1)) // CHECK: } func doit() { consume( Value(first: 13) ) } doit() // CHECK: ; Function Attrs: noinline nounwind readnone // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueVMa"([[INT]] %0, %swift.type* %1, i8** %2) #{{[0-9]+}} { // CHECK: entry: // CHECK: [[ERASED_TYPE:%[0-9]+]] = bitcast %swift.type* %1 to i8* // CHECK: [[ERASED_TABLE:%[0-9]+]] = bitcast i8** %2 to i8* // CHECK: br label %[[TYPE_COMPARISON_LABEL:[0-9]+]] // CHECK: [[TYPE_COMPARISON_LABEL]]: // CHECK: [[EQUAL_TYPE:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSiN" to i8*), [[ERASED_TYPE]] // CHECK: [[EQUAL_TYPES:%[0-9]+]] = and i1 true, [[EQUAL_TYPE]] // CHECK: [[ARGUMENT_BUFFER:%[0-9]+]] = bitcast i8* [[ERASED_TABLE]] to i8** // CHECK: [[UNCAST_PROVIDED_PROTOCOL_DESCRIPTOR:%[0-9]+]] = load i8*, i8** [[ARGUMENT_BUFFER]], align 1 // CHECK: [[PROVIDED_PROTOCOL_DESCRIPTOR:%[0-9]+]] = bitcast i8* [[UNCAST_PROVIDED_PROTOCOL_DESCRIPTOR]] to %swift.protocol_conformance_descriptor* // CHECK: [[EQUAL_DESCRIPTORS:%[0-9]+]] = call swiftcc i1 @swift_compareProtocolConformanceDescriptors(%swift.protocol_conformance_descriptor* [[PROVIDED_PROTOCOL_DESCRIPTOR]], %swift.protocol_conformance_descriptor* @"$sSi4main1PAAMc") // CHECK: [[EQUAL_ARGUMENTS:%[0-9]+]] = and i1 [[EQUAL_TYPES]], [[EQUAL_DESCRIPTORS]] // CHECK: br i1 [[EQUAL_ARGUMENTS]], label %[[EXIT_PRESPECIALIZED:[0-9]+]], label %[[EXIT_NORMAL:[0-9]+]] // CHECK: [[EXIT_PRESPECIALIZED]]: // CHECK: ret %swift.metadata_response { %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, i8**, i32{{(, \[4 x i8\])?}}, i64 }>* @"$s4main5ValueVySiGMf" to %swift.full_type*), i32 0, i32 1), [[INT]] 0 } // CHECK: [[EXIT_NORMAL]]: // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateGenericMetadata([[INT]] %0, i8* [[ERASED_TYPE]], i8* [[ERASED_TABLE]], i8* undef, %swift.type_descriptor* bitcast ({{.+}}$s4main5ValueVMn{{.+}} to %swift.type_descriptor*)) // CHECK: ret %swift.metadata_response {{%[0-9]+}} // CHECK: }
apache-2.0
e6ccb51ae9a4aad707240fe19127ec1d
56.536232
338
0.622166
3.068006
false
false
false
false
jfosterdavis/FlashcardHero
FlashcardHero/TDPerformanceLog+CoreDataClass.swift
1
1330
// // TDPerformanceLog+CoreDataClass.swift // FlashcardHero // // Created by Jacob Foster Davis on 11/15/16. // Copyright © 2016 Zero Mu, LLC. All rights reserved. // import Foundation import CoreData public class TDPerformanceLog: NSManagedObject { convenience init(datetime: NSDate, questionTypeId: Int, wasCorrect: Bool, quizletTD: QuizletTermDefinition, wrongAnswerTD: QuizletTermDefinition?, wrongAnswerFITB: String?, studySession: StudySession, context: NSManagedObjectContext){ if let ent = NSEntityDescription.entity(forEntityName: "TDPerformanceLog", in: context) { self.init(entity: ent, insertInto: context) self.datetime = datetime self.questionTypeId = Int64(questionTypeId) self.wasCorrect = wasCorrect self.quizletTD = quizletTD self.studySession = studySession //optionals if let wrongAnswerTD = wrongAnswerTD { self.wrongAnswerTD = wrongAnswerTD } if let wrongAnswerFITB = wrongAnswerFITB { self.wrongAnswerFITB = wrongAnswerFITB } } else { fatalError("Unable to find Entity name! (TDPerformanceLog)") } } }
apache-2.0
205f2d1de195b0e3a6ebf7810757c7d3
29.204545
238
0.613995
4.996241
false
false
false
false
cotkjaer/Silverback
Silverback/NSError.swift
1
3072
// // NSError.swift // Silverback // // Created by Christian Otkjær on 16/11/15. // Copyright © 2015 Christian Otkjær. All rights reserved. // import Foundation import UIKit extension NSError { public class var defaultAsyncErrorHandler : ((NSError) -> Void) { return { (error: NSError) -> Void in error.presentAsAlert() } } public convenience init( domain: String, code: Int, description: String? = nil, reason: String? = nil, underlyingError: NSError? = nil) { var errorUserInfo: [String : AnyObject] = [:] if description != nil { errorUserInfo[NSLocalizedDescriptionKey] = description ?? "" } if reason != nil { errorUserInfo[NSLocalizedFailureReasonErrorKey] = reason ?? "" } if underlyingError != nil { errorUserInfo[NSUnderlyingErrorKey] = underlyingError } self.init(domain: domain, code: code, userInfo: errorUserInfo) } public func presentAsAlert(handler:(() -> Void)? = nil) { presentInViewController(nil, withHandler: handler) } // public func presentInViewController(controller: UIViewController?) // { // let alertController = UIAlertController(title: self.localizedDescription, message: self.localizedFailureReason, preferredStyle: .Alert) // // //TODO: localizedRecoveryOptions and localizedRecoverySuggestion // // // let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in // // // ... // // } // // alertController.addAction(cancelAction) // // let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in // // println("Ignored Error: \(self)") // } // alertController.addAction(OKAction) // // controller?.presentViewController(alertController, animated: true) { NSLog("Showing error: \(self)") } // } public func presentInViewController(controller: UIViewController?, withHandler handler:(() -> Void)? = nil) { let alertController = UIAlertController(title: self.localizedDescription, message: self.localizedFailureReason, preferredStyle: .Alert) let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in if let realHandler = handler { realHandler() } else { debugPrint("Ignored Error: \(self)") } } alertController.addAction(OKAction) if let realController = controller ?? UIApplication.topViewController() { realController.presentViewController(alertController, animated: true) { debugPrint("Showing error: \(self)") } } else { debugPrint("ERROR could not be presented: \(self)") } } }
mit
71e75277f5cd159824d30eb0cafd869e
31.659574
149
0.566634
5.246154
false
false
false
false
pozi119/Valine
Valine/Valine.swift
1
2934
// // Valine.swift // Valine // // Created by Valo on 15/12/23. // Copyright © 2015年 Valo. All rights reserved. // import UIKit public func pageHop(hopMethod:HopMethod,hop:Hop)->AnyObject?{ if hop.controller != nil { Utils.setParameters(hop.parameters, forObject:hop.controller!) } switch hopMethod{ case .Push: Manager.sharedManager.currentNaviController?.pushViewController(hop.controller!, animated:hop.animated) if(hop.removeVCs?.count > 0){ var existVCs = Manager.sharedManager.currentNaviController?.viewControllers for var idx = 0; idx < existVCs?.count; ++idx{ let vc = existVCs![idx] let vcName = NSStringFromClass(vc.classForKeyedArchiver!) for tmpName in hop.removeVCs!{ if vcName.containsString(tmpName){ existVCs?.removeAtIndex(idx) } } } Manager.sharedManager.currentNaviController?.viewControllers = existVCs! } case .Pop: if hop.controller == nil{ Manager.sharedManager.currentNaviController?.popViewControllerAnimated(hop.animated) } else{ var destVC = hop.controller let existVCs = Manager.sharedManager.currentNaviController?.viewControllers for vc in existVCs!{ let vcName = NSStringFromClass(vc.classForKeyedArchiver!) if vcName.containsString(hop.aController!){ destVC = vc if hop.parameters != nil{ Utils.setParameters(hop.parameters, forObject:destVC!) } break } } Manager.sharedManager.currentNaviController?.popToViewController(destVC!, animated: hop.animated) } case .Present: var sourceVC:UIViewController if hop.sourceInNav && Manager.sharedManager.currentNaviController != nil{ sourceVC = Manager.sharedManager.currentNaviController! } else{ sourceVC = Manager.sharedManager.currentViewController! } var destVC = hop.controller if hop.destInNav{ if destVC!.navigationController != nil{ destVC = destVC!.navigationController! } else{ destVC = UINavigationController(rootViewController: destVC!) } } if hop.alpha < 1.0 && hop.alpha > 0.0 { hop.controller!.view.alpha = hop.alpha } sourceVC.presentViewController(destVC!, animated:hop.animated, completion:hop.completion) case .Dismiss: Manager.sharedManager.currentViewController?.dismissViewControllerAnimated(hop.animated, completion:hop.completion) } return nil }
gpl-2.0
30a7c49d9194098f6a70910cd5fd0cd1
34.313253
123
0.582054
5.468284
false
false
false
false
cotsog/BricBrac
Curio/Curio.swift
1
36318
// // Curio.swift // BricBrac // // Created by Marc Prud'hommeaux on 6/30/15. // Copyright © 2015 io.glimpse. All rights reserved. // /// A JSON Schema processor that emits Swift code using the Bric-a-Brac framework for marshalling and unmarshalling. /// /// Current shortcomings: /// • "anyOf" schema type values cannot prevent that all their tuple elements not be set to nil /// /// TODO: /// • hide Indirect in private fields and make public Optional getters/setters public struct Curio { /// whether to generate structs or classes (classes are faster to compiler for large models) public var generateValueTypes = true /// the number of properties beyond which Optional types should instead be Indirect; this is needed beause /// a struct that contains many other stucts can make very large compilation units and take a very long /// time to compile public var indirectCountThreshold = 20 public var accessor: ([CodeTypeName])->(CodeAccess) = { _ in .Default } public var renamer: ([CodeTypeName], String)->(CodeTypeName?) = { (parents, id) in nil } /// special prefixes to trim (adheres to the convention that top-level types go in the "defintions" level) public var trimPrefixes = ["#/definitions/"] public var propOrdering: ([CodeTypeName], String)->(Array<String>?) = { (parents, id) in nil } public init() { } enum CodegenErrors : ErrorType, CustomDebugStringConvertible { case TypeArrayNotSupported case IllegalDefaultType case DefaultValueNotInStringEnum case NonStringEnumsNotSupported // TODO case TupleTypeingNotSupported // TODO case IllegalState(String) case Unsupported(String) case IllegalProperty(Schema) case CompileError(String) var debugDescription : String { switch self { case TypeArrayNotSupported: return "TypeArrayNotSupported" case IllegalDefaultType: return "IllegalDefaultType" case DefaultValueNotInStringEnum: return "DefaultValueNotInStringEnum" case NonStringEnumsNotSupported: return "NonStringEnumsNotSupported" case TupleTypeingNotSupported: return "TupleTypeingNotSupported" case IllegalState(let x): return "IllegalState(\(x))" case Unsupported(let x): return "Unsupported(\(x))" case IllegalProperty(let x): return "IllegalProperty(\(x))" case CompileError(let x): return "CompileError(\(x))" } } } /// Alphabetical characters static let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" /// “Identifiers begin with an uppercase or lowercase letter A through Z, an underscore (_), a noncombining alphanumeric Unicode character in the Basic Multilingual Plane, or a character outside the Basic Multilingual Plane that isn’t in a Private Use Area.” static let nameStart = Set((alphabet.uppercaseString + "_" + alphabet.lowercaseString).characters) /// “After the first character, digits and combining Unicode characters are also allowed.” static let nameBody = Set(Array(nameStart) + "0123456789".characters) /// Reserved words as per the Swift language guide static let reservedWords = Set(["class", "deinit", "enum", "extension", "func", "import", "init", "internal", "let", "operator", "private", "protocol", "public", "static", "struct", "subscript", "typealias", "var", "break", "case", "continue", "default", "do", "else", "fallthrough", "for", "if", "in", "retu", ", switch", "where", "while", "as", "dynamicType", "false", "is", "nil", "self", "Self", "super", "true", "__COLUMN__", "__FILE__", "__FUNCTION__", "__LINE__", "associativity", "convenience", "dynamic", "didSet", "final", "get", "infix", "inout", "lazy", "left", "mutating", "none", "nonmutating", "optional", "override", "postfix", "precedence", "prefix", "Protocol", "required", "right", "set", "Type", "unowned", "weak", "willSet"]) func propName(parents: [CodeTypeName], var _ id: String) -> CodePropName { if let pname = renamer(parents, id) { return pname } if id == "init" { id = "initx" // even escaped with `init`, it crashes the compiler } while let first = id.characters.first where !Curio.nameStart.contains(first) { id = String(id.characters.dropFirst()) } if self.dynamicType.reservedWords.contains(id) { id = "`" + id + "`" } return id } func typeName(parents: [CodeTypeName], _ id: String) -> CodeTypeName { if let tname = renamer(parents, id) { return tname } var name = "" var capnext = true var nm = id for pre in trimPrefixes { if nm.hasPrefix(pre) { nm = nm[pre.endIndex..<nm.endIndex] } } for c in nm.characters { let validCharacters = name.isEmpty ? self.dynamicType.nameStart : self.dynamicType.nameBody if !validCharacters.contains(c) { capnext = true } else if capnext { name.appendContentsOf(String(c).uppercaseString) capnext = false } else { name.append(c) } } if self.dynamicType.reservedWords.contains(name) { name = "`" + name + "`" } if name.isEmpty { // e.g., ">=" -> "U62U61" for c in id.unicodeScalars { name += "U\(c.value)" } } return CodeTypeName(name) } /// Reifies the given schema as a Swift data structure public func reify(schema: Schema, id: String, var parents: [CodeTypeName]) throws -> CodeNamedType { func dictionaryType(keyType: CodeType, _ valueType: CodeType) -> CodeExternalType { return CodeExternalType("Dictionary", generics: [keyType, valueType], access: accessor(parents)) } func arrayType(type: CodeType) -> CodeExternalType { return CodeExternalType("Array", generics: [type], access: accessor(parents)) } func collectionOfOneType(type: CodeType) -> CodeExternalType { return CodeExternalType("CollectionOfOne", generics: [type], access: accessor(parents)) } func optionalType(type: CodeType) -> CodeExternalType { return CodeExternalType("Optional", generics: [type], access: accessor(parents)) } func indirectType(type: CodeType) -> CodeExternalType { return CodeExternalType("Indirect", generics: [type], access: accessor(parents)) } func notBracType(type: CodeType) -> CodeExternalType { return CodeExternalType("NotBrac", generics: [type], access: accessor(parents)) } let BricType = CodeExternalType("Bric", access: accessor(parents)) let StringType = CodeExternalType("String", access: accessor(parents)) let IntType = CodeExternalType("Int", access: accessor(parents)) let DoubleType = CodeExternalType("Double", access: accessor(parents)) let BoolType = CodeExternalType("Bool", access: accessor(parents)) let VoidType = CodeExternalType("Void", access: accessor(parents)) let ObjectType = dictionaryType(StringType, BricType) /// Calculate the fully-qualified name of the given type func fullName(type: CodeType) -> String { return (parents + [type.identifier]).joinWithSeparator(".") } let bricable = CodeProtocol(name: "Bricable", access: accessor(parents)) let bricfun = CodeFunction.Declaration(name: "bric", access: accessor(parents), instance: true, returns: CodeTuple(elements: [(name: nil, type: BricType, value: nil, anon: false)])) let bracable = CodeProtocol(name: "Bracable", access: accessor(parents)) let bracfun: (CodeType)->(CodeFunction.Declaration) = { CodeFunction.Declaration(name: "brac", access: self.accessor(parents), instance: false, exception: true, arguments: CodeTuple(elements: [(name: "bric", type: BricType, value: nil, anon: false)]), returns: CodeTuple(elements: [(name: nil, type: CodeExternalType(fullName($0), access: self.accessor(parents)), value: nil, anon: false)])) } let bricbrac = CodeProtocol(name: "BricBrac", access: accessor(parents)) let comments = [schema.title, schema.description].filter({ $0 != nil }).map({ $0! }) func createComplexEnumeration(multi: [Schema]) throws -> CodeEnum { let ename = typeName(parents, id) var code = CodeEnum(name: ename, access: accessor(parents)) code.comments = comments var bricbody : [String] = [] var bracbody : [String] = [] bricbody.append("switch self {") bracbody.append("return try bric.bracOne([") var casenames = Set<String>() for sub in multi { let subname = sub.title.flatMap({ typeName(parents, $0) }) ?? "Type\(casenames.count+1)" let casetype: CodeType switch sub.type { case .Some(.A(.String)) where sub._enum == nil: casetype = StringType case .Some(.A(.Number)): casetype = DoubleType case .Some(.A(.Boolean)): casetype = BoolType case .Some(.A(.Integer)): casetype = IntType case .Some(.A(.Null)): casetype = VoidType default: let subtype = try reify(sub, id: subname, parents: parents + [code.name]) // when the generated code is merely a typealias, just inline it in the enum case if let alias = subtype as? CodeTypeAlias where alias.peers.isEmpty { casetype = alias.type } else { code.nestedTypes.append(subtype) if generateValueTypes && subtype.directReferences.map({ $0.name }).contains(ename) { casetype = indirectType(subtype) } else { casetype = subtype } } } let cname = typeName(parents, casetype.identifier) + "Case" var casename = cname var n = 0 // make sure case names are unique by suffixing with a number while casenames.contains(casename) { casename = cname + String(++n) } casenames.insert(casename) code.cases.append(CodeEnum.Case(name: casename, type: casetype)) if casetype.identifier == "Void" { // Void can't be extended, so we need to special-case it to avoid calling methods on the type bricbody.append("case .\(casename): return .Nul") // bracbody.append("{ Void() },") // just skip it bracbody.append("{ try .\(casename)(bric.bracNul()) },") } else { bricbody.append("case .\(casename)(let x): return x.bric()") bracbody.append("{ try .\(casename)(\(casetype.identifier).brac(bric)) },") } } bricbody.append("}") bracbody.append("])") code.conforms.append(bricbrac) code.funcs.append(CodeFunction.Implementation(declaration: bricfun, body: bricbody, comments: [])) if bracbody.isEmpty { bracbody.append("fatalError()") } code.funcs.append(CodeFunction.Implementation(declaration: bracfun(code), body: bracbody, comments: [])) return code } func createSimpleEnumeration(typename: CodeTypeName, name: String, types: [Schema.SimpleTypes]) -> CodeNamedType { var assoc = CodeEnum(name: typeName(parents, name), access: accessor(parents + [typeName(parents, name)])) var bricbody : [String] = [] var bracbody : [String] = [] bricbody.append("switch self {") bracbody.append("return try bric.bracOne([") for (_, sub) in types.enumerate() { switch sub { case .String: assoc.cases.append(CodeEnum.Case(name: "Text", type: StringType)) bricbody.append("case .Text(let x): return x.bric()") bracbody.append("{ try .Text(String.brac(bric)) },") case .Number: assoc.cases.append(CodeEnum.Case(name: "Number", type: DoubleType)) bricbody.append("case .Number(let x): return x.bric()") bracbody.append("{ try .Number(Double.brac(bric)) },") case .Boolean: assoc.cases.append(CodeEnum.Case(name: "Boolean", type: BoolType)) bricbody.append("case .Boolean(let x): return x.bric()") bracbody.append("{ try .Boolean(Bool.brac(bric)) },") case .Integer: assoc.cases.append(CodeEnum.Case(name: "Integer", type: IntType)) bricbody.append("case .Integer(let x): return x.bric()") bracbody.append("{ try .Integer(Int.brac(bric)) },") case .Null: assoc.cases.append(CodeEnum.Case(name: "None", type: nil)) bricbody.append("case .None: return .Nul") bracbody.append("{ .Nul },") default: //print("warning: making Bric for key: \(name)") assoc.cases.append(CodeEnum.Case(name: "Object", type: BricType)) bricbody.append("case .Object(let x): return x.bric()") bracbody.append("{ .Object(bric) },") } } bricbody.append("}") bracbody.append("])") assoc.conforms.append(bricable) assoc.funcs.append(CodeFunction.Implementation(declaration: bricfun, body: bricbody, comments: [])) parents += [typename] if bracbody.isEmpty { bracbody.append("fatalError()") } assoc.conforms.append(bracable) assoc.funcs.append(CodeFunction.Implementation(declaration: bracfun(assoc), body: bracbody, comments: [])) parents = Array(parents.dropLast()) return assoc } enum StateMode { case Standard, AllOf, AnyOf } typealias PropInfo = (name: String?, required: Bool, schema: Schema) /// Creates a schema instance for an "object" type with all the listed properties func createObject(typename: CodeTypeName, properties: [PropInfo], mode: StateMode) throws -> CodeStateType { let merge = mode == .AllOf || mode == .AnyOf var code: CodeStateType if generateValueTypes { code = CodeStruct(name: typename, access: accessor(parents + [typename])) } else { code = CodeClass(name: typename, access: accessor(parents + [typename])) } code.comments = comments typealias PropNameType = (name: CodePropName, type: CodeType) var proptypes: [PropNameType] = [] // assign some anonymous names to the properties var anonPropCount = 0 var props = properties.map({ (name: $0.name ?? "p\(anonPropCount++)", required: $0.required, prop: $0.schema, anon: $0.name == nil) }) for (name, required, prop, anon) in props { var proptype: CodeType if let ref = prop.ref { let tname = typeName(parents, ref) proptype = CodeExternalType(tname, access: accessor(parents + [typename])) } else { switch prop.type { case .Some(.A(.String)) where prop._enum == nil: proptype = StringType case .Some(.A(.Number)): proptype = DoubleType case .Some(.A(.Boolean)): proptype = BoolType case .Some(.A(.Integer)): proptype = IntType case .Some(.A(.Null)): proptype = VoidType case .Some(.B(let types)): let assoc = createSimpleEnumeration(typename, name: name, types: types) code.nestedTypes.append(assoc) proptype = assoc case .Some(.A(.Array)): switch prop.items { case .None: proptype = arrayType(BricType) case .Some(.B): throw CodegenErrors.TypeArrayNotSupported case .Some(.A(let itemz)): if let item = itemz.value { // FIXME: indirect if let ref = item.ref { proptype = arrayType(CodeExternalType(typeName(parents, ref), access: accessor(parents))) } else { let type = try reify(item, id: name + "Item", parents: parents + [code.name]) code.nestedTypes.append(type) proptype = arrayType(type) } } else { throw CodegenErrors.Unsupported("Empty indirect") } } default: // generate the type for the object let subtype = try reify(prop, id: prop.title ?? (name + "Type"), parents: parents + [code.name]) code.nestedTypes.append(subtype) proptype = subtype } } if !required { let structProps = props.filter({ (name, required, prop, anon) in switch prop.type?.types.first { case .None: return true // unspecified object type: maybe a $ref case .Some(.Object): return true // a custom object default: return false // raw types never get an indirect } }) if structProps.count >= self.indirectCountThreshold { proptype = indirectType(proptype) } else { proptype = optionalType(proptype) } } let propn = propName(parents + [typename], name) let propd = CodeProperty.Declaration(name: propn, type: proptype, access: accessor(parents)) let propi = propd.implementation propd.comments = [prop.title, prop.description].filter({ $0 != nil }).map({ $0! }) code.props.append(propi) let pt: PropNameType = (name: propn, type: proptype) proptypes.append(pt) } var addPropType: CodeType? = nil let hasAdditionalProps: Bool? // true=yes, false=no, nil=unspecified switch schema.additionalProperties { case .None: hasAdditionalProps = nil // TODO: make a global default for whether unspecified additionalProperties means yes or no case .Some(.A(false)): hasAdditionalProps = false // FIXME: when this is false, allOf union types won't validate case .Some(.A(true)), .Some(.B): // TODO: generate object types for B hasAdditionalProps = true addPropType = ObjectType // additionalProperties default to [String:Bric] } let addPropName = renamer(parents, "additionalProperties") ?? "additionalProperties" if let addPropType = addPropType { let propn = propName(parents + [typename], addPropName) let propd = CodeProperty.Declaration(name: propn, type: addPropType, access: accessor(parents)) let propi = propd.implementation code.props.append(propi) let pt: PropNameType = (name: propn, type: addPropType) // proptypes.append(pt) } /// Creates a Keys enumeration of all the valid keys for this state instance func makeKeys(keyName: String) { var cases: [CodeCaseSimple<String>] = [] for (key, _, _, _) in props { let pname = propName(parents + [typename], key) cases.append(CodeCaseSimple(name: pname, value: key)) } if let _ = addPropType { cases.append(CodeCaseSimple(name: addPropName, value: "")) } if !cases.isEmpty { code.nestedTypes.insert(CodeSimpleEnum(name: keyName, access: accessor(parents), cases: cases), atIndex: 0) } } /// Creates a memberwise initializer for the object type func makeInit(merged: Bool) { var elements: [CodeTupleElement] = [] var initbody: [String] = [] for p1 in code.props { // allOf merged will take any sub-states and create initializers with all of their arguments let sub = merged ? p1.declaration.type as? CodeStateType : nil for p in (sub?.props ?? [p1]) { let d = p.declaration let e = CodeTupleElement(name: d.name, type: d.type, value: d.type.defaultValue, anon: merge) elements.append(e) initbody.append("self.\(d.name) = \(d.name)") } } let initargs = CodeTuple(elements: elements) let initfun = CodeFunction.Declaration(name: "init", access: accessor(parents), instance: true, arguments: initargs, returns: CodeTuple(elements: [])) let initimp = CodeFunction.Implementation(declaration: initfun, body: initbody, comments: []) code.funcs.append(initimp) } let keysName = "Keys" if !merge { // create an enumeration of "Keys" for all the object's properties makeKeys(keysName) } makeInit(false) // if merge { makeInit(true) } // TODO: make convenience initializers for merged (i.e., allOf) nested properties var bricbody : [String] = [] var bracbody : [String] = [] if mode == .AllOf || mode == .AnyOf { bricbody.append("return Bric(merge: [") for (name, _, _, _) in props { bricbody.append("\(propName(parents + [typename], name)).bric(),") } bricbody.append("])") if mode == .AllOf { bracbody.append("return try \(fullName(code))(") } else if mode == .AnyOf { bracbody.append("return try \(fullName(code))(") } for (i, pt) in proptypes.enumerate() { let sep = (i == props.count-1 ? "" : ",") let ti: String = pt.type.identifier bracbody.append("\(ti).brac(bric)" + sep) } bracbody.append(")") } else { bricbody.append("return Bric(object: [") if hasAdditionalProps == true { // empty key for additional properties; first so addprop keys don't clobber state keys bricbody.append("(\(keysName).\(addPropName), \(addPropName).bric()),") } for (key, _, _, _) in props { let pname = propName(parents + [typename], key) bricbody.append("(\(keysName).\(pname), \(pname).bric()),") } bricbody.append("])") if hasAdditionalProps == false { bracbody.append("try bric.prohibitExtraKeys(\(keysName))") } bracbody.append("return try \(fullName(code))(") for (i, t) in props.enumerate() { let sep = (i == props.count - (addPropType == nil ? 1 : 0) ? "" : ",") let pname = propName(parents + [typename], t.name) bracbody.append("\(pname): bric.bracKey(\(keysName).\(pname))" + sep) } if hasAdditionalProps == true { // empty key for additional properties; first so addprop keys don't clobber state keys bracbody.append("\(addPropName): bric.bracDisjoint(\(keysName).self)") } bracbody.append(")") } if bricbody.isEmpty { bricbody.append("fatalError()") } code.funcs.append(CodeFunction.Implementation(declaration: bricfun, body: bricbody, comments: [])) if bracbody.isEmpty { bracbody.append("fatalError()") } code.funcs.append(CodeFunction.Implementation(declaration: bracfun(code), body: bracbody, comments: [])) code.conforms.append(bricbrac) return code } func createArray(typename: CodeTypeName) throws -> CodeNamedType { // when a top-level type is an array, we make it a typealias with a type for the individual elements switch schema.items { case .None: return CodeTypeAlias(name: typeName(parents, id), type: arrayType(BricType), access: accessor(parents)) case .Some(.B): throw CodegenErrors.TypeArrayNotSupported case .Some(.A(let itemz)): if let item = itemz.value { // FIXME: make indirect to avoid circular references if let ref = item.ref { return CodeTypeAlias(name: typeName(parents, id), type: arrayType(CodeExternalType(typeName(parents, ref), access: accessor(parents))), access: accessor(parents)) } else { // note that we do not tack on the alias' name, because it will not be used as the external name of the type let type = try reify(item, id: typename + "Item", parents: parents) let alias = CodeTypeAlias(name: typeName(parents, id), type: arrayType(type), access: accessor(parents), peers: [type]) return alias } } else { throw CodegenErrors.Unsupported("Empty indirect") } } } func createStringEnum(typename: CodeTypeName, values: [Bric]) throws -> CodeSimpleEnum<String> { var code = CodeSimpleEnum<String>(name: typeName(parents, id), access: accessor(parents)) code.comments = comments for e in values { if case .Str(let evalue) = e { code.cases.append(CodeCaseSimple<String>(name: typeName(parents, evalue), value: evalue)) } else { throw CodegenErrors.NonStringEnumsNotSupported } } var bricbody : [String] = [] var bracbody : [String] = [] // when there is only a single possible value, make it the default if let firstCase = code.cases.first where code.cases.count == 1 { code.defaultValue = "." + firstCase.name } bricbody.append("return .Nul") // bricbody.append("return Bric(object: [") // for (name, _, _) in props { // bricbody.append("\"\(name)\" : \(propName(parents, name)).bric(),") // } // bricbody.append("])") code.conforms.append(bricbrac) code.funcs.append(CodeFunction.Implementation(declaration: bricfun, body: bricbody, comments: [])) if bracbody.isEmpty { bracbody.append("fatalError()") } code.funcs.append(CodeFunction.Implementation(declaration: bracfun(code), body: bracbody, comments: [])) return code } func getPropInfo(properties: [String: Schema]) -> [PropInfo] { /// JSON Schema Draft 4 doesn't have any notion of property ordering, so we use a user-defined sorter /// followed by ordering them by their appearance in the (non-standard) "propertyOrder" element /// followed by ordering them by their appearance in the "required" element /// followed by alphabetical property name ordering let ordering = (propOrdering(parents, id) ?? []) + (schema.propertyOrder ?? []) + (schema.required ?? []) + Array(properties.keys).sort() let ordered = properties.sort { a, b in return ordering.indexOf(a.0) <= ordering.indexOf(b.0) } let req = Set(schema.required ?? []) let props = ordered.map({ PropInfo(name: $0, required: req.contains($0), schema: $1) }) return props } let type = schema.type let typename = typeName(parents, id) if let values = schema._enum { return try createStringEnum(typename, values: values) } else if case .Some(.A(.String)) = type { return CodeTypeAlias(name: typename, type: StringType, access: accessor(parents)) } else if case .Some(.A(.Integer)) = type { return CodeTypeAlias(name: typename, type: IntType, access: accessor(parents)) } else if case .Some(.A(.Number)) = type { return CodeTypeAlias(name: typename, type: DoubleType, access: accessor(parents)) } else if case .Some(.A(.Boolean)) = type { return CodeTypeAlias(name: typename, type: BoolType, access: accessor(parents)) } else if case .Some(.A(.Null)) = type { return CodeTypeAlias(name: typename, type: VoidType, access: accessor(parents)) } else if case .Some(.A(.Array)) = type { return try createArray(typename) } else if let properties = schema.properties where !properties.isEmpty { return try createObject(typename, properties: getPropInfo(properties), mode: .Standard) } else if let allOf = schema.allOf { // represent allOf as a struct with non-optional properties var props: [PropInfo] = [] for propSchema in allOf { // // an internal nested state type can be safely collapsed into the owning object // // not working for a few reasons, one of which is bric merge info // if let subProps = propSchema.properties where !subProps.isEmpty { // props.extend(getPropInfo(subProps)) // } else { // props.append(PropInfo(name: nil, required: true, schema: propSchema)) // } props.append(PropInfo(name: nil, required: true, schema: propSchema)) } return try createObject(typename, properties: props, mode: .AllOf) } else if let anyOf = schema.anyOf { // anyOf is one or more Xs, so make it a tuple of (CollectionOfOne<X>, Array<X>) // FIXME: compiler hang, maybe because the tuple can't be de-brac'd // let oneOf = try createComplexEnumeration(anyOf) // let tuple = CodeTuple(elements: [(name: nil, type: collectionOfOneType(oneOf), value: nil, anon: false), (name: nil, type: arrayType(oneOf), value: nil, anon: false)]) // let allOfId = typename + "Tuple" // return CodeTypeAlias(name: allOfId, type: tuple, access: accessor(parents), peers: [oneOf]) // represent anyOf as a struct with optional properties let props: [PropInfo] = anyOf.map({ (name: nil, required: false, schema: $0 ) }) return try createObject(typename, properties: props, mode: .AnyOf) } else if let oneOf = schema.oneOf { // TODO: allows properties in addition to oneOf return try createComplexEnumeration(oneOf) } else if let ref = schema.ref { // create a typealias to the reference return CodeTypeAlias(name: typename, type: CodeExternalType(typeName(parents, ref), access: accessor(parents)), access: accessor(parents)) } else if let not = schema.not.value { // a "not" generates a validator against an inverse schema let inverseId = "Not" + typename let inverseSchema = try reify(not, id: inverseId, parents: parents) return CodeTypeAlias(name: typename, type: notBracType(inverseSchema), access: accessor(parents), peers: [inverseSchema]) } else if schema.bric() == [:] { // an empty schema just generates pure Bric return CodeTypeAlias(name: typename, type: BricType, access: accessor(parents)) } else if case .Some(.A(.Object)) = type, .Some(.B(.Some(let adp))) = schema.additionalProperties { // an empty schema with additionalProperties makes it a [String:Type] let adpType = try reify(adp, id: typename + "Value", parents: parents) return CodeTypeAlias(name: typename, type: dictionaryType(StringType, adpType), access: accessor(parents), peers: [adpType]) } else if case .Some(.A(.Object)) = type, .Some(.A(let adp)) = schema.additionalProperties where adp == true { // an empty schema with additionalProperties makes it a [String:Bric] //print("warning: making Brictionary for code: \(schema.bric().stringify())") return CodeTypeAlias(name: typename, type: ObjectType, access: accessor(parents)) } else { // throw CodegenErrors.IllegalState("No code to generate for: \(schema.bric().stringify())") //print("warning: making Bric for code: \(schema.bric().stringify())") return CodeTypeAlias(name: typename, type: BricType, access: accessor(parents)) } } } public extension Schema { enum BracReferenceError : ErrorType, CustomDebugStringConvertible { case ReferenceRequiredRoot(String) case ReferenceMustBeRelativeToCurrentDocument(String) case ReferenceMustBeRelativeToDocumentRoot(String) case RefWithoutAdditionalProperties(String) case ReferenceNotFound(String) public var debugDescription : String { switch self { case ReferenceRequiredRoot(let str): return "ReferenceRequiredRoot: \(str)" case ReferenceMustBeRelativeToCurrentDocument(let str): return "ReferenceMustBeRelativeToCurrentDocument: \(str)" case ReferenceMustBeRelativeToDocumentRoot(let str): return "ReferenceMustBeRelativeToDocumentRoot: \(str)" case RefWithoutAdditionalProperties(let str): return "RefWithoutAdditionalProperties: \(str)" case ReferenceNotFound(let str): return "ReferenceNotFound: \(str)" } } } /// Support for JSON $ref <http://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03> func resolve(path: String) throws -> Schema { var parts = path.characters.split(isSeparator: { $0 == "/" }).map { String($0) } // print("parts: \(parts)") if parts.isEmpty { throw BracReferenceError.ReferenceRequiredRoot(path) } let first = parts.removeAtIndex(0) if first != "#" { throw BracReferenceError.ReferenceMustBeRelativeToCurrentDocument(path) } if parts.isEmpty { throw BracReferenceError.ReferenceRequiredRoot(path) } let root = parts.removeAtIndex(0) if _additionalProperties.isEmpty { throw BracReferenceError.RefWithoutAdditionalProperties(path) } guard var json = _additionalProperties[root] else { throw BracReferenceError.ReferenceNotFound(path) } for part in parts { guard let next: Bric = json[part] else { throw BracReferenceError.ReferenceNotFound(path) } json = next } return try Schema.brac(json) } }
mit
9f1b08416d2fc21e36974563b4331c55
49.073103
750
0.567364
4.898529
false
false
false
false
zhuhaow/NEKit
src/ProxyServer/ProxyServer.swift
1
3009
import Foundation import CocoaAsyncSocket import Resolver /** The base proxy server class. This proxy does not listen on any port. */ open class ProxyServer: NSObject, TunnelDelegate { typealias TunnelArray = [Tunnel] /// The port of proxy server. public let port: Port /// The address of proxy server. public let address: IPAddress? /// The type of the proxy server. /// /// This can be set to anything describing the proxy server. public let type: String /// The description of proxy server. open override var description: String { return "<\(type) address:\(String(describing: address)) port:\(port)>" } open var observer: Observer<ProxyServerEvent>? var tunnels: TunnelArray = [] /** Create an instance of proxy server. - parameter address: The address of proxy server. - parameter port: The port of proxy server. - warning: If you are using Network Extension, you have to set address or you may not able to connect to the proxy server. */ public init(address: IPAddress?, port: Port) { self.address = address self.port = port type = "\(Swift.type(of: self))" super.init() self.observer = ObserverFactory.currentFactory?.getObserverForProxyServer(self) } /** Start the proxy server. - throws: The error occured when starting the proxy server. */ open func start() throws { QueueFactory.executeOnQueueSynchronizedly { GlobalIntializer.initalize() self.observer?.signal(.started(self)) } } /** Stop the proxy server. */ open func stop() { QueueFactory.executeOnQueueSynchronizedly { for tunnel in tunnels { tunnel.forceClose() } observer?.signal(.stopped(self)) } } /** Delegate method when the proxy server accepts a new ProxySocket from local. When implementing a concrete proxy server, e.g., HTTP proxy server, the server should listen on some port and then wrap the raw socket in a corresponding ProxySocket subclass, then call this method. - parameter socket: The accepted proxy socket. */ func didAcceptNewSocket(_ socket: ProxySocket) { observer?.signal(.newSocketAccepted(socket, onServer: self)) let tunnel = Tunnel(proxySocket: socket) tunnel.delegate = self tunnels.append(tunnel) tunnel.openTunnel() } // MARK: TunnelDelegate implementation /** Delegate method when a tunnel closed. The server will remote it internally. - parameter tunnel: The closed tunnel. */ func tunnelDidClose(_ tunnel: Tunnel) { observer?.signal(.tunnelClosed(tunnel, onServer: self)) guard let index = tunnels.firstIndex(of: tunnel) else { // things went strange return } tunnels.remove(at: index) } }
bsd-3-clause
996319252cda6ee1833e7a64e768d4ce
27.121495
203
0.63011
4.723705
false
false
false
false
RxSwiftCommunity/RxSwift-Ext
Source/RxSwift/retryWithBehavior.swift
2
4610
// // retryWithBehavior.swift // RxSwiftExt // // Created by Anton Efimenko on 17/07/16. // Copyright © 2016 RxSwift Community. All rights reserved. // import Foundation import RxSwift /** Specifies how observable sequence will be repeated in case of an error - Immediate: Will be immediatelly repeated specified number of times - Delayed: Will be repeated after specified delay specified number of times - ExponentialDelayed: Will be repeated specified number of times. Delay will be incremented by multiplier after each iteration (multiplier = 0.5 means 50% increment) - CustomTimerDelayed: Will be repeated specified number of times. Delay will be calculated by custom closure */ public enum RepeatBehavior { case immediate (maxCount: UInt) case delayed (maxCount: UInt, time: Double) case exponentialDelayed (maxCount: UInt, initial: Double, multiplier: Double) case customTimerDelayed (maxCount: UInt, delayCalculator: (UInt) -> DispatchTimeInterval) } public typealias RetryPredicate = (Error) -> Bool extension RepeatBehavior { /** Extracts maxCount and calculates delay for current RepeatBehavior - parameter currentAttempt: Number of current attempt - returns: Tuple with maxCount and calculated delay for provided attempt */ func calculateConditions(_ currentRepetition: UInt) -> (maxCount: UInt, delay: DispatchTimeInterval) { switch self { case .immediate(let max): // if Immediate, return 0.0 as delay return (maxCount: max, delay: .never) case .delayed(let max, let time): // return specified delay return (maxCount: max, delay: .milliseconds(Int(time * 1000))) case .exponentialDelayed(let max, let initial, let multiplier): // if it's first attempt, simply use initial delay, otherwise calculate delay let delay = currentRepetition == 1 ? initial : initial * pow(1 + multiplier, Double(currentRepetition - 1)) return (maxCount: max, delay: .milliseconds(Int(delay * 1000))) case .customTimerDelayed(let max, let delayCalculator): // calculate delay using provided calculator return (maxCount: max, delay: delayCalculator(currentRepetition)) } } } extension ObservableType { /** Repeats the source observable sequence using given behavior in case of an error or until it successfully terminated - parameter behavior: Behavior that will be used in case of an error - parameter scheduler: Schedular that will be used for delaying subscription after error - parameter shouldRetry: Custom optional closure for checking error (if returns true, repeat will be performed) - returns: Observable sequence that will be automatically repeat if error occurred */ public func retry(_ behavior: RepeatBehavior, scheduler: SchedulerType = MainScheduler.instance, shouldRetry: RetryPredicate? = nil) -> Observable<Element> { return retry(1, behavior: behavior, scheduler: scheduler, shouldRetry: shouldRetry) } /** Repeats the source observable sequence using given behavior in case of an error or until it successfully terminated - parameter currentAttempt: Number of current attempt - parameter behavior: Behavior that will be used in case of an error - parameter scheduler: Schedular that will be used for delaying subscription after error - parameter shouldRetry: Custom optional closure for checking error (if returns true, repeat will be performed) - returns: Observable sequence that will be automatically repeat if error occurred */ internal func retry(_ currentAttempt: UInt, behavior: RepeatBehavior, scheduler: SchedulerType = MainScheduler.instance, shouldRetry: RetryPredicate? = nil) -> Observable<Element> { guard currentAttempt > 0 else { return Observable.empty() } // calculate conditions for bahavior let conditions = behavior.calculateConditions(currentAttempt) return catchError { error -> Observable<Element> in // return error if exceeds maximum amount of retries guard conditions.maxCount > currentAttempt else { return Observable.error(error) } if let shouldRetry = shouldRetry, !shouldRetry(error) { // also return error if predicate says so return Observable.error(error) } guard conditions.delay != .never else { // if there is no delay, simply retry return self.retry(currentAttempt + 1, behavior: behavior, scheduler: scheduler, shouldRetry: shouldRetry) } // otherwise retry after specified delay return Observable<Void>.just(()).delaySubscription(conditions.delay, scheduler: scheduler).flatMapLatest { self.retry(currentAttempt + 1, behavior: behavior, scheduler: scheduler, shouldRetry: shouldRetry) } } } }
mit
08cb7e67fdac1e7668503387816897da
43.317308
158
0.760469
4.479106
false
false
false
false
groue/GRMustache.swift
Sources/Expression.swift
4
2625
// The MIT License // // Copyright (c) 2015 Gwendal Roué // // 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 /// The type for expressions that appear in tags: `name`, `user.name`, /// `uppercase(user.name)`, etc. enum Expression { // {{ . }} case implicitIterator // {{ identifier }} case identifier(identifier: String) // {{ <expression>.identifier }} indirect case scoped(baseExpression: Expression, identifier: String) // {{ <expression>(<expression>) }} indirect case filter(filterExpression: Expression, argumentExpression: Expression, partialApplication: Bool) } /// Expression conforms to Equatable so that the Compiler can check that section /// tags have matching openings and closings: {{# person }}...{{/ person }} is /// OK but {{# foo }}...{{/ bar }} is not. extension Expression: Equatable { } func ==(lhs: Expression, rhs: Expression) -> Bool { switch (lhs, rhs) { case (.implicitIterator, .implicitIterator): return true case (.identifier(let lIdentifier), .identifier(let rIdentifier)): return lIdentifier == rIdentifier case (.scoped(let lBase, let lIdentifier), .scoped(let rBase, let rIdentifier)): return lBase == rBase && lIdentifier == rIdentifier case (.filter(let lFilter, let lArgument, let lPartialApplication), .filter(let rFilter, let rArgument, let rPartialApplication)): return lFilter == rFilter && lArgument == rArgument && lPartialApplication == rPartialApplication default: return false } }
mit
9cf954cd5f488801943a27d16b224350
38.757576
134
0.701601
4.636042
false
false
false
false
CaiMiao/CGSSGuide
DereGuide/Common/CloudKitSync/SyncCoordinator.swift
1
11287
// // RemoteSync.swift // DereGuide // // Created by Daniel Eggert on 22/05/2015. // Copyright (c) 2015 objc.io. All rights reserved. // import UIKit import CoreData import CloudKit public protocol CloudKitNotificationDrain { func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) } private let RemoteTypeEnvKey = "CloudKitRemote" /// This is the central class that coordinates synchronization with the remote backend. /// /// This classs does not have any model specific knowledge. It relies on multiple `ChangeProcessor` instances to process changes or communicate with the remote. Change processors have model-specific knowledge. /// /// The change processors (`ChangeProcessor`) each have 1 specific aspect of syncing as their role. In our case there are three: one for uploading moods, one for downloading moods, and one for removing moods. /// /// The `SyncCoordinator` is mostly single-threaded by design. This allows for the code to be relatively simple. All sync code runs on the queue of the `syncContext`. Entry points that may run on another queue **must** switch onto that context's queue using `perform(_:)`. /// /// Note that inside this class we use `perform(_:)` in lieu of `dispatch_async()` to make sure all work is done on the sync context's queue. Adding asynchronous work to a dispatch group makes it easier to test. We can easily wait for all code to be completed by waiting on that group. /// /// This class uses the `SyncContextType` and `ApplicationActiveStateObserving` protocols. public final class SyncCoordinator { static let shared = SyncCoordinator(viewContext: CoreDataStack.default.viewContext, syncContext: CoreDataStack.default.syncContext) internal typealias ApplicationDidBecomeActive = () -> () let viewContext: NSManagedObjectContext let syncContext: NSManagedObjectContext let syncGroup: DispatchGroup = DispatchGroup() let membersRemote: MembersRemote let unitsRemote: UnitsRemote let favoriteCardsRemote: FavoriteCardsRemote let favoriteCharasRemote: FavoriteCharasRemote let favoriteSongsRemote: FavoriteSongsRemote fileprivate var observerTokens: [NSObjectProtocol] = [] //< The tokens registered with NotificationCenter let changeProcessors: [ChangeProcessor] //< The change processors for upload, download, etc. var teardownFlag = atomic_flag() private init(viewContext: NSManagedObjectContext, syncContext: NSManagedObjectContext) { self.membersRemote = MembersRemote() self.unitsRemote = UnitsRemote() self.favoriteCardsRemote = FavoriteCardsRemote() self.favoriteCharasRemote = FavoriteCharasRemote() self.favoriteSongsRemote = FavoriteSongsRemote() self.viewContext = viewContext self.syncContext = syncContext syncContext.name = "SyncCoordinator" syncContext.mergePolicy = CloudKitMergePolicy(mode: .remote) // Member in remote has a reference of .deleteSelf action, so Member doesn't need a remover // local Unit need all of the 6 members to create, Member is created when Unit is downloaded by fetching in CloudKit using the CKReference on remote Member, so Member downloader only responsible for update remote changes changeProcessors = [UnitUploader(remote: unitsRemote), UnitDownloader(remote: unitsRemote), MemberDownloader(remote: membersRemote), UnitRemover(remote: unitsRemote), MemberUploader(remote: membersRemote), UnitModifier(remote: unitsRemote), MemberModifier(remote: membersRemote), FavoriteCardUploader(remote: favoriteCardsRemote), FavoriteCardDownloader(remote: favoriteCardsRemote), FavoriteCardRemover(remote: favoriteCardsRemote), FavoriteCharaUploader(remote: favoriteCharasRemote), FavoriteCharaDownloader(remote: favoriteCharasRemote), FavoriteCharaRemover(remote: favoriteCharasRemote), FavoriteSongUploader(remote: favoriteSongsRemote), FavoriteSongDownloader(remote: favoriteSongsRemote), FavoriteSongRemover(remote: favoriteSongsRemote)] setup() } /// The `tearDown` method must be called in order to stop the sync coordinator. public func tearDown() { guard !atomic_flag_test_and_set(&teardownFlag) else { return } perform { self.removeAllObserverTokens() } } deinit { guard atomic_flag_test_and_set(&teardownFlag) else { fatalError("deinit called without tearDown() being called.") } // We must not call tearDown() at this point, because we can not call async code from within deinit. // We want to be able to call async code inside tearDown() to make sure things run on the right thread. } fileprivate func setup() { self.perform { // All these need to run on the same queue, since they're modifying `observerTokens` self.unitsRemote.cloudKitContainer.fetchUserRecordID(completionHandler: { (userRecordID, error) in self.viewContext.userID = userRecordID?.recordName }) self.setupContexts() self.setupChangeProcessors() self.setupApplicationActiveNotifications() } } } extension SyncCoordinator: CloudKitNotificationDrain { public func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) { perform { self.fetchNewRemoteData() } } } // MARK: - Context Owner - extension SyncCoordinator : ContextOwner { /// The sync coordinator holds onto tokens used to register with the NotificationCenter. func addObserverToken(_ token: NSObjectProtocol) { observerTokens.append(token) } func removeAllObserverTokens() { observerTokens.removeAll() } func processChangedLocalObjects(_ objects: [NSManagedObject]) { for cp in changeProcessors { cp.processChangedLocalObjects(objects, in: self) } } fileprivate func processChangedLocalObjects(_ objects: [NSManagedObject], using processor: ChangeProcessor) { processor.processChangedLocalObjects(objects, in: self) } } // MARK: - Context - extension SyncCoordinator: ChangeProcessorContext { /// This is the context that the sync coordinator, change processors, and other sync components do work on. var managedObjectContext: NSManagedObjectContext { return syncContext } /// This switches onto the sync context's queue. If we're already on it, it will simply run the block. func perform(_ block: @escaping () -> ()) { syncContext.perform(group: syncGroup, block: block) } func perform<A,B>(_ block: @escaping (A,B) -> ()) -> (A,B) -> () { return { (a: A, b: B) -> () in self.perform { block(a, b) } } } func perform<A,B,C>(_ block: @escaping (A,B,C) -> ()) -> (A,B,C) -> () { return { (a: A, b: B, c: C) -> () in self.perform { block(a, b, c) } } } func delayedSaveOrRollback() { managedObjectContext.delayedSaveOrRollback(group: syncGroup) } } // MARK: Setup extension SyncCoordinator { fileprivate func setupChangeProcessors() { for cp in self.changeProcessors { cp.setup(for: self) } } } // MARK: - Active & Background - extension SyncCoordinator: ApplicationActiveStateObserving { func applicationDidFinishLaunching() { fetchRemoteDataForApplicationDidFinishLaunching() } func applicationDidBecomeActive() { fetchLocallyTrackedObjects() fetchRemoteDataForApplicationDidBecomeActive() } func applicationDidEnterBackground() { syncContext.refreshAllObjects() } // fileprivate func fetchLocallyTrackedObjects() { // self.perform { // // TODO: Could optimize this to only execute a single fetch request per entity. // var objects: Set<NSManagedObject> = [] // for cp in self.changeProcessors { // guard let entityAndPredicate = cp.entityAndPredicateForLocallyTrackedObjects(in: self) else { continue } // let request = entityAndPredicate.fetchRequest // request.returnsObjectsAsFaults = false // // let result = try! self.syncContext.fetch(request) // objects.formUnion(result) // // } // self.processChangedLocalObjects(Array(objects)) // } // } fileprivate func fetchLocallyTrackedObjects() { self.perform { // TODO: Could optimize this to only execute a single fetch request per entity. for cp in self.changeProcessors { guard let entityAndPredicate = cp.entityAndPredicateForLocallyTrackedObjects(in: self) else { continue } let request = entityAndPredicate.fetchRequest request.returnsObjectsAsFaults = false let result = try! self.syncContext.fetch(request) self.processChangedLocalObjects(result, using: cp) } } } } // MARK: - Remote - extension SyncCoordinator { fileprivate func fetchRemoteDataForApplicationDidBecomeActive() { self.fetchNewRemoteData() } fileprivate func fetchRemoteDataForApplicationDidFinishLaunching() { self.fetchLatestRemoteData() } fileprivate func fetchLatestRemoteData() { perform { for changeProcessor in self.changeProcessors { changeProcessor.fetchLatestRemoteRecords(in: self) self.delayedSaveOrRollback() } } } fileprivate func fetchNewRemoteData() { fetchNewRemoteData(using: unitsRemote) fetchNewRemoteData(using: membersRemote) fetchNewRemoteData(using: favoriteCardsRemote) fetchNewRemoteData(using: favoriteCharasRemote) } fileprivate func fetchNewRemoteData<T: Remote>(using remote: T) { remote.fetchNewRecords { (changes, callback) in self.processRemoteChanges(changes) { self.perform { self.managedObjectContext.delayedSaveOrRollback(group: self.syncGroup) { success in callback(success) } } } } } fileprivate func processRemoteChanges<T>(_ changes: [RemoteRecordChange<T>], completion: @escaping () -> ()) { self.changeProcessors.asyncForEach(completion: completion) { changeProcessor, innerCompletion in perform { changeProcessor.processRemoteChanges(changes, in: self, completion: innerCompletion) } } } }
mit
77bf47a242fa1c637e57533fd8de8cfa
36.374172
285
0.65066
5.367095
false
false
false
false
ykobets/SwiftMeter
Source/SwiftMeter.swift
1
7958
// // SwiftMeter.swift // SwiftMeter // // Created by Yurii on 29/03/2017. // Copyright © 2017 Yurii Kobets. All rights reserved. // import Foundation import QuartzCore fileprivate var timebase_info: mach_timebase_info = mach_timebase_info(numer: 0, denom: 0) fileprivate var numer: UInt64? fileprivate var denom: UInt64? struct StopWatch { typealias TimeEventDouble = (String, Double) fileprivate typealias TimeEvent = (String, TimeValue) fileprivate typealias TimeEventPause = (TimeValue, Bool) //$1 - when event has paused, $2 - isPaused fileprivate typealias WarnEvent = (String, TimeValue) fileprivate var startTimestamp: UInt64 = 0 fileprivate var stopTimestamp: UInt64 = 0 fileprivate var tag: String? fileprivate var splits = [TimeEvent]() fileprivate var pauses = [TimeEventPause]() init() { mach_timebase_info(&timebase_info) numer = UInt64(timebase_info.numer) denom = UInt64(timebase_info.denom) } init(tag: String?) { self.init() self.tag = tag } init(_ tag: String?) { self.init(tag: tag) } var isRunning: Bool { return startTimestamp > 0 && stopTimestamp == 0 } /// Start a stopwatch instance mutating func start() { startTimestamp = mach_absolute_time() } /// Stops countdown mutating func stop() { if isRunning { stopTimestamp = mach_absolute_time() } } /// Pause countdown mutating func pause() { if isRunning { pauses.append((TimeValue.now(), true)) } } /// Resume countdown mutating func resume() { if isRunning { pauses.append((TimeValue.now(), false)) } } mutating func split(_ eventTag: String? = nil) -> TimeValue { let splitTime = elapsedTime(start: startTimestamp, end: currentTimeNanoseconds()) let tag = eventTag ?? "Split \(splits.count))" self.splits.append((tag, splitTime)) return splitTime } func stepTime(_ eventTag: String) -> TimeValue { return self.splits.first { event -> Bool in return event.0 == eventTag }.map { event in return event.1 } ?? TimeValue.timeValueZero } /// Time elapsed since start of the stopwatch var elapsedTime: TimeValue { var pausedTime: UInt64 = 0 var pauseStarted = TimeValue.timeValueZero for (_, value) in pauses.enumerated() { if (value.1 == true) { pauseStarted = value.0 } if pauseStarted != TimeValue.timeValueZero && value.1 == false { let pauseEnded = value.0 pausedTime += elapsedTime(start: pauseStarted.value, end: pauseEnded.value).value } } return TimeValue(elapsedTime(start: startTimestamp, end: stopTimestamp).value - pausedTime) } private func elapsedTime(start: UInt64, end: UInt64) -> TimeValue { guard start > 0 && end > 0 && start < end else { return TimeValue.timeValueZero } let elapsed = ((end - start) * numer!) / denom! return TimeValue(value: elapsed, type: .nanosecond) } func activeSplits(unit: TimeUnit = .nanosecond) -> [TimeEventDouble] { return splits.map { ($0, $1.timeinterval(unit: unit)) } } func formattedTime(unit: TimeUnit) -> String { let elapsedTime = self.elapsedTime let formattedTime = elapsedTime.timeinterval(unit: unit) let tag = self.tag ?? "\(startTimestamp)" return "[Stopwatch - \(tag)] time elapsed - \(formattedTime) \(unit.unitName())" } private func currentTimeNanoseconds() -> UInt64 { return mach_absolute_time() } func warnWithTimeLapsed(value: TimeValue) { } } /// Time representation in seconds, milliseconds, nanoseconds enum TimeUnit { case nanosecond, microsecond, millisecond, second func unitName() -> String { switch self { case .nanosecond: return "nanoseconds" case .microsecond: return "microseconds" case .millisecond: return "milliseconds" case .second: return "seconds" } } } /// Time value with type (representation). The milliseconds is default struct TimeValue { private let microsecondsInSecond: UInt64 = 1_000 private let millisecondsInSecond: UInt64 = 1_000_000 private let nanosecondsInSecond: UInt64 = 1_000_000_000 static let timeValueZero = TimeValue(0) /// value in nanoseconds fileprivate var value: UInt64 = 0 var type = TimeUnit.nanosecond var nanoseconds: UInt64 { return value } var microseconds: UInt64 { return valueFor(unit: .microsecond) } var milliseconds: UInt64 { return valueFor(unit: .millisecond) } var seconds: UInt64 { return valueFor(unit: .second) } init(value: UInt64, type: TimeUnit) { switch type { case .nanosecond: self.value = value case .microsecond: self.value = value * microsecondsInSecond case .millisecond: self.value = value * millisecondsInSecond case .second: self.value = value * nanosecondsInSecond } self.type = type } init(_ value: UInt64) { self.value = value self.type = .nanosecond } func timeinterval(unit: TimeUnit) -> Double { switch unit { case .nanosecond: return Double(value) case .microsecond: return Double(value) / Double(microsecondsInSecond) case .millisecond: return Double(value) / Double(millisecondsInSecond) case .second: return Double(value) / Double(nanosecondsInSecond) } } func valueFor(unit: TimeUnit) -> UInt64 { switch unit { case .nanosecond: return value case .microsecond: return value / microsecondsInSecond case .millisecond: return value / millisecondsInSecond case .second: return value / nanosecondsInSecond } } static func now() -> TimeValue { return TimeValue(mach_absolute_time()) } } extension TimeValue: Equatable { static func == (lhs: TimeValue, rhs: TimeValue) -> Bool { return lhs.nanoseconds == rhs.nanoseconds } } extension TimeValue: Comparable { public static func <(lhs: TimeValue, rhs: TimeValue) -> Bool { return lhs.nanoseconds < rhs.nanoseconds } public static func <=(lhs: TimeValue, rhs: TimeValue) -> Bool { return lhs.nanoseconds <= rhs.nanoseconds } public static func >=(lhs: TimeValue, rhs: TimeValue) -> Bool { return lhs.nanoseconds >= rhs.nanoseconds } public static func >(lhs: TimeValue, rhs: TimeValue) -> Bool{ return lhs.nanoseconds > rhs.nanoseconds } } /// Log functions controlled by SwiftMeter class SwiftMeter { func startTimer() -> StopWatch { return StopWatch() } } /// Benchmark protocol which is core for this class protocol SwiftMeterable { func executionTimeInterval(_ block: () -> ()) -> CFTimeInterval } extension SwiftMeterable { func executionTimeInterval(_ block: () -> ()) -> CFTimeInterval { var stopwatch = StopWatch() stopwatch.start() block(); stopwatch.stop() return stopwatch.elapsedTime.timeinterval(unit: .second) } } struct MeterPrint { static var enabledLogging = true public static func print(_ value: String) { if enabledLogging { print(value) } } } extension NSObject { public static func printMeter(_ value: String) { MeterPrint.print(value) } }
mit
dfab4a3351c1e3af9c9e2c300341a599
25.791246
104
0.602363
4.645067
false
false
false
false
nervousnet/nervousnet-iOS
Pods/Zip/Zip/ZipUtilities.swift
1
3140
// // ZipUtilities.swift // Zip // // Created by Roy Marmelstein on 26/01/2016. // Copyright © 2016 Roy Marmelstein. All rights reserved. // import Foundation internal class ZipUtilities { // File manager let fileManager = NSFileManager.defaultManager() /** * ProcessedFilePath struct */ internal struct ProcessedFilePath { let filePathURL: NSURL let fileName: String? func filePath() -> String { if let filePath = filePathURL.path { return filePath } else { return String() } } } //MARK: Path processing /** Process zip paths - parameter paths: Paths as NSURL. - returns: Array of ProcessedFilePath structs. */ internal func processZipPaths(paths: [NSURL]) -> [ProcessedFilePath]{ var processedFilePaths = [ProcessedFilePath]() for path in paths { guard let filePath = path.path else { continue } var isDirectory: ObjCBool = false fileManager.fileExistsAtPath(filePath, isDirectory: &isDirectory) if !isDirectory { let processedPath = ProcessedFilePath(filePathURL: path, fileName: path.lastPathComponent) processedFilePaths.append(processedPath) } else { let directoryContents = expandDirectoryFilePath(path) processedFilePaths.appendContentsOf(directoryContents) } } return processedFilePaths } /** Recursive function to expand directory contents and parse them into ProcessedFilePath structs. - parameter directory: Path of folder as NSURL. - returns: Array of ProcessedFilePath structs. */ internal func expandDirectoryFilePath(directory: NSURL) -> [ProcessedFilePath] { var processedFilePaths = [ProcessedFilePath]() if let directoryPath = directory.path, let enumerator = fileManager.enumeratorAtPath(directoryPath) { while let filePathComponent = enumerator.nextObject() as? String { let path = directory.URLByAppendingPathComponent(filePathComponent) guard let filePath = path.path, let directoryName = directory.lastPathComponent else { continue } var isDirectory: ObjCBool = false fileManager.fileExistsAtPath(filePath, isDirectory: &isDirectory) if !isDirectory { let fileName = (directoryName as NSString).stringByAppendingPathComponent(filePathComponent) let processedPath = ProcessedFilePath(filePathURL: path, fileName: fileName) processedFilePaths.append(processedPath) } else { let directoryContents = expandDirectoryFilePath(path) processedFilePaths.appendContentsOf(directoryContents) } } } return processedFilePaths } }
gpl-3.0
24ce6d3476252e116951a5b036955f6e
32.404255
112
0.596687
6.142857
false
false
false
false
nikita-leonov/DependentType
DependentType.playground/Pages/Use Case.xcplaygroundpage/Contents.swift
1
901
//: Such tooling allows us to perform boolean operations with compile time guaranatees let b1 = DependentType<Bool, False>() let b2 = DependentType<Bool, True>() let step1 = !(b1&&b2) let step2 = step1 == !b1 //Replace == with != to observer type-enforced compile-time guaranteed computation check in action. let step3 = step1 != !step2 && b1 let result: DependentType<Bool, True> = !step3 //: All steps infer types with a proper values, since all computation happens during compile time. Any changes in bool operations in step1 - step3 that cause breach of Contract<Bool, True> will cause compile time warning. //: Due to type language limitations (absence of dependant types) not every check is possible. Some of contracts still verified at runtime. let unsafeBoolean = false let unsafeResult: DependentType<Bool, True> = DependentType<Bool, True>() //: [Back to contract operators](@previous)
mit
cf63b746354842c685258d5ae348abe5
52
221
0.754717
3.900433
false
false
false
false
TrustWallet/trust-wallet-ios
Trust/Transfer/ViewControllers/ConfirmPaymentViewController.swift
1
8483
// Copyright DApps Platform Inc. All rights reserved. import BigInt import Foundation import UIKit import Result import StatefulViewController enum ConfirmType { case sign case signThenSend } enum ConfirmResult { case signedTransaction(SentTransaction) case sentTransaction(SentTransaction) } class ConfirmPaymentViewController: UIViewController { private let keystore: Keystore let session: WalletSession lazy var sendTransactionCoordinator = { return SendTransactionCoordinator(session: self.session, keystore: keystore, confirmType: confirmType, server: server) }() lazy var submitButton: UIButton = { let button = Button(size: .large, style: .solid) button.translatesAutoresizingMaskIntoConstraints = false button.setTitle(viewModel.actionButtonText, for: .normal) button.addTarget(self, action: #selector(send), for: .touchUpInside) return button }() lazy var viewModel: ConfirmPaymentViewModel = { //TODO: Refactor return ConfirmPaymentViewModel(type: self.confirmType) }() var configurator: TransactionConfigurator let confirmType: ConfirmType let server: RPCServer var didCompleted: ((Result<ConfirmResult, AnyError>) -> Void)? lazy var stackView: UIStackView = { let stackView = UIStackView() stackView.translatesAutoresizingMaskIntoConstraints = false stackView.spacing = 0 stackView.axis = .vertical return stackView }() lazy var footerStack: UIStackView = { let footerStack = UIStackView(arrangedSubviews: [ submitButton, ]) footerStack.translatesAutoresizingMaskIntoConstraints = false return footerStack }() init( session: WalletSession, keystore: Keystore, configurator: TransactionConfigurator, confirmType: ConfirmType, server: RPCServer ) { self.session = session self.keystore = keystore self.configurator = configurator self.confirmType = confirmType self.server = server super.init(nibName: nil, bundle: nil) navigationItem.rightBarButtonItem = UIBarButtonItem(image: R.image.transactionSlider(), style: .done, target: self, action: #selector(edit)) view.backgroundColor = viewModel.backgroundColor navigationItem.title = viewModel.title errorView = ErrorView(onRetry: { [weak self] in self?.fetch() }) loadingView = LoadingView() view.addSubview(stackView) view.addSubview(footerStack) fetch() } func fetch() { startLoading() configurator.load { [weak self] result in guard let `self` = self else { return } switch result { case .success: self.reloadView() self.endLoading() case .failure(let error): self.endLoading(animated: true, error: error, completion: nil) } } configurator.configurationUpdate.subscribe { [weak self] _ in guard let `self` = self else { return } self.reloadView() } } private func configure(for detailsViewModel: ConfirmPaymentDetailsViewModel) { stackView.removeAllArrangedSubviews() NSLayoutConstraint.activate([ stackView.topAnchor.constraint(equalTo: view.layoutGuide.topAnchor), stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor), stackView.trailingAnchor.constraint(equalTo: view.trailingAnchor), footerStack.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -StyleLayout.sideMargin), footerStack.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: StyleLayout.sideMargin), footerStack.bottomAnchor.constraint(equalTo: view.layoutGuide.bottomAnchor, constant: -StyleLayout.sideMargin), submitButton.leadingAnchor.constraint(equalTo: footerStack.leadingAnchor), submitButton.trailingAnchor.constraint(equalTo: footerStack.leadingAnchor), ]) let header = TransactionHeaderView() header.translatesAutoresizingMaskIntoConstraints = false header.configure(for: detailsViewModel.transactionHeaderViewModel) let items: [UIView] = [ .spacer(height: TransactionAppearance.spacing), header, .spacer(height: 10), TransactionAppearance.divider(color: Colors.lightGray, alpha: 0.3), .spacer(height: TransactionAppearance.spacing), TransactionAppearance.item( title: detailsViewModel.paymentFromTitle, subTitle: detailsViewModel.currentWalletDescriptionString ), .spacer(height: TransactionAppearance.spacing), TransactionAppearance.divider(color: Colors.lightGray, alpha: 0.3), .spacer(height: TransactionAppearance.spacing), TransactionAppearance.item( title: detailsViewModel.requesterTitle, subTitle: detailsViewModel.requesterText ), .spacer(height: TransactionAppearance.spacing), TransactionAppearance.divider(color: Colors.lightGray, alpha: 0.3), .spacer(height: TransactionAppearance.spacing), networkFeeView(detailsViewModel), .spacer(height: TransactionAppearance.spacing), TransactionAppearance.divider(color: Colors.lightGray, alpha: 0.3), TransactionAppearance.oneLine( title: detailsViewModel.totalTitle, subTitle: detailsViewModel.totalText, titleStyle: .headingSemiBold, subTitleStyle: .paragraph, layoutMargins: UIEdgeInsets(top: 15, left: 15, bottom: 15, right: 15), backgroundColor: UIColor(hex: "faf9f9") ), TransactionAppearance.divider(color: Colors.lightGray, alpha: 0.3), ] for item in items { stackView.addArrangedSubview(item) } updateSubmitButton() } private func networkFeeView(_ viewModel: ConfirmPaymentDetailsViewModel) -> UIView { return TransactionAppearance.oneLine( title: viewModel.estimatedFeeTitle, subTitle: viewModel.estimatedFeeText ) { [unowned self] _, _, _ in self.edit() } } private func updateSubmitButton() { let status = configurator.balanceValidStatus() let buttonTitle = viewModel.getActionButtonText( status, config: configurator.session.config, transfer: configurator.transaction.transfer ) submitButton.isEnabled = status.sufficient submitButton.setTitle(buttonTitle, for: .normal) } private func reloadView() { let viewModel = ConfirmPaymentDetailsViewModel( transaction: configurator.previewTransaction(), session: session, server: server ) self.configure(for: viewModel) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc func edit() { let controller = ConfigureTransactionViewController( configuration: configurator.configuration, transfer: configurator.transaction.transfer, config: session.config, session: session ) controller.delegate = self self.navigationController?.pushViewController(controller, animated: true) } @objc func send() { self.displayLoading() let transaction = configurator.signTransaction self.sendTransactionCoordinator.send(transaction: transaction) { [weak self] result in guard let `self` = self else { return } self.didCompleted?(result) self.hideLoading() } } } extension ConfirmPaymentViewController: StatefulViewController { func hasContent() -> Bool { return false } } extension ConfirmPaymentViewController: ConfigureTransactionViewControllerDelegate { func didEdit(configuration: TransactionConfiguration, in viewController: ConfigureTransactionViewController) { configurator.update(configuration: configuration) reloadView() navigationController?.popViewController(animated: true) } }
gpl-3.0
91968446dc514515ddb1a1c2f174d7ca
35.407725
148
0.655429
5.584595
false
true
false
false
Piwigo/Piwigo-Mobile
piwigo/Album/Extensions/AlbumViewController+Favorites.swift
1
7504
// // AlbumViewController+Favorites.swift // piwigo // // Created by Eddy Lelièvre-Berna on 15/06/2022. // Copyright © 2022 Piwigo.org. All rights reserved. // import Foundation extension AlbumViewController { // MARK: Favorites Bar Button func getFavoriteBarButton() -> UIBarButtonItem? { let areFavorites = CategoriesData.sharedInstance() .category(withId: categoryId, containsImagesWithId: selectedImageIds) let button = UIBarButtonItem.favoriteImageButton(areFavorites, target: self) button.action = areFavorites ? #selector(removeFromFavorites) : #selector(addToFavorites) return button } // MARK: - Add images to favorites @objc func addToFavorites() { initSelection(beforeAction: .addToFavorites) } func addImageToFavorites() { if selectedImageIds.isEmpty { // Close HUD with success updatePiwigoHUDwithSuccess() { [self] in hidePiwigoHUD(afterDelay: kDelayPiwigoHUD) { [self] in // Update button favoriteBarButton?.setFavoriteImage(for: true) favoriteBarButton?.action = #selector(removeFromFavorites) // Deselect images cancelSelect() // Update favorite icons refreshFavorites() } } return } // Get image data guard let imageId = selectedImageIds.last?.intValue, let imageData = CategoriesData.sharedInstance() .getImageForCategory(categoryId, andId: imageId) else { // Forget this image selectedImageIds.removeLast() // Update HUD updatePiwigoHUD(withProgress: 1.0 - Float(selectedImageIds.count) / Float(totalNumberOfImages)) // Next image addImageToFavorites() return } // Add image to favorites ImageUtilities.addToFavorites(imageData) { [self] in // Update HUD updatePiwigoHUD(withProgress: 1.0 - Float(selectedImageIds.count) / Float(totalNumberOfImages)) // Image added to favorites selectedImageIds.removeLast() // Next image addImageToFavorites() } failure: { [self] error in // Failed — Ask user if he/she wishes to retry let title = NSLocalizedString("imageFavorites_title", comment: "Favorites") var message = NSLocalizedString("imageFavoritesAddError_message", comment: "Failed to add this photo to your favorites.") dismissRetryPiwigoError(withTitle: title, message: message, errorMessage: error.localizedDescription, dismiss: { [self] in hidePiwigoHUD() { [self] in updateButtonsInSelectionMode() } }, retry: { [self] in // Relogin and retry LoginUtilities.reloginAndRetry() { [unowned self] in addImageToFavorites() } failure: { [self] error in message = NSLocalizedString("internetErrorGeneral_broken", comment: "Sorry…") dismissPiwigoError(withTitle: title, message: message, errorMessage: error?.localizedDescription ?? "") { [self] in hidePiwigoHUD() { [self] in updateButtonsInSelectionMode() } } } }) } } private func refreshFavorites() { // Loop over the visible cells let visibleCells = imagesCollection?.visibleCells ?? [] visibleCells.forEach { cell in if let imageCell = cell as? ImageCollectionViewCell, let imageId = imageCell.imageData?.imageId { let Ids = [NSNumber(value: imageId)] let isFavorite = CategoriesData.sharedInstance() .category(withId: kPiwigoFavoritesCategoryId, containsImagesWithId: Ids) imageCell.isFavorite = isFavorite imageCell.setNeedsLayout() imageCell.layoutIfNeeded() } } } // MARK: - Remove images from favorites @objc func removeFromFavorites() { initSelection(beforeAction: .removeFromFavorites) } func removeImageFromFavorites() { if selectedImageIds.isEmpty { // Close HUD with success updatePiwigoHUDwithSuccess() { [self] in hidePiwigoHUD(afterDelay: kDelayPiwigoHUD) { [self] in // Update button favoriteBarButton?.setFavoriteImage(for: false) favoriteBarButton?.action = #selector(addToFavorites) // Deselect images cancelSelect() // Hide favorite icons refreshFavorites() } } return } // Get image data guard let imageId = selectedImageIds.last?.intValue, let imageData = CategoriesData.sharedInstance() .getImageForCategory(categoryId, andId: imageId) else { // Forget this image selectedImageIds.removeLast() // Update HUD updatePiwigoHUD(withProgress: 1.0 - Float(selectedImageIds.count) / Float(totalNumberOfImages)) // Next image removeImageFromFavorites() return } // Remove image to favorites ImageUtilities.removeFromFavorites(imageData) { [self] in // Update HUD updatePiwigoHUD(withProgress: 1.0 - Float(selectedImageIds.count) / Float(totalNumberOfImages)) // Image removed from the favorites selectedImageIds.removeLast() // Next image removeImageFromFavorites() } failure: { [unowned self] error in // Failed — Ask user if he/she wishes to retry let title = NSLocalizedString("imageFavorites_title", comment: "Favorites") var message = NSLocalizedString("imageFavoritesRemoveError_message", comment: "Failed to remove this photo from your favorites.") dismissRetryPiwigoError(withTitle: title, message: message, errorMessage: error.localizedDescription, dismiss: { [unowned self] in hidePiwigoHUD() { [unowned self] in updateButtonsInSelectionMode() } }, retry: { [unowned self] in // Relogin and retry LoginUtilities.reloginAndRetry() { [unowned self] in removeImageFromFavorites() } failure: { [self] error in message = NSLocalizedString("internetErrorGeneral_broken", comment: "Sorry…") dismissPiwigoError(withTitle: title, message: message, errorMessage: error?.localizedDescription ?? "") { [unowned self] in hidePiwigoHUD() { [unowned self] in updateButtonsInSelectionMode() } } } }) } } }
mit
4b866d7a4d98abaed00fd83412e3e73b
38.235602
141
0.552042
6.014446
false
false
false
false
wordpress-mobile/AztecEditor-iOS
Aztec/Classes/Formatters/Implementations/LiFormatter.swift
2
1972
import Foundation import UIKit // MARK: - Pre Formatter // open class LiFormatter: ParagraphAttributeFormatter { /// Attributes to be added by default /// let placeholderAttributes: [NSAttributedString.Key: Any]? /// Designated Initializer /// init(placeholderAttributes: [NSAttributedString.Key : Any]? = nil) { self.placeholderAttributes = placeholderAttributes } // MARK: - Overwriten Methods func apply(to attributes: [NSAttributedString.Key: Any], andStore representation: HTMLRepresentation?) -> [NSAttributedString.Key: Any] { var resultingAttributes = attributes let newParagraphStyle = ParagraphStyle() if let paragraphStyle = attributes[.paragraphStyle] as? NSParagraphStyle { newParagraphStyle.setParagraphStyle(paragraphStyle) } newParagraphStyle.insertProperty(HTMLLi(with: representation), afterLastOfType: TextList.self) resultingAttributes[.paragraphStyle] = newParagraphStyle return resultingAttributes } func remove(from attributes: [NSAttributedString.Key: Any]) -> [NSAttributedString.Key: Any] { guard let paragraphStyle = attributes[.paragraphStyle] as? ParagraphStyle else { return attributes } let newParagraphStyle = ParagraphStyle() newParagraphStyle.setParagraphStyle(paragraphStyle) newParagraphStyle.removeProperty(ofType: HTMLLi.self) var resultingAttributes = attributes resultingAttributes[.paragraphStyle] = newParagraphStyle return resultingAttributes } func present(in attributes: [NSAttributedString.Key : Any]) -> Bool { guard let paragraphStyle = attributes[.paragraphStyle] as? ParagraphStyle else { return false } return paragraphStyle.hasProperty { (property) -> Bool in return property is HTMLLi } } }
mpl-2.0
9373b89c8d03bf26b5df3b81ee71b9ac
30.806452
141
0.675456
5.851632
false
false
false
false
peteratseneca/dps923winter2015
Week_07/Friends with photos/Classes/FriendList.swift
1
4354
// // FriendList.swift // Friends // // Created by Peter McIntyre on 2015-02-11. // Copyright (c) 2015 School of ICT, Seneca College. All rights reserved. // import UIKit import CoreData class FriendList: UITableViewController, NSFetchedResultsControllerDelegate, EditItemDelegate { // MARK: - Private properties var frc: NSFetchedResultsController! // MARK: - Properties // Passed in by the app delegate during app initialization var model: Model! // MARK: - View lifecycle override func viewDidLoad() { super.viewDidLoad() // Configure and load the fetched results controller (frc) frc = model.frc_friend // This controller will be the frc delegate frc.delegate = self; // No predicate (which means the results will NOT be filtered) frc.fetchRequest.predicate = nil; // Create an error object var error: NSError? = nil // Perform fetch, and if there's an error, log it if !frc.performFetch(&error) { println(error?.description) } } // MARK: - Table view methods override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return self.frc.sections?.count ?? 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let sectionInfo = self.frc.sections![section] as NSFetchedResultsSectionInfo return sectionInfo.numberOfObjects } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell self.configureCell(cell, atIndexPath: indexPath) return cell } func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) { let item = frc.objectAtIndexPath(indexPath) as Friend // Configure text label cell.textLabel!.text = item.friendName // Configure image // This is how you get an image from the data store // The data store type is NSData // So, we have to make an image from the NSData cell.imageView!.image = UIImage(data: item.photo) } // New method, to configure a section title override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { let sectionInfo = self.frc.sections![section] as NSFetchedResultsSectionInfo return sectionInfo.name } func controllerDidChangeContent(controller: NSFetchedResultsController) { tableView.reloadData() } // MARK: - Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "toFriendDetail" { // Get a reference to the destination view controller let vc = segue.destinationViewController as FriendDetail // From the data source (the fetched results controller)... // Get a reference to the object for the tapped/selected table view row let item = frc.objectAtIndexPath(self.tableView.indexPathForSelectedRow()!) as Friend // Pass on the objects vc.model = self.model vc.detailItem = item // Configure the view if you wish vc.title = item.friendName } if segue.identifier == "toFriendEdit" { // Get a reference to destination controller let nav = segue.destinationViewController as UINavigationController let vc = nav.topViewController as FriendEdit // Configure the controller vc.delegate = self vc.model = self.model vc.title = "Add" } } // MARK: - Delegate methods func editItemDelegate(controller: AnyObject, didEditItem item: AnyObject?) { self.model.saveChanges() // Was presented modally, so dismiss it controller.dismissViewControllerAnimated(true, completion: nil) } }
mit
fe64b0881514fb8dc6d14716e62ea2e5
31.251852
118
0.61943
5.610825
false
true
false
false
michaello/Aloha
AlohaGIF/RecordButton.swift
1
9796
// // RecordButton.swift // Instant // // Created by Samuel Beek on 21/06/15. // Copyright (c) 2015 Samuel Beek. All rights reserved. // import UIKit public enum RecordButtonState: Int { case recording case idle case hidden } @objc open class RecordButton : UIButton { open var buttonColor: UIColor! = .white { didSet { circleLayer.backgroundColor = buttonColor.cgColor circleBorder.borderColor = UIColor(white: 1.0, alpha: 0.5).cgColor } } open var progressColor: UIColor! = .red { didSet { gradientMaskLayer.colors = [UIColor.themeColor.cgColor, UIColor(red: 250.0/255.0, green: 188.0/255.0, blue: 81.0/255.0, alpha: 1.0).cgColor] } } /// Closes the circle and hides when the RecordButton is finished open var closeWhenFinished: Bool = false var indicator: UIActivityIndicatorView! open var buttonState : RecordButtonState = .idle { didSet { switch buttonState { case .idle: self.alpha = 1.0 currentProgress = 0 setProgress(0) setRecording(false) case .recording: self.alpha = 1.0 setRecording(true) case .hidden: self.alpha = 0 } } } fileprivate var circleLayer: CALayer! fileprivate var circleBorder: CALayer! fileprivate var progressLayer: CAShapeLayer! fileprivate var gradientMaskLayer: CAGradientLayer! fileprivate var currentProgress: CGFloat! = 0 override public init(frame: CGRect) { super.init(frame: frame) self.addTarget(self, action: #selector(RecordButton.didTouchDown), for: .touchDown) self.addTarget(self, action: #selector(RecordButton.didTouchUp), for: .touchUpInside) self.addTarget(self, action: #selector(RecordButton.didTouchUp), for: .touchUpOutside) self.drawButton() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.addTarget(self, action: #selector(RecordButton.didTouchDown), for: .touchDown) self.addTarget(self, action: #selector(RecordButton.didTouchUp), for: .touchUpInside) self.addTarget(self, action: #selector(RecordButton.didTouchUp), for: .touchUpOutside) self.drawButton() } open func drawButton() { self.backgroundColor = UIColor.clear let layer = self.layer circleLayer = CALayer() circleLayer.backgroundColor = buttonColor.cgColor let size: CGFloat = self.frame.size.width / 1.5 circleLayer.bounds = CGRect(x: 0, y: 0, width: size, height: size) circleLayer.anchorPoint = CGPoint(x: 0.5, y: 0.5) circleLayer.position = CGPoint(x: self.bounds.midX,y: self.bounds.midY) circleLayer.cornerRadius = size / 2 layer.insertSublayer(circleLayer, at: 0) circleBorder = CALayer() circleBorder.backgroundColor = UIColor.clear.cgColor circleBorder.borderWidth = 1 circleBorder.borderColor = UIColor(white: 1.0, alpha: 0.2).cgColor circleBorder.bounds = CGRect(x: 0, y: 0, width: self.bounds.size.width - 1.5, height: self.bounds.size.height - 1.5) circleBorder.anchorPoint = CGPoint(x: 0.5, y: 0.5) circleBorder.position = CGPoint(x: self.bounds.midX,y: self.bounds.midY) circleBorder.cornerRadius = self.frame.size.width / 2 layer.insertSublayer(circleBorder, at: 0) let startAngle: CGFloat = CGFloat.pi + CGFloat.pi / 2.0 let endAngle: CGFloat = CGFloat.pi * 3.0 + CGFloat.pi / 2.0 let centerPoint: CGPoint = CGPoint(x: self.frame.size.width / 2, y: self.frame.size.height / 2) gradientMaskLayer = self.gradientMask() progressLayer = CAShapeLayer() progressLayer.path = UIBezierPath(arcCenter: centerPoint, radius: self.frame.size.width / 2 - 2, startAngle: startAngle, endAngle: endAngle, clockwise: true).cgPath progressLayer.backgroundColor = UIColor.clear.cgColor progressLayer.fillColor = nil progressLayer.strokeColor = UIColor.black.cgColor progressLayer.lineWidth = 4.0 progressLayer.strokeStart = 0.0 progressLayer.strokeEnd = 0.0 progressColor = .white gradientMaskLayer.mask = progressLayer layer.insertSublayer(gradientMaskLayer, at: 0) addSpinner() } fileprivate func setRecording(_ recording: Bool) { let duration: TimeInterval = 0.15 circleLayer.contentsGravity = "center" let scale = CABasicAnimation(keyPath: "transform.scale") scale.fromValue = recording ? 1.0 : 0.88 scale.toValue = recording ? 0.88 : 1 scale.duration = duration scale.fillMode = kCAFillModeForwards scale.isRemovedOnCompletion = false let color = CABasicAnimation(keyPath: "backgroundColor") color.duration = duration color.fillMode = kCAFillModeForwards color.isRemovedOnCompletion = false color.toValue = recording ? progressColor.cgColor : buttonColor.cgColor let circleAnimations = CAAnimationGroup() circleAnimations.isRemovedOnCompletion = false circleAnimations.fillMode = kCAFillModeForwards circleAnimations.duration = duration circleAnimations.animations = [scale, color] let borderColor: CABasicAnimation = CABasicAnimation(keyPath: "borderColor") borderColor.duration = duration borderColor.fillMode = kCAFillModeForwards borderColor.isRemovedOnCompletion = false borderColor.toValue = recording ? UIColor(red: 0.83, green: 0.86, blue: 0.89, alpha: 1).cgColor : buttonColor let borderScale = CABasicAnimation(keyPath: "transform.scale") borderScale.fromValue = recording ? 1.0 : 0.88 borderScale.toValue = recording ? 0.88 : 1.0 borderScale.duration = duration borderScale.fillMode = kCAFillModeForwards borderScale.isRemovedOnCompletion = false let borderAnimations = CAAnimationGroup() borderAnimations.isRemovedOnCompletion = false borderAnimations.fillMode = kCAFillModeForwards borderAnimations.duration = duration borderAnimations.animations = [borderColor, borderScale] let fade = CABasicAnimation(keyPath: "opacity") fade.fromValue = recording ? 0.0 : 1.0 fade.toValue = recording ? 1.0 : 0.0 fade.duration = duration fade.fillMode = kCAFillModeForwards fade.isRemovedOnCompletion = false circleLayer.add(circleAnimations, forKey: "circleAnimations") progressLayer.add(fade, forKey: "fade") circleBorder.add(borderAnimations, forKey: "borderAnimations") } fileprivate func gradientMask() -> CAGradientLayer { let gradientLayer = CAGradientLayer() gradientLayer.frame = self.bounds gradientLayer.locations = [0.0, 1.0] gradientLayer.colors = [progressColor, progressColor] return gradientLayer } override open func layoutSubviews() { circleLayer.anchorPoint = CGPoint(x: 0.5, y: 0.5) circleLayer.position = CGPoint(x: self.bounds.midX,y: self.bounds.midY) circleBorder.anchorPoint = CGPoint(x: 0.5, y: 0.5) circleBorder.position = CGPoint(x: self.bounds.midX,y: self.bounds.midY) super.layoutSubviews() } open func didTouchDown(){ self.buttonState = .recording } open func didTouchUp() { if(closeWhenFinished) { self.setProgress(1) UIView.animate(withDuration: 0.3, animations: { self.buttonState = .hidden }, completion: { completion in self.setProgress(0) self.currentProgress = 0 }) } else { self.buttonState = .idle } } /** Set the relative length of the circle border to the specified progress - parameter newProgress: the relative lenght, a percentage as float. */ open func setProgress(_ newProgress: CGFloat) { progressLayer.strokeEnd = newProgress } open override func didMoveToSuperview() { super.didMoveToSuperview() translatesAutoresizingMaskIntoConstraints = false guard let superview = superview, constraints.isEmpty else { return } centerXAnchor.constraint(equalTo: superview.centerXAnchor).isActive = true centerYAnchor.constraint(equalTo: superview.centerYAnchor).isActive = true heightAnchor.constraint(equalToConstant: 70.0).isActive = true widthAnchor.constraint(equalToConstant: 70.0).isActive = true superview.layoutIfNeeded() drawButton() } private func addSpinner() { indicator = UIActivityIndicatorView() indicator.alpha = 0.0 indicator.frame = bounds indicator.color = .themeColor indicator.center = CGPoint(x: bounds.width / 2, y: bounds.height / 2) addSubview(indicator) } func startLoading() { isEnabled = false UIView.animate(withDuration: 0.3) { self.indicator.alpha = 1.0 } indicator.startAnimating() } func stopLoading() { isEnabled = true UIView.animate(withDuration: 0.3, animations: { self.indicator.alpha = 0.0 }) { _ in self.indicator.stopAnimating() } } }
mit
b1d693ce189e0d762c5cbda3c34ee857
35.966038
172
0.629849
4.942482
false
false
false
false
IamAlchemist/DemoCI
DemoCI/ScalarFilterParameter.swift
1
709
// // ScalarFilterParameter.swift // DemoCI // // Created by wizard lee on 7/24/16. // Copyright © 2016 cc.kauhaus. All rights reserved. // import UIKit class ScalarFilterParameter { var name: String? var key: String var minimumValue: Float? var maximumValue: Float? var currentValue: Float init(key: String, value: Float) { self.key = key self.currentValue = value } init(name: String, key: String, minimumValue: Float, maximumValue: Float, currentValue: Float) { self.name = name self.key = key self.minimumValue = minimumValue self.maximumValue = maximumValue self.currentValue = currentValue } }
mit
fcac3da61954c357f5a8123b51ccb27c
22.6
100
0.638418
4.164706
false
false
false
false
marksands/SwiftLensLuncheon
UserListValueTypes/Identifiable.swift
1
809
// // Created by Christopher Trott on 1/8/16. // Copyright © 2016 twocentstudios. All rights reserved. // import Foundation /// Identifiable represents the concept of the same object or resource in a different state. protocol Identifiable { func =~=(lhs: Self, rhs: Self) -> Bool } infix operator =~= { associativity none precedence 130 } /// Helper for determining if two arrays of have objects of equal identity. func =~=<T : Identifiable>(lhs: [T], rhs: [T]) -> Bool { if lhs.count != rhs.count { return false } let zipped = Zip2Sequence(lhs, rhs) let mapped = zipped.map { (lElement, rElement) -> Bool in return lElement =~= rElement } let reduced = mapped.reduce(true) { (element, result) -> Bool in return element && result } return reduced }
mit
bf3f42c74a8a18623f180f4feb030ce6
28.925926
92
0.659653
3.866029
false
false
false
false
Rypac/hn
hn/FirebaseService.swift
1
1043
import Foundation import RxSwift final class FirebaseService { typealias Item = FirebaseItem private let apiClient: APIClient private let decoder = JSONDecoder() init(apiClient: APIClient) { self.apiClient = apiClient } func topStories() -> Single<[Int]> { return apiClient.get(Firebase.topStories.url) .map { [decoder] response in guard (200..<299).contains(response.statusCode) else { throw APIServiceError.invalidStatusCode } guard let data = response.body else { throw APIServiceError.invalidPayload } return try decoder.decode(data) } } func item(id: Int) -> Single<Item> { return apiClient.get(Firebase.item(id).url) .map { [decoder] response in guard (200..<299).contains(response.statusCode) else { throw APIServiceError.invalidStatusCode } guard let data = response.body else { throw APIServiceError.invalidPayload } return try decoder.decode(data) } } }
mit
de9cfc1ad4303b05f263d76c67b918c8
25.74359
62
0.643337
4.534783
false
false
false
false
TsuiOS/LoveFreshBeen
LoveFreshBeenX/Class/View/Home/XNHomeHeadView.swift
1
1675
// // XNHeaderView.swift // LoveFreshBeenX // // Created by xuning on 16/6/9. // Copyright © 2016年 hus. All rights reserved. // import UIKit class XNHomeHeadView: UIView { private var pageScrollView: XNPageScrollView? private var hotView: XNHomeHotView? var tableHeadViewHeight: CGFloat = 0 { willSet { NSNotificationCenter.defaultCenter().postNotificationName(HomeTableHeadViewHeightDidChange, object: newValue) frame = CGRectMake(0, -newValue, ScreenWidth, newValue) } } var headData: XNHeadResources? { didSet { pageScrollView?.headData = headData hotView?.headData = headData?.data } } override init(frame: CGRect) { super.init(frame: frame) buildPageScrollView() buildHotView() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func buildPageScrollView() { pageScrollView = XNPageScrollView(frame: CGRectZero, placeholder: UIImage(named: "v2_placeholder_full_size")!) addSubview(pageScrollView!) } private func buildHotView() { hotView = XNHomeHotView() hotView?.backgroundColor = UIColor.whiteColor() addSubview(hotView!) } override func layoutSubviews() { super.layoutSubviews() pageScrollView?.frame = CGRectMake(0, 0, ScreenWidth, 150) hotView?.frame = CGRectMake(0, CGRectGetMaxY(pageScrollView!.frame), ScreenWidth, 80) tableHeadViewHeight = CGRectGetMaxY(hotView!.frame) } }
mit
b5cb2a004d1eccbbdc5122f711e53850
25.125
121
0.627392
4.818444
false
false
false
false