repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
IvonLiu/moscrop-secondary-ios
Pods/Kingfisher/Sources/ImageCache.swift
2
27471
// // ImageCache.swift // Kingfisher // // Created by Wei Wang on 15/4/6. // // Copyright (c) 2016 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(OSX) import AppKit #else import UIKit #endif /** This notification will be sent when the disk cache got cleaned either there are cached files expired or the total size exceeding the max allowed size. The manually invoking of `clearDiskCache` method will not trigger this notification. The `object` of this notification is the `ImageCache` object which sends the notification. A list of removed hashes (files) could be retrieved by accessing the array under `KingfisherDiskCacheCleanedHashKey` key in `userInfo` of the notification object you received. By checking the array, you could know the hash codes of files are removed. The main purpose of this notification is supplying a chance to maintain some necessary information on the cached files. See [this wiki](https://github.com/onevcat/Kingfisher/wiki/How-to-implement-ETag-based-304-(Not-Modified)-handling-in-Kingfisher) for a use case on it. */ public let KingfisherDidCleanDiskCacheNotification = "com.onevcat.Kingfisher.KingfisherDidCleanDiskCacheNotification" /** Key for array of cleaned hashes in `userInfo` of `KingfisherDidCleanDiskCacheNotification`. */ public let KingfisherDiskCacheCleanedHashKey = "com.onevcat.Kingfisher.cleanedHash" private let defaultCacheName = "default" private let cacheReverseDNS = "com.onevcat.Kingfisher.ImageCache." private let ioQueueName = "com.onevcat.Kingfisher.ImageCache.ioQueue." private let processQueueName = "com.onevcat.Kingfisher.ImageCache.processQueue." private let defaultCacheInstance = ImageCache(name: defaultCacheName) private let defaultMaxCachePeriodInSecond: NSTimeInterval = 60 * 60 * 24 * 7 //Cache exists for 1 week /// It represents a task of retrieving image. You can call `cancel` on it to stop the process. public typealias RetrieveImageDiskTask = dispatch_block_t /** Cache type of a cached image. - None: The image is not cached yet when retrieving it. - Memory: The image is cached in memory. - Disk: The image is cached in disk. */ public enum CacheType { case None, Memory, Disk } /// `ImageCache` represents both the memory and disk cache system of Kingfisher. While a default image cache object will be used if you prefer the extension methods of Kingfisher, you can create your own cache object and configure it as your need. You should use an `ImageCache` object to manipulate memory and disk cache for Kingfisher. public class ImageCache { //Memory private let memoryCache = NSCache() /// The largest cache cost of memory cache. The total cost is pixel count of all cached images in memory. public var maxMemoryCost: UInt = 0 { didSet { self.memoryCache.totalCostLimit = Int(maxMemoryCost) } } //Disk private let ioQueue: dispatch_queue_t private var fileManager: NSFileManager! ///The disk cache location. public let diskCachePath: String /// The longest time duration of the cache being stored in disk. Default is 1 week. public var maxCachePeriodInSecond = defaultMaxCachePeriodInSecond /// The largest disk size can be taken for the cache. It is the total allocated size of cached files in bytes. Default is 0, which means no limit. public var maxDiskCacheSize: UInt = 0 private let processQueue: dispatch_queue_t /// The default cache. public class var defaultCache: ImageCache { return defaultCacheInstance } /** Init method. Passing a name for the cache. It represents a cache folder in the memory and disk. - parameter name: Name of the cache. It will be used as the memory cache name and the disk cache folder name appending to the cache path. This value should not be an empty string. - parameter path: Optional - Location of cache path on disk. If `nil` is passed (the default value), the cache folder in of your app will be used. If you want to cache some user generating images, you could pass the Documentation path here. - returns: The cache object. */ public init(name: String, path: String? = nil) { if name.isEmpty { fatalError("[Kingfisher] You should specify a name for the cache. A cache with empty name is not permitted.") } let cacheName = cacheReverseDNS + name memoryCache.name = cacheName let dstPath = path ?? NSSearchPathForDirectoriesInDomains(.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true).first! diskCachePath = (dstPath as NSString).stringByAppendingPathComponent(cacheName) ioQueue = dispatch_queue_create(ioQueueName + name, DISPATCH_QUEUE_SERIAL) processQueue = dispatch_queue_create(processQueueName + name, DISPATCH_QUEUE_CONCURRENT) dispatch_sync(ioQueue, { () -> Void in self.fileManager = NSFileManager() }) #if !os(OSX) && !os(watchOS) NSNotificationCenter.defaultCenter().addObserver(self, selector: "clearMemoryCache", name: UIApplicationDidReceiveMemoryWarningNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "cleanExpiredDiskCache", name: UIApplicationWillTerminateNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "backgroundCleanExpiredDiskCache", name: UIApplicationDidEnterBackgroundNotification, object: nil) #endif } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } } // MARK: - Store & Remove extension ImageCache { /** Store an image to cache. It will be saved to both memory and disk. It is an async operation, if you need to do something about the stored image, use `-storeImage:forKey:toDisk:completionHandler:` instead. - parameter image: The image will be stored. - parameter originalData: The original data of the image. Kingfisher will use it to check the format of the image and optimize cache size on disk. If `nil` is supplied, the image data will be saved as a normalized PNG file. It is strongly suggested to supply it whenever possible, to get a better performance and disk usage. - parameter key: Key for the image. */ public func storeImage(image: Image, originalData: NSData? = nil, forKey key: String) { storeImage(image, originalData: originalData, forKey: key, toDisk: true, completionHandler: nil) } /** Store an image to cache. It is an async operation. - parameter image: The image will be stored. - parameter originalData: The original data of the image. Kingfisher will use it to check the format of the image and optimize cache size on disk. If `nil` is supplied, the image data will be saved as a normalized PNG file. It is strongly suggested to supply it whenever possible, to get a better performance and disk usage. - parameter key: Key for the image. - parameter toDisk: Whether this image should be cached to disk or not. If false, the image will be only cached in memory. - parameter completionHandler: Called when stroe operation completes. */ public func storeImage(image: Image, originalData: NSData? = nil, forKey key: String, toDisk: Bool, completionHandler: (() -> ())?) { memoryCache.setObject(image, forKey: key, cost: image.kf_imageCost) func callHandlerInMainQueue() { if let handler = completionHandler { dispatch_async(dispatch_get_main_queue()) { handler() } } } if toDisk { dispatch_async(ioQueue, { () -> Void in let imageFormat: ImageFormat if let originalData = originalData { imageFormat = originalData.kf_imageFormat } else { imageFormat = .Unknown } let data: NSData? switch imageFormat { case .PNG: data = originalData ?? ImagePNGRepresentation(image) case .JPEG: data = originalData ?? ImageJPEGRepresentation(image, 1.0) case .GIF: data = originalData ?? ImageGIFRepresentation(image) case .Unknown: data = originalData ?? ImagePNGRepresentation(image.kf_normalizedImage()) } if let data = data { if !self.fileManager.fileExistsAtPath(self.diskCachePath) { do { try self.fileManager.createDirectoryAtPath(self.diskCachePath, withIntermediateDirectories: true, attributes: nil) } catch _ {} } self.fileManager.createFileAtPath(self.cachePathForKey(key), contents: data, attributes: nil) } callHandlerInMainQueue() }) } else { callHandlerInMainQueue() } } /** Remove the image for key for the cache. It will be opted out from both memory and disk. It is an async operation, if you need to do something about the stored image, use `-removeImageForKey:fromDisk:completionHandler:` instead. - parameter key: Key for the image. */ public func removeImageForKey(key: String) { removeImageForKey(key, fromDisk: true, completionHandler: nil) } /** Remove the image for key for the cache. It is an async operation. - parameter key: Key for the image. - parameter fromDisk: Whether this image should be removed from disk or not. If false, the image will be only removed from memory. - parameter completionHandler: Called when removal operation completes. */ public func removeImageForKey(key: String, fromDisk: Bool, completionHandler: (() -> ())?) { memoryCache.removeObjectForKey(key) func callHandlerInMainQueue() { if let handler = completionHandler { dispatch_async(dispatch_get_main_queue()) { handler() } } } if fromDisk { dispatch_async(ioQueue, { () -> Void in do { try self.fileManager.removeItemAtPath(self.cachePathForKey(key)) } catch _ {} callHandlerInMainQueue() }) } else { callHandlerInMainQueue() } } } // MARK: - Get data from cache extension ImageCache { /** Get an image for a key from memory or disk. - parameter key: Key for the image. - parameter options: Options of retrieving image. - parameter completionHandler: Called when getting operation completes with image result and cached type of this image. If there is no such key cached, the image will be `nil`. - returns: The retrieving task. */ public func retrieveImageForKey(key: String, options: KingfisherOptionsInfo?, completionHandler: ((Image?, CacheType!) -> ())?) -> RetrieveImageDiskTask? { // No completion handler. Not start working and early return. guard let completionHandler = completionHandler else { return nil } var block: RetrieveImageDiskTask? if let image = self.retrieveImageInMemoryCacheForKey(key) { //Found image in memory cache. if let options = options where options.backgroundDecode { dispatch_async(self.processQueue, { () -> Void in let result = image.kf_decodedImage(scale: options.scaleFactor) dispatch_async(options.callbackDispatchQueue, { () -> Void in completionHandler(result, .Memory) }) }) } else { completionHandler(image, .Memory) } } else { var sSelf: ImageCache! = self block = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS) { // Begin to load image from disk let options = options ?? KingfisherEmptyOptionsInfo if let image = sSelf.retrieveImageInDiskCacheForKey(key, scale: options.scaleFactor) { if options.backgroundDecode { dispatch_async(sSelf.processQueue, { () -> Void in let result = image.kf_decodedImage(scale: options.scaleFactor) sSelf.storeImage(result!, forKey: key, toDisk: false, completionHandler: nil) dispatch_async(options.callbackDispatchQueue, { () -> Void in completionHandler(result, .Memory) sSelf = nil }) }) } else { sSelf.storeImage(image, forKey: key, toDisk: false, completionHandler: nil) dispatch_async(options.callbackDispatchQueue, { () -> Void in completionHandler(image, .Disk) sSelf = nil }) } } else { // No image found from either memory or disk dispatch_async(options.callbackDispatchQueue, { () -> Void in completionHandler(nil, nil) sSelf = nil }) } } dispatch_async(sSelf.ioQueue, block!) } return block } /** Get an image for a key from memory. - parameter key: Key for the image. - returns: The image object if it is cached, or `nil` if there is no such key in the cache. */ public func retrieveImageInMemoryCacheForKey(key: String) -> Image? { return memoryCache.objectForKey(key) as? Image } /** Get an image for a key from disk. - parameter key: Key for the image. - param scale: The scale factor to assume when interpreting the image data. - returns: The image object if it is cached, or `nil` if there is no such key in the cache. */ public func retrieveImageInDiskCacheForKey(key: String, scale: CGFloat = 1.0) -> Image? { return diskImageForKey(key, scale: scale) } } // MARK: - Clear & Clean extension ImageCache { /** Clear memory cache. */ @objc public func clearMemoryCache() { memoryCache.removeAllObjects() } /** Clear disk cache. This is could be an async or sync operation. Specify the way you want it by passing the `sync` parameter. */ public func clearDiskCache() { clearDiskCacheWithCompletionHandler(nil) } /** Clear disk cache. This is an async operation. - parameter completionHander: Called after the operation completes. */ public func clearDiskCacheWithCompletionHandler(completionHander: (()->())?) { dispatch_async(ioQueue, { () -> Void in do { try self.fileManager.removeItemAtPath(self.diskCachePath) try self.fileManager.createDirectoryAtPath(self.diskCachePath, withIntermediateDirectories: true, attributes: nil) } catch _ { } if let completionHander = completionHander { dispatch_async(dispatch_get_main_queue(), { () -> Void in completionHander() }) } }) } /** Clean expired disk cache. This is an async operation. */ @objc public func cleanExpiredDiskCache() { cleanExpiredDiskCacheWithCompletionHander(nil) } /** Clean expired disk cache. This is an async operation. - parameter completionHandler: Called after the operation completes. */ public func cleanExpiredDiskCacheWithCompletionHander(completionHandler: (()->())?) { // Do things in cocurrent io queue dispatch_async(ioQueue, { () -> Void in let diskCacheURL = NSURL(fileURLWithPath: self.diskCachePath) let resourceKeys = [NSURLIsDirectoryKey, NSURLContentModificationDateKey, NSURLTotalFileAllocatedSizeKey] let expiredDate = NSDate(timeIntervalSinceNow: -self.maxCachePeriodInSecond) var cachedFiles = [NSURL: [NSObject: AnyObject]]() var URLsToDelete = [NSURL]() var diskCacheSize: UInt = 0 if let fileEnumerator = self.fileManager.enumeratorAtURL(diskCacheURL, includingPropertiesForKeys: resourceKeys, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles, errorHandler: nil), urls = fileEnumerator.allObjects as? [NSURL] { for fileURL in urls { do { let resourceValues = try fileURL.resourceValuesForKeys(resourceKeys) // If it is a Directory. Continue to next file URL. if let isDirectory = resourceValues[NSURLIsDirectoryKey] as? NSNumber { if isDirectory.boolValue { continue } } // If this file is expired, add it to URLsToDelete if let modificationDate = resourceValues[NSURLContentModificationDateKey] as? NSDate { if modificationDate.laterDate(expiredDate) == expiredDate { URLsToDelete.append(fileURL) continue } } if let fileSize = resourceValues[NSURLTotalFileAllocatedSizeKey] as? NSNumber { diskCacheSize += fileSize.unsignedLongValue cachedFiles[fileURL] = resourceValues } } catch _ { } } } for fileURL in URLsToDelete { do { try self.fileManager.removeItemAtURL(fileURL) } catch _ { } } if self.maxDiskCacheSize > 0 && diskCacheSize > self.maxDiskCacheSize { let targetSize = self.maxDiskCacheSize / 2 // Sort files by last modify date. We want to clean from the oldest files. let sortedFiles = cachedFiles.keysSortedByValue { resourceValue1, resourceValue2 -> Bool in if let date1 = resourceValue1[NSURLContentModificationDateKey] as? NSDate, date2 = resourceValue2[NSURLContentModificationDateKey] as? NSDate { return date1.compare(date2) == .OrderedAscending } // Not valid date information. This should not happen. Just in case. return true } for fileURL in sortedFiles { do { try self.fileManager.removeItemAtURL(fileURL) } catch { } URLsToDelete.append(fileURL) if let fileSize = cachedFiles[fileURL]?[NSURLTotalFileAllocatedSizeKey] as? NSNumber { diskCacheSize -= fileSize.unsignedLongValue } if diskCacheSize < targetSize { break } } } dispatch_async(dispatch_get_main_queue(), { () -> Void in if URLsToDelete.count != 0 { let cleanedHashes = URLsToDelete.map({ (url) -> String in return url.lastPathComponent! }) NSNotificationCenter.defaultCenter().postNotificationName(KingfisherDidCleanDiskCacheNotification, object: self, userInfo: [KingfisherDiskCacheCleanedHashKey: cleanedHashes]) } completionHandler?() }) }) } #if !os(OSX) && !os(watchOS) /** Clean expired disk cache when app in background. This is an async operation. In most cases, you should not call this method explicitly. It will be called automatically when `UIApplicationDidEnterBackgroundNotification` received. */ @objc public func backgroundCleanExpiredDiskCache() { func endBackgroundTask(inout task: UIBackgroundTaskIdentifier) { UIApplication.sharedApplication().endBackgroundTask(task) task = UIBackgroundTaskInvalid } var backgroundTask: UIBackgroundTaskIdentifier! backgroundTask = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler { () -> Void in endBackgroundTask(&backgroundTask!) } cleanExpiredDiskCacheWithCompletionHander { () -> () in endBackgroundTask(&backgroundTask!) } } #endif } // MARK: - Check cache status extension ImageCache { /** * Cache result for checking whether an image is cached for a key. */ public struct CacheCheckResult { public let cached: Bool public let cacheType: CacheType? } /** Check whether an image is cached for a key. - parameter key: Key for the image. - returns: The check result. */ public func isImageCachedForKey(key: String) -> CacheCheckResult { if memoryCache.objectForKey(key) != nil { return CacheCheckResult(cached: true, cacheType: .Memory) } let filePath = cachePathForKey(key) var diskCached = false dispatch_sync(ioQueue) { () -> Void in diskCached = self.fileManager.fileExistsAtPath(filePath) } if diskCached { return CacheCheckResult(cached: true, cacheType: .Disk) } return CacheCheckResult(cached: false, cacheType: nil) } /** Get the hash for the key. This could be used for matching files. - parameter key: The key which is used for caching. - returns: Corresponding hash. */ public func hashForKey(key: String) -> String { return cacheFileNameForKey(key) } /** Calculate the disk size taken by cache. It is the total allocated size of the cached files in bytes. - parameter completionHandler: Called with the calculated size when finishes. */ public func calculateDiskCacheSizeWithCompletionHandler(completionHandler: ((size: UInt) -> ())) { dispatch_async(ioQueue, { () -> Void in let diskCacheURL = NSURL(fileURLWithPath: self.diskCachePath) let resourceKeys = [NSURLIsDirectoryKey, NSURLTotalFileAllocatedSizeKey] var diskCacheSize: UInt = 0 if let fileEnumerator = self.fileManager.enumeratorAtURL(diskCacheURL, includingPropertiesForKeys: resourceKeys, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles, errorHandler: nil), urls = fileEnumerator.allObjects as? [NSURL] { for fileURL in urls { do { let resourceValues = try fileURL.resourceValuesForKeys(resourceKeys) // If it is a Directory. Continue to next file URL. if let isDirectory = resourceValues[NSURLIsDirectoryKey]?.boolValue { if isDirectory { continue } } if let fileSize = resourceValues[NSURLTotalFileAllocatedSizeKey] as? NSNumber { diskCacheSize += fileSize.unsignedLongValue } } catch _ { } } } dispatch_async(dispatch_get_main_queue(), { () -> Void in completionHandler(size: diskCacheSize) }) }) } } // MARK: - Internal Helper extension ImageCache { func diskImageForKey(key: String, scale: CGFloat) -> Image? { if let data = diskImageDataForKey(key) { return Image.kf_imageWithData(data, scale: scale) } else { return nil } } func diskImageDataForKey(key: String) -> NSData? { let filePath = cachePathForKey(key) return NSData(contentsOfFile: filePath) } func cachePathForKey(key: String) -> String { let fileName = cacheFileNameForKey(key) return (diskCachePath as NSString).stringByAppendingPathComponent(fileName) } func cacheFileNameForKey(key: String) -> String { return key.kf_MD5 } } extension Image { var kf_imageCost: Int { return kf_images == nil ? Int(size.height * size.width * kf_scale * kf_scale) : Int(size.height * size.width * kf_scale * kf_scale) * kf_images!.count } } extension Dictionary { func keysSortedByValue(isOrderedBefore: (Value, Value) -> Bool) -> [Key] { return Array(self).sort{ isOrderedBefore($0.1, $1.1) }.map{ $0.0 } } }
mit
cc5e77d9113ac35d68fabffbc5d40e56
40.74924
337
0.591897
5.617791
false
false
false
false
christophercotton/Alamofire
Tests/RequestTests.swift
36
23746
// RequestTests.swift // // Copyright (c) 2014-2015 Alamofire Software Foundation (http://alamofire.org) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Alamofire import Foundation import XCTest class RequestInitializationTestCase: BaseTestCase { func testRequestClassMethodWithMethodAndURL() { // Given let URLString = "https://httpbin.org/" // When let request = Alamofire.request(.GET, URLString) // Then XCTAssertNotNil(request.request, "request URL request should not be nil") XCTAssertEqual(request.request?.HTTPMethod ?? "", "GET", "request HTTP method should match expected value") XCTAssertEqual(request.request?.URLString ?? "", URLString, "request URL string should be equal") XCTAssertNil(request.response, "request response should be nil") } func testRequestClassMethodWithMethodAndURLAndParameters() { // Given let URLString = "https://httpbin.org/get" // When let request = Alamofire.request(.GET, URLString, parameters: ["foo": "bar"]) // Then XCTAssertNotNil(request.request, "request URL request should not be nil") XCTAssertEqual(request.request?.HTTPMethod ?? "", "GET", "request HTTP method should match expected value") XCTAssertNotEqual(request.request?.URLString ?? "", URLString, "request URL string should be equal") XCTAssertEqual(request.request?.URL?.query ?? "", "foo=bar", "query is incorrect") XCTAssertNil(request.response, "request response should be nil") } func testRequestClassMethodWithMethodURLParametersAndHeaders() { // Given let URLString = "https://httpbin.org/get" let headers = ["Authorization": "123456"] // When let request = Alamofire.request(.GET, URLString, parameters: ["foo": "bar"], headers: headers) // Then XCTAssertNotNil(request.request, "request should not be nil") XCTAssertEqual(request.request?.HTTPMethod ?? "", "GET", "request HTTP method should match expected value") XCTAssertNotEqual(request.request?.URLString ?? "", URLString, "request URL string should be equal") XCTAssertEqual(request.request?.URL?.query ?? "", "foo=bar", "query is incorrect") let authorizationHeader = request.request?.valueForHTTPHeaderField("Authorization") ?? "" XCTAssertEqual(authorizationHeader, "123456", "Authorization header is incorrect") XCTAssertNil(request.response, "response should be nil") } } // MARK: - class RequestResponseTestCase: BaseTestCase { func testRequestResponse() { // Given let URLString = "https://httpbin.org/get" let expectation = expectationWithDescription("GET request should succeed: \(URLString)") var request: NSURLRequest? var response: NSHTTPURLResponse? var data: NSData? var error: ErrorType? // When Alamofire.request(.GET, URLString, parameters: ["foo": "bar"]) .response { responseRequest, responseResponse, responseData, responseError in request = responseRequest response = responseResponse data = responseData error = responseError expectation.fulfill() } waitForExpectationsWithTimeout(defaultTimeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNotNil(response, "response should not be nil") XCTAssertNotNil(data, "data should not be nil") XCTAssertNil(error, "error should be nil") } func testRequestResponseWithProgress() { // Given let randomBytes = 4 * 1024 * 1024 let URLString = "https://httpbin.org/bytes/\(randomBytes)" let expectation = expectationWithDescription("Bytes download progress should be reported: \(URLString)") var byteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = [] var progressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = [] var responseRequest: NSURLRequest? var responseResponse: NSHTTPURLResponse? var responseData: NSData? var responseError: ErrorType? // When let request = Alamofire.request(.GET, URLString) request.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in let bytes = (bytes: bytesRead, totalBytes: totalBytesRead, totalBytesExpected: totalBytesExpectedToRead) byteValues.append(bytes) let progress = ( completedUnitCount: request.progress.completedUnitCount, totalUnitCount: request.progress.totalUnitCount ) progressValues.append(progress) } request.response { request, response, data, error in responseRequest = request responseResponse = response responseData = data responseError = error expectation.fulfill() } waitForExpectationsWithTimeout(defaultTimeout, handler: nil) // Then XCTAssertNotNil(responseRequest, "response request should not be nil") XCTAssertNotNil(responseResponse, "response response should not be nil") XCTAssertNotNil(responseData, "response data should not be nil") XCTAssertNil(responseError, "response error should be nil") XCTAssertEqual(byteValues.count, progressValues.count, "byteValues count should equal progressValues count") if byteValues.count == progressValues.count { for index in 0..<byteValues.count { let byteValue = byteValues[index] let progressValue = progressValues[index] XCTAssertGreaterThan(byteValue.bytes, 0, "reported bytes should always be greater than 0") XCTAssertEqual( byteValue.totalBytes, progressValue.completedUnitCount, "total bytes should be equal to completed unit count" ) XCTAssertEqual( byteValue.totalBytesExpected, progressValue.totalUnitCount, "total bytes expected should be equal to total unit count" ) } } if let lastByteValue = byteValues.last, lastProgressValue = progressValues.last { let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected) let progressValueFractionalCompletion = Double(lastProgressValue.0) / Double(lastProgressValue.1) XCTAssertEqual(byteValueFractionalCompletion, 1.0, "byte value fractional completion should equal 1.0") XCTAssertEqual(progressValueFractionalCompletion, 1.0, "progress value fractional completion should equal 1.0") } else { XCTFail("last item in bytesValues and progressValues should not be nil") } } func testRequestResponseWithStream() { // Given let randomBytes = 4 * 1024 * 1024 let URLString = "https://httpbin.org/bytes/\(randomBytes)" let expectation = expectationWithDescription("Bytes download progress should be reported: \(URLString)") var byteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = [] var progressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = [] var accumulatedData = [NSData]() var responseRequest: NSURLRequest? var responseResponse: NSHTTPURLResponse? var responseData: NSData? var responseError: ErrorType? // When let request = Alamofire.request(.GET, URLString) request.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in let bytes = (bytes: bytesRead, totalBytes: totalBytesRead, totalBytesExpected: totalBytesExpectedToRead) byteValues.append(bytes) let progress = ( completedUnitCount: request.progress.completedUnitCount, totalUnitCount: request.progress.totalUnitCount ) progressValues.append(progress) } request.stream { accumulatedData.append($0) } request.response { request, response, data, error in responseRequest = request responseResponse = response responseData = data responseError = error expectation.fulfill() } waitForExpectationsWithTimeout(defaultTimeout, handler: nil) // Then XCTAssertNotNil(responseRequest, "response request should not be nil") XCTAssertNotNil(responseResponse, "response response should not be nil") XCTAssertNil(responseData, "response data should be nil") XCTAssertNil(responseError, "response error should be nil") XCTAssertGreaterThanOrEqual(accumulatedData.count, 1, "accumulated data should have one or more parts") XCTAssertEqual(byteValues.count, progressValues.count, "byteValues count should equal progressValues count") if byteValues.count == progressValues.count { for index in 0..<byteValues.count { let byteValue = byteValues[index] let progressValue = progressValues[index] XCTAssertGreaterThan(byteValue.bytes, 0, "reported bytes should always be greater than 0") XCTAssertEqual( byteValue.totalBytes, progressValue.completedUnitCount, "total bytes should be equal to completed unit count" ) XCTAssertEqual( byteValue.totalBytesExpected, progressValue.totalUnitCount, "total bytes expected should be equal to total unit count" ) } } if let lastByteValue = byteValues.last, lastProgressValue = progressValues.last { let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected) let progressValueFractionalCompletion = Double(lastProgressValue.0) / Double(lastProgressValue.1) XCTAssertEqual(byteValueFractionalCompletion, 1.0, "byte value fractional completion should equal 1.0") XCTAssertEqual( progressValueFractionalCompletion, 1.0, "progress value fractional completion should equal 1.0" ) XCTAssertEqual( accumulatedData.reduce(Int64(0)) { $0 + $1.length }, lastByteValue.totalBytes, "accumulated data length should match byte count" ) } else { XCTFail("last item in bytesValues and progressValues should not be nil") } } func testPOSTRequestWithUnicodeParameters() { // Given let URLString = "https://httpbin.org/post" let parameters = [ "french": "français", "japanese": "日本語", "arabic": "العربية", "emoji": "😃" ] let expectation = expectationWithDescription("request should succeed") var request: NSURLRequest? var response: NSHTTPURLResponse? var result: Result<AnyObject>? // When Alamofire.request(.POST, URLString, parameters: parameters) .responseJSON { responseRequest, responseResponse, responseResult in request = responseRequest response = responseResponse result = responseResult expectation.fulfill() } waitForExpectationsWithTimeout(defaultTimeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNotNil(response, "response should not be nil") XCTAssertNotNil(result, "result should be nil") if let JSON = result?.value as? [String: AnyObject], form = JSON["form"] as? [String: String] { XCTAssertEqual(form["french"], parameters["french"], "french parameter value should match form value") XCTAssertEqual(form["japanese"], parameters["japanese"], "japanese parameter value should match form value") XCTAssertEqual(form["arabic"], parameters["arabic"], "arabic parameter value should match form value") XCTAssertEqual(form["emoji"], parameters["emoji"], "emoji parameter value should match form value") } else { XCTFail("form parameter in JSON should not be nil") } } func testPOSTRequestWithBase64EncodedImages() { // Given let URLString = "https://httpbin.org/post" let pngBase64EncodedString: String = { let URL = URLForResource("unicorn", withExtension: "png") let data = NSData(contentsOfURL: URL)! return data.base64EncodedStringWithOptions(.Encoding64CharacterLineLength) }() let jpegBase64EncodedString: String = { let URL = URLForResource("rainbow", withExtension: "jpg") let data = NSData(contentsOfURL: URL)! return data.base64EncodedStringWithOptions(.Encoding64CharacterLineLength) }() let parameters = [ "email": "[email protected]", "png_image": pngBase64EncodedString, "jpeg_image": jpegBase64EncodedString ] let expectation = expectationWithDescription("request should succeed") var request: NSURLRequest? var response: NSHTTPURLResponse? var result: Result<AnyObject>? // When Alamofire.request(.POST, URLString, parameters: parameters) .responseJSON { responseRequest, responseResponse, responseResult in request = responseRequest response = responseResponse result = responseResult expectation.fulfill() } waitForExpectationsWithTimeout(defaultTimeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNotNil(response, "response should not be nil") XCTAssertNotNil(result, "result should be nil") if let JSON = result?.value as? [String: AnyObject], form = JSON["form"] as? [String: String] { XCTAssertEqual(form["email"], parameters["email"], "email parameter value should match form value") XCTAssertEqual(form["png_image"], parameters["png_image"], "png_image parameter value should match form value") XCTAssertEqual(form["jpeg_image"], parameters["jpeg_image"], "jpeg_image parameter value should match form value") } else { XCTFail("form parameter in JSON should not be nil") } } } // MARK: - extension Request { private func preValidate(operation: Void -> Void) -> Self { delegate.queue.addOperationWithBlock { operation() } return self } private func postValidate(operation: Void -> Void) -> Self { delegate.queue.addOperationWithBlock { operation() } return self } } // MARK: - class RequestExtensionTestCase: BaseTestCase { func testThatRequestExtensionHasAccessToTaskDelegateQueue() { // Given let URLString = "https://httpbin.org/get" let expectation = expectationWithDescription("GET request should succeed: \(URLString)") var responses: [String] = [] // When Alamofire.request(.GET, URLString) .preValidate { responses.append("preValidate") } .validate() .postValidate { responses.append("postValidate") } .response { _, _, _, _ in responses.append("response") expectation.fulfill() } waitForExpectationsWithTimeout(defaultTimeout, handler: nil) // Then if responses.count == 3 { XCTAssertEqual(responses[0], "preValidate", "response at index 0 should be preValidate") XCTAssertEqual(responses[1], "postValidate", "response at index 1 should be postValidate") XCTAssertEqual(responses[2], "response", "response at index 2 should be response") } else { XCTFail("responses count should be equal to 3") } } } // MARK: - class RequestDescriptionTestCase: BaseTestCase { func testRequestDescription() { // Given let URLString = "https://httpbin.org/get" let request = Alamofire.request(.GET, URLString) let initialRequestDescription = request.description let expectation = expectationWithDescription("Request description should update: \(URLString)") var finalRequestDescription: String? var response: NSHTTPURLResponse? // When request.response { _, responseResponse, _, _ in finalRequestDescription = request.description response = responseResponse expectation.fulfill() } waitForExpectationsWithTimeout(defaultTimeout, handler: nil) // Then XCTAssertEqual(initialRequestDescription, "GET https://httpbin.org/get", "incorrect request description") XCTAssertEqual( finalRequestDescription ?? "", "GET https://httpbin.org/get (\(response?.statusCode ?? -1))", "incorrect request description" ) } } // MARK: - class RequestDebugDescriptionTestCase: BaseTestCase { // MARK: Properties let manager: Manager = { let manager = Manager(configuration: NSURLSessionConfiguration.defaultSessionConfiguration()) manager.startRequestsImmediately = false return manager }() let managerDisallowingCookies: Manager = { let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() configuration.HTTPShouldSetCookies = false let manager = Manager(configuration: configuration) manager.startRequestsImmediately = false return manager }() // MARK: Tests func testGETRequestDebugDescription() { // Given let URLString = "https://httpbin.org/get" // When let request = manager.request(.GET, URLString) let components = cURLCommandComponents(request) // Then XCTAssertEqual(components[0..<3], ["$", "curl", "-i"], "components should be equal") XCTAssertFalse(components.contains("-X"), "command should not contain explicit -X flag") XCTAssertEqual(components.last ?? "", "\"\(URLString)\"", "URL component should be equal") } func testPOSTRequestDebugDescription() { // Given let URLString = "https://httpbin.org/post" // When let request = manager.request(.POST, URLString) let components = cURLCommandComponents(request) // Then XCTAssertEqual(components[0..<3], ["$", "curl", "-i"], "components should be equal") XCTAssertEqual(components[3..<5], ["-X", "POST"], "command should contain explicit -X flag") XCTAssertEqual(components.last ?? "", "\"\(URLString)\"", "URL component should be equal") } func testPOSTRequestWithJSONParametersDebugDescription() { // Given let URLString = "https://httpbin.org/post" // When let request = manager.request(.POST, URLString, parameters: ["foo": "bar"], encoding: .JSON) let components = cURLCommandComponents(request) // Then XCTAssertEqual(components[0..<3], ["$", "curl", "-i"], "components should be equal") XCTAssertEqual(components[3..<5], ["-X", "POST"], "command should contain explicit -X flag") XCTAssertTrue( request.debugDescription.rangeOfString("-H \"Content-Type: application/json\"") != nil, "command should contain 'application/json' Content-Type" ) XCTAssertTrue( request.debugDescription.rangeOfString("-d \"{\\\"foo\\\":\\\"bar\\\"}\"") != nil, "command data should contain JSON encoded parameters" ) XCTAssertEqual(components.last ?? "", "\"\(URLString)\"", "URL component should be equal") } func testPOSTRequestWithCookieDebugDescription() { // Given let URLString = "https://httpbin.org/post" let properties = [ NSHTTPCookieDomain: "httpbin.org", NSHTTPCookiePath: "/post", NSHTTPCookieName: "foo", NSHTTPCookieValue: "bar", ] let cookie = NSHTTPCookie(properties: properties)! manager.session.configuration.HTTPCookieStorage?.setCookie(cookie) // When let request = manager.request(.POST, URLString) let components = cURLCommandComponents(request) // Then XCTAssertEqual(components[0..<3], ["$", "curl", "-i"], "components should be equal") XCTAssertEqual(components[3..<5], ["-X", "POST"], "command should contain explicit -X flag") XCTAssertEqual(components.last ?? "", "\"\(URLString)\"", "URL component should be equal") XCTAssertEqual(components[5..<6], ["-b"], "command should contain -b flag") } func testPOSTRequestWithCookiesDisabledDebugDescription() { // Given let URLString = "https://httpbin.org/post" let properties = [ NSHTTPCookieDomain: "httpbin.org", NSHTTPCookiePath: "/post", NSHTTPCookieName: "foo", NSHTTPCookieValue: "bar", ] let cookie = NSHTTPCookie(properties: properties)! managerDisallowingCookies.session.configuration.HTTPCookieStorage?.setCookie(cookie) // When let request = managerDisallowingCookies.request(.POST, URLString) let components = cURLCommandComponents(request) // Then let cookieComponents = components.filter { $0 == "-b" } XCTAssertTrue(cookieComponents.isEmpty, "command should not contain -b flag") } // MARK: Test Helper Methods private func cURLCommandComponents(request: Request) -> [String] { let whitespaceCharacterSet = NSCharacterSet.whitespaceAndNewlineCharacterSet() return request.debugDescription.componentsSeparatedByCharactersInSet(whitespaceCharacterSet) .filter { $0 != "" && $0 != "\\" } } }
mit
0e1dbc20de8b86eef2bf8f9b06924e07
38.156766
126
0.633824
5.568881
false
false
false
false
LudvigOdin/ARNModalTransition
ARNModalTransition/ARNModalTransition/ModalViewController.swift
1
1827
// // ModalViewController.swift // ARNModalTransition // // Created by xxxAIRINxxx on 2015/01/17. // Copyright (c) 2015 xxxAIRINxxx. All rights reserved. // import UIKit class ModalViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { var tableView : UITableView = UITableView(frame: CGRectZero, style: .Plain) let cellIdentifier : String = "Cell" deinit { print("deinit ModalViewController") } override func viewDidLoad() { super.viewDidLoad() self.tableView.frame = self.view.bounds self.tableView.dataSource = self self.tableView.delegate = self self.tableView.registerClass(UITableViewCell.classForCoder(), forCellReuseIdentifier: self.cellIdentifier) self.view.addSubview(self.tableView) self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Close", style: .Plain, target: self, action: "tapCloseButton") self.navigationItem.rightBarButtonItem?.tintColor = UIColor.whiteColor() } func tapCloseButton() { animator.interactiveType = .None self.dismissViewControllerAnimated(true, completion: nil) } // MARK: UITableViewDataSource func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 50 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(self.cellIdentifier, forIndexPath: indexPath) return cell } // MARK: UITableViewDelegate func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) } }
mit
a19b793e9a84f2e3c7e3bda78d789c0b
32.218182
135
0.695676
5.503012
false
false
false
false
coreyjv/Emby.ApiClient.Swift
Emby.ApiClient/apiinteraction/ApiClient.swift
1
104364
// // ApiClient.swift // Emby.ApiClient // import Foundation public class ApiClient: BaseApiClient { private let apiEventListener: ApiEventListener? private let httpClient: IAsyncHttpClient private var networkConnection: INetworkConnection? //private var apiWebSocket: ApiWebSocket? private var serverInfo: ServerInfo? private var connectionMode = ConnectionMode.Local // private Observable authenticatedObservable = new AutomaticObservable(); // public Observable getAuthenticatedObservable() { // return authenticatedObservable; // } // init(httpClient: IAsyncHttpClient, jsonSerializer: IJsonSerializer, logger: ILogger, serverAddress: String, accessToken: String, apiEventListener: ApiEventListener) { self.httpClient = httpClient self.apiEventListener = apiEventListener super.init(logger: logger, jsonSerializer: jsonSerializer, serverAddress: serverAddress, accessToken: accessToken) resetHttpHeaders() } init(httpClient: IAsyncHttpClient, jsonSerializer: IJsonSerializer, logger: ILogger, serverAddress: String, appName: String, applicationVersion: String, device: DeviceProtocol, apiEventListener: ApiEventListener) { self.httpClient = httpClient self.apiEventListener = apiEventListener super.init(logger: logger, jsonSerializer: jsonSerializer, serverAddress: serverAddress, clientName: appName, device: device, applicationVersion: applicationVersion) resetHttpHeaders() } init(httpClient: IAsyncHttpClient, jsonSerializer: IJsonSerializer, logger: ILogger, serverAddress: String, appName: String, applicationVersion: String, device: DeviceProtocol) { self.httpClient = httpClient self.apiEventListener = nil super.init(logger: logger, jsonSerializer: jsonSerializer, serverAddress: serverAddress, clientName: appName, device: device, applicationVersion: applicationVersion) resetHttpHeaders() } // MARK: - Request Creation and Sending private func sendRequest<T: JSONSerializable>(var request: HttpRequest, success: (T) -> Void, failure: (EmbyError) -> Void) { request.addHeaders(httpHeaders) httpClient.sendRequest(request, success: success, failure: failure) } private func sendCollectionRequest<Value: JSONSerializable>(var request: HttpRequest, success: ([Value]) -> Void, failure: (EmbyError) -> Void) { request.addHeaders(httpHeaders) httpClient.sendCollectionRequest(request, success: success, failure: failure) } // MARK: - Public API Methods /** Authenticates a user and returns the result - Parameter username: The username - Parameter password: The password - Parameter success: Success callback with an AuthenticationResult - Parameter failure: Failure callback with an EmbyError */ public func authenticateUserAsync(username: String, password: String, success: (AuthenticationResult) -> Void, failure: (EmbyError) -> Void) { precondition(!username.isEmpty, "Illegal Argument: username") let dict = QueryStringDictionary() dict.Add("Username", value: username) dict.Add("Password", value: password.sha1()) dict.Add("PasswordMd5", value: password.md5()) let urlString = getApiUrl("Users/AuthenticateByName") let request = HttpRequest(url: urlString, method: .POST, postData: dict) sendRequest(request, success: success, failure: failure) } /** Gets a list of public users - Parameter success: Success callback with an array of UserDto - Parameter failure: Failure callback with an EmbyError */ public func getPublicUsersAsync(success: ([UserDto]) -> Void, failure: (EmbyError) -> Void) { let urlString = getApiUrl("Users/Public") let request = HttpRequest(url: urlString, method: .GET) sendCollectionRequest(request, success: success, failure: failure) } /** Retrieves an item for a user - Parameter id: The Item Id - Parameter userId: The User Id - Parameter success: Success callback with an BaseItemDto - Parameter failure: Failure callback with an EmbyError */ public func getItemAsync(id: String, userId: String, success: (BaseItemDto) -> Void, failure: (EmbyError) -> Void) { precondition(!id.isEmpty, "Illegal Argument: id") precondition(!userId.isEmpty, "Illegal Argument: userId") let url = getApiUrl("/Users/\(userId)/Items/\(id)") getItemFromUrl(url, success: success, failure: failure) } /** Retrieves an array of items for a user - Parameter query: The ItemQuery - Parameter success: Success callback with an array of BaseItemDto - Parameter failure: Failure callback with an EmbyError */ public func getItemsAsync(query: ItemQuery, success: ([BaseItemDto]) -> Void, failure: (EmbyError) -> Void) { let url = getItemListUrl(query) getItemsFromUrl(url, success: success, failure: failure) } /** Retrieves an array of item counts for a user - Parameter query: The ItemCountsQuery - Parameter success: Success callback with an ItemCounts - Parameter failure: Failure callback with an EmbyError */ public func getItemCountsAsync(query: ItemCountsQuery, success: (ItemCounts) -> Void, failure: (EmbyError) -> Void) { let dict = QueryStringDictionary() dict.addIfNotNilOrEmpty("UserId", value: query.userId) dict.addIfNotNil("IsFavorite", value: query.favorite) let urlString = getApiUrl("Items/Counts", queryString: dict) let urlWithFormat = addDataFormat(urlString) let request = HttpRequest(url: urlWithFormat, method: .GET, postData: dict) sendRequest(request, success: success, failure: failure) } /** Retrieves a list of users - Parameter query: The user query - Parameter success: Success callback with an array of UserDto - Parameter failure: Failure callback with an EmbyError */ public func getUsersAsync(query: UserQuery, success: ([UserDto]) -> Void, failure: (EmbyError) -> Void) { let dict = QueryStringDictionary() dict.addIfNotNil("IsDisabled", value: query.disabled) dict.addIfNotNil("IsHidden", value: query.hidden) let urlString = getApiUrl("Users", queryString: dict) let request = HttpRequest(url: urlString, method: .GET, postData: dict) sendCollectionRequest(request, success: success, failure: failure) } /** Retrieves root items for user - Parameter userId: The User Id - Parameter success: Success callback with an BaseItemDto - Parameter failure: Failure callback with an EmbyError */ public func getRootFolderAsync(userId: String, success: (BaseItemDto) -> Void, failure: (EmbyError) -> Void) { precondition(!userId.isEmpty, "Illegal Argument: userId") let url = getApiUrl("/Users/\(userId)/Items/Root") getItemFromUrl(url, success: success, failure: failure) } /** Retrieves the intros - Parameter userId: The User Id - Parameter success: Success callback with an BaseItemDto - Parameter failure: Failure callback with an EmbyError */ public func getIntrosAsync(itemId: String, userId: String, success: ([BaseItemDto]) -> Void, failure: (EmbyError) -> Void) { precondition(!itemId.isEmpty, "Illegal Argument: itemId") precondition(!userId.isEmpty, "Illegal Argument: userId") let url = getApiUrl("/Users/\(userId)/Items/\(itemId)/Intros") getItemsFromUrl(url, success: success, failure: failure) } /** Retrieves client sessions - Parameter query: The Session Query - Parameter success: Success callback with an SessionInfoDto - Parameter failure: Failure callback with an EmbyError */ public func getClientSessionsAsync(query: SessionQuery, success: ([SessionInfoDto]) -> Void, failure: (EmbyError) -> Void) { let dict = QueryStringDictionary() dict.Add("ControllableByUserId", value: query.controllableByUserId) let urlString = getApiUrl("Sessions", queryString: dict) let request = HttpRequest(url: urlString, method: .GET) sendCollectionRequest(request, success: success, failure: failure) } /** Retrieves registartion information - Parameter query: The feature - Parameter success: Success callback with an RegistrationInfo - Parameter failure: Failure callback with an EmbyError */ public func getRegistrationInfo(feature: String, success: (RegistrationInfo) -> Void, failure: (EmbyError) -> Void) { precondition(!feature.isEmpty, "Illegal Argument: feature") let url = getApiUrl("/Registrations/\(feature)") let urlWithFormat = addDataFormat(url) getItemFromUrl(urlWithFormat, success: success, failure: failure) } public func enableAutomaticNetworking(info: ServerInfo, initialMode: ConnectionMode, networkConnection: INetworkConnection) { self.networkConnection = networkConnection self.connectionMode = initialMode self.serverInfo = info self.setServerAddress(info.getAddress(initialMode)!) } // // public void OpenWebSocket(){ // // if (apiWebSocket == null){ // // Logger.Debug("Creating ApiWebSocket"); // apiWebSocket = new ApiWebSocket(getJsonSerializer(), Logger, apiEventListener, this); // } // // apiWebSocket.EnsureWebSocket(); // } // // void OnRemoteLoggedOut(HttpException httpError) { // // RemoteLogoutReason reason = RemoteLogoutReason.GeneralAccesError; // // if (httpError.getHeaders() != null ){ // // String errorCode = httpError.getHeaders().get("X-Application-Error-Code"); // // if (StringHelper.EqualsIgnoreCase(errorCode, "ParentalControl")) { // reason = RemoteLogoutReason.ParentalControlRestriction; // } // } // // apiEventListener.onRemoteLoggedOut(this, reason); // } // // private void SendRequest(HttpRequest request, final boolean fireGlobalEvents, final Response<String> response) // { // httpClient.Send(request, new ApiClientRequestListener(this, fireGlobalEvents, response)); // } // // private void Send(String url, String method, final Response<String> response) // { // HttpRequest request = new HttpRequest(); // request.setUrl(url); // request.setMethod(method); // request.setRequestHeaders(this.HttpHeaders); // SendRequest(request, true, response); // } // // private void Send(String url, String method, String requestContent, String requestContentType, final Response<String> response) // { // HttpRequest request = new HttpRequest(); // request.setUrl(url); // request.setMethod(method); // request.setRequestHeaders(this.HttpHeaders); // request.setRequestContent(requestContent); // request.setRequestContentType(requestContentType); // SendRequest(request, true, response); // } // // private void Send(String url, // String method, // QueryStringDictionary postData, // boolean fireGlobalEvents, // final Response<String> response) // { // HttpRequest request = new HttpRequest(); // request.setUrl(url); // request.setMethod(method); // request.setRequestHeaders(this.HttpHeaders); // request.setPostData(postData); // SendRequest(request, fireGlobalEvents, response); // } // // public void getResponseStream(String address, Response<InputStream> response){ // // getResponseStreamInternal(address, response); // } // // protected void getResponseStreamInternal(String address, Response<InputStream> response){ // // Logger.Debug("Getting response stream from " + address); // // HttpURLConnection conn = null; // // try // { // URL url = new URL(address); // // conn = (HttpURLConnection) url.openConnection(); // conn.setDoInput(true); // Allow Inputs // conn.setUseCaches(false); // Don't use a Cached Copy // conn.setRequestMethod("GET"); // conn.setRequestProperty("Connection", "Keep-Alive"); // // for (String key: this.HttpHeaders.keySet()){ // conn.setRequestProperty(key, this.HttpHeaders.get(key)); // } // // InputStream inputStream = conn.getInputStream(); // // response.onResponse(inputStream); // // } // catch (Exception ex) // { // response.onError(ex); // } // } // // // // // private func getItemFromUrl<T: JSONSerializable>(url: String, success: (T) -> Void, failure: (EmbyError) -> Void) { let urlWithFormat = addDataFormat(url) let request = HttpRequest(url: urlWithFormat, method: .GET) sendRequest(request, success: success, failure: failure) } private func getItemsFromUrl<Value: JSONSerializable>(url: String, success: ([Value]) -> Void, failure: (EmbyError) -> Void) { let urlWithFormat = addDataFormat(url) let request = HttpRequest(url: urlWithFormat, method: .GET) sendCollectionRequest(request, success: success, failure: failure) } /** Gets the next up async - Parameter query: The query - Parameter success: Success callback with an array of BaseItemDto - Parameter failure: Failure callback with an EmbyError */ public func getNextUpEpisodesAsync(query: NextUpQuery, success: ([BaseItemDto]) -> Void, failure: (EmbyError) -> Void) { let url = getNextUpUrl(query) getItemsFromUrl(url, success: success, failure: failure) } public func getUpcomingEpisodesAsync(query: UpcomingEpisodesQuery, success: ([BaseItemDto]) -> Void, failure: (EmbyError) -> Void) { let dict = QueryStringDictionary() dict.add("Fields", value: query.fields?.map({$0.rawValue})) dict.addIfNotNil("Limit", value: query.limit) dict.addIfNotNil("StartIndex", value: query.startIndex) dict.addIfNotNil("UserId", value: query.userId) dict.addIfNotNil("EnableImages", value: query.enableImages) dict.addIfNotNil("ImageTypeLimit", value: query.imageTypeLimit) dict.add("EnableImageTypes", value: query.enableImageTypes?.map({$0.rawValue})) let url = getApiUrl("Shows/Upcoming", queryString: dict) getItemsFromUrl(url, success: success, failure: failure) } /** Gets the similar movies async - Parameter query: The query - Parameter success: Success callback with an array of BaseItemDto - Parameter failure: Failure callback with an EmbyError */ public func getSimilarItems(query: SimilarItemsQuery, success: ([BaseItemDto]) -> Void, failure: (EmbyError) -> Void) { let url = getSimilarItemListUrl(query, type: "Items") getItemsFromUrl(url, success: success, failure: failure) } public func getEpisodesAsync(query: EpisodeQuery, success: ([BaseItemDto]) -> Void, failure: (EmbyError) -> Void) { let dict = QueryStringDictionary() dict.addIfNotNil("Season", value: query.seasonNumber) dict.addIfNotNilOrEmpty("UserId", value: query.userId) dict.addIfNotNilOrEmpty("SeasonId", value: query.seasonId) dict.add("Fields", value: query.fields?.map({$0.rawValue})) dict.addIfNotNilOrEmpty("AdjacentTo", value: query.adjacentTo) dict.addIfNotNil("IsMissing", value: query.isMissing) dict.addIfNotNil("IsVirtualUnaired", value: query.isVirtualUnaired) let url = getApiUrl("Shows/\(query.seriesId)/Episodes", queryString: dict) getItemsFromUrl(url, success: success, failure: failure) } public func getSeasonsAsync(query: SeasonQuery, success: ([BaseItemDto]) -> Void, failure: (EmbyError) -> Void) { let dict = QueryStringDictionary() dict.addIfNotNilOrEmpty("UserId", value: query.userId) dict.add("Fields", value: query.fields?.map({$0.rawValue})) dict.addIfNotNil("IsMissing", value: query.isMissing) dict.addIfNotNil("IsVirtualUnaired", value: query.isVirtualUnaired) dict.addIfNotNil("IsSpecialSeason", value: query.isSpecialSeason) let url = getApiUrl("Shows/\(query.seriesId)/Seasons", queryString: dict) getItemsFromUrl(url, success: success, failure: failure) } /** Gets the instant mix from album async - Parameter query: The query - Parameter success: Success callback with an array of BaseItemDto - Parameter failure: Failure callback with an EmbyError */ public func getInstantMixFromItem(query: SimilarItemsQuery, success: ([BaseItemDto]) -> Void, failure: (EmbyError) -> Void) { let url = getInstantMixUrl(query, type: "Items"); getItemsFromUrl(url, success: success, failure: failure) } /** Gets the genres async - Parameter query: The query - Parameter success: Success callback with an array of BaseItemDto - Parameter failure: Failure callback with an EmbyError */ public func getGenresAsync(query: ItemsByNameQuery, success: ([BaseItemDto]) -> Void, failure: (EmbyError) -> Void) { let url = getItemByNameListUrl(query, type: "Genres") getItemsFromUrl(url, success: success, failure: failure) } /** Gets the studios async - Parameter query: The query - Parameter success: Success callback with an array of BaseItemDto - Parameter failure: Failure callback with an EmbyError */ public func getStudiosAsync(query: ItemsByNameQuery, success: ([BaseItemDto]) -> Void, failure: (EmbyError) -> Void) { let url = getItemByNameListUrl(query, type: "Studios") getItemsFromUrl(url, success: success, failure: failure) } /** Gets the artists async - Parameter query: The query - Parameter success: Success callback with an array of BaseItemDto - Parameter failure: Failure callback with an EmbyError */ public func getArtistsAsync(query: ItemsByNameQuery, success: ([BaseItemDto]) -> Void, failure: (EmbyError) -> Void) { let url = getItemByNameListUrl(query, type: "Artists") getItemsFromUrl(url, success: success, failure: failure) } /** Gets the album artists async - Parameter query: The query - Parameter success: Success callback with an array of BaseItemDto - Parameter failure: Failure callback with an EmbyError */ public func getAlbumArtistsAsync(query: ItemsByNameQuery, success: ([BaseItemDto]) -> Void, failure: (EmbyError) -> Void) { let url = getItemByNameListUrl(query, type: "Artists/AlbumArtists") getItemsFromUrl(url, success: success, failure: failure) } /** Gets the people async - Parameter query: The query - Parameter success: Success callback with an array of BaseItemDto - Parameter failure: Failure callback with an EmbyError */ public func getPeopleAsync(query: PersonsQuery, success: ([BaseItemDto]) -> Void, failure: (EmbyError) -> Void) { var url = getItemByNameListUrl(query, type: "Persons") if let personTypes = query.personTypes { url += "&PersonTypes=\(personTypes.joinWithSeparator(","))" } getItemsFromUrl(url, success: success, failure: failure) } /** Gets a studio async - Parameter name: The studio name - Parameter userId: The User ID - Parameter success: Success callback with an array of BaseItemDto - Parameter failure: Failure callback with an EmbyError */ public func getStudioAsync(name: String, userId: String, success: (BaseItemDto) -> Void, failure: (EmbyError) -> Void) { precondition(!name.isEmpty, "Illegal Argument: name") precondition(!userId.isEmpty, "Illegal Argument: userId") let dict = QueryStringDictionary() dict.Add("userId", value: userId) let url = getApiUrl("Studios/\(getSlugName(name))", queryString: dict) getItemFromUrl(url, success: success, failure: failure) } /** Gets a genre async - Parameter name: The genre name - Parameter userId: The User ID - Parameter success: Success callback with an array of BaseItemDto - Parameter failure: Failure callback with an EmbyError */ public func getGenreAsync(name: String, userId: String, success: (BaseItemDto) -> Void, failure: (EmbyError) -> Void) { precondition(!name.isEmpty, "Illegal Argument: name") precondition(!userId.isEmpty, "Illegal Argument: userId") let dict = QueryStringDictionary() dict.Add("userId", value: userId) let url = getApiUrl("Genres/\(getSlugName(name))", queryString: dict) getItemFromUrl(url, success: success, failure: failure) } /** Gets a music genre async - Parameter name: The music genre name - Parameter userId: The User ID - Parameter success: Success callback with an array of BaseItemDto - Parameter failure: Failure callback with an EmbyError */ public func getMusicGenreAsync(name: String, userId: String, success: (BaseItemDto) -> Void, failure: (EmbyError) -> Void) { precondition(!name.isEmpty, "Illegal Argument: name") precondition(!userId.isEmpty, "Illegal Argument: userId") let dict = QueryStringDictionary() dict.Add("userId", value: userId) let url = getApiUrl("MusicGenres/\(getSlugName(name))", queryString: dict) getItemFromUrl(url, success: success, failure: failure) } /** Gets a music genre async - Parameter name: The music genre name - Parameter userId: The User ID - Parameter success: Success callback with an array of BaseItemDto - Parameter failure: Failure callback with an EmbyError */ public func getMusicGenreAsync(name: String, success: (BaseItemDto) -> Void, failure: (EmbyError) -> Void) { precondition(!name.isEmpty, "Illegal Argument: name") let url = getApiUrl("MusicGenres/\(getSlugName(name))") getItemFromUrl(url, success: success, failure: failure) } /** Gets a game genre async - Parameter name: The game genre name - Parameter userId: The User ID - Parameter success: Success callback with an array of BaseItemDto - Parameter failure: Failure callback with an EmbyError */ public func getGameGenreAsync(name: String, userId: String, success: (BaseItemDto) -> Void, failure: (EmbyError) -> Void) { precondition(!name.isEmpty, "Illegal Argument: name") precondition(!userId.isEmpty, "Illegal Argument: userId") let dict = QueryStringDictionary() dict.Add("userId", value: userId) let url = getApiUrl("GameGenres/\(getSlugName(name))", queryString: dict) getItemFromUrl(url, success: success, failure: failure) } /** Gets an artist async - Parameter name: The artist name - Parameter userId: The User ID - Parameter success: Success callback with an array of BaseItemDto - Parameter failure: Failure callback with an EmbyError */ public func getArtistAsync(name: String, userId: String, success: (BaseItemDto) -> Void, failure: (EmbyError) -> Void) { precondition(!name.isEmpty, "Illegal Argument: name") precondition(!userId.isEmpty, "Illegal Argument: userId") let dict = QueryStringDictionary() dict.Add("userId", value: userId) let url = getApiUrl("Artists/\(getSlugName(name))", queryString: dict) getItemFromUrl(url, success: success, failure: failure) } // // /// <summary> // /// Restarts the server async. // /// </summary> // /// <returns>Task.</returns> // public void RestartServerAsync(final EmptyResponse response) // { // String url = GetApiUrl("System/Restart"); // // PostAsync(url, response); // } // /** Gets the system status async - Parameter success: Success callback with an SystemInfo - Parameter failure: Failure callback with an EmbyError */ public func getSystemInfoAsync(success: (SystemInfo) -> Void, failure: (EmbyError) -> Void) { var url = getApiUrl("System/Info") url = addDataFormat(url) let request = HttpRequest(url: url, method: .GET) sendRequest(request, success: success, failure: failure) } /** Gets public system information async - Parameter success: Success callback with an PublicSystemInfo - Parameter failure: Failure callback with an EmbyError */ public func getPublicSystemInfoAsync(success: (PublicSystemInfo) -> Void, failure: (EmbyError) -> Void) { var url = getApiUrl("System/Info/Public") url = addDataFormat(url) let request = HttpRequest(url: url, method: .GET) sendRequest(request, success: success, failure: failure) } /** Gets a list of plugins installed on the server async - Parameter success: Success callback with an SystemInfo - Parameter failure: Failure callback with an EmbyError */ public func getInstalledPluginsAsync(success: ([PluginInfo]) -> Void, failure: (EmbyError) -> Void) { var url = getApiUrl("System/Info/Public") url = addDataFormat(url) let request = HttpRequest(url: url, method: .GET) sendCollectionRequest(request, success: success, failure: failure) } /** Gets the current server configuration async - Parameter success: Success callback with an ServerConfigureation - Parameter failure: Failure callback with an EmbyError */ public func getServerConfigurationAsync(success: (ServerConfiguration) -> Void, failure: (EmbyError) -> Void) { var url = getApiUrl("System/Configuration") url = addDataFormat(url) let request = HttpRequest(url: url, method: .GET) sendRequest(request, success: success, failure: failure) } // // /// <summary> // /// Gets the scheduled tasks. // /// </summary> // /// <returns>Task{TaskInfo[]}.</returns> // public void GetScheduledTasksAsync(final Response<TaskInfo[]> response) // { // String url = GetApiUrl("ScheduledTasks"); // // url = AddDataFormat(url); // Send(url, "GET", new SerializedResponse<TaskInfo[]>(response, jsonSerializer, new TaskInfo[]{}.getClass())); // } // // /// <summary> // /// Gets the scheduled task async. // /// </summary> // /// <param name="id">The id.</param> // /// <returns>Task{TaskInfo}.</returns> // /// <exception cref="System.IllegalArgumentException">id</exception> // public void GetScheduledTaskAsync(String id, final Response<TaskInfo> response) // { // if (tangible.DotNetToJavaStringHelper.isNullOrEmpty(id)) // { // throw new IllegalArgumentException("id"); // } // // String url = GetApiUrl("ScheduledTasks/" + id); // // url = AddDataFormat(url); // // Send(url, "GET", new SerializedResponse<TaskInfo>(response, jsonSerializer, TaskInfo.class)); // } // // /// <summary> // /// Gets a user by id // /// </summary> // /// <param name="id">The id.</param> // /// <returns>Task{UserDto}.</returns> // /// <exception cref="System.IllegalArgumentException">id</exception> // public void GetUserAsync(String id, final Response<UserDto> response) // { // if (tangible.DotNetToJavaStringHelper.isNullOrEmpty(id)) // { // throw new IllegalArgumentException("id"); // } // // String url = GetApiUrl("Users/" + id); // // url = AddDataFormat(url); // // Send(url, "GET", new SerializedResponse<UserDto>(response, jsonSerializer, UserDto.class)); // } // // /// <summary> // /// Gets the parental ratings async. // /// </summary> // /// <returns>Task{List{ParentalRating}}.</returns> // public void GetParentalRatingsAsync(final Response<ParentalRating[]> response) // { // String url = GetApiUrl("Localization/ParentalRatings"); // // url = AddDataFormat(url); // Send(url, "GET", new SerializedResponse<ParentalRating[]>(response, jsonSerializer, new ParentalRating[]{}.getClass())); // } // // /// <summary> // /// Gets local trailers for an item // /// </summary> // /// <param name="userId">The user id.</param> // /// <param name="itemId">The item id.</param> // /// <returns>Task{ItemsResult}.</returns> // /// <exception cref="System.IllegalArgumentException">query</exception> // public void GetLocalTrailersAsync(String userId, String itemId, final Response<BaseItemDto[]> response) // { // if (tangible.DotNetToJavaStringHelper.isNullOrEmpty(userId)) // { // throw new IllegalArgumentException("userId"); // } // if (tangible.DotNetToJavaStringHelper.isNullOrEmpty(itemId)) // { // throw new IllegalArgumentException("itemId"); // } // // String url = GetApiUrl("Users/" + userId + "/Items/" + itemId + "/LocalTrailers"); // // url = AddDataFormat(url); // Send(url, "GET", new SerializedResponse<BaseItemDto[]>(response, jsonSerializer, new BaseItemDto[]{}.getClass())); // } // // /// <summary> // /// Gets special features for an item // /// </summary> // /// <param name="userId">The user id.</param> // /// <param name="itemId">The item id.</param> // /// <returns>Task{BaseItemDto[]}.</returns> // /// <exception cref="System.IllegalArgumentException">userId</exception> // public void GetSpecialFeaturesAsync(String userId, String itemId, final Response<BaseItemDto[]> response) // { // if (tangible.DotNetToJavaStringHelper.isNullOrEmpty(userId)) // { // throw new IllegalArgumentException("userId"); // } // if (tangible.DotNetToJavaStringHelper.isNullOrEmpty(itemId)) // { // throw new IllegalArgumentException("itemId"); // } // // String url = GetApiUrl("Users/" + userId + "/Items/" + itemId + "/SpecialFeatures"); // // url = AddDataFormat(url); // // Send(url, "GET", new SerializedResponse<BaseItemDto[]>(response, jsonSerializer, new BaseItemDto[]{}.getClass())); // } // // /// <summary> // /// Gets the cultures async. // /// </summary> // /// <returns>Task{CultureDto[]}.</returns> // public void GetCulturesAsync(final Response<CultureDto[]> response) // { // String url = GetApiUrl("Localization/Cultures"); // // url = AddDataFormat(url); // Send(url, "GET", new SerializedResponse<CultureDto[]>(response, jsonSerializer, new CultureDto[]{}.getClass())); // } // // /// <summary> // /// Gets the countries async. // /// </summary> // /// <returns>Task{CountryInfo[]}.</returns> // public void GetCountriesAsync(final Response<CountryInfo[]> response) // { // String url = GetApiUrl("Localization/Countries"); // // url = AddDataFormat(url); // Send(url, "GET", new SerializedResponse<CountryInfo[]>(response, jsonSerializer, new CountryInfo[]{}.getClass())); // } // // /// <summary> // /// Gets the game system summaries async. // /// </summary> // /// <returns>Task{List{GameSystemSummary}}.</returns> // public void GetGameSystemSummariesAsync(final Response<GameSystemSummary[]> response) // { // String url = GetApiUrl("Games/SystemSummaries"); // // url = AddDataFormat(url); // Send(url, "GET", new SerializedResponse<GameSystemSummary[]>(response, jsonSerializer, new GameSystemSummary[]{}.getClass())); // } // // public void MarkPlayedAsync(String itemId, String userId, Date datePlayed, final Response<UserItemDataDto> response) // { // if (tangible.DotNetToJavaStringHelper.isNullOrEmpty(itemId)) { // throw new IllegalArgumentException("itemId"); // } // if (tangible.DotNetToJavaStringHelper.isNullOrEmpty(userId)) { // throw new IllegalArgumentException("userId"); // } // // QueryStringDictionary dict = new QueryStringDictionary(); // // if (datePlayed != null) // { // SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss"); // dict.Add("DatePlayed", formatter.format(datePlayed)); // } // // String url = GetApiUrl("Users/" + userId + "/PlayedItems/" + itemId, dict); // url = AddDataFormat(url); // // Send(url, "POST", dict, true, new SerializedResponse<UserItemDataDto>(response, jsonSerializer, UserItemDataDto.class)); // } // // /// <summary> // /// Marks the unplayed async. // /// </summary> // /// <param name="itemId">The item id.</param> // /// <param name="userId">The user id.</param> // /// <returns>Task{UserItemDataDto}.</returns> // /// <exception cref="System.IllegalArgumentException"> // /// itemId // /// or // /// userId // /// </exception> // public void MarkUnplayedAsync(String itemId, String userId, final Response<UserItemDataDto> response) // { // if (tangible.DotNetToJavaStringHelper.isNullOrEmpty(itemId)) { // throw new IllegalArgumentException("itemId"); // } // if (tangible.DotNetToJavaStringHelper.isNullOrEmpty(userId)) { // throw new IllegalArgumentException("userId"); // } // // String url = GetApiUrl("Users/" + userId + "/PlayedItems/" + itemId); // url = AddDataFormat(url); // // Send(url, "DELETE", new SerializedResponse<UserItemDataDto>(response, jsonSerializer, new UserItemDataDto().getClass())); // } // // /// <summary> // /// Updates the favorite status async. // /// </summary> // /// <param name="itemId">The item id.</param> // /// <param name="userId">The user id.</param> // /// <param name="isFavorite">if set to <c>true</c> [is favorite].</param> // /// <returns>Task.</returns> // /// <exception cref="System.IllegalArgumentException">itemId</exception> // public void UpdateFavoriteStatusAsync(String itemId, String userId, Boolean isFavorite, final Response<UserItemDataDto> response) // { // if (tangible.DotNetToJavaStringHelper.isNullOrEmpty(itemId)) { // throw new IllegalArgumentException("itemId"); // } // if (tangible.DotNetToJavaStringHelper.isNullOrEmpty(userId)) { // throw new IllegalArgumentException("userId"); // } // // String url = GetApiUrl("Users/" + userId + "/FavoriteItems/" + itemId); // url = AddDataFormat(url); // // Send(url, isFavorite ? "POST" : "DELETE", new SerializedResponse<UserItemDataDto>(response, jsonSerializer, new UserItemDataDto().getClass())); // } // // /// <summary> // /// Reports to the server that the user has begun playing an item // /// </summary> // /// <param name="info">The information.</param> // /// <returns>Task{UserItemDataDto}.</returns> // /// <exception cref="System.IllegalArgumentException">itemId</exception> // public void ReportPlaybackStartAsync(PlaybackStartInfo info, final EmptyResponse response) // { // if (info == null) // { // throw new IllegalArgumentException("info"); // } // // Logger.Debug("ReportPlaybackStart: Item %s", info.getItem()); // // String url = GetApiUrl("Sessions/Playing"); // // PostAsync(url, info, response); // } // // /// <summary> // /// Reports playback progress to the server // /// </summary> // /// <param name="info">The information.</param> // /// <returns>Task{UserItemDataDto}.</returns> // /// <exception cref="System.IllegalArgumentException">itemId</exception> // public void ReportPlaybackProgressAsync(PlaybackProgressInfo info, final EmptyResponse response) // { // if (info == null) // { // throw new IllegalArgumentException("info"); // } // // if (apiWebSocket != null && apiWebSocket.IsWebSocketOpen()){ // //apiWebSocket.SendWebSocketMessage("ReportPlaybackProgress", info, response); // //return; // } // // String url = GetApiUrl("Sessions/Playing/Progress"); // PostAsync(url, info, response); // } // // /// <summary> // /// Reports to the server that the user has stopped playing an item // /// </summary> // /// <param name="info">The information.</param> // /// <returns>Task{UserItemDataDto}.</returns> // /// <exception cref="System.IllegalArgumentException">itemId</exception> // public void ReportPlaybackStoppedAsync(PlaybackStopInfo info, final EmptyResponse response) // { // if (info == null) // { // throw new IllegalArgumentException("info"); // } // // String url = GetApiUrl("Sessions/Playing/Stopped"); // // PostAsync(url, info, response); // } // // /// <summary> // /// Instructs another client to browse to a library item. // /// </summary> // /// <param name="sessionId">The session id.</param> // /// <param name="itemId">The id of the item to browse to.</param> // /// <param name="itemName">The name of the item to browse to.</param> // /// <param name="itemType">The type of the item to browse to.</param> // /// <returns>Task.</returns> // /// <exception cref="System.IllegalArgumentException">sessionId // /// or // /// itemId // /// or // /// itemName // /// or // /// itemType</exception> // public void SendBrowseCommandAsync(String sessionId, String itemId, String itemName, String itemType, final EmptyResponse response) // { // GeneralCommand cmd = new GeneralCommand(); // // cmd.setName("DisplayContent"); // // cmd.getArguments().put("ItemType", itemType); // cmd.getArguments().put("ItemId", itemId); // cmd.getArguments().put("ItemName", itemName); // // SendCommandAsync(sessionId, cmd, response); // } // // /// <summary> // /// Sends the play command async. // /// </summary> // /// <param name="sessionId">The session id.</param> // /// <param name="request">The request.</param> // /// <returns>Task.</returns> // /// <exception cref="System.IllegalArgumentException">sessionId // /// or // /// request</exception> // public void SendPlayCommandAsync(String sessionId, PlayRequest request, final EmptyResponse response) // { // if (tangible.DotNetToJavaStringHelper.isNullOrEmpty(sessionId)) // { // throw new IllegalArgumentException("sessionId"); // } // if (request == null) // { // throw new IllegalArgumentException("request"); // } // // QueryStringDictionary dict = new QueryStringDictionary(); // dict.Add("ItemIds", request.getItemIds()); // dict.AddIfNotNull("StartPositionTicks", request.getStartPositionTicks()); // dict.Add("PlayCommand", request.getPlayCommand()); // // String url = GetApiUrl("Sessions/" + sessionId + "/Playing", dict); // // PostAsync(url, response); // } // // public void SendMessageCommandAsync(String sessionId, MessageCommand command, final EmptyResponse response) // { // GeneralCommand cmd = new GeneralCommand(); // // cmd.setName("DisplayMessage"); // // cmd.getArguments().put("Header", command.getHeader()); // cmd.getArguments().put("Text", command.getText()); // // if (command.getTimeoutMs() != null) // { // cmd.getArguments().put("Timeout", StringHelper.ToStringCultureInvariant(command.getTimeoutMs())); // } // // SendCommandAsync(sessionId, cmd, response); // } // // /// <summary> // /// Sends the system command async. // /// </summary> // /// <param name="sessionId">The session id.</param> // /// <param name="command">The command.</param> // /// <returns>Task.</returns> // /// <exception cref="System.IllegalArgumentException">sessionId</exception> // public void SendCommandAsync(String sessionId, GeneralCommand command, final EmptyResponse response) // { // if (tangible.DotNetToJavaStringHelper.isNullOrEmpty(sessionId)) // { // throw new IllegalArgumentException("sessionId"); // } // // String url = GetApiUrl("Sessions/" + sessionId + "/Command"); // // PostAsync(url, command, response); // } // // private void DeleteAsync(String url, final EmptyResponse response) // { // if (tangible.DotNetToJavaStringHelper.isNullOrEmpty(url)) // { // throw new IllegalArgumentException("url"); // } // // Response<String> stringResponse = new Response<String>(response); // // Send(url, "DELETE", stringResponse); // } // // private void PostAsync(String url, final EmptyResponse response) // { // if (tangible.DotNetToJavaStringHelper.isNullOrEmpty(url)) // { // throw new IllegalArgumentException("url"); // } // // PostAsync(url, new QueryStringDictionary(), response); // } // // private void PostAsync(String url, // QueryStringDictionary postBody, // boolean fireGlobalEvents, // final Response<String> response) // { // if (tangible.DotNetToJavaStringHelper.isNullOrEmpty(url)) // { // throw new IllegalArgumentException("url"); // } // // Send(url, "POST", postBody, fireGlobalEvents, response); // } // // private void PostAsync(String url, Object obj, final EmptyResponse response) // { // if (tangible.DotNetToJavaStringHelper.isNullOrEmpty(url)) // { // throw new IllegalArgumentException("url"); // } // // Response<String> jsonResponse = new Response<String>(response); // // String json = getJsonSerializer().SerializeToString(obj); // // Send(url, "POST", json, "application/json", jsonResponse); // } // // /// <summary> // /// Sends the playstate command async. // /// </summary> // /// <param name="sessionId">The session id.</param> // /// <param name="request">The request.</param> // /// <returns>Task.</returns> // public void SendPlaystateCommandAsync(String sessionId, PlaystateRequest request, final EmptyResponse response) // { // QueryStringDictionary dict = new QueryStringDictionary(); // dict.AddIfNotNull("SeekPositionTicks", request.getSeekPositionTicks()); // // String url = GetApiUrl("Sessions/" + sessionId + "/Playing/" + request.getCommand(), dict); // // PostAsync(url, response); // } // // /// <summary> // /// Clears a user's rating for an item // /// </summary> // /// <param name="itemId">The item id.</param> // /// <param name="userId">The user id.</param> // /// <returns>Task{UserItemDataDto}.</returns> // /// <exception cref="System.IllegalArgumentException">itemId</exception> // public void ClearUserItemRatingAsync(String itemId, String userId, final Response<UserItemDataDto> response) // { // if (tangible.DotNetToJavaStringHelper.isNullOrEmpty(itemId)) // { // throw new IllegalArgumentException("itemId"); // } // // if (tangible.DotNetToJavaStringHelper.isNullOrEmpty(userId)) // { // throw new IllegalArgumentException("userId"); // } // // String url = GetApiUrl("Users/" + userId + "/Items/" + itemId + "/Rating"); // url = AddDataFormat(url); // Send(url, "DELETE", new SerializedResponse<UserItemDataDto>(response, jsonSerializer, new UserItemDataDto().getClass())); // } // // /// <summary> // /// Updates a user's rating for an item, based on likes or dislikes // /// </summary> // /// <param name="itemId">The item id.</param> // /// <param name="userId">The user id.</param> // /// <param name="likes">if set to <c>true</c> [likes].</param> // /// <returns>Task.</returns> // /// <exception cref="System.IllegalArgumentException">itemId</exception> // public void UpdateUserItemRatingAsync(String itemId, String userId, Boolean likes, final Response<UserItemDataDto> response) // { // if (tangible.DotNetToJavaStringHelper.isNullOrEmpty(itemId)) // { // throw new IllegalArgumentException("itemId"); // } // // if (tangible.DotNetToJavaStringHelper.isNullOrEmpty(userId)) // { // throw new IllegalArgumentException("userId"); // } // // QueryStringDictionary dict = new QueryStringDictionary (); // // dict.Add("likes", likes); // // String url = GetApiUrl("Users/" + userId + "/Items/" + itemId + "/Rating", dict); // url = AddDataFormat(url); // Send(url, "POST", new SerializedResponse<UserItemDataDto>(response, jsonSerializer, new UserItemDataDto().getClass())); // } // // /// <summary> // /// Authenticates a user and returns the result // /// </summary> // /// <param name="username">The username.</param> // /// <param name="sha1Hash">The sha1 hash.</param> // /// <returns>Task.</returns> // /// <exception cref="System.IllegalArgumentException">userId</exception> // public void AuthenticateUserAsync(String username, String password, final Response<AuthenticationResult> response) // throws NoSuchAlgorithmException, UnsupportedEncodingException // { // if (tangible.DotNetToJavaStringHelper.isNullOrEmpty(username)) // { // throw new IllegalArgumentException("username"); // } // // String url = GetApiUrl("Users/AuthenticateByName"); // // QueryStringDictionary dict = new QueryStringDictionary (); // // dict.Add("username", username); // dict.Add("password", Sha1.getHash(password)); // dict.Add("passwordMd5", Md5.getHash(ConnectPassword.PerformPreHashFilter(password))); // // url = AddDataFormat(url); // Response<String> jsonResponse = new Response<String>(response){ // // @Override // public void onResponse(String jsonResponse) { // // AuthenticationResult obj = DeserializeFromString(jsonResponse, AuthenticationResult.class); // // SetAuthenticationInfo(obj.getAccessToken(), obj.getUser().getId()); // // getAuthenticatedObservable().notifyObservers(obj); // // response.onResponse(obj); // } // }; // // PostAsync(url, dict, false, jsonResponse); // } // // /// <summary> // /// Updates the server configuration async. // /// </summary> // /// <param name="configuration">The configuration.</param> // /// <returns>Task.</returns> // /// <exception cref="System.IllegalArgumentException">configuration</exception> // public void UpdateServerConfigurationAsync(ServerConfiguration configuration, final EmptyResponse response) // { // if (configuration == null) // { // throw new IllegalArgumentException("configuration"); // } // // String url = GetApiUrl("System/Configuration"); // // PostAsync(url, configuration, response); // } // // /// <summary> // /// Updates the scheduled task triggers. // /// </summary> // /// <param name="id">The id.</param> // /// <param name="triggers">The triggers.</param> // /// <returns>Task{RequestResult}.</returns> // /// <exception cref="System.IllegalArgumentException">id</exception> // public void UpdateScheduledTaskTriggersAsync(String id, TaskTriggerInfo[] triggers, final EmptyResponse response) // { // if (tangible.DotNetToJavaStringHelper.isNullOrEmpty(id)) // { // throw new IllegalArgumentException("id"); // } // // if (triggers == null) // { // throw new IllegalArgumentException("triggers"); // } // // String url = GetApiUrl("ScheduledTasks/" + id + "/Triggers"); // // PostAsync(url, triggers, response); // } // // /// <summary> // /// Gets the display preferences. // /// </summary> // /// <param name="id">The id.</param> // /// <param name="userId">The user id.</param> // /// <param name="client">The client.</param> // /// <returns>Task{BaseItemDto}.</returns> // public void GetDisplayPreferencesAsync(String id, String userId, String client, final Response<DisplayPreferences> response) // { // QueryStringDictionary dict = new QueryStringDictionary(); // // dict.Add("userId", userId); // dict.Add("client", client); // // String url = GetApiUrl("DisplayPreferences/" + id, dict); // // url = AddDataFormat(url); // // Send(url, "GET", new SerializedResponse<DisplayPreferences>(response, jsonSerializer, DisplayPreferences.class)); // } // // /// <summary> // /// Updates display preferences for a user // /// </summary> // /// <param name="displayPreferences">The display preferences.</param> // /// <returns>Task{DisplayPreferences}.</returns> // /// <exception cref="System.IllegalArgumentException">userId</exception> // public void UpdateDisplayPreferencesAsync(DisplayPreferences displayPreferences, String userId, String client, final EmptyResponse response) // { // if (displayPreferences == null) // { // throw new IllegalArgumentException("displayPreferences"); // } // // QueryStringDictionary dict = new QueryStringDictionary(); // // dict.Add("userId", userId); // dict.Add("client", client); // // String url = GetApiUrl("DisplayPreferences/" + displayPreferences.getId(), dict); // // PostAsync(url, displayPreferences, response); // } // // public void GetNotificationsSummary(String userId, final Response<NotificationsSummary> response) // { // String url = GetApiUrl("Notifications/" + userId + "/Summary"); // // url = AddDataFormat(url); // Send(url, "GET", new SerializedResponse<NotificationsSummary>(response, jsonSerializer, NotificationsSummary.class)); // } // // public void MarkNotificationsRead(String userId, String[] notificationIdList, Boolean isRead, final EmptyResponse response) // { // String url = "Notifications/" + userId; // // url += isRead ? "/Read" : "/Unread"; // // QueryStringDictionary dict = new QueryStringDictionary(); // // dict.Add("Ids", notificationIdList); // // url = GetApiUrl(url, dict); // // PostAsync(url, response); // } // // public void GetNotificationsAsync(NotificationQuery query, final Response<NotificationResult> response) // { // String url = "Notifications/" + query.getUserId(); // // QueryStringDictionary dict = new QueryStringDictionary(); // dict.AddIfNotNull("ItemIds", query.getIsRead()); // dict.AddIfNotNull("StartIndex", query.getStartIndex()); // dict.AddIfNotNull("Limit", query.getLimit()); // // url = GetApiUrl(url, dict); // // url = AddDataFormat(url); // // Send(url, "GET", new SerializedResponse<NotificationResult>(response, jsonSerializer, NotificationResult.class)); // } // // public void GetAllThemeMediaAsync(String userId, String itemId, Boolean inheritFromParent, final Response<AllThemeMediaResult> response) // { // QueryStringDictionary queryString = new QueryStringDictionary(); // // queryString.Add("InheritFromParent", inheritFromParent); // queryString.AddIfNotNullOrEmpty("UserId", userId); // // String url = GetApiUrl("Items/" + itemId + "/ThemeMedia", queryString); // // url = AddDataFormat(url); // // Send(url, "GET", new SerializedResponse<AllThemeMediaResult>(response, jsonSerializer, AllThemeMediaResult.class)); // } // // public void GetSearchHintsAsync(SearchQuery query, final Response<SearchHintResult> response) // { // if (query == null || tangible.DotNetToJavaStringHelper.isNullOrEmpty(query.getSearchTerm())) // { // throw new IllegalArgumentException("query"); // } // // QueryStringDictionary queryString = new QueryStringDictionary(); // // queryString.AddIfNotNullOrEmpty("SearchTerm", query.getSearchTerm()); // queryString.AddIfNotNullOrEmpty("UserId", query.getUserId()); // queryString.AddIfNotNull("StartIndex", query.getStartIndex()); // queryString.AddIfNotNull("Limit", query.getLimit()); // // queryString.Add("IncludeArtists", query.getIncludeArtists()); // queryString.Add("IncludeGenres", query.getIncludeGenres()); // queryString.Add("IncludeMedia", query.getIncludeMedia()); // queryString.Add("IncludePeople", query.getIncludePeople()); // queryString.Add("IncludeStudios", query.getIncludeStudios()); // queryString.Add("IncludeItemTypes", query.getIncludeItemTypes()); // // String url = GetApiUrl("Search/Hints", queryString); // // url = AddDataFormat(url); // // Send(url, "GET", new SerializedResponse<SearchHintResult>(response, jsonSerializer, SearchHintResult.class)); // } // // public void GetThemeSongsAsync(String userId, String itemId, Boolean inheritFromParent, final Response<ThemeMediaResult> response) // { // QueryStringDictionary queryString = new QueryStringDictionary(); // // queryString.Add("InheritFromParent", inheritFromParent); // queryString.AddIfNotNullOrEmpty("UserId", userId); // // String url = GetApiUrl("Items/" + itemId + "/ThemeSongs", queryString); // // url = AddDataFormat(url); // // Send(url, "GET", new SerializedResponse<ThemeMediaResult>(response, jsonSerializer, ThemeMediaResult.class)); // } // // public void GetThemeVideosAsync(String userId, String itemId, Boolean inheritFromParent, final Response<ThemeMediaResult> response) // { // QueryStringDictionary queryString = new QueryStringDictionary(); // // queryString.Add("InheritFromParent", inheritFromParent); // queryString.AddIfNotNullOrEmpty("UserId", userId); // // String url = GetApiUrl("Items/" + itemId + "/ThemeVideos", queryString); // // url = AddDataFormat(url); // // Send(url, "GET", new SerializedResponse<ThemeMediaResult>(response, jsonSerializer, ThemeMediaResult.class)); // } // // /// <summary> // /// Gets the critic reviews. // /// </summary> // /// <param name="itemId">The item id.</param> // /// <param name="startIndex">The start index.</param> // /// <param name="limit">The limit.</param> // /// <returns>Task{ItemReviewsResult}.</returns> // /// <exception cref="System.IllegalArgumentException"> // /// id // /// or // /// userId // /// </exception> // public void GetCriticReviews(String itemId, Integer startIndex, Integer limit, final Response<ItemReviewsResult> response) // { // if (tangible.DotNetToJavaStringHelper.isNullOrEmpty(itemId)) // { // throw new IllegalArgumentException("itemId"); // } // // QueryStringDictionary queryString = new QueryStringDictionary(); // // queryString.AddIfNotNull("startIndex", startIndex); // queryString.AddIfNotNull("limit", limit); // // String url = GetApiUrl("Items/" + itemId + "/CriticReviews", queryString); // // url = AddDataFormat(url); // // Send(url, "GET", new SerializedResponse<ItemReviewsResult>(response, jsonSerializer, ItemReviewsResult.class)); // } // // /// <summary> // /// Gets the index of the game player. // /// </summary> // /// <param name="userId">The user id.</param> // /// <param name="cancellationToken">The cancellation token.</param> // /// <returns>Task{List{ItemIndex}}.</returns> // public void GetGamePlayerIndex(String userId, final Response<ItemIndex[]> response) // { // QueryStringDictionary queryString = new QueryStringDictionary(); // // queryString.AddIfNotNullOrEmpty("UserId", userId); // // String url = GetApiUrl("Games/PlayerIndex", queryString); // // url = AddDataFormat(url); // Send(url, "GET", new SerializedResponse<ItemIndex[]>(response, jsonSerializer, new ItemIndex[]{}.getClass())); // } // // /// <summary> // /// Gets the index of the year. // /// </summary> // /// <param name="userId">The user id.</param> // /// <param name="includeItemTypes">The include item types.</param> // /// <param name="cancellationToken">The cancellation token.</param> // /// <returns>Task{List{ItemIndex}}.</returns> // public void GetYearIndex(String userId, String[] includeItemTypes, final Response<ItemIndex[]> response) // { // QueryStringDictionary queryString = new QueryStringDictionary(); // // queryString.AddIfNotNullOrEmpty("UserId", userId); // queryString.AddIfNotNull("IncludeItemTypes", includeItemTypes); // // String url = GetApiUrl("Items/YearIndex", queryString); // // url = AddDataFormat(url); // Send(url, "GET", new SerializedResponse<ItemIndex[]>(response, jsonSerializer, new ItemIndex[]{}.getClass())); // } // // public void ReportCapabilities(ClientCapabilities capabilities, final EmptyResponse response) // { // if (capabilities == null) // { // throw new IllegalArgumentException("capabilities"); // } // // String url = GetApiUrl("Sessions/Capabilities/Full"); // // PostAsync(url, capabilities, response); // } // // public void GetLiveTvInfoAsync(final Response<LiveTvInfo> response) // { // String url = GetApiUrl("LiveTv/Info"); // // url = AddDataFormat(url); // Send(url, "GET", new SerializedResponse<LiveTvInfo>(response, jsonSerializer, LiveTvInfo.class)); // } // // public void GetLiveTvRecordingGroupsAsync(RecordingGroupQuery query, final Response<ItemsResult> response) // { // if (query == null) // { // throw new IllegalArgumentException("query"); // } // // QueryStringDictionary dict = new QueryStringDictionary (); // // dict.AddIfNotNullOrEmpty("UserId", query.getUserId()); // // String url = GetApiUrl("LiveTv/Recordings/Groups", dict); // // url = AddDataFormat(url); // Send(url, "GET", new SerializedResponse<ItemsResult>(response, jsonSerializer, ItemsResult.class)); // } // // public void GetLiveTvRecordingsAsync(RecordingQuery query, final Response<ItemsResult> response) // { // if (query == null) // { // throw new IllegalArgumentException("query"); // } // // QueryStringDictionary dict = new QueryStringDictionary (); // // dict.AddIfNotNullOrEmpty("UserId", query.getUserId()); // dict.AddIfNotNullOrEmpty("ChannelId", query.getChannelId()); // dict.AddIfNotNullOrEmpty("GroupId", query.getGroupId()); // dict.AddIfNotNullOrEmpty("Id", query.getUserId()); // dict.AddIfNotNullOrEmpty("SeriesTimerId", query.getSeriesTimerId()); // dict.AddIfNotNull("IsInProgress", query.getIsInProgress()); // dict.AddIfNotNull("StartIndex", query.getStartIndex()); // dict.AddIfNotNull("Limit", query.getLimit()); // // dict.AddIfNotNull("EnableImages", query.getEnableImages()); // dict.AddIfNotNull("ImageTypeLimit", query.getImageTypeLimit()); // dict.AddIfNotNull("EnableImageTypes", query.getEnableImageTypes()); // dict.AddIfNotNull("Fields", query.getFields()); // // String url = GetApiUrl("LiveTv/Recordings", dict); // // url = AddDataFormat(url); // Send(url, "GET", new SerializedResponse<ItemsResult>(response, jsonSerializer, ItemsResult.class)); // } // // public void GetLiveTvChannelsAsync(LiveTvChannelQuery query, final Response<ChannelInfoDtoResult> response) // { // if (query == null) // { // throw new IllegalArgumentException("query"); // } // // QueryStringDictionary dict = new QueryStringDictionary (); // // dict.AddIfNotNullOrEmpty("UserId", query.getUserId()); // dict.AddIfNotNull("StartIndex", query.getStartIndex()); // dict.AddIfNotNull("Limit", query.getLimit()); // dict.AddIfNotNull("IsFavorite", query.getIsFavorite()); // dict.AddIfNotNull("IsLiked", query.getIsLiked()); // dict.AddIfNotNull("IsDisliked", query.getIsDisliked()); // dict.AddIfNotNull("EnableFavoriteSorting", query.getEnableFavoriteSorting()); // // if (query.getChannelType() != null) // { // dict.Add("ChannelType", query.getChannelType()); // } // // String url = GetApiUrl("LiveTv/Channels", dict); // // url = AddDataFormat(url); // Send(url, "GET", new SerializedResponse<ChannelInfoDtoResult>(response, jsonSerializer, ChannelInfoDtoResult.class)); // } // // public void CancelLiveTvSeriesTimerAsync(String id, final EmptyResponse response) // { // if (tangible.DotNetToJavaStringHelper.isNullOrEmpty(id)) // { // throw new IllegalArgumentException("id"); // } // // QueryStringDictionary dict = new QueryStringDictionary (); // // String url = GetApiUrl("LiveTv/SeriesTimers/" + id, dict); // // DeleteAsync(url, response); // } // // public void CancelLiveTvTimerAsync(String id, final EmptyResponse response) // { // if (tangible.DotNetToJavaStringHelper.isNullOrEmpty(id)) // { // throw new IllegalArgumentException("id"); // } // // QueryStringDictionary dict = new QueryStringDictionary (); // // String url = GetApiUrl("LiveTv/Timers/" + id, dict); // // DeleteAsync(url, response); // } // // public void GetLiveTvChannelAsync(String id, String userId, final Response<ChannelInfoDto> response) // { // if (tangible.DotNetToJavaStringHelper.isNullOrEmpty(id)) // { // throw new IllegalArgumentException("id"); // } // // QueryStringDictionary dict = new QueryStringDictionary (); // dict.AddIfNotNullOrEmpty("userId", userId); // // String url = GetApiUrl("LiveTv/Channels/" + id, dict); // // url = AddDataFormat(url); // Send(url, "GET", new SerializedResponse<ChannelInfoDto>(response, jsonSerializer, ChannelInfoDto.class)); // } // // public void GetLiveTvRecordingAsync(String id, String userId, final Response<BaseItemDto> response) // { // if (tangible.DotNetToJavaStringHelper.isNullOrEmpty(id)) // { // throw new IllegalArgumentException("id"); // } // // QueryStringDictionary dict = new QueryStringDictionary (); // dict.AddIfNotNullOrEmpty("userId", userId); // // String url = GetApiUrl("LiveTv/Recordings/" + id, dict); // // url = AddDataFormat(url); // Send(url, "GET", new SerializedResponse<BaseItemDto>(response, jsonSerializer, BaseItemDto.class)); // } // // public void GetLiveTvRecordingGroupAsync(String id, String userId, final Response<BaseItemDto> response) // { // if (tangible.DotNetToJavaStringHelper.isNullOrEmpty(id)) // { // throw new IllegalArgumentException("id"); // } // // QueryStringDictionary dict = new QueryStringDictionary (); // dict.AddIfNotNullOrEmpty("userId", userId); // // String url = GetApiUrl("LiveTv/Recordings/Groups/" + id, dict); // // url = AddDataFormat(url); // Send(url, "GET", new SerializedResponse<BaseItemDto>(response, jsonSerializer, BaseItemDto.class)); // } // // public void GetLiveTvSeriesTimerAsync(String id, final Response<SeriesTimerInfoDto> response) // { // if (tangible.DotNetToJavaStringHelper.isNullOrEmpty(id)) // { // throw new IllegalArgumentException("id"); // } // // QueryStringDictionary dict = new QueryStringDictionary (); // // String url = GetApiUrl("LiveTv/SeriesTimers/" + id, dict); // // url = AddDataFormat(url); // Send(url, "GET", new SerializedResponse<SeriesTimerInfoDto>(response, jsonSerializer, SeriesTimerInfoDto.class)); // } // // public void GetLiveTvSeriesTimersAsync(SeriesTimerQuery query, final Response<SeriesTimerInfoDtoResult> response) // { // if (query == null) // { // throw new IllegalArgumentException("query"); // } // // QueryStringDictionary dict = new QueryStringDictionary (); // // dict.AddIfNotNullOrEmpty("SortBy", query.getSortBy()); // dict.Add("SortOrder", query.getSortOrder()); // // String url = GetApiUrl("LiveTv/SeriesTimers", dict); // // url = AddDataFormat(url); // Send(url, "GET", new SerializedResponse<SeriesTimerInfoDtoResult>(response, jsonSerializer, SeriesTimerInfoDtoResult.class)); // } // // public void GetLiveTvTimerAsync(String id, final Response<TimerInfoDto> response) // { // if (tangible.DotNetToJavaStringHelper.isNullOrEmpty(id)) // { // throw new IllegalArgumentException("id"); // } // // QueryStringDictionary dict = new QueryStringDictionary (); // // String url = GetApiUrl("LiveTv/Timers/" + id, dict); // // url = AddDataFormat(url); // Send(url, "GET", new SerializedResponse<TimerInfoDto>(response, jsonSerializer, TimerInfoDto.class)); // } // // public void GetLiveTvTimersAsync(TimerQuery query, final Response<TimerInfoDtoResult> response) // { // if (query == null) // { // throw new IllegalArgumentException("query"); // } // // QueryStringDictionary dict = new QueryStringDictionary (); // // dict.AddIfNotNullOrEmpty("ChannelId", query.getChannelId()); // dict.AddIfNotNullOrEmpty("SeriesTimerId", query.getSeriesTimerId()); // // String url = GetApiUrl("LiveTv/Timers", dict); // // url = AddDataFormat(url); // Send(url, "GET", new SerializedResponse<TimerInfoDtoResult>(response, jsonSerializer, new TimerInfoDtoResult().getClass())); // } // // public void GetLiveTvProgramsAsync(ProgramQuery query, final Response<ItemsResult> response) // { // if (query == null) // { // throw new IllegalArgumentException("query"); // } // // QueryStringDictionary dict = new QueryStringDictionary (); // // String isoDateFormat = "o"; // // if (query.getMaxEndDate() != null) // { // dict.Add("MaxEndDate", getIsoString(query.getMaxEndDate())); // } // if (query.getMaxStartDate() != null) // { // dict.Add("MaxStartDate", getIsoString(query.getMaxStartDate())); // } // if (query.getMinEndDate() != null) // { // dict.Add("MinEndDate", getIsoString(query.getMinEndDate())); // } // if (query.getMinStartDate() != null) // { // dict.Add("MinStartDate", getIsoString(query.getMinStartDate())); // } // // dict.AddIfNotNull("EnableImages", query.getEnableImages()); // dict.AddIfNotNull("ImageTypeLimit", query.getImageTypeLimit()); // dict.AddIfNotNull("EnableImageTypes", query.getEnableImageTypes()); // dict.AddIfNotNull("Fields", query.getFields()); // dict.AddIfNotNull("SortBy", query.getSortBy()); // // dict.AddIfNotNullOrEmpty("UserId", query.getUserId()); // // if (query.getChannelIds() != null) // { // dict.Add("ChannelIds", tangible.DotNetToJavaStringHelper.join(",", query.getChannelIds())); // } // // // TODO: This endpoint supports POST if the query String is too long // String url = GetApiUrl("LiveTv/Programs", dict); // // url = AddDataFormat(url); // Send(url, "GET", new SerializedResponse<ItemsResult>(response, jsonSerializer, ItemsResult.class)); // } // // public void GetRecommendedLiveTvProgramsAsync(RecommendedProgramQuery query, final Response<ItemsResult> response) // { // if (query == null) // { // throw new IllegalArgumentException("query"); // } // // QueryStringDictionary dict = new QueryStringDictionary (); // // dict.AddIfNotNull("EnableImages", query.getEnableImages()); // dict.AddIfNotNull("ImageTypeLimit", query.getImageTypeLimit()); // dict.AddIfNotNull("EnableImageTypes", query.getEnableImageTypes()); // dict.AddIfNotNull("Fields", query.getFields()); // // dict.AddIfNotNullOrEmpty("UserId", query.getUserId()); // dict.AddIfNotNull("Limit", query.getLimit()); // dict.AddIfNotNull("HasAired", query.getHasAired()); // dict.AddIfNotNull("IsAiring", query.getIsAiring()); // // String url = GetApiUrl("LiveTv/Programs/Recommended", dict); // // url = AddDataFormat(url); // Send(url, "GET", new SerializedResponse<ItemsResult>(response, jsonSerializer, ItemsResult.class)); // } // // public void CreateLiveTvSeriesTimerAsync(SeriesTimerInfoDto timer, final EmptyResponse response) // { // if (timer == null) // { // throw new IllegalArgumentException("timer"); // } // // String url = GetApiUrl("LiveTv/SeriesTimers"); // // PostAsync(url, timer, response); // } // // public void CreateLiveTvTimerAsync(BaseTimerInfoDto timer, final EmptyResponse response) // { // if (timer == null) // { // throw new IllegalArgumentException("timer"); // } // // String url = GetApiUrl("LiveTv/Timers"); // // PostAsync(url, timer, response); // } // // public void GetDefaultLiveTvTimerInfo(String programId, final Response<SeriesTimerInfoDto> response) // { // if (tangible.DotNetToJavaStringHelper.isNullOrEmpty(programId)) // { // throw new IllegalArgumentException("programId"); // } // // QueryStringDictionary dict = new QueryStringDictionary (); // // dict.AddIfNotNullOrEmpty("programId", programId); // // String url = GetApiUrl("LiveTv/Timers/Defaults", dict); // // url = AddDataFormat(url); // Send(url, "GET", new SerializedResponse<SeriesTimerInfoDto>(response, jsonSerializer, SeriesTimerInfoDto.class)); // } // // public void GetDefaultLiveTvTimerInfo(final Response<SeriesTimerInfoDto> response) // { // String url = GetApiUrl("LiveTv/Timers/Defaults"); // // url = AddDataFormat(url); // Send(url, "GET", new SerializedResponse<SeriesTimerInfoDto>(response, jsonSerializer, SeriesTimerInfoDto.class)); // } // // public void GetLiveTvGuideInfo(final Response<GuideInfo> response) // { // String url = GetApiUrl("LiveTv/GuideInfo"); // // url = AddDataFormat(url); // Send(url, "GET", new SerializedResponse<GuideInfo>(response, jsonSerializer, GuideInfo.class)); // } // // public void GetLiveTvProgramAsync(String id, String userId, final Response<BaseItemDto> response) // { // if (tangible.DotNetToJavaStringHelper.isNullOrEmpty(id)) // { // throw new IllegalArgumentException("id"); // } // // QueryStringDictionary dict = new QueryStringDictionary (); // dict.AddIfNotNullOrEmpty("userId", userId); // // String url = GetApiUrl("LiveTv/Programs/" + id, dict); // // url = AddDataFormat(url); // Send(url, "GET", new SerializedResponse<BaseItemDto>(response, jsonSerializer, BaseItemDto.class)); // } // // public void UpdateLiveTvSeriesTimerAsync(SeriesTimerInfoDto timer, final EmptyResponse response) // { // if (timer == null) // { // throw new IllegalArgumentException("timer"); // } // // String url = GetApiUrl("LiveTv/SeriesTimers/" + timer.getId()); // // PostAsync(url, timer, response); // } // // public void UpdateLiveTvTimerAsync(TimerInfoDto timer, final EmptyResponse response) // { // if (timer == null) // { // throw new IllegalArgumentException("timer"); // } // // String url = GetApiUrl("LiveTv/Timers/" + timer.getId()); // // PostAsync(url, timer, response); // } // // public void SendString(String sessionId, String text, final EmptyResponse response) // { // GeneralCommand cmd = new GeneralCommand(); // // cmd.setName("SendString"); // // cmd.getArguments().put("String", text); // // SendCommandAsync(sessionId, cmd, response); // } // // public void SetAudioStreamIndex(String sessionId, int index, final EmptyResponse response) // { // GeneralCommand cmd = new GeneralCommand(); // // cmd.setName("SetAudioStreamIndex"); // // cmd.getArguments().put("Index", StringHelper.ToStringCultureInvariant(index)); // // SendCommandAsync(sessionId, cmd, response); // } // // public void SetSubtitleStreamIndex(String sessionId, Integer index, final EmptyResponse response) // { // GeneralCommand cmd = new GeneralCommand(); // // cmd.setName("SetSubtitleStreamIndex"); // // int indexValue = index == null ? -1 : index.intValue(); // // cmd.getArguments().put("Index", StringHelper.ToStringCultureInvariant(indexValue)); // // SendCommandAsync(sessionId, cmd, response); // } // // public void SetVolume(String sessionId, int volume, final EmptyResponse response) // { // GeneralCommand cmd = new GeneralCommand(); // // cmd.setName("SetVolume"); // // cmd.getArguments().put("Volume", StringHelper.ToStringCultureInvariant(volume)); // // SendCommandAsync(sessionId, cmd, response); // } // // public void GetAdditionalParts(String itemId, String userId, final Response<ItemsResult> response) // { // QueryStringDictionary queryString = new QueryStringDictionary(); // // queryString.AddIfNotNullOrEmpty("UserId", userId); // // String url = GetApiUrl("Videos/" + itemId + "/AdditionalParts", queryString); // // GetItemsFromUrl(url, response); // } // // public void GetChannelFeatures(String channelId, final Response<ChannelFeatures> response) // { // String url = GetApiUrl("Channels/" + channelId + "/Features"); // // url = AddDataFormat(url); // Send(url, "GET", new SerializedResponse<ChannelFeatures>(response, jsonSerializer, ChannelFeatures.class)); // } // // public void GetChannelItems(ChannelItemQuery query, final Response<ItemsResult> response) // { // QueryStringDictionary queryString = new QueryStringDictionary(); // // queryString.AddIfNotNullOrEmpty("UserId", query.getUserId()); // queryString.AddIfNotNull("StartIndex", query.getStartIndex()); // queryString.AddIfNotNull("Limit", query.getLimit()); // queryString.AddIfNotNullOrEmpty("FolderId", query.getFolderId()); // // queryString.AddIfNotNull("Fields", query.getFields()); // queryString.AddIfNotNull("Limit", query.getLimit()); // // queryString.AddIfNotNull("Filters", query.getFilters()); // queryString.AddIfNotNull("SortBy", query.getSortBy()); // queryString.Add("SortOrder", query.getSortOrder()); // // String url = GetApiUrl("Channels/" + query.getChannelId() + "/Items", queryString); // // GetItemsFromUrl(url, response); // } // // public void GetChannels(ChannelQuery query, final Response<ItemsResult> response) // { // QueryStringDictionary queryString = new QueryStringDictionary(); // // queryString.AddIfNotNullOrEmpty("UserId", query.getUserId()); // queryString.AddIfNotNull("SupportsLatestItems", query.getSupportsLatestItems()); // queryString.AddIfNotNull("StartIndex", query.getStartIndex()); // queryString.AddIfNotNull("Limit", query.getLimit()); // queryString.AddIfNotNull("IsFavorite", query.getIsFavorite()); // // String url = GetApiUrl("Channels", queryString); // // GetItemsFromUrl(url, response); // } // // public void GetCurrentSessionAsync(final Response<SessionInfoDto> response) // { // QueryStringDictionary queryString = new QueryStringDictionary(); // // queryString.Add("DeviceId", getDeviceId()); // String url = GetApiUrl("Sessions", queryString); // // url = AddDataFormat(url); // Send(url, "GET", new SerializedResponse<SessionInfoDto>(response, jsonSerializer, SessionInfoDto.class)); // } // // public void StopTranscodingProcesses(String deviceId, String playSessionId, final EmptyResponse response) // { // QueryStringDictionary queryString = new QueryStringDictionary(); // // queryString.Add("DeviceId", getDeviceId()); // queryString.AddIfNotNullOrEmpty("PlaySessionId", playSessionId); // String url = GetApiUrl("Videos/ActiveEncodings", queryString); // // DeleteAsync(url, response); // } // // public void GetLatestChannelItems(AllChannelMediaQuery query, final Response<ItemsResult> response) // { // throw new UnsupportedOperationException(); // } // // public void DeleteItem(String id, final EmptyResponse response) // { // String url = GetApiUrl("Items/" + id); // // DeleteAsync(url, response); // } // // public void Logout(final EmptyResponse response) // { // String url = GetApiUrl("Sessions/Logout"); // // PostAsync(url, new EmptyResponse() { // // @Override // public void onResponse() { // // ClearAuthenticationInfo(); // response.onResponse(); // } // // @Override // public void onError(Exception ex) { // // Logger.ErrorException("Error logging out", ex); // ClearAuthenticationInfo(); // response.onResponse(); // } // }); // // if (apiWebSocket != null && apiWebSocket.IsWebSocketOpenOrConnecting()){ // apiWebSocket.Close(); // apiWebSocket = null; // } // } // // public void GetUserViews(String userId, final Response<ItemsResult> response) // { // if (tangible.DotNetToJavaStringHelper.isNullOrEmpty(userId)) // { // throw new IllegalArgumentException("userId"); // } // // String url = GetApiUrl("Users/" + userId + "/Views"); // // GetItemsFromUrl(url, response); // } // // public void GetLatestItems(LatestItemsQuery query, final Response<BaseItemDto[]> response) // { // if (query == null) // { // throw new IllegalArgumentException("query"); // } // // QueryStringDictionary queryString = new QueryStringDictionary(); // queryString.AddIfNotNull("GroupItems", query.getGroupItems()); // queryString.AddIfNotNull("IncludeItemTypes", query.getIncludeItemTypes()); // queryString.AddIfNotNullOrEmpty("ParentId", query.getParentId()); // queryString.AddIfNotNull("IsPlayed", query.getIsPlayed()); // queryString.AddIfNotNull("StartIndex", query.getStartIndex()); // queryString.AddIfNotNull("Limit", query.getLimit()); // queryString.AddIfNotNull("Fields", query.getFields()); // // String url = GetApiUrl("Users/" + query.getUserId() + "/Items/Latest", queryString); // // url = AddDataFormat(url); // // Send(url, "GET", new SerializedResponse<BaseItemDto[]>(response, jsonSerializer, new BaseItemDto[]{}.getClass())); // } // // public void AddToPlaylist(String playlistId, String[] itemIds, String userId, final EmptyResponse response) // { // if (tangible.DotNetToJavaStringHelper.isNullOrEmpty(playlistId)) // { // throw new IllegalArgumentException("playlistId"); // } // // QueryStringDictionary dict = new QueryStringDictionary(); // // dict.AddIfNotNull("Ids", itemIds); // String url = GetApiUrl("Playlists/"+playlistId+"/Items", dict); // // PostAsync(url, response); // } // // public void CreatePlaylist(PlaylistCreationRequest request, final Response<PlaylistCreationResult> response) // { // QueryStringDictionary queryString = new QueryStringDictionary(); // // queryString.Add("UserId", request.getUserId()); // queryString.Add("Name", request.getName()); // // queryString.AddIfNotNullOrEmpty("MediaType", request.getMediaType()); // // queryString.AddIfNotNull("Ids", request.getItemIdList()); // // String url = GetApiUrl("Playlists/", queryString); // url = AddDataFormat(url); // // Send(url, "POST", new SerializedResponse<PlaylistCreationResult>(response, jsonSerializer, PlaylistCreationResult.class)); // } // // public void GetPlaylistItems(PlaylistItemQuery query, final Response<ItemsResult> response) // { // QueryStringDictionary queryString = new QueryStringDictionary(); // // queryString.AddIfNotNull("StartIndex", query.getStartIndex()); // // queryString.AddIfNotNull("Limit", query.getLimit()); // queryString.Add("UserId", query.getUserId()); // // queryString.AddIfNotNull("fields", query.getFields()); // // String url = GetApiUrl("Playlists/" + query.getId() + "/Items", queryString); // // GetItemsFromUrl(url, response); // } // // public void RemoveFromPlaylist(String playlistId, String[] entryIds, final EmptyResponse response) // { // QueryStringDictionary dict = new QueryStringDictionary(); // // dict.AddIfNotNull("EntryIds", entryIds); // String url = GetApiUrl("Playlists/"+playlistId+"/Items", dict); // // DeleteAsync(url, response); // } // // public void GetFilters(String userId, // String parentId, // String[] mediaTypes, // String[] itemTypes, // Response<QueryFilters> response) { // // QueryStringDictionary queryString = new QueryStringDictionary(); // queryString.AddIfNotNullOrEmpty("UserId", userId); // queryString.AddIfNotNullOrEmpty("ParentId", parentId); // queryString.AddIfNotNull("IncludeItemTypes", itemTypes); // queryString.AddIfNotNull("MediaTypes", mediaTypes); // // String url = GetApiUrl("Items/Filters", queryString); // // url = AddDataFormat(url); // // Send(url, "GET", new SerializedResponse<QueryFilters>(response, jsonSerializer, QueryFilters.class)); // } // // public void GetPlaybackInfo(PlaybackInfoRequest request, final Response<PlaybackInfoResponse> response) // { // QueryStringDictionary dict = new QueryStringDictionary(); // // dict.Add("UserId", request.getUserId()); // // String url = GetApiUrl("Items/" + request.getId() + "/PlaybackInfo", dict); // // url = AddDataFormat(url); // // Send(url, "GET", new SerializedResponse<PlaybackInfoResponse>(response, jsonSerializer, PlaybackInfoResponse.class)); // } // // public void GetPlaybackInfoWithPost(PlaybackInfoRequest request, final Response<PlaybackInfoResponse> response) // { // String url = GetApiUrl("Items/" + request.getId() + "/PlaybackInfo"); // // url = AddDataFormat(url); // // Send(url, "POST", jsonSerializer.SerializeToString(request), "application/json", new SerializedResponse<PlaybackInfoResponse>(response, jsonSerializer, PlaybackInfoResponse.class)); // } // // public void OpenLiveStream(LiveStreamRequest request, final Response<LiveStreamResponse> response) // { // String url = GetApiUrl("LiveStreams/Open"); // // url = AddDataFormat(url); // // String json = getJsonSerializer().SerializeToString(request); // Send(url, "POST", json, "application/json", new SerializedResponse<LiveStreamResponse>(response, jsonSerializer, LiveStreamResponse.class)); // } // // public void GetDevicesOptions(final Response<DevicesOptions> response) // { // String url = GetApiUrl("System/Configuration/devices"); // // url = AddDataFormat(url); // // Send(url, "GET", new SerializedResponse<DevicesOptions>(response, jsonSerializer, DevicesOptions.class)); // } // // public void GetContentUploadHistory(final Response<ContentUploadHistory> response) // { // QueryStringDictionary dict = new QueryStringDictionary(); // // dict.Add("DeviceId", getDeviceId()); // // String url = GetApiUrl("Devices/CameraUploads", dict); // // url = AddDataFormat(url); // // Send(url, "GET", new SerializedResponse<ContentUploadHistory>(response, jsonSerializer, ContentUploadHistory.class)); // } // // public void UploadFile(FileInputStream fileInputStream, // LocalFileInfo file, // IProgress<Double> progress, // CancellationToken cancellationToken) throws IOException, IllegalArgumentException { // // UploadFileInternal(fileInputStream, file, progress, cancellationToken); // } // // protected void UploadFileInternal(FileInputStream fileInputStream, // LocalFileInfo file, // IProgress<Double> progress, // CancellationToken cancellationToken) throws IOException ,IllegalArgumentException { // // if (tangible.DotNetToJavaStringHelper.isNullOrEmpty(getDeviceId())) // { // throw new IllegalArgumentException("ApiClient.deviceId cannot be null or empty"); // } // // if (tangible.DotNetToJavaStringHelper.isNullOrEmpty(file.getId())) // { // throw new IllegalArgumentException("file.getId() cannot be null or empty"); // } // // if (tangible.DotNetToJavaStringHelper.isNullOrEmpty(file.getName())) // { // throw new IllegalArgumentException("file.getName() cannot be null or empty"); // } // // QueryStringDictionary dict = new QueryStringDictionary(); // // dict.Add("DeviceId", getDeviceId()); // dict.Add("Name", file.getName()); // dict.Add("Id", file.getId()); // dict.AddIfNotNullOrEmpty("Album", file.getAlbum()); // // HttpURLConnection conn = null; // DataOutputStream dos = null; // URL url = new URL(GetApiUrl("Devices/CameraUploads", dict)); // // int maxBufferSize = 1 * 1024 * 1024; // // try { // // // Open a HTTP connection to the URL // conn = (HttpURLConnection) url.openConnection(); // conn.setDoInput(true); // Allow Inputs // conn.setDoOutput(true); // Allow Outputs // conn.setUseCaches(false); // Don't use a Cached Copy // conn.setRequestMethod("POST"); // conn.setRequestProperty("Connection", "Keep-Alive"); // conn.setRequestProperty("Content-Type", file.getMimeType()); // // for (String key: this.HttpHeaders.keySet()){ // conn.setRequestProperty(key, this.HttpHeaders.get(key)); // } // // String parameter = this.HttpHeaders.getAuthorizationParameter(); // if (!tangible.DotNetToJavaStringHelper.isNullOrEmpty(parameter)) // { // String value = this.HttpHeaders.getAuthorizationScheme() + " " + parameter; // conn.setRequestProperty("Authorization", value); // } // // dos = new DataOutputStream(conn.getOutputStream()); // // // createUserAction a buffer of maximum size // int bytesAvailable = fileInputStream.available(); // // int bufferSize = Math.min(bytesAvailable, maxBufferSize); // byte[] buffer = new byte[bufferSize]; // // // read file and write it into form... // long bytesRead = fileInputStream.read(buffer, 0, bufferSize); // // while (bytesRead > 0) { // // dos.write(buffer, 0, bufferSize); // bytesAvailable = fileInputStream.available(); // bufferSize = Math.min(bytesAvailable, maxBufferSize); // bytesRead = fileInputStream.read(buffer, 0, bufferSize); // } // // String serverResponseMessage = conn.getResponseMessage(); // // int responseCode = conn.getResponseCode(); // // if(responseCode == 200 || responseCode == 204){ // // progress.reportComplete(); // } // else{ // // HttpException ex = new HttpException(serverResponseMessage); // ex.setStatusCode(responseCode); // // progress.reportError(ex); // } // // } // catch (Exception ex) { // // Logger.ErrorException("Error uploading file", ex); // progress.reportError(new HttpException(ex.getMessage())); // } // finally { // // //close the streams // // fileInputStream.close(); // // if (dos != null){ // dos.flush(); // dos.close(); // } // } // } // // public void GetNewsItems(final Response<NewsItemsResult> response) { // // String url = GetApiUrl("News/Product"); // url = AddDataFormat(url); // // Send(url, "GET", new SerializedResponse<NewsItemsResult>(response, jsonSerializer, NewsItemsResult.class)); // } // // public void UpdateUserConfiguration(String userId, UserConfiguration configuration, EmptyResponse response) { // // response.onError(new UnsupportedOperationException()); // } // // public void CreateSyncJob(SyncJobRequest request, Response<SyncJobCreationResult> response){ // // if (request == null) // { // throw new IllegalArgumentException("request"); // } // // String url = GetApiUrl("Sync/Jobs"); // url = AddDataFormat(url); // // Send(url, "POST", jsonSerializer.SerializeToString(request), "application/json", new SerializedResponse<SyncJobCreationResult>(response, jsonSerializer, SyncJobCreationResult.class)); // } // // public void CancelSyncJob(SyncJob job, EmptyResponse response) { // // if (job == null) // { // throw new IllegalArgumentException("job"); // } // // String url = GetApiUrl("Sync/Jobs/" + job.getId()); // // DeleteAsync(url, response); // } // // public void UpdateSyncJob(SyncJob job, EmptyResponse response){ // // if (job == null) // { // throw new IllegalArgumentException("job"); // } // // String url = GetApiUrl("Sync/Jobs/" + job.getId()); // // PostAsync(url, job, response); // } // // public void GetSyncJobItemFile(String id, Response<InputStream> response){ // // getResponseStream(getSyncJobItemFileUrl(id), response); // } // // public String getSyncJobItemFileUrl(String id) // { // if (tangible.DotNetToJavaStringHelper.isNullOrEmpty(id)) // { // throw new IllegalArgumentException("id"); // } // // return GetApiUrl("Sync/JobItems/" + id + "/File"); // } // // public void GetSyncJobs(SyncJobQuery query, Response<SyncJobQueryResult> response) { // // QueryStringDictionary dict = new QueryStringDictionary(); // // dict.AddIfNotNull("Limit", query.getLimit()); // dict.AddIfNotNull("StartIndex", query.getStartIndex()); // dict.AddIfNotNull("SyncNewContent", query.getSyncNewContent()); // dict.AddIfNotNullOrEmpty("TargetId", query.getTargetId()); // // dict.AddIfNotNull("Statuses", query.getStatuses(), ","); // // String url = GetApiUrl("Sync/Jobs", dict); // url = AddDataFormat(url); // // Send(url, "GET", new SerializedResponse<SyncJobQueryResult>(response, jsonSerializer, SyncJobQueryResult.class)); // } // // public void GetSyncJobItems(SyncJobItemQuery query, Response<SyncJobItemQueryResult> response) { // // QueryStringDictionary dict = new QueryStringDictionary(); // // dict.AddIfNotNullOrEmpty("JobId", query.getJobId()); // dict.AddIfNotNull("Limit", query.getLimit()); // dict.AddIfNotNull("StartIndex", query.getStartIndex()); // dict.AddIfNotNullOrEmpty("TargetId", query.getTargetId()); // // dict.AddIfNotNull("Statuses", query.getStatuses(), ","); // // String url = GetApiUrl("Sync/JobItems", dict); // url = AddDataFormat(url); // // Send(url, "GET", new SerializedResponse<SyncJobItemQueryResult>(response, jsonSerializer, SyncJobItemQueryResult.class)); // } // // public void reportSyncJobItemTransferred(String id, EmptyResponse response) { // // if (tangible.DotNetToJavaStringHelper.isNullOrEmpty(id)) // { // throw new IllegalArgumentException("id"); // } // // String url = GetApiUrl("Sync/JobItems/" + id + "/Transferred"); // // PostAsync(url, response); // } // // public void GetOfflineUser(String id, Response<UserDto> response) { // // if (tangible.DotNetToJavaStringHelper.isNullOrEmpty(id)) // { // throw new IllegalArgumentException("id"); // } // // String url = GetApiUrl("Users/" + id + "/Offline"); // url = AddDataFormat(url); // // Send(url, "GET", new SerializedResponse<UserDto>(response, jsonSerializer, UserDto.class)); // } // // public void ReportOfflineActions(ArrayList<UserAction> actions, EmptyResponse response) { // // if (actions == null || actions.size() == 0) // { // throw new IllegalArgumentException("actions"); // } // // String url = GetApiUrl("Sync/OfflineActions"); // // PostAsync(url, actions, response); // } // // public void SyncData(SyncDataRequest request, final Response<SyncDataResponse> response) { // // if (request == null) // { // throw new IllegalArgumentException("request"); // } // // String url = GetApiUrl("Sync/Data"); // url = AddDataFormat(url); // // String json = getJsonSerializer().SerializeToString(request); // Send(url, "POST", json, "application/json", new SerializedResponse<SyncDataResponse>(response, jsonSerializer, SyncDataResponse.class)); // } // // public void getSyncJobItemAdditionalFile(String syncJobItemId, String filename, final Response<InputStream> response){ // // QueryStringDictionary dict = new QueryStringDictionary(); // // dict.AddIfNotNullOrEmpty("Name", filename); // // String url = GetApiUrl("Sync/JobItems/" + syncJobItemId + "/AdditionalFiles", dict); // // getResponseStream(url, response); // } // // public void getReadySyncItems(String targetId, final Response<ReadySyncItemsResult> response) { // // QueryStringDictionary dict = new QueryStringDictionary(); // // dict.AddIfNotNullOrEmpty("TargetId", targetId); // // String url = GetApiUrl("Sync/Items/Ready", dict); // url = AddDataFormat(url); // // Send(url, "GET", new SerializedResponse<ReadySyncItemsResult>(response, jsonSerializer, url, Logger, new ReadySyncItemsResult().getClass())); // } // // public void detectBitrate(final Response<Long> response) { // // // First try a small amount so that we don't hang up their mobile connection // detectBitrate(1000000, new Response<Long>(response) { // // @Override // public void onResponse(Long bitrate) { // // if (bitrate < 3000000) { // response.onResponse(Math.round(bitrate * .8)); // return; // } // // // If that produced a fairly high speed, try again with a larger size to get a more accurate result // detectBitrate(3000000, new Response<Long>(response) { // // @Override // public void onResponse(Long bitrate) { // // response.onResponse(Math.round(bitrate * .8)); // } // // }); // } // }); // } // // protected void detectBitrate(final long downloadBytes, final Response<Long> response) { // // detectBitrateInternal(downloadBytes, response); // } // // protected void detectBitrateInternal(final long downloadBytes, final Response<Long> response) { // // QueryStringDictionary dict = new QueryStringDictionary(); // // dict.Add("Size", downloadBytes); // // String address = GetApiUrl("Playback/BitrateTest", dict); // // HttpURLConnection conn = null; // // try // { // URL url = new URL(address); // // conn = (HttpURLConnection) url.openConnection(); // conn.setDoInput(true); // Allow Inputs // conn.setUseCaches(false); // Don't use a Cached Copy // conn.setRequestMethod("GET"); // conn.setRequestProperty("Connection", "Keep-Alive"); // // for (String key: this.HttpHeaders.keySet()){ // conn.setRequestProperty(key, this.HttpHeaders.get(key)); // } // // final long startTime = System.currentTimeMillis(); // // try (InputStream inputStream = conn.getInputStream()){ // // byte[] byteChunk = new byte[4096]; // Or whatever size you want to read in at a time. // int n; // // while ( (n = inputStream.read(byteChunk)) > 0 ) { // // } // // double time = System.currentTimeMillis() - startTime; // double bitrate = downloadBytes * 8; // bitrate /= time; // bitrate *= 1000; // // response.onResponse(Math.round(bitrate)); // } // catch (IOException ioException){ // response.onError(ioException); // return; // } // } // catch (Exception ex) // { // response.onError(ex); // } // } // // public void getSubtitles(String url, Response<SubtitleTrackInfo> response) { // // url = AddDataFormat(url); // // Send(url, "GET", new SerializedResponse<SubtitleTrackInfo>(response, jsonSerializer, url, Logger, new SubtitleTrackInfo().getClass())); // } }
mit
b8475f3abf0c19d1118e663d0397a6f1
37.78298
218
0.597447
4.195538
false
false
false
false
mcxiaoke/learning-ios
cocoa_programming_for_osx/22_DragAndDrop/Dice/Dice/DieView.swift
1
12282
// // DieView.swift // Dice // // Created by mcxiaoke on 16/5/5. // Copyright © 2016年 mcxiaoke. All rights reserved. // import Cocoa @IBDesignable class DieView: NSView, NSDraggingSource { var mouseDownEvent: NSEvent? var highlightFroDragging: Bool = false { didSet { needsDisplay = true } } var highlighted: Bool = false { didSet { needsDisplay = true } } var intValue : Int? = 5 { didSet { needsDisplay = true } } var pressed: Bool = false { didSet { needsDisplay = true } } func setup(){ self.registerForDraggedTypes([NSPasteboardTypeString]) randomize() } override init(frame frameRect: NSRect) { super.init(frame: frameRect) setup() } required init?(coder: NSCoder) { super.init(coder: coder) setup() } override var intrinsicContentSize: NSSize { return NSSize(width: 40, height: 40) } override var focusRingMaskBounds: NSRect { return bounds } override func drawFocusRingMask() { NSBezierPath.fillRect(bounds) } override var acceptsFirstResponder: Bool { return true } override func becomeFirstResponder() -> Bool { return true } override func resignFirstResponder() -> Bool { return true } override func keyDown(theEvent: NSEvent) { interpretKeyEvents([theEvent]) } override func insertTab(sender: AnyObject?) { window?.selectNextKeyView(sender) } override func insertBacktab(sender: AnyObject?) { window?.selectPreviousKeyView(sender) } override func insertText(insertString: AnyObject) { let text = insertString as! String if let number = Int(text) { intValue = number } } override func mouseEntered(theEvent: NSEvent) { highlighted = true window?.makeFirstResponder(self) } override func mouseExited(theEvent: NSEvent) { highlighted = false } override func viewDidMoveToWindow() { window?.acceptsMouseMovedEvents = true // let options: NSTrackingAreaOptions = .MouseEnteredAndExited | .ActiveAlways | .InVisibleRect // Swift 2 fix // http://stackoverflow.com/questions/36560189/no-candidates-produce-the-expected-contextual-result-type-nstextstorageedit let options: NSTrackingAreaOptions = [.MouseEnteredAndExited, .ActiveAlways, .InVisibleRect ] let trackingArea = NSTrackingArea(rect: NSRect(), options: options, owner: self, userInfo: nil) addTrackingArea(trackingArea) } func randomize() { intValue = Int(arc4random_uniform(5)+1) } override func mouseDown(theEvent: NSEvent) { mouseDownEvent = theEvent let pointInView = convertPoint(theEvent.locationInWindow, fromView: nil) // let dieFrame = metricsForSize(bounds.size).dieFrame // pressed = dieFrame.contains(pointInView) pressed = diePathWithSize(bounds.size).containsPoint(pointInView) } override func mouseDragged(theEvent: NSEvent) { // Swift.print("mouse dragged, location: \(theEvent.locationInWindow)") let downPoint = mouseDownEvent!.locationInWindow let dragPoint = theEvent.locationInWindow let distanceDragged = hypot(downPoint.x - dragPoint.x, downPoint.y - dragPoint.y) if distanceDragged < 3 { return } pressed = false if let intValue = intValue { let imageSize = bounds.size let image = NSImage(size: imageSize, flipped: false) { (imageBounds) in self.drawDieWithSize(imageBounds.size) return true } let draggingFrameOrigin = convertPoint(downPoint, fromView: nil) let draggingFrame = NSRect(origin: draggingFrameOrigin, size: imageSize) .offsetBy(dx: -imageSize.width/2, dy: -imageSize.height/2) let pbItem = NSPasteboardItem() let bitmap = self.bitmapImageRepForCachingDisplayInRect(self.bounds)! self.cacheDisplayInRect(self.bounds, toBitmapImageRep: bitmap) pbItem.setString("\(intValue)", forType: NSPasteboardTypeString) pbItem.setData(bitmap.representationUsingType(.NSPNGFileType, properties: [:]), forType: NSPasteboardTypePNG) let item = NSDraggingItem(pasteboardWriter: pbItem) item.draggingFrame = draggingFrame item.imageComponentsProvider = { let component = NSDraggingImageComponent(key: NSDraggingImageComponentIconKey) component.contents = image component.frame = NSRect(origin: NSPoint(), size: imageSize) return [component] } beginDraggingSessionWithItems([item], event: mouseDownEvent!, source: self) } } override func mouseUp(theEvent: NSEvent) { // Swift.print("mouse up click count: \(theEvent.clickCount)") if theEvent.clickCount == 2 { randomize() } pressed = false } // dragging source func draggingSession(session: NSDraggingSession, sourceOperationMaskForDraggingContext context: NSDraggingContext) -> NSDragOperation { return [.Copy, .Delete] } func draggingSession(session: NSDraggingSession, endedAtPoint screenPoint: NSPoint, operation: NSDragOperation) { if operation == .Delete { intValue = nil } } // dragging destination override func draggingEntered(sender: NSDraggingInfo) -> NSDragOperation { if sender.draggingSource() as? DieView == self { return .None } highlightFroDragging = true return sender.draggingSourceOperationMask() } override func draggingUpdated(sender: NSDraggingInfo) -> NSDragOperation { Swift.print("operation mask = \(sender.draggingSourceOperationMask().rawValue)") if sender.draggingSource() === self { return .None } return [.Copy,.Delete] } override func draggingExited(sender: NSDraggingInfo?) { highlightFroDragging = false } override func performDragOperation(sender: NSDraggingInfo) -> Bool { return readFromPasteboard(sender.draggingPasteboard()) } override func concludeDragOperation(sender: NSDraggingInfo?) { highlightFroDragging = false } override func drawRect(dirtyRect: NSRect) { let bgColor = NSColor.lightGrayColor() bgColor.set() NSBezierPath.fillRect(bounds) // NSColor.greenColor().set() // let path = NSBezierPath() // path.moveToPoint(NSPoint(x: 0, y: 0)) // path.lineToPoint(NSPoint(x: bounds.width, y: bounds.height)) // path.stroke() if highlightFroDragging { let gradient = NSGradient(startingColor: NSColor.whiteColor(), endingColor: NSColor.grayColor()) gradient?.drawInRect(bounds, relativeCenterPosition: NSZeroPoint) }else{ // if highlighted { // NSColor.redColor().set() // let rect = CGRect(x: 5, y: bounds.height - 15, width: 10, height: 10) // NSBezierPath(ovalInRect:rect).fill() // } drawDieWithSize(bounds.size) } } func metricsForSize(size:CGSize) -> (edgeLength: CGFloat, dieFrame: CGRect, drawingBounds:CGRect) { let edgeLength = min(size.width, size.height) let padding = edgeLength / 10.0 // at center let ox = (size.width - edgeLength )/2 let oy = (size.height - edgeLength)/2 let drawingBounds = CGRect(x: ox, y: oy, width: edgeLength, height: edgeLength) var dieFrame = drawingBounds.insetBy(dx: padding, dy: padding) if pressed { dieFrame = dieFrame.offsetBy(dx: 0, dy: -edgeLength/40) } return (edgeLength, dieFrame, drawingBounds) } func diePathWithSize(size:CGSize) -> NSBezierPath { let (edgeLength, dieFrame, _) = metricsForSize(size) let cornerRadius:CGFloat = edgeLength / 5.0 return NSBezierPath(roundedRect: dieFrame, xRadius: cornerRadius, yRadius: cornerRadius) } func drawDieWithSize(size:CGSize) { if let intValue = intValue { let (edgeLength, dieFrame, drawingBounds) = metricsForSize(size) let cornerRadius:CGFloat = edgeLength / 5.0 let dotRadius = edgeLength / 12.0 let dotFrame = dieFrame.insetBy(dx: dotRadius * 2.5, dy: dotRadius * 2.5) NSGraphicsContext.saveGraphicsState() let shadow = NSShadow() shadow.shadowOffset = NSSize(width: 0, height: -1) shadow.shadowBlurRadius = ( pressed ? edgeLength/100 : edgeLength / 20) shadow.set() NSColor.whiteColor().set() NSBezierPath(roundedRect: dieFrame, xRadius: cornerRadius, yRadius: cornerRadius).fill() NSGraphicsContext.restoreGraphicsState() // NSColor.redColor().set() NSColor.blackColor().set() let gradient = NSGradient(startingColor: NSColor.redColor(), endingColor: NSColor.greenColor()) // gradient?.drawInRect(drawingBounds, angle: 180.0) func drawDot(u: CGFloat, v:CGFloat) { let dotOrigin = CGPoint(x: dotFrame.minX + dotFrame.width * u, y: dotFrame.minY + dotFrame.height * v) let dotRect = CGRect(origin: dotOrigin, size: CGSizeZero).insetBy(dx: -dotRadius, dy: -dotRadius) let path = NSBezierPath(ovalInRect: dotRect) path.fill() } if (1...6).indexOf(intValue) != nil { if [1,3,5].indexOf(intValue) != nil { drawDot(0.5, v: 0.5) } if (2...6).indexOf(intValue) != nil { drawDot(0, v: 1) drawDot(1, v: 0) } if (4...6).indexOf(intValue) != nil { drawDot(1, v: 1) drawDot(0, v: 0) } if intValue == 6 { drawDot(0, v: 0.5) drawDot(1, v: 0.5) } }else{ let paraStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle paraStyle.alignment = .Center let font = NSFont.systemFontOfSize(edgeLength * 0.5) let attrs = [ NSForegroundColorAttributeName: NSColor.blackColor(), NSFontAttributeName: font, NSParagraphStyleAttributeName: paraStyle ] let string = "\(intValue)" as NSString string.drawCenteredInRect(dieFrame, withAttributes: attrs) } } } @IBAction func saveAsPDF(sender: AnyObject!) { let sp = NSSavePanel() sp.allowedFileTypes = ["pdf"] sp.beginSheetModalForWindow(window!) { [unowned sp] (result) in if result == NSModalResponseOK { // let data = self.dataWithPDFInsideRect(self.bounds) do { try data.writeToURL(sp.URL!, options: NSDataWritingOptions.DataWritingAtomic) }catch { let alert = NSAlert() alert.messageText = "Save Error" alert.informativeText = "Can not save as PDF!" alert.runModal() } } } } // pasteboard func writeToPasteboard(pasteboard: NSPasteboard) { if let value = intValue { let text = "\(value)" let image = self.bitmapImageRepForCachingDisplayInRect(self.bounds)! self.cacheDisplayInRect(self.bounds, toBitmapImageRep: image) pasteboard.clearContents() pasteboard.setString(text, forType: NSPasteboardTypeString) pasteboard.setData(image.representationUsingType(.NSPNGFileType, properties: [:]), forType: NSPasteboardTypePNG) self.writePDFInsideRect(self.bounds, toPasteboard: pasteboard) } } func readFromPasteboard(pasteboard: NSPasteboard) -> Bool { let objects = pasteboard.readObjectsForClasses([NSString.self], options: [:]) as! [String] if let str = objects.first { intValue = Int(str) return true } return false } @IBAction func cut(sender: AnyObject?) { writeToPasteboard(NSPasteboard.generalPasteboard()) intValue = nil } @IBAction func copy(sender:AnyObject?) { writeToPasteboard(NSPasteboard.generalPasteboard()) } @IBAction func paste(sender:AnyObject?) { readFromPasteboard(NSPasteboard.generalPasteboard()) } @IBAction func delete(sener: AnyObject?) { intValue = nil } override func validateMenuItem(menuItem: NSMenuItem) -> Bool { switch menuItem.action { case #selector(copy(_:)): return intValue != nil case #selector(cut(_:)): return intValue != nil case #selector(delete(_:)): return intValue != nil default: return super.validateMenuItem(menuItem) } } }
apache-2.0
77dc6bf083acc810f58ef0841ba2516a
29.243842
137
0.657953
4.445692
false
false
false
false
kzaher/RxFeedback
Sources/RxFeedback/AsyncSynchronized.swift
1
1299
// // AsyncLock.swift // RxFeedback // // Created by Krunoslav Zaher on 11/4/18. // Copyright © 2018 Krunoslav Zaher. All rights reserved. // import Foundation internal class AsyncSynchronized<State> { internal typealias Mutate = (inout State) -> Void private let lock = NSRecursiveLock() /// Using array as a `Queue`. private var queue: [Mutate] private var state: State init(_ initialState: State) { self.queue = [] self.state = initialState } internal func async(_ mutate: @escaping Mutate) { guard var executeMutation = self.enqueue(mutate) else { return } repeat { executeMutation(&state) guard let nextExecute = self.dequeue() else { return } executeMutation = nextExecute } while true } private func enqueue(_ mutate: @escaping Mutate) -> Mutate? { lock.lock(); defer { lock.unlock() } let wasEmpty = self.queue.isEmpty self.queue.append(mutate) guard wasEmpty else { return nil } return mutate } private func dequeue() -> Mutate? { lock.lock(); defer { lock.unlock() } _ = queue.removeFirst() return queue.first } }
mit
68bd1456aa41d06a6724c34c08c3496c
22.6
65
0.57396
4.506944
false
false
false
false
texuf/outandabout
outandabout/outandabout/RSBarcodes/RSUnifiedCodeGenerator.swift
1
2879
// // RSUnifiedCodeGenerator.swift // RSBarcodesSample // // Created by R0CKSTAR on 6/10/14. // Copyright (c) 2014 P.D.Q. All rights reserved. // import Foundation import UIKit import AVFoundation public class RSUnifiedCodeGenerator: RSCodeGenerator { public var useBuiltInCode128Generator = true public class var shared: RSUnifiedCodeGenerator { return UnifiedCodeGeneratorSharedInstance } // MARK: RSCodeGenerator public func generateCode(contents: String, machineReadableCodeObjectType: String) -> UIImage? { var codeGenerator:RSCodeGenerator? = nil switch machineReadableCodeObjectType { case AVMetadataObjectTypeQRCode, AVMetadataObjectTypePDF417Code, AVMetadataObjectTypeAztecCode: return RSAbstractCodeGenerator.generateCode(contents, filterName: RSAbstractCodeGenerator.filterName(machineReadableCodeObjectType)) case AVMetadataObjectTypeCode39Code: codeGenerator = RSCode39Generator() case AVMetadataObjectTypeCode39Mod43Code: codeGenerator = RSCode39Mod43Generator() case AVMetadataObjectTypeEAN8Code: codeGenerator = RSEAN8Generator() case AVMetadataObjectTypeEAN13Code: codeGenerator = RSEAN13Generator() case AVMetadataObjectTypeInterleaved2of5Code: codeGenerator = RSITFGenerator() case AVMetadataObjectTypeITF14Code: codeGenerator = RSITF14Generator() case AVMetadataObjectTypeUPCECode: codeGenerator = RSUPCEGenerator() case AVMetadataObjectTypeCode93Code: codeGenerator = RSCode93Generator() // iOS 8 included, but my implementation's performance is better :) case AVMetadataObjectTypeCode128Code: if self.useBuiltInCode128Generator { return RSAbstractCodeGenerator.generateCode(contents, filterName: RSAbstractCodeGenerator.filterName(machineReadableCodeObjectType)) } else { codeGenerator = RSCode128Generator() } case RSBarcodesTypeISBN13Code: codeGenerator = RSISBN13Generator() case RSBarcodesTypeISSN13Code: codeGenerator = RSISSN13Generator() case RSBarcodesTypeExtendedCode39Code: codeGenerator = RSExtendedCode39Generator() default: return nil } return codeGenerator!.generateCode(contents, machineReadableCodeObjectType: machineReadableCodeObjectType) } public func generateCode(machineReadableCodeObject: AVMetadataMachineReadableCodeObject) -> UIImage? { return self.generateCode(machineReadableCodeObject.stringValue, machineReadableCodeObjectType: machineReadableCodeObject.type) } } let UnifiedCodeGeneratorSharedInstance = RSUnifiedCodeGenerator()
mit
f04422d6f9ea849319d1f03097e653b6
40.128571
148
0.711358
6.528345
false
false
false
false
marinehero/Safe
Tests/chan-test.swift
2
5357
// // chan-test.swift // Safe // // Created by Josh Baker on 7/2/15. // Copyright © 2015 ONcast. All rights reserved. // import XCTest extension Tests { func testChanUnbuffered() { let count = 100 let total = IntA(0) let xtotal = makeTotal(count) let nums = Chan<Int>() dispatch { NSThread.sleepForTimeInterval(0.05) while let i = <-nums { total += i } } for var i = 0; i < count; i++ { nums <- i } XCTAssert(nums.count() == 0, "The channel count should equal Zero.") nums.close() XCTAssert(xtotal == total, "The expected total is incorrect. xtotal: \(xtotal), total: \(total)") } func testChanBuffered() { let count = 100 let total = IntA(0) let xtotal = makeTotal(count) let nums = Chan<Int>(10) let done = Chan<Bool>() dispatch { NSThread.sleepForTimeInterval(0.05) while let i = <-nums { total += i } done <- true } for var i = 0; i < count; i++ { nums <- i } nums.close() <-done XCTAssert(xtotal == total, "The expected total is incorrect. xtotal: \(xtotal), total: \(total)") } func testChanSelect() { let count = 100 let total = IntA(0) let xtotal = makeTotal(count) let nums = Chan<Int>(10) let done = Chan<Bool>() dispatch { NSThread.sleepForTimeInterval(0.05) var chanOpened = true for ; chanOpened ; { _select { _case(nums) { i in if let i = i { total += i } else { chanOpened = false } } } } done <- true } for var i = 0; i < count; i++ { nums <- i } nums.close() <-done XCTAssert(xtotal == total, "The expected total is incorrect. xtotal: \(xtotal), total: \(total)") } func testChanSelectMultiple() { let count = 100 let total = IntA(0) let total2 = IntA(0) let xtotal = makeTotal(count) let nums = Chan<Int>(10) let nums2 = Chan<Int>() let done = Chan<Bool>() dispatch { NSThread.sleepForTimeInterval(0.05) var chanOpened = true var chanOpened2 = true for ; chanOpened || chanOpened2 ; { _select { _case(nums) { i in if let i = i { total += i } else { chanOpened = false } } _case(nums2) { i in if let i = i { total2 += i } else { chanOpened2 = false } } } } done <- true } for var i = 0; i < count; i++ { nums <- i nums2 <- i } nums.close() nums2.close() <-done XCTAssert(xtotal == total, "The expected total is incorrect. xtotal: \(xtotal), total: \(total)") XCTAssert(xtotal == total2, "The expected total is incorrect. xtotal: \(xtotal), total: \(total2)") } func testChanSelectDefault() { let count = 100 let total = IntA(0) let total2 = IntA(0) let defaultUsed = BoolA(false) let xtotal = makeTotal(count) let nums = Chan<Int>(10) let nums2 = Chan<Int>() let done = Chan<Bool>() dispatch { NSThread.sleepForTimeInterval(0.05) var chanOpened = true var chanOpened2 = true for ; chanOpened || chanOpened2 ; { _select { _case(nums) { i in if let i = i { total += i } else { chanOpened = false } } _case(nums2) { i in if let i = i { total2 += i } else { chanOpened2 = false } } _default { NSThread.sleepForTimeInterval(0.05) defaultUsed.store(true) } } } done <- true } for var i = 0; i < count; i++ { nums <- i nums2 <- i } NSThread.sleepForTimeInterval(0.05) nums.close() nums2.close() <-done XCTAssert(xtotal == total, "The expected total is incorrect. xtotal: \(xtotal), total: \(total)") XCTAssert(xtotal == total2, "The expected total is incorrect. xtotal: \(xtotal), total: \(total2)") XCTAssert(defaultUsed == true, "Expecting default statment to be used.") } }
mit
da02f8673626711e84f8076e74e19b19
29.259887
107
0.409821
4.694128
false
false
false
false
xwu/swift
test/SILGen/observers.swift
1
20024
// RUN: %target-swift-emit-silgen -Xllvm -sil-full-demangle -parse-as-library -disable-objc-attr-requires-foundation-module -enable-objc-interop %s | %FileCheck %s var zero: Int = 0 func use(_: Int) {} func takeInt(_ a : Int) {} public struct DidSetWillSetTests { // CHECK-LABEL: sil [ossa] @$s9observers010DidSetWillC5TestsV{{[_0-9a-zA-Z]*}}fC public init(x : Int) { // Accesses to didset/willset variables are direct in init methods and dtors. a = x a = x // CHECK: bb0(%0 : $Int, %1 : $@thin DidSetWillSetTests.Type): // CHECK: [[SELF:%.*]] = mark_uninitialized [rootself] // CHECK: [[PB_SELF:%.*]] = project_box [[SELF]] // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB_SELF]] // CHECK: [[P1:%.*]] = struct_element_addr [[WRITE]] : $*DidSetWillSetTests, #DidSetWillSetTests.a // CHECK-NEXT: assign %0 to [[P1]] // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB_SELF]] // CHECK: [[P2:%.*]] = struct_element_addr [[WRITE]] : $*DidSetWillSetTests, #DidSetWillSetTests.a // CHECK-NEXT: assign %0 to [[P2]] } public var a: Int { // CHECK-LABEL: sil private [ossa] @$s9observers010DidSetWillC5TestsV1a{{[_0-9a-zA-Z]*}}vw willSet(newA) { // CHECK: bb0(%0 : $Int, %1 : $*DidSetWillSetTests): // CHECK-NEXT: debug_value %0 // CHECK-NEXT: debug_value %1 : $*DidSetWillSetTests, {{.*}} expr op_deref takeInt(a) // CHECK: [[READ:%.*]] = begin_access [read] [unknown] %1 // CHECK-NEXT: [[FIELDPTR:%.*]] = struct_element_addr [[READ]] : $*DidSetWillSetTests, #DidSetWillSetTests.a // CHECK-NEXT: [[A:%.*]] = load [trivial] [[FIELDPTR]] : $*Int // CHECK-NEXT: end_access [[READ]] // CHECK: [[TAKEINTFN:%.*]] = function_ref @$s9observers7takeInt{{[_0-9a-zA-Z]*}}F // CHECK-NEXT: apply [[TAKEINTFN]]([[A]]) : $@convention(thin) (Int) -> () takeInt(newA) // CHECK-NEXT: // function_ref observers.takeInt(Swift.Int) -> () // CHECK-NEXT: [[TAKEINTFN:%.*]] = function_ref @$s9observers7takeInt{{[_0-9a-zA-Z]*}}F // CHECK-NEXT: apply [[TAKEINTFN]](%0) : $@convention(thin) (Int) -> () a = zero // reassign, but don't infinite loop. // CHECK-NEXT: // function_ref observers.zero.unsafeMutableAddressor : Swift.Int // CHECK-NEXT: [[ZEROFN:%.*]] = function_ref @$s9observers4zero{{[_0-9a-zA-Z]*}}vau // CHECK-NEXT: [[ZERORAW:%.*]] = apply [[ZEROFN]]() : $@convention(thin) () -> Builtin.RawPointer // CHECK-NEXT: [[ZEROADDR:%.*]] = pointer_to_address [[ZERORAW]] : $Builtin.RawPointer to [strict] $*Int // CHECK-NEXT: [[READ:%.*]] = begin_access [read] [dynamic] [[ZEROADDR]] : $*Int // CHECK-NEXT: [[ZERO:%.*]] = load [trivial] [[READ]] // CHECK-NEXT: end_access [[READ]] : $*Int // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [unknown] %1 // CHECK-NEXT: [[AADDR:%.*]] = struct_element_addr [[WRITE]] : $*DidSetWillSetTests, #DidSetWillSetTests.a // CHECK-NEXT: assign [[ZERO]] to [[AADDR]] } // CHECK-LABEL: sil private [ossa] @$s9observers010DidSetWillC5TestsV1a{{[_0-9a-zA-Z]*}}vW didSet { // CHECK: bb0(%0 : $*DidSetWillSetTests): // CHECK-NEXT: debug_value %0 : $*DidSetWillSetTests, {{.*}} expr op_deref takeInt(a) // CHECK: [[READ:%.*]] = begin_access [read] [unknown] %0 // CHECK-NEXT: [[AADDR:%.*]] = struct_element_addr [[READ]] : $*DidSetWillSetTests, #DidSetWillSetTests.a // CHECK-NEXT: [[A:%.*]] = load [trivial] [[AADDR]] : $*Int // CHECK-NEXT: end_access [[READ]] // CHECK-NEXT: // function_ref observers.takeInt(Swift.Int) -> () // CHECK-NEXT: [[TAKEINTFN:%.*]] = function_ref @$s9observers7takeInt{{[_0-9a-zA-Z]*}}F // CHECK-NEXT: apply [[TAKEINTFN]]([[A]]) : $@convention(thin) (Int) -> () (self).a = zero // reassign, but don't infinite loop. // CHECK-NEXT: // function_ref observers.zero.unsafeMutableAddressor : Swift.Int // CHECK-NEXT: [[ZEROFN:%.*]] = function_ref @$s9observers4zero{{[_0-9a-zA-Z]*}}vau // CHECK-NEXT: [[ZERORAW:%.*]] = apply [[ZEROFN]]() : $@convention(thin) () -> Builtin.RawPointer // CHECK-NEXT: [[ZEROADDR:%.*]] = pointer_to_address [[ZERORAW]] : $Builtin.RawPointer to [strict] $*Int // CHECK-NEXT: [[READ:%.*]] = begin_access [read] [dynamic] [[ZEROADDR]] : $*Int // CHECK-NEXT: [[ZERO:%.*]] = load [trivial] [[READ]] // CHECK-NEXT: end_access [[READ]] : $*Int // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 // CHECK-NEXT: [[AADDR:%.*]] = struct_element_addr [[WRITE]] : $*DidSetWillSetTests, #DidSetWillSetTests.a // CHECK-NEXT: assign [[ZERO]] to [[AADDR]] } // This is the synthesized getter and setter for the willset/didset variable. // CHECK-LABEL: sil [transparent] [serialized] [ossa] @$s9observers010DidSetWillC5TestsV1aSivg // CHECK: bb0(%0 : $DidSetWillSetTests): // CHECK-NEXT: debug_value %0 // CHECK-NEXT: %2 = struct_extract %0 : $DidSetWillSetTests, #DidSetWillSetTests.a // CHECK-NEXT: return %2 : $Int{{.*}} // id: %3 // CHECK-LABEL: sil [ossa] @$s9observers010DidSetWillC5TestsV1aSivs : $@convention(method) (Int, @inout DidSetWillSetTests) -> () { // CHECK: bb0([[NEWVALUE:%.*]] : $Int, %1 : $*DidSetWillSetTests): // CHECK-NEXT: debug_value [[NEWVALUE]] : $Int, let, name "value", argno 1 // CHECK-NEXT: debug_value %1{{.*}} expr op_deref // CHECK-NEXT: [[MODIFY_ONE:%.*]] = begin_access [modify] [unknown] %1 : $*DidSetWillSetTests // CHECK-NEXT: // function_ref observers.DidSetWillSetTests.a.willset : Swift.Int // CHECK-NEXT: [[WILLSETFN:%.*]] = function_ref @$s9observers010DidSetWillC5TestsV1aSivw : $@convention(method) (Int, @inout DidSetWillSetTests) -> () // CHECK-NEXT: [[RESULT:%.*]] = apply [[WILLSETFN]]([[NEWVALUE]], [[MODIFY_ONE]]) : $@convention(method) (Int, @inout DidSetWillSetTests) -> () // CHECK-NEXT: end_access [[MODIFY_ONE]] : $*DidSetWillSetTests // CHECK-NEXT: [[MODIFY_TWO:%.*]] = begin_access [modify] [unknown] %1 : $*DidSetWillSetTests // CHECK-NEXT: [[ADDR:%.*]] = struct_element_addr [[MODIFY_TWO]] : $*DidSetWillSetTests, #DidSetWillSetTests.a // CHECK-NEXT: assign [[NEWVALUE]] to [[ADDR]] : $*Int // CHECK-NEXT: end_access [[MODIFY_TWO]] : $*DidSetWillSetTests // CHECK-NEXT: [[MODIFY_THREE:%.*]] = begin_access [modify] [unknown] %1 : $*DidSetWillSetTests // CHECK-NEXT: // function_ref observers.DidSetWillSetTests.a.didset : Swift.Int // CHECK-NEXT: [[DIDSETFN:%.*]] = function_ref @$s9observers010DidSetWillC5TestsV1aSivW : $@convention(method) (@inout DidSetWillSetTests) -> () // CHECK-NEXT: [[RESULT:%.*]] = apply [[DIDSETFN]]([[MODIFY_THREE]]) : $@convention(method) (@inout DidSetWillSetTests) -> () // CHECK-NEXT: end_access [[MODIFY_THREE]] : $*DidSetWillSetTests // CHECK-NEXT: [[TUPLE:%.*]] = tuple () // CHECK-NEXT: return [[TUPLE]] : $() } // CHECK-LABEL: sil hidden [ossa] @$s9observers010DidSetWillC5TestsV8testReadSiyF // CHECK: [[SELF:%.*]] = begin_access [read] [unknown] %0 : $*DidSetWillSetTests // CHECK-NEXT: [[PROP:%.*]] = struct_element_addr [[SELF]] : $*DidSetWillSetTests // CHECK-NEXT: [[LOAD:%.*]] = load [trivial] [[PROP]] : $*Int // CHECK-NEXT: end_access [[SELF]] : $*DidSetWillSetTests // CHECK-NEXT: return [[LOAD]] : $Int mutating func testRead() -> Int { return a } // CHECK-LABEL: sil hidden [ossa] @$s9observers010DidSetWillC5TestsV9testWrite5inputySi_tF // CHECK: [[SELF:%.*]] = begin_access [modify] [unknown] %1 : $*DidSetWillSetTests // CHECK-NEXT: // function_ref observers.DidSetWillSetTests.a.setter // CHECK-NEXT: [[SETTER:%.*]] = function_ref @$s9observers010DidSetWillC5TestsV1aSivs // CHECK-NEXT: apply [[SETTER]](%0, [[SELF]]) // CHECK-NEXT: end_access [[SELF]] : $*DidSetWillSetTests // CHECK-NEXT: [[RET:%.*]] = tuple () // CHECK-NEXT: return [[RET]] : $() mutating func testWrite(input: Int) { a = input } // CHECK-LABEL: sil hidden [ossa] @$s9observers010DidSetWillC5TestsV13testReadWrite5inputySi_tF // CHECK: [[SELF:%.*]] = begin_access [modify] [unknown] %1 : $*DidSetWillSetTests // CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $Int // CHECK-NEXT: [[PROP:%.*]] = struct_element_addr [[SELF]] : $*DidSetWillSetTests // CHECK-NEXT: [[LOAD:%.*]] = load [trivial] [[PROP]] : $*Int // CHECK-NEXT: store [[LOAD]] to [trivial] [[TEMP]] : $*Int // (modification goes here) // CHECK: [[RELOAD:%.*]] = load [trivial] [[TEMP]] : $*Int // CHECK-NEXT: // function_ref observers.DidSetWillSetTests.a.setter // CHECK-NEXT: [[SETTER:%.*]] = function_ref @$s9observers010DidSetWillC5TestsV1aSivs // CHECK-NEXT: apply [[SETTER]]([[RELOAD]], [[SELF]]) // CHECK-NEXT: end_access [[SELF]] : $*DidSetWillSetTests // CHECK-NEXT: dealloc_stack [[TEMP]] : $*Int // CHECK-NEXT: [[RET:%.*]] = tuple () // CHECK-NEXT: return [[RET]] : $() mutating func testReadWrite(input: Int) { a += input } } // Test global observing properties. var global_observing_property : Int = zero { // The variable is initialized with "zero". // CHECK-LABEL: sil private [global_init_once_fn] [ossa] @{{.*}}WZ : $@convention(c) () -> () { // CHECK: bb0: // CHECK-NEXT: alloc_global @$s9observers25global_observing_propertySiv // CHECK-NEXT: %1 = global_addr @$s9observers25global_observing_propertySivp : $*Int // CHECK: observers.zero.unsafeMutableAddressor // CHECK: return // global_observing_property's setter needs to call didSet. // CHECK-LABEL: sil private [ossa] @$s9observers25global_observing_property{{[_0-9a-zA-Z]*}}vW didSet { // The didSet implementation needs to call takeInt. takeInt(global_observing_property) // CHECK: function_ref observers.takeInt // CHECK-NEXT: function_ref @$s9observers7takeInt{{[_0-9a-zA-Z]*}}F // Setting the variable from within its own didSet doesn't recursively call didSet. global_observing_property = zero // CHECK: // function_ref observers.global_observing_property.unsafeMutableAddressor : Swift.Int // CHECK-NEXT: [[ADDRESSOR:%.*]] = function_ref @$s9observers25global_observing_propertySivau : $@convention(thin) () -> Builtin.RawPointer // CHECK-NEXT: [[ADDRESS:%.*]] = apply [[ADDRESSOR]]() : $@convention(thin) () -> Builtin.RawPointer // CHECK-NEXT: [[POINTER:%.*]] = pointer_to_address [[ADDRESS]] : $Builtin.RawPointer to [strict] $*Int // CHECK-NEXT: // function_ref observers.zero.unsafeMutableAddressor : Swift.Int // CHECK-NEXT: [[ZEROFN:%.*]] = function_ref @$s9observers4zero{{[_0-9a-zA-Z]*}}vau // CHECK-NEXT: [[ZERORAW:%.*]] = apply [[ZEROFN]]() : $@convention(thin) () -> Builtin.RawPointer // CHECK-NEXT: [[ZEROADDR:%.*]] = pointer_to_address [[ZERORAW]] : $Builtin.RawPointer to [strict] $*Int // CHECK-NEXT: [[READ:%.*]] = begin_access [read] [dynamic] [[ZEROADDR]] : $*Int // CHECK-NEXT: [[ZERO:%.*]] = load [trivial] [[READ]] // CHECK-NEXT: end_access [[READ]] : $*Int // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[POINTER]] : $*Int // CHECK-NEXT: assign [[ZERO]] to [[WRITE]] : $*Int // CHECK-NEXT: end_access [[WRITE]] : $*Int // CHECK-NOT: function_ref @$s9observers25global_observing_property{{[_0-9a-zA-Z]*}}vW // CHECK: end sil function } // CHECK-LABEL: sil hidden [ossa] @$s9observers25global_observing_property{{[_0-9a-zA-Z]*}}vs // CHECK: function_ref observers.global_observing_property.unsafeMutableAddressor // CHECK-NEXT: function_ref @$s9observers25global_observing_property{{[_0-9a-zA-Z]*}}vau // CHECK: function_ref observers.global_observing_property.didset // CHECK-NEXT: function_ref @$s9observers25global_observing_property{{[_0-9a-zA-Z]*}}vW } func force_global_observing_property_setter() { let x = global_observing_property global_observing_property = x } // Test local observing properties. // CHECK-LABEL: sil hidden [ossa] @$s9observers24local_observing_property{{[_0-9a-zA-Z]*}}SiF func local_observing_property(_ arg: Int) { var localproperty: Int = arg { didSet { takeInt(localproperty) localproperty = zero } } takeInt(localproperty) localproperty = arg // Alloc and initialize the property to the argument value. // CHECK: bb0([[ARG:%[0-9]+]] : $Int) // CHECK: [[BOX:%[0-9]+]] = alloc_box ${ var Int } // CHECK: [[PB:%.*]] = project_box [[BOX]] // CHECK: store [[ARG]] to [trivial] [[PB]] } // didSet of localproperty (above) // Ensure that setting the variable from within its own didSet doesn't recursively call didSet. // CHECK-LABEL: sil private [ossa] @$s9observers24local_observing_property{{[_0-9a-zA-Z]*}}SiF13localproperty{{[_0-9a-zA-Z]*}}SivW // CHECK: bb0(%0 : @guaranteed ${ var Int }) // CHECK: [[POINTER:%.*]] = project_box %0 : ${ var Int }, 0 // CHECK: // function_ref observers.zero.unsafeMutableAddressor : Swift.Int // CHECK-NEXT: [[ZEROFN:%.*]] = function_ref @$s9observers4zero{{[_0-9a-zA-Z]*}}vau // CHECK-NEXT: [[ZERORAW:%.*]] = apply [[ZEROFN]]() : $@convention(thin) () -> Builtin.RawPointer // CHECK-NEXT: [[ZEROADDR:%.*]] = pointer_to_address [[ZERORAW]] : $Builtin.RawPointer to [strict] $*Int // CHECK-NEXT: [[READ:%.*]] = begin_access [read] [dynamic] [[ZEROADDR]] : $*Int // CHECK-NEXT: [[ZERO:%.*]] = load [trivial] [[READ]] // CHECK-NEXT: end_access [[READ]] : $*Int // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [unknown] [[POINTER]] : $*Int // CHECK-NEXT: assign [[ZERO]] to [[WRITE]] : $*Int // CHECK-NEXT: end_access [[WRITE]] : $*Int // CHECK-NOT: function_ref @$s9observers24local_observing_property{{[_0-9a-zA-Z]*}}SiF13localproperty{{[_0-9a-zA-Z]*}}SivW // CHECK: end sil function func local_generic_observing_property<T>(_ arg: Int, _: T) { var localproperty1: Int = arg { didSet { takeInt(localproperty1) } } takeInt(localproperty1) localproperty1 = arg var localproperty2: Int = arg { didSet { _ = T.self takeInt(localproperty2) } } takeInt(localproperty2) localproperty2 = arg } // <rdar://problem/16006333> observing properties don't work in @objc classes @objc class ObservingPropertyInObjCClass { var bounds: Int { willSet {} didSet {} } init(b: Int) { bounds = b } } // CHECK-LABEL: sil hidden [ossa] @$s9observers32propertyWithDidSetTakingOldValueyyF : $@convention(thin) () -> () { func propertyWithDidSetTakingOldValue() { var p : Int = zero { didSet(oldValue) { // access to oldValue use(oldValue) // and newValue. use(p) } } p = zero } // CHECK-LABEL: sil private [ossa] @$s9observers32propertyWithDidSetTakingOldValueyyF1pL_Sivs // CHECK: bb0([[ARG1:%.*]] : $Int, [[ARG2:%.*]] : @guaranteed ${ var Int }): // CHECK-NEXT: debug_value [[ARG1]] : $Int, let, name "value", argno 1 // CHECK-NEXT: [[ARG2_PB:%.*]] = project_box [[ARG2]] // CHECK-NEXT: debug_value [[ARG2_PB]] : $*Int, var, name "p", argno 2, expr op_deref // CHECK-NEXT: [[READ:%.*]] = begin_access [read] [unknown] [[ARG2_PB]] // CHECK-NEXT: [[ARG2_PB_VAL:%.*]] = load [trivial] [[READ]] : $*Int // CHECK-NEXT: end_access [[READ]] // CHECK-NEXT: debug_value [[ARG2_PB_VAL]] : $Int // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [unknown] [[ARG2_PB]] // CHECK-NEXT: assign [[ARG1]] to [[WRITE]] : $*Int // CHECK-NEXT: end_access [[WRITE]] // SEMANTIC ARC TODO: Another case where we need to put the mark_function_escape on a new projection after a copy. // CHECK-NEXT: mark_function_escape [[ARG2_PB]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[FUNC:%.*]] = function_ref @$s9observers32propertyWithDidSetTakingOldValueyyF1pL_SivW : $@convention(thin) (Int, @guaranteed { var Int }) -> () // CHECK-NEXT: %{{.*}} = apply [[FUNC]]([[ARG2_PB_VAL]], [[ARG2]]) : $@convention(thin) (Int, @guaranteed { var Int }) -> () // CHECK-NEXT: %{{.*}} = tuple () // CHECK-NEXT: return %{{.*}} : $() // CHECK-NEXT:} // end sil function '$s9observers32propertyWithDidSetTakingOldValue{{[_0-9a-zA-Z]*}}' // <rdar://problem/16406886> Observing properties don't work with ownership types class Ref {} struct ObservingPropertiesWithOwnershipTypes { unowned var alwaysPresent : Ref { didSet { } } init(res: Ref) { alwaysPresent = res } } // CHECK-LABEL: sil private [ossa] @$s9observers37ObservingPropertiesWithOwnershipTypesV13alwaysPresentAA3RefCvW : $@convention(method) (@inout ObservingPropertiesWithOwnershipTypes) -> () { struct ObservingPropertiesWithOwnershipTypesInferred { unowned var alwaysPresent = Ref() { didSet { } } weak var maybePresent = nil as Ref? { willSet { } } } // CHECK-LABEL: sil private [ossa] @$s9observers45ObservingPropertiesWithOwnershipTypesInferredV13alwaysPresentAA3RefCvW : $@convention(method) (@inout ObservingPropertiesWithOwnershipTypesInferred) -> () { // CHECK-LABEL: sil private [ossa] @$s9observers45ObservingPropertiesWithOwnershipTypesInferredV12maybePresentAA3RefCSgvw : $@convention(method) (@guaranteed Optional<Ref>, @inout ObservingPropertiesWithOwnershipTypesInferred) -> () { //<rdar://problem/16620121> Initializing constructor tries to initialize computed property overridden with willSet/didSet class ObservedBase { var printInfo: Ref! } class ObservedDerived : ObservedBase { override init() {} override var printInfo: Ref! { didSet { } } } // CHECK-LABEL: sil private [ossa] @$s9observers15ObservedDerivedC9printInfoAA3RefCSgvW : $@convention(method) (@guaranteed ObservedDerived) -> () { /// <rdar://problem/26408353> crash when overriding internal property with /// public property public class BaseClassWithInternalProperty { var x: () = () } public class DerivedClassWithPublicProperty : BaseClassWithInternalProperty { public override var x: () { didSet {} } } // CHECK-LABEL: sil hidden [transparent] [ossa] @$s9observers29BaseClassWithInternalPropertyC1xytvg // CHECK-LABEL: sil [ossa] @$s9observers30DerivedClassWithPublicPropertyC1xytvg // CHECK: bb0([[SELF:%.*]] : @guaranteed $DerivedClassWithPublicProperty): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $DerivedClassWithPublicProperty // CHECK-NEXT: [[SUPER:%.*]] = upcast [[SELF_COPY]] : $DerivedClassWithPublicProperty to $BaseClassWithInternalProperty // CHECK-NEXT: [[BORROWED_SUPER:%.*]] = begin_borrow [[SUPER]] // CHECK-NEXT: // function_ref observers.BaseClassWithInternalProperty.x.getter : () // CHECK-NEXT: [[METHOD:%.*]] = function_ref @$s9observers29BaseClassWithInternalPropertyC1xytvg : $@convention(method) (@guaranteed BaseClassWithInternalProperty) -> () // CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[BORROWED_SUPER]]) : $@convention(method) (@guaranteed BaseClassWithInternalProperty) -> () // CHECK-NEXT: end_borrow [[BORROWED_SUPER]] // CHECK-NEXT: destroy_value [[SUPER]] : $BaseClassWithInternalProperty // CHECK: } // end sil function '$s9observers30DerivedClassWithPublicPropertyC1xytvg' // Make sure we use the correct substitutions when referencing a property in a // generic base class public class GenericBase<T> { var storage: T? = nil } public class ConcreteDerived : GenericBase<Int> { override var storage: Int? { didSet {} } } // CHECK-LABEL: sil private [ossa] @$s9observers15ConcreteDerivedC7storageSiSgvW : $@convention(method) (@guaranteed ConcreteDerived) -> () { // Make sure we upcast properly when the overridden property is in an ancestor // of our superclass public class BaseObserved { var x: Int = 0 } public class MiddleObserved : BaseObserved {} public class DerivedObserved : MiddleObserved { override var x: Int { didSet {} } } // CHECK-LABEL: sil private [ossa] @$s9observers15DerivedObservedC1xSivW : $@convention(method) (@guaranteed DerivedObserved) -> () {
apache-2.0
847174b1d6d74fc5569baa2172298611
44.926606
234
0.639083
3.683591
false
true
false
false
brightdigit/speculid
tests/cairosvg/CairoSVGTests.swift
1
2696
@testable import CairoSVG import XCTest extension NSColor: CairoColorProtocol { public var red: Double { Double(redComponent) } public var green: Double { Double(greenComponent) } public var blue: Double { Double(blueComponent) } } class ImageFile: NSObject, ImageFileProtocol { let url: URL let format: ImageFileFormat init(url: URL, fileFormat: ImageFileFormat) { self.url = url format = fileFormat super.init() } } class ImageSpecification: NSObject, ImageSpecificationProtocol { let file: ImageFileProtocol let geometry: GeometryDimension let removeAlphaChannel: Bool let backgroundColor: CairoColorProtocol? init(file: ImageFileProtocol, geometry: GeometryDimension, removeAlphaChannel: Bool, backgroundColor: CairoColorProtocol?) { self.file = file self.geometry = geometry self.removeAlphaChannel = removeAlphaChannel self.backgroundColor = backgroundColor super.init() } } class CairoSVGTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. let expectedWidth: CGFloat = 90.0 let bundle = Bundle(for: type(of: self)) let url = bundle.url(forResource: "geometry", withExtension: "svg")! let srcImageFile = ImageFile(url: url, fileFormat: .svg) // swiftlint:disable:next force_try let imageHandle = try! ImageHandleBuilder.shared.imageHandle(fromFile: srcImageFile) let destDirURL = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true) let destImageFile = ImageFile(url: destDirURL.appendingPathComponent(UUID().uuidString), fileFormat: .png) let specs = ImageSpecification(file: destImageFile, geometry: GeometryDimension(value: expectedWidth, dimension: .width), removeAlphaChannel: true, backgroundColor: NSColor.cyan) // swiftlint:disable:next force_try try! CairoInterface.exportImage(imageHandle, withSpecification: specs) XCTAssert(FileManager.default.fileExists(atPath: destImageFile.url.path)) let image = NSImage(byReferencing: destImageFile.url) XCTAssertEqual(image.size.width, expectedWidth) } func testPerformanceExample() { // This is an example of a performance test case. measure { // Put the code you want to measure the time of here. } } }
mit
984bee8ac6ef8b030f7738d769fb3edb
31.481928
182
0.73405
4.38374
false
true
false
false
Tomikes/eidolon
Kiosk/App/Views/Spinner.swift
7
1509
import UIKit class Spinner: UIView { var spinner:UIView! let rotationDuration = 0.9; func createSpinner() -> UIView { let view = UIView(frame: CGRectMake(0, 0, 20, 5)) view.backgroundColor = .blackColor() return view } override func awakeFromNib() { spinner = createSpinner() addSubview(spinner) backgroundColor = .clearColor() animateN(Float.infinity) } override func layoutSubviews() { // .center uses frame spinner.center = CGPointMake( CGRectGetWidth(bounds) / 2, CGRectGetHeight(bounds) / 2) } func animateN(times: Float) { let transformOffset = -1.01 * M_PI let transform = CATransform3DMakeRotation( CGFloat(transformOffset), 0, 0, 1); let rotationAnimation = CABasicAnimation(keyPath:"transform"); rotationAnimation.toValue = NSValue(CATransform3D:transform) rotationAnimation.duration = rotationDuration; rotationAnimation.cumulative = true; rotationAnimation.repeatCount = Float(times); layer.addAnimation(rotationAnimation, forKey:"spin"); } func animate(animate: Bool) { let isAnimating = layer.animationForKey("spin") != nil if (isAnimating && !animate) { layer.removeAllAnimations() } else if (!isAnimating && animate) { self.animateN(Float.infinity) } } func stopAnimating() { layer.removeAllAnimations() animateN(1) } }
mit
95cbf15be41812a0d78907ae41ef64b7
28.588235
94
0.628893
4.821086
false
false
false
false
LYM-mg/MGDS_Swift
MGDS_Swift/MGDS_Swift/Class/Home/Tencent/BaseTableViewController.swift
1
6918
// // BaseTableViewController.swift // MGDS_Swift // // Created by i-Techsys.com on 17/1/18. // Copyright © 2017年 i-Techsys. All rights reserved. // import UIKit import MJRefresh enum VideoSidType: Int { case tencent = 0 case sina = 1 case netease = 2 } class BaseTableViewController: UITableViewController { public var videoSid: VideoSidType = VideoSidType(rawValue: 0)! var page = 10 lazy var dataArr = [VideoList]() lazy var playerView: ZFPlayerView = { let playerView = ZFPlayerView() playerView.delegate = self // 当cell播放视频由全屏变为小屏时候,不回到中间位置 playerView.cellPlayerOnCenter = true /** 静音(默认为NO)*/ playerView.mute = false // 当cell划出屏幕的时候停止播放 playerView.stopPlayWhileCellNotVisable = false //(可选设置)可以设置视频的填充模式,默认为(等比例填充,直到一个维度到达区域边界) playerView.playerLayerGravity = .resizeAspect return playerView }() lazy var controlView: ZFPlayerControlView = ZFPlayerControlView() override func viewDidLoad() { super.viewDidLoad() tableView.estimatedRowHeight = 350.0 tableView.rowHeight = UITableView.automaticDimension // 设置分割线从最左开始 if tableView.responds(to: #selector(setter: UITableViewCell.separatorInset)) { tableView.separatorInset = UIEdgeInsets.zero } if tableView.responds(to: #selector(setter: UIView.layoutMargins)) { tableView.layoutMargins = UIEdgeInsets.zero } setUpRefresh() self.view.layoutIfNeeded() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) playerView.resetPlayer() } } // MARK: - 加载数据 extension BaseTableViewController { func setUpRefresh() { weak var weakSelf = self // MARK: 下拉刷新 tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: { let strongSelf = weakSelf if KAppDelegate.sidArray.count > strongSelf!.videoSid.rawValue { if KAppDelegate.sidArray.isEmpty && KAppDelegate.sidArray.count == 0 { strongSelf?.tableView.mj_header?.endRefreshing() return } let sidModel = KAppDelegate.sidArray[strongSelf!.videoSid.rawValue] self.dataArr.removeAll() strongSelf!.page = 10 let index = Int(arc4random_uniform(10)) strongSelf?.loadData(urlStr: "http://c.3g.163.com/nc/video/list/\(sidModel.sid!)/y/\(index)-15.html", sidModel: sidModel) } }) // 设置自动切换透明度(在导航栏下面自动隐藏) tableView.mj_header?.isAutomaticallyChangeAlpha = true // MARK: 上拉刷新 tableView.mj_footer = MJRefreshAutoFooter(refreshingBlock: { let strongSelf = weakSelf let sidModel = KAppDelegate.sidArray[strongSelf!.videoSid.rawValue] strongSelf!.page += 10 let urlStr = "http://c.3g.163.com/nc/video/list/\(sidModel.sid!)/y/\(self.page-10)-\(self.page).html" weakSelf?.loadData(urlStr: urlStr, sidModel: sidModel) }) self.tableView.mj_footer?.isAutomaticallyHidden = true self.tableView.mj_header?.beginRefreshing() } func loadData(urlStr: String,sidModel: VideoSidList) { weak var weakSelf = self SysNetWorkTools.share.progressTitle("正在加载数据...").getVideoList(withURLString: urlStr, listID: sidModel.sid, success: { (listArray, _) in weakSelf?.dataArr += listArray as! [VideoList] DispatchQueue.main.async { weakSelf?.tableView.reloadData() weakSelf?.tableView.mj_header?.endRefreshing() weakSelf?.tableView.mj_footer?.endRefreshing() } }, failure: { (err) in weakSelf?.showHint(hint: "数据请求失败") weakSelf?.tableView.mj_header?.endRefreshing() weakSelf?.tableView.mj_footer?.endRefreshing() }) // 1.显示指示器 dataArr = KAppDelegate.videosArray self.tableView.reloadData() self.tableView.mj_header?.endRefreshing() self.tableView.mj_footer?.endRefreshing() } } // MARK: - 数据源 extension BaseTableViewController { override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataArr.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "KTencentCellID", for: indexPath) as! TencentCell cell.model = self.dataArr[indexPath.row] cell.delegate = self return cell } override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { if(cell.responds(to: #selector(setter: UITableViewCell.separatorInset))){ cell.separatorInset = .zero } if(cell.responds(to: #selector(setter: UIView.layoutMargins))){ cell.layoutMargins = .zero } } } // MARK: - TableViewCellProtocol extension BaseTableViewController: TencentCellProtocol { /// 点击播放 func playBtnClick(cell: TencentCell ,model: VideoList) { // 分辨率字典(key:分辨率名称,value:分辨率url) let playerModel = ZFPlayerModel() playerModel.title = model.title; playerModel.videoURL = URL(string: model.mp4_url) playerModel.placeholderImageURLString = model.topicImg playerModel.tableView = self.tableView; playerModel.indexPath = tableView.indexPath(for: cell) // player的父视图 playerModel.fatherView = cell.playImageV; // 设置播放控制层和model playerView.playerControlView(self.controlView, playerModel: playerModel) // 下载功能 playerView.hasDownload = false // 自动播放 playerView.autoPlayTheVideo() } } // MARK: - TableViewCellProtocol extension BaseTableViewController: ZFPlayerDelegate { func zf_playerDownload(_ url: String!) { // 此处是截取的下载地址,可以自己根据服务器的视频名称来赋值 let name = (url as NSString).lastPathComponent print(name) } }
mit
72523f57b1c95427c737f141f119ade3
33.354497
143
0.61959
4.634547
false
false
false
false
ihomway/RayWenderlichCourses
Advanced Swift 3/Advanced Swift 3.playground/Sources/Random.swift
1
2636
/** * Copyright (c) 2017 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit public extension FloatingPoint { static func unitRandom() -> Self { return Self(arc4random())/(Self(UInt32.max)+Self(1)) } static func closedUnitRandom() -> Self { return Self(arc4random())/Self(UInt32.max) } } // Closed ranges want to include the upperBound so they use Double.closedUnitRandom() public extension ClosedRange where Bound: FloatingPoint { public var random: Bound { // generate a random value [0, 1] return lowerBound + (upperBound - lowerBound) * Bound.closedUnitRandom() } } // Half open ranges should not include the upperBound so they use Double. public extension Range where Bound: FloatingPoint { public var random: Bound { // generate a radom value [0, 1) return lowerBound + (upperBound - lowerBound) * Bound.unitRandom() } } public extension Int { public var randomUniform: Int { return Int(arc4random_uniform(UInt32(self))) } } public extension RandomAccessCollection { var random: Iterator.Element { precondition(!isEmpty) let count: Int = numericCast(self.count) let randomDistance: IndexDistance = numericCast(count.randomUniform) let index = self.index(startIndex, offsetBy: randomDistance) return self[index] } } public extension UIColor { static var random: UIColor { let r = CGFloat(arc4random())/CGFloat(UInt32.max) let g = CGFloat(arc4random())/CGFloat(UInt32.max) let b = CGFloat(arc4random())/CGFloat(UInt32.max) return UIColor(red: r, green: g, blue: b, alpha: 1) } }
mit
70142e93996fc61475a71df1d940d208
35.109589
85
0.731032
4.177496
false
false
false
false
lvogelzang/Blocky
Blocky/Levels/Level36.swift
1
877
// // Level36.swift // Blocky // // Created by Lodewijck Vogelzang on 07-12-18 // Copyright (c) 2018 Lodewijck Vogelzang. All rights reserved. // import UIKit final class Level36: Level { let levelNumber = 36 var tiles = [[0, 1, 0, 1, 0], [1, 1, 1, 1, 1], [0, 1, 0, 1, 0], [0, 1, 0, 1, 0]] let cameraFollowsBlock = false let blocky: Blocky let enemies: [Enemy] let foods: [Food] init() { blocky = Blocky(startLocation: (0, 1), endLocation: (4, 1)) let pattern0 = [("S", 0.5), ("S", 0.5), ("S", 0.5), ("N", 0.5), ("N", 0.5), ("N", 0.5)] let enemy0 = Enemy(enemyNumber: 0, startLocation: (1, 3), animationPattern: pattern0) let pattern1 = [("S", 0.5), ("S", 0.5), ("S", 0.5), ("N", 0.5), ("N", 0.5), ("N", 0.5)] let enemy1 = Enemy(enemyNumber: 1, startLocation: (3, 3), animationPattern: pattern1) enemies = [enemy0, enemy1] foods = [] } }
mit
709f6fc9571cf5c2165d2598df951851
24.794118
89
0.573546
2.649547
false
false
false
false
qutheory/vapor
Sources/Vapor/Logging/LoggingSystem+Environment.swift
2
1530
extension LoggingSystem { public static func bootstrap(from environment: inout Environment, _ factory: (Logger.Level) -> (String) -> LogHandler) throws { let level = try Logger.Level.detect(from: &environment) // Disable stack traces if log level > trace. if level > .trace { StackTrace.isCaptureEnabled = false } // Bootstrap logger with a factory created by the factoryfactory. return LoggingSystem.bootstrap(factory(level)) } public static func bootstrap(from environment: inout Environment) throws { try self.bootstrap(from: &environment) { level in let console = Terminal() return { (label: String) in return ConsoleLogger(label: label, console: console, level: level) } } } } extension Logger.Level: LosslessStringConvertible { public init?(_ description: String) { self.init(rawValue: description.lowercased()) } public var description: String { self.rawValue } public static func detect(from environment: inout Environment) throws -> Logger.Level { struct LogSignature: CommandSignature { @Option(name: "log", help: "Change log level") var level: Logger.Level? init() { } } // Determine log level from environment. return try LogSignature(from: &environment.commandInput).level ?? Environment.process.LOG_LEVEL ?? (environment == .production ? .notice: .info) } }
mit
84fec8ec365c0450d2d8a3dd1be7cac6
37.25
131
0.632026
4.78125
false
false
false
false
lukaskollmer/Mathe
Mathe/BinomialDistributionViewController.swift
1
5093
// // BinomialDistributionViewController.swift // Mathe // // Created by Lukas Kollmer on 12/01/2017. // Copyright © 2017 Lukas Kollmer. All rights reserved. // import UIKit import MatheKit private enum CalculationTrigger { case change case button } class BinomialDistributionViewController: UITableViewController, UITextFieldDelegate { @IBOutlet weak var nTextField: UITextField! @IBOutlet weak var pTextField: UITextField! @IBOutlet weak var kTextField: UITextField! @IBOutlet weak var resultLabel: UILabel! override func loadView() { super.loadView() title = "Binomial distribution" for textField in [nTextField, pTextField, kTextField] { textField?.keyboardType = .numbersAndPunctuation textField?.delegate = self textField?.autocorrectionType = .no textField?.autocapitalizationType = .none textField?.spellCheckingType = .no textField?.textAlignment = .center } tableView.keyboardDismissMode = .interactive //navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Calculate", style: .plain, target: self, action: #selector(calculateButton)) resultLabel.text = nil } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) nTextField.becomeFirstResponder() } func calculateButton() { calculate(trigger: .button) } // Why do we pass a trigger? Because we only show an error message if the calculation was triggered by the bar button item private func calculate(trigger: CalculationTrigger) { guard let n = nTextField.text?.intValue, let p: Double = pTextField.text?.doubleValue, let k = kTextField.text?.intValue else { resultLabel.text = nil if trigger == .button { error(message: "Invalid input") } return } // No idea if running the calculation on a background thread is actually beneficial, tbh DispatchQueue.global(qos: .background).async { let input = MKBinomialDistributionValues(numberOfTries: Int32(n), possibility: p, k: Int32(k) ) let distribution = MKBinomialDistrubution.binomialDistribution(with: input) DispatchQueue.main.async { self.resultLabel.text = "\(distribution)" } } } private func error(message: String) { let alert = UIAlertController(title: "🤦‍♂️", message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Got it", style: .cancel) { _ in alert.dismiss(animated: true, completion: nil) }) present(alert, animated: true, completion: nil) } // MARK: TextField delegate func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { guard string.isNumber else { return false } if let text = textField.text { let nsstring = NSString(string: text) textField.text = String(nsstring.replacingCharacters(in: range, with: string)) } calculate(trigger: .change) return false } func textFieldShouldReturn(_ textField: UITextField) -> Bool { var tag = textField.tag if tag == 3 { tag = 1 } else { tag += 1 } [nTextField, pTextField, kTextField][tag - 1]?.becomeFirstResponder() return false // prevent line breaks } } // MARK: String extensions private let allowedCharacters: [Character] = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "/", ","] private extension String { var isNumber: Bool { return self.characters.filter { !allowedCharacters.contains($0) }.isEmpty } var properComma: String { return self.replacingOccurrences(of: ",", with: ".") } var intValue: Int? { guard self.isNumber else { return nil } guard !self.characters.isEmpty else { return nil } return Int(self) ?? nil } var doubleValue: Double? { guard self.isNumber else { return nil } guard !self.characters.isEmpty else { return nil } guard self.contains("/") else { return Double(self.properComma) } guard (self.characters.filter({ $0 == "/" }).count == 1) else { return nil } if let lhs = self.components(separatedBy: "/").first?.properComma.intValue, let rhs = self.components(separatedBy: "/").last?.properComma.intValue { return Double(lhs) / Double(rhs) } else { return nil } } }
mit
cb27ad9f19f5f051c5077f4c77dc703b
30.571429
146
0.576825
5.042659
false
false
false
false
czechboy0/DVR
DVR/URLResponse.swift
6
714
import Foundation // There isn't a mutable NSURLResponse, so we have to make our own. class URLResponse: NSURLResponse { private var _URL: NSURL? override var URL: NSURL? { get { return _URL ?? super.URL } set { _URL = newValue } } } extension NSURLResponse { var dictionary: [String: AnyObject] { if let url = URL?.absoluteString { return ["url": url] } return [:] } } extension URLResponse { convenience init(dictionary: [String: AnyObject]) { self.init() if let string = dictionary["url"] as? String, url = NSURL(string: string) { URL = url } } }
mit
31813e1d6f4766bd008a6dcde6e59018
18.297297
83
0.539216
4.353659
false
false
false
false
SteveLeviathan/SpeakSwift
SpeakSwift/SpeakSwift/SpeechObject.swift
1
1796
// // SpeechObject.swift // SpeakSwift // // Created by Steve Overmars on 08-06-14. // Copyright (c) 2014 Appify Media. All rights reserved. // import Foundation struct SpeechObject { let speechString: String let language: String let rate: Float let pitch: Float let volume: Float init(speechString: String = "", language: String = "", rate: Float = 1.0, pitch: Float = 1.0, volume: Float = 1.0) { self.speechString = speechString self.language = language self.rate = rate self.pitch = pitch self.volume = volume } /// Returns a SpeechObject from a Dictionary init(dictionary: [String: String]) { let speechString = dictionary["speechString"] ?? "" let language = dictionary["language"] ?? "" let rateStr = dictionary["rate"] ?? "1.0" let pitchStr = dictionary["pitch"] ?? "1.0" let volumeStr = dictionary["volume"] ?? "1.0" let rate = Float(rateStr) ?? 1.0 let pitch = Float(pitchStr) ?? 1.0 let volume = Float(volumeStr) ?? 1.0 self.speechString = speechString self.language = language self.rate = rate self.pitch = pitch self.volume = volume } /// Returns a Dictionary representation of a SpeechObject func dictionaryRepresentation () -> [String: String] { var dictionary: [String: String] = [:] dictionary["speechString"] = speechString dictionary["language"] = language dictionary["rate"] = String(format: "%.2f", rate) dictionary["pitch"] = String(format: "%.2f", pitch) dictionary["volume"] = String(format: "%.2f", volume) return dictionary } }
mit
e2ffa4e2c2151c4ae9020eb845e54499
24.657143
61
0.57461
4.196262
false
false
false
false
stephentyrone/swift
test/IRGen/prespecialized-metadata/struct-public-inmodule-1argument-1distinct_use.swift
3
3019
// 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: @"$s4main5ValueVySiGMf" = linkonce_odr hidden constant <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // 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: i32 0{{(, \[4 x i8\] zeroinitializer)?}}, // CHECK-SAME: i64 3 // CHECK-SAME: }>, align [[ALIGNMENT]] @frozen public struct Value<First> { 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*, 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{{( protected| dllexport)?}} swiftcc %swift.metadata_response @"$s4main5ValueVMa"([[INT]] %0, %swift.type* %1) #{{[0-9]+}} { // CHECK: entry: // CHECK: [[ERASED_TYPE:%[0-9]+]] = bitcast %swift.type* %1 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: br i1 [[EQUAL_TYPES]], 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*, 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* undef, i8* undef, %swift.type_descriptor* bitcast ({{.+}}$s4main5ValueVMn{{.+}} to %swift.type_descriptor*)) #{{[0-9]+}} // CHECK: ret %swift.metadata_response {{%[0-9]+}} // CHECK: }
apache-2.0
0bd367a9b2cc35e3b838796f61b91888
51.051724
332
0.611461
3.064975
false
false
false
false
mrudulp/iOSSrc
autotest/appiumTest/sampleApps/UICatalogObj_Swift/Swift/UICatalog/ImageViewController.swift
3
1390
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: A view controller that demonstrates how to use UIImageView. */ import UIKit class ImageViewController: UIViewController { // MARK: View Life Cycle override func viewDidLoad() { super.viewDidLoad() configureImageView() } // MARK: Configuration func configureImageView() { // The root view of the view controller set in Interface Builder is a UIImageView. let imageView = view as! UIImageView // Fetch the images (each image is of the format image_animal_number). imageView.animationImages = map(1...5) { UIImage(named: "image_animal_\($0)")! } // We want the image to be scaled to the correct aspect ratio within imageView's bounds. imageView.contentMode = .ScaleAspectFit // If the image does not have the same aspect ratio as imageView's bounds, then imageView's backgroundColor will be applied to the "empty" space. imageView.backgroundColor = UIColor.whiteColor() imageView.animationDuration = 5 imageView.startAnimating() imageView.isAccessibilityElement = true imageView.accessibilityLabel = NSLocalizedString("Animated", comment: "") } }
mit
7d7d65c05c6ed02f6ebd6a114d546226
32.853659
153
0.65562
5.421875
false
true
false
false
opfeffer/swift-sodium
Examples/iOS/ViewController.swift
1
1429
// // ViewController.swift // Example iOS // // Created by RamaKrishna Mallireddy on 19/04/15. // Copyright (c) 2015 Frank Denis. All rights reserved. // import UIKit import Sodium class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let sodium = Sodium()! let aliceKeyPair = sodium.box.keyPair()! let bobKeyPair = sodium.box.keyPair()! let message = "My Test Message".toData()! print("Original Message:\(message.toString())") let encryptedMessageFromAliceToBob: Data = sodium.box.seal( message: message, recipientPublicKey: bobKeyPair.publicKey, senderSecretKey: aliceKeyPair.secretKey)! print("Encrypted Message:\(encryptedMessageFromAliceToBob)") let messageVerifiedAndDecryptedByBob = sodium.box.open( nonceAndAuthenticatedCipherText: encryptedMessageFromAliceToBob, senderPublicKey: bobKeyPair.publicKey, recipientSecretKey: aliceKeyPair.secretKey) print("Decrypted Message:\(messageVerifiedAndDecryptedByBob!.toString())") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
isc
1ab15e661344215d0d1c4d25fa0eceb3
27.58
82
0.652904
4.860544
false
false
false
false
superk589/CGSSGuide
DereGuide/Unit/Controller/UDTabViewController.swift
2
3686
// // UDTabViewController.swift // DereGuide // // Created by zzk on 2018/6/23. // Copyright © 2018 zzk. All rights reserved. // import UIKit import Tabman import Pageboy protocol UnitDetailConfigurable: class { var unit: Unit { set get } var parentTabController: UDTabViewController? { set get } } class UDTabViewController: TabmanViewController, PageboyViewControllerDataSource, TMBarDataSource { private var viewControllers: [UnitDetailConfigurable & UIViewController] private var observer: ManagedObjectObserver? var unit: Unit { didSet { observer = ManagedObjectObserver(object: unit, changeHandler: { [weak self] (type) in if type == .delete { self?.navigationController?.popViewController(animated: true) } else if type == .update { self?.setNeedsReloadUnit() if self?.isShowing ?? false { self?.reloadUnitIfNeeded() } } }) setNeedsReloadUnit() if self.isShowing { reloadUnitIfNeeded() } } } init(unit: Unit) { self.unit = unit viewControllers = [UnitSimulationController(unit: unit), UnitInformationController(unit: unit)] super.init(nibName: nil, bundle: nil) viewControllers.forEach { $0.parentTabController = self } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private var isShowing = false private var needsReloadUnit = false func setNeedsReloadUnit() { needsReloadUnit = true } func reloadUnitIfNeeded() { if needsReloadUnit { needsReloadUnit = false for vc in viewControllers { vc.unit = unit } } } private var items = [TMBarItem]() override func viewDidLoad() { super.viewDidLoad() self.items = [ NSLocalizedString("得分计算", comment: ""), NSLocalizedString("队伍信息", comment: "") ].map { TMBarItem(title: $0) } dataSource = self let bar = TMBarView<TMHorizontalBarLayout, TMLabelBarButton, TMBarIndicator.None>() let systemBar = bar.systemBar() bar.layout.contentInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20) bar.layout.transitionStyle = .progressive addBar(systemBar, dataSource: self, at: .bottom) bar.buttons.customize { (button) in button.selectedTintColor = .parade button.tintColor = .lightGray } systemBar.backgroundStyle = .blur(style: .extraLight) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) isShowing = true reloadUnitIfNeeded() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) isShowing = false } func numberOfViewControllers(in pageboyViewController: PageboyViewController) -> Int { return viewControllers.count } func viewController(for pageboyViewController: PageboyViewController, at index: PageboyViewController.PageIndex) -> UIViewController? { return viewControllers[index] } func defaultPage(for pageboyViewController: PageboyViewController) -> PageboyViewController.Page? { return .at(index: 0) } func barItem(for bar: TMBar, at index: Int) -> TMBarItemable { return items[index] } }
mit
d70206ca13332621363d2553c4ec347e
29.831933
139
0.604524
5.131469
false
false
false
false
PopcornTimeTV/PopcornTimeTV
PopcornTime/UI/iOS/Table View Controllers/StreamToDevicesTableViewController.swift
1
1815
import Foundation class StreamToDevicesTableViewController: GoogleCastTableViewController { override func numberOfSections(in tableView: UITableView) -> Int { return 2 } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return section == 1 ? "AirPlay" : super.tableView(tableView, titleForHeaderInSection: section) } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return section == 1 ? 1 : super.tableView(tableView, numberOfRowsInSection: section) } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.section == 1 { tableView.deselectRow(at: indexPath, animated: true) (tableView.cellForRow(at: indexPath) as! AirPlayTableViewCell).routeButton.sendActions(for: .touchUpInside) } else { super.tableView(tableView, didSelectRowAt: indexPath) } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.section == 1 { return tableView.dequeueReusableCell(withIdentifier: "airPlayCell", for: indexPath) } else { return super.tableView(tableView, cellForRowAt: indexPath) } } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return section == 1 ? 18 : super.tableView(tableView, heightForHeaderInSection: section) } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return indexPath.section == 1 ? 44 : super.tableView(tableView, heightForRowAt: indexPath) } }
gpl-3.0
d2d3d6758316c0d91f7dab46627e0ba7
41.209302
119
0.687052
5.45045
false
false
false
false
SusanDoggie/Doggie
Sources/DoggieGPU/Packed.swift
1
3329
// // Packed.swift // // The MIT License // Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #if canImport(Metal) struct Packed2<Scalar> { var x: Scalar var y: Scalar @_transparent init(_ x: Scalar, _ y: Scalar) { self.x = x self.y = y } } struct Packed3<Scalar> { var x: Scalar var y: Scalar var z: Scalar @_transparent init(_ x: Scalar, _ y: Scalar, _ z: Scalar) { self.x = x self.y = y self.z = z } } struct Packed4<Scalar> { var x: Scalar var y: Scalar var z: Scalar var w: Scalar @_transparent init(_ x: Scalar, _ y: Scalar, _ z: Scalar, _ w: Scalar) { self.x = x self.y = y self.z = z self.w = w } } extension Packed2 where Scalar: BinaryFloatingPoint { @_transparent init(_ point: Point) { self.init(Scalar(point.x), Scalar(point.y)) } @_transparent init(_ size: Size) { self.init(Scalar(size.width), Scalar(size.height)) } } extension Packed3 where Scalar: BinaryFloatingPoint { @_transparent init(_ vector: Vector) { self.init(Scalar(vector.x), Scalar(vector.y), Scalar(vector.z)) } } extension Packed4 where Scalar: BinaryFloatingPoint { @_transparent init(_ rect: Rect) { self.init(Scalar(rect.minX), Scalar(rect.minY), Scalar(rect.width), Scalar(rect.height)) } } typealias packed_int2 = Packed2<Int32> typealias packed_int3 = Packed3<Int32> typealias packed_int4 = Packed4<Int32> typealias packed_uint2 = Packed2<UInt32> typealias packed_uint3 = Packed3<UInt32> typealias packed_uint4 = Packed4<UInt32> typealias packed_float2 = Packed2<Float> typealias packed_float3 = Packed3<Float> typealias packed_float4 = Packed4<Float> typealias packed_float3x2 = Packed3<Packed2<Float>> extension packed_float3x2 { @_transparent init(_ transform: SDTransform) { self.init( Packed2(Float(transform.a), Float(transform.d)), Packed2(Float(transform.b), Float(transform.e)), Packed2(Float(transform.c), Float(transform.f)) ) } } #endif
mit
bdb1c019ca3f0a9dd3a6afb6490f791d
24.412214
96
0.647642
3.694784
false
false
false
false
tsigo/BombcastNavigator
BombcastNavigator/BombcastDetailViewController.swift
1
1010
// // BombcastDetailViewController.swift // BombcastNavigator // // Created by Robert Speicher on 12/8/14. // Copyright (c) 2014 Robert Speicher. All rights reserved. // import UIKit import AVFoundation import AVKit class BombcastDetailViewController: UIViewController { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var descriptionLabel: UILabel! var viewModel: BombcastViewModel? override func viewDidLoad() { titleLabel.text = viewModel?.title descriptionLabel.text = viewModel?.description descriptionLabel.sizeToFit() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "EmbeddedPlayer" { if let mediaUrl = viewModel?.media { let playerController = segue.destinationViewController as AVPlayerViewController playerController.player = AVPlayer(URL: mediaUrl) playerController.player.play() } } } }
mit
249672168159ece1a9d09d968468cfa3
27.885714
96
0.684158
5.126904
false
false
false
false
TonnyTao/HowSwift
how_to_update_view_in_mvvm.playground/Sources/RxSwift/RxSwift/Observables/Create.swift
8
2562
// // Create.swift // RxSwift // // Created by Krunoslav Zaher on 2/8/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // extension ObservableType { // MARK: create /** Creates an observable sequence from a specified subscribe method implementation. - seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html) - parameter subscribe: Implementation of the resulting observable sequence's `subscribe` method. - returns: The observable sequence with the specified implementation for the `subscribe` method. */ public static func create(_ subscribe: @escaping (AnyObserver<Element>) -> Disposable) -> Observable<Element> { AnonymousObservable(subscribe) } } final private class AnonymousObservableSink<Observer: ObserverType>: Sink<Observer>, ObserverType { typealias Element = Observer.Element typealias Parent = AnonymousObservable<Element> // state private let isStopped = AtomicInt(0) #if DEBUG private let synchronizationTracker = SynchronizationTracker() #endif override init(observer: Observer, cancel: Cancelable) { super.init(observer: observer, cancel: cancel) } func on(_ event: Event<Element>) { #if DEBUG self.synchronizationTracker.register(synchronizationErrorMessage: .default) defer { self.synchronizationTracker.unregister() } #endif switch event { case .next: if load(self.isStopped) == 1 { return } self.forwardOn(event) case .error, .completed: if fetchOr(self.isStopped, 1) == 0 { self.forwardOn(event) self.dispose() } } } func run(_ parent: Parent) -> Disposable { parent.subscribeHandler(AnyObserver(self)) } } final private class AnonymousObservable<Element>: Producer<Element> { typealias SubscribeHandler = (AnyObserver<Element>) -> Disposable let subscribeHandler: SubscribeHandler init(_ subscribeHandler: @escaping SubscribeHandler) { self.subscribeHandler = subscribeHandler } override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { let sink = AnonymousObservableSink(observer: observer, cancel: cancel) let subscription = sink.run(self) return (sink: sink, subscription: subscription) } }
mit
e677fdda8d7d343d275fd2f2e5cb1baf
31.833333
171
0.665756
4.89675
false
false
false
false
tad-iizuka/swift-sdk
Source/ConversationV1/Models/Context.swift
2
3043
/** * Copyright IBM Corporation 2016 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation import RestKit /** The context, or state, associated with a message. */ public struct Context: JSONEncodable, JSONDecodable { /// The raw JSON object used to construct this model. public let json: [String: Any] /// The unique identifier of the conversation. public let conversationID: String /// A system object that includes information about the dialog. public let system: System /// Used internally to initialize a `Context` model from JSON. public init(json: JSON) throws { self.json = try json.getDictionaryObject() conversationID = try json.getString(at: "conversation_id") system = try json.decode(at: "system", type: System.self) } /// Used internally to serialize a `Context` model to JSON. public func toJSONObject() -> Any { return json } } /** A system object that includes information about the dialog. */ public struct System: JSONEncodable, JSONDecodable { /// The raw JSON object used to construct this model. public let json: [String: Any] /// An array of dialog node ids that are in focus in the conversation. If no node is in the /// list, the conversation restarts at the root with the next request. If multiple dialog nodes /// are in the list, several dialogs are in progress, and the last ID in the list is active. /// When the active dialog ends, it is removed from the stack and the previous one becomes /// active. public let dialogStack: [String] /// The number of cycles of user input and response in this conversation. public let dialogTurnCounter: Int /// The number of inputs in this conversation. This counter might be higher than the /// `dialogTurnCounter` when multiple inputs are needed before a response can be returned. public let dialogRequestCounter: Int /// Used internally to initialize a `System` model from JSON. public init(json: JSON) throws { self.json = try json.getDictionaryObject() dialogStack = try json.getArray(at: "dialog_stack").map { try $0.getString(at: "dialog_node") } dialogTurnCounter = try json.getInt(at: "dialog_turn_counter") dialogRequestCounter = try json.getInt(at: "dialog_request_counter") } /// Used internally to serialize a `System` model to JSON. public func toJSONObject() -> Any { return json } }
apache-2.0
235bf7fac6943841351d91dc063219b5
38.519481
103
0.691094
4.541791
false
false
false
false
andreaperizzato/CoreStore
CoreStoreDemo/CoreStoreDemo/Transactions Demo/TransactionsDemoViewController.swift
1
6618
// // TransactionsDemoViewController.swift // CoreStoreDemo // // Created by John Rommel Estropia on 2015/05/24. // Copyright (c) 2015 John Rommel Estropia. All rights reserved. // import UIKit import CoreLocation import MapKit import AddressBookUI import CoreStore import GCDKit private struct Static { static let placeController: ObjectMonitor<Place> = { try! CoreStore.addSQLiteStoreAndWait( fileName: "PlaceDemo.sqlite", configuration: "TransactionsDemo", resetStoreOnModelMismatch: true ) var place = CoreStore.fetchOne(From(Place)) if place == nil { CoreStore.beginSynchronous { (transaction) -> Void in let place = transaction.create(Into(Place)) place.setInitialValues() transaction.commit() } place = CoreStore.fetchOne(From(Place)) } return CoreStore.monitorObject(place!) }() } // MARK: - TransactionsDemoViewController class TransactionsDemoViewController: UIViewController, MKMapViewDelegate, ObjectObserver { // MARK: NSObject deinit { Static.placeController.removeObserver(self) } // MARK: UIViewController override func viewDidLoad() { super.viewDidLoad() let longPressGesture = UILongPressGestureRecognizer(target: self, action: "longPressGestureRecognized:") self.mapView?.addGestureRecognizer(longPressGesture) Static.placeController.addObserver(self) self.navigationItem.rightBarButtonItem = UIBarButtonItem( barButtonSystemItem: .Refresh, target: self, action: "refreshButtonTapped:" ) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) let alert = UIAlertController( title: "Transactions Demo", message: "This demo shows how to use the 3 types of transactions to save updates: synchronous, asynchronous, and unsafe.\n\nTap and hold on the map to change the pin location.", preferredStyle: .Alert ) alert.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if let mapView = self.mapView, let place = Static.placeController.object { mapView.addAnnotation(place) mapView.setCenterCoordinate(place.coordinate, animated: false) mapView.selectAnnotation(place, animated: false) } } // MARK: MKMapViewDelegate func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? { let identifier = "MKAnnotationView" var annotationView: MKPinAnnotationView! = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier) as? MKPinAnnotationView if annotationView == nil { annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier) annotationView.enabled = true annotationView.canShowCallout = true annotationView.animatesDrop = true } else { annotationView.annotation = annotation } return annotationView } // MARK: ObjectObserver func objectMonitor(monitor: ObjectMonitor<Place>, willUpdateObject object: Place) { // none } func objectMonitor(monitor: ObjectMonitor<Place>, didUpdateObject object: Place, changedPersistentKeys: Set<KeyPath>) { if let mapView = self.mapView { mapView.removeAnnotations(mapView.annotations ?? []) mapView.addAnnotation(object) mapView.setCenterCoordinate(object.coordinate, animated: true) mapView.selectAnnotation(object, animated: true) if changedPersistentKeys.contains("latitude") || changedPersistentKeys.contains("longitude") { self.geocodePlace(object) } } } func objectMonitor(monitor: ObjectMonitor<Place>, didDeleteObject object: Place) { // none } // MARK: Private var geocoder: CLGeocoder? @IBOutlet weak var mapView: MKMapView? @IBAction dynamic func longPressGestureRecognized(sender: AnyObject?) { if let mapView = self.mapView, let gesture = sender as? UILongPressGestureRecognizer where gesture.state == .Began { let coordinate = mapView.convertPoint( gesture.locationInView(mapView), toCoordinateFromView: mapView ) CoreStore.beginAsynchronous { (transaction) -> Void in let place = transaction.edit(Static.placeController.object) place?.coordinate = coordinate transaction.commit { (_) -> Void in } } } } @IBAction dynamic func refreshButtonTapped(sender: AnyObject?) { CoreStore.beginSynchronous { (transaction) -> Void in let place = transaction.edit(Static.placeController.object) place?.setInitialValues() transaction.commit() } } func geocodePlace(place: Place) { let transaction = CoreStore.beginUnsafe() self.geocoder?.cancelGeocode() let geocoder = CLGeocoder() self.geocoder = geocoder geocoder.reverseGeocodeLocation( CLLocation(latitude: place.latitude, longitude: place.longitude), completionHandler: { [weak self] (placemarks, error) -> Void in if let placemark = placemarks?.first, let addressDictionary = placemark.addressDictionary { let place = transaction.edit(Static.placeController.object) place?.title = placemark.name place?.subtitle = ABCreateStringWithAddressDictionary(addressDictionary, true) transaction.commit { (_) -> Void in } } self?.geocoder = nil } ) } }
mit
b8bda7d212bb3f0c93d2c18e8e0885a5
30.665072
189
0.593382
5.946092
false
false
false
false
nmdias/FeedKit
Sources/FeedKit/Models/RSS/RSSFeedItemCategory.swift
2
3465
// // RSSFeedItemCategory.swift // // Copyright (c) 2016 - 2018 Nuno Manuel Dias // // 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 /// Includes the item in one or more categories. /// /// <category> is an optional sub-element of <item>. /// /// It has one optional attribute, domain, a string that identifies a /// categorization taxonomy. /// /// The value of the element is a forward-slash-separated string that /// identifies a hierarchic location in the indicated taxonomy. Processors /// may establish conventions for the interpretation of categories. /// /// Two examples are provided below: /// /// <category>Grateful Dead</category> /// <category domain="http://www.fool.com/cusips">MSFT</category> /// /// You may include as many category elements as you need to, for different /// domains, and to have an item cross-referenced in different parts of the /// same domain. public class RSSFeedItemCategory { /// The element's attributes. public class Attributes { /// A string that identifies a categorization taxonomy. It's an optional /// attribute of `<category>`. /// /// Example: http://www.fool.com/cusips public var domain: String? } /// The element's attributes. public var attributes: Attributes? /// The element's value. public var value: String? public init() { } } // MARK: - Initializers extension RSSFeedItemCategory { convenience init(attributes attributeDict: [String : String]) { self.init() self.attributes = RSSFeedItemCategory.Attributes(attributes: attributeDict) } } extension RSSFeedItemCategory.Attributes { convenience init?(attributes attributeDict: [String : String]) { if attributeDict.isEmpty { return nil } self.init() self.domain = attributeDict["domain"] } } // MARK: - Equatable extension RSSFeedItemCategory: Equatable { public static func ==(lhs: RSSFeedItemCategory, rhs: RSSFeedItemCategory) -> Bool { return lhs.attributes == rhs.attributes } } extension RSSFeedItemCategory.Attributes: Equatable { public static func ==(lhs: RSSFeedItemCategory.Attributes, rhs: RSSFeedItemCategory.Attributes) -> Bool { return lhs.domain == rhs.domain } }
mit
043c747d9dbdaf446950e236967fc4a4
29.663717
109
0.680808
4.5
false
false
false
false
nathawes/swift
test/IRGen/prespecialized-metadata/struct-extradata-no_field_offsets-trailing_flags.swift
5
3389
// RUN: %target-swift-frontend -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment // REQUIRES: VENDOR=apple || OS=linux-gnu // UNSUPPORTED: CPU=i386 && OS=ios // UNSUPPORTED: CPU=armv7 && OS=ios // UNSUPPORTED: CPU=armv7s && OS=ios // CHECK: [[EXTRA_DATA_PATTERN:@[0-9]+]] = internal constant { i64 } zeroinitializer, align [[ALIGNMENT]] // CHECK: @"$s4main4PairVMP" = internal constant <{ // : i32, // : i32, // : i32, // : i32, // : i32, // : i16, // : i16 // : }> <{ // : i32 trunc ( // : i64 sub ( // : i64 ptrtoint ( // : %swift.type* ( // : %swift.type_descriptor*, // : i8**, // : i8* // : )* @"$s4main4PairVMi" to i64 // : ), // : i64 ptrtoint ( // : <{ i32, i32, i32, i32, i32, i16, i16 }>* @"$s4main4PairVMP" to i64 // : ) // : ) to i32 // : ), // : i32 trunc ( // : i64 sub ( // : i64 ptrtoint ( // : %swift.metadata_response ( // : %swift.type*, // : i8*, // : i8** // : )* @"$s4main4PairVMr" to i64 // : ), // : i64 ptrtoint ( // : i32* getelementptr inbounds ( // : <{ i32, i32, i32, i32, i32, i16, i16 }>, // : <{ i32, i32, i32, i32, i32, i16, i16 }>* @"$s4main4PairVMP", // : i32 0, // : i32 1 // : ) to i64 // : ) // : ) to i32 // : ), // : i32 1073741827, // : i32 trunc ( // : i64 sub ( // : i64 ptrtoint ( // : %swift.vwtable* @"$s4main4PairVWV" to i64 // : ), // : i64 ptrtoint ( // : i32* getelementptr inbounds ( // : <{ i32, i32, i32, i32, i32, i16, i16 }>, // : <{ i32, i32, i32, i32, i32, i16, i16 }>* @"$s4main4PairVMP", // : i32 0, // : i32 3 // : ) to i64 // : ) // : ) to i32 // : ), // : i32 trunc ( // CHECK-SAME: [[INT]] sub ( // CHECK-SAME: [[INT]] ptrtoint ( // CHECK-SAME: { // CHECK-SAME: i64 // CHECK-SAME: }* [[EXTRA_DATA_PATTERN]] to [[INT]] // CHECK-SAME: ), // CHECK-SAME: [[INT]] ptrtoint ( // CHECK-SAME: i32* getelementptr inbounds ( // CHECK-SAME: <{ i32, i32, i32, i32, i32, i16, i16 }>, // CHECK-SAME: <{ i32, i32, i32, i32, i32, i16, i16 }>* @"$s4main4PairVMP", // CHECK-SAME: i32 0, // CHECK-SAME: i32 4 // CHECK-SAME: ) to [[INT]] // CHECK-SAME: ) // CHECK-SAME: ) // : ), // : i16 5, // : i16 1 // : }>, align 8 struct Pair<First, Second, Third> { let first: First let second: Second let third: Third }
apache-2.0
154e3d87690d7a5cb5fdcbaa6c471de5
35.44086
173
0.362349
3.112029
false
false
false
false
pattypatpat2632/EveryoneGetsToDJ
EveryoneGetsToDJ/EveryoneGetsToDJ/instructionsTextView.swift
1
1319
// // instructionsTextView.swift // EveryoneGetsToDJ // // Created by Patrick O'Leary on 6/25/17. // Copyright © 2017 Patrick O'Leary. All rights reserved. // import UIKit class instructionsTextView: UITextView { required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.textColor = colorScheme.model.foregroundColor self.backgroundColor = colorScheme.model.backgroundColor self.layer.borderWidth = 5 self.layer.borderColor = colorScheme.model.foregroundColor.cgColor self.layer.cornerRadius = 2 setText() } func setText() { self.text = "Everyone Gets to DJ!\n\n To use this app, one person must act as the host. The host's phone will play back all of the music. The host must log in to their Spotify Premium account in order play back any music.\n When the host has created a jukebox, everyone else on the same Wi-Fi network will be able to select and join that jukebox. Everyone who has joined a jukebox can add up to five songs at a time to the jukebox. A song cannot be added the playlist if its already on the list.\n\n\n Everyone Gets to DJ was created by Patrick O'Leary. For support or questions, please email [email protected]\n\nVersion 1.0.1\n Disc by Curve from the Noun Project" } }
mit
ef23f51ff1b5ce05a19ecfe7a4b37987
47.814815
686
0.717754
4.018293
false
false
false
false
skyylex/Algorithmus
Playgrounds/BinaryTree.playground/Contents.swift
1
1535
import Foundation let root = Node<Int>(newValue: 40) let tree = BinaryTree<Int>(root: root, orderRule: OrderResult.RightGreaterOrEqual) tree.addNode(Node<Int>(newValue: 10)) tree.addNode(Node<Int>(newValue: -10)) tree.addNode(Node<Int>(newValue: 22)) tree.addNode(Node<Int>(newValue: 70)) tree.addNode(Node<Int>(newValue: 44)) tree.addNode(Node<Int>(newValue: 55)) tree.addNode(Node<Int>(newValue: 445)) tree.addNode(Node<Int>(newValue: 5333)) tree.addNode(Node<Int>(newValue: 443)) tree.addNode(Node<Int>(newValue: 4433)) tree.addNode(Node<Int>(newValue: 44333)) tree.addNode(Node<Int>(newValue: 443333)) tree.addNode(Node<Int>(newValue: 20)) tree.addNode(Node<Int>(newValue: 0)) tree.addNode(Node<Int>(newValue: 30)) let deep = tree.deep let maxSymbolsInValue = 5 print("\n\n Text-drawn binary tree \n\n") tree.traverseUpsideDown({ nodes in let node = nodes.first let additionalOffset = node!.root ? 0 : node!.level let spaces = (0...(deep * (maxSymbolsInValue - additionalOffset))).map { _ in return " " } let offsetString = spaces.reduce("") { $0 + $1} let horizontalSpaces = (0...maxSymbolsInValue * 2).map { _ in return " " } let horizontalSpaceString = horizontalSpaces.reduce("") { $0 + $1} let levelString = nodes.reduce("") { current, node in return current + horizontalSpaceString + String(node.value) } print(offsetString + levelString) }) print("\n\n Plain sorted list \n\n") tree.traverse { (node : Node<Int>) -> Void in print(String(node.value)) }
mit
e77ce5da00121f515e4355ff8a5c2fce
30.326531
94
0.689251
3.322511
false
false
false
false
vector-im/riot-ios
Riot/Managers/Settings/Shared/RiotSharedSettings.swift
2
7587
/* 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 Foundation import MatrixSDK @objc enum WidgetPermission: Int { case undefined case granted case declined } /// Shared user settings across all Riot clients. /// It implements https://github.com/vector-im/riot-meta/blob/master/spec/settings.md @objcMembers class RiotSharedSettings: NSObject { // MARK: - Constants private enum Settings { static let breadcrumbs = "im.vector.setting.breadcrumbs" static let integrationProvisioning = "im.vector.setting.integration_provisioning" static let allowedWidgets = "im.vector.setting.allowed_widgets" } // MARK: - Properties // MARK: Private private let session: MXSession private lazy var serializationService: SerializationServiceType = SerializationService() // MARK: - Setup init(session: MXSession) { self.session = session } // MARK: - Public // MARK: Integration provisioning var hasIntegrationProvisioningEnabled: Bool { return getIntegrationProvisioning()?.enabled ?? true } func getIntegrationProvisioning() -> RiotSettingIntegrationProvisioning? { guard let integrationProvisioningDict = getAccountData(forEventType: Settings.integrationProvisioning) else { return nil } return try? serializationService.deserialize(integrationProvisioningDict) } @discardableResult func setIntegrationProvisioning(enabled: Bool, success: @escaping () -> Void, failure: @escaping (Error?) -> Void) -> MXHTTPOperation? { // Update only the "widgets" field in the account data var integrationProvisioningDict = getAccountData(forEventType: Settings.integrationProvisioning) ?? [:] integrationProvisioningDict[RiotSettingIntegrationProvisioning.CodingKeys.enabled.rawValue] = enabled return session.setAccountData(integrationProvisioningDict, forType: Settings.integrationProvisioning, success: success, failure: failure) } // MARK: Allowed widgets func permission(for widget: Widget) -> WidgetPermission { guard let allowedWidgets = getAllowedWidgets() else { return .undefined } if let value = allowedWidgets.widgets[widget.widgetEvent.eventId] { return value == true ? .granted : .declined } else { return .undefined } } func getAllowedWidgets() -> RiotSettingAllowedWidgets? { guard let allowedWidgetsDict = getAccountData(forEventType: Settings.allowedWidgets) else { return nil } return try? serializationService.deserialize(allowedWidgetsDict) } @discardableResult func setPermission(_ permission: WidgetPermission, for widget: Widget, success: @escaping () -> Void, failure: @escaping (Error?) -> Void) -> MXHTTPOperation? { guard let widgetEventId = widget.widgetEvent.eventId else { return nil } var widgets = getAllowedWidgets()?.widgets ?? [:] switch permission { case .undefined: widgets.removeValue(forKey: widgetEventId) case .granted: widgets[widgetEventId] = true case .declined: widgets[widgetEventId] = false } // Update only the "widgets" field in the account data var allowedWidgetsDict = getAccountData(forEventType: Settings.allowedWidgets) ?? [:] allowedWidgetsDict[RiotSettingAllowedWidgets.CodingKeys.widgets.rawValue] = widgets return session.setAccountData(allowedWidgetsDict, forType: Settings.allowedWidgets, success: success, failure: failure) } // MARK: Allowed native widgets /// Get the permission for widget that will be displayed natively instead within /// a webview. /// /// - Parameters: /// - widget: the widget /// - url: the url the native implementation will open. Nil will use the url declared in the widget /// - Returns: the permission func permission(forNative widget: Widget, fromUrl url: URL? = nil) -> WidgetPermission { guard let allowedWidgets = getAllowedWidgets() else { return .undefined } guard let type = widget.type, let domain = domainForNativeWidget(widget, fromUrl: url) else { return .undefined } if let value = allowedWidgets.nativeWidgets[type]?[domain] { return value == true ? .granted : .declined } else { return .undefined } } /// Set the permission for widget that is displayed natively. /// /// - Parameters: /// - permission: the permission to set /// - widget: the widget /// - url: the url the native implementation opens. Nil will use the url declared in the widget /// - success: the success block /// - failure: the failure block /// - Returns: a `MXHTTPOperation` instance. @discardableResult func setPermission(_ permission: WidgetPermission, forNative widget: Widget, fromUrl url: URL?, success: @escaping () -> Void, failure: @escaping (Error?) -> Void) -> MXHTTPOperation? { guard let type = widget.type, let domain = domainForNativeWidget(widget, fromUrl: url) else { return nil } var nativeWidgets = getAllowedWidgets()?.nativeWidgets ?? [String: [String: Bool]]() var nativeWidgetsType = nativeWidgets[type] ?? [String: Bool]() switch permission { case .undefined: nativeWidgetsType.removeValue(forKey: domain) case .granted: nativeWidgetsType[domain] = true case .declined: nativeWidgetsType[domain] = false } nativeWidgets[type] = nativeWidgetsType // Update only the "native_widgets" field in the account data var allowedWidgetsDict = getAccountData(forEventType: Settings.allowedWidgets) ?? [:] allowedWidgetsDict[RiotSettingAllowedWidgets.CodingKeys.nativeWidgets.rawValue] = nativeWidgets return session.setAccountData(allowedWidgetsDict, forType: Settings.allowedWidgets, success: success, failure: failure) } // MARK: - Private private func getAccountData(forEventType eventType: String) -> [String: Any]? { return session.accountData.accountData(forEventType: eventType) as? [String: Any] } private func domainForNativeWidget(_ widget: Widget, fromUrl url: URL? = nil) -> String? { var widgetUrl: URL? if let widgetUrlString = widget.url { widgetUrl = URL(string: widgetUrlString) } guard let url = url ?? widgetUrl, let domain = url.host else { return nil } return domain } }
apache-2.0
03351bdca9677301a471e6991ac1a71a
33.643836
145
0.643601
4.998024
false
false
false
false
Jnosh/swift
test/decl/protocol/recursive_requirement.swift
6
2861
// RUN: %target-typecheck-verify-swift // ----- protocol Foo { associatedtype Bar : Foo // expected-error{{type may not reference itself as a requirement}} } struct Oroborous : Foo { typealias Bar = Oroborous } // ----- protocol P { associatedtype A : P // expected-error{{type may not reference itself as a requirement}} } struct X<T: P> { } func f<T : P>(_ z: T) { _ = X<T.A>() } // ----- protocol PP2 { associatedtype A : P2 = Self // expected-error{{type may not reference itself as a requirement}} } protocol P2 : PP2 { associatedtype A = Self } struct X2<T: P2> { } struct Y2 : P2 { typealias A = Y2 } func f<T : P2>(_ z: T) { _ = X2<T.A>() // expected-error{{type 'T.A' does not conform to protocol 'P2'}} } // ----- protocol P3 { associatedtype A: P4 = Self // expected-error{{type may not reference itself as a requirement}} } protocol P4 : P3 {} protocol DeclaredP : P3, // expected-warning{{redundant conformance constraint 'Self': 'P3'}} P4 {} // expected-note{{conformance constraint 'Self': 'P3' implied here}} struct Y3 : DeclaredP { } struct X3<T:P4> {} func f2<T:P4>(_ a: T) { _ = X3<T.A>() } f2(Y3()) // ----- protocol Alpha { associatedtype Beta: Gamma } protocol Gamma { associatedtype Delta: Alpha } // FIXME: Redundancy diagnostics are odd here. struct Epsilon<T: Alpha, // expected-note{{conformance constraint 'U': 'Gamma' implied here}} // expected-warning@-1{{redundant conformance constraint 'T': 'Alpha'}} U: Gamma> // expected-warning{{redundant conformance constraint 'U': 'Gamma'}} // expected-note@-1{{conformance constraint 'T': 'Alpha' implied here}} where T.Beta == U, U.Delta == T {} // ----- protocol AsExistentialA { var delegate : AsExistentialB? { get } } protocol AsExistentialB { func aMethod(_ object : AsExistentialA) } protocol AsExistentialAssocTypeA { var delegate : AsExistentialAssocTypeB? { get } // expected-error {{protocol 'AsExistentialAssocTypeB' can only be used as a generic constraint because it has Self or associated type requirements}} } protocol AsExistentialAssocTypeB { func aMethod(_ object : AsExistentialAssocTypeA) associatedtype Bar } protocol AsExistentialAssocTypeAgainA { var delegate : AsExistentialAssocTypeAgainB? { get } associatedtype Bar } protocol AsExistentialAssocTypeAgainB { func aMethod(_ object : AsExistentialAssocTypeAgainA) // expected-error {{protocol 'AsExistentialAssocTypeAgainA' can only be used as a generic constraint because it has Self or associated type requirements}} } // SR-547 protocol A { associatedtype B1: B associatedtype C1: C mutating func addObserver(_ observer: B1, forProperty: C1) } protocol C { } protocol B { associatedtype BA: A associatedtype BC: C func observeChangeOfProperty(_ property: BC, observable: BA) }
apache-2.0
f2027a15d978183c90f4a28e3293d71c
20.839695
210
0.682978
3.612374
false
false
false
false
crossroadlabs/ExpressCommandLine
swift-express/Commands/Init/Init.swift
1
3936
//===--- Init.swift -------------------------------===// //Copyright (c) 2015-2016 Daniel Leping (dileping) // //This file is part of Swift Express Command Line // //Swift Express Command Line 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. // //Swift Express Command Line 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 Swift Express Command Line. If not, see <http://www.gnu.org/licenses/>. // //===---------------------------------------------===// import Commandant import Result import Foundation struct InitStep : Step { let dependsOn:[Step] = [CreateTempDirectory(), CloneGitRepository(), CopyDirectoryContents(excludeList: ["^\\.git$", "^LICENSE$", "^NOTICE$", "^README.md$"]), RenameXcodeProject(), RenamePackageSwift()] func run(params: [String: Any], combinedOutput: StepResponse) throws -> [String: Any] { // Nothing to do. All tasks done return [String: Any]() } func cleanup(params:[String: Any], output: StepResponse) throws { // Nothing to do } func callParams(ownParams: [String: Any], forStep: Step, previousStepsOutput: StepResponse) throws -> [String: Any] { switch forStep { case _ as CloneGitRepository: return ["repositoryURL": ownParams["template"]!, "outputFolder": previousStepsOutput["tempDirectory"]!] case _ as CreateTempDirectory: return [String: Any]() case _ as CopyDirectoryContents: let path = (ownParams["path"]! as! String).addPathComponent(ownParams["name"]! as! String) return ["inputFolder": previousStepsOutput["clonedFolder"]!, "outputFolder": path] case _ as RenameXcodeProject: return ["workingFolder": previousStepsOutput["outputFolder"]!, "newProjectName": ownParams["name"]!] case _ as RenamePackageSwift: return ["workingFolder": previousStepsOutput["outputFolder"]!, "newProjectName": ownParams["name"]!, "projectName":previousStepsOutput["oldProjectName"]!] case _ as CarthageInstallLibs: return ["workingFolder": previousStepsOutput["outputFolder"]!] default: throw SwiftExpressError.BadOptions(message: "Wrong step") } } } struct InitCommand: StepCommand { typealias Options = InitCommandOptions let verb = "init" let function = "Creates new Express application project" func step(opts: Options) -> Step { return InitStep() } func getOptions(opts: Options) -> Result<[String:Any], SwiftExpressError> { return Result(["name": opts.name, "template": opts.template, "path": opts.path.standardizedPath()]) } } struct InitCommandOptions : OptionsType { let name: String let template: String let path: String static func create(template: String) -> (String -> (String -> InitCommandOptions)) { return { (path: String) in { (name: String) in InitCommandOptions(name: name, template: template, path: path) } } } static func evaluate(m: CommandMode) -> Result<InitCommandOptions, CommandantError<SwiftExpressError>> { return create <*> m <| Option(key: "template", defaultValue: "https://github.com/crossroadlabs/ExpressTemplate.git", usage: "git url for project template") <*> m <| Option(key: "path", defaultValue: ".", usage: "output directory") <*> m <| Argument(usage: "name of application") } }
gpl-3.0
05d6d2c41307a1c9ee4ec6917fd993b5
41.322581
166
0.644563
4.646989
false
false
false
false
haawa799/WaniKit2
Sources/WaniKit/WaniKit operations/CriticalItems/ParseCriticalItemsOperation.swift
2
1072
// // ParseUserInfoOperation.swift // Pods // // Created by Andriy K. on 12/14/15. // // import Foundation public typealias CriticalItemsResponse = (userInfo: UserInfo?, criticalItems: CriticalItems?) public typealias CriticalItemsResponseHandler = (Result<CriticalItemsResponse, NSError>) -> Void public class ParseCriticalItemsOperation: ParseOperation<CriticalItemsResponse> { override init(cacheFile: NSURL, handler: ResponseHandler) { super.init(cacheFile: cacheFile, handler: handler) name = "Parse Critical items list" } override func parsedValue(rootDictionary: NSDictionary?) -> CriticalItemsResponse? { var user: UserInfo? if let userInfo = rootDictionary?[WaniKitConstants.ResponseKeys.UserInfoKey] as? NSDictionary { user = UserInfo(dict: userInfo) } var criticalItems: CriticalItems? if let requestedInfo = rootDictionary?[WaniKitConstants.ResponseKeys.RequestedInfoKey] as? NSArray { criticalItems = CriticalItems(array: requestedInfo) } return (user, criticalItems) } }
mit
059ad287a62f56a4f6d128fac47c1a2f
27.972973
104
0.735075
4.253968
false
false
false
false
PureSwift/Bluetooth
Sources/BluetoothHCI/HCIReadDeviceAddress.swift
1
1479
// // HCIReadDeviceAddress.swift // Bluetooth // // Created by Alsey Coleman Miller on 6/14/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation // MARK: - Method public extension BluetoothHostControllerInterface { /// Read Device Address func readDeviceAddress(timeout: HCICommandTimeout = .default) async throws -> BluetoothAddress { return try await deviceRequest(HCIReadDeviceAddress.self, timeout: timeout).address } } // MARK: - Return Parameter /// Read Device Address /// /// On a BR/EDR Controller, this command reads the Bluetooth Controller address (BD_ADDR). /// /// On an LE Controller, this command shall read the Public Device Address. /// If this Controller does not have a Public Device Address, the value 0x000000000000 shall be returned. /// /// - Note: On a BR/EDR/LE Controller, the public address shall be the same as the `BD_ADDR`. @frozen public struct HCIReadDeviceAddress: HCICommandReturnParameter { public static let command = InformationalCommand.readDeviceAddress public static let length = 6 /// The Bluetooth address of the device. public let address: BluetoothAddress public init?(data: Data) { guard data.count == type(of: self).length else { return nil } self.address = BluetoothAddress(littleEndian: BluetoothAddress(bytes: (data[0], data[1], data[2], data[3], data[4], data[5]))) } }
mit
4cfb8355d285201903b3a33b142528c5
29.163265
134
0.688092
4.321637
false
false
false
false
PureSwift/Bluetooth
Sources/BluetoothHCI/HCILEAdvertisingReport.swift
1
5042
// // HCILEAdvertisingReport.swift // Bluetooth // // Created by Alsey Coleman Miller on 6/14/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation /// LE Advertising Report Event /// /// The LE Advertising Report event indicates that a Bluetooth device /// or multiple Bluetooth devices have responded to an active scan /// or received some information during a passive scan. /// The Controller may queue these advertising reports and send /// information from multiple devices in one LE Advertising Report event. @frozen public struct HCILEAdvertisingReport: HCIEventParameter { public static let event = LowEnergyEvent.advertisingReport // 0x02 public static let length = 1 + Report.length // must have at least one report public let reports: [Report] public init?(data: Data) { guard data.count >= type(of: self).length else { return nil } // Number of responses in event. let reportCount = Int(data[0]) // Num_Reports // 0x01 - 0x19 guard reportCount >= 0x01, reportCount <= 0x19 else { return nil } var reports = [Report]() reports.reserveCapacity(reportCount) var offset = 1 for _ in 0 ..< reportCount { let reportBytes = data.suffixNoCopy(from: offset) guard let report = Report(data: reportBytes) else { return nil } offset += Report.length + report.responseData.count reports.append(report) } self.reports = reports } public struct Report { public static let length = 1 + 1 + 6 + 1 + /* 0 - 31 */ 0 + 1 public let event: Event public let addressType: LowEnergyAddressType // Address_Type public let address: BluetoothAddress // Address /// Advertising or scan response data public let responseData: LowEnergyAdvertisingData // Data /// RSSI /// /// Size: 1 Octet (signed integer) /// Range: -127 ≤ N ≤ +20 /// Units: dBm public let rssi: RSSI? // RSSI public init?(data: Data) { guard data.count >= Report.length else { return nil } // parse enums guard let event = Event(rawValue: data[0]), let addressType = LowEnergyAddressType(rawValue: data[1]) else { return nil } let address = BluetoothAddress(littleEndian: BluetoothAddress(bytes: (data[2], data[3], data[4], data[5], data[6], data[7]))) let length = Int(data[8]) self.event = event self.addressType = addressType self.address = address guard data.count >= (9 + length) else { return nil } let responseData = data.subdataNoCopy(in: 9 ..< (9 + length)) assert(responseData.count == length) guard let advertisingData = LowEnergyAdvertisingData(data: responseData) else { return nil } self.responseData = advertisingData // not enough bytes guard data.count == (Report.length + length) else { return nil } self.rssi = RSSI(rawValue: Int8(bitPattern: data[9 + length])) } /// Low Energy Advertising Event public enum Event: UInt8 { // Event_Type /// Connectable undirected advertising event case undirected = 0x00 // ADV_IND /// Connectable directed advertising event case directed = 0x01 // ADV_DIRECT_IND /// Scannable undirected advertising event case scannable = 0x02 // ADV_SCAN_IND /// Non-connectable undirected advertising event case nonConnectable = 0x03 // ADV_NONCONN_IND /// Scan Response case scanResponse = 0x04 // SCAN_RSP /// Whether the event is connectable. public var isConnectable: Bool { switch self { case .undirected: return true case .directed: return true case .scannable: return true // if you can scan, you can connect case .nonConnectable: return false case .scanResponse: return true } } } } }
mit
07efca5bdc42192a468cb05bbad01993
32.357616
87
0.50129
5.421959
false
false
false
false
pattogato/WGUtils
WGUtils/WGDeviceUtils.swift
1
6462
// // Device.swift // WGUtils // // Created by Bence Pattogato on 18/02/16. // Copyright © 2016 Wintergarden. All rights reserved. // import UIKit struct Device { // MARK: - Singletons static var TheCurrentDevice: UIDevice { struct Singleton { static let device = UIDevice.currentDevice() } return Singleton.device } static var TheCurrentDeviceVersion: Float { struct Singleton { static let stringVersion = UIDevice.currentDevice().systemVersion as NSString static let version = stringVersion.floatValue } return Singleton.version } static var TheCurrentDeviceHeight: CGFloat { struct Singleton { static let height = UIScreen.mainScreen().bounds.size.height } return Singleton.height } // MARK: - Device Idiom Checks static var PHONE_OR_PAD: String { if isPhone() { return "iPhone" } else if isPad() { return "iPad" } return "Not iPhone nor iPad" } static var DEBUG_OR_RELEASE: String { #if DEBUG return "Debug" #else return "Release" #endif } static var SIMULATOR_OR_DEVICE: String { #if (arch(i386) || arch(x86_64)) && os(iOS) return "Simulator" #else return "Device" #endif } static func isPhone() -> Bool { return TheCurrentDevice.userInterfaceIdiom == .Phone } static func isPad() -> Bool { return TheCurrentDevice.userInterfaceIdiom == .Pad } static func isDebug() -> Bool { return DEBUG_OR_RELEASE == "Debug" } static func isRelease() -> Bool { return DEBUG_OR_RELEASE == "Release" } static func isSimulator() -> Bool { return SIMULATOR_OR_DEVICE == "Simulator" } static func isDevice() -> Bool { return SIMULATOR_OR_DEVICE == "Device" } // MARK: - Device Version Checks enum Versions: Float { case Five = 5.0 case Six = 6.0 case Seven = 7.0 case Eight = 8.0 case Nine = 9.0 } static func isVersion(version: Versions) -> Bool { return TheCurrentDeviceVersion >= version.rawValue && TheCurrentDeviceVersion < (version.rawValue + 1.0) } static func isVersionOrLater(version: Versions) -> Bool { return TheCurrentDeviceVersion >= version.rawValue } static func isVersionOrEarlier(version: Versions) -> Bool { return TheCurrentDeviceVersion < (version.rawValue + 1.0) } static var CURRENT_VERSION: String { return "\(TheCurrentDeviceVersion)" } // MARK: iOS 7 Checks static func IS_OS_7() -> Bool { return isVersion(.Seven) } static func IS_OS_7_OR_LATER() -> Bool { return isVersionOrLater(.Seven) } static func IS_OS_7_OR_EARLIER() -> Bool { return isVersionOrEarlier(.Seven) } // MARK: iOS 8 Checks static func IS_OS_8() -> Bool { return isVersion(.Eight) } static func IS_OS_8_OR_LATER() -> Bool { return isVersionOrLater(.Eight) } static func IS_OS_8_OR_EARLIER() -> Bool { return isVersionOrEarlier(.Eight) } // MARK: iOS 9 Checks static func IS_OS_9() -> Bool { return isVersion(.Nine) } static func IS_OS_9_OR_LATER() -> Bool { return isVersionOrLater(.Nine) } static func IS_OS_9_OR_EARLIER() -> Bool { return isVersionOrEarlier(.Nine) } // MARK: - Device Size Checks enum Heights: CGFloat { case Inches_3_5 = 480 case Inches_4 = 568 case Inches_4_7 = 667 case Inches_5_5 = 736 } static func isSize(height: Heights) -> Bool { return TheCurrentDeviceHeight == height.rawValue } static func isSizeOrLarger(height: Heights) -> Bool { return TheCurrentDeviceHeight >= height.rawValue } static func isSizeOrSmaller(height: Heights) -> Bool { return TheCurrentDeviceHeight <= height.rawValue } static var CURRENT_SIZE: String { if IS_3_5_INCHES() { return "3.5 Inches" } else if IS_4_INCHES() { return "4 Inches" } else if IS_4_7_INCHES() { return "4.7 Inches" } else if IS_5_5_INCHES() { return "5.5 Inches" } return "\(TheCurrentDeviceHeight) Points" } // MARK: Retina Check static func IS_RETINA() -> Bool { return UIScreen.mainScreen().respondsToSelector("scale") } // MARK: 3.5 Inch Checks static func IS_3_5_INCHES() -> Bool { return isPhone() && isSize(.Inches_3_5) } static func IS_3_5_INCHES_OR_LARGER() -> Bool { return isPhone() && isSizeOrLarger(.Inches_3_5) } static func IS_3_5_INCHES_OR_SMALLER() -> Bool { return isPhone() && isSizeOrSmaller(.Inches_3_5) } // MARK: 4 Inch Checks static func IS_4_INCHES() -> Bool { return isPhone() && isSize(.Inches_4) } static func IS_4_INCHES_OR_LARGER() -> Bool { return isPhone() && isSizeOrLarger(.Inches_4) } static func IS_4_INCHES_OR_SMALLER() -> Bool { return isPhone() && isSizeOrSmaller(.Inches_4) } // MARK: 4.7 Inch Checks static func IS_4_7_INCHES() -> Bool { return isPhone() && isSize(.Inches_4_7) } static func IS_4_7_INCHES_OR_LARGER() -> Bool { return isPhone() && isSizeOrLarger(.Inches_4_7) } static func IS_4_7_INCHES_OR_SMALLER() -> Bool { return isPhone() && isSizeOrLarger(.Inches_4_7) } // MARK: 5.5 Inch Checks static func IS_5_5_INCHES() -> Bool { return isPhone() && isSize(.Inches_5_5) } static func IS_5_5_INCHES_OR_LARGER() -> Bool { return isPhone() && isSizeOrLarger(.Inches_5_5) } static func IS_5_5_INCHES_OR_SMALLER() -> Bool { return isPhone() && isSizeOrLarger(.Inches_5_5) } // MARK: - International Checks static var CURRENT_REGION: String { return NSLocale.currentLocale().objectForKey(NSLocaleCountryCode) as! String } }
mit
f1b249a4aedede1a66d1b3ef4d9c06fd
24.046512
112
0.556261
3.9809
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/Pods/XCGLogger/Sources/XCGLogger/Filters/DevFilter.swift
27
1289
// // DevFilter.swift // XCGLogger: https://github.com/DaveWoodCom/XCGLogger // // Created by Dave Wood on 2016-09-01. // Copyright © 2016 Dave Wood, Cerebral Gardens. // Some rights reserved: https://github.com/DaveWoodCom/XCGLogger/blob/master/LICENSE.txt // // MARK: - DevFilter /// Filter log messages by devs open class DevFilter: UserInfoFilter { /// Initializer to create an inclusion list of devs to match against /// /// Note: Only log messages with a specific dev will be logged, all others will be excluded /// /// - Parameters: /// - devs: Set or Array of devs to match against. /// public override init<S: Sequence>(includeFrom devs: S) where S.Iterator.Element == String { super.init(includeFrom: devs) userInfoKey = XCGLogger.Constants.userInfoKeyDevs } /// Initializer to create an exclusion list of devs to match against /// /// Note: Log messages with a specific dev will be excluded from logging /// /// - Parameters: /// - devs: Set or Array of devs to match against. /// public override init<S: Sequence>(excludeFrom devs: S) where S.Iterator.Element == String { super.init(excludeFrom: devs) userInfoKey = XCGLogger.Constants.userInfoKeyDevs } }
mit
054326e8287cfdc2e5cd3e6c45d9683c
33.810811
95
0.666149
4.063091
false
false
false
false
ppraveentr/MobileCore
Sources/AppTheming/ThemeComponents/UISearchBar+Theme.swift
1
5434
// // SearchBar+Extension.swift // MobileCore-AppTheming // // Created by Praveen Prabhakar on 02/10/18. // Copyright © 2018 Praveen Prabhakar. All rights reserved. // #if canImport(CoreUtility) import CoreUtility #endif import Foundation import UIKit // MARK: AssociatedKey private extension AssociatedKey { static var searchUITextField = "searchUITextField" static var searchBarAttributes = "searchBarAttributes" } // MARK: UISearchBar extension UISearchBar: ThemeProtocol { public func updateTheme(_ theme: ThemeModel) { searchBarStyle = .prominent isTranslucent = false var tintColor: UIColor? var textcolor: UIColor? var font: UIFont? for (kind, value) in theme { switch kind { case ThemeKey.barTintColor.rawValue: if let barTintColor = getColor(value as? String) { self.barTintColor = barTintColor self.backgroundImage = UIImage() self.backgroundColor = .clear } case ThemeKey.tintColor.rawValue: tintColor = getColor(value as? String) case ThemeKey.textcolor.rawValue: textcolor = getColor(value as? String) case ThemeKey.textfont.rawValue: font = getFont(value as? String) default: break } } addObserver(self, forKeyPath: #keyPath(UISearchBar.placeholder), options: [.new], context: nil) configure(tintColor: tintColor, textColor: textcolor, font: font) } // MARK: - Key-Value Observing // swiftlint:disable block_based_kvo override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) { guard let searchField = searchUITextField, let att = searchBarAttributes, !att.isEmpty else { return } if keyPath == #keyPath(UISearchBar.placeholder), let sting = searchField.attributedPlaceholder?.string { // Update placeHolder searchField.attributedPlaceholder = NSAttributedString(string: sting, attributes: att) } } // swiftlint:enable block_based_kvo } // MARK: UISearchBar private extension UISearchBar { // MARK: SearchTextField var searchUITextField: UITextField? { get { if let textField: UITextField = AssociatedObject.getAssociated(self, key: &AssociatedKey.searchUITextField) { return textField } let textField: UITextField? = self.findInSubView() self.searchUITextField = textField return textField } set { AssociatedObject<UITextField>.setAssociated(self, value: newValue, key: &AssociatedKey.searchUITextField) } } // MARK: SearchTextField var searchBarAttributes: AttributedDictionary? { get { AssociatedObject.getAssociated(self, key: &AssociatedKey.searchBarAttributes) } set { AssociatedObject<AttributedDictionary>.setAssociated(self, value: newValue, key: &AssociatedKey.searchBarAttributes) } } func configure(tintColor: UIColor? = nil, textColor: UIColor? = nil, font: UIFont? = nil) { guard let tintColor = tintColor else { return } self.tintColor = tintColor guard let textField: UITextField = searchUITextField else { return } if let glassIconView = textField.leftView as? UIImageView { glassIconView.image = glassIconView.image?.withRenderingMode(.alwaysTemplate) glassIconView.tintColor = tintColor } if let clearButton = textField.value(forKey: "clearButton") as? UIButton { clearButton.setImage(clearButton.imageView?.image?.withRenderingMode(.automatic), for: .normal) clearButton.tintColor = tintColor } update(font: font, textColor: textColor) } func update(font: UIFont?, textColor: UIColor?) { // Find the index of the search field in the search bar subviews. if let searchField = searchUITextField { // Set its frame. searchField.frame = CGRect(x: 5.0, y: 5.0, width: frame.width - 10.0, height: frame.height - 10.0) var att = AttributedDictionary() // Set the font and text color of the search field. if font != nil { searchField.font = font } if let font = searchField.font?.withSize((searchField.font?.pointSize)! - 1) { att[.font] = font } if textColor != nil { searchField.textColor = textColor att[.foregroundColor] = textColor // let label = UILabel.appearance(whenContainedInInstancesOf: [UISearchBar.self]) // label.textColor = textColor } if let sting = searchField.attributedPlaceholder?.string, !att.isEmpty { searchField.attributedPlaceholder = NSAttributedString(string: sting, attributes: att) } // Save preference self.searchBarAttributes = att // Set the background color of the search field. searchField.backgroundColor = .clear } } }
mit
63c1cf9244da518042c210e774874ffe
37.531915
155
0.613841
5.264535
false
false
false
false
alyakan/SimpleHttp
Sources/SimpleHTTPRequest.swift
1
838
// // SimpleHTTPRequest.swift // SimpleHTTP // // Created by Aly Yakan on 5/5/17. // Copyright © 2017 cookiecutter-swift. All rights reserved. // import Foundation public enum HTTPMethod: String { case get = "GET" case post = "POSt" case put = "PUT" case delete = "DELETE" } public class SimpleHTTPRequest { public private(set) var url: URL! public private(set) var httpMethod: HTTPMethod! public private(set) var parameters: NSDictionary? public private(set) var headers: Dictionary<String, String>? public init() {} public init?(url: URL, httpMethod: HTTPMethod, parameters: NSDictionary? = nil, headers: Dictionary<String, String>? = nil) { self.url = url self.httpMethod = httpMethod self.parameters = parameters self.headers = headers } }
mit
2600b63545af99c91b552b071cc966de
25.15625
129
0.659498
4.043478
false
false
false
false
ello/ello-ios
ShareExtension/ExtensionItemPreview.swift
1
821
//// /// ExtensionItemPreview.swift // struct ExtensionItemPreview { let image: UIImage? let imagePath: URL? let text: String? let gifData: Data? init(image: UIImage? = nil, imagePath: URL? = nil, text: String? = nil, gifData: Data? = nil) { self.image = image self.imagePath = imagePath self.text = text self.gifData = gifData } var description: String { return "image: \(String(describing: self.image)), imagePath: \(String(describing: self.imagePath)) text: \(String(describing: self.text)) gif: \(self.gifData == nil)" } } func == (lhs: ExtensionItemPreview, rhs: ExtensionItemPreview) -> Bool { return lhs.image == rhs.image && lhs.imagePath == rhs.imagePath && lhs.text == rhs.text && lhs.gifData == rhs.gifData }
mit
01ddca52f74b962163598ac689e5b880
29.407407
171
0.618758
3.800926
false
false
false
false
oyvkva/KapabelSDK
Source/KapabelGlobals.swift
1
4170
// // KapabelGlobals.swift // KapabelSDK // // Created by Øyvind Kvanes on 19/01/2017. // Copyright © 2017 Kvanes AS. All rights reserved. // // Variables var KAPLOG = false var KAPTOAST = true var KAPGATE = true var KAPAPPID = 0 var KAPGROUPNAME = "" var APITOKEN = "" var USERTOKEN = "" var USERNAME = "" var SESSIONID = 0 var CURRENTUSER = KapabelUser(logInDict: ["token":"0"]) // Contants let BaseURL = "https://kapabel.no/v1/api/" let AppStoreURL = URL(string: "itms://itunes.apple.com/no/app/kapabel-for-students-parents/id1140067858?mt=8") let SessionAliveTime = 3600.0 // Seconds a session stays alive until a new is created // UserDefault keys let AppTaskListKey = "TheKapabelTasks" let TokenNameKey = "TheKapabelToken" let SessionNameKey = "TheKapabelSession" let SavedUserNameKey = "TheKapabelSavedUserName" let SessionSaveDateKey = "TheKapabelSessionSaveDate" // MARK: Helper methods func errorWith(code: Int){ if (code == 401){ logMs("Wrong API key") } else if (code == 404){ logMs("URL not found") } else if (code == 1){ logMs("Wrong token, please log in again") } else if (code == 7){ logMs("Task already closed") } else if (code == 14){ logMs("TaskID does not exist") } else if (code == -1009){ logMs("Offline mode for: \(USERNAME)") } else { logMs("Unknown error \(code)") } } func headers() -> [String: String]{ return [ "Authorization": "Token token=\(APITOKEN)", "Content-Type": "application/x-www-form-urlencoded" ] } func convertStringToDictionary(_ text: String) -> [String:AnyObject]? { if let data = text.data(using: String.Encoding.utf8) { do { let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:AnyObject] return json } catch { logMs("Error converting string") } } return nil } func urlScheme() -> String { let info = Bundle.main.infoDictionary?["CFBundleURLTypes"] as? [AnyObject] if let urlSchemes = info?[0]["CFBundleURLSchemes"] { if let schemes = urlSchemes as? NSArray{ if schemes.count > 0 { return (schemes[0] as? String)! } } } return "http://kapabel.io" } // MARK: Logging func logMs(_ msg: String){ if (KAPLOG){ print("KapabelSDK: \(msg)") } } // MARK: Toasts func displayWelcomeToastFor(name: String) { if (KAPTOAST){ let toastMessage = "\("Logged in as".kapLocalized) \(name)." KapabelToast.make(toastMessage).show() } } func displayErrorToast() { if (KAPTOAST){ let toastMessage = "Login failed.".kapLocalized KapabelToast.make(toastMessage).show() } } func displayOfflineModeToastFor(user: String) { if (KAPTOAST){ let toastMessage = "\("Results will be saved offline for".kapLocalized) \(user)." KapabelToast.make(toastMessage).show() let tasksLeft = KapabelTaskManager.instance.getTasksArrayCount() if tasksLeft > 1 { let toastMessage = "\("Offline results saved".kapLocalized): \(tasksLeft)" KapabelToast.make(toastMessage).show() } KapabelToast.make("The results will be submitted when you go online.".kapLocalized).show() } } func displayLoggedOutToast() { if (KAPTOAST){ let toastMessage = "Not logged in. Please log in again.".kapLocalized KapabelToast.make(toastMessage).show() } } func displaySubmitToast(tasksLeft: Int) { if (KAPTOAST){ let toastMessage = "\("Submitting".kapLocalized) \(tasksLeft) \("results".kapLocalized)..." KapabelToast.make(toastMessage).show() } } func displaySubmitDoneToast() { if (KAPTOAST){ let toastMessage = "Results submitted.".kapLocalized KapabelToast.make(toastMessage).show() } } // MARK: String extension extension String { var kapLocalized: String { return NSLocalizedString(self, tableName: "Kapabel", bundle: Bundle.main, value: "", comment: "") } }
mit
a9e8821df98372ed6499ccc73930bbb8
24.260606
119
0.62524
3.577682
false
false
false
false
rhodgkins/RDHCommonCrypto
RDHCommonCrypto/KeyDerivation.swift
1
7719
// // KeyDerivation.swift // RDHCommonCrypto // // Created by Richard Hodgkins on 21/09/2014. // Copyright (c) 2014 Rich Hodgkins. All rights reserved. // import Foundation public extension String { public var length: Int { return (self as NSString).length } } private extension CCPseudoRandomAlgorithm { var defaultDerivedKeyLength: Int { switch(Int(self)) { case kCCPRFHmacAlgSHA1: return 160 / 8 case kCCPRFHmacAlgSHA224: return 224 / 8 case kCCPRFHmacAlgSHA256: return 256 / 8 case kCCPRFHmacAlgSHA384: return 384 / 8 case kCCPRFHmacAlgSHA512: return 512 / 8 default: return 128 / 8 } } } private extension RDHPseudoRandomAlgorithm { var defaultDerivedKeyLength: Int { return self.toRaw().defaultDerivedKeyLength } } // Don't extend NSObject as there are no instance methods @objc public class KeyDerivation { /// Cannot instantiate this class private init() { assertionFailure("KeyDerivation cannot be instantiated") } // MARK: - PBKDF2: Key derivation /// Instead of specifiying the number of rounds a duration can be provided when using PBKDF2. class func PBKDF2UsingPassword(password: String!, withSalt salt: NSData?, pseudoRandomAlgorithm prf: RDHPseudoRandomAlgorithm, targettedDuration: NSTimeInterval, derivedKeyLength: Int? = nil) -> (derivedKey: NSData?, error: NSError?) { let algorithm = RDHPBKDFAlgorithm.PBKDF2 return PBKDF2UsingPassword(password, withSalt: salt, pseudoRandomAlgorithm: prf, targettedDuration: targettedDuration, derivedKeyLength: derivedKeyLength) } class func PBKDF2UsingPassword(password: String!, withSalt salt: NSData?, pseudoRandomAlgorithm prf: RDHPseudoRandomAlgorithm, numberOfRounds rounds: Int = 1, derivedKeyLength: Int? = nil) -> (derivedKey: NSData?, error: NSError?) { return PBKDFWithAlgorithm(RDHPBKDFAlgorithm.PBKDF2, usingPassword: password, withSalt: salt, pseudoRandomAlgorithm: prf, numberOfRounds: rounds, derivedKeyLength: derivedKeyLength) } // MARK: - Generic PBKDF: Key derivation /// Instead of specifiying the number of rounds a duration can be provided. class func PBKDFWithAlgorithm(algorithm: RDHPBKDFAlgorithm, usingPassword password: String!, withSalt salt: NSData?, pseudoRandomAlgorithm prf: RDHPseudoRandomAlgorithm, targettedDuration: NSTimeInterval, derivedKeyLength: Int? = nil) -> (derivedKey: NSData?, error: NSError?) { let rounds = calibratePBKDFWithAlgorithm(algorithm, password: password, salt: salt, pseudoRandomAlgorithm: prf, targettedDuration: targettedDuration, derivedKeyLength: derivedKeyLength) return PBKDFWithAlgorithm(RDHPBKDFAlgorithm.PBKDF2, usingPassword: password, withSalt: salt, pseudoRandomAlgorithm: prf, numberOfRounds: rounds, derivedKeyLength: derivedKeyLength) } /// @returns the derived key data data, if this is nil then error is set. class func PBKDFWithAlgorithm(algorithm: RDHPBKDFAlgorithm, usingPassword password: String!, withSalt salt: NSData?, pseudoRandomAlgorithm prf: RDHPseudoRandomAlgorithm, numberOfRounds rounds: Int = 1, derivedKeyLength: Int? = nil) -> (derivedKey: NSData?, error: NSError?) { var usedDerivedKeyLength = derivedKeyLength ?? prf.defaultDerivedKeyLength var resultantError: NSError? let resultantDerivedKey = PBKDFWithAlgorithm(algorithm.toRaw(), password: password, salt: salt, pseudoRandomAlgorithm: prf.toRaw(), numberOfRounds: rounds, derivedKeyLength: usedDerivedKeyLength, error: &resultantError) return (resultantDerivedKey, resultantError) } /// Objective-C method. Marked as internal for Swift as there is a Swift specific function. @returns the encrypted data, if this is nil then error is set. @objc class func PBKDFWithAlgorithm(algorithm: CCPBKDFAlgorithm, password: String!, salt: NSData?, pseudoRandomAlgorithm prf: CCPseudoRandomAlgorithm, numberOfRounds rounds: Int, derivedKeyLength: Int, error: NSErrorPointer = nil) -> NSData? { assert(rounds > 0, "Number of rounds must be greater than 0: \(rounds)") assert(derivedKeyLength > 0, "The expected derived key length must be greater than 0: \(derivedKeyLength)") // Salt var saltLength: UInt = 0 var saltBytes: UnsafePointer<UInt8> = nil if let actualSalt = salt { saltLength = UInt(actualSalt.length) saltBytes = UnsafePointer<UInt8>(actualSalt.bytes) } // Derived key var derivedKey: NSMutableData? = NSMutableData(length: derivedKeyLength) let derivedKeyChars = UnsafeMutablePointer<UInt8>(derivedKey!.mutableBytes) // Operation let status = RDHStatus.statusForOperation { CCKeyDerivationPBKDF(algorithm, password, strlen(password), saltBytes, saltLength, prf, uint(rounds), derivedKeyChars, UInt(derivedKeyLength)) } if (status != RDHStatus.Success) { derivedKey!.length = 0 derivedKey = nil } if (error != nil) { error.memory = status.error() } return derivedKey } // MARK: - PBKDF2: Round calibration /// @returns the number of iterations to use for the desired processing time when using PBKDF2. public class func calibratePBKDF2UsingPassword(password: String!, salt: NSData?, pseudoRandomAlgorithm prf: RDHPseudoRandomAlgorithm, targettedDuration: NSTimeInterval, derivedKeyLength: Int? = nil) -> Int { return calibratePBKDFWithAlgorithm(RDHPBKDFAlgorithm.PBKDF2, password: password, salt: salt, pseudoRandomAlgorithm: prf, targettedDuration: targettedDuration, derivedKeyLength: derivedKeyLength) } // MARK: - Generic PBKDF: Round calibration /// @returns the number of iterations to use for the desired processing time. public class func calibratePBKDFWithAlgorithm(algorithm: RDHPBKDFAlgorithm, password: String!, salt: NSData?, pseudoRandomAlgorithm prf: RDHPseudoRandomAlgorithm, targettedDuration: NSTimeInterval, derivedKeyLength: Int? = nil) -> Int { var usedDerivedKeyLength = derivedKeyLength ?? prf.defaultDerivedKeyLength return calibratePBKDFWithAlgorithm(algorithm.toRaw(), password: password, salt: salt, pseudoRandomAlgorithm: prf.toRaw(), targettedDuration: targettedDuration, derivedKeyLength: usedDerivedKeyLength) } /// Objective-C method. Marked as internal for Swift as there is a Swift specific function. @returns the number of iterations to use for the desired processing time. @objc class func calibratePBKDFWithAlgorithm(algorithm: CCPBKDFAlgorithm, password: String!, salt: NSData?, pseudoRandomAlgorithm prf: CCPseudoRandomAlgorithm, targettedDuration: NSTimeInterval, derivedKeyLength: Int) -> Int { assert(derivedKeyLength > 0, "The expected derived key length must be greater than 0: \(derivedKeyLength)") assert(targettedDuration > 0, "The targetted duration must be greater than 0: \(targettedDuration)") // Salt var saltLength = salt?.length ?? 0 // Duration let durationMillis = UInt32(ceil(targettedDuration * 1000)) // Operation let rounds = CCCalibratePBKDF(algorithm, strlen(password), UInt(saltLength), prf, UInt(derivedKeyLength), durationMillis) return Int(rounds) } }
mit
240d1b713a095dbeeba5577f5e514d31
48.806452
282
0.696722
4.655609
false
false
false
false
devcarlos/RappiApp
RappiApp/AppDelegate.swift
1
6790
// // AppDelegate.swift // RappiApp // // Created by Carlos Alcala on 7/1/16. // Copyright © 2016 Carlos Alcala. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. self.setupNavigationBar() if InternetHandler.shared.isReachable() { NSLog("INTERNET REACHABLE") } 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:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.kurrentap.ToddTest" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("RappiApp", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("RappiApp.sqlite") print("SQLITE: \(url)") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } func setupNavigationBar() { // custom navigation bar settings UINavigationBar.appearance().setBackgroundImage(UIImage(), forBarMetrics: .Default) UINavigationBar.appearance().shadowImage = UIImage() UINavigationBar.appearance().tintColor = UIColor.whiteColor() UINavigationBar.appearance().backgroundColor = UIColor.clearColor() UINavigationBar.appearance().translucent = false } }
mit
10867bda01506dc18fa9a780e6e25acd
51.223077
291
0.703933
5.960492
false
false
false
false
esttorhe/RxSwift
RxSwift/RxSwift/Observables/Implementations/Merge.swift
1
8895
// // Merge.swift // Rx // // Created by Krunoslav Zaher on 3/28/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation // sequential class Merge_Iter<O: ObserverType> : ObserverType { typealias Element = O.Element typealias DisposeKey = Bag<Disposable>.KeyType let parent: Merge_<O> let disposeKey: DisposeKey init(parent: Merge_<O>, disposeKey: DisposeKey) { self.parent = parent self.disposeKey = disposeKey } func on(event: Event<Element>) { switch event { case .Next: parent.lock.performLocked { trySend(parent.observer, event) } case .Error: parent.lock.performLocked { trySend(parent.observer, event) self.parent.dispose() } case .Completed: let group = parent.mergeState.group group.removeDisposable(disposeKey) self.parent.lock.performLocked { let state = parent.mergeState if state.stopped && state.group.count == 1 { trySendCompleted(parent.observer) self.parent.dispose() } } } } } class Merge_<O: ObserverType> : Sink<O>, ObserverType { typealias Element = Observable<O.Element> typealias Parent = Merge<O.Element> typealias MergeState = ( stopped: Bool, group: CompositeDisposable, sourceSubscription: SingleAssignmentDisposable ) let parent: Parent var lock = NSRecursiveLock() var mergeState: MergeState = ( stopped: false, group: CompositeDisposable(), sourceSubscription: SingleAssignmentDisposable() ) init(parent: Parent, observer: O, cancel: Disposable) { self.parent = parent _ = self.mergeState super.init(observer: observer, cancel: cancel) } func run() -> Disposable { let state = self.mergeState state.group.addDisposable(state.sourceSubscription) let disposable = self.parent.sources.subscribeSafe(self) state.sourceSubscription.disposable = disposable return state.group } func on(event: Event<Element>) { switch event { case .Next(let value): let innerSubscription = SingleAssignmentDisposable() let maybeKey = mergeState.group.addDisposable(innerSubscription) if let key = maybeKey { let observer = Merge_Iter(parent: self, disposeKey: key) let disposable = value.subscribeSafe(observer) innerSubscription.disposable = disposable } case .Error(let error): lock.performLocked { trySendError(observer, error) self.dispose() } case .Completed: lock.performLocked { let mergeState = self.mergeState let group = mergeState.group self.mergeState.stopped = true if group.count == 1 { trySendCompleted(observer) self.dispose() } else { mergeState.sourceSubscription.dispose() } } } } } // concurrent class Merge_ConcurrentIter<O: ObserverType> : ObserverType { typealias Element = O.Element typealias DisposeKey = Bag<Disposable>.KeyType typealias Parent = Merge_Concurrent<O> let parent: Parent let disposeKey: DisposeKey init(parent: Parent, disposeKey: DisposeKey) { self.parent = parent self.disposeKey = disposeKey } func on(event: Event<Element>) { switch event { case .Next: parent.lock.performLocked { trySend(parent.observer, event) } case .Error: parent.lock.performLocked { trySend(parent.observer, event) self.parent.dispose() } case .Completed: parent.lock.performLocked { let mergeState = parent.mergeState mergeState.group.removeDisposable(disposeKey) if mergeState.queue.value.count > 0 { let s = mergeState.queue.value.dequeue() self.parent.subscribe(s, group: mergeState.group) } else { parent.mergeState.activeCount = mergeState.activeCount - 1 if mergeState.stopped && parent.mergeState.activeCount == 0 { trySendCompleted(parent.observer) self.parent.dispose() } } } } } } class Merge_Concurrent<O: ObserverType> : Sink<O>, ObserverType { typealias Element = Observable<O.Element> typealias Parent = Merge<O.Element> typealias QueueType = Queue<Observable<O.Element>> typealias MergeState = ( stopped: Bool, queue: RxMutableBox<QueueType>, sourceSubscription: SingleAssignmentDisposable, group: CompositeDisposable, activeCount: Int ) let parent: Parent var lock = NSRecursiveLock() var mergeState: MergeState = ( stopped: false, queue: RxMutableBox(Queue(capacity: 2)), sourceSubscription: SingleAssignmentDisposable(), group: CompositeDisposable(), activeCount: 0 ) init(parent: Parent, observer: O, cancel: Disposable) { self.parent = parent let state = self.mergeState _ = state.group.addDisposable(state.sourceSubscription) super.init(observer: observer, cancel: cancel) } func run() -> Disposable { let state = self.mergeState state.group.addDisposable(state.sourceSubscription) let disposable = self.parent.sources.subscribeSafe(self) state.sourceSubscription.disposable = disposable return state.group } func subscribe(innerSource: Element, group: CompositeDisposable) { let subscription = SingleAssignmentDisposable() let key = group.addDisposable(subscription) if let key = key { let observer = Merge_ConcurrentIter(parent: self, disposeKey: key) let disposable = innerSource.subscribeSafe(observer) subscription.disposable = disposable } } func on(event: Event<Element>) { switch event { case .Next(let value): let subscribe = lock.calculateLocked { () -> Bool in let mergeState = self.mergeState if mergeState.activeCount < self.parent.maxConcurrent { self.mergeState.activeCount += 1 return true } else { mergeState.queue.value.enqueue(value) return false } } if subscribe { self.subscribe(value, group: mergeState.group) } case .Error(let error): lock.performLocked { trySendError(observer, error) self.dispose() } case .Completed: lock.performLocked { let mergeState = self.mergeState _ = mergeState.group if mergeState.activeCount == 0 { trySendCompleted(observer) self.dispose() } else { mergeState.sourceSubscription.dispose() } self.mergeState.stopped = true } } } } class Merge<Element> : Producer<Element> { let sources: Observable<Observable<Element>> let maxConcurrent: Int init(sources: Observable<Observable<Element>>, maxConcurrent: Int) { self.sources = sources self.maxConcurrent = maxConcurrent } override func run<O: ObserverType where O.Element == Element>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable { if maxConcurrent > 0 { let sink = Merge_Concurrent(parent: self, observer: observer, cancel: cancel) setSink(sink) return sink.run() } else { let sink = Merge_(parent: self, observer: observer, cancel: cancel) setSink(sink) return sink.run() } } }
mit
a29aab49f499e5e553044b91b3479ae2
29.054054
145
0.539404
5.413877
false
false
false
false
darina/omim
iphone/Maps/UI/Authorization/User+AppleId.swift
5
1630
import Foundation fileprivate enum Const { static let kAppleIdKey = "kAppleIdKey" static let kAppleIdFirstName = "kAppleIdFirstName" static let kAppleIdLastName = "kAppleIdLastName" } struct AppleId { let userId: String let firstName: String let lastName: String } @available(iOS 13.0, *) extension User { static func setAppleId(_ appleId: AppleId) { KeychainStorage.shared.set(appleId.userId, forKey: Const.kAppleIdKey) KeychainStorage.shared.set(appleId.firstName, forKey: Const.kAppleIdFirstName) KeychainStorage.shared.set(appleId.lastName, forKey: Const.kAppleIdLastName) } static func getAppleId() -> AppleId? { guard let userId = KeychainStorage.shared.string(forKey: Const.kAppleIdKey), let firstName = KeychainStorage.shared.string(forKey: Const.kAppleIdFirstName), let lastName = KeychainStorage.shared.string(forKey: Const.kAppleIdLastName) else { return nil } return AppleId(userId: userId, firstName: firstName, lastName: lastName) } @objc static func verifyAppleId() { guard let userId = KeychainStorage.shared.string(forKey: Const.kAppleIdKey) else { return } let appleIDProvider = ASAuthorizationAppleIDProvider() appleIDProvider.getCredentialState(forUserID: userId) { (state, error) in switch state { case .revoked, .notFound: logOut() KeychainStorage.shared.deleteString(forKey: Const.kAppleIdKey) KeychainStorage.shared.deleteString(forKey: Const.kAppleIdFirstName) KeychainStorage.shared.deleteString(forKey: Const.kAppleIdLastName) default: break } } } }
apache-2.0
15ccb973beef85801ed9a32c3f62e646
33.680851
95
0.733129
4.054726
false
true
false
false
CodePath2017Group4/travel-app
RoadTripPlanner/YelpFusionClient.swift
1
11189
// // YelpFusionClient.swift // RoadTripPlanner // // Created by Diana Fisher on 10/17/17. // Copyright © 2017 Deepthy. All rights reserved. // import YelpAPI //import AFNetworking import CoreLocation import CDYelpFusionKit class YelpFusionClient { var yelpClient: YLPClient? static let sharedInstance = YelpFusionClient() func authorize() { YLPClient.authorize(withAppId: APIKeys.Yelp.clientId, secret: APIKeys.Yelp.clientSecret) { (client: YLPClient?, error: Error?) in if (client != nil) { self.yelpClient = client log.verbose("SUCCESS!") } else if (error != nil) { log.error(error!) } } } func search(withLocationName location: String, term: String) { yelpClient?.search(withLocation: location, term: term, limit: 20, offset: 0, sort: YLPSortType.bestMatched, completionHandler: { (search: YLPSearch?, error: Error?) in let businesses = search?.businesses log.info(businesses?.count ?? 0) for b in businesses! { log.info (b.name) } }) } //used in create trip func searchQueryWith(location: CLLocationCoordinate2D, term: String, params: [String]? , completionHandler: @escaping ([YLPBusiness]?, Error?) -> Void) { print("entered searchQueryWith") let query = YLPQuery(coordinate: YLPCoordinate(latitude: location.latitude, longitude: location.longitude)) query.term = term query.limit = 10 //query.radiusFilter = 25 query.sort = YLPSortType.distance var category = Category(term: term) query.categoryFilter = params//["gasstation","bakeries"]//category.getCategoryList() yelpClient?.search(with: query, completionHandler : { (search: YLPSearch?, error: Error?) in let businesses = search?.businesses completionHandler(businesses, nil) log.info(businesses) let notificationName = NSNotification.Name(rawValue: "BussinessesDidUpdate") NotificationCenter.default.post(name: notificationName, object: nil, userInfo: ["businesses": businesses as! [YLPBusiness]?, "type": term]) for b in businesses! { log.info (b.name) } }) } // working - used in code func searchQueryWith(location: CLLocation, term: String, completionHandler: @escaping ([YLPBusiness]?, Error?) -> Void) { let query = YLPQuery(coordinate: YLPCoordinate(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)) query.term = term query.limit = 5 query.radiusFilter = 8046 query.sort = YLPSortType.distance var category = Category(term: term) query.categoryFilter = category.getCategoryList() yelpClient?.search(with: query, completionHandler : { (search: YLPSearch?, error: Error?) in let businesses = search?.businesses completionHandler(businesses, nil) // log.info(businesses) let notificationName = NSNotification.Name(rawValue: "BussinessesDidUpdate") NotificationCenter.default.post(name: notificationName, object: nil, userInfo: ["businesses": businesses as! [YLPBusiness]?]) for b in businesses! { log.info (b.name) } }) } func businessDetaillsWith(id: String, completionHandler: @escaping (YLPBusiness, Error?) -> Void) { yelpClient?.business(withId: id, completionHandler: { (search: YLPBusiness?, error: Error?) in let business = search for y in (business?.categories)! { print("cat \(y.name)") } /* let notificationName = NSNotification.Name(rawValue: "BussinessUpdate") NotificationCenter.default.post(name: notificationName, object: nil, userInfo: ["business": business as! YLPBusiness?])*/ }) } func businessReviewsWith(id: String, completionHandler: @escaping (YLPBusiness, Error?) -> Void) { yelpClient?.reviewsForBusiness(withId: id, completionHandler: { (yelpReviews: YLPBusinessReviews?, error: Error?) in let reviews = yelpReviews?.reviews for review in reviews! { print("cat \(review)") } let notificationName = NSNotification.Name(rawValue: "BussinessReview") NotificationCenter.default.post(name: notificationName, object: nil, userInfo: ["reviews": reviews as! [YLPReview]]) }) } func searchWith(location: CLLocationCoordinate2D, term: String, completionHandler: @escaping ([YLPBusiness]?, Error?) -> Void) { let query = YLPQuery(coordinate: YLPCoordinate(latitude: location.latitude, longitude: location.longitude)) query.term = (term) query.limit = 20 //query.radiusFilter = 25 query.sort = YLPSortType.distance var category = Category(term: term) query.categoryFilter = category.getCategoryList() yelpClient?.search(with: query, completionHandler : { (search: YLPSearch?, error: Error?) in let businesses = search?.businesses completionHandler(businesses, nil) // log.info(businesses) let notificationName = NSNotification.Name(rawValue: "BussinessesDidUpdate") NotificationCenter.default.post(name: notificationName, object: nil, userInfo: ["businesses": businesses as! [YLPBusiness]?]) }) } func search(inCurrent location: CLLocationCoordinate2D, term: String, completionHandler: @escaping ([YLPBusiness]?, Error?) -> Void) { var category = Category(term: term) var cat = category.getCategoryList().joined(separator: ",") yelpClient?.search(with: YLPCoordinate(latitude: location.latitude, longitude: location.longitude), term: term, limit: 25, offset: 0, sort: YLPSortType.bestMatched, completionHandler: { (search: YLPSearch?, error: Error?) in let businesses = search?.businesses completionHandler(businesses, nil) let notificationName = NSNotification.Name(rawValue: "BussinessesDidUpdate") NotificationCenter.default.post(name: notificationName, object: nil, userInfo: ["businesses": businesses as! [YLPBusiness]]) log.info(businesses?.count ?? 0) }) } func search(withLocation location: CLLocation, term: String, completion: @escaping ([YLPBusiness]?, Error?) -> Void) { let ylpCoordinate = YLPCoordinate(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude) yelpClient?.search(with: ylpCoordinate, term: term, limit: 20, offset: 0, sort: YLPSortType.mostReviewed, completionHandler: { (search: YLPSearch?, error: Error?) in if error != nil { log.error(error ?? "Unknown Error Occurred") completion(nil, error) } else { let businesses = search?.businesses // log.info(businesses?.count ?? 0) completion(businesses, nil) } }) } //========================= CDYelpFusionClient ========== static let shared = YelpFusionClient() var apiClient: CDYelpAPIClient! func configure() { let client = CDYelpAPIClient(clientId: APIKeys.Yelp.clientId, clientSecret: APIKeys.Yelp.clientSecret) if client.isAuthenticated() { self.apiClient = client log.verbose("Success!") } else { log.verbose("Authentication Failure!") } } func businessWith(id: String, completionHandler: @escaping (CDYelpBusiness, Error?) -> Void) { // YelpFusionClient().configure() print("id \(id)") var idString = "" /* self.apiClient.searchBusinesses(byTerm: "gasstation", location: "San Francisco", latitude: nil, longitude: nil, radius: nil, categories: nil, locale: nil, limit: 1, offset: 0, sortBy: nil, priceTiers: nil, openNow: true, openAt: nil, attributes: nil) { (resonse: CDYelpSearchResponse?, error: Error?) in var t = resonse?.businesses print("t \(t?.count)") print("t \(t![0])") print("t \(t![0].id)") idString = (t![0].id)! } print("idString \(idString)") if (idString).isEmpty { idString = id }*/ print("apiClient \(self.apiClient)") self.apiClient?.fetchBusiness(byId: "deli-board-san-francisco", locale: nil) { (business: CDYelpBusiness?, error: Error?) in print("inside CDYelpBusiness") let business = business print("business?.price \(business?.price)") let notificationName = NSNotification.Name(rawValue: "BussinessUpdate") NotificationCenter.default.post(name: notificationName, object: nil, userInfo: ["business": business as! CDYelpBusiness?]) } } func searchQueryWith(location: CLLocation, term: String, completionHandler: @escaping ([CDYelpBusiness]?, Error?) -> Void) { /* let query = YLPQuery(coordinate: YLPCoordinate(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)) query.term = term query.limit = 20 //query.radiusFilter = 25 query.sort = YLPSortType.distance var category = Category(term: term) query.categoryFilter = category.getCategoryList() print("apiClient in searchQueryWith \(apiClient)")*/ print("term \(term)") apiClient?.searchBusinesses(byTerm: term, location: nil, latitude: location.coordinate.latitude, longitude: location.coordinate.longitude, radius: 40000, categories: nil, locale: nil, limit: 50, offset: 0, sortBy: CDYelpSortType.distance, priceTiers: nil, openNow: nil, openAt: nil, attributes: nil) { (response: CDYelpSearchResponse?, error: Error?) in let businesses = response?.businesses completionHandler(businesses, nil) let notificationName = NSNotification.Name(rawValue: "BussinessesDidUpdate") NotificationCenter.default.post(name: notificationName, object: nil, userInfo: ["businesses": businesses as! [CDYelpBusiness]?]) for b in businesses! { log.info ("====? "+b.name!) } } } }
mit
a0906bf0803d6ae3a1f34fa6062da6b2
36.41806
361
0.588935
4.814114
false
false
false
false
hilenium/HISwiftExtensions
Example/Tests/StringTests.swift
1
3288
//// //// StringTests.swift //// HISwiftExtensions //// //// Created by Matthew on 27/12/2015. //// Copyright © 2015 CocoaPods. All rights reserved. //// // //import Quick //import Nimble //import HISwiftExtensions // //class StringExtensionsSpec: QuickSpec { // // override func spec() { // describe("string extensions") { // // it("underscore to camelCase") { // let s = "foo_bar" // let k = s.underscoreToCamelCase // expect(k).to(equal("fooBar")) // } // // it("uppercase first") { // let s = "foo" // let u = s.uppercaseFirst // expect(u.characters.first).to(equal("F")) // expect(Array(u.characters)[1]).to(equal("o")) // expect(Array(u.characters)[2]).to(equal("o")) // } // // it("trim") { // // let s = " foo " // let t = s.trim // expect(t).to(equal("foo")) // } // // it("truncate shorter than length of string") { // // let s = "this is a string" // let t = s.truncate(4) // expect(t).to(equal("this...")) // } // // it("truncate length of string") { // // let s = "this is a string" // let t = s.truncate(16) // expect(t).to(equal(s)) // } // // it("url encode") { // // let s = "the string" // let u = s.urlEncode // expect(u).to(equal("the%20string")) // } // // it("split") { // // let s = "the-string" // let u = s.split("-") // expect(u).to(equal(["the", "string"])) // } // // it("is valid email") { // // let s = "[email protected]" // expect(s.isValidEmail).to(equal(true)) // } // // it("is not valid email") { // // let s = "hilenium.com" // expect(s.isValidEmail).to(equal(false)) // } // // it("count") { // // let s = "string" // expect(s.count).to(equal(6)) // } // // it("to date") { // // let s = "2000-01-01T00:00:00+00:00" // // let dateFormatter = DateFormatter() // dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZ" // let date = dateFormatter.date(from: s) // // expect(s.toDate()).to(equal(date)) // } // // it("subscript") { // // expect("foo"[0]).to(equal("f")) // } // // it("strip") { // // let html = "<p>hello</p>" // let string = html.stripHTML // expect(string).to(equal("hello")) // // } // } // } //}
mit
b56bdeb0366d39c185fcf464f72e5a0c
28.881818
72
0.351384
3.867059
false
false
false
false
leolanzinger/readory
Readory_test/PageContentViewController.swift
1
1219
// // PageContentViewController.swift // UIPageViewController // // Created by Shrikar Archak on 1/15/15. // Copyright (c) 2015 Shrikar Archak. All rights reserved. // import UIKit class PageContentViewController: UIViewController { @IBOutlet weak var onBoardingImage: UIImageView! @IBOutlet weak var onBoardingNumber: UILabel! @IBOutlet weak var okButton: UIButton! @IBOutlet weak var onBoardingStack: UIStackView! @IBOutlet weak var onBoardingLabel: UILabel! var pageIndex: Int! var titleText : String! var imageName : String! var ok_button : UIButton! var max: Int? override func viewDidLoad() { super.viewDidLoad() ok_button = self.okButton self.onBoardingImage.image = UIImage(named: imageName) self.onBoardingNumber.text = String(pageIndex) self.onBoardingLabel.text = self.titleText self.onBoardingLabel.alpha = 0.1 UIView.animateWithDuration(1.0, animations: { () -> Void in self.onBoardingLabel.alpha = 1.0 }) if (pageIndex < max) { okButton.hidden = true } else { onBoardingStack.hidden = true } } }
mit
4b938a0242f5f704a92feba3ae1bdab8
27.372093
67
0.641509
4.322695
false
false
false
false
tlax/looper
looper/Controller/Camera/CCameraCrop.swift
1
3832
import UIKit class CCameraCrop:CController { weak var record:MCameraRecord! private weak var viewCrop:VCameraCrop! private let kMinThreshold:CGFloat = 2 init(record:MCameraRecord) { self.record = record super.init() } required init?(coder:NSCoder) { return nil } override func loadView() { let viewCrop:VCameraCrop = VCameraCrop(controller:self) self.viewCrop = viewCrop view = viewCrop } override func viewDidAppear(_ animated:Bool) { super.viewDidAppear(animated) viewCrop.viewImage.createShades() } //MARK: private private func asyncSave() { let originalLeft:CGFloat = viewCrop.viewImage.thumbTopLeft.originalX let originalRight:CGFloat = viewCrop.viewImage.thumbTopRight.originalX let originalTop:CGFloat = viewCrop.viewImage.thumbTopLeft.originalY let originalBottom:CGFloat = viewCrop.viewImage.thumbBottomLeft.originalY let posLeft:CGFloat = viewCrop.viewImage.thumbTopLeft.positionX let posRight:CGFloat = viewCrop.viewImage.thumbTopRight.positionX let posTop:CGFloat = viewCrop.viewImage.thumbTopLeft.positionY let posBottom:CGFloat = viewCrop.viewImage.thumbBottomLeft.positionY let deltaLeft:CGFloat = posLeft - originalLeft let deltaRight:CGFloat = originalRight - posRight let deltaTop:CGFloat = posTop - originalTop let deltaBottom:CGFloat = originalBottom - posBottom if deltaLeft > kMinThreshold || deltaRight > kMinThreshold || deltaTop > kMinThreshold || deltaBottom > kMinThreshold { let originalSize:CGFloat = viewCrop.viewImage.imageSize let imageRatio:CGFloat = viewCrop.viewImage.imageRatio let distanceLeft:CGFloat = deltaLeft / imageRatio let distanceRight:CGFloat = deltaRight / imageRatio let distanceTop:CGFloat = deltaTop / imageRatio let newSize:CGFloat = originalSize - (distanceLeft + distanceRight) var croppedRecords:[MCameraRecordItem] = [] let imageSize:CGSize = CGSize( width:newSize, height:newSize) let drawingRect:CGRect = CGRect( x:-distanceLeft, y:-distanceTop, width:originalSize, height:originalSize) for rawItem:MCameraRecordItem in record.items { let originalImage:UIImage = rawItem.image UIGraphicsBeginImageContext(imageSize) originalImage.draw(in:drawingRect) guard let croppedImage:UIImage = UIGraphicsGetImageFromCurrentImageContext() else { UIGraphicsEndImageContext() continue } UIGraphicsEndImageContext() let croppedItem:MCameraRecordItem = MCameraRecordItem( image:croppedImage) croppedRecords.append(croppedItem) } record.items = croppedRecords } DispatchQueue.main.async { [weak self] in self?.savingFinished() } } private func savingFinished() { parentController.pop(vertical:CParent.TransitionVertical.fromTop) } //MARK: public func save() { viewCrop.startLoading() DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async { [weak self] in self?.asyncSave() } } }
mit
ffb419e7c813b05cf4b0a0243218d7f0
30.669421
125
0.583768
5.374474
false
false
false
false
TG908/iOS
TUM Campus App/TuitionStatusManager.swift
1
2523
// // TuitionStatusManager.swift // TUM Campus App // // Created by Mathias Quintero on 12/6/15. // Copyright © 2015 LS1 TUM. All rights reserved. // import Foundation import Alamofire import SwiftyJSON import SWXMLHash class TuitionStatusManager: Manager { var main: TumDataManager? var single = false required init(mainManager: TumDataManager) { main = mainManager } init(mainManager: TumDataManager, single: Bool) { main = mainManager self.single = single } static var tuitionItems = [DataElement]() func fetchData(_ handler: @escaping ([DataElement]) -> ()) { if TuitionStatusManager.tuitionItems.isEmpty { let url = getURL() Alamofire.request(url).responseString() { (response) in if let data = response.result.value { let tuitionData = SWXMLHash.parse(data) let rows = tuitionData["rowset"]["row"].all for row in rows { if let soll = row["soll"].element?.text, let frist = row["frist"].element?.text, let bez = row["semester_bezeichnung"].element?.text { let dateformatter = DateFormatter() dateformatter.dateFormat = "yyyy-MM-dd" if let fristDate = dateformatter.date(from: frist) { let tuition = Tuition(frist: fristDate, semester: bez, soll: soll) TuitionStatusManager.tuitionItems.append(tuition) } } } self.handle(handler) } } } else { handle(handler) } } func handle(_ handler: ([DataElement]) -> ()) { if single { if let tuitionItem = TuitionStatusManager.tuitionItems.first { handler([tuitionItem]) } } else { handler(TuitionStatusManager.tuitionItems) } } func getURL() -> String { let base = TUMOnlineWebServices.BaseUrl.rawValue + TUMOnlineWebServices.TuitionStatus.rawValue if let token = main?.getToken() { return base + "?" + TUMOnlineWebServices.TokenParameter.rawValue + "=" + token } return "" } }
gpl-3.0
ab4027f61fb48c1b91d2989261a5d5e2
31.333333
102
0.507534
4.878143
false
false
false
false
CharlesVu/Smart-iPad
MKHome/Weather/Skycons.swift
1
20191
// // SKYIconView.swift // Icon-iOS // // Created by Miwand Najafe on 2016-06-10. // Copyright © 2016 Miwand Najafe. All rights reserved. // import Foundation import UIKit import ForecastIO let STROKE: CGFloat = 0.08 let TWO_PI = Double.pi * 2.0 let TWO_OVER_SQRT_2 = 2.0 / sqrt(2) struct SKYWindOffset { var start: CGFloat? var end: CGFloat? } let WIND_PATHS = [ [ -0.7500, -0.1800, -0.7219, -0.1527, -0.6971, -0.1225, -0.6739, -0.0910, -0.6516, -0.0588, -0.6298, -0.0262, -0.6083, 0.0065, -0.5868, 0.0396, -0.5643, 0.0731, -0.5372, 0.1041, -0.5033, 0.1259, -0.4662, 0.1406, -0.4275, 0.1493, -0.3881, 0.1530, -0.3487, 0.1526, -0.3095, 0.1488, -0.2708, 0.1421, -0.2319, 0.1342, -0.1943, 0.1217, -0.1600, 0.1025, -0.1290, 0.0785, -0.1012, 0.0509, -0.0764, 0.0206, -0.0547, -0.0120, -0.0378, -0.0472, -0.0324, -0.0857, -0.0389, -0.1241, -0.0546, -0.1599, -0.0814, -0.1876, -0.1193, -0.1964, -0.1582, -0.1935, -0.1931, -0.1769, -0.2157, -0.1453, -0.2290, -0.1085, -0.2327, -0.0697, -0.2240, -0.0317, -0.2064, 0.0033, -0.1853, 0.0362, -0.1613, 0.0672, -0.1350, 0.0961, -0.1051, 0.1213, -0.0706, 0.1397, -0.0332, 0.1512, 0.0053, 0.1580, 0.0442, 0.1624, 0.0833, 0.1636, 0.1224, 0.1615, 0.1613, 0.1565, 0.1999, 0.1500, 0.2378, 0.1402, 0.2749, 0.1279, 0.3118, 0.1147, 0.3487, 0.1015, 0.3858, 0.0892, 0.4236, 0.0787, 0.4621, 0.0715, 0.5012, 0.0702, 0.5398, 0.0766, 0.5768, 0.0890, 0.6123, 0.1055, 0.6466, 0.1244, 0.6805, 0.1440, 0.7147, 0.1630, 0.7500, 0.1800 ], [ -0.7500, 0.0000, -0.7033, 0.0195, -0.6569, 0.0399, -0.6104, 0.0600, -0.5634, 0.0789, -0.5155, 0.0954, -0.4667, 0.1089, -0.4174, 0.1206, -0.3676, 0.1299, -0.3174, 0.1365, -0.2669, 0.1398, -0.2162, 0.1391, -0.1658, 0.1347, -0.1157, 0.1271, -0.0661, 0.1169, -0.0170, 0.1046, 0.0316, 0.0903, 0.0791, 0.0728, 0.1259, 0.0534, 0.1723, 0.0331, 0.2188, 0.0129, 0.2656, -0.0064, 0.3122, -0.0263, 0.3586, -0.0466, 0.4052, -0.0665, 0.4525, -0.0847, 0.5007, -0.1002, 0.5497, -0.1130, 0.5991, -0.1240, 0.6491, -0.1325, 0.6994, -0.1380, 0.7500, -0.1400 ] ] let Wind_OFFSETS = [SKYWindOffset(start: 0.36, end: 0.11), SKYWindOffset(start: 0.56, end: 0.16)] class SKYIconView: UIView { fileprivate var _type = Icon.clearDay fileprivate var _color = UIColor(named: "normalText")! fileprivate var _timer: Timer! var w: CGFloat { return bounds.width } var h: CGFloat { return bounds.height } var s: CGFloat { return min(w, h) } override init(frame: CGRect) { super.init(frame: frame) self.play() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } var setType: Icon { get { return _type } set { _type = newValue } } var setColor: UIColor { get { return _color } set { _color = newValue } } func refresh() { self.setNeedsDisplay() } override func draw(_ rect: CGRect) { // super.drawRect(rect) let ctx: CGContext = UIGraphicsGetCurrentContext()! self.drawRect(rect, inContext: ctx) } func isAnimating() -> Bool { return self._timer != nil } func play() { if _timer != nil { self.pause() } self._timer = Timer.scheduledTimer(timeInterval: 1/30, target: self, selector: #selector(update(_:)), userInfo: nil, repeats: true) } func pause() { if self._timer != nil { self._timer?.invalidate() } self._timer = nil } @objc func update(_ timer: Timer) { self.refresh() } // MARK: Drawing fileprivate func drawRect(_ rect: CGRect, inContext context: CGContext) { let time: Double = Date().timeIntervalSince1970 * 1000 let color: CGColor = self._color.cgColor switch self._type { case .clearDay: drawClearDayInContext(context, time: time, color: color) case .clearNight: drawClearNightInContext(context, time: time, color: color) case .cloudy: drawCloudyInContext(context, time: time, color: color) case .fog: drawFogInContext(context, time: time, color: color) case .partlyCloudyDay: drawPartlyCloudyDayInContext(context, time: time, color: color) case .partlyCloudyNight: drawPartlyCloudyNightInCotnext(context, time: time, color: color) case .rain: drawRainInContext(context, time: time, color: color) case .sleet: drawSleetInContext(context, time: time, color: color) case .wind: drawWindInContext(context, time: time, color: color) case .snow: drawSnowInContext(context, time: time, color: color) } } // MARK: Icons fileprivate func drawClearDayInContext(_ ctx: CGContext, time: Double, color: CGColor) { sun(ctx, t: time, cx: w * 0.5, cy: h * 0.5, cw: s, s: s * STROKE, color: color) } fileprivate func drawClearNightInContext(_ ctx: CGContext, time: Double, color: CGColor) { moon(ctx, t: time, cx: w * 0.5, cy: h * 0.5, cw: s, s: s * STROKE, color: color) } fileprivate func drawPartlyCloudyDayInContext(_ ctx: CGContext, time: Double, color: CGColor) { ctx.beginTransparencyLayer(auxiliaryInfo: nil) sun(ctx, t: time, cx: w * 0.625, cy: h * 0.375, cw: s * 0.75, s: s * STROKE, color: color) cloud(ctx, t: time, cx: w * 0.375, cy: h * 0.625, cw: s * 0.75, s: s * STROKE, color: color) ctx.endTransparencyLayer() } fileprivate func drawPartlyCloudyNightInCotnext(_ ctx: CGContext, time: Double, color: CGColor) { ctx.beginTransparencyLayer(auxiliaryInfo: nil) moon(ctx, t: time, cx: w * 0.625, cy: h * 0.375, cw: s * 0.75, s: s * STROKE, color: color) cloud(ctx, t: time, cx: w * 0.375, cy: h * 0.625, cw: s * 0.75, s: s * STROKE, color: color) ctx.endTransparencyLayer() } fileprivate func drawCloudyInContext(_ ctx: CGContext, time: Double, color: CGColor) { ctx.beginTransparencyLayer(auxiliaryInfo: nil) cloud(ctx, t: time, cx: w * 0.5, cy: h * 0.5, cw: s, s: s * STROKE, color: color) ctx.endTransparencyLayer() } fileprivate func drawRainInContext(_ ctx: CGContext, time: Double, color: CGColor) { ctx.beginTransparencyLayer(auxiliaryInfo: nil) rain(ctx, t: time, cx: w * 0.5, cy: h * 0.37, cw: s * 0.9, s: s * STROKE, color: color) cloud(ctx, t: time, cx: w * 0.5, cy: h * 0.37, cw: s * 0.9, s: s * STROKE, color: color) ctx.endTransparencyLayer() } fileprivate func drawSleetInContext(_ ctx: CGContext, time: Double, color: CGColor) { ctx.beginTransparencyLayer(auxiliaryInfo: nil) sleet(ctx, t: time, cx: w * 0.5, cy: h * 0.37, cw: s * 0.9, s: s * STROKE, color: color) cloud(ctx, t: time, cx: w * 0.5, cy: h * 0.37, cw: s * 0.9, s: s * STROKE, color: color) ctx.endTransparencyLayer() } fileprivate func drawSnowInContext(_ ctx: CGContext, time: Double, color: CGColor) { ctx.beginTransparencyLayer(auxiliaryInfo: nil) snow(ctx, t: time, cx: w * 0.5, cy: h * 0.37, cw: s * 0.9, s: s * STROKE, color: color) cloud(ctx, t: time, cx: w * 0.5, cy: h * 0.37, cw: s * 0.9, s: s * STROKE, color: color) ctx.endTransparencyLayer() } fileprivate func drawWindInContext(_ ctx: CGContext, time: Double, color: CGColor) { swoosh(ctx, t: time, cx: w * 0.5, cy: h * 0.5, cw: s, s: s * STROKE, index: 0, total: 2, color: color) swoosh(ctx, t: time, cx: w * 0.5, cy: h * 0.5, cw: s, s: s * STROKE, index: 1, total: 2, color: color) } fileprivate func drawFogInContext(_ ctx: CGContext, time: Double, color: CGColor) { let k = s * STROKE ctx.beginTransparencyLayer(auxiliaryInfo: nil) fogBank(ctx, t: time, cx: w * 0.5, cy: h * 0.32, cw: s * 0.75, s: k, color: color) ctx.endTransparencyLayer() let newTime = time/5000 let ds = Double(s) let a = CGFloat(cos((newTime) * TWO_PI) * ds * 0.02) let b = CGFloat(cos((newTime + 0.25) * TWO_PI) * ds * 0.02) let c = CGFloat(cos((newTime + 0.50) * TWO_PI) * ds * 0.02) let d = CGFloat(cos((newTime + 0.75) * TWO_PI) * ds * 0.02) let n = h * 0.936 let e = floor(n - k * 0.5) + 0.5 let f = floor((n - k * 2.5)) + 0.5 setUpStroke(ctx, lineCapType: .round, joinCapType: .round, lineWidth: k, color: color, fillColor: nil) line(ctx, ax: a + w * 0.2 + k * 0.5, ay: e, bx: b + w * 0.8 - k * 0.5, by: e) line(ctx, ax: c + w * 0.2 + k * 0.5, ay: f, bx: d + w * 0.8 - k * 0.5, by: f) } // MARK: Basic shapes fileprivate func puff(_ ctx: CGContext, t: Double, cx: CGFloat, cy: CGFloat, rx: CGFloat, ry: CGFloat, rmin: CGFloat, rmax: CGFloat) { let c = CGFloat(cos(t * TWO_PI)) let s = CGFloat(sin(t * TWO_PI)) let rmaximum = rmax - rmin circle(ctx, x: cx - s * rx, y: cy + c * ry + rmaximum * 0.5, r: rmin + (1 - c * 0.5) * rmaximum) } fileprivate func puffs(_ ctx: CGContext, t: Double, cx: CGFloat, cy: CGFloat, rx: CGFloat, ry: CGFloat, rmin: CGFloat, rmax: CGFloat) { for i in (0..<5).reversed() { puff(ctx, t: t + Double(i) / 5, cx: cx, cy: cy, rx: rx, ry: ry, rmin: rmin, rmax: rmax) } } fileprivate func cloud(_ ctx: CGContext, t: Double, cx: CGFloat, cy: CGFloat, cw: CGFloat, s: CGFloat, color: CGColor) { let time = t/30000 let a = cw * 0.21 let b = cw * 0.12 let c = cw * 0.24 let d = cw * 0.28 ctx.setFillColor(color) puffs(ctx, t: time, cx: cx, cy: cy, rx: a, ry: b, rmin: c, rmax: d) ctx.setBlendMode(.destinationOut) puffs(ctx, t: time, cx: cx, cy: cy, rx: a, ry: b, rmin: c - s, rmax: d - s) ctx.setBlendMode(.normal) } fileprivate func sun(_ ctx: CGContext, t: Double, cx: CGFloat, cy: CGFloat, cw: CGFloat, s: CGFloat, color: CGColor) { let time = t/120000 let a = cw * 0.25 - s * 0.5 let b = cw * 0.32 + s * 0.5 let c = cw * 0.50 - s * 0.5 setUpStroke(ctx, lineCapType: .round, joinCapType: .round, lineWidth: s, color: color, fillColor: nil) ctx.beginPath() CGContextAddArc(ctx, cx, cy, a, 0, CGFloat(TWO_PI), 1) ctx.strokePath() for i in (0...8).reversed() { let p = (time + Double(i) / 8) * (TWO_PI) let cosine = CGFloat(cos(p)) let sine = CGFloat(sin(p)) line(ctx, ax: cx + cosine * b, ay: cy + sine * b, bx: cx + cosine * c, by: cy + sine * c) } } fileprivate func moon(_ ctx: CGContext, t: Double, cx: CGFloat, cy: CGFloat, cw: CGFloat, s: CGFloat, color: CGColor) { let time = t/15000 let a = cw * 0.29 - s * 0.5 let b: CGFloat = cw * 0.05 let c = CGFloat(cos(time * TWO_PI)) let p = CGFloat(c * CGFloat(TWO_PI / -16)) let newcx = cx + c * b setUpStroke(ctx, lineCapType: .round, joinCapType: .round, lineWidth: s, color: color, fillColor: nil) ctx.beginPath() CGContextAddArc(ctx, newcx, cy, a, p + CGFloat(TWO_PI/8), p + CGFloat(TWO_PI * 7/8), 0) CGContextAddArc(ctx, newcx + cos(p) * a * CGFloat(TWO_OVER_SQRT_2), cy + sin(p) * a * CGFloat(TWO_OVER_SQRT_2), a, p + CGFloat(TWO_PI) * 5 / 8, p + CGFloat(TWO_PI) * 3 / 8, 1) ctx.closePath() ctx.strokePath() } fileprivate func rain(_ ctx: CGContext, t: Double, cx: CGFloat, cy: CGFloat, cw: CGFloat, s: CGFloat, color: CGColor) { let time = t / 1350 let a: Double = Double(cw) * 0.16 let b = TWO_PI * 11 / 12 let c = TWO_PI * 7 / 12 ctx.setFillColor(color) for i in (0...4).reversed() { let p = fmod(time + Double(i)/4, 1) let x = floor(Double(cx) + ((Double(i) - 1.5) / 1.5) * (i == 1 || i == 2 ? -1 : 1) * a) + 0.5 let y = cy + CGFloat(p) * cw ctx.beginPath() ctx.move(to: CGPoint(x: CGFloat(x), y: y - s * 1.5)) CGContextAddArc(ctx, CGFloat(x), y, s * 0.75, CGFloat(b), CGFloat(c), 0) ctx.fillPath() } } fileprivate func sleet(_ ctx: CGContext, t: Double, cx: CGFloat, cy: CGFloat, cw: CGFloat, s: CGFloat, color: CGColor) { let time = t / 750 let a = cw * 0.1875 setUpStroke(ctx, lineCapType: .round, joinCapType: .round, lineWidth: s * 0.05, color: color, fillColor: nil) for i in (0..<4) { let p = fmod(time + Double(i) / 4, 1) let x = floor(cx + (CGFloat((Double(i) - 1.5) / 1.5) * (i == 1 || i == 2 ? -1 : 1)) * a) + 0.5 let y = cy + CGFloat(p) * cw line(ctx, ax: x, ay: y - s * 1.5, bx: x, by: y + s * 1.5) } } fileprivate func snow(_ ctx: CGContext, t: Double, cx: CGFloat, cy: CGFloat, cw: CGFloat, s: CGFloat, color: CGColor) { let time = t/3000 let a = cw * 0.16 let b = Double(s * 0.75) let u = time * TWO_PI * 0.7 let ux = CGFloat(cos(u) * b) let uy = CGFloat(sin(u) * b) let v = u + TWO_PI / 3 let vx = CGFloat(cos(v) * b) let vy = CGFloat(sin(v) * b) let w = u + TWO_PI * 2 / 3 let wx = CGFloat(cos(w) * b) let wy = CGFloat(sin(w) * b) setUpStroke(ctx, lineCapType: .round, joinCapType: .round, lineWidth: s * 0.5, color: color, fillColor: nil) for i in (0..<4).reversed() { let p = fmod(time + Double(i)/4, 1) let x = cx + CGFloat(sin(p + Double(i) / 4 * TWO_PI)) * a let y = cy + CGFloat(p) * cw line(ctx, ax: x - ux, ay: y - uy, bx: x + ux, by: y + uy) line(ctx, ax: x - vx, ay: y - vy, bx: x + vx, by: y + vy) line(ctx, ax: x - wx, ay: y - wy, bx: x + wx, by: y + wy) } } fileprivate func fogBank(_ ctx: CGContext, t: Double, cx: CGFloat, cy: CGFloat, cw: CGFloat, s: CGFloat, color: CGColor) { let time = t/30000 let a = cw * 0.21 let b = cw * 0.06 let c = cw * 0.21 let d = cw * 0.28 ctx.setFillColor(color) puffs(ctx, t: time, cx: cx, cy: cy, rx: a, ry: b, rmin: c, rmax: d) ctx.setBlendMode(.destinationOut) puffs(ctx, t: time, cx: cx, cy: cy, rx: a, ry: b, rmin: c - s, rmax: d - s) ctx.setBlendMode(.normal) } fileprivate func leaf(_ ctx: CGContext, t: Double, x: CGFloat, y: CGFloat, cw: CGFloat, s: CGFloat, color: CGColor) { let a = cw / 8 let b = a / 3 let c = 2 * b let d = CGFloat(fmod(t, 1) * TWO_PI) let e = CGFloat(cos(d)) let f = CGFloat(sin(d)) setUpStroke(ctx, lineCapType: .round, joinCapType: .round, lineWidth: s, color: color, fillColor: color) ctx.beginPath() CGContextAddArc(ctx, x, y, a, d, d + CGFloat(Double.pi), 1) CGContextAddArc(ctx, x - b * e, y - b * f, c, d + CGFloat(Double.pi), d, 1) CGContextAddArc(ctx, x + c * e, y + c * f, b, d + CGFloat(Double.pi), d, 0) ctx.setBlendMode(.destinationOut) ctx.beginTransparencyLayer(auxiliaryInfo: nil) ctx.endTransparencyLayer() ctx.setBlendMode(.normal) ctx.strokePath() } fileprivate func swoosh(_ ctx: CGContext, t: Double, cx: CGFloat, cy: CGFloat, cw: CGFloat, s: CGFloat, index: Int, total: Double, color: CGColor) { let time = t / 2500 let windOffset = Wind_OFFSETS[index] let pathLength = index == 0 ? 128 : 64 let path = WIND_PATHS[index] var a = fmod(time + Double(index) - Double(windOffset.start!), total) var c = fmod(time + Double(index) - Double(windOffset.end!), total) var e = fmod(time + Double(index), total) setUpStroke(ctx, lineCapType: .round, joinCapType: .round, lineWidth: s, color: color, fillColor: nil) if a < 1 { ctx.beginPath() a *= Double(pathLength) / 2 - 1 var b = floor(a) a -= b b *= 2 b += 2 let ax = (path[Int(b) - 2] * (1 - a) + path[Int(b)] * a) let ay = (path[Int(b) - 1] * (1 - a) + path[Int(b) + 1] * a) let x = cx + CGFloat(ax) * cw let y = cy + CGFloat(ay) * cw ctx.move(to: CGPoint(x: x, y: y)) if c < 1 { c *= Double(pathLength) / 2 - 1 var d = floor(c) c -= d d *= 2 d += 2 for i in Int(b)...Int(d) where i != Int(d) && i % 2 == 0 { ctx.addLine(to: CGPoint(x: cx + CGFloat(path[i]) * cw, y: cy + CGFloat(path[i + 1]) * cw)) } let condX = (path[Int(d) - 2] * (1 - c) + path[Int(d)] * c) let condY = (path[Int(d) - 1] * (1 - c) + path[Int(d) + 1] * c) let bx = cx + CGFloat(condX) * cw let by = cy + CGFloat(condY) * cw ctx.addLine(to: CGPoint(x: bx, y: by)) } else { for i in Int(b)...pathLength where i != pathLength && i % 2 == 0 { ctx.addLine(to: CGPoint(x: cx + CGFloat(path[i]) * cw, y: cy + CGFloat(path[i + 1]) * cw)) } } ctx.strokePath() } else if c < 1 { ctx.beginPath() c *= Double(pathLength) / 2 - 1 var d = floor(c) c -= d d *= 2 d += 2 ctx.move(to: CGPoint(x: cx + CGFloat(path[0]) * cw, y: cy + CGFloat(path[1]) * cw)) for i in (2...Int(d)) where i != Int(d) && i % 2 == 0 { ctx.addLine(to: CGPoint(x: cx + CGFloat(path[i]) * cw, y: cy + CGFloat(path[i + 1]) * cw)) } let dx = (path[Int(d) - 2] * (1 - c) + path[Int(d)] * c) let dy = (path[Int(d) - 1] * (1 - c) + path[Int(d) + 1] * c) ctx.addLine(to: CGPoint(x: cx + CGFloat(dx) * cw, y: cy + CGFloat(dy) * cw)) ctx.strokePath() } if e < 1 { e *= Double(pathLength) / 2 - 1 var f = floor(e) e -= f f *= 2 f += 2 let fx = (path[Int(f) - 2] * (1 - e) + path[Int(f)] * e) let fy = (path[Int(f) - 1] * (1 - e) + path[Int(f) + 1] * e) leaf(ctx, t: time, x: cx + CGFloat(fx) * cw, y: cy + CGFloat(fy) * cw, cw: cw, s: s, color: color) } } // MARK: Setting up Stroke func setUpStroke(_ ctx: CGContext, lineCapType: CGLineCap, joinCapType: CGLineJoin, lineWidth: CGFloat, color: CGColor, fillColor: CGColor?) { ctx.setStrokeColor(color) ctx.setLineWidth(lineWidth) ctx.setLineCap(.round) ctx.setLineJoin(.round) if fillColor != nil { ctx.setFillColor(fillColor!) } } // MARK: Drawing Primitives fileprivate func circle(_ ctx: CGContext, x: CGFloat, y: CGFloat, r: CGFloat) { ctx.beginPath() CGContextAddArc(ctx, x, y, r, 0, CGFloat(Double.pi) * 2, 1) ctx.fillPath() } fileprivate func line(_ ctx: CGContext, ax: CGFloat, ay: CGFloat, bx: CGFloat, by: CGFloat) { ctx.beginPath() ctx.move(to: CGPoint(x: ax, y: ay)) ctx.addLine(to: CGPoint(x: bx, y: by)) ctx.strokePath() } func CGContextAddArc(_ context: CGContext, _ centerX: CGFloat, _ centerY: CGFloat, _ radius: CGFloat, _ startAngle: CGFloat, _ endAngle: CGFloat, _ clockwise: Int ) { let centerPoint = CGPoint(x: centerX, y: centerY) let isClockWise = clockwise == 0 ? false : true context.addArc(center: centerPoint, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: isClockWise) } }
mit
174db480daa96e073d9befb2085a5128
36.18232
183
0.52947
3.028803
false
false
false
false
darkzero/DZ_UIKit
Example/DZ_UIKit/CheckBoxViewController.swift
1
4836
// // CheckBoxViewController.swift // DZ_UIKit // // Created by 胡 昱化 on 17/1/30. // Copyright © 2017年 CocoaPods. All rights reserved. // import UIKit import DZ_UIKit class CheckBoxViewController: UIViewController { @IBOutlet var checkBox1: DZCheckBox!; @IBOutlet var checkBox2: DZCheckBox!; @IBOutlet var checkBox3: DZCheckBox!; @IBOutlet var checkBox4: DZCheckBox!; @IBOutlet var checkBox5: DZCheckBox!; override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated); // #Recommend // add checkbox using storyboard // then group them with code let checkboxGroupA = DZCheckBoxGroup(); checkboxGroupA.multipleCheckEnabled = false; checkboxGroupA.addCheckBox(checkBox1); checkboxGroupA.addCheckBox(checkBox2); checkboxGroupA.addCheckBox(checkBox3); checkboxGroupA.addCheckBox(checkBox4); checkboxGroupA.addCheckBox(checkBox5); checkboxGroupA.addTarget(self, action: #selector(onCheckBoxGroupValueChanged(_:)), for: .valueChanged); // creating with code let checkboxGroup = DZCheckBoxGroup(frame: CGRect(x: 10, y: 200, width: 240, height: 48)); checkboxGroup.backgroundColor = UIColor.red; checkboxGroup.multipleCheckEnabled = false; checkboxGroup.addCheckBox( DZCheckBox(frame: CGRect(x: 0, y: 0, width: 48, height: 48), type: DZCheckBoxType.square)); checkboxGroup.addCheckBox( DZCheckBox(frame: CGRect(x: 0, y: 0, width: 48, height: 48), type: DZCheckBoxType.square, borderColor: UIColor.white)); checkboxGroup.addCheckBox( DZCheckBox(frame: CGRect(x: 0, y: 0, width: 48, height: 48), type: DZCheckBoxType.rounded)); checkboxGroup.addCheckBox( DZCheckBox(frame: CGRect(x: 0, y: 0, width: 48, height: 48), type: DZCheckBoxType.rounded, borderColor: UIColor.orange)); checkboxGroup.addCheckBox( DZCheckBox(frame: CGRect(x: 0, y: 0, width: 48, height: 48), type: DZCheckBoxType.circular)); checkboxGroup.addCheckBox( DZCheckBox(frame: CGRect(x: 0, y: 0, width: 48, height: 48), type: DZCheckBoxType.circular, borderColor: UIColor.orange, checkedColor: RGB_HEX("9988333", 1.0))); checkboxGroup.addTarget(self, action: #selector(onCheckBoxGroupValueChanged(_:)), for: .valueChanged); self.view.addSubview(checkboxGroup); let checkBoxBar = DZCheckBoxGroup(frame: CGRect(x: 10, y: 280, width: 0, height: 240)); checkBoxBar.style = .bar; checkBoxBar.addCheckBox( DZCheckBox(frame: CGRect(x: 0, y: 0, width: 32, height: 32), type: DZCheckBoxType.circular, title: "CheckBar 01", checkedColor: UIColor.orange)); checkBoxBar.addCheckBox( DZCheckBox(frame: CGRect(x: 0, y: 0, width: 32, height: 32), type: DZCheckBoxType.circular, title: "CheckBar 02", borderColor: UIColor.orange)); checkBoxBar.addCheckBox( DZCheckBox(frame: CGRect(x: 0, y: 0, width: 32, height: 32), type: DZCheckBoxType.circular, title: "CheckBar 03", borderColor: UIColor.orange)); checkBoxBar.checkedIndexes = [0]; checkBoxBar.multipleCheckEnabled = false; self.view.addSubview(checkBoxBar); let checkBoxList = DZCheckBoxGroup(frame: CGRect(x: 10, y: 340, width: 200, height: 240)); checkBoxList.style = .list; checkBoxList.addCheckBox( DZCheckBox(frame: CGRect(x: 0, y: 0, width: 32, height: 32), type: DZCheckBoxType.circular, title: "CheckList 01", checkedColor: UIColor.orange)); checkBoxList.addCheckBox( DZCheckBox(frame: CGRect(x: 0, y: 0, width: 32, height: 32), type: DZCheckBoxType.circular, title: "CheckList 02", borderColor: UIColor.orange)); checkBoxList.addCheckBox( DZCheckBox(frame: CGRect(x: 0, y: 0, width: 32, height: 32), type: DZCheckBoxType.circular, title: "CheckList 03", borderColor: UIColor.orange)); checkBoxList.checkedIndexes = [0]; checkBoxList.multipleCheckEnabled = true; self.view.addSubview(checkBoxList); } @IBAction internal func onCheckBoxValueChanged(_ sender: AnyObject) { debugPrint("AAAAAAAA"); } @objc internal func onCheckBoxGroupValueChanged(_ sender: AnyObject) { let group = sender as! DZCheckBoxGroup; debugPrint(group.checkedIndexes); } }
mit
620be80965474f6aa1df67bbf179f2fd
45.864078
111
0.615496
4.298308
false
false
false
false
mrdepth/EVEUniverse
Neocom/Neocom/Fitting/Stats/FittingEditorResistancesStats.swift
2
4264
// // FittingEditorResistancesStats.swift // Neocom // // Created by Artem Shimanski on 3/12/20. // Copyright © 2020 Artem Shimanski. All rights reserved. // import SwiftUI import Dgmpp struct ResistanceView: View { @ObservedObject var ship: DGMShip var resistance: DGMPercent var damageType: DamageType var body: some View { Text(String("\(Int(resistance * 100))%")) .lineLimit(1) .frame(maxWidth: .infinity, minHeight: 18) .padding(.horizontal, 4) .background(ProgressView(progress: Float(resistance))) .background(Color(.black)) .foregroundColor(.white) .accentColor(damageType.accentColor) } } struct ResistancesLayerView: View { @ObservedObject var ship: DGMShip var damage: DGMDamageVector var body: some View { Group { ResistanceView(ship: ship, resistance: damage.em, damageType: .em) ResistanceView(ship: ship, resistance: damage.thermal, damageType: .thermal) ResistanceView(ship: ship, resistance: damage.kinetic, damageType: .kinetic) ResistanceView(ship: ship, resistance: damage.explosive, damageType: .explosive) } } } struct FittingEditorResistancesStats: View { private enum HPColumn {} @ObservedObject var ship: DGMShip @State private var hpColumnWidth: CGFloat? var body: some View { let resistances = ship.resistances let damagePattern = ship.damagePattern let hp = ship.hitPoints let ehp = ship.effectiveHitPoints let formatter = UnitFormatter(unit: .none, style: .short) return Section(header: Text("RESISTANCES")) { VStack(spacing: 2) { HStack { Color.clear.frame(width: 16, height: 0) Icon(Image("em"), size: .small).frame(maxWidth: .infinity) Icon(Image("thermal"), size: .small).frame(maxWidth: .infinity) Icon(Image("kinetic"), size: .small).frame(maxWidth: .infinity) Icon(Image("explosion"), size: .small).frame(maxWidth: .infinity) Text("HP").sizePreference(HPColumn.self).frame(width: hpColumnWidth) } HStack { Icon(Image("shield"), size: .small) ResistancesLayerView(ship: ship, damage: DGMDamageVector(resistances.shield)) Text("\(formatter.string(from: hp.shield))").sizePreference(HPColumn.self).frame(width: hpColumnWidth) } HStack { Icon(Image("armor"), size: .small) ResistancesLayerView(ship: ship, damage: DGMDamageVector(resistances.armor)) Text("\(formatter.string(from: hp.armor))").sizePreference(HPColumn.self).frame(width: hpColumnWidth) } HStack { Icon(Image("hull"), size: .small) ResistancesLayerView(ship: ship, damage: DGMDamageVector(resistances.hull)) Text("\(formatter.string(from: hp.hull))").sizePreference(HPColumn.self).frame(width: hpColumnWidth) } Divider() HStack { Icon(Image("damagePattern"), size: .small) ResistancesLayerView(ship: ship, damage: damagePattern) Color.clear.frame(width: hpColumnWidth) } Divider() Text("EHP: \(UnitFormatter.localizedString(from: ehp.shield + ehp.armor + ehp.hull, unit: .none, style: .long))").frame(maxWidth: .infinity, alignment: .trailing) }.font(.caption) .lineLimit(1) .onSizeChange(HPColumn.self) {self.hpColumnWidth = $0.map{$0.width}.max()} } } } #if DEBUG struct FittingEditorResistancesStats_Previews: PreviewProvider { static var previews: some View { let gang = DGMGang.testGang() return List { FittingEditorResistancesStats(ship: gang.pilots.first!.ship!) }.listStyle(GroupedListStyle()) .environmentObject(gang) .modifier(ServicesViewModifier.testModifier()) } } #endif
lgpl-2.1
11a29d9ab0688a3b8ad06b362bf12089
39.216981
178
0.589256
4.345566
false
false
false
false
alblue/swift
stdlib/public/core/Hasher.swift
1
15003
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Defines the Hasher struct, representing Swift's standard hash function. // //===----------------------------------------------------------------------===// import SwiftShims @inline(__always) internal func _loadPartialUnalignedUInt64LE( _ p: UnsafeRawPointer, byteCount: Int ) -> UInt64 { var result: UInt64 = 0 switch byteCount { case 7: result |= UInt64(p.load(fromByteOffset: 6, as: UInt8.self)) &<< 48 fallthrough case 6: result |= UInt64(p.load(fromByteOffset: 5, as: UInt8.self)) &<< 40 fallthrough case 5: result |= UInt64(p.load(fromByteOffset: 4, as: UInt8.self)) &<< 32 fallthrough case 4: result |= UInt64(p.load(fromByteOffset: 3, as: UInt8.self)) &<< 24 fallthrough case 3: result |= UInt64(p.load(fromByteOffset: 2, as: UInt8.self)) &<< 16 fallthrough case 2: result |= UInt64(p.load(fromByteOffset: 1, as: UInt8.self)) &<< 8 fallthrough case 1: result |= UInt64(p.load(fromByteOffset: 0, as: UInt8.self)) fallthrough case 0: return result default: _sanityCheckFailure() } } extension Hasher { /// This is a buffer for segmenting arbitrary data into 8-byte chunks. Buffer /// storage is represented by a single 64-bit value in the format used by the /// finalization step of SipHash. (The least significant 56 bits hold the /// trailing bytes, while the most significant 8 bits hold the count of bytes /// appended so far, modulo 256. The count of bytes currently stored in the /// buffer is in the lower three bits of the byte count.) // FIXME: Remove @usableFromInline and @_fixed_layout once Hasher is resilient. // rdar://problem/38549901 @usableFromInline @_fixed_layout internal struct _TailBuffer { // msb lsb // +---------+-------+-------+-------+-------+-------+-------+-------+ // |byteCount| tail (<= 56 bits) | // +---------+-------+-------+-------+-------+-------+-------+-------+ internal var value: UInt64 @inline(__always) internal init() { self.value = 0 } @inline(__always) internal init(tail: UInt64, byteCount: UInt64) { // byteCount can be any value, but we only keep the lower 8 bits. (The // lower three bits specify the count of bytes stored in this buffer.) // FIXME: This should be a single expression, but it causes exponential // behavior in the expression type checker <rdar://problem/42672946>. let shiftedByteCount: UInt64 = ((byteCount & 7) << 3) let mask: UInt64 = (1 << shiftedByteCount - 1) _sanityCheck(tail & ~mask == 0) self.value = (byteCount &<< 56 | tail) } @inline(__always) internal init(tail: UInt64, byteCount: Int) { self.init(tail: tail, byteCount: UInt64(truncatingIfNeeded: byteCount)) } internal var tail: UInt64 { @inline(__always) get { return value & ~(0xFF &<< 56) } } internal var byteCount: UInt64 { @inline(__always) get { return value &>> 56 } } @inline(__always) internal mutating func append(_ bytes: UInt64) -> UInt64 { let c = byteCount & 7 if c == 0 { value = value &+ (8 &<< 56) return bytes } let shift = c &<< 3 let chunk = tail | (bytes &<< shift) value = (((value &>> 56) &+ 8) &<< 56) | (bytes &>> (64 - shift)) return chunk } @inline(__always) internal mutating func append(_ bytes: UInt64, count: UInt64) -> UInt64? { _sanityCheck(count >= 0 && count < 8) _sanityCheck(bytes & ~((1 &<< (count &<< 3)) &- 1) == 0) let c = byteCount & 7 let shift = c &<< 3 if c + count < 8 { value = (value | (bytes &<< shift)) &+ (count &<< 56) return nil } let chunk = tail | (bytes &<< shift) value = ((value &>> 56) &+ count) &<< 56 if c + count > 8 { value |= bytes &>> (64 - shift) } return chunk } } } extension Hasher { // FIXME: Remove @usableFromInline and @_fixed_layout once Hasher is resilient. // rdar://problem/38549901 @usableFromInline @_fixed_layout internal struct _Core { private var _buffer: _TailBuffer private var _state: Hasher._State @inline(__always) internal init(state: Hasher._State) { self._buffer = _TailBuffer() self._state = state } @inline(__always) internal init() { self.init(state: _State()) } @inline(__always) internal init(seed: Int) { self.init(state: _State(seed: seed)) } @inline(__always) internal mutating func combine(_ value: UInt) { #if arch(i386) || arch(arm) combine(UInt32(truncatingIfNeeded: value)) #else combine(UInt64(truncatingIfNeeded: value)) #endif } @inline(__always) internal mutating func combine(_ value: UInt64) { _state.compress(_buffer.append(value)) } @inline(__always) internal mutating func combine(_ value: UInt32) { let value = UInt64(truncatingIfNeeded: value) if let chunk = _buffer.append(value, count: 4) { _state.compress(chunk) } } @inline(__always) internal mutating func combine(_ value: UInt16) { let value = UInt64(truncatingIfNeeded: value) if let chunk = _buffer.append(value, count: 2) { _state.compress(chunk) } } @inline(__always) internal mutating func combine(_ value: UInt8) { let value = UInt64(truncatingIfNeeded: value) if let chunk = _buffer.append(value, count: 1) { _state.compress(chunk) } } @inline(__always) internal mutating func combine(bytes: UInt64, count: Int) { _sanityCheck(count >= 0 && count < 8) let count = UInt64(truncatingIfNeeded: count) if let chunk = _buffer.append(bytes, count: count) { _state.compress(chunk) } } @inline(__always) internal mutating func combine(bytes: UnsafeRawBufferPointer) { var remaining = bytes.count guard remaining > 0 else { return } var data = bytes.baseAddress! // Load first unaligned partial word of data do { let start = UInt(bitPattern: data) let end = _roundUp(start, toAlignment: MemoryLayout<UInt64>.alignment) let c = min(remaining, Int(end - start)) if c > 0 { let chunk = _loadPartialUnalignedUInt64LE(data, byteCount: c) combine(bytes: chunk, count: c) data += c remaining -= c } } _sanityCheck( remaining == 0 || Int(bitPattern: data) & (MemoryLayout<UInt64>.alignment - 1) == 0) // Load as many aligned words as there are in the input buffer while remaining >= MemoryLayout<UInt64>.size { combine(UInt64(littleEndian: data.load(as: UInt64.self))) data += MemoryLayout<UInt64>.size remaining -= MemoryLayout<UInt64>.size } // Load last partial word of data _sanityCheck(remaining >= 0 && remaining < 8) if remaining > 0 { let chunk = _loadPartialUnalignedUInt64LE(data, byteCount: remaining) combine(bytes: chunk, count: remaining) } } @inline(__always) internal mutating func finalize() -> UInt64 { return _state.finalize(tailAndByteCount: _buffer.value) } } } /// The universal hash function used by `Set` and `Dictionary`. /// /// `Hasher` can be used to map an arbitrary sequence of bytes to an integer /// hash value. You can feed data to the hasher using a series of calls to /// mutating `combine` methods. When you've finished feeding the hasher, the /// hash value can be retrieved by calling `finalize()`: /// /// var hasher = Hasher() /// hasher.combine(23) /// hasher.combine("Hello") /// let hashValue = hasher.finalize() /// /// Within the execution of a Swift program, `Hasher` guarantees that finalizing /// it will always produce the same hash value as long as it is fed the exact /// same sequence of bytes. However, the underlying hash algorithm is designed /// to exhibit avalanche effects: slight changes to the seed or the input byte /// sequence will typically produce drastic changes in the generated hash value. /// /// - Note: Do not save or otherwise reuse hash values across executions of your /// program. `Hasher` is usually randomly seeded, which means it will return /// different values on every new execution of your program. The hash /// algorithm implemented by `Hasher` may itself change between any two /// versions of the standard library. @_fixed_layout // FIXME: Should be resilient (rdar://problem/38549901) public struct Hasher { internal var _core: _Core /// Creates a new hasher. /// /// The hasher uses a per-execution seed value that is set during process /// startup, usually from a high-quality random source. @_effects(releasenone) public init() { self._core = _Core() } /// Initialize a new hasher using the specified seed value. /// The provided seed is mixed in with the global execution seed. @usableFromInline @_effects(releasenone) internal init(_seed: Int) { self._core = _Core(seed: _seed) } /// Initialize a new hasher using the specified seed value. @usableFromInline // @testable @_effects(releasenone) internal init(_rawSeed: (UInt64, UInt64)) { self._core = _Core(state: _State(rawSeed: _rawSeed)) } /// Indicates whether we're running in an environment where hashing needs to /// be deterministic. If this is true, the hash seed is not random, and hash /// tables do not apply per-instance perturbation that is not repeatable. /// This is not recommended for production use, but it is useful in certain /// test environments where randomization may lead to unwanted nondeterminism /// of test results. @inlinable internal static var _isDeterministic: Bool { @inline(__always) get { return _swift_stdlib_Hashing_parameters.deterministic } } /// The 128-bit hash seed used to initialize the hasher state. Initialized /// once during process startup. @inlinable // @testable internal static var _executionSeed: (UInt64, UInt64) { @inline(__always) get { // The seed itself is defined in C++ code so that it is initialized during // static construction. Almost every Swift program uses hash tables, so // initializing the seed during the startup seems to be the right // trade-off. return ( _swift_stdlib_Hashing_parameters.seed0, _swift_stdlib_Hashing_parameters.seed1) } } /// Adds the given value to this hasher, mixing its essential parts into the /// hasher state. /// /// - Parameter value: A value to add to the hasher. @inlinable @inline(__always) public mutating func combine<H: Hashable>(_ value: H) { value.hash(into: &self) } @_effects(releasenone) @usableFromInline internal mutating func _combine(_ value: UInt) { _core.combine(value) } @_effects(releasenone) @usableFromInline internal mutating func _combine(_ value: UInt64) { _core.combine(value) } @_effects(releasenone) @usableFromInline internal mutating func _combine(_ value: UInt32) { _core.combine(value) } @_effects(releasenone) @usableFromInline internal mutating func _combine(_ value: UInt16) { _core.combine(value) } @_effects(releasenone) @usableFromInline internal mutating func _combine(_ value: UInt8) { _core.combine(value) } @_effects(releasenone) @usableFromInline internal mutating func _combine(bytes value: UInt64, count: Int) { _core.combine(bytes: value, count: count) } /// Adds the contents of the given buffer to this hasher, mixing it into the /// hasher state. /// /// - Parameter bytes: A raw memory buffer. @_effects(releasenone) public mutating func combine(bytes: UnsafeRawBufferPointer) { _core.combine(bytes: bytes) } /// Finalize the hasher state and return the hash value. /// Finalizing invalidates the hasher; additional bits cannot be combined /// into it, and it cannot be finalized again. @_effects(releasenone) @usableFromInline internal mutating func _finalize() -> Int { return Int(truncatingIfNeeded: _core.finalize()) } /// Finalizes the hasher state and returns the hash value. /// /// Finalizing consumes the hasher: it is illegal to finalize a hasher you /// don't own, or to perform operations on a finalized hasher. (These may /// become compile-time errors in the future.) /// /// Hash values are not guaranteed to be equal across different executions of /// your program. Do not save hash values to use during a future execution. /// /// - Returns: The hash value calculated by the hasher. @_effects(releasenone) public __consuming func finalize() -> Int { var core = _core return Int(truncatingIfNeeded: core.finalize()) } @_effects(readnone) @usableFromInline internal static func _hash(seed: Int, _ value: UInt64) -> Int { var state = _State(seed: seed) state.compress(value) let tbc = _TailBuffer(tail: 0, byteCount: 8) return Int(truncatingIfNeeded: state.finalize(tailAndByteCount: tbc.value)) } @_effects(readnone) @usableFromInline internal static func _hash(seed: Int, _ value: UInt) -> Int { var state = _State(seed: seed) #if arch(i386) || arch(arm) _sanityCheck(UInt.bitWidth < UInt64.bitWidth) let tbc = _TailBuffer( tail: UInt64(truncatingIfNeeded: value), byteCount: UInt.bitWidth &>> 3) #else _sanityCheck(UInt.bitWidth == UInt64.bitWidth) state.compress(UInt64(truncatingIfNeeded: value)) let tbc = _TailBuffer(tail: 0, byteCount: 8) #endif return Int(truncatingIfNeeded: state.finalize(tailAndByteCount: tbc.value)) } @_effects(readnone) @usableFromInline internal static func _hash( seed: Int, bytes value: UInt64, count: Int) -> Int { _sanityCheck(count >= 0 && count < 8) var state = _State(seed: seed) let tbc = _TailBuffer(tail: value, byteCount: count) return Int(truncatingIfNeeded: state.finalize(tailAndByteCount: tbc.value)) } @_effects(readnone) @usableFromInline internal static func _hash( seed: Int, bytes: UnsafeRawBufferPointer) -> Int { var core = _Core(seed: seed) core.combine(bytes: bytes) return Int(truncatingIfNeeded: core.finalize()) } }
apache-2.0
2ff8d7c271443424d11ae77c8da4f03f
31.615217
81
0.63094
4.134197
false
false
false
false
automationWisdri/WISData.JunZheng
WISData.JunZheng/View/Operation/OperationView.swift
1
9220
// // OperationView.swift // WISData.JunZheng // // Created by Allen on 16/9/6. // Copyright © 2016 Wisdri. All rights reserved. // import UIKit import SwiftyJSON class OperationView: UIView { @IBOutlet weak var viewTitleLabel: UILabel! @IBOutlet weak var dataView: UIView! private var firstColumnView: UIView! private var scrollView: UIScrollView! private var firstColumnTableView: DataTableView! private var columnTableView = [DataTableView]() private var switchRowCount = [Int]() private var totalRowCount = 0 private var tableTitleJSON = JSON.null var tableContentJSON = [JSON]() var switchContentJSON = [[JSON]]() var viewHeight: CGFloat = CGFloat(35.0) override func awakeFromNib() { super.awakeFromNib() // Basic setup self.backgroundColor = UIColor.whiteColor() self.viewTitleLabel.backgroundColor = UIColor.wisGrayColor().colorWithAlphaComponent(0.3) } func initialDrawTable(switchRowCount: [Int], viewHeight: CGFloat) { self.dataView.removeAllSubviews() self.switchRowCount = switchRowCount self.totalRowCount = switchRowCount.reduce(0, combine: + ) // Get table column title if let path = NSBundle.mainBundle().pathForResource("OperationTitle", ofType: "json") { let data = NSData(contentsOfFile: path) tableTitleJSON = JSON(data: data!) } else { tableTitleJSON = JSON.null } // Define the table dimensions let dataViewWidth = CURRENT_SCREEN_WIDTH let dataViewHeight = viewHeight - WISCommon.viewHeaderTitleHeight // let firstColumnViewWidth: CGFloat = 90 // -2 是因为 KEY "No" 和 "SwitchTimes" 不作为表格列名 let opColumnCount = Operation().propertyNames().count - 2 let switchColumnCount = SwitchTime().propertyNames().count let totalColumnCount = opColumnCount + switchColumnCount // Draw view for first column firstColumnView = UIView(frame: CGRectMake(0, 0, WISCommon.firstColumnViewWidth, dataViewHeight)) firstColumnView.backgroundColor = UIColor.whiteColor() // headerView.userInteractionEnabled = true self.dataView.addSubview(firstColumnView) // Draw first column table firstColumnTableView = DataTableView(frame: firstColumnView.bounds, style: .Plain, rowInfo: switchRowCount) firstColumnTableView.dataTableDelegate = self firstColumnView.addSubview(firstColumnTableView) // Draw view for data table scrollView = UIScrollView(frame: CGRectMake (WISCommon.firstColumnViewWidth, 0, dataViewWidth - WISCommon.firstColumnViewWidth, dataViewHeight)) scrollView.contentSize = CGSizeMake(CGFloat(totalColumnCount) * WISCommon.DataTableColumnWidth, DataTableHeaderRowHeight + CGFloat(totalRowCount) * DataTableBaseRowHeight) scrollView.showsHorizontalScrollIndicator = true scrollView.showsVerticalScrollIndicator = true scrollView.bounces = true scrollView.delegate = self scrollView.backgroundColor = UIColor.whiteColor() self.dataView.addSubview(scrollView) // Draw data table self.columnTableView.removeAll() var tableColumnsCount = 0 for p in Operation().propertyNames() { if p == "No" || p == "SwitchTimes" { continue } else { let tempColumnTableView = DataTableView(frame: CGRectMake(CGFloat(tableColumnsCount) * WISCommon.DataTableColumnWidth, 0, WISCommon.DataTableColumnWidth, dataViewHeight), style: .Plain, rowInfo: switchRowCount) self.columnTableView.append(tempColumnTableView) self.columnTableView[tableColumnsCount].dataTableDelegate = self self.scrollView.addSubview(self.columnTableView[tableColumnsCount]) tableColumnsCount += 1 } } for _ in SwitchTime().propertyNames() { let tempColumnTableView = DataTableView(frame: CGRectMake(CGFloat(tableColumnsCount) * WISCommon.DataTableColumnWidth, 0, WISCommon.DataTableColumnWidth, dataViewHeight), style: .Plain, rowInfo: nil) self.columnTableView.append(tempColumnTableView) self.columnTableView[tableColumnsCount].dataTableDelegate = self self.scrollView.addSubview(self.columnTableView[tableColumnsCount]) tableColumnsCount += 1 } fillDataTableContent() } func arrangeOperationSubView(viewHeight: CGFloat) { // Define the table dimensions let dataViewWidth = CURRENT_SCREEN_WIDTH let dataViewHeight = viewHeight - WISCommon.viewHeaderTitleHeight guard let scrollView = self.scrollView else { return } scrollView.frame = CGRectMake(WISCommon.firstColumnViewWidth, 0, dataViewWidth - WISCommon.firstColumnViewWidth, dataViewHeight) /* * Issue 1 中的 4# 问题,暂未解决 let opColumnCount = Operation().propertyNames().count - 2 let switchColumnCount = SwitchTime().propertyNames().count let totalColumnCount = opColumnCount + switchColumnCount if ( dataViewWidth - WISCommon.firstColumnViewWidth ) > CGFloat(totalColumnCount) * WISCommon.DataTableColumnWidth { // 重绘表格 let dataTableColumnWidth: CGFloat = ( dataViewWidth - WISCommon.firstColumnViewWidth) / CGFloat(totalColumnCount) let subviews = scrollView.subviews as! [DataTableView] for subview in subviews { subview.bounds.size = CGSize(width: dataTableColumnWidth, height: dataViewHeight) subview.layoutIfNeeded() } } */ } private func fillDataTableContent() { firstColumnTableView.viewModel.headerString = SearchParameter["date"]! + "\n" + getShiftName(SearchParameter["shiftNo"]!)[0] let firstColumnTitleArray = DJName firstColumnTableView.viewModel.titleArray = firstColumnTitleArray self.firstColumnTableView.viewModel.titleArraySubject .onNext(firstColumnTitleArray) var tableColumnsCount = 0 for p in Operation().propertyNames() { if p == "No" || p == "SwitchTimes" { continue } else { // header let columnTitle: String = self.tableTitleJSON["title"][p].stringValue self.columnTableView[tableColumnsCount].viewModel.headerString = columnTitle // content var contentArray: [String] = [] for j in 0 ..< self.tableContentJSON.count { let content = self.tableContentJSON[j][p].stringValue.trimNumberFromFractionalPart(2) contentArray.append(content) } self.columnTableView[tableColumnsCount].viewModel.titleArray = contentArray self.columnTableView[tableColumnsCount].viewModel.titleArraySubject.onNext(contentArray) self.columnTableView[tableColumnsCount].reloadData() tableColumnsCount += 1 } } for p in SwitchTime().propertyNames() { // header let columnTitle: String = self.tableTitleJSON["title"]["SwitchTimes"][p].stringValue self.columnTableView[tableColumnsCount].viewModel.headerString = columnTitle // content var contentArray: [String] = [] for i in 0 ..< self.tableContentJSON.count { if self.switchContentJSON[i].count == 0 { contentArray.append(EMPTY_STRING) } else { for j in 0 ..< self.switchRowCount[i] { let content = self.switchContentJSON[i][j][p].stringValue contentArray.append(content) } } } self.columnTableView[tableColumnsCount].viewModel.titleArray = contentArray self.columnTableView[tableColumnsCount].viewModel.titleArraySubject .onNext(contentArray) tableColumnsCount += 1 } } } // MARK: - Extension extension OperationView: DataTableViewDelegate { func dataTableViewContentOffSet(contentOffSet: CGPoint) { for subView in scrollView.subviews { if subView.isKindOfClass(DataTableView) { (subView as! DataTableView).setTableViewContentOffSet(contentOffSet) } } for subView in firstColumnView.subviews { (subView as! DataTableView).setTableViewContentOffSet(contentOffSet) } } } extension OperationView: UIScrollViewDelegate { func scrollViewDidScroll(scrollView: UIScrollView) { // let p: CGPoint = scrollView.contentOffset // print(NSStringFromCGPoint(p)) } }
mit
ccffa996befa70056ce6229ce3c3ef91
40.686364
226
0.633628
5.249571
false
false
false
false
smud/Smud
Sources/Smud/Data/Mobile.swift
1
923
// // Mobile.swift // // This source file is part of the SMUD open source project // // Copyright (c) 2016 SMUD project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SMUD project authors // import Foundation public class Mobile: Creature { public let prototype: Entity public var id: String public var home: Room? public var shortDescription: String public init(prototype: Entity, world: World) { self.prototype = prototype let id = prototype["mobile"]?.string ?? "" assert(id != "") self.id = id let name = prototype["name"]?.string ?? "No name" shortDescription = prototype["short"]?.string ?? "" super.init(name: name, world: world) health = prototype["health"]?.int ?? health } }
apache-2.0
f89a9ddc98111939ef2d5565554e83cc
23.945946
68
0.629469
4.416268
false
false
false
false
Gaea-iOS/SegmentedControl
SegmentedControl/Classes/Slider.swift
1
956
// // Slider.swift // Pods // // Created by 王小涛 on 2016/12/20. // // import Foundation public class Slider: UIView { private let slider = UIView() private var sliderSize: CGSize = CGSize(width: 0, height: 2) public convenience init(isSelected: Bool, color: UIColor = UIColor(red: 1.0, green: 0.4, blue: 0.6, alpha: 1), size: CGSize = CGSize(width: 0, height: 2)) { self.init() addSubview(slider) slider.backgroundColor = color sliderSize = size slider.isHidden = !isSelected } public override var frame: CGRect { didSet { super.frame = frame let width = min(sliderSize.width < 1 ? bounds.width: sliderSize.width, bounds.width) let x = (bounds.width - width) / 2 let y = bounds.height - sliderSize.height self.slider.frame = CGRect(x: x, y: y, width: width, height: sliderSize.height) } } }
mit
0811150018f5934c2bb1a1d2670d1e33
27.787879
160
0.590526
3.740157
false
false
false
false
ebluehands/LuhnModN
LuhnModN/LuhnModN.swift
1
6304
// // LuhnModN.swift // LuhnModN // // Created by Arnaud Bultot on 17/12/15. // Copyright © 2015 ebluehands. All rights reserved. // /* The MIT License (MIT) Copyright (c) 2015 Arnaud Bultot 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 Darwin enum LuhnError: Error { case invalidCharacters case moduloOutOfRange } /// This is an implementation of the [Luhn mod N algorithm](https://en.wikipedia.org/wiki/Luhn_mod_N_algorithm) public class LuhnModN { // MARK: Public /** Check if a string is valid - Parameter sequence: The string to validate - Parameter mod: The mod in which to compute. It corresponds to the number of valid characters - Returns: true if the string is valid, false otherwise */ public static func isValid(_ sequence: String, withModulo mod: Int = 10) -> Bool { guard validate(modulo: mod) && !containsInvalidCharacters(sequence, withModulo: Int32(mod)) else { return false } let sum = calculateLuhnSum(for: sequence, withModulo: mod, shouldDouble: { ($0 % 2 != 0) }) let remainder = sum % mod return remainder == 0 } /** Add the check character - Parameter sequence: The string to add the check character - Parameter mod: The mod in which to compute. It corresponds to the number of valid characters - Throws: LuhnError - Returns: The string with the check character */ public static func addCheckCharacter(to sequence: String, withModulo mod: Int = 10) throws -> String { guard validate(modulo: mod) else { throw LuhnError.moduloOutOfRange } guard !containsInvalidCharacters(sequence, withModulo: Int32(mod)) else { throw LuhnError.invalidCharacters } return sequence + generateCheckCharacter(for: sequence, withModulo : mod) } // MARK: Private /** Calculate the luhn sum - Parameter sequence: The string - Parameter mod: The mod in which to compute. It corresponds to the number of valid characters - Parameter shouldDouble: A closure to know if the value should be doubled or not - Returns: The Luhn sum */ private static func calculateLuhnSum(for sequence: String, withModulo mod: Int, shouldDouble: (_ index : Int) -> Bool) -> Int { return sequence .reversed() .map { codePoint(fromCharacter: $0, withModulo: Int32(mod)) } .enumerated() .map { sum(digits: $1 * ((shouldDouble($0)) ? 2 : 1), withModulo : mod) } .reduce(0, +) } /** Calculate the check character - Parameter sequence: The input to string from which the check character should be calculated - Parameter mod: The mod in which to compute. It corresponds to the number of valid characters - Returns: The check character */ private static func generateCheckCharacter(for sequence: String, withModulo mod: Int) -> String { let sum = calculateLuhnSum(for: sequence, withModulo : mod, shouldDouble: { ($0 % 2 == 0) }) let remainder = sum % mod let checkCodePoint = (mod - remainder) % mod return character(fromCodePoint: checkCodePoint, withModulo : mod) } /** Check if a string contains invalid characters - Parameter sequence : The string to check - Parameter mod: The mod in which to compute. It corresponds to the number of valid characters - Returns: true if one or more invalid characters were found, true otherwise */ private static func containsInvalidCharacters(_ sequence: String, withModulo mod: Int32) -> Bool { return sequence .reduce(false) { $0 || (strtoul(String($1), nil, mod) == 0 && $1 != "0") } } /** Validate the mod. The mod should be between 2 and 36 inclusive - Parameter mod: The mod - Returns: true if the mod is valid, false otherwise */ private static func validate(modulo mod: Int) -> Bool { return mod > 1 && mod < 37 } /** Get the int value of a character - Parameter character: The character - Parameter mod: The mod in which to compute. It corresponds to the number of valid characters - Returns: The int value of the character */ private static func codePoint(fromCharacter character: Character, withModulo mod: Int32) -> Int { return Int(strtoul(String(character), nil, mod)) } /** Get the string value of an int - Parameter codePoint: The int to convert - Parameter mod: The mod in which to compute. It corresponds to the number of valid characters - Returns: The string value of the integer */ private static func character(fromCodePoint codePoint: Int, withModulo mod: Int) -> String { return String(codePoint, radix: mod) } /** Sum the digits of a number - Parameter addend: The number - Parameter mod: The mod in which to compute. It corresponds to the number of valid characters - Returns : The sum of its digit */ private static func sum(digits addend: Int, withModulo mod: Int) -> Int { return (addend / mod) + (addend % mod) } }
mit
49ee3fa652007065c4c0564aaabf86a7
35.017143
131
0.663335
4.550903
false
false
false
false
whereuat/whereuat-ios
whereuat-ios/Views/SettingsView/SettingsViewController.swift
1
1094
// // SettingsViewController.swift // whereuat // // Created by Raymond Jacobson on 5/11/16. // Copyright © 2016 whereuat. All rights reserved. // import UIKit class SettingsViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() self.drawVersionTextView() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.setNavigationBarItems("Settings") } func drawVersionTextView() { let textBoxWidth = CGFloat(100) let versionTextView = UITextView(frame: CGRect(x: (self.view.frame.size.width/2 - textBoxWidth/2), y: 100, width: 100, height: 200)) let versionNumber: AnyObject? = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] versionTextView.text = "whereu@ Version " + String(versionNumber!) versionTextView.font = FontStyle.p versionTextView.textColor = ColorWheel.darkGray versionTextView.textAlignment = NSTextAlignment.Center self.view.addSubview(versionTextView) } }
apache-2.0
eedf5b005ce937234304d4ef568b919d
31.176471
140
0.686185
4.592437
false
false
false
false
Raizlabs/RIGImageGallery
RIGImageGallery/RIGAutoCenteringScrollView.swift
1
4610
// // RIGAutoCenteringScrollView.swift // RIGPhotoViewer // // Created by Michael Skiba on 2/9/16. // Copyright © 2016 Raizlabs. All rights reserved. // import UIKit open class RIGAutoCenteringScrollView: UIScrollView { internal var allowZoom: Bool = false internal var baseInsets: UIEdgeInsets = UIEdgeInsets() { didSet { updateZoomScale(preserveScale: true) } } open var zoomImage: UIImage? { didSet { if oldValue === zoomImage { return } if let img = zoomImage { contentView.isHidden = false contentView.image = img } else { contentView.isHidden = true } updateZoomScale(preserveScale: false) } } fileprivate var contentView = UIImageView() public override init(frame: CGRect) { super.init(frame: frame) showsVerticalScrollIndicator = false showsHorizontalScrollIndicator = false addSubview(contentView) configureConstraints() delegate = self } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open override var frame: CGRect { didSet { updateZoomScale(preserveScale: true) } } } extension RIGAutoCenteringScrollView { func toggleZoom(animated: Bool = true) { if self.isUserInteractionEnabled { if zoomScale != minimumZoomScale { setZoomScale(minimumZoomScale, animated: animated) } else { setZoomScale(maximumZoomScale, animated: animated) } } } } private extension RIGAutoCenteringScrollView { func configureConstraints() { contentView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ contentView.leadingAnchor.constraint(equalTo: leadingAnchor), contentView.trailingAnchor.constraint(equalTo: trailingAnchor), contentView.topAnchor.constraint(equalTo: topAnchor), contentView.bottomAnchor.constraint(equalTo: bottomAnchor), ]) } func updateZoomScale(preserveScale: Bool) { guard let image = zoomImage else { contentSize = frame.size minimumZoomScale = 1 maximumZoomScale = 1 setZoomScale(1, animated: false) return } updateConstraintsIfNeeded() layoutIfNeeded() let adjustedFrame = UIEdgeInsetsInsetRect(frame, baseInsets) let wScale = adjustedFrame.width / image.size.width let hScale = adjustedFrame.height / image.size.height let oldMin = minimumZoomScale minimumZoomScale = min(wScale, hScale) maximumZoomScale = max(1, minimumZoomScale * 3) if preserveScale { if zoomScale <= oldMin || zoomScale <= minimumZoomScale { contentSize = image.size setZoomScale(minimumZoomScale, animated: false) } } else { contentSize = image.size setZoomScale(minimumZoomScale, animated: false) } centerContent() } // After much fiddling, using insets to correct zoom behavior was found at: http://petersteinberger.com/blog/2013/how-to-center-uiscrollview/ func centerContent() { guard !contentSize.equalTo(CGSize()) else { return } let adjustedSize = UIEdgeInsetsInsetRect(bounds, baseInsets).size let vertical: CGFloat let horizontal: CGFloat if contentSize.width < adjustedSize.width { horizontal = floor((adjustedSize.width - contentSize.width) * 0.5) } else { horizontal = 0 } if contentSize.height < adjustedSize.height { vertical = floor((adjustedSize.height - contentSize.height) * 0.5) } else { vertical = 0 } contentInset = UIEdgeInsets(top: vertical + baseInsets.top, left: horizontal + baseInsets.left, bottom: vertical + baseInsets.bottom, right: horizontal + baseInsets.right) updateConstraintsIfNeeded() layoutIfNeeded() } } extension RIGAutoCenteringScrollView: UIScrollViewDelegate { open func viewForZooming(in scrollView: UIScrollView) -> UIView? { return allowZoom ? contentView : nil } open func scrollViewDidZoom(_ scrollView: UIScrollView) { centerContent() } }
mit
34f8c56ad0bd45c0f85a45834361710e
27.276074
179
0.611412
5.384346
false
false
false
false
arnaudbenard/my-npm
Pods/Charts/Charts/Classes/Data/LineRadarChartDataSet.swift
20
1493
// // LineRadarChartDataSet.swift // Charts // // Created by Daniel Cohen Gindi on 26/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics import UIKit public class LineRadarChartDataSet: BarLineScatterCandleChartDataSet { public var fillColor = UIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0) public var fillAlpha = CGFloat(0.33) private var _lineWidth = CGFloat(1.0) public var drawFilledEnabled = false /// line width of the chart (min = 0.2, max = 10) /// :default: 1 public var lineWidth: CGFloat { get { return _lineWidth } set { _lineWidth = newValue if (_lineWidth < 0.2) { _lineWidth = 0.5 } if (_lineWidth > 10.0) { _lineWidth = 10.0 } } } public var isDrawFilledEnabled: Bool { return drawFilledEnabled } // MARK: NSCopying public override func copyWithZone(zone: NSZone) -> AnyObject { var copy = super.copyWithZone(zone) as! LineRadarChartDataSet copy.fillColor = fillColor copy._lineWidth = _lineWidth copy.drawFilledEnabled = drawFilledEnabled return copy } }
mit
2bcb39573e673c8c3323baf0112f5fdc
23.080645
103
0.58205
4.430267
false
false
false
false
danielgindi/Charts
ChartsDemo-iOS/Swift/Components/XYMarkerView.swift
2
1081
// // XYMarkerView.swift // ChartsDemo-iOS // // Created by Jacob Christie on 2017-07-09. // Copyright © 2017 jc. All rights reserved. // import Foundation import Charts #if canImport(UIKit) import UIKit #endif public class XYMarkerView: BalloonMarker { public var xAxisValueFormatter: AxisValueFormatter fileprivate var yFormatter = NumberFormatter() public init(color: UIColor, font: UIFont, textColor: UIColor, insets: UIEdgeInsets, xAxisValueFormatter: AxisValueFormatter) { self.xAxisValueFormatter = xAxisValueFormatter yFormatter.minimumFractionDigits = 1 yFormatter.maximumFractionDigits = 1 super.init(color: color, font: font, textColor: textColor, insets: insets) } public override func refreshContent(entry: ChartDataEntry, highlight: Highlight) { let string = "x: " + xAxisValueFormatter.stringForValue(entry.x, axis: XAxis()) + ", y: " + yFormatter.string(from: NSNumber(floatLiteral: entry.y))! setLabel(string) } }
apache-2.0
5c07174a7d0ea5b24676b88fcced3924
29.857143
87
0.675
4.556962
false
false
false
false
RMizin/PigeonMessenger-project
FalconMessenger/Supporting Files/CoreManagers/GlobalVariables.swift
1
1430
// // GlobalVariables.swift // FalconMessenger // // Created by Roman Mizin on 8/1/18. // Copyright © 2018 Roman Mizin. All rights reserved. // import UIKit let globalVariables = GlobalVariables() final class GlobalVariables: NSObject { let reportDatabaseURL = "https://pigeon-project-79c81-d6fdd.firebaseio.com/" let imageSourcePhotoLibrary = "imageSourcePhotoLibrary" let imageSourceCamera = "imageSourceCamera" var isInsertingCellsToTop: Bool = false var contentSizeWhenInsertingToTop: CGSize? var localPhones: [String] = [] { didSet { NotificationCenter.default.post(name: .localPhonesUpdated, object: nil) } } } extension NSNotification.Name { static let profilePictureDidSet = NSNotification.Name(Bundle.main.bundleIdentifier! + ".profilePictureDidSet") static let blacklistUpdated = NSNotification.Name(Bundle.main.bundleIdentifier! + ".blacklistUpdated") static let localPhonesUpdated = NSNotification.Name(Bundle.main.bundleIdentifier! + ".localPhones") static let authenticationSucceeded = NSNotification.Name(Bundle.main.bundleIdentifier! + ".authenticationSucceeded") static let inputViewResigned = NSNotification.Name(Bundle.main.bundleIdentifier! + ".inputViewResigned") static let inputViewResponded = NSNotification.Name(Bundle.main.bundleIdentifier! + ".inputViewResponded") static let messageSent = NSNotification.Name(Bundle.main.bundleIdentifier! + ".messageSent") }
gpl-3.0
91b7642b0af99c63a893b2f714307809
41.029412
118
0.782365
4.317221
false
false
false
false
sunlijian/sunlijianRepository
singBlog/singBlog/Classes/Module/Main/MainTabBarController.swift
1
1785
// // MainTabBarController.swift // 新浪微博 // // Created by sunlijian on 15/10/6. // Copyright © 2015年 myCompany. All rights reserved. // import UIKit class MainTabBarController: UITabBarController { @IBOutlet weak var mainTabBar: MainTabBar! override func viewDidLoad() { super.viewDidLoad() //添加 storyboard addChildControllers() mainTabBar.composeButton.addTarget(self, action: "clickButton:", forControlEvents: UIControlEvents.TouchUpInside) } //中间 button 的点击事件 func clickButton(sender: UIButton){ print(sender) } //添加 tabBar对应的storyboard private func addChildControllers(){ //设置 tabBar 的字体 tabBar.tintColor = UIColor.orangeColor() //添加首页 addChildController("Home", "首页", "tabbar_home") //添加 message addChildController("Message", "消息", "tabbar_message_center") //添加 发现 addChildController("Discover", "发现", "tabbar_discover") //添加我 addChildController("Profile", "我", "tabbar_profile") } //添加单个视图 private func addChildController(name:String, _ title:String, _ imageName:String){ //加载storyboard let storyboard = UIStoryboard(name: name, bundle: nil) //设置对应的导航 let nav = storyboard.instantiateInitialViewController() as! UINavigationController //设置导航的 title nav.topViewController?.title = title //设置 tabBar 的图片 nav.tabBarItem.image = UIImage(named: imageName) // //添加到当前的 tabBar 上 addChildViewController(nav) } }
apache-2.0
42498f2c3b32d4c6eeb50dbbdaafed63
25.322581
121
0.619485
4.744186
false
false
false
false
IFTTT/RazzleDazzle
Source/PathPositionAnimation.swift
1
2234
// // PathPositionAnimation.swift // RazzleDazzle // // Created by Laura Skelton on 6/30/15. // Copyright © 2015 IFTTT. All rights reserved. // import UIKit /** Animates the view's position along the given path. */ public class PathPositionAnimation : Animation<CGFloat>, Animatable { private let view : UIView public var path : CGPath? { didSet { createKeyframeAnimation() } } private let animationKey = "PathPosition" public var rotationMode : String? = kCAAnimationRotateAuto { didSet { createKeyframeAnimation() } } public init(view: UIView, path: CGPath?) { self.view = view self.path = path super.init() createKeyframeAnimation() // CAAnimations are lost when application enters the background, so re-add them NotificationCenter.default.addObserver( self, selector: #selector(PathPositionAnimation.createKeyframeAnimation), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil) } deinit { NotificationCenter.default.removeObserver(self) } public func animate(_ time: CGFloat) { if !hasKeyframes() {return} view.layer.timeOffset = CFTimeInterval(self[time]) } public override func validateValue(_ value: CGFloat) -> Bool { return (value >= 0) && (value <= 1) } @objc private func createKeyframeAnimation() { // Set up a CAKeyframeAnimation to move the view along the path view.layer.add(pathAnimation(), forKey: animationKey) view.layer.speed = 0 view.layer.timeOffset = 0 } private func pathAnimation() -> CAKeyframeAnimation { let animation = CAKeyframeAnimation() animation.keyPath = "position" animation.path = path animation.duration = 1 animation.isAdditive = true animation.repeatCount = Float.infinity animation.calculationMode = kCAAnimationPaced animation.rotationMode = rotationMode animation.fillMode = kCAFillModeBoth animation.isRemovedOnCompletion = false return animation } }
mit
359babefb76589d1de3c3954e206b77b
28.773333
87
0.633229
5.029279
false
false
false
false
KyoheiG3/RxSwift
Tests/RxSwiftTests/Observable+SingleTest.swift
1
42401
// // Observable+SingleTest.swift // Tests // // Created by Krunoslav Zaher on 2/8/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation import XCTest import RxSwift import RxTest class ObservableSingleTest : RxTest { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } } // Creation extension ObservableSingleTest { func testAsObservable_asObservable() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(220, 2), completed(250) ]) let ys = xs.asObservable() XCTAssert(xs !== ys) let res = scheduler.start { ys } let correct = [ next(220, 2), completed(250) ] XCTAssertEqual(res.events, correct) } func testAsObservable_hides() { let xs = PrimitiveHotObservable<Int>() let res = xs.asObservable() XCTAssertTrue(res !== xs) } func testAsObservable_never() { let scheduler = TestScheduler(initialClock: 0) let xs : Observable<Int> = Observable.never() let res = scheduler.start { xs } let correct: [Recorded<Event<Int>>] = [] XCTAssertEqual(res.events, correct) } #if TRACE_RESOURCES func testAsObservableReleasesResourcesOnComplete() { _ = Observable<Int>.empty().asObservable().subscribe() } func testAsObservableReleasesResourcesOnError() { _ = Observable<Int>.empty().asObservable().subscribe() } #endif } // Distinct extension ObservableSingleTest { func testDistinctUntilChanged_allChanges() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(210, 2), next(220, 3), next(230, 4), next(240, 5), completed(250) ]) let res = scheduler.start { xs.distinctUntilChanged { $0 } } let correctMessages = [ next(210, 2), next(220, 3), next(230, 4), next(240, 5), completed(250) ] let correctSubscriptions = [ Subscription(200, 250) ] XCTAssertEqual(res.events, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func testDistinctUntilChanged_someChanges() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(210, 2), // * next(215, 3), // * next(220, 3), next(225, 2), // * next(230, 2), next(230, 1), // * next(240, 2), // * completed(250) ]) let res = scheduler.start { xs.distinctUntilChanged { $0 } } let correctMessages = [ next(210, 2), next(215, 3), next(225, 2), next(230, 1), next(240, 2), completed(250) ] let correctSubscriptions = [ Subscription(200, 250) ] XCTAssertEqual(res.events, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func testDistinctUntilChanged_allEqual() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(210, 2), next(220, 3), next(230, 4), next(240, 5), completed(250) ]) let res = scheduler.start { xs.distinctUntilChanged { l, r in true } } let correctMessages = [ next(210, 2), completed(250) ] let correctSubscriptions = [ Subscription(200, 250) ] XCTAssertEqual(res.events, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func testDistinctUntilChanged_allDifferent() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(210, 2), next(220, 2), next(230, 2), next(240, 2), completed(250) ]) let res = scheduler.start { xs.distinctUntilChanged({ l, r in false }) } let correctMessages = [ next(210, 2), next(220, 2), next(230, 2), next(240, 2), completed(250) ] let correctSubscriptions = [ Subscription(200, 250) ] XCTAssertEqual(res.events, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func testDistinctUntilChanged_keySelector_Div2() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(210, 2), next(220, 4), next(230, 3), next(240, 5), completed(250) ]) let res = scheduler.start { xs.distinctUntilChanged({ $0 % 2 }) } let correctMessages = [ next(210, 2), next(230, 3), completed(250) ] let correctSubscriptions = [ Subscription(200, 250) ] XCTAssertEqual(res.events, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func testDistinctUntilChanged_keySelectorThrows() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(210, 2), next(220, 3), completed(250) ]) let res = scheduler.start { xs.distinctUntilChanged({ _ in throw testError }) } let correctMessages = [ next(210, 2), error(220, testError) ] let correctSubscriptions = [ Subscription(200, 220) ] XCTAssertEqual(res.events, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func testDistinctUntilChanged_comparerThrows() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(210, 2), next(220, 3), completed(250) ]) let res = scheduler.start { xs.distinctUntilChanged({ $0 }, comparer: { _, _ in throw testError }) } let correctMessages = [ next(210, 2), error(220, testError) ] let correctSubscriptions = [ Subscription(200, 220) ] XCTAssertEqual(res.events, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } #if TRACE_RESOURCES func testDistinctUntilChangedReleasesResourcesOnComplete() { _ = Observable<Int>.just(1).distinctUntilChanged().subscribe() } func testDistinctUntilChangedReleasesResourcesOnError() { _ = Observable<Int>.error(testError).distinctUntilChanged().subscribe() } #endif } // doOn extension ObservableSingleTest { func testDoOn_shouldSeeAllValues() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(210, 2), next(220, 3), next(230, 4), next(240, 5), completed(250) ]) var i = 0 var sum = 2 + 3 + 4 + 5 let res = scheduler.start { xs.do(onNext: { element in i += 1 sum -= element }) } XCTAssertEqual(i, 4) XCTAssertEqual(sum, 0) let correctMessages = [ next(210, 2), next(220, 3), next(230, 4), next(240, 5), completed(250) ] let correctSubscriptions = [ Subscription(200, 250) ] XCTAssertEqual(res.events, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func testDoOn_plainAction() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(210, 2), next(220, 3), next(230, 4), next(240, 5), completed(250) ]) var i = 0 let res = scheduler.start { xs.do(onNext: { _ in i += 1 }) } XCTAssertEqual(i, 4) let correctMessages = [ next(210, 2), next(220, 3), next(230, 4), next(240, 5), completed(250) ] let correctSubscriptions = [ Subscription(200, 250) ] XCTAssertEqual(res.events, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func testDoOn_nextCompleted() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(210, 2), next(220, 3), next(230, 4), next(240, 5), completed(250) ]) var i = 0 var sum = 2 + 3 + 4 + 5 var completedEvaluation = false let res = scheduler.start { xs.do(onNext: { value in i += 1 sum -= value }, onCompleted: { completedEvaluation = true }) } XCTAssertEqual(i, 4) XCTAssertEqual(sum, 0) XCTAssertEqual(completedEvaluation, true) let correctMessages = [ next(210, 2), next(220, 3), next(230, 4), next(240, 5), completed(250) ] let correctSubscriptions = [ Subscription(200, 250) ] XCTAssertEqual(res.events, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func testDoOn_completedNever() { let scheduler = TestScheduler(initialClock: 0) let recordedEvents: [Recorded<Event<Int>>] = [ ] let xs = scheduler.createHotObservable(recordedEvents) var i = 0 var completedEvaluation = false let res = scheduler.start { xs.do(onNext: { e in i += 1 }, onCompleted: { completedEvaluation = true }) } XCTAssertEqual(i, 0) XCTAssertEqual(completedEvaluation, false) let correctMessages: [Recorded<Event<Int>>] = [ ] let correctSubscriptions = [ Subscription(200, 1000) ] XCTAssertEqual(res.events, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func testDoOn_nextError() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(210, 2), next(220, 3), next(230, 4), next(240, 5), error(250, testError) ]) var i = 0 var sum = 2 + 3 + 4 + 5 var sawError = false let res = scheduler.start { xs.do(onNext: { value in i += 1 sum -= value }, onError: { _ in sawError = true }) } XCTAssertEqual(i, 4) XCTAssertEqual(sum, 0) XCTAssertEqual(sawError, true) let correctMessages = [ next(210, 2), next(220, 3), next(230, 4), next(240, 5), error(250, testError) ] let correctSubscriptions = [ Subscription(200, 250) ] XCTAssertEqual(res.events, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func testDoOn_nextErrorNot() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(210, 2), next(220, 3), next(230, 4), next(240, 5), completed(250) ]) var i = 0 var sum = 2 + 3 + 4 + 5 var sawError = false let res = scheduler.start { xs.do(onNext: { value in i += 1 sum -= value }, onError: { e in sawError = true }) } XCTAssertEqual(i, 4) XCTAssertEqual(sum, 0) XCTAssertEqual(sawError, false) let correctMessages = [ next(210, 2), next(220, 3), next(230, 4), next(240, 5), completed(250) ] let correctSubscriptions = [ Subscription(200, 250) ] XCTAssertEqual(res.events, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func testDoOnNext_normal() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(210, 2), next(220, 3), next(230, 4), next(240, 5), completed(250) ]) var numberOfTimesInvoked = 0 let res = scheduler.start { xs.do(onNext: { error in numberOfTimesInvoked = numberOfTimesInvoked + 1 }) } let correctMessages = [ next(210, 2), next(220, 3), next(230, 4), next(240, 5), completed(250) ] let correctSubscriptions = [ Subscription(200, 250) ] XCTAssertEqual(res.events, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) XCTAssertEqual(numberOfTimesInvoked, 4) } func testDoOnNext_throws() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(210, 2), next(220, 3), next(230, 4), next(240, 5), completed(250) ]) var numberOfTimesInvoked = 0 let res = scheduler.start { xs.do(onNext: { error in if numberOfTimesInvoked > 2 { throw testError } numberOfTimesInvoked = numberOfTimesInvoked + 1 }) } let correctMessages = [ next(210, 2), next(220, 3), next(230, 4), error(240, testError) ] let correctSubscriptions = [ Subscription(200, 240) ] XCTAssertEqual(res.events, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) XCTAssertEqual(numberOfTimesInvoked, 3) } func testDoOnError_normal() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(210, 2), error(250, testError) ]) var recordedError: Swift.Error! var numberOfTimesInvoked = 0 let res = scheduler.start { xs.do(onError: { error in recordedError = error numberOfTimesInvoked = numberOfTimesInvoked + 1 }) } let correctMessages = [ next(210, 2), error(250, testError) ] let correctSubscriptions = [ Subscription(200, 250) ] XCTAssertEqual(res.events, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) XCTAssertEqual(recordedError as! TestError, testError) XCTAssertEqual(numberOfTimesInvoked, 1) } func testDoOnError_throws() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(210, 2), error(250, testError) ]) let res = scheduler.start { xs.do(onError: { _ in throw testError1 }) } let correctMessages = [ next(210, 2), error(250, testError1) ] let correctSubscriptions = [ Subscription(200, 250) ] XCTAssertEqual(res.events, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func testDoOnCompleted_normal() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(210, 2), next(220, 3), next(230, 4), next(240, 5), completed(250) ]) var didComplete = false let res = scheduler.start { xs.do(onCompleted: { error in didComplete = true }) } let correctMessages = [ next(210, 2), next(220, 3), next(230, 4), next(240, 5), completed(250) ] let correctSubscriptions = [ Subscription(200, 250) ] XCTAssertEqual(res.events, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) XCTAssertEqual(didComplete, true) } func testDoOnCompleted_throws() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(210, 2), next(220, 3), next(230, 4), next(240, 5), completed(250) ]) let res = scheduler.start { xs.do(onCompleted: { error in throw testError }) } let correctMessages = [ next(210, 2), next(220, 3), next(230, 4), next(240, 5), error(250, testError) ] let correctSubscriptions = [ Subscription(200, 250) ] XCTAssertEqual(res.events, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } enum DoOnEvent { case sourceSubscribe case sourceDispose case doOnNext case doOnCompleted case doOnError case doOnSubscribe case doOnDispose } func testDoOnOrder_Completed() { var events = [DoOnEvent]() _ = Observable<Int>.create { observer in events.append(.sourceSubscribe) observer.on(.next(0)) observer.on(.completed) return Disposables.create { events.append(.sourceDispose) } } .do( onNext: { _ in events.append(.doOnNext) }, onCompleted: { events.append(.doOnCompleted) }, onSubscribe: { events.append(.doOnSubscribe) }, onDispose: { events.append(.doOnDispose) } ) .subscribe { _ in } XCTAssertEqual(events, [.doOnSubscribe, .sourceSubscribe, .doOnNext, .doOnCompleted, .sourceDispose, .doOnDispose]) } func testDoOnOrder_Error() { var events = [DoOnEvent]() _ = Observable<Int>.create { observer in events.append(.sourceSubscribe) observer.on(.next(0)) observer.on(.error(testError)) return Disposables.create { events.append(.sourceDispose) } } .do( onNext: { _ in events.append(.doOnNext) }, onError: { _ in events.append(.doOnError) }, onSubscribe: { events.append(.doOnSubscribe) }, onDispose: { events.append(.doOnDispose) } ) .subscribe { _ in } XCTAssertEqual(events, [.doOnSubscribe, .sourceSubscribe, .doOnNext, .doOnError, .sourceDispose, .doOnDispose]) } func testDoOnOrder_Dispose() { var events = [DoOnEvent]() Observable<Int>.create { observer in events.append(.sourceSubscribe) observer.on(.next(0)) return Disposables.create { events.append(.sourceDispose) } } .do( onNext: { _ in events.append(.doOnNext) }, onSubscribe: { events.append(.doOnSubscribe) }, onDispose: { events.append(.doOnDispose) } ) .subscribe { _ in } .dispose() XCTAssertEqual(events, [.doOnSubscribe, .sourceSubscribe, .doOnNext, .sourceDispose, .doOnDispose]) } #if TRACE_RESOURCES func testDoReleasesResourcesOnComplete() { _ = Observable<Int>.just(1).do().subscribe() } func testDoReleasesResourcesOnError() { _ = Observable<Int>.error(testError).do().subscribe() } #endif } // retry extension ObservableSingleTest { func testRetry_Basic() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createColdObservable([ next(100, 1), next(150, 2), next(200, 3), completed(250) ]) let res = scheduler.start { xs.retry() } XCTAssertEqual(res.events, [ next(300, 1), next(350, 2), next(400, 3), completed(450) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 450) ]) } func testRetry_Infinite() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createColdObservable([ next(100, 1), next(150, 2), next(200, 3), ]) let res = scheduler.start { xs.retry() } XCTAssertEqual(res.events, [ next(300, 1), next(350, 2), next(400, 3), ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 1000) ]) } func testRetry_Observable_Error() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createColdObservable([ next(100, 1), next(150, 2), next(200, 3), error(250, testError), ]) let res = scheduler.start(1100) { xs.retry() } XCTAssertEqual(res.events, [ next(300, 1), next(350, 2), next(400, 3), next(550, 1), next(600, 2), next(650, 3), next(800, 1), next(850, 2), next(900, 3), next(1050, 1) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 450), Subscription(450, 700), Subscription(700, 950), Subscription(950, 1100) ]) } func testRetryCount_Basic() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createColdObservable([ next(5, 1), next(10, 2), next(15, 3), error(20, testError) ]) let res = scheduler.start { xs.retry(3) } XCTAssertEqual(res.events, [ next(205, 1), next(210, 2), next(215, 3), next(225, 1), next(230, 2), next(235, 3), next(245, 1), next(250, 2), next(255, 3), error(260, testError) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 220), Subscription(220, 240), Subscription(240, 260) ]) } func testRetryCount_Dispose() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createColdObservable([ next(5, 1), next(10, 2), next(15, 3), error(20, testError) ]) let res = scheduler.start(231) { xs.retry(3) } XCTAssertEqual(res.events, [ next(205, 1), next(210, 2), next(215, 3), next(225, 1), next(230, 2), ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 220), Subscription(220, 231), ]) } func testRetryCount_Infinite() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createColdObservable([ next(5, 1), next(10, 2), next(15, 3), error(20, testError) ]) let res = scheduler.start(231) { xs.retry(3) } XCTAssertEqual(res.events, [ next(205, 1), next(210, 2), next(215, 3), next(225, 1), next(230, 2), ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 220), Subscription(220, 231), ]) } func testRetryCount_Completed() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createColdObservable([ next(100, 1), next(150, 2), next(200, 3), completed(250) ]) let res = scheduler.start { xs.retry(3) } XCTAssertEqual(res.events, [ next(300, 1), next(350, 2), next(400, 3), completed(450) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 450), ]) } func testRetry_tailRecursiveOptimizationsTest() { var count = 1 let sequenceSendingImmediateError: Observable<Int> = Observable.create { observer in observer.on(.next(0)) observer.on(.next(1)) observer.on(.next(2)) if count < 2 { observer.on(.error(testError)) count += 1 } observer.on(.next(3)) observer.on(.next(4)) observer.on(.next(5)) observer.on(.completed) return Disposables.create() } _ = sequenceSendingImmediateError .retry() .subscribe { _ in } } #if TRACE_RESOURCES func testRetryReleasesResourcesOnComplete() { _ = Observable<Int>.just(1).retry().subscribe() } func testRetryReleasesResourcesOnError() { _ = Observable<Int>.error(testError).retry(1).subscribe() } #endif } struct CustomErrorType : Error { } class RetryWhenError: Error { init() { } } let retryError: RetryWhenError = RetryWhenError() // retryWhen extension ObservableSingleTest { func testRetryWhen_Never() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), completed(250) ]) let empty = scheduler.createHotObservable([ next(150, 1), completed(210) ]) let res = scheduler.start(300) { xs.retryWhen { (errors: Observable<NSError>) in return empty } } let correct = [ completed(250, Int.self) ] XCTAssertEqual(res.events, correct) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 250) ]) } func testRetryWhen_ObservableNever() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(210, 2), next(220, 3), next(230, 4), next(240, 5), error(250, retryError) ]) let never = scheduler.createHotObservable([ next(150, 1) ]) let res = scheduler.start() { xs.retryWhen { (errors: Observable<RetryWhenError>) in return never } } let correct = [ next(210, 2), next(220, 3), next(230, 4), next(240, 5) ] XCTAssertEqual(res.events, correct) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 250) ]) } func testRetryWhen_ObservableNeverComplete() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(210, 2), next(220, 3), next(230, 4), next(240, 5), completed(250) ]) let never = scheduler.createHotObservable([ next(150, 1) ]) let res = scheduler.start() { xs.retryWhen { (errors: Observable<RetryWhenError>) in return never } } let correct = [ next(210, 2), next(220, 3), next(230, 4), next(240, 5), completed(250) ] XCTAssertEqual(res.events, correct) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 250) ]) } func testRetryWhen_ObservableEmpty() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createColdObservable([ next(100, 1), next(150, 2), next(200, 3), completed(250) ]) let empty = scheduler.createHotObservable([ next(150, 0), completed(0) ]) let res = scheduler.start() { xs.retryWhen { (errors: Observable<RetryWhenError>) in return empty } } let correct = [ next(300, 1), next(350, 2), next(400, 3), completed(450) ] XCTAssertEqual(res.events, correct) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 450) ]) } func testRetryWhen_ObservableNextError() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createColdObservable([ next(10, 1), next(20, 2), error(30, retryError), completed(40) ]) let res = scheduler.start(300) { xs.retryWhen { (errors: Observable<RetryWhenError>) in return errors.scan(0) { (_a, e) in var a = _a a += 1 if a == 2 { throw testError1 } return a } } } let correct = [ next(210, 1), next(220, 2), next(240, 1), next(250, 2), error(260, testError1) ] XCTAssertEqual(res.events, correct) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 230), Subscription(230, 260) ]) } func testRetryWhen_ObservableComplete() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createColdObservable([ next(10, 1), next(20, 2), error(30, retryError), completed(40) ]) let empty = scheduler.createHotObservable([ next(150, 1), completed(230) ]) let res = scheduler.start() { xs.retryWhen({ (errors: Observable<RetryWhenError>) in return empty.asObservable() }) } let correct = [ next(210, 1), next(220, 2), completed(230) ] XCTAssertEqual(res.events, correct) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 230) ]) } func testRetryWhen_ObservableNextComplete() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createColdObservable([ next(10, 1), next(20, 2), error(30, retryError), completed(40) ]) let res = scheduler.start(300) { xs.retryWhen { (errors: Observable<RetryWhenError>) in return errors.scan(0) { (a, e) in return a + 1 }.takeWhile { (num: Int) -> Bool in return num < 2 } } } let correct = [ next(210, 1), next(220, 2), next(240, 1), next(250, 2), completed(260) ] XCTAssertEqual(res.events, correct) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 230), Subscription(230, 260) ]) } func testRetryWhen_ObservableInfinite() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createColdObservable([ next(10, 1), next(20, 2), error(30, retryError), completed(40) ]) let never = scheduler.createHotObservable([ next(150, 1) ]) let res = scheduler.start() { xs.retryWhen { (errors: Observable<RetryWhenError>) in return never } } let correct = [ next(210, 1), next(220, 2) ] XCTAssertEqual(res.events, correct) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 230) ]) } func testRetryWhen_Incremental_BackOff() { let scheduler = TestScheduler(initialClock: 0) // just fails let xs = scheduler.createColdObservable([ next(5, 1), error(10, retryError) ]) let maxAttempts = 4 let res = scheduler.start(800) { xs.retryWhen { (errors: Observable<Swift.Error>) in return errors.flatMapWithIndex { (e, a) -> Observable<Int64> in if a >= maxAttempts - 1 { return Observable.error(e) } return Observable<Int64>.timer(RxTimeInterval((a + 1) * 50), scheduler: scheduler) } } } let correct = [ next(205, 1), next(265, 1), next(375, 1), next(535, 1), error(540, retryError) ] XCTAssertEqual(res.events, correct) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 210), Subscription(260, 270), Subscription(370, 380), Subscription(530, 540) ]) } func testRetryWhen_IgnoresDifferentErrorTypes() { let scheduler = TestScheduler(initialClock: 0) // just fails let xs = scheduler.createColdObservable([ next(5, 1), error(10, retryError) ]) let res = scheduler.start(800) { xs.retryWhen { (errors: Observable<CustomErrorType>) in errors } } let correct = [ next(205, 1), error(210, retryError) ] XCTAssertEqual(res.events, correct) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 210) ]) } func testRetryWhen_tailRecursiveOptimizationsTest() { var count = 1 let sequenceSendingImmediateError: Observable<Int> = Observable.create { observer in observer.on(.next(0)) observer.on(.next(1)) observer.on(.next(2)) if count < 2 { observer.on(.error(retryError)) count += 1 } observer.on(.next(3)) observer.on(.next(4)) observer.on(.next(5)) observer.on(.completed) return Disposables.create() } _ = sequenceSendingImmediateError .retryWhen { errors in return errors } .subscribe { _ in } } #if TRACE_RESOURCES func testRetryWhen1ReleasesResourcesOnComplete() { _ = Observable<Int>.just(1).retryWhen { e in e }.subscribe() } func testRetryWhen2ReleasesResourcesOnComplete() { _ = Observable<Int>.error(testError).retryWhen { e in e.take(1) }.subscribe() } func testRetryWhen1ReleasesResourcesOnError() { _ = Observable<Int>.error(testError).retryWhen { e in return e.flatMapLatest { e in return Observable<Int>.error(e) } }.subscribe() } #endif } // MARK: IgnoreElements extension ObservableSingleTest { func testIgnoreElements_DoesNotSendValues() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(210, 1), next(220, 2), completed(230) ]) let res = scheduler.start { xs.ignoreElements() } XCTAssertEqual(res.events, [ completed(230) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 230) ]) } #if TRACE_RESOURCES func testIgnoreElementsReleasesResourcesOnComplete() { _ = Observable<Int>.just(1).ignoreElements().subscribe() } func testIgnoreElementsReleasesResourcesOnError() { _ = Observable<Int>.error(testError).ignoreElements().subscribe() } #endif } // scan extension ObservableSingleTest { func testScan_Seed_Never() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(0, 0) ]) let seed = 42 let res = scheduler.start { xs.scan(seed) { $0 + $1 } } XCTAssertEqual(res.events, [ ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 1000) ]) } func testScan_Seed_Empty() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), completed(250) ]) let seed = 42 let res = scheduler.start { xs.scan(seed) { $0 + $1 } } XCTAssertEqual(res.events, [ completed(250) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 250) ]) } func testScan_Seed_Return() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(220, 2), completed(250) ]) let seed = 42 let res = scheduler.start { xs.scan(seed) { $0 + $1 } } XCTAssertEqual(res.events, [ next(220, seed + 2), completed(250) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 250) ]) } func testScan_Seed_Throw() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), error(250, testError) ]) let seed = 42 let res = scheduler.start { xs.scan(seed) { $0 + $1 } } XCTAssertEqual(res.events, [ error(250, testError) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 250) ]) } func testScan_Seed_SomeData() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(210, 2), next(220, 3), next(230, 4), next(240, 5), completed(250) ]) let seed = 42 let res = scheduler.start { xs.scan(seed) { $0 + $1 } } let messages = [ next(210, seed + 2), next(220, seed + 2 + 3), next(230, seed + 2 + 3 + 4), next(240, seed + 2 + 3 + 4 + 5), completed(250) ] XCTAssertEqual(res.events, messages) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 250) ]) } func testScan_Seed_AccumulatorThrows() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(210, 2), next(220, 3), next(230, 4), next(240, 5), completed(250) ]) let seed = 42 let res = scheduler.start { xs.scan(seed) { (a, e) in if e == 4 { throw testError } else { return a + e } } } XCTAssertEqual(res.events, [ next(210, seed + 2), next(220, seed + 2 + 3), error(230, testError) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 230) ]) } #if TRACE_RESOURCES func testScanReleasesResourcesOnComplete() { _ = Observable<Int>.just(1).scan(0, accumulator: +).subscribe() } func testScan1ReleasesResourcesOnError() { _ = Observable<Int>.error(testError).scan(0, accumulator: +).subscribe() } func testScan2ReleasesResourcesOnError() { _ = Observable<Int>.just(1).scan(0, accumulator: { _ in throw testError }).subscribe() } #endif }
mit
bb478ab1caa785295c83af7445dfc180
23.970554
123
0.495967
4.777465
false
true
false
false
cherrythia/FYP
FYP Table/AppDelegate.swift
1
6402
// // AppDelegate.swift // FYP Table // // Created by Chia Wei Zheng Terry on 18/1/15. // Copyright (c) 2015 Chia Wei Zheng Terry. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. 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:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: URL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "TerryChia.FYP_Table" in the application's documents Application Support directory. let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = Bundle.main.url(forResource: "FYP_Table", withExtension: "momd")! return NSManagedObjectModel(contentsOf: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.appendingPathComponent("FYP_Table.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator?.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil) } catch { } /* if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) == nil { coordinator = nil // Report any error we got. let dict = NSMutableDictionary() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error //error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict as [Any: Any]) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. //NSLog("Unresolved error \(error), \(error!.userInfo)") abort() }*/ return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges { do { try moc.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error)") abort() } } } } }
mit
4e0b319ca590ab93c406ce76bcf879a4
51.47541
290
0.694783
5.746858
false
false
false
false
eure/ReceptionApp
iOS/ReceptionApp/Transitions/ContactToInputFieldTransitionController.swift
1
5822
// // ContactToInputFieldTransitionController.swift // ReceptionApp // // Created by Hiroshi Kimura on 8/26/15. // Copyright © 2016 eureka, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation import UIKit // MARK: - ContactToInputFieldTransitionController final class ContactToInputFieldTransitionController: NSObject, UIViewControllerAnimatedTransitioning { // MARK: Internal required init(operation: UINavigationControllerOperation) { self.operation = operation super.init() } // MARK: UIViewControllerAnimatedTransitioning @objc dynamic func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return 0.8 } @objc dynamic func animateTransition(transitionContext: UIViewControllerContextTransitioning) { let containerView = transitionContext.containerView()! let offset = UIScreen.mainScreen().bounds.width switch self.operation { case .Push: let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as! ContactToViewController let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)! let inputFieldView = (toVC as! InputFieldTransition).inputFieldView let nextButton = (toVC as! InputFieldTransition).nextButton let transform = CATransform3DMakeTranslation(-offset, 0, 0) inputFieldView.layer.transform = CATransform3DMakeTranslation(offset, 0, 0) let nextButtonCurrentAlpha = nextButton.alpha nextButton.alpha = 0 UIView.animateAndChainWithDuration( 0.4, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: [], animations: { fromVC.inputFieldView.layer.transform = transform fromVC.tableView.layer.transform = transform }, completion: { _ in containerView.addSubview(toVC.view) } ).animateWithDuration( 0.4, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: [], animations: { inputFieldView.layer.transform = CATransform3DIdentity nextButton.alpha = nextButtonCurrentAlpha }, completion: { _ in transitionContext.completeTransition(true) } ) case .Pop: let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)! let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) as! ContactToViewController let inputFieldView = (fromVC as! InputFieldTransition).inputFieldView let nextButton = (fromVC as! InputFieldTransition).nextButton let transform = CATransform3DMakeTranslation(-offset, 0, 0) toVC.inputFieldView.layer.transform = transform toVC.tableView.layer.transform = transform UIView.animateAndChainWithDuration( 0.4, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: [], animations: { inputFieldView.layer.transform = CATransform3DMakeTranslation(offset, 0, 0) nextButton.alpha = 0 }, completion: { _ in containerView.addSubview(toVC.view) } ).animateWithDuration( 0.4, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: [], animations: { toVC.inputFieldView.layer.transform = CATransform3DIdentity toVC.tableView.layer.transform = CATransform3DIdentity }, completion: { _ in transitionContext.completeTransition(true) } ) default: return } } // MARK: Private private let operation: UINavigationControllerOperation }
mit
4789a11f24500f7556bd7d132c631560
36.798701
133
0.590448
6.245708
false
false
false
false
austinzheng/swift
test/Constraints/patterns.swift
1
10030
// RUN: %target-typecheck-verify-swift // Leaf expression patterns are matched to corresponding pieces of a switch // subject (TODO: or ~= expression) using ~= overload resolution. switch (1, 2.5, "three") { case (1, _, _): () // Double is ExpressibleByIntegerLiteral case (_, 2, _), (_, 2.5, _), (_, _, "three"): () // ~= overloaded for (Range<Int>, Int) case (0..<10, _, _), (0..<10, 2.5, "three"), (0...9, _, _), (0...9, 2.5, "three"): () default: () } switch (1, 2) { case (var a, a): // expected-error {{use of unresolved identifier 'a'}} () } // 'is' patterns can perform the same checks that 'is' expressions do. protocol P { func p() } class B : P { init() {} func p() {} func b() {} } class D : B { override init() { super.init() } func d() {} } class E { init() {} func e() {} } struct S : P { func p() {} func s() {} } // Existential-to-concrete. var bp : P = B() switch bp { case is B, is D, is S: () case is E: () default: () } switch bp { case let b as B: b.b() case let d as D: d.b() d.d() case let s as S: s.s() case let e as E: e.e() default: () } // Super-to-subclass. var db : B = D() switch db { case is D: () case is E: // expected-warning {{always fails}} () default: () } // Raise an error if pattern productions are used in expressions. var b = var a // expected-error{{expected initial value after '='}} expected-error {{type annotation missing in pattern}} expected-error {{consecutive statements on a line must be separated by ';'}} {{8-8=;}} var c = is Int // expected-error{{expected initial value after '='}} expected-error {{expected expression}} expected-error {{consecutive statements on a line must be separated by ';'}} {{8-8=;}} // TODO: Bad recovery in these cases. Although patterns are never valid // expr-unary productions, it would be good to parse them anyway for recovery. //var e = 2 + var y //var e = var y + 2 // 'E.Case' can be used in a dynamic type context as an equivalent to // '.Case as E'. protocol HairType {} enum MacbookHair: HairType { case HairSupply(S) } enum iPadHair<T>: HairType { case HairForceOne } enum Watch { case Sport, Watch, Edition } let hair: HairType = MacbookHair.HairSupply(S()) switch hair { case MacbookHair.HairSupply(let s): s.s() case iPadHair<S>.HairForceOne: () case iPadHair<E>.HairForceOne: () case iPadHair.HairForceOne: // expected-error{{generic enum type 'iPadHair' is ambiguous without explicit generic parameters when matching value of type 'HairType'}} () case Watch.Edition: // TODO: should warn that cast can't succeed with currently known conformances () case .HairForceOne: // expected-error{{type 'HairType' has no member 'HairForceOne'}} () default: break } // <rdar://problem/19382878> Introduce new x? pattern switch Optional(42) { case let x?: break // expected-warning{{immutable value 'x' was never used; consider replacing with '_' or removing it}} case nil: break } func SR2066(x: Int?) { // nil literals should still work when wrapped in parentheses switch x { case (nil): break case _?: break } switch x { case ((nil)): break case _?: break } switch (x, x) { case ((nil), _): break case (_?, _): break } } // Test x???? patterns. switch (nil as Int???) { case let x???: print(x, terminator: "") case let x??: print(x as Any, terminator: "") case let x?: print(x as Any, terminator: "") case 4???: break case nil??: break // expected-warning {{case is already handled by previous patterns; consider removing it}} case nil?: break // expected-warning {{case is already handled by previous patterns; consider removing it}} default: break } switch ("foo" as String?) { case "what": break default: break } // Test some value patterns. let x : Int? extension Int { func method() -> Int { return 42 } } func ~= <T : Equatable>(lhs: T?, rhs: T?) -> Bool { return lhs == rhs } switch 4 as Int? { case x?.method(): break // match value default: break } switch 4 { case x ?? 42: break // match value default: break } for (var x) in 0...100 {} // expected-warning{{variable 'x' was never used; consider replacing with '_' or removing it}} for var x in 0...100 {} // rdar://20167543 expected-warning{{variable 'x' was never used; consider replacing with '_' or removing it}} for (let x) in 0...100 { _ = x} // expected-error {{'let' pattern cannot appear nested in an already immutable context}} var (let y) = 42 // expected-error {{'let' cannot appear nested inside another 'var' or 'let' pattern}} let (var z) = 42 // expected-error {{'var' cannot appear nested inside another 'var' or 'let' pattern}} // Crash when re-typechecking EnumElementPattern. // FIXME: This should actually type-check -- the diagnostics are bogus. But // at least we don't crash anymore. protocol PP { associatedtype E } struct A<T> : PP { typealias E = T } extension PP { func map<T>(_ f: (Self.E) -> T) -> T {} } enum EE { case A case B } func good(_ a: A<EE>) -> Int { return a.map { switch $0 { case .A: return 1 default: return 2 } } } func bad(_ a: A<EE>) { a.map { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{10-10= () -> Int in }} let _: EE = $0 return 1 } } func ugly(_ a: A<EE>) { a.map { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{10-10= () -> Int in }} switch $0 { case .A: return 1 default: return 2 } } } // SR-2057 enum SR2057 { case foo } let sr2057: SR2057? if case .foo = sr2057 { } // expected-error{{enum case 'foo' not found in type 'SR2057?'}} // Invalid 'is' pattern class SomeClass {} if case let doesNotExist as SomeClass:AlsoDoesNotExist {} // expected-error@-1 {{use of undeclared type 'AlsoDoesNotExist'}} // expected-error@-2 {{variable binding in a condition requires an initializer}} // `.foo` and `.bar(...)` pattern syntax should also be able to match // static members as expr patterns struct StaticMembers: Equatable { init() {} init(_: Int) {} init?(opt: Int) {} static var prop = StaticMembers() static var optProp: Optional = StaticMembers() static func method(_: Int) -> StaticMembers { return prop } static func method(withLabel: Int) -> StaticMembers { return prop } static func optMethod(_: Int) -> StaticMembers? { return optProp } static func ==(x: StaticMembers, y: StaticMembers) -> Bool { return true } } let staticMembers = StaticMembers() let optStaticMembers: Optional = StaticMembers() switch staticMembers { case .init: break // expected-error{{cannot match values of type 'StaticMembers'}} case .init(opt:): break // expected-error{{cannot match values of type 'StaticMembers'}} case .init(): break case .init(0): break case .init(_): break // expected-error{{'_' can only appear in a pattern}} case .init(let x): break // expected-error{{cannot appear in an expression}} case .init(opt: 0): break // expected-error{{pattern cannot match values of type 'StaticMembers'}} case .prop: break // TODO: repeated error message case .optProp: break // expected-error* {{not unwrapped}} case .method: break // expected-error{{cannot match}} case .method(0): break case .method(_): break // expected-error{{'_' can only appear in a pattern}} case .method(let x): break // expected-error{{cannot appear in an expression}} case .method(withLabel:): break // expected-error{{cannot match}} case .method(withLabel: 0): break case .method(withLabel: _): break // expected-error{{'_' can only appear in a pattern}} case .method(withLabel: let x): break // expected-error{{cannot appear in an expression}} case .optMethod: break // expected-error{{cannot match}} case .optMethod(0): break // expected-error{{pattern cannot match values of type 'StaticMembers'}} } _ = 0 // rdar://problem/32241441 - Add fix-it for cases in switch with optional chaining struct S_32241441 { enum E_32241441 { case foo case bar } var type: E_32241441 = E_32241441.foo } func rdar32241441() { let s: S_32241441? = S_32241441() switch s?.type { case .foo: // expected-error {{enum case 'foo' not found in type 'S_32241441.E_32241441?'}} {{12-12=?}} break; case .bar: // expected-error {{enum case 'bar' not found in type 'S_32241441.E_32241441?'}} {{12-12=?}} break; } } // SR-6100 struct One<Two> { public enum E: Error { // if you remove associated value, everything works case SomeError(String) } } func testOne() { do { } catch let error { // expected-warning{{'catch' block is unreachable because no errors are thrown in 'do' block}} if case One.E.SomeError = error {} // expected-error{{generic enum type 'One.E' is ambiguous without explicit generic parameters when matching value of type 'Error'}} } } // SR-8347 // constrain initializer expressions of optional some pattern bindings to be optional func test8347() -> String { struct C { subscript (s: String) -> String? { return "" } subscript (s: String) -> [String] { return [""] } func f() -> String? { return "" } func f() -> Int { return 3 } func g() -> String { return "" } func h() -> String { // expected-note {{found this candidate}} return "" } func h() -> Double { // expected-note {{found this candidate}} return 3.0 } func h() -> Int? { //expected-note{{found this candidate}} return 2 } func h() -> Float? { //expected-note{{found this candidate}} return nil } } let c = C() if let s = c[""] { return s } if let s = c.f() { return s } if let s = c.g() { //expected-error{{initializer for conditional binding must have Optional type, not 'String'}} return s } if let s = c.h() { //expected-error{{ambiguous use of 'h()'}} return s } }
apache-2.0
4ae9cb95430f71b0e66d8c422afdcfc4
23.704433
208
0.633799
3.610511
false
false
false
false
brentdax/swift
stdlib/public/SDK/Foundation/ExtraStringAPIs.swift
3
1201
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// extension String.UTF16View.Index { /// Construct from an integer offset. @available(swift, deprecated: 3.2) @available(swift, obsoleted: 4.0) public init(_ offset: Int) { assert(offset >= 0, "Negative UTF16 index offset not allowed") self.init(encodedOffset: offset) } @available(swift, deprecated: 3.2) @available(swift, obsoleted: 4.0) public func distance(to other: String.UTF16View.Index?) -> Int { return _offset.distance(to: other!._offset) } @available(swift, deprecated: 3.2) @available(swift, obsoleted: 4.0) public func advanced(by n: Int) -> String.UTF16View.Index { return String.UTF16View.Index(_offset.advanced(by: n)) } }
apache-2.0
38c633534ccad16c68c32508d9d1a8f1
35.393939
80
0.613655
4.085034
false
false
false
false
Friend-LGA/LGSideMenuController
LGSideMenuController/Extensions/Validators/LGSideMenuController+ValidatingViewsTransforms.swift
1
13959
// // LGSideMenuController+ValidatingViewsTransforms.swift // LGSideMenuController // // // The MIT License (MIT) // // Copyright © 2015 Grigorii Lutkov <[email protected]> // (https://github.com/Friend-LGA/LGSideMenuController) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation import UIKit private let pointsNeededForShadow: CGFloat = 10.0 internal extension LGSideMenuController { func validateViewsTransforms() { self.validateRootViewsTransforms() self.validateLeftViewsTransforms() self.validateRightViewsTransforms() } func validateRootViewsTransforms() { validateRootViewsTransforms(percentage: self.isSideViewShowing ? 1.0 : 0.0) } func validateLeftViewsTransforms() { validateLeftViewsTransforms(percentage: self.isSideViewShowing ? 1.0 : 0.0) } func validateRightViewsTransforms() { validateRightViewsTransforms(percentage: self.isSideViewShowing ? 1.0 : 0.0) } func validateRootViewsTransforms(percentage: CGFloat) { guard let containerView = self.rootContainerView, let coverView = self.rootViewCoverView else { return } let isLeftViewMoving = self.leftView != nil && self.isLeftViewVisible let isRightViewMoving = self.rightView != nil && self.isRightViewVisible containerView.alpha = { if isLeftViewMoving { return 1.0 - (1.0 - self.rootViewAlphaWhenHiddenForLeftView) * percentage } else if isRightViewMoving { return 1.0 - (1.0 - self.rootViewAlphaWhenHiddenForRightView) * percentage } else { return 1.0 } }() coverView.alpha = { if isLeftViewMoving { return self.rootViewCoverAlphaForLeftView * percentage } else if isRightViewMoving { return self.rootViewCoverAlphaForRightView * percentage } else { return 0.0 } }() let scale: CGFloat = { // If any of side views is visible, we can't change the scale of root view if self.isSideViewAlwaysVisible { return 1.0 } var rootViewScale: CGFloat = 1.0 if isLeftViewMoving { rootViewScale = self.rootViewScaleWhenHiddenForLeftView } if isRightViewMoving { rootViewScale = self.rootViewScaleWhenHiddenForRightView } return 1.0 + (rootViewScale - 1.0) * percentage }() let translate: CGPoint = { var result: CGPoint = .zero if isLeftViewMoving { result = CGPoint(x: self.rootViewOffsetTotalForLeftView.x * percentage, y: self.rootViewOffsetTotalForLeftView.y * percentage) } else if isRightViewMoving { result = CGPoint(x: -(self.rootViewOffsetTotalForRightView.x * percentage), y: self.rootViewOffsetTotalForRightView.y * percentage) } if scale != 1.0 { let shift = containerView.bounds.width * (1.0 - scale) / 2.0 if isLeftViewMoving { result.x -= shift * percentage } else if isRightViewMoving { result.x += shift * percentage } } return result }() let transformScale = CGAffineTransform(scaleX: scale, y: scale) let transfromTranslate = CGAffineTransform(translationX: translate.x, y: translate.y) let transform = transformScale.concatenating(transfromTranslate) containerView.transform = transform self.didTransformRootViewCallbacks(percentage: percentage) } func validateLeftViewsTransforms(percentage: CGFloat) { guard self.leftView != nil, let containerView = self.leftContainerView, let backgroundDecorationView = self.leftViewBackgroundDecorationView, let backgroundShadowView = self.leftViewBackgroundShadowView, let wrapperView = self.leftViewWrapperView, let coverView = self.leftViewCoverView else { return } let viewAlpha: CGFloat = { if self.isLeftViewAlwaysVisible { return 1.0 } return 1.0 - (1.0 - self.leftViewAlphaWhenHidden) * (1.0 - percentage) }() if self.leftViewPresentationStyle.isAbove { containerView.alpha = viewAlpha } else { wrapperView.alpha = viewAlpha } containerView.transform = { var translateX: CGFloat = 0.0 if self.rightView != nil && self.isRightViewVisible { translateX -= self.rootViewOffsetTotalForRightView.x * percentage if self.leftViewPresentationStyle.isHiddenAside && !self.isLeftViewAlwaysVisible { translateX -= self.leftViewWidthTotal } } else if self.leftViewPresentationStyle.isHiddenAside && !self.isLeftViewAlwaysVisible { translateX -= self.leftViewWidthTotal * (1.0 - percentage) } return CGAffineTransform(translationX: translateX, y: 0.0) }() backgroundDecorationView.transform = { var scale = self.leftViewBackgroundScaleWhenShowing var offsetX = self.leftViewBackgroundOffsetWhenShowing.x var offsetY = self.leftViewBackgroundOffsetWhenShowing.y if !self.isLeftViewAlwaysVisible { scale = (self.leftViewBackgroundScaleWhenHidden * (1.0 - percentage)) + (self.leftViewBackgroundScaleWhenShowing * percentage) offsetX = (self.leftViewBackgroundOffsetWhenHidden.x * (1.0 - percentage)) + (self.leftViewBackgroundOffsetWhenShowing.x * percentage) offsetY = (self.leftViewBackgroundOffsetWhenHidden.y * (1.0 - percentage)) + (self.leftViewBackgroundOffsetWhenShowing.y * percentage) } let transformTranslate = CGAffineTransform(translationX: offsetX, y: offsetY) let transformScale = CGAffineTransform(scaleX: scale, y: scale) return transformTranslate.concatenating(transformScale) }() backgroundShadowView.alpha = { if self.leftViewPresentationStyle.isAbove && !self.isLeftViewAlwaysVisible { let pointsPerPercent = self.leftViewWidthTotal / 100.0 let percentsNeeded = pointsNeededForShadow / pointsPerPercent / 100.0 return percentage / percentsNeeded } return 1.0 }() wrapperView.transform = { if self.isLeftViewAlwaysVisible { return CGAffineTransform(translationX: self.leftViewOffsetWhenShowing.x, y: self.leftViewOffsetWhenShowing.y) } else { let scale = 1.0 + (self.leftViewScaleWhenHidden - 1.0) * (1.0 - percentage) let offsetX = (self.leftViewOffsetWhenHidden.x * (1.0 - percentage)) + (self.leftViewOffsetWhenShowing.x * percentage) let offsetY = (self.leftViewOffsetWhenHidden.y * (1.0 - percentage)) + (self.leftViewOffsetWhenShowing.y * percentage) let transformTranslate = CGAffineTransform(translationX: offsetX, y: offsetY) let transformScale = CGAffineTransform(scaleX: scale, y: scale) return transformTranslate.concatenating(transformScale) } }() coverView.alpha = { if !self.isLeftViewAlwaysVisible { return self.leftViewCoverAlpha - (self.leftViewCoverAlpha * percentage) } else if self.rightView != nil && self.isRightViewVisible { return self.leftViewCoverAlphaWhenAlwaysVisible * percentage } return 0.0 }() self.didTransformLeftViewCallbacks(percentage: percentage) } func validateRightViewsTransforms(percentage: CGFloat) { guard self.rightView != nil, let containerView = self.rightContainerView, let backgroundDecorationView = self.rightViewBackgroundDecorationView, let backgroundShadowView = self.rightViewBackgroundShadowView, let wrapperView = self.rightViewWrapperView, let coverView = self.rightViewCoverView else { return } let viewAlpha: CGFloat = { if self.isRightViewAlwaysVisible { return 1.0 } return 1.0 - (1.0 - self.rightViewAlphaWhenHidden) * (1.0 - percentage) }() if self.rightViewPresentationStyle.isAbove { containerView.alpha = viewAlpha } else { wrapperView.alpha = viewAlpha } containerView.transform = { var translateX: CGFloat = 0.0 if self.leftView != nil && self.isLeftViewVisible { translateX += self.rootViewOffsetTotalForLeftView.x * percentage if self.rightViewPresentationStyle.isHiddenAside && !self.isRightViewAlwaysVisible { translateX += self.rightViewWidthTotal } } else if self.rightViewPresentationStyle.isHiddenAside && !self.isRightViewAlwaysVisible { translateX += self.rightViewWidthTotal * (1.0 - percentage) } return CGAffineTransform(translationX: translateX, y: 0.0) }() backgroundDecorationView.transform = { var scale = self.rightViewBackgroundScaleWhenShowing var offsetX = self.rightViewBackgroundOffsetWhenShowing.x var offsetY = self.rightViewBackgroundOffsetWhenShowing.y if !self.isRightViewAlwaysVisible { scale = (self.rightViewBackgroundScaleWhenHidden * (1.0 - percentage)) + (self.rightViewBackgroundScaleWhenShowing * percentage) offsetX = (self.rightViewBackgroundOffsetWhenHidden.x * (1.0 - percentage)) + (self.rightViewBackgroundOffsetWhenShowing.x * percentage) offsetY = (self.rightViewBackgroundOffsetWhenHidden.y * (1.0 - percentage)) + (self.rightViewBackgroundOffsetWhenShowing.y * percentage) } let transformTranslate = CGAffineTransform(translationX: offsetX, y: offsetY) let transformScale = CGAffineTransform(scaleX: scale, y: scale) return transformTranslate.concatenating(transformScale) }() backgroundShadowView.alpha = { if self.rightViewPresentationStyle.isAbove && !self.isRightViewAlwaysVisible { let pointsPerPercent = self.rightViewWidthTotal / 100.0 let percentsNeeded = pointsNeededForShadow / pointsPerPercent / 100.0 return percentage / percentsNeeded } return 1.0 }() wrapperView.transform = { if self.isRightViewAlwaysVisible { return CGAffineTransform(translationX: self.rightViewOffsetWhenShowing.x, y: self.rightViewOffsetWhenShowing.y) } else { let scale = 1.0 + (self.rightViewScaleWhenHidden - 1.0) * (1.0 - percentage) let offsetX = (self.rightViewOffsetWhenHidden.x * (1.0 - percentage)) + (self.rightViewOffsetWhenShowing.x * percentage) let offsetY = (self.rightViewOffsetWhenHidden.y * (1.0 - percentage)) + (self.rightViewOffsetWhenShowing.y * percentage) let transformTranslate = CGAffineTransform(translationX: offsetX, y: offsetY) let transformScale = CGAffineTransform(scaleX: scale, y: scale) return transformTranslate.concatenating(transformScale) } }() coverView.alpha = { if !self.isRightViewAlwaysVisible { return self.rightViewCoverAlpha - (self.rightViewCoverAlpha * percentage) } else if self.leftView != nil && self.isLeftViewVisible { return self.rightViewCoverAlphaWhenAlwaysVisible * percentage } return 0.0 }() self.didTransformRightViewCallbacks(percentage: percentage) } }
mit
b06a4f7365becdbf0889909e5fda9184
39.575581
101
0.605101
5.165803
false
false
false
false
k8mil/ContactCircularView
ContactCircularView/Classes/InitialsCreator.swift
1
1201
// // Created by Kamil Wysocki on 14/10/16. // Copyright (c) 2016 CocoaPods. All rights reserved. // import Foundation /** Class than implement FormattedTextCreator protocol */ @objc open class InitialsCreator: NSObject, FormattedTextCreator { /** Method that allows you to create initials from name using `formattedTextFromString` method. Exaples : "John" -> "J" "John Doe" -> "JD" "John Mark Doe" -> "JD" */ open func formattedTextFromString(_ string: String) -> String { var wordsArray = string.components(separatedBy: CharacterSet.whitespacesAndNewlines) wordsArray = wordsArray.filter({ (word: String) -> Bool in return !(word.isEmpty) }) if (wordsArray.count == 1) { if let oneLetter = wordsArray.first?.characters.first { return String(oneLetter) } } if (wordsArray.count >= 2) { if let firstLetter = wordsArray.first?.characters.first, let secondLetter = wordsArray.last?.characters.first { return String(firstLetter) + String(secondLetter) } } return "" } }
mit
47d89d000d74261a9167dbb4dc8a2521
28.292683
123
0.597835
4.415441
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/WalletPayload/Sources/WalletPayloadKit/Models/Types/Wallet.swift
1
9592
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine import Foundation import ToolKit import WalletCore /// The derived Wallet from the response model, `BlockchainWallet` /// Note: This should be renamed to `Wallet` once we finalise the migration to native code. public struct NativeWallet: Equatable { public let guid: String public let sharedKey: String public let doubleEncrypted: Bool public let doublePasswordHash: String? public let metadataHDNode: String? public let options: Options public let hdWallets: [HDWallet] public let addresses: [Address] public let txNotes: [String: String]? // The following is still present in json but not used on iOS public let addressBook: [AddressBookEntry]? /// Returns the default HDWallet from the list /// - NOTE: We never add multiple HDWallet(s) var defaultHDWallet: HDWallet? { hdWallets.first } /// Returns `true` if the mnemonic has been previously marked as verified /// otherwise `false var isMnemonicVerified: Bool { defaultHDWallet?.mnemonicVerified ?? false } var isHDWallet: Bool { !hdWallets.isEmpty } var spendableActiveAddresses: [String] { addresses.lazy .filter { !$0.isArchived && !$0.isWatchOnly } .map(\.addr) } public init( guid: String, sharedKey: String, doubleEncrypted: Bool, doublePasswordHash: String?, metadataHDNode: String?, options: Options, hdWallets: [HDWallet], addresses: [Address], txNotes: [String: String]?, addressBook: [AddressBookEntry]? ) { self.guid = guid self.sharedKey = sharedKey self.doubleEncrypted = doubleEncrypted self.doublePasswordHash = doublePasswordHash self.metadataHDNode = metadataHDNode self.options = options self.hdWallets = hdWallets self.addresses = addresses self.txNotes = txNotes self.addressBook = addressBook } } // MARK: - Wallet Retriever /// Streams the current initiliazed wrapper func getWrapper( walletHolder: WalletHolderAPI ) -> AnyPublisher<Wrapper, WalletError> { walletHolder.walletStatePublisher .flatMap { walletState -> AnyPublisher<Wrapper, WalletError> in guard let wrapper = walletState?.wrapper else { return .failure(.payloadNotFound) } return .just(wrapper) } .eraseToAnyPublisher() } /// Streams the current initiliazed wrapper func getWallet( walletHolder: WalletHolderAPI ) -> AnyPublisher<NativeWallet, WalletError> { getWrapper(walletHolder: walletHolder) .map(\.wallet) .eraseToAnyPublisher() } // MARK: - Wallet Creation /// Generates a new `Wallet` from the given context /// - Parameter context: A `WalletCreationContext` /// - Returns: A `Result<NativeWallet, WalletCreateError>` func generateWallet(context: WalletCreationContext) -> Result<NativeWallet, WalletCreateError> { generateHDWallet(mnemonic: context.mnemonic, accountName: context.accountName, totalAccounts: context.totalAccounts) .map { hdWallet in NativeWallet( guid: context.guid, sharedKey: context.sharedKey, doubleEncrypted: false, doublePasswordHash: nil, metadataHDNode: nil, options: Options.default, hdWallets: [hdWallet], addresses: [], txNotes: [:], addressBook: [] ) } } /// Retrieves a `WalletCore.HDWallet` from the given mnemonic /// - Parameter mnemonic: A `String` to be used as the mnemonic phrase /// - Returns: A `Result<HDWallet, WalletCreateError>` func getHDWallet( from mnemonic: String ) -> Result<WalletCore.HDWallet, WalletCreateError> { guard let wallet = WalletCore.HDWallet(mnemonic: mnemonic, passphrase: "") else { return .failure(.mnemonicFailure(.unableToProvide)) } return .success(wallet) } /// Retrieves the entropy in hex format from the given mnemonic /// - Parameter mnemonic: A `String` to be used as the mnemonic phrase /// - Returns: A `Result<String, WalletCreateError>` that contains either the seed in hexadecimal format or failure func getSeedHex( from mnemonic: String ) -> Result<String, WalletCreateError> { getHDWallet(from: mnemonic) .map(\.entropy) .map(\.toHexString) } // MARK: - Wallet Methods /// Gets a mnemonic phrase from the given wallet /// - Parameters: /// - wallet: A `Wallet` value to retrieve the mnemonic from /// - secondPassword: A optional `String` representing the second password of the wallet /// - Returns: A `Mnemonic` phrase func getMnemonic( from wallet: NativeWallet, secondPassword: String? = nil ) -> Result<String, WalletError> { getSeedHex(from: wallet, secondPassword: secondPassword) .map(Data.init(hex:)) .flatMap(getHDWallet(from:)) .map(\.mnemonic) } /// Gets the masterNode (BIP39 seed) from the given wallet /// This is used to calculate the derivations, xpriv/xpubs etc /// /// - Parameters: /// - wallet: A `Wallet` value to retrieve the mnemonic from /// - secondPassword: A optional `String` representing the second password of the wallet /// - Returns: A `String` of the seed func getMasterNode( from wallet: NativeWallet, secondPassword: String? = nil ) -> Result<String, WalletError> { getSeedHex(from: wallet, secondPassword: secondPassword) .map(Data.init(hex:)) .flatMap(getHDWallet(from:)) .map(\.seed) .map(\.toHexString) } /// Returns the seedHex from the given wallet /// - Parameters: /// - wallet: A `Wallet` object to retrieve the seedHex /// - secondPassword: An optional String representing the second password /// - Returns: `Result<String, WalletError>` func getSeedHex( from wallet: NativeWallet, secondPassword: String? = nil ) -> Result<String, WalletError> { guard let seedHex = wallet.defaultHDWallet?.seedHex else { return .failure(.initialization(.missingSeedHex)) } if wallet.doubleEncrypted { guard let secondPassword = secondPassword else { return .failure(.initialization(.needsSecondPassword)) } return decryptValue( secondPassword: secondPassword, wallet: wallet, value: seedHex ) } return .success(seedHex) } // MARK: - Second Password /// Decrypts a value using a second password /// - Parameters: /// - secondPassword: A `String` value representing the user's second password /// - wallet: A `Wallet` object /// - value: A `String` encrypted value to be decrypted /// - Returns: A `Result<String, WalletError>` with a decrypted value or a failure func decryptValue( secondPassword: String, wallet: NativeWallet, value: String ) -> Result<String, WalletError> { validateSecondPassword( password: secondPassword, wallet: wallet ) { wallet in decryptValue( using: secondPassword, sharedKey: wallet.sharedKey, pbkdf2Iterations: wallet.options.pbkdf2Iterations, value: value ) .mapError(WalletError.map(from:)) } } /// Validates if a second password is correct or fails /// - Parameters: /// - password: A `String` value representing the user's second password /// - wallet: A `Wallet` value /// - perform: A closure to perform second password decryption /// - Returns: `Result<Value, WalletError>` func validateSecondPassword<Value>( password: String, wallet: NativeWallet, perform: (NativeWallet) -> Result<Value, WalletError> ) -> Result<Value, WalletError> { guard isValid(secondPassword: password, wallet: wallet) else { return .failure(.initialization(.invalidSecondPassword)) } return perform(wallet) } /// Validates whether the given second password is valid /// - Parameters: /// - secondPassword: A `String` for the second password /// - wallet: A `Wallet` value /// - Returns: `true` if the given secondPassword matches the stored one, otherwise `false` func isValid(secondPassword: String, wallet: NativeWallet) -> Bool { guard wallet.doubleEncrypted else { return false } let iterations = wallet.options.pbkdf2Iterations let sharedKey = wallet.sharedKey let computedHash = hashNTimes(iterations: iterations, value: sharedKey + secondPassword) return wallet.doublePasswordHash == computedHash } // MARK: Private /// Gets an HDWallet from the given parameters /// - Parameters: /// - entropy: A `Data` value representing the entropy for the `HDWallet` /// - Returns: A `WalletCore.HDWallet` object private func getHDWallet( from entropy: Data ) -> Result<WalletCore.HDWallet, WalletError> { getHDWallet(from: entropy, passphrase: "") } /// Gets an HDWallet from the given parameters /// - Parameters: /// - entropy: A `Data` value representing the entropy for the `HDWallet` /// - passphrase: An optional `String` if the HDWallet is encrypted /// - Returns: A `WalletCore.HDWallet` object private func getHDWallet( from entropy: Data, passphrase: String = "" ) -> Result<WalletCore.HDWallet, WalletError> { guard let hdWallet = WalletCore.HDWallet(entropy: entropy, passphrase: passphrase) else { return .failure(.decryption(.hdWalletCreation)) } return .success(hdWallet) }
lgpl-3.0
8e2c87c9706e59603f15d465e6f26ae2
32.534965
120
0.668856
4.32027
false
false
false
false
Erickson0806/AdaptivePhotos
AdaptivePhotosUsingUIKitTraitsandSizeClasses/AdaptiveCode/AdaptiveCode/ListTableViewController.swift
1
9091
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: A view controller that shows a list of conversations that can be viewed. */ import UIKit class ListTableViewController: UITableViewController { // MARK: Properties let user: User static let cellIdentifier = "ConversationCell" // MARK: Initialization init(user: User) { self.user = user super.init(style: .Plain) title = NSLocalizedString("Conversations", comment: "Conversations") navigationItem.leftBarButtonItem = UIBarButtonItem(title: NSLocalizedString("About", comment: "About"), style: .Plain, target: self, action: "showAboutViewController:") navigationItem.rightBarButtonItem = UIBarButtonItem(title: NSLocalizedString("Profile", comment: "Profile"), style: .Plain, target: self, action: "showProfileViewController:") clearsSelectionOnViewWillAppear = false } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } // MARK: View Controller override func viewDidLoad() { super.viewDidLoad() tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: ListTableViewController.cellIdentifier) NSNotificationCenter.defaultCenter().addObserver(self, selector: "showDetailTargetDidChange:", name: UIViewControllerShowDetailTargetDidChangeNotification, object: nil) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // Deselect any index paths that push when tapped for indexPath in tableView.indexPathsForSelectedRows ?? [] { let pushes: Bool if shouldShowConversationViewForIndexPath(indexPath) { pushes = willShowingViewControllerPushWithSender(self) } else { pushes = willShowingDetailViewControllerPushWithSender(self) } if pushes { // If we're pushing for this indexPath, deselect it when we appear. tableView.deselectRowAtIndexPath(indexPath, animated: animated) } } if let visiblePhoto = currentVisibleDetailPhotoWithSender(self) { for indexPath in tableView.indexPathsForVisibleRows ?? [] { let photo = photoForIndexPath(indexPath) if photo == visiblePhoto { tableView.selectRowAtIndexPath(indexPath, animated: true, scrollPosition: .None) } } } } func showDetailTargetDidChange(notification: NSNotification) { /* Whenever the target for showDetailViewController: changes, update all of our cells (to ensure they have the right accessory type). */ for cell in tableView.visibleCells { if let indexPath = tableView.indexPathForCell(cell) { tableView(tableView, willDisplayCell: cell, forRowAtIndexPath: indexPath) } } } override func containsPhoto(photo: Photo) -> Bool { return true } // MARK: About func showAboutViewController(sender: UIBarButtonItem) { if presentedViewController != nil { // Dismiss Profile if visible dismissViewControllerAnimated(true, completion: nil) } let aboutViewController = AboutViewController() aboutViewController.navigationItem.title = NSLocalizedString("About", comment: "About") aboutViewController.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: "closeAboutViewController:") let navController = UINavigationController(rootViewController: aboutViewController) navController.modalPresentationStyle = .FullScreen presentViewController(navController, animated: true, completion: nil) } func closeAboutViewController(sender: UIBarButtonItem) { dismissViewControllerAnimated(true, completion: nil) } // MARK: Profile func showProfileViewController(sender: UIBarButtonItem) { let profileController = ProfileViewController(user: user) profileController.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: "closeProfileViewController:") let profileNavController = UINavigationController(rootViewController: profileController) profileNavController.modalPresentationStyle = .Popover profileNavController.popoverPresentationController?.barButtonItem = sender // Set self as the presentation controller's delegate so that we can adapt its appearance profileNavController.popoverPresentationController?.delegate = self presentViewController(profileNavController, animated: true, completion:nil) } func closeProfileViewController(sender: UIBarButtonItem) { dismissViewControllerAnimated(true, completion: nil) } // MARK: Table View func conversationForIndexPath(indexPath: NSIndexPath) -> Conversation { return user.conversations[indexPath.row] } func photoForIndexPath(indexPath: NSIndexPath) -> Photo? { if shouldShowConversationViewForIndexPath(indexPath) { return nil } else { let conversation = conversationForIndexPath(indexPath) return conversation.photos.last } } // Returns whether the conversation at indexPath contains more than one photo. func shouldShowConversationViewForIndexPath(indexPath: NSIndexPath) -> Bool { let conversation = conversationForIndexPath(indexPath) return conversation.photos.count > 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return user.conversations.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { return tableView.dequeueReusableCellWithIdentifier(ListTableViewController.cellIdentifier, forIndexPath: indexPath) } override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { // Whether to show the disclosure indicator for this cell. let pushes: Bool if shouldShowConversationViewForIndexPath(indexPath) { // If the conversation corresponding to this row has multiple photos. pushes = willShowingViewControllerPushWithSender(self) } else { // If the conversation corresponding to this row has a single photo. pushes = willShowingDetailViewControllerPushWithSender(self) } /* Only show a disclosure indicator if selecting this cell will trigger a push in the master view controller (the navigation controller above ourself). */ cell.accessoryType = pushes ? .DisclosureIndicator : .None let conversation = conversationForIndexPath(indexPath) cell.textLabel?.text = conversation.name } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let conversation = conversationForIndexPath(indexPath) if shouldShowConversationViewForIndexPath(indexPath) { let controller = ConversationViewController(conversation: conversation) controller.title = conversation.name // If this row has a conversation, we just want to show it. showViewController(controller, sender: self) } else { if let photo = conversation.photos.last { let controller = PhotoViewController(photo: photo) controller.title = conversation.name // If this row has a single photo, then show it as the detail (if possible). showDetailViewController(controller, sender: self) } } } } extension ListTableViewController: UIPopoverPresentationControllerDelegate { func presentationController(presentationController: UIPresentationController, willPresentWithAdaptiveStyle style: UIModalPresentationStyle, transitionCoordinator: UIViewControllerTransitionCoordinator?) { guard let presentedNavigationController = presentationController.presentedViewController as? UINavigationController else { return } // We want to hide the navigation bar if we're presenting in our original style (Popover) let hidesNavigationBar = style == .None presentedNavigationController.setNavigationBarHidden(hidesNavigationBar, animated: false) } }
apache-2.0
4bcf0b60f83dc8bedcf8e1956683aae1
39.216814
208
0.677742
6.281272
false
false
false
false
hisui/ReactiveSwift
ReactiveSwift/Subject.swift
1
2496
// Copyright (c) 2014 segfault.jp. All rights reserved. import Foundation public class Subject<A>: SubjectSource<A> { private var last: A public init(_ initialValue: A, _ name: String = __FUNCTION__) { self.last = initialValue super.init(name) } public var value: A { set(a) { merge(Update(a, self as AnyObject)) } get { return last } } public func update(a: A, by o: AnyObject) { merge(Update(a, o)) } override public func merge(a: Update<A>) { last = a.detail commit(a) } override public var firstValue: Box<A> { return Box(last) } public func bimap<B>(f: A -> B, _ g: B -> A, _ context: ExecutionContext) -> Subject<B> { let peer = Subject<B>(f(last)) setMappingBetween2(self, b: peer, f: f, context: context) setMappingBetween2(peer, b: self, f: g, context: context) return peer } } public class Update<A> { public let sender: AnyObject? public let detail: A public init(_ detail: A, _ sender: AnyObject?) { self.sender = sender self.detail = detail } public func map<B>(f: A -> B) -> Update<B> { return Update<B>(f(detail), sender) } } public class SubjectSource<A>: ForeignSource<Update<A>>, Mergeable { public let name: String public typealias UpdateDiff = A public typealias UpdateType = Update<A> public init(_ name: String = __FUNCTION__) { self.name = name } public func merge(a: Update<A>) { return undefined() } // TODO protected public func commit(a: Update<A>) { emitValue(a) } var firstValue: Box<A> { return undefined() } override final func invoke(chan: Dispatcher<Update<A>>) { super.invoke(chan) chan.emitValue(Update(+firstValue, self)) } public var unwrap: Stream<A> { return map { $0.detail } } } public protocol Mergeable { typealias UpdateDiff func merge(a: Update<UpdateDiff>) } func setMappingBetween2<A, B>(a: SubjectSource<A>, b: SubjectSource<B>, f: A -> B, context: ExecutionContext) { (setMappingBetween2(a, b: b, f: f) as Stream<()>).open(context) } // TODO fixes memory leak func setMappingBetween2<A, B, X>(a: SubjectSource<A>, b: SubjectSource<B>, f: A -> B) -> Stream<X> { return a.skip(1) .foreach { o in if o.sender !== b { b.merge(o.map(f)) } } .nullify() }
mit
031ebe514bcdbaa2e06316c3b74e0dec
23.470588
111
0.583734
3.575931
false
false
false
false
HongyuGao/FeedMeIOS
FeedMeIOS/OrderTableViewController.swift
1
8629
// // OrderTableViewController.swift // FeedMeIOS // // Created by Jun Chen on 26/03/2016. // Copyright © 2016 FeedMe. All rights reserved. // import UIKit class OrderTableViewController: UITableViewController, UIPopoverPresentationControllerDelegate, SSRadioButtonControllerDelegate { @IBOutlet weak var totalPrice: UILabel! @IBOutlet weak var deliveryFeeLabel: UILabel! @IBOutlet weak var totalFeeLabel: UILabel! @IBOutlet weak var deliveryAddressLabel: UILabel! @IBOutlet weak var addressSelectionView: UIView! var defaultDeliveryAddress: Address? var otherDeliveryAddresses = [Address]() // var radioButtons: [UIButton]? // var radioButtonController: SSRadioButtonsController? override func viewDidLoad() { super.viewDidLoad() if FeedMe.Variable.order != nil { totalPrice.text = "$" + String(format: "%.2f", FeedMe.Variable.order!.totalPrice) } else { totalPrice.text = "$" + String(format: "%.2f", 0) } FeedMe.Variable.selectedDeliveryAddress = User().defaultDeliveryAddress! FeedMe.Variable.selectedDeliveryAddress.setAsSelected() deliveryAddressLabel.text = FeedMe.Variable.selectedDeliveryAddress.toSimpleAddressString() updateGrandTotalFee() loadAddresses() // configureRadioButtonView(addressSelectionView) } override func viewWillAppear(animated: Bool) { self.deliveryAddressLabel.text = FeedMe.Variable.selectedDeliveryAddress.toSimpleAddressString() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func updateGrandTotalFee() { var grandTotalString = deliveryFeeLabel.text! grandTotalString.removeAtIndex(grandTotalString.startIndex) let grandTotal = FeedMe.Variable.order!.totalPrice + Double(grandTotalString)! totalFeeLabel.text = "$" + String(format: "%.2f", grandTotal) } // MARK: - configure addresses selction view. /* func addRadioButton(view: UIView, _ x: CGFloat, _ y: CGFloat, _ width: CGFloat, _ height: CGFloat, _ text: String ) -> SSRadioButton { let button = SSRadioButton() button.frame = CGRectMake(x, y, width, height) button.backgroundColor = UIColor(red: 0.82, green: 0.76, blue: 0.76, alpha: 1.0) button.setTitle(text, forState: UIControlState.Normal) button.titleLabel!.font = UIFont(name: "Times New Roman", size: 15) button.titleLabel!.textColor = UIColor.darkTextColor() button.addTarget(self, action: #selector(SSRadioButtonControllerDelegate.didSelectButton(_:)), forControlEvents: UIControlEvents.TouchUpInside) self.view.addSubview(button) print(view.frame.origin.x, view.frame.origin.y, view.frame.width, view.frame.height) print(button.frame.origin.x, button.frame.origin.y, button.frame.width, button.frame.height) return button } func configureRadioButtonView(view: UIView) { let x0 = view.frame.origin.x let y0 = view.frame.origin.y let width = view.frame.width let height = view.frame.height let radioButtonHeight = 50.0 let firstRadioButton = addRadioButton(view, x0, y0, width, CGFloat(radioButtonHeight), defaultDeliveryAddress!.toSimpleAddressString()) radioButtonController = SSRadioButtonsController(buttons: firstRadioButton) let circleRadius = 15 var y = y0 + CGFloat(circleRadius * 3 + 1) for address in otherDeliveryAddresses { radioButtonController?.addButton(addRadioButton(view, x0, y, width, CGFloat(radioButtonHeight), address.toSimpleAddressString())) y += CGFloat(circleRadius * 3 + 1) } radioButtonController!.delegate = self radioButtonController!.shouldLetDeSelect = true } func didSelectButton(aButton: UIButton?) { } */ /** To be changed. */ func loadAddresses() { defaultDeliveryAddress = Address(userName: "CSIT", addressLine1: "108 N Rd", addressLine2: "Acton", postcode: "2601", phone: "(02) 6125 5111", suburb: "Canberra", state: "ACT", selected: true) let otherAddress1 = Address(userName: "Jason", addressLine1: "109 N Rd", addressLine2: "Acton", postcode: "2601", phone: "(02) 6125 5111", suburb: "Canberra", state: "ACT", selected: false) let otherAddress2 = Address(userName: "Jun Chen", addressLine1: "110 N Rd", addressLine2: "Acton", postcode: "2601", phone: "(02) 6125 5111", suburb: "Canberra", state: "ACT", selected: false) otherDeliveryAddresses += [otherAddress1] otherDeliveryAddresses += [otherAddress2] } // MARK: - IBActions. @IBAction func newAddressBtnClicked(sender: UIButton) { } // MARK: - Editing in the table view cell @IBAction func increaseBtn(sender: UIButton) { let cell = sender.superview!.superview! as! OrderTableViewCell FeedMe.Variable.order!.addDish(FeedMe.Variable.order!.id2dish[cell.tag]!, qty: 1) cell.dishQtyLabel.text = String(Int(cell.dishQtyLabel.text!)! + 1) totalPrice.text = "$" + String(format: "%.2f", FeedMe.Variable.order!.totalPrice) updateGrandTotalFee() } @IBAction func decreaseBtn(sender: UIButton) { let cell = sender.superview!.superview! as! OrderTableViewCell let newQty = Int(cell.dishQtyLabel.text!)! - 1 FeedMe.Variable.order!.removeDish(cell.tag, qty: 1) if newQty == 0 { self.tableView.reloadData() } else { cell.dishQtyLabel.text = String(newQty) } totalPrice.text = "$" + String(format: "%.2f", FeedMe.Variable.order!.totalPrice) updateGrandTotalFee() } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return FeedMe.Variable.order!.id2dish.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellIdentifier = "OrderTableViewCell" let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! OrderTableViewCell // Configure the cell... let dish = FeedMe.Variable.order!.dishesList()[indexPath.row] cell.dishNameLabel.text = dish.name! cell.dishPriceLabel.text = "$" + String(format: "%.2f", Double(dish.price!)) cell.dishQtyLabel.text = String(FeedMe.Variable.order!.id2count[dish.ID]!) cell.tag = dish.ID return cell } // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
e8a5ff5df05ceb4e582125649f58dfb4
37.346667
200
0.659249
4.666306
false
false
false
false
descorp/SwiftPlayground
General.playground/Pages/BinaryTree.xcplaygroundpage/Contents.swift
1
934
//: [Previous](@previous) import Foundation var str = "Hello, playground" //: [Next](@next) class Node: Comparable { var left: Node? var right: Node? var value: Int = 0 init(_ value: Int) { self.value = value } static func <(lhs: Node, rhs: Node) -> Bool { return lhs.value < rhs.value } static func ==(lhs: Node, rhs: Node) -> Bool { return lhs.value == rhs.value } } class Tree { private var array = [Node]() subscript(index: Int) -> Node? { get { return array[index] } set(value) { if let value = value { array[index] = value } else { array.remove(at: index) } } } static func +=(left: Tree, right: Node) { left.addNode(right) } private func addNode(_ node: Node) { } }
mit
daeeee075352d0bc15eb8cedd47bf258
17.313725
50
0.468951
3.974468
false
false
false
false
ZamzamInc/ZamzamKit
Sources/ZamzamLocation/LocationManager.swift
1
6199
// // LocationManager.swift // ZamzamLocation // // Created by Basem Emara on 2020-05-30. // Copyright © 2020 Zamzam Inc. All rights reserved. // import Combine import CoreLocation.CLError import CoreLocation.CLHeading import CoreLocation.CLLocation /// A `LocationManager` proxy with publisher. public class LocationManager { private let service: LocationService public init(service: LocationService) { self.service = service self.service.delegate = self } } // MARK: - Authorization public extension LocationManager { /// Determines if location services is enabled and authorized for always or when in use. var isAuthorized: Bool { service.isAuthorized } #if !os(watchOS) && !os(tvOS) /// Indicates whether a widget is eligible to receive location updates. var isAuthorizedForWidgetUpdates: Bool { service.isAuthorizedForWidgetUpdates } #endif /// Determines if location services is enabled and authorized for the specified authorization type. func isAuthorized(for type: LocationAPI.AuthorizationType) -> Bool { service.isAuthorized(for: type) } /// Determines if the user has not chosen whether the app can use location services. var canRequestAuthorization: Bool { service.canRequestAuthorization } /// Requests permission to use location services. /// /// - Parameters: /// - type: Type of permission required, whether in the foreground (.whenInUse) or while running (.always). /// - startUpdatingLocation: Starts the generation of updates that report the user’s current location. /// - completion: True if the authorization succeeded for the authorization type, false otherwise. func requestAuthorization(for type: LocationAPI.AuthorizationType = .whenInUse) -> AnyPublisher<Bool, Never> { let publisher = Self.authorizationSubject .compactMap { $0 } .debounce(for: 0.2, scheduler: DispatchQueue.main) .eraseToAnyPublisher() // Handle authorized and exit guard !isAuthorized(for: type) else { Self.authorizationSubject.send(true) return publisher } // Request appropiate authorization before exit defer { service.requestAuthorization(for: type) } // Handle mismatched allowed and exit guard !isAuthorized else { // Notify in case authorization dialog not launched by OS // since user will be notified first time only and ignored subsequently Self.authorizationSubject.send(false) return publisher } // Handle denied and exit guard service.canRequestAuthorization else { Self.authorizationSubject.send(false) return publisher } return publisher } } // MARK: - Coordinate public extension LocationManager { /// The most recently retrieved user location. var location: CLLocation? { service.location } /// Starts the generation of updates that report the user’s current location. func startUpdatingLocation( enableBackground: Bool = false, pauseAutomatically: Bool? = nil ) -> AnyPublisher<Result<CLLocation, CLError>, Never> { service.startUpdatingLocation( enableBackground: enableBackground, pauseAutomatically: pauseAutomatically ) return Self.locationSubject .compactMap { $0 } .eraseToAnyPublisher() } /// Stops the generation of location updates. func stopUpdatingLocation() { service.stopUpdatingLocation() } } #if os(iOS) public extension LocationManager { /// Starts the generation of updates based on significant location changes. func startMonitoringSignificantLocationChanges() -> AnyPublisher<Result<CLLocation, CLError>, Never> { service.startMonitoringSignificantLocationChanges() return Self.locationSubject .compactMap { $0 } .eraseToAnyPublisher() } /// Stops the delivery of location events based on significant location changes. func stopMonitoringSignificantLocationChanges() { service.stopMonitoringSignificantLocationChanges() } } #endif // MARK: - Heading #if os(iOS) || os(watchOS) public extension LocationManager { /// The most recently reported heading. var heading: CLHeading? { service.heading } /// Starts the generation of updates that report the user’s current heading. func startUpdatingHeading(allowCalibration: Bool = false) -> AnyPublisher<Result<CLHeading, CLError>, Never> { service.shouldDisplayHeadingCalibration = allowCalibration if !service.startUpdatingHeading() { Self.headingSubject.send(.failure(CLError(.headingFailure))) } return Self.headingSubject .compactMap { $0 } .eraseToAnyPublisher() } /// Stops the generation of heading updates. func stopUpdatingHeading() { service.shouldDisplayHeadingCalibration = false service.stopUpdatingHeading() } func locationService(didUpdateHeading newHeading: CLHeading) { Self.headingSubject.send(.success(newHeading)) } } #endif // MARK: - Delegates extension LocationManager: LocationServiceDelegate { public func locationService(didChangeAuthorization authorization: Bool) { Self.authorizationSubject.send(authorization) } public func locationService(didUpdateLocation location: CLLocation) { Self.locationSubject.send(.success(location)) } public func locationService(didFailWithError error: CLError) { Self.locationSubject.send(.failure(error)) #if os(iOS) || os(watchOS) Self.headingSubject.send(.failure(error)) #endif } } // MARK: - Observers private extension LocationManager { static let authorizationSubject = CurrentValueSubject<Bool?, Never>(nil) static let locationSubject = CurrentValueSubject<Result<CLLocation, CLError>?, Never>(nil) #if os(iOS) || os(watchOS) static let headingSubject = CurrentValueSubject<Result<CLHeading, CLError>?, Never>(nil) #endif }
mit
e7550143cc5caf51c2d0dc996cccd971
32.112299
114
0.689276
5.172932
false
false
false
false
codestergit/swift
test/SILGen/protocols.swift
2
21995
// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s //===----------------------------------------------------------------------===// // Calling Existential Subscripts //===----------------------------------------------------------------------===// protocol SubscriptableGet { subscript(a : Int) -> Int { get } } protocol SubscriptableGetSet { subscript(a : Int) -> Int { get set } } var subscriptableGet : SubscriptableGet var subscriptableGetSet : SubscriptableGetSet func use_subscript_rvalue_get(_ i : Int) -> Int { return subscriptableGet[i] } // CHECK-LABEL: sil hidden @{{.*}}use_subscript_rvalue_get // CHECK: bb0(%0 : $Int): // CHECK: [[GLOB:%[0-9]+]] = global_addr @_T09protocols16subscriptableGetAA013SubscriptableC0_pv : $*SubscriptableGet // CHECK: [[PROJ:%[0-9]+]] = open_existential_addr immutable_access [[GLOB]] : $*SubscriptableGet to $*[[OPENED:@opened(.*) SubscriptableGet]] // CHECK: [[ALLOCSTACK:%[0-9]+]] = alloc_stack $[[OPENED]] // CHECK: copy_addr [[PROJ]] to [initialization] [[ALLOCSTACK]] : $*[[OPENED]] // CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #SubscriptableGet.subscript!getter.1 // CHECK-NEXT: [[RESULT:%[0-9]+]] = apply [[METH]]<[[OPENED]]>(%0, [[ALLOCSTACK]]) // CHECK-NEXT: destroy_addr [[ALLOCSTACK]] // CHECK-NEXT: dealloc_stack [[ALLOCSTACK]] : $*[[OPENED]] // CHECK-NEXT: return [[RESULT]] func use_subscript_lvalue_get(_ i : Int) -> Int { return subscriptableGetSet[i] } // CHECK-LABEL: sil hidden @{{.*}}use_subscript_lvalue_get // CHECK: bb0(%0 : $Int): // CHECK: [[GLOB:%[0-9]+]] = global_addr @_T09protocols19subscriptableGetSetAA013SubscriptablecD0_pv : $*SubscriptableGetSet // CHECK: [[PROJ:%[0-9]+]] = open_existential_addr immutable_access [[GLOB]] : $*SubscriptableGetSet to $*[[OPENED:@opened(.*) SubscriptableGetSet]] // CHECK: [[ALLOCSTACK:%[0-9]+]] = alloc_stack $[[OPENED]] // CHECK: copy_addr [[PROJ]] to [initialization] [[ALLOCSTACK]] : $*[[OPENED]] // CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #SubscriptableGetSet.subscript!getter.1 // CHECK-NEXT: [[RESULT:%[0-9]+]] = apply [[METH]]<[[OPENED]]>(%0, [[ALLOCSTACK]]) // CHECK-NEXT: destroy_addr [[ALLOCSTACK]] : $*[[OPENED]] // CHECK-NEXT: dealloc_stack [[ALLOCSTACK]] : $*[[OPENED]] // CHECK-NEXT: return [[RESULT]] func use_subscript_lvalue_set(_ i : Int) { subscriptableGetSet[i] = i } // CHECK-LABEL: sil hidden @{{.*}}use_subscript_lvalue_set // CHECK: bb0(%0 : $Int): // CHECK: [[GLOB:%[0-9]+]] = global_addr @_T09protocols19subscriptableGetSetAA013SubscriptablecD0_pv : $*SubscriptableGetSet // CHECK: [[PROJ:%[0-9]+]] = open_existential_addr mutable_access [[GLOB]] : $*SubscriptableGetSet to $*[[OPENED:@opened(.*) SubscriptableGetSet]] // CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #SubscriptableGetSet.subscript!setter.1 // CHECK-NEXT: apply [[METH]]<[[OPENED]]>(%0, %0, [[PROJ]]) //===----------------------------------------------------------------------===// // Calling Archetype Subscripts //===----------------------------------------------------------------------===// func use_subscript_archetype_rvalue_get<T : SubscriptableGet>(_ generic : T, idx : Int) -> Int { return generic[idx] } // CHECK-LABEL: sil hidden @{{.*}}use_subscript_archetype_rvalue_get // CHECK: bb0(%0 : $*T, %1 : $Int): // CHECK: [[STACK:%[0-9]+]] = alloc_stack $T // CHECK: copy_addr %0 to [initialization] [[STACK]] // CHECK: [[METH:%[0-9]+]] = witness_method $T, #SubscriptableGet.subscript!getter.1 // CHECK-NEXT: apply [[METH]]<T>(%1, [[STACK]]) // CHECK-NEXT: destroy_addr [[STACK]] : $*T // CHECK-NEXT: dealloc_stack [[STACK]] : $*T // CHECK-NEXT: destroy_addr %0 func use_subscript_archetype_lvalue_get<T : SubscriptableGetSet>(_ generic: inout T, idx : Int) -> Int { return generic[idx] } // CHECK-LABEL: sil hidden @{{.*}}use_subscript_archetype_lvalue_get // CHECK: bb0(%0 : $*T, %1 : $Int): // CHECK: [[GUARANTEEDSTACK:%[0-9]+]] = alloc_stack $T // CHECK: copy_addr %0 to [initialization] [[GUARANTEEDSTACK]] : $*T // CHECK: [[METH:%[0-9]+]] = witness_method $T, #SubscriptableGetSet.subscript!getter.1 // CHECK-NEXT: [[APPLYRESULT:%[0-9]+]] = apply [[METH]]<T>(%1, [[GUARANTEEDSTACK]]) // CHECK-NEXT: destroy_addr [[GUARANTEEDSTACK]] : $*T // CHECK-NEXT: dealloc_stack [[GUARANTEEDSTACK]] : $*T // CHECK: return [[APPLYRESULT]] func use_subscript_archetype_lvalue_set<T : SubscriptableGetSet>(_ generic: inout T, idx : Int) { generic[idx] = idx } // CHECK-LABEL: sil hidden @{{.*}}use_subscript_archetype_lvalue_set // CHECK: bb0(%0 : $*T, %1 : $Int): // CHECK: [[METH:%[0-9]+]] = witness_method $T, #SubscriptableGetSet.subscript!setter.1 // CHECK-NEXT: apply [[METH]]<T>(%1, %1, %0) //===----------------------------------------------------------------------===// // Calling Existential Properties //===----------------------------------------------------------------------===// protocol PropertyWithGetter { var a : Int { get } } protocol PropertyWithGetterSetter { var b : Int { get set } } var propertyGet : PropertyWithGetter var propertyGetSet : PropertyWithGetterSetter func use_property_rvalue_get() -> Int { return propertyGet.a } // CHECK-LABEL: sil hidden @{{.*}}use_property_rvalue_get // CHECK: [[GLOB:%[0-9]+]] = global_addr @_T09protocols11propertyGetAA18PropertyWithGetter_pv : $*PropertyWithGetter // CHECK: [[PROJ:%[0-9]+]] = open_existential_addr immutable_access [[GLOB]] : $*PropertyWithGetter to $*[[OPENED:@opened(.*) PropertyWithGetter]] // CHECK: [[COPY:%.*]] = alloc_stack $[[OPENED]] // CHECK-NEXT: copy_addr [[PROJ]] to [initialization] [[COPY]] : $*[[OPENED]] // CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #PropertyWithGetter.a!getter.1 // CHECK-NEXT: apply [[METH]]<[[OPENED]]>([[COPY]]) func use_property_lvalue_get() -> Int { return propertyGetSet.b } // CHECK-LABEL: sil hidden @{{.*}}use_property_lvalue_get // CHECK: [[GLOB:%[0-9]+]] = global_addr @_T09protocols14propertyGetSetAA24PropertyWithGetterSetter_pv : $*PropertyWithGetterSetter // CHECK: [[PROJ:%[0-9]+]] = open_existential_addr immutable_access [[GLOB]] : $*PropertyWithGetterSetter to $*[[OPENED:@opened(.*) PropertyWithGetterSetter]] // CHECK: [[STACK:%[0-9]+]] = alloc_stack $[[OPENED]] // CHECK: copy_addr [[PROJ]] to [initialization] [[STACK]] // CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #PropertyWithGetterSetter.b!getter.1 // CHECK-NEXT: apply [[METH]]<[[OPENED]]>([[STACK]]) func use_property_lvalue_set(_ x : Int) { propertyGetSet.b = x } // CHECK-LABEL: sil hidden @{{.*}}use_property_lvalue_set // CHECK: bb0(%0 : $Int): // CHECK: [[GLOB:%[0-9]+]] = global_addr @_T09protocols14propertyGetSetAA24PropertyWithGetterSetter_pv : $*PropertyWithGetterSetter // CHECK: [[PROJ:%[0-9]+]] = open_existential_addr mutable_access [[GLOB]] : $*PropertyWithGetterSetter to $*[[OPENED:@opened(.*) PropertyWithGetterSetter]] // CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #PropertyWithGetterSetter.b!setter.1 // CHECK-NEXT: apply [[METH]]<[[OPENED]]>(%0, [[PROJ]]) //===----------------------------------------------------------------------===// // Calling Archetype Properties //===----------------------------------------------------------------------===// func use_property_archetype_rvalue_get<T : PropertyWithGetter>(_ generic : T) -> Int { return generic.a } // CHECK-LABEL: sil hidden @{{.*}}use_property_archetype_rvalue_get // CHECK: bb0(%0 : $*T): // CHECK: [[STACK:%[0-9]+]] = alloc_stack $T // CHECK: copy_addr %0 to [initialization] [[STACK]] // CHECK: [[METH:%[0-9]+]] = witness_method $T, #PropertyWithGetter.a!getter.1 // CHECK-NEXT: apply [[METH]]<T>([[STACK]]) // CHECK-NEXT: destroy_addr [[STACK]] // CHECK-NEXT: dealloc_stack [[STACK]] // CHECK-NEXT: destroy_addr %0 func use_property_archetype_lvalue_get<T : PropertyWithGetterSetter>(_ generic : T) -> Int { return generic.b } // CHECK-LABEL: sil hidden @{{.*}}use_property_archetype_lvalue_get // CHECK: bb0(%0 : $*T): // CHECK: [[STACK:%[0-9]+]] = alloc_stack $T // CHECK: copy_addr %0 to [initialization] [[STACK]] : $*T // CHECK: [[METH:%[0-9]+]] = witness_method $T, #PropertyWithGetterSetter.b!getter.1 // CHECK-NEXT: apply [[METH]]<T>([[STACK]]) // CHECK-NEXT: destroy_addr [[STACK]] : $*T // CHECK-NEXT: dealloc_stack [[STACK]] : $*T // CHECK-NEXT: destroy_addr %0 func use_property_archetype_lvalue_set<T : PropertyWithGetterSetter>(_ generic: inout T, v : Int) { generic.b = v } // CHECK-LABEL: sil hidden @{{.*}}use_property_archetype_lvalue_set // CHECK: bb0(%0 : $*T, %1 : $Int): // CHECK: [[METH:%[0-9]+]] = witness_method $T, #PropertyWithGetterSetter.b!setter.1 // CHECK-NEXT: apply [[METH]]<T>(%1, %0) //===----------------------------------------------------------------------===// // Calling Initializers //===----------------------------------------------------------------------===// protocol Initializable { init(int: Int) } // CHECK-LABEL: sil hidden @_T09protocols27use_initializable_archetype{{[_0-9a-zA-Z]*}}F func use_initializable_archetype<T: Initializable>(_ t: T, i: Int) { // CHECK: [[T_INIT:%[0-9]+]] = witness_method $T, #Initializable.init!allocator.1 : {{.*}} : $@convention(witness_method) <τ_0_0 where τ_0_0 : Initializable> (Int, @thick τ_0_0.Type) -> @out τ_0_0 // CHECK: [[T_RESULT:%[0-9]+]] = alloc_stack $T // CHECK: [[T_META:%[0-9]+]] = metatype $@thick T.Type // CHECK: [[T_RESULT_ADDR:%[0-9]+]] = apply [[T_INIT]]<T>([[T_RESULT]], %1, [[T_META]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : Initializable> (Int, @thick τ_0_0.Type) -> @out τ_0_0 // CHECK: destroy_addr [[T_RESULT]] : $*T // CHECK: dealloc_stack [[T_RESULT]] : $*T // CHECK: destroy_addr [[VAR_0:%[0-9]+]] : $*T // CHECK: [[RESULT:%[0-9]+]] = tuple () // CHECK: return [[RESULT]] : $() T(int: i) } // CHECK: sil hidden @_T09protocols29use_initializable_existential{{[_0-9a-zA-Z]*}}F func use_initializable_existential(_ im: Initializable.Type, i: Int) { // CHECK: bb0([[IM:%[0-9]+]] : $@thick Initializable.Type, [[I:%[0-9]+]] : $Int): // CHECK: [[ARCHETYPE_META:%[0-9]+]] = open_existential_metatype [[IM]] : $@thick Initializable.Type to $@thick (@opened([[N:".*"]]) Initializable).Type // CHECK: [[TEMP_VALUE:%[0-9]+]] = alloc_stack $Initializable // CHECK: [[TEMP_ADDR:%[0-9]+]] = init_existential_addr [[TEMP_VALUE]] : $*Initializable, $@opened([[N]]) Initializable // CHECK: [[INIT_WITNESS:%[0-9]+]] = witness_method $@opened([[N]]) Initializable, #Initializable.init!allocator.1 : {{.*}}, [[ARCHETYPE_META]]{{.*}} : $@convention(witness_method) <τ_0_0 where τ_0_0 : Initializable> (Int, @thick τ_0_0.Type) -> @out τ_0_0 // CHECK: [[INIT_RESULT:%[0-9]+]] = apply [[INIT_WITNESS]]<@opened([[N]]) Initializable>([[TEMP_ADDR]], [[I]], [[ARCHETYPE_META]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : Initializable> (Int, @thick τ_0_0.Type) -> @out τ_0_0 // CHECK: destroy_addr [[TEMP_VALUE]] : $*Initializable // CHECK: dealloc_stack [[TEMP_VALUE]] : $*Initializable im.init(int: i) // CHECK: [[RESULT:%[0-9]+]] = tuple () // CHECK: return [[RESULT]] : $() } //===----------------------------------------------------------------------===// // Protocol conformance and witness table generation //===----------------------------------------------------------------------===// class ClassWithGetter : PropertyWithGetter { var a: Int { get { return 42 } } } // Make sure we are generating a protocol witness that calls the class method on // ClassWithGetter. // CHECK-LABEL: sil private [transparent] [thunk] @_T09protocols15ClassWithGetterCAA08PropertycD0A2aDP1aSifgTW : $@convention(witness_method) (@in_guaranteed ClassWithGetter) -> Int { // CHECK: bb0([[C:%.*]] : $*ClassWithGetter): // CHECK-NEXT: [[CCOPY:%.*]] = alloc_stack $ClassWithGetter // CHECK-NEXT: copy_addr [[C]] to [initialization] [[CCOPY]] // CHECK-NEXT: [[CCOPY_LOADED:%.*]] = load [take] [[CCOPY]] // CHECK-NEXT: [[BORROWED_CCOPY_LOADED:%.*]] = begin_borrow [[CCOPY_LOADED]] // CHECK-NEXT: [[FUN:%.*]] = class_method [[BORROWED_CCOPY_LOADED]] : $ClassWithGetter, #ClassWithGetter.a!getter.1 : (ClassWithGetter) -> () -> Int, $@convention(method) (@guaranteed ClassWithGetter) -> Int // CHECK-NEXT: apply [[FUN]]([[BORROWED_CCOPY_LOADED]]) // CHECK-NEXT: end_borrow [[BORROWED_CCOPY_LOADED]] from [[CCOPY_LOADED]] // CHECK-NEXT: destroy_value [[CCOPY_LOADED]] // CHECK-NEXT: dealloc_stack [[CCOPY]] // CHECK-NEXT: return class ClassWithGetterSetter : PropertyWithGetterSetter, PropertyWithGetter { var a: Int { get { return 1 } set {} } var b: Int { get { return 2 } set {} } } // CHECK-LABEL: sil private [transparent] [thunk] @_T09protocols21ClassWithGetterSetterCAA08PropertycdE0A2aDP1bSifgTW : $@convention(witness_method) (@in_guaranteed ClassWithGetterSetter) -> Int { // CHECK: bb0([[C:%.*]] : $*ClassWithGetterSetter): // CHECK-NEXT: [[CCOPY:%.*]] = alloc_stack $ClassWithGetterSetter // CHECK-NEXT: copy_addr [[C]] to [initialization] [[CCOPY]] // CHECK-NEXT: [[CCOPY_LOADED:%.*]] = load [take] [[CCOPY]] // CHECK-NEXT: [[BORROWED_CCOPY_LOADED:%.*]] = begin_borrow [[CCOPY_LOADED]] // CHECK-NEXT: [[FUN:%.*]] = class_method [[BORROWED_CCOPY_LOADED]] : $ClassWithGetterSetter, #ClassWithGetterSetter.b!getter.1 : (ClassWithGetterSetter) -> () -> Int, $@convention(method) (@guaranteed ClassWithGetterSetter) -> Int // CHECK-NEXT: apply [[FUN]]([[BORROWED_CCOPY_LOADED]]) // CHECK-NEXT: end_borrow [[BORROWED_CCOPY_LOADED]] from [[CCOPY_LOADED]] // CHECK-NEXT: destroy_value [[CCOPY_LOADED]] // CHECK-NEXT: dealloc_stack [[CCOPY]] // CHECK-NEXT: return // Stored variables fulfilling property requirements // class ClassWithStoredProperty : PropertyWithGetter { var a : Int = 0 // Make sure that accesses go through the generated accessors for classes. func methodUsingProperty() -> Int { return a } // CHECK-LABEL: sil hidden @_T09protocols23ClassWithStoredPropertyC011methodUsingE0SiyF // CHECK: bb0([[ARG:%.*]] : $ClassWithStoredProperty): // CHECK-NEXT: debug_value [[ARG]] // CHECK-NOT: copy_value // CHECK-NEXT: [[FUN:%.*]] = class_method [[ARG]] : $ClassWithStoredProperty, #ClassWithStoredProperty.a!getter.1 : (ClassWithStoredProperty) -> () -> Int, $@convention(method) (@guaranteed ClassWithStoredProperty) -> Int // CHECK-NEXT: [[RESULT:%.*]] = apply [[FUN]]([[ARG]]) // CHECK-NOT: destroy_value // CHECK-NEXT: return [[RESULT]] : $Int } struct StructWithStoredProperty : PropertyWithGetter { var a : Int // Make sure that accesses aren't going through the generated accessors. func methodUsingProperty() -> Int { return a } // CHECK-LABEL: sil hidden @_T09protocols24StructWithStoredPropertyV011methodUsingE0SiyF // CHECK: bb0(%0 : $StructWithStoredProperty): // CHECK-NEXT: debug_value %0 // CHECK-NEXT: %2 = struct_extract %0 : $StructWithStoredProperty, #StructWithStoredProperty.a // CHECK-NEXT: return %2 : $Int } // Make sure that we generate direct function calls for out struct protocol // witness since structs don't do virtual calls for methods. // // *NOTE* Even though at first glance the copy_addr looks like a leak // here, StructWithStoredProperty is a trivial struct implying that no // leak is occurring. See the test with StructWithStoredClassProperty // that makes sure in such a case we don't leak. This is due to the // thunking code being too dumb but it is harmless to program // correctness. // // CHECK-LABEL: sil private [transparent] [thunk] @_T09protocols24StructWithStoredPropertyVAA0eC6GetterA2aDP1aSifgTW : $@convention(witness_method) (@in_guaranteed StructWithStoredProperty) -> Int { // CHECK: bb0([[C:%.*]] : $*StructWithStoredProperty): // CHECK-NEXT: [[CCOPY:%.*]] = alloc_stack $StructWithStoredProperty // CHECK-NEXT: copy_addr [[C]] to [initialization] [[CCOPY]] // CHECK-NEXT: [[CCOPY_LOADED:%.*]] = load [trivial] [[CCOPY]] // CHECK-NEXT: function_ref // CHECK-NEXT: [[FUN:%.*]] = function_ref @_T09protocols24StructWithStoredPropertyV1aSifg : $@convention(method) (StructWithStoredProperty) -> Int // CHECK-NEXT: apply [[FUN]]([[CCOPY_LOADED]]) // CHECK-NEXT: dealloc_stack [[CCOPY]] // CHECK-NEXT: return class C {} // Make sure that if the getter has a class property, we pass it in // in_guaranteed and don't leak. struct StructWithStoredClassProperty : PropertyWithGetter { var a : Int var c: C = C() // Make sure that accesses aren't going through the generated accessors. func methodUsingProperty() -> Int { return a } // CHECK-LABEL: sil hidden @_T09protocols29StructWithStoredClassPropertyV011methodUsingF0SiyF // CHECK: bb0(%0 : $StructWithStoredClassProperty): // CHECK-NEXT: debug_value %0 // CHECK-NEXT: %2 = struct_extract %0 : $StructWithStoredClassProperty, #StructWithStoredClassProperty.a // CHECK-NEXT: return %2 : $Int } // CHECK-LABEL: sil private [transparent] [thunk] @_T09protocols29StructWithStoredClassPropertyVAA0fC6GetterA2aDP1aSifgTW : $@convention(witness_method) (@in_guaranteed StructWithStoredClassProperty) -> Int { // CHECK: bb0([[C:%.*]] : $*StructWithStoredClassProperty): // CHECK-NEXT: [[CCOPY:%.*]] = alloc_stack $StructWithStoredClassProperty // CHECK-NEXT: copy_addr [[C]] to [initialization] [[CCOPY]] // CHECK-NEXT: [[CCOPY_LOADED:%.*]] = load [take] [[CCOPY]] // CHECK-NEXT: [[BORROWED_CCOPY_LOADED:%.*]] = begin_borrow [[CCOPY_LOADED]] // CHECK-NEXT: function_ref // CHECK-NEXT: [[FUN:%.*]] = function_ref @_T09protocols29StructWithStoredClassPropertyV1aSifg : $@convention(method) (@guaranteed StructWithStoredClassProperty) -> Int // CHECK-NEXT: apply [[FUN]]([[BORROWED_CCOPY_LOADED]]) // CHECK-NEXT: end_borrow [[BORROWED_CCOPY_LOADED]] from [[CCOPY_LOADED]] // CHECK-NEXT: destroy_value [[CCOPY_LOADED]] // CHECK-NEXT: dealloc_stack [[CCOPY]] // CHECK-NEXT: return // rdar://22676810 protocol ExistentialProperty { var p: PropertyWithGetterSetter { get set } } func testExistentialPropertyRead<T: ExistentialProperty>(_ t: inout T) { let b = t.p.b } // CHECK-LABEL: sil hidden @_T09protocols27testExistentialPropertyRead{{[_0-9a-zA-Z]*}}F // CHECK: [[P_TEMP:%.*]] = alloc_stack $PropertyWithGetterSetter // CHECK: [[T_TEMP:%.*]] = alloc_stack $T // CHECK: copy_addr %0 to [initialization] [[T_TEMP]] : $*T // CHECK: [[P_GETTER:%.*]] = witness_method $T, #ExistentialProperty.p!getter.1 : // CHECK-NEXT: apply [[P_GETTER]]<T>([[P_TEMP]], [[T_TEMP]]) // CHECK-NEXT: destroy_addr [[T_TEMP]] // CHECK-NEXT: [[OPEN:%.*]] = open_existential_addr immutable_access [[P_TEMP]] : $*PropertyWithGetterSetter to $*[[P_OPENED:@opened(.*) PropertyWithGetterSetter]] // CHECK-NEXT: [[T0:%.*]] = alloc_stack $[[P_OPENED]] // CHECK-NEXT: copy_addr [[OPEN]] to [initialization] [[T0]] // CHECK-NEXT: [[B_GETTER:%.*]] = witness_method $[[P_OPENED]], #PropertyWithGetterSetter.b!getter.1 // CHECK-NEXT: apply [[B_GETTER]]<[[P_OPENED]]>([[T0]]) // CHECK-NEXT: destroy_addr [[T0]] // CHECK-NOT: witness_method // CHECK: return func modify(_ x: inout Int) {} // Make sure we call the materializeForSet callback with the correct // generic signature. func modifyProperty<T : PropertyWithGetterSetter>(_ x: inout T) { modify(&x.b) } // CHECK-LABEL: sil hidden @_T09protocols14modifyPropertyyxzAA0C16WithGetterSetterRzlF // CHECK: [[MODIFY_FN:%.*]] = function_ref @_T09protocols6modifyySizF // CHECK: [[WITNESS_FN:%.*]] = witness_method $T, #PropertyWithGetterSetter.b!materializeForSet.1 // CHECK: [[RESULT:%.*]] = apply [[WITNESS_FN]]<T> // CHECK: [[TEMPORARY:%.*]] = tuple_extract [[RESULT]] // CHECK: [[CALLBACK:%.*]] = tuple_extract [[RESULT]] // CHECK: [[TEMPORARY_ADDR_TMP:%.*]] = pointer_to_address [[TEMPORARY]] : $Builtin.RawPointer to [strict] $*Int // CHECK: [[TEMPORARY_ADDR:%.*]] = mark_dependence [[TEMPORARY_ADDR_TMP]] : $*Int on %0 : $*T // CHECK: apply [[MODIFY_FN]]([[TEMPORARY_ADDR]]) // CHECK: switch_enum [[CALLBACK]] : $Optional<Builtin.RawPointer>, case #Optional.some!enumelt.1: bb1, case #Optional.none!enumelt: bb2 // CHECK: bb1([[CALLBACK_ADDR:%.*]] : $Builtin.RawPointer): // CHECK: [[CALLBACK:%.*]] = pointer_to_thin_function [[CALLBACK_ADDR]] // CHECK: [[METATYPE:%.*]] = metatype $@thick T.Type // CHECK: [[TEMPORARY:%.*]] = address_to_pointer [[TEMPORARY_ADDR]] : $*Int to $Builtin.RawPointer // CHECK: apply [[CALLBACK]]<T> // CHECK-LABEL: sil_witness_table hidden ClassWithGetter: PropertyWithGetter module protocols { // CHECK-NEXT: method #PropertyWithGetter.a!getter.1: {{.*}} : @_T09protocols15ClassWithGetterCAA08PropertycD0A2aDP1aSifgTW // CHECK-NEXT: } // CHECK-LABEL: sil_witness_table hidden ClassWithGetterSetter: PropertyWithGetterSetter module protocols { // CHECK-NEXT: method #PropertyWithGetterSetter.b!getter.1: {{.*}} : @_T09protocols21ClassWithGetterSetterCAA08PropertycdE0A2aDP1bSifgTW // CHECK-NEXT: method #PropertyWithGetterSetter.b!setter.1: {{.*}} : @_T09protocols21ClassWithGetterSetterCAA08PropertycdE0A2aDP1bSifsTW // CHECK-NEXT: method #PropertyWithGetterSetter.b!materializeForSet.1: {{.*}} : @_T09protocols21ClassWithGetterSetterCAA08PropertycdE0A2aDP1bSifmTW // CHECK-NEXT: } // CHECK-LABEL: sil_witness_table hidden ClassWithGetterSetter: PropertyWithGetter module protocols { // CHECK-NEXT: method #PropertyWithGetter.a!getter.1: {{.*}} : @_T09protocols21ClassWithGetterSetterCAA08PropertycD0A2aDP1aSifgTW // CHECK-NEXT: } // CHECK-LABEL: sil_witness_table hidden StructWithStoredProperty: PropertyWithGetter module protocols { // CHECK-NEXT: method #PropertyWithGetter.a!getter.1: {{.*}} : @_T09protocols24StructWithStoredPropertyVAA0eC6GetterA2aDP1aSifgTW // CHECK-NEXT: } // CHECK-LABEL: sil_witness_table hidden StructWithStoredClassProperty: PropertyWithGetter module protocols { // CHECK-NEXT: method #PropertyWithGetter.a!getter.1: {{.*}} : @_T09protocols29StructWithStoredClassPropertyVAA0fC6GetterA2aDP1aSifgTW // CHECK-NEXT: }
apache-2.0
c8e0b48a0352c8c73af708d256afd21a
48.839002
257
0.643478
3.771924
false
false
false
false
vector-im/vector-ios
Tools/Templates/buildable/ScreenTemplate/TemplateScreenCoordinator.swift
1
2404
/* Copyright 2021 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 Foundation import UIKit final class TemplateScreenCoordinator: TemplateScreenCoordinatorProtocol { // MARK: - Properties // MARK: Private private let parameters: TemplateScreenCoordinatorParameters private var templateScreenViewModel: TemplateScreenViewModelProtocol private let templateScreenViewController: TemplateScreenViewController // MARK: Public // Must be used only internally var childCoordinators: [Coordinator] = [] weak var delegate: TemplateScreenCoordinatorDelegate? // MARK: - Setup init(parameters: TemplateScreenCoordinatorParameters) { self.parameters = parameters let templateScreenViewModel = TemplateScreenViewModel(session: self.parameters.session) let templateScreenViewController = TemplateScreenViewController.instantiate(with: templateScreenViewModel) self.templateScreenViewModel = templateScreenViewModel self.templateScreenViewController = templateScreenViewController } // MARK: - Public func start() { self.templateScreenViewModel.coordinatorDelegate = self } func toPresentable() -> UIViewController { return self.templateScreenViewController } } // MARK: - TemplateScreenViewModelCoordinatorDelegate extension TemplateScreenCoordinator: TemplateScreenViewModelCoordinatorDelegate { func templateScreenViewModel(_ viewModel: TemplateScreenViewModelProtocol, didCompleteWithUserDisplayName userDisplayName: String?) { self.delegate?.templateScreenCoordinator(self, didCompleteWithUserDisplayName: userDisplayName) } func templateScreenViewModelDidCancel(_ viewModel: TemplateScreenViewModelProtocol) { self.delegate?.templateScreenCoordinatorDidCancel(self) } }
apache-2.0
7b35471f738702341ec7d0bae8d096c9
34.352941
137
0.755824
5.877751
false
false
false
false
jverdi/Gramophone
Tests/UsersTests.swift
1
30393
// // UserTests.swift // Gramophone // // Copyright (c) 2017 Jared Verdi. All Rights Reserved // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Quick import Nimble import OHHTTPStubs @testable import Gramophone class UserSpec: QuickSpec { override func spec() { describe("GET me") { if enableStubbing { stub(condition: isHost(GramophoneTestsHost) && isPath("/v1/users/self") && isMethodGET()) { request in return OHHTTPStubsResponse( fileAtPath: OHPathForFile("user.json", type(of: self))!, statusCode: 200, headers: GramophoneTestsHeaders ) } } it("requires authentication") { TestingUtilities.testAuthentication() { gramophone, completion in gramophone.client.me() { completion($0) } } } it("parses http successful response") { TestingUtilities.testSuccessfulRequest(httpCode: 200) { gramophone, completion in gramophone.client.me() { completion($0) } } } it("parses into a User object") { TestingUtilities.testSuccessfulRequestWithDataConfirmation(httpCode: 200) { gramophone, completion in gramophone.client.me() { completion($0) { user in expect(user.ID).to(equal("4869495376")) expect(user.username).to(equal("jvtester")) expect(user.fullName).to(equal("Jared")) expect(user.profilePictureURL).to(equal( URL(string: "https://instagram.fktm4-1.fna.fbcdn.net/t51.2885-19/11906329_960233084022564_1448528159_a.jpg") )) expect(user.bio).to(equal("This is #jvtester and I #jvtest_ all of the things")) expect(user.websiteURL).to(beNil()) expect(user.mediaCount).to(equal(2)) expect(user.followingCount).to(equal(0)) expect(user.followersCount).to(equal(0)) } } } } } let scopes: [Scope] = [.publicContent] describe("GET user by id") { let userID = "4869495376" if enableStubbing { stub(condition: isHost(GramophoneTestsHost) && isPath("/v1/users/\(userID)") && isMethodGET()) { request in return OHHTTPStubsResponse( fileAtPath: OHPathForFile("user.json", type(of: self))!, statusCode: 200, headers: GramophoneTestsHeaders ) } } it("requires the correct scopes") { TestingUtilities.testScopes(scopes: scopes) { gramophone, completion in gramophone.client.user(withID: userID) { completion($0) } } } it("requires authentication") { TestingUtilities.testAuthentication(scopes: scopes) { gramophone, completion in gramophone.client.user(withID: userID) { completion($0) } } } it("parses http successful response") { TestingUtilities.testSuccessfulRequest(httpCode: 200, scopes: scopes) { gramophone, completion in gramophone.client.user(withID: userID) { completion($0) } } } it("parses into a User object") { TestingUtilities.testSuccessfulRequestWithDataConfirmation(httpCode: 200, scopes: scopes) { gramophone, completion in gramophone.client.user(withID: userID) { completion($0) { user in expect(user.ID).to(equal("4869495376")) expect(user.username).to(equal("jvtester")) expect(user.fullName).to(equal("Jared")) expect(user.profilePictureURL).to(equal( URL(string: "https://instagram.fktm4-1.fna.fbcdn.net/t51.2885-19/11906329_960233084022564_1448528159_a.jpg") )) expect(user.bio).to(equal("This is #jvtester and I #jvtest_ all of the things")) expect(user.websiteURL).to(beNil()) expect(user.mediaCount).to(equal(2)) expect(user.followingCount).to(equal(0)) expect(user.followersCount).to(equal(0)) } } } } } describe("GET my recent media") { if enableStubbing { stub(condition: isHost(GramophoneTestsHost) && isPath("/v1/users/self/media/recent") && isMethodGET()) { request in return OHHTTPStubsResponse( fileAtPath: OHPathForFile("media.json", type(of: self))!, statusCode: 200, headers: GramophoneTestsHeaders ) } } it("requires authentication") { TestingUtilities.testAuthentication() { gramophone, completion in gramophone.client.myRecentMedia(options: nil) { completion($0) } } } it("parses http successful response") { TestingUtilities.testSuccessfulRequest(httpCode: 200) { gramophone, completion in gramophone.client.myRecentMedia(options: nil) { completion($0) } } } it("parses into Media objects") { TestingUtilities.testSuccessfulRequestWithDataConfirmation(httpCode: 200) { gramophone, completion in gramophone.client.myRecentMedia(options: nil) { completion($0) { media in expect(media.items.count).to(equal(3)) let media = media.items[0] expect(media.ID).to(equal("1482048616133874767_989545")) expect(media.user.ID).to(equal("989545")) expect(media.user.fullName).to(equal("Jared Verdi")) expect(media.user.profilePictureURL).to(equal( URL(string: "https://scontent.cdninstagram.com/t51.2885-19/11249876_446198148894593_1426023307_a.jpg")) ) expect(media.user.username).to(equal("jverdi")) expect(media.images).toNot(beNil()) if let images = media.images { expect(images[Media.ImageSize.thumbnail]).toNot(beNil()) expect(images[Media.ImageSize.lowRes]).toNot(beNil()) expect(images[Media.ImageSize.standard]).toNot(beNil()) if let thumbnail = images[Media.ImageSize.thumbnail] { expect(thumbnail.width).to(equal(150)) expect(thumbnail.height).to(equal(150)) expect(thumbnail.url).to(equal(URL(string: "https://scontent.cdninstagram.com/t51.2885-15/s150x150/e35/c108.0.863.863/17662429_420883991615204_3921714365731962880_n.jpg" )!)) } if let lowRes = images[Media.ImageSize.lowRes] { expect(lowRes.width).to(equal(320)) expect(lowRes.height).to(equal(255)) expect(lowRes.url).to(equal(URL(string: "https://scontent.cdninstagram.com/t51.2885-15/s320x320/e35/17662429_420883991615204_3921714365731962880_n.jpg" )!)) } if let standard = images[Media.ImageSize.standard] { expect(standard.width).to(equal(640)) expect(standard.height).to(equal(511)) expect(standard.url).to(equal(URL(string: "https://scontent.cdninstagram.com/t51.2885-15/s640x640/sh0.08/e35/17662429_420883991615204_3921714365731962880_n.jpg" )!)) } } expect(media.videos).to(beNil()) expect(media.creationDate).to(equal(Date(timeIntervalSince1970: 1490893984))) if let caption = media.caption { expect(caption.ID).to(equal("17864935459119823")) expect(caption.text).to(equal("Bridge Sunsets\n.\n.\n.\n.\n.\n.\n#sunrise #chasingsunrise #skylovers #longexposure_shots #longexpo #nakedplanet #earthmagazine #ourplanetdaily #thebest_capture #natgeowild #natgeohub #awesomeearth #master_shots #skylove #instasky #yourshottphotographer #sunrise_and_sunsets #sunrise_sunsets_aroundworld #cloudlovers #cloudsofinstagram #instasunrise #sunrisesunset #cloudstagram #best_skyshots #twilightscapes #artofvisuals #theimaged #instagood #instagoodmyphoto #peoplescreatives")) expect(caption.creationDate).to(equal(Date(timeIntervalSince1970: 1490893984))) expect(caption.creator.ID).to(equal("989545")) expect(caption.creator.fullName).to(equal("Jared Verdi")) expect(caption.creator.profilePictureURL).to(equal( URL(string: "https://scontent.cdninstagram.com/t51.2885-19/11249876_446198148894593_1426023307_a.jpg") )) expect(caption.creator.username).to(equal("jverdi")) } expect(media.userHasLiked).to(equal(false)) expect(media.likesCount).to(equal(136)) expect(Set(media.tags)).to(equal(Set(["peoplescreatives", "instasky", "chasingsunrise", "instagoodmyphoto", "awesomeearth", "cloudlovers", "best_skyshots", "yourshottphotographer", "sunrise", "cloudsofinstagram", "theimaged", "nakedplanet", "earthmagazine", "natgeohub", "master_shots", "longexpo", "skylove", "ourplanetdaily", "instagood", "natgeowild", "skylovers", "artofvisuals", "thebest_capture", "twilightscapes", "longexposure_shots", "sunrise_and_sunsets", "instasunrise", "sunrisesunset", "sunrise_sunsets_aroundworld", "cloudstagram"]))) expect(media.filterName).to(equal("Ashby")) expect(media.commentCount).to(equal(10)) expect(media.type).to(equal(Media.MediaType.image)) expect(media.url).to(equal(URL(string: "https://www.instagram.com/p/BSRS104hNRP/"))) expect(media.location).to(beNil()) // expect(media.attribution).to(beNil()) expect(media.usersInPhoto).to(beEmpty()) } } } } } describe("GET user recent media") { let userID = "4869495376" if enableStubbing { stub(condition: isHost(GramophoneTestsHost) && isPath("/v1/users/\(userID)/media/recent") && isMethodGET()) { request in return OHHTTPStubsResponse( fileAtPath: OHPathForFile("media.json", type(of: self))!, statusCode: 200, headers: GramophoneTestsHeaders ) } } it("requires the correct scopes") { TestingUtilities.testScopes(scopes: scopes) { gramophone, completion in gramophone.client.userRecentMedia(withID: userID, options: nil) { completion($0) } } } it("requires authentication") { TestingUtilities.testAuthentication(scopes: scopes) { gramophone, completion in gramophone.client.userRecentMedia(withID: userID, options: nil) { completion($0) } } } it("parses http successful response") { TestingUtilities.testSuccessfulRequest(httpCode: 200, scopes: scopes) { gramophone, completion in gramophone.client.userRecentMedia(withID: userID, options: nil) { completion($0) } } } it("parses into Media objects") { TestingUtilities.testSuccessfulRequestWithDataConfirmation(httpCode: 200, scopes: scopes) { gramophone, completion in gramophone.client.userRecentMedia(withID: userID, options: nil) { completion($0) { media in expect(media.items.count).to(equal(3)) let media = media.items[0] expect(media.ID).to(equal("1482048616133874767_989545")) expect(media.user.ID).to(equal("989545")) expect(media.user.fullName).to(equal("Jared Verdi")) expect(media.user.profilePictureURL).to(equal( URL(string: "https://scontent.cdninstagram.com/t51.2885-19/11249876_446198148894593_1426023307_a.jpg")) ) expect(media.user.username).to(equal("jverdi")) expect(media.images).toNot(beNil()) if let images = media.images { expect(images[Media.ImageSize.thumbnail]).toNot(beNil()) expect(images[Media.ImageSize.lowRes]).toNot(beNil()) expect(images[Media.ImageSize.standard]).toNot(beNil()) if let thumbnail = images[Media.ImageSize.thumbnail] { expect(thumbnail.width).to(equal(150)) expect(thumbnail.height).to(equal(150)) expect(thumbnail.url).to(equal(URL(string: "https://scontent.cdninstagram.com/t51.2885-15/s150x150/e35/c108.0.863.863/17662429_420883991615204_3921714365731962880_n.jpg" )!)) } if let lowRes = images[Media.ImageSize.lowRes] { expect(lowRes.width).to(equal(320)) expect(lowRes.height).to(equal(255)) expect(lowRes.url).to(equal(URL(string: "https://scontent.cdninstagram.com/t51.2885-15/s320x320/e35/17662429_420883991615204_3921714365731962880_n.jpg" )!)) } if let standard = images[Media.ImageSize.standard] { expect(standard.width).to(equal(640)) expect(standard.height).to(equal(511)) expect(standard.url).to(equal(URL(string: "https://scontent.cdninstagram.com/t51.2885-15/s640x640/sh0.08/e35/17662429_420883991615204_3921714365731962880_n.jpg" )!)) } } expect(media.videos).to(beNil()) expect(media.creationDate).to(equal(Date(timeIntervalSince1970: 1490893984))) if let caption = media.caption { expect(caption.ID).to(equal("17864935459119823")) expect(caption.text).to(equal("Bridge Sunsets\n.\n.\n.\n.\n.\n.\n#sunrise #chasingsunrise #skylovers #longexposure_shots #longexpo #nakedplanet #earthmagazine #ourplanetdaily #thebest_capture #natgeowild #natgeohub #awesomeearth #master_shots #skylove #instasky #yourshottphotographer #sunrise_and_sunsets #sunrise_sunsets_aroundworld #cloudlovers #cloudsofinstagram #instasunrise #sunrisesunset #cloudstagram #best_skyshots #twilightscapes #artofvisuals #theimaged #instagood #instagoodmyphoto #peoplescreatives")) expect(caption.creationDate).to(equal(Date(timeIntervalSince1970: 1490893984))) expect(caption.creator.ID).to(equal("989545")) expect(caption.creator.fullName).to(equal("Jared Verdi")) expect(caption.creator.profilePictureURL).to(equal( URL(string: "https://scontent.cdninstagram.com/t51.2885-19/11249876_446198148894593_1426023307_a.jpg") )) expect(caption.creator.username).to(equal("jverdi")) } expect(media.userHasLiked).to(equal(false)) expect(media.likesCount).to(equal(136)) expect(Set(media.tags)).to(equal(Set(["peoplescreatives", "instasky", "chasingsunrise", "instagoodmyphoto", "awesomeearth", "cloudlovers", "best_skyshots", "yourshottphotographer", "sunrise", "cloudsofinstagram", "theimaged", "nakedplanet", "earthmagazine", "natgeohub", "master_shots", "longexpo", "skylove", "ourplanetdaily", "instagood", "natgeowild", "skylovers", "artofvisuals", "thebest_capture", "twilightscapes", "longexposure_shots", "sunrise_and_sunsets", "instasunrise", "sunrisesunset", "sunrise_sunsets_aroundworld", "cloudstagram"]))) expect(media.filterName).to(equal("Ashby")) expect(media.commentCount).to(equal(10)) expect(media.type).to(equal(Media.MediaType.image)) expect(media.url).to(equal(URL(string: "https://www.instagram.com/p/BSRS104hNRP/"))) expect(media.location).to(beNil()) // expect(media.attribution).to(beNil()) expect(media.usersInPhoto).to(beEmpty()) } } } } } describe("GET my liked media") { if enableStubbing { stub(condition: isHost(GramophoneTestsHost) && isPath("/v1/users/self/media/liked") && isMethodGET()) { request in return OHHTTPStubsResponse( fileAtPath: OHPathForFile("media.json", type(of: self))!, statusCode: 200, headers: GramophoneTestsHeaders ) } } it("requires the correct scopes") { TestingUtilities.testScopes(scopes: scopes) { gramophone, completion in gramophone.client.myLikedMedia(options: nil) { completion($0) } } } it("requires authentication") { TestingUtilities.testAuthentication(scopes: scopes) { gramophone, completion in gramophone.client.myLikedMedia(options: nil) { completion($0) } } } it("parses http successful response") { TestingUtilities.testSuccessfulRequest(httpCode: 200, scopes: scopes) { gramophone, completion in gramophone.client.myLikedMedia(options: nil) { completion($0) } } } it("parses into Media objects") { TestingUtilities.testSuccessfulRequestWithDataConfirmation(httpCode: 200, scopes: scopes) { gramophone, completion in gramophone.client.myLikedMedia(options: nil) { completion($0) { media in expect(media.items.count).to(equal(3)) let media = media.items[0] expect(media.ID).to(equal("1482048616133874767_989545")) expect(media.user.ID).to(equal("989545")) expect(media.user.fullName).to(equal("Jared Verdi")) expect(media.user.profilePictureURL).to(equal( URL(string: "https://scontent.cdninstagram.com/t51.2885-19/11249876_446198148894593_1426023307_a.jpg")) ) expect(media.user.username).to(equal("jverdi")) expect(media.images).toNot(beNil()) if let images = media.images { expect(images[Media.ImageSize.thumbnail]).toNot(beNil()) expect(images[Media.ImageSize.lowRes]).toNot(beNil()) expect(images[Media.ImageSize.standard]).toNot(beNil()) if let thumbnail = images[Media.ImageSize.thumbnail] { expect(thumbnail.width).to(equal(150)) expect(thumbnail.height).to(equal(150)) expect(thumbnail.url).to(equal(URL(string: "https://scontent.cdninstagram.com/t51.2885-15/s150x150/e35/c108.0.863.863/17662429_420883991615204_3921714365731962880_n.jpg" )!)) } if let lowRes = images[Media.ImageSize.lowRes] { expect(lowRes.width).to(equal(320)) expect(lowRes.height).to(equal(255)) expect(lowRes.url).to(equal(URL(string: "https://scontent.cdninstagram.com/t51.2885-15/s320x320/e35/17662429_420883991615204_3921714365731962880_n.jpg" )!)) } if let standard = images[Media.ImageSize.standard] { expect(standard.width).to(equal(640)) expect(standard.height).to(equal(511)) expect(standard.url).to(equal(URL(string: "https://scontent.cdninstagram.com/t51.2885-15/s640x640/sh0.08/e35/17662429_420883991615204_3921714365731962880_n.jpg" )!)) } } expect(media.videos).to(beNil()) expect(media.creationDate).to(equal(Date(timeIntervalSince1970: 1490893984))) if let caption = media.caption { expect(caption.ID).to(equal("17864935459119823")) expect(caption.text).to(equal("Bridge Sunsets\n.\n.\n.\n.\n.\n.\n#sunrise #chasingsunrise #skylovers #longexposure_shots #longexpo #nakedplanet #earthmagazine #ourplanetdaily #thebest_capture #natgeowild #natgeohub #awesomeearth #master_shots #skylove #instasky #yourshottphotographer #sunrise_and_sunsets #sunrise_sunsets_aroundworld #cloudlovers #cloudsofinstagram #instasunrise #sunrisesunset #cloudstagram #best_skyshots #twilightscapes #artofvisuals #theimaged #instagood #instagoodmyphoto #peoplescreatives")) expect(caption.creationDate).to(equal(Date(timeIntervalSince1970: 1490893984))) expect(caption.creator.ID).to(equal("989545")) expect(caption.creator.fullName).to(equal("Jared Verdi")) expect(caption.creator.profilePictureURL).to(equal( URL(string: "https://scontent.cdninstagram.com/t51.2885-19/11249876_446198148894593_1426023307_a.jpg") )) expect(caption.creator.username).to(equal("jverdi")) } expect(media.userHasLiked).to(equal(false)) expect(media.likesCount).to(equal(136)) expect(Set(media.tags)).to(equal(Set(["peoplescreatives", "instasky", "chasingsunrise", "instagoodmyphoto", "awesomeearth", "cloudlovers", "best_skyshots", "yourshottphotographer", "sunrise", "cloudsofinstagram", "theimaged", "nakedplanet", "earthmagazine", "natgeohub", "master_shots", "longexpo", "skylove", "ourplanetdaily", "instagood", "natgeowild", "skylovers", "artofvisuals", "thebest_capture", "twilightscapes", "longexposure_shots", "sunrise_and_sunsets", "instasunrise", "sunrisesunset", "sunrise_sunsets_aroundworld", "cloudstagram"]))) expect(media.filterName).to(equal("Ashby")) expect(media.commentCount).to(equal(10)) expect(media.type).to(equal(Media.MediaType.image)) expect(media.url).to(equal(URL(string: "https://www.instagram.com/p/BSRS104hNRP/"))) expect(media.location).to(beNil()) // expect(media.attribution).to(beNil()) expect(media.usersInPhoto).to(beEmpty()) } } } } } describe("GET users") { let query = "jverdi" if enableStubbing { stub(condition: isHost(GramophoneTestsHost) && isPath("/v1/users/search") && isMethodGET()) { request in return OHHTTPStubsResponse( fileAtPath: OHPathForFile("users.json", type(of: self))!, statusCode: 200, headers: GramophoneTestsHeaders ) } } it("requires the correct scopes") { TestingUtilities.testScopes(scopes: scopes) { gramophone, completion in gramophone.client.users(query: query, options: nil) { completion($0) } } } it("requires authentication") { TestingUtilities.testAuthentication(scopes: scopes) { gramophone, completion in gramophone.client.users(query: query, options: nil) { completion($0) } } } it("parses http successful response") { TestingUtilities.testSuccessfulRequest(httpCode: 200, scopes: scopes) { gramophone, completion in gramophone.client.users(query: query, options: nil) { completion($0) } } } it("parses into User objects") { TestingUtilities.testSuccessfulRequestWithDataConfirmation(httpCode: 200, scopes: scopes) { gramophone, completion in gramophone.client.users(query: query, options: nil) { completion($0) { users in expect(users.items.count).to(equal(1)) let user = users.items[0] expect(user.ID).to(equal("989545")) expect(user.username).to(equal("jverdi")) expect(user.fullName).to(equal("Jared Verdi")) expect(user.profilePictureURL).to(equal( URL(string: "https://scontent.cdninstagram.com/t51.2885-19/11249876_446198148894593_1426023307_a.jpg") )) expect(user.bio).to(equal("behance mobile @ adobe 📷 sony a7r ii")) expect(user.websiteURL).to(beNil()) } } } } } } }
mit
9e238522c47cb43ba8ca1c223b4cbbee
61.659794
576
0.504541
4.845344
false
true
false
false
JacquesCarette/literate-scientific-software
code/stable/glassbr/src/swift/DerivedValues.swift
1
9405
/** DerivedValues.swift Provides the function for calculating derived values - Authors: Nikitha Krithnan and W. Spencer Smith */ import Foundation /** Calculates values that can be immediately derived from the inputs - Parameter inParams: structure holding the input values */ func derived_values(_ inParams: InputParameters) throws -> Void { var outfile: FileHandle do { outfile = try FileHandle(forWritingTo: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("log.txt")) try outfile.seekToEnd() } catch { throw "Error opening file." } do { try outfile.write(contentsOf: Data("function derived_values called with inputs: {".utf8)) try outfile.write(contentsOf: Data("\n".utf8)) } catch { throw "Error printing to file." } do { try outfile.write(contentsOf: Data(" inParams = ".utf8)) } catch { throw "Error printing to file." } do { try outfile.write(contentsOf: Data("Instance of InputParameters object".utf8)) try outfile.write(contentsOf: Data("\n".utf8)) } catch { throw "Error printing to file." } do { try outfile.write(contentsOf: Data(" }".utf8)) try outfile.write(contentsOf: Data("\n".utf8)) } catch { throw "Error printing to file." } do { try outfile.close() } catch { throw "Error closing file." } inParams.h = 1.0 / 1000.0 * (inParams.t == 2.5 ? 2.16 : inParams.t == 2.7 ? 2.59 : inParams.t == 3.0 ? 2.92 : inParams.t == 4.0 ? 3.78 : inParams.t == 5.0 ? 4.57 : inParams.t == 6.0 ? 5.56 : inParams.t == 8.0 ? 7.42 : inParams.t == 10.0 ? 9.02 : inParams.t == 12.0 ? 11.91 : inParams.t == 16.0 ? 15.09 : inParams.t == 19.0 ? 18.26 : 21.44) do { outfile = try FileHandle(forWritingTo: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("log.txt")) try outfile.seekToEnd() } catch { throw "Error opening file." } do { try outfile.write(contentsOf: Data("var 'inParams.h' assigned ".utf8)) } catch { throw "Error printing to file." } do { try outfile.write(contentsOf: Data(String(inParams.h).utf8)) } catch { throw "Error printing to file." } do { try outfile.write(contentsOf: Data(" in module DerivedValues".utf8)) try outfile.write(contentsOf: Data("\n".utf8)) } catch { throw "Error printing to file." } do { try outfile.close() } catch { throw "Error closing file." } inParams.LDF = pow(3.0 / 60.0, 7.0 / 16.0) do { outfile = try FileHandle(forWritingTo: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("log.txt")) try outfile.seekToEnd() } catch { throw "Error opening file." } do { try outfile.write(contentsOf: Data("var 'inParams.LDF' assigned ".utf8)) } catch { throw "Error printing to file." } do { try outfile.write(contentsOf: Data(String(inParams.LDF).utf8)) } catch { throw "Error printing to file." } do { try outfile.write(contentsOf: Data(" in module DerivedValues".utf8)) try outfile.write(contentsOf: Data("\n".utf8)) } catch { throw "Error printing to file." } do { try outfile.close() } catch { throw "Error closing file." } if inParams.g == "AN" { inParams.GTF = 1 do { outfile = try FileHandle(forWritingTo: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("log.txt")) try outfile.seekToEnd() } catch { throw "Error opening file." } do { try outfile.write(contentsOf: Data("var 'inParams.GTF' assigned ".utf8)) } catch { throw "Error printing to file." } do { try outfile.write(contentsOf: Data(String(inParams.GTF).utf8)) } catch { throw "Error printing to file." } do { try outfile.write(contentsOf: Data(" in module DerivedValues".utf8)) try outfile.write(contentsOf: Data("\n".utf8)) } catch { throw "Error printing to file." } do { try outfile.close() } catch { throw "Error closing file." } } else if inParams.g == "FT" { inParams.GTF = 4 do { outfile = try FileHandle(forWritingTo: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("log.txt")) try outfile.seekToEnd() } catch { throw "Error opening file." } do { try outfile.write(contentsOf: Data("var 'inParams.GTF' assigned ".utf8)) } catch { throw "Error printing to file." } do { try outfile.write(contentsOf: Data(String(inParams.GTF).utf8)) } catch { throw "Error printing to file." } do { try outfile.write(contentsOf: Data(" in module DerivedValues".utf8)) try outfile.write(contentsOf: Data("\n".utf8)) } catch { throw "Error printing to file." } do { try outfile.close() } catch { throw "Error closing file." } } else if inParams.g == "HS" { inParams.GTF = 2 do { outfile = try FileHandle(forWritingTo: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("log.txt")) try outfile.seekToEnd() } catch { throw "Error opening file." } do { try outfile.write(contentsOf: Data("var 'inParams.GTF' assigned ".utf8)) } catch { throw "Error printing to file." } do { try outfile.write(contentsOf: Data(String(inParams.GTF).utf8)) } catch { throw "Error printing to file." } do { try outfile.write(contentsOf: Data(" in module DerivedValues".utf8)) try outfile.write(contentsOf: Data("\n".utf8)) } catch { throw "Error printing to file." } do { try outfile.close() } catch { throw "Error closing file." } } else { throw "Undefined case encountered in function GTF" } inParams.SD = sqrt(pow(inParams.SD_x, 2.0) + pow(inParams.SD_y, 2.0) + pow(inParams.SD_z, 2.0)) do { outfile = try FileHandle(forWritingTo: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("log.txt")) try outfile.seekToEnd() } catch { throw "Error opening file." } do { try outfile.write(contentsOf: Data("var 'inParams.SD' assigned ".utf8)) } catch { throw "Error printing to file." } do { try outfile.write(contentsOf: Data(String(inParams.SD).utf8)) } catch { throw "Error printing to file." } do { try outfile.write(contentsOf: Data(" in module DerivedValues".utf8)) try outfile.write(contentsOf: Data("\n".utf8)) } catch { throw "Error printing to file." } do { try outfile.close() } catch { throw "Error closing file." } inParams.AR = inParams.a / inParams.b do { outfile = try FileHandle(forWritingTo: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("log.txt")) try outfile.seekToEnd() } catch { throw "Error opening file." } do { try outfile.write(contentsOf: Data("var 'inParams.AR' assigned ".utf8)) } catch { throw "Error printing to file." } do { try outfile.write(contentsOf: Data(String(inParams.AR).utf8)) } catch { throw "Error printing to file." } do { try outfile.write(contentsOf: Data(" in module DerivedValues".utf8)) try outfile.write(contentsOf: Data("\n".utf8)) } catch { throw "Error printing to file." } do { try outfile.close() } catch { throw "Error closing file." } inParams.w_TNT = inParams.w * inParams.TNT do { outfile = try FileHandle(forWritingTo: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("log.txt")) try outfile.seekToEnd() } catch { throw "Error opening file." } do { try outfile.write(contentsOf: Data("var 'inParams.w_TNT' assigned ".utf8)) } catch { throw "Error printing to file." } do { try outfile.write(contentsOf: Data(String(inParams.w_TNT).utf8)) } catch { throw "Error printing to file." } do { try outfile.write(contentsOf: Data(" in module DerivedValues".utf8)) try outfile.write(contentsOf: Data("\n".utf8)) } catch { throw "Error printing to file." } do { try outfile.close() } catch { throw "Error closing file." } }
bsd-2-clause
7d7af01d64f08d985e87f7c1cac0bd03
32
343
0.572036
4.082031
false
false
false
false
lanjing99/RxSwiftDemo
24-building-complete-rxswift-app/starter/QuickTodo/QuickTodo/Services/TaskService.swift
1
3697
/* * Copyright (c) 2016 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import Foundation import RealmSwift import RxSwift import RxRealm struct TaskService { init() { // create a few default tasks do { let realm = try Realm() if realm.objects(TaskItem.self).count == 0 { ["Chapter 5: Filtering operators", "Chapter 4: Observables and Subjects in practice", "Chapter 3: Subjects", "Chapter 2: Observables", "Chapter 1: Hello, RxSwift"].forEach { self.createTask(title: $0) } } } catch _ { } } fileprivate func withRealm<T>(_ operation: String, action: (Realm) throws -> T) -> T? { do { let realm = try Realm() return try action(realm) } catch let err { print("Failed \(operation) realm with error: \(err)") return nil } } @discardableResult func createTask(title: String) -> Observable<TaskItem> { let result = withRealm("creating") { realm -> Observable<TaskItem> in let task = TaskItem() task.title = title try realm.write { task.uid = (realm.objects(TaskItem.self).max(ofProperty: "uid") ?? 0) + 1 realm.add(task) } return .just(task) } return result ?? .error(TaskServiceError.creationFailed) } @discardableResult func delete(task: TaskItem) -> Observable<Void> { let result = withRealm("deleting") { realm-> Observable<Void> in try realm.write { realm.delete(task) } return .empty() } return result ?? .error(TaskServiceError.deletionFailed(task)) } @discardableResult func update(task: TaskItem, title: String) -> Observable<TaskItem> { let result = withRealm("updating title") { realm -> Observable<TaskItem> in try realm.write { task.title = title } return .just(task) } return result ?? .error(TaskServiceError.updateFailed(task)) } @discardableResult func toggle(task: TaskItem) -> Observable<TaskItem> { let result = withRealm("toggling") { realm -> Observable<TaskItem> in try realm.write { if task.checked == nil { task.checked = Date() } else { task.checked = nil } } return .just(task) } return result ?? .error(TaskServiceError.toggleFailed(task)) } func tasks() -> Observable<Results<TaskItem>> { let result = withRealm("getting tasks") { realm -> Observable<Results<TaskItem>> in let realm = try Realm() let tasks = realm.objects(TaskItem.self) return Observable.collection(from: tasks) } return result ?? .empty() } }
mit
ea78116cb73a6350ec45bdc0acdda8c4
30.87069
89
0.653773
4.201136
false
false
false
false
djwbrown/swift
test/SILGen/constrained_extensions.swift
2
14523
// RUN: %target-swift-frontend -emit-silgen -primary-file %s | %FileCheck %s // RUN: %target-swift-frontend -emit-sil -O -primary-file %s > /dev/null // RUN: %target-swift-frontend -emit-ir -primary-file %s > /dev/null extension Array where Element == Int { // CHECK-LABEL: sil @_T0Sa22constrained_extensionsSiRszlESaySiGyt1x_tcfC : $@convention(method) (@thin Array<Int>.Type) -> @owned Array<Int> public init(x: ()) { self.init() } // CHECK-LABEL: sil @_T0Sa22constrained_extensionsSiRszlE16instancePropertySifg : $@convention(method) (@guaranteed Array<Int>) -> Int // CHECK-LABEL: sil @_T0Sa22constrained_extensionsSiRszlE16instancePropertySifs : $@convention(method) (Int, @inout Array<Int>) -> () // CHECK-LABEL: sil private [transparent] [serialized] @_T0Sa22constrained_extensionsSiRszlE16instancePropertySifmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Array<Int>, @thick Array<Int>.Type) -> () // CHECK-LABEL: sil [transparent] [serialized] @_T0Sa22constrained_extensionsSiRszlE16instancePropertySifm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Array<Int>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) public var instanceProperty: Element { get { return self[0] } set { self[0] = newValue } } // CHECK-LABEL: sil @_T0Sa22constrained_extensionsSiRszlE14instanceMethodSiyF : $@convention(method) (@guaranteed Array<Int>) -> Int public func instanceMethod() -> Element { return instanceProperty } // CHECK-LABEL: sil @_T0Sa22constrained_extensionsSiRszlE14instanceMethodS2i1e_tF : $@convention(method) (Int, @guaranteed Array<Int>) -> Int public func instanceMethod(e: Element) -> Element { return e } // CHECK-LABEL: sil @_T0Sa22constrained_extensionsSiRszlE14staticPropertySifgZ : $@convention(method) (@thin Array<Int>.Type) -> Int public static var staticProperty: Element { return Array(x: ()).instanceProperty } // CHECK-LABEL: sil @_T0Sa22constrained_extensionsSiRszlE12staticMethodSiyFZ : $@convention(method) (@thin Array<Int>.Type) -> Int public static func staticMethod() -> Element { return staticProperty } // CHECK-LABEL: sil @_T0Sa22constrained_extensionsSiRszlE12staticMethodS2iSg1e_tFZfA_ : $@convention(thin) () -> Optional<Int> // CHECK-LABEL: sil @_T0Sa22constrained_extensionsSiRszlE12staticMethodS2iSg1e_tFZ : $@convention(method) (Optional<Int>, @thin Array<Int>.Type) -> Int public static func staticMethod(e: Element? = nil) -> Element { return e! } // CHECK-LABEL: sil @_T0Sa22constrained_extensionsSiRszlE9subscriptSiyt_tcfg : $@convention(method) (@guaranteed Array<Int>) -> Int public subscript(i: ()) -> Element { return self[0] } // CHECK-LABEL: sil @_T0Sa22constrained_extensionsSiRszlE21inoutAccessOfPropertyyyF : $@convention(method) (@inout Array<Int>) -> () public mutating func inoutAccessOfProperty() { func increment(x: inout Element) { x += 1 } increment(x: &instanceProperty) } } extension Dictionary where Key == Int { // CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszr0_lEABySiq_Gyt1x_tcfC : $@convention(method) <Key, Value where Key == Int> (@thin Dictionary<Int, Value>.Type) -> @owned Dictionary<Int, Value> { public init(x: ()) { self.init() } // CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszr0_lE16instancePropertyq_fg : $@convention(method) <Key, Value where Key == Int> (@guaranteed Dictionary<Int, Value>) -> @out Value // CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszr0_lE16instancePropertyq_fs : $@convention(method) <Key, Value where Key == Int> (@in Value, @inout Dictionary<Int, Value>) -> () // CHECK-LABEL: sil private [transparent] [serialized] @_T0s10DictionaryV22constrained_extensionsSiRszr0_lE16instancePropertyq_fmytfU_ : $@convention(method) <Key, Value where Key == Int> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Dictionary<Int, Value>, @thick Dictionary<Int, Value>.Type) -> () // CHECK-LABEL: sil [transparent] [serialized] @_T0s10DictionaryV22constrained_extensionsSiRszr0_lE16instancePropertyq_fm : $@convention(method) <Key, Value where Key == Int> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Dictionary<Int, Value>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) public var instanceProperty: Value { get { return self[0]! } set { self[0] = newValue } } // CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszr0_lE14instanceMethodq_yF : $@convention(method) <Key, Value where Key == Int> (@guaranteed Dictionary<Int, Value>) -> @out Value public func instanceMethod() -> Value { return instanceProperty } // CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszr0_lE14instanceMethodq_q_1v_tF : $@convention(method) <Key, Value where Key == Int> (@in Value, @guaranteed Dictionary<Int, Value>) -> @out Value public func instanceMethod(v: Value) -> Value { return v } // CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszr0_lE12staticMethodSiyFZ : $@convention(method) <Key, Value where Key == Int> (@thin Dictionary<Int, Value>.Type) -> Int public static func staticMethod() -> Key { return staticProperty } // CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszr0_lE14staticPropertySifgZ : $@convention(method) <Key, Value where Key == Int> (@thin Dictionary<Int, Value>.Type) -> Int public static var staticProperty: Key { return 0 } // CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszr0_lE12staticMethodq_SiSg1k_q_Sg1vtFZfA_ : $@convention(thin) <Key, Value where Key == Int> () -> Optional<Int> // CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszr0_lE12staticMethodq_SiSg1k_q_Sg1vtFZfA0_ : $@convention(thin) <Key, Value where Key == Int> () -> @out Optional<Value> // CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszr0_lE12staticMethodq_SiSg1k_q_Sg1vtFZ : $@convention(method) <Key, Value where Key == Int> (Optional<Int>, @in Optional<Value>, @thin Dictionary<Int, Value>.Type) -> @out Value public static func staticMethod(k: Key? = nil, v: Value? = nil) -> Value { return v! } // CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszr0_lE17callsStaticMethodq_yFZ : $@convention(method) <Key, Value where Key == Int> (@thin Dictionary<Int, Value>.Type) -> @out Value public static func callsStaticMethod() -> Value { return staticMethod() } // CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszr0_lE16callsConstructorq_yFZ : $@convention(method) <Key, Value where Key == Int> (@thin Dictionary<Int, Value>.Type) -> @out Value public static func callsConstructor() -> Value { return Dictionary(x: ()).instanceMethod() } // CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszr0_lE9subscriptq_yt_tcfg : $@convention(method) <Key, Value where Key == Int> (@guaranteed Dictionary<Int, Value>) -> @out Value public subscript(i: ()) -> Value { return self[0]! } // CHECK-LABEL: sil @_T0s10DictionaryV22constrained_extensionsSiRszr0_lE21inoutAccessOfPropertyyyF : $@convention(method) <Key, Value where Key == Int> (@inout Dictionary<Int, Value>) -> () public mutating func inoutAccessOfProperty() { func increment(x: inout Value) { } increment(x: &instanceProperty) } } public class GenericClass<X, Y> {} extension GenericClass where Y == () { // CHECK-LABEL: sil @_T022constrained_extensions12GenericClassCAAytRs_r0_lE5valuexfg : $@convention(method) <X, Y where Y == ()> (@guaranteed GenericClass<X, ()>) -> @out X // CHECK-LABEL: sil @_T022constrained_extensions12GenericClassCAAytRs_r0_lE5valuexfs : $@convention(method) <X, Y where Y == ()> (@in X, @guaranteed GenericClass<X, ()>) -> () // CHECK-LABEL: sil private [transparent] [serialized] @_T022constrained_extensions12GenericClassCAAytRs_r0_lE5valuexfmytfU_ : $@convention(method) <X, Y where Y == ()> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout GenericClass<X, ()>, @thick GenericClass<X, ()>.Type) -> () // CHECK-LABEL: sil [transparent] [serialized] @_T022constrained_extensions12GenericClassCAAytRs_r0_lE5valuexfm : $@convention(method) <X, Y where Y == ()> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed GenericClass<X, ()>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) public var value: X { get { while true {} } set {} } // CHECK-LABEL: sil @_T022constrained_extensions12GenericClassCAAytRs_r0_lE5emptyytfg : $@convention(method) <X, Y where Y == ()> (@guaranteed GenericClass<X, ()>) -> () // CHECK-LABEL: sil @_T022constrained_extensions12GenericClassCAAytRs_r0_lE5emptyytfs : $@convention(method) <X, Y where Y == ()> (@guaranteed GenericClass<X, ()>) -> () // CHECK-LABEL: sil private [transparent] [serialized] @_T022constrained_extensions12GenericClassCAAytRs_r0_lE5emptyytfmytfU_ : $@convention(method) <X, Y where Y == ()> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout GenericClass<X, ()>, @thick GenericClass<X, ()>.Type) -> () // CHECK-LABEL: sil [transparent] [serialized] @_T022constrained_extensions12GenericClassCAAytRs_r0_lE5emptyytfm : $@convention(method) <X, Y where Y == ()> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed GenericClass<X, ()>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) public var empty: Y { get { return () } set {} } // CHECK-LABEL: sil @_T022constrained_extensions12GenericClassCAAytRs_r0_lE9subscriptxyt_tcfg : $@convention(method) <X, Y where Y == ()> (@guaranteed GenericClass<X, ()>) -> @out X // CHECK-LABEL: sil @_T022constrained_extensions12GenericClassCAAytRs_r0_lE9subscriptxyt_tcfs : $@convention(method) <X, Y where Y == ()> (@in X, @guaranteed GenericClass<X, ()>) -> () // CHECK-LABEL: sil private [transparent] [serialized] @_T022constrained_extensions12GenericClassCAAytRs_r0_lE9subscriptxyt_tcfmytfU_ : $@convention(method) <X, Y where Y == ()> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout GenericClass<X, ()>, @thick GenericClass<X, ()>.Type) -> () // CHECK-LABEL: sil [transparent] [serialized] @_T022constrained_extensions12GenericClassCAAytRs_r0_lE9subscriptxyt_tcfm : $@convention(method) <X, Y where Y == ()> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed GenericClass<X, ()>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) public subscript(_: Y) -> X { get { while true {} } set {} } // CHECK-LABEL: sil @_T022constrained_extensions12GenericClassCAAytRs_r0_lE9subscriptyxcfg : $@convention(method) <X, Y where Y == ()> (@in X, @guaranteed GenericClass<X, ()>) -> () // CHECK-LABEL: sil @_T022constrained_extensions12GenericClassCAAytRs_r0_lE9subscriptyxcfs : $@convention(method) <X, Y where Y == ()> (@in X, @guaranteed GenericClass<X, ()>) -> () // CHECK-LABEL: sil private [transparent] [serialized] @_T022constrained_extensions12GenericClassCAAytRs_r0_lE9subscriptyxcfmytfU_ : $@convention(method) <X, Y where Y == ()> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout GenericClass<X, ()>, @thick GenericClass<X, ()>.Type) -> () // CHECK-LABEL: sil [transparent] [serialized] @_T022constrained_extensions12GenericClassCAAytRs_r0_lE9subscriptyxcfm : $@convention(method) <X, Y where Y == ()> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in X, @guaranteed GenericClass<X, ()>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) public subscript(_: X) -> Y { get { while true {} } set {} } } protocol VeryConstrained {} struct AnythingGoes<T> { // CHECK-LABEL: sil hidden [transparent] @_T022constrained_extensions12AnythingGoesV13meaningOfLifexSgvfi : $@convention(thin) <T> () -> @out Optional<T> var meaningOfLife: T? = nil } extension AnythingGoes where T : VeryConstrained { // CHECK-LABEL: sil hidden @_T022constrained_extensions12AnythingGoesVA2A15VeryConstrainedRzlEACyxGyt13fromExtension_tcfC : $@convention(method) <T where T : VeryConstrained> (@thin AnythingGoes<T>.Type) -> @out AnythingGoes<T> { // CHECK: [[INIT:%.*]] = function_ref @_T022constrained_extensions12AnythingGoesV13meaningOfLifexSgvfi : $@convention(thin) <τ_0_0> () -> @out Optional<τ_0_0> // CHECK: [[RESULT:%.*]] = alloc_stack $Optional<T> // CHECK: apply [[INIT]]<T>([[RESULT]]) : $@convention(thin) <τ_0_0> () -> @out Optional<τ_0_0> // CHECK: return init(fromExtension: ()) {} } extension Array where Element == Int { struct Nested { // CHECK-LABEL: sil hidden [transparent] @_T0Sa22constrained_extensionsSiRszlE6NestedV1eSiSgvfi : $@convention(thin) () -> Optional<Int> var e: Element? = nil // CHECK-LABEL: sil hidden @_T0Sa22constrained_extensionsSiRszlE6NestedV10hasDefaultySiSg1e_tFfA_ : $@convention(thin) () -> Optional<Int> // CHECK-LABEL: sil hidden @_T0Sa22constrained_extensionsSiRszlE6NestedV10hasDefaultySiSg1e_tF : $@convention(method) (Optional<Int>, @inout Array<Int>.Nested) -> () mutating func hasDefault(e: Element? = nil) { self.e = e } } } extension Array where Element == AnyObject { class NestedClass { // CHECK-LABEL: sil hidden @_T0Sa22constrained_extensionsyXlRszlE11NestedClassCfd : $@convention(method) (@guaranteed Array<AnyObject>.NestedClass) -> @owned Builtin.NativeObject // CHECK-LABEL: sil hidden @_T0Sa22constrained_extensionsyXlRszlE11NestedClassCfD : $@convention(method) (@owned Array<AnyObject>.NestedClass) -> () deinit { } // CHECK-LABEL: sil hidden @_T0Sa22constrained_extensionsyXlRszlE11NestedClassCACyyXl_GycfC : $@convention(method) (@thick Array<AnyObject>.NestedClass.Type) -> @owned Array<AnyObject>.NestedClass // CHECK-LABEL: sil hidden @_T0Sa22constrained_extensionsyXlRszlE11NestedClassCACyyXl_Gycfc : $@convention(method) (@owned Array<AnyObject>.NestedClass) -> @owned Array<AnyObject>.NestedClass } class DerivedClass : NestedClass { // CHECK-LABEL: sil hidden [transparent] @_T0Sa22constrained_extensionsyXlRszlE12DerivedClassC1eyXlSgvfi : $@convention(thin) () -> @owned Optional<AnyObject> // CHECK-LABEL: sil hidden @_T0Sa22constrained_extensionsyXlRszlE12DerivedClassCfE : $@convention(method) (@guaranteed Array<AnyObject>.DerivedClass) -> () var e: Element? = nil } } func referenceNestedTypes() { _ = Array<AnyObject>.NestedClass() _ = Array<AnyObject>.DerivedClass() }
apache-2.0
9147d751cf5c050c2c3551f2aa0d3b45
63.528889
317
0.720298
3.812763
false
false
false
false
xedin/swift
test/SILOptimizer/access_enforcement_noescape.swift
21
21457
// RUN: %target-swift-frontend -module-name access_enforcement_noescape -enforce-exclusivity=checked -Onone -emit-sil -swift-version 4 -parse-as-library %s | %FileCheck %s // This tests SILGen and AccessEnforcementSelection as a single set of tests. // (Some static/dynamic enforcement selection is done in SILGen, and some is // deferred. That may change over time but we want the outcome to be the same). // // These tests attempt to fully cover the possibilities of reads and // modifications to captures along with `inout` arguments on both the caller and // callee side. // // Tests that result in a compile-time error have been commented out // here so we can FileCheck this output. Instead, copies of these // tests are compiled access_enforcement_noescape_error.swift to check // the compiler diagnostics. // Helper func doOne(_ f: () -> ()) { f() } // Helper func doTwo(_: ()->(), _: ()->()) {} // Helper func doOneInout(_: ()->(), _: inout Int) {} // Error: Cannot capture nonescaping closure. // This triggers an early diagnostics, so it's handled in inout_capture_disgnostics.swift. // func reentrantCapturedNoescape(fn: (() -> ()) -> ()) { // let c = { fn {} } // fn(c) // } // Helper struct Frob { mutating func outerMut() { doOne { innerMut() } } mutating func innerMut() {} } // Allow nested mutable access via closures. func nestedNoEscape(f: inout Frob) { doOne { f.outerMut() } } // CHECK-LABEL: sil hidden @$s27access_enforcement_noescape14nestedNoEscape1fyAA4FrobVz_tF : $@convention(thin) (@inout Frob) -> () { // CHECK-NOT: begin_access // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape14nestedNoEscape1fyAA4FrobVz_tF' // closure #1 in nestedNoEscape(f:) // CHECK-LABEL: sil private @$s27access_enforcement_noescape14nestedNoEscape1fyAA4FrobVz_tFyyXEfU_ : $@convention(thin) (@inout_aliasable Frob) -> () { // CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Frob // CHECK: %{{.*}} = apply %{{.*}}([[ACCESS]]) : $@convention(method) (@inout Frob) -> () // CHECK: end_access [[ACCESS]] : $*Frob // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape14nestedNoEscape1fyAA4FrobVz_tFyyXEfU_' // Allow aliased noescape reads. func readRead() { var x = 3 // Inside each closure: [read] [static] doTwo({ _ = x }, { _ = x }) x = 42 } // CHECK-LABEL: sil hidden @$s27access_enforcement_noescape8readReadyyF : $@convention(thin) () -> () { // CHECK: [[ALLOC:%.*]] = alloc_stack $Int, var, name "x" // CHECK-NOT: begin_access // CHECK: apply // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape8readReadyyF' // closure #1 in readRead() // CHECK-LABEL: sil private @$s27access_enforcement_noescape8readReadyyFyyXEfU_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK-NOT: begin_access [read] [dynamic] // CHECK: [[ACCESS:%.*]] = begin_access [read] [static] %0 : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape8readReadyyFyyXEfU_' // closure #2 in readRead() // CHECK-LABEL: sil private @$s27access_enforcement_noescape8readReadyyFyyXEfU0_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK-NOT: begin_access [read] [dynamic] // CHECK: [[ACCESS:%.*]] = begin_access [read] [static] %0 : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape8readReadyyFyyXEfU0_' // Allow aliased noescape reads of an `inout` arg. func inoutReadRead(x: inout Int) { // Inside each closure: [read] [static] doTwo({ _ = x }, { _ = x }) } // CHECK-LABEL: sil hidden @$s27access_enforcement_noescape09inoutReadE01xySiz_tF : $@convention(thin) (@inout Int) -> () { // CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed] [on_stack] // CHECK: [[PA2:%.*]] = partial_apply [callee_guaranteed] [on_stack] // CHECK-NOT: begin_access // CHECK: apply %{{.*}}([[PA1]], [[PA2]]) // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape09inoutReadE01xySiz_tF' // closure #1 in inoutReadRead(x:) // CHECK-LABEL: sil private @$s27access_enforcement_noescape09inoutReadE01xySiz_tFyyXEfU_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK-NOT: begin_access [read] [dynamic] // CHECK: [[ACCESS:%.*]] = begin_access [read] [static] %0 : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape09inoutReadE01xySiz_tFyyXEfU_' // closure #2 in inoutReadRead(x:) // CHECK-LABEL: sil private @$s27access_enforcement_noescape09inoutReadE01xySiz_tFyyXEfU0_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK-NOT: begin_access [read] [dynamic] // CHECK: [[ACCESS:%.*]] = begin_access [read] [static] %0 : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape09inoutReadE01xySiz_tFyyXEfU0_' // Allow aliased noescape read + boxed read. func readBoxRead() { var x = 3 let c = { _ = x } // Inside may-escape closure `c`: [read] [dynamic] // Inside never-escape closure: [read] [dynamic] doTwo(c, { _ = x }) x = 42 } // CHECK-LABEL: sil hidden @$s27access_enforcement_noescape11readBoxReadyyF : $@convention(thin) () -> () { // CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed] // CHECK: [[CVT1:%.*]] = convert_escape_to_noescape [[PA1]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> () // CHECK: [[PA2:%.*]] = partial_apply [callee_guaranteed] [on_stack] // CHECK-NOT: begin_access // CHECK: apply %{{.*}}([[CVT1]], [[PA2]]) // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape11readBoxReadyyF' // closure #1 in readBoxRead() // CHECK-LABEL: sil private @$s27access_enforcement_noescape11readBoxReadyyFyycfU_ : $@convention(thin) (@guaranteed { var Int }) -> () { // CHECK: [[ADDR:%.*]] = project_box %0 : ${ var Int }, 0 // CHECK: [[ACCESS:%.*]] = begin_access [read] [dynamic] [[ADDR]] : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape11readBoxReadyyFyycfU_' // closure #2 in readBoxRead() // CHECK-LABEL: sil private @$s27access_enforcement_noescape11readBoxReadyyFyyXEfU0_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK: [[ACCESS:%.*]] = begin_access [read] [dynamic] %0 : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape11readBoxReadyyFyyXEfU0_' // Error: cannout capture inout. // // func inoutReadReadBox(x: inout Int) { // let c = { _ = x } // doTwo({ _ = x }, c) // } // Allow aliased noescape read + write. func readWrite() { var x = 3 // Inside closure 1: [read] [static] // Inside closure 2: [modify] [static] doTwo({ _ = x }, { x = 42 }) } // CHECK-LABEL: sil hidden @$s27access_enforcement_noescape9readWriteyyF : $@convention(thin) () -> () { // CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed] [on_stack] // CHECK: [[PA2:%.*]] = partial_apply [callee_guaranteed] [on_stack] // CHECK-NOT: begin_access // CHECK: apply %{{.*}}([[PA1]], [[PA2]]) // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape9readWriteyyF' // closure #1 in readWrite() // CHECK-LABEL: sil private @$s27access_enforcement_noescape9readWriteyyFyyXEfU_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK-NOT: [[ACCESS:%.*]] = begin_access [read] [dynamic] // CHECK: [[ACCESS:%.*]] = begin_access [read] [static] %0 : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape9readWriteyyFyyXEfU_' // closure #2 in readWrite() // CHECK-LABEL: sil private @$s27access_enforcement_noescape9readWriteyyFyyXEfU0_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK-NOT: [[ACCESS:%.*]] = begin_access [modify] [dynamic] // CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape9readWriteyyFyyXEfU0_' // Allow aliased noescape read + write of an `inout` arg. func inoutReadWrite(x: inout Int) { // Inside closure 1: [read] [static] // Inside closure 2: [modify] [static] // Compile time error: see access_enforcement_noescape_error.swift. // doTwo({ _ = x }, { x = 3 }) } // CHECK-LABEL: sil hidden @$s27access_enforcement_noescape14inoutReadWrite1xySiz_tF : $@convention(thin) (@inout Int) -> () { func readBoxWrite() { var x = 3 let c = { _ = x } // Inside may-escape closure `c`: [read] [dynamic] // Inside never-escape closure: [modify] [dynamic] doTwo(c, { x = 42 }) } // CHECK-LABEL: sil hidden @$s27access_enforcement_noescape12readBoxWriteyyF : $@convention(thin) () -> () { // CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed] // CHECK: [[CVT1:%.*]] = convert_escape_to_noescape [[PA1]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> () // CHECK: [[PA2:%.*]] = partial_apply [callee_guaranteed] [on_stack] // CHECK-NOT: begin_access // CHECK: apply %{{.*}}([[CVT1]], [[PA2]]) // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape12readBoxWriteyyF' // closure #1 in readBoxWrite() // CHECK-LABEL: sil private @$s27access_enforcement_noescape12readBoxWriteyyFyycfU_ : $@convention(thin) (@guaranteed { var Int }) -> () { // CHECK: [[ADDR:%.*]] = project_box %0 : ${ var Int }, 0 // CHECK: [[ACCESS:%.*]] = begin_access [read] [dynamic] [[ADDR]] : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape12readBoxWriteyyFyycfU_' // closure #2 in readBoxWrite() // CHECK-LABEL: sil private @$s27access_enforcement_noescape12readBoxWriteyyFyyXEfU0_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] %0 : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape12readBoxWriteyyFyyXEfU0_' // Error: cannout capture inout. // func inoutReadBoxWrite(x: inout Int) { // let c = { _ = x } // doTwo({ x = 42 }, c) // } func readWriteBox() { var x = 3 let c = { x = 42 } // Inside may-escape closure `c`: [modify] [dynamic] // Inside never-escape closure: [read] [dynamic] doTwo({ _ = x }, c) } // CHECK-LABEL: sil hidden @$s27access_enforcement_noescape12readWriteBoxyyF : $@convention(thin) () -> () { // CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed] // CHECK: [[PA2:%.*]] = partial_apply [callee_guaranteed] [on_stack] // CHECK: [[CVT1:%.*]] = convert_escape_to_noescape [[PA1]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> () // CHECK-NOT: begin_access // CHECK: apply %{{.*}}([[PA2]], [[CVT1]]) // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape12readWriteBoxyyF' // closure #1 in readWriteBox() // CHECK-LABEL: sil private @$s27access_enforcement_noescape12readWriteBoxyyFyycfU_ : $@convention(thin) (@guaranteed { var Int }) -> () { // CHECK: [[ADDR:%.*]] = project_box %0 : ${ var Int }, 0 // CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[ADDR]] : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape12readWriteBoxyyFyycfU_' // closure #2 in readWriteBox() // CHECK-LABEL: sil private @$s27access_enforcement_noescape12readWriteBoxyyFyyXEfU0_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK: [[ACCESS:%.*]] = begin_access [read] [dynamic] %0 : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape12readWriteBoxyyFyyXEfU0_' // Error: cannout capture inout. // func inoutReadWriteBox(x: inout Int) { // let c = { x = 42 } // doTwo({ _ = x }, c) // } // Error: noescape read + write inout. func readWriteInout() { var x = 3 // Around the call: [modify] [static] // Inside closure: [modify] [static] // Compile time error: see access_enforcement_noescape_error.swift. // doOneInout({ _ = x }, &x) } // CHECK-LABEL: sil hidden @$s27access_enforcement_noescape14readWriteInoutyyF : $@convention(thin) () -> () { // Error: noescape read + write inout of an inout. func inoutReadWriteInout(x: inout Int) { // Around the call: [modify] [static] // Inside closure: [modify] [static] // Compile time error: see access_enforcement_noescape_error.swift. // doOneInout({ _ = x }, &x) } // CHECK-LABEL: sil hidden @$s27access_enforcement_noescape19inoutReadWriteInout1xySiz_tF : $@convention(thin) (@inout Int) -> () { // Traps on boxed read + write inout. // Covered by Interpreter/enforce_exclusive_access.swift. func readBoxWriteInout() { var x = 3 let c = { _ = x } // Around the call: [modify] [dynamic] // Inside closure: [read] [dynamic] doOneInout(c, &x) } // CHECK-LABEL: sil hidden @$s27access_enforcement_noescape17readBoxWriteInoutyyF : $@convention(thin) () -> () { // CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed] // CHECK: [[CVT:%.*]] = convert_escape_to_noescape [[PA1]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> () // CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] %1 : $*Int // CHECK: apply %{{.*}}([[CVT]], [[ACCESS]]) // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape17readBoxWriteInoutyyF' // closure #1 in readBoxWriteInout() // CHECK-LABEL: sil private @$s27access_enforcement_noescape17readBoxWriteInoutyyFyycfU_ : $@convention(thin) (@guaranteed { var Int }) -> () { // CHECK: [[ADDR:%.*]] = project_box %0 : ${ var Int }, 0 // CHECK: [[ACCESS:%.*]] = begin_access [read] [dynamic] [[ADDR]] : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape17readBoxWriteInoutyyFyycfU_' // Error: inout cannot be captured. // This triggers an early diagnostics, so it's handled in inout_capture_disgnostics.swift. // func inoutReadBoxWriteInout(x: inout Int) { // let c = { _ = x } // doOneInout(c, &x) // } // Allow aliased noescape write + write. func writeWrite() { var x = 3 // Inside closure 1: [modify] [static] // Inside closure 2: [modify] [static] doTwo({ x = 42 }, { x = 87 }) _ = x } // CHECK-LABEL: sil hidden @$s27access_enforcement_noescape10writeWriteyyF : $@convention(thin) () -> () { // CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed] [on_stack] // CHECK: [[PA2:%.*]] = partial_apply [callee_guaranteed] [on_stack] // CHECK-NOT: begin_access // CHECK: apply %{{.*}}([[PA1]], [[PA2]]) // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape10writeWriteyyF' // closure #1 in writeWrite() // CHECK-LABEL: sil private @$s27access_enforcement_noescape10writeWriteyyFyyXEfU_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape10writeWriteyyFyyXEfU_' // closure #2 in writeWrite() // CHECK-LABEL: sil private @$s27access_enforcement_noescape10writeWriteyyFyyXEfU0_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape10writeWriteyyFyyXEfU0_' // Allow aliased noescape write + write of an `inout` arg. func inoutWriteWrite(x: inout Int) { // Inside closure 1: [modify] [static] // Inside closure 2: [modify] [static] doTwo({ x = 42}, { x = 87 }) } // CHECK-LABEL: sil hidden @$s27access_enforcement_noescape010inoutWriteE01xySiz_tF : $@convention(thin) (@inout Int) -> () { // CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed] [on_stack] // CHECK: [[PA2:%.*]] = partial_apply [callee_guaranteed] [on_stack] // CHECK-NOT: begin_access // CHECK: apply %{{.*}}([[PA1]], [[PA2]]) // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape010inoutWriteE01xySiz_tF' // closure #1 in inoutWriteWrite(x:) // CHECK-LABEL: sil private @$s27access_enforcement_noescape010inoutWriteE01xySiz_tFyyXEfU_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape010inoutWriteE01xySiz_tFyyXEfU_' // closure #2 in inoutWriteWrite(x:) // CHECK-LABEL: sil private @$s27access_enforcement_noescape010inoutWriteE01xySiz_tFyyXEfU0_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape010inoutWriteE01xySiz_tFyyXEfU0_' // Traps on aliased boxed write + noescape write. // Covered by Interpreter/enforce_exclusive_access.swift. func writeWriteBox() { var x = 3 let c = { x = 87 } // Inside may-escape closure `c`: [modify] [dynamic] // Inside never-escape closure: [modify] [dynamic] doTwo({ x = 42 }, c) _ = x } // CHECK-LABEL: sil hidden @$s27access_enforcement_noescape13writeWriteBoxyyF : $@convention(thin) () -> () { // CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed] // CHECK: [[PA2:%.*]] = partial_apply [callee_guaranteed] [on_stack] // CHECK: [[CVT1:%.*]] = convert_escape_to_noescape [[PA1]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> () // CHECK-NOT: begin_access // CHECK: apply %{{.*}}([[PA2]], [[CVT1]]) // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape13writeWriteBoxyyF' // closure #1 in writeWriteBox() // CHECK-LABEL: sil private @$s27access_enforcement_noescape13writeWriteBoxyyFyycfU_ : $@convention(thin) (@guaranteed { var Int }) -> () { // CHECK: [[ADDR:%.*]] = project_box %0 : ${ var Int }, 0 // CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[ADDR]] : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape13writeWriteBoxyyFyycfU_' // closure #2 in writeWriteBox() // CHECK-LABEL: sil private @$s27access_enforcement_noescape13writeWriteBoxyyFyyXEfU0_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] %0 : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape13writeWriteBoxyyFyyXEfU0_' // Error: inout cannot be captured. // func inoutWriteWriteBox(x: inout Int) { // let c = { x = 87 } // doTwo({ x = 42 }, c) // } // Error: on noescape write + write inout. func writeWriteInout() { var x = 3 // Around the call: [modify] [static] // Inside closure: [modify] [static] // Compile time error: see access_enforcement_noescape_error.swift. // doOneInout({ x = 42 }, &x) } // CHECK-LABEL: sil hidden @$s27access_enforcement_noescape15writeWriteInoutyyF : $@convention(thin) () -> () { // Error: on noescape write + write inout. func inoutWriteWriteInout(x: inout Int) { // Around the call: [modify] [static] // Inside closure: [modify] [static] // Compile time error: see access_enforcement_noescape_error.swift. // doOneInout({ x = 42 }, &x) } // inoutWriteWriteInout(x:) // Traps on boxed write + write inout. // Covered by Interpreter/enforce_exclusive_access.swift. func writeBoxWriteInout() { var x = 3 let c = { x = 42 } // Around the call: [modify] [dynamic] // Inside closure: [modify] [dynamic] doOneInout(c, &x) } // CHECK-LABEL: sil hidden @$s27access_enforcement_noescape18writeBoxWriteInoutyyF : $@convention(thin) () -> () { // CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed] // CHECK: [[CVT:%.*]] = convert_escape_to_noescape [[PA1]] : $@callee_guaranteed () -> () to $@noescape @callee_guaranteed () -> () // CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] %1 : $*Int // CHECK: apply %{{.*}}([[CVT]], [[ACCESS]]) // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape18writeBoxWriteInoutyyF' // closure #1 in writeBoxWriteInout() // CHECK-LABEL: sil private @$s27access_enforcement_noescape18writeBoxWriteInoutyyFyycfU_ : $@convention(thin) (@guaranteed { var Int }) -> () { // CHECK: [[ADDR:%.*]] = project_box %0 : ${ var Int }, 0 // CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[ADDR]] : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '$s27access_enforcement_noescape18writeBoxWriteInoutyyFyycfU_' // Error: Cannot capture inout // This triggers an early diagnostics, so it's handled in inout_capture_disgnostics.swift. // func inoutWriteBoxWriteInout(x: inout Int) { // let c = { x = 42 } // doOneInout(c, &x) // } // Helper func doBlockInout(_: @convention(block) ()->(), _: inout Int) {} func readBlockWriteInout() { var x = 3 // Around the call: [modify] [static] // Inside closure: [read] [static] // Compile time error: see access_enforcement_noescape_error.swift. // doBlockInout({ _ = x }, &x) } // CHECK-LABEL: sil hidden @$s27access_enforcement_noescape19readBlockWriteInoutyyF : $@convention(thin) () -> () { // Test AccessSummaryAnalysis. // // The captured @inout_aliasable argument to `doOne` is re-partially applied, // then stored is a box before passing it to doBlockInout. func noEscapeBlock() { var x = 3 doOne { // Compile time error: see access_enforcement_noescape_error.swift. // doBlockInout({ _ = x }, &x) } } // CHECK-LABEL: sil hidden @$s27access_enforcement_noescape13noEscapeBlockyyF : $@convention(thin) () -> () {
apache-2.0
f601e1be7fb32904906f31576bdae332
44.172632
171
0.662068
3.292971
false
false
false
false
darrenclark/objc2swift
objc2swift/main.swift
1
618
// // main.swift // objc2swift // // Created by Darren Clark on 2015-10-30. // Copyright © 2015 Darren Clark. All rights reserved. // import Foundation let file = Process.arguments[1] let index = Index(excludeDeclarationsFromPCH: true, displayDiagnostics: false) do { let tu = try TranslationUnit(index: index, path: file) let converter = ASTConverter() converter.convertTranslationUnit(tu) let outputStream = StringOutputStream() let codeGenerator = CodeGenerator(outputStream: outputStream) codeGenerator.writeAST(converter.nodes) print(outputStream.stringValue) } catch { exit(EXIT_FAILURE) }
mit
37f31e257cc3f27d94c9cb0b689d772b
21.035714
78
0.753647
3.608187
false
false
false
false
nethergrim/xpolo
XPolo/Pods/BFKit-Swift/Sources/BFKit/Apple/UIKit/UIScrollViewExtension.swift
1
2392
// // UIScrollViewExtension.swift // BFKit // // The MIT License (MIT) // // Copyright (c) 2015 - 2017 Fabrizio Brancati. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation import UIKit // MARK: - UIScrollView extension /// This extesion adds some useful functions to UIScrollView. public extension UIScrollView { // MARK: - Functions /// Create an UIScrollView and set some parameters. /// /// - Parameters: /// - frame: ScrollView frame. /// - contentSize: ScrollView content size. /// - clipsToBounds: Set if ScrollView has to clips to bounds. /// - pagingEnabled: Set if ScrollView has paging enabled. /// - showScrollIndicators: Set if ScrollView has to show the scroll indicators, vertical and horizontal. /// - delegate: ScrollView delegate. public convenience init(frame: CGRect, contentSize: CGSize, clipsToBounds: Bool, pagingEnabled: Bool, showScrollIndicators: Bool, delegate: UIScrollViewDelegate?) { self.init(frame: frame) self.delegate = delegate self.isPagingEnabled = pagingEnabled self.clipsToBounds = clipsToBounds self.showsVerticalScrollIndicator = showScrollIndicators self.showsHorizontalScrollIndicator = showScrollIndicators self.contentSize = contentSize } }
gpl-3.0
27096829cf40c7926e808de71674a370
43.296296
168
0.724916
4.774451
false
false
false
false
rui4u/weibo
Rui微博/Rui微博/Classes/Model/UserAccout.swift
1
3712
// // UserAccout.swift // Rui微博 // // Created by 沙睿 on 15/10/12. // Copyright © 2015年 沙睿. All rights reserved. // import UIKit class UserAccout: NSObject ,NSCoding{ /// 用户是否登录标记 class var userLogon: Bool { return shareUserAccount != nil } /// 用于调用access_token,接口获取授权后的access token var access_token: String? /// access_token的生命周期,单位是秒数 - 准确的数据类型是`数值` var expires_in: NSTimeInterval = 0 { didSet { expiresDate = NSDate(timeIntervalSinceNow: expires_in) } } /// 过期日期 var expiresDate: NSDate? /// 当前授权用户的UID var uid: String? /// 友好显示名称 var name: String? /// 用户头像地址(大图),180×180像素 var avatar_large: String? init(dict: [String : AnyObject]) { super.init() setValuesForKeysWithDictionary(dict) UserAccout.userAccount = self } /// 利用运行时机制,排除key缺失情况 override func setValue(value: AnyObject?, forUndefinedKey key: String) {} func loadUserInfo(finished: (error: NSError?)->()) { NetworkTools.shareNetTooks.loadUserInfo(uid!) { (result, error) -> () in if error != nil { // 提示:error一定要传递! finished(error: error) return } // 设置用户信息 self.name = result!["name"] as? String self.avatar_large = result!["avatar_large"] as? String // 保存用户信息 self.saveAccount() // 完成回调 finished(error: nil) } } /// 保存文件路径 static private let accountPath = NSSearchPathForDirectoriesInDomains( NSSearchPathDirectory.DocumentDirectory,NSSearchPathDomainMask.UserDomainMask,true).last!.stringByAppendingString("/account.plist") func saveAccount(){ NSKeyedArchiver.archiveRootObject(self, toFile: UserAccout.accountPath) } /// 静态用户属性 private static var userAccount: UserAccout? class var shareUserAccount : UserAccout? { if userAccount == nil { userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? UserAccout } if let date = userAccount?.expiresDate where date.compare(NSDate()) == NSComparisonResult.OrderedAscending{ //账号已过期,,清空账号信息 userAccount = nil } return userAccount } // MARK: - NSCoding /// `归`档 -> 保存,将自定义对象转换成二进制数据保存到磁盘 func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(access_token, forKey: "access_token") aCoder.encodeDouble(expires_in, forKey: "expires_in") aCoder.encodeObject(expiresDate, forKey: "expiresDate") aCoder.encodeObject(uid, forKey: "uid") aCoder.encodeObject(name, forKey: "name") aCoder.encodeObject(avatar_large, forKey: "avatar_large") } /// `解`档 -> 恢复 将二进制数据从磁盘恢复成自定义对象 required init?(coder aDecoder: NSCoder) { access_token = aDecoder.decodeObjectForKey("access_token") as? String expires_in = aDecoder.decodeDoubleForKey("expires_in") expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate uid = aDecoder.decodeObjectForKey("uid") as? String name = aDecoder.decodeObjectForKey("name") as? String avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String } }
mit
9e35b05ed1fdb202da979feb38c8e15d
31.407767
205
0.617436
4.44474
false
false
false
false
Shivol/Swift-CS333
playgrounds/swift/Swift Standard Library 2.playground/Pages/Indexing and Slicing Strings.xcplaygroundpage/Sources/GroupChat.swift
3
2336
import UIKit public var pastAllowedLengthFunction: ((String) -> Range<String.Index>?)? private let messageCellIdentifier = "MessageCell" private class GroupChatController: UITableViewController { override init(style: UITableViewStyle) { super.init(style: style) tableView.register(UITableViewCell.self, forCellReuseIdentifier: messageCellIdentifier) view.frame = CGRect(x: 0, y: 0, width: 320, height: 300) tableView.separatorStyle = .singleLine tableView.separatorColor = .blue tableView.estimatedRowHeight = 60 } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return messages.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: messageCellIdentifier, for: indexPath) let attributedString = NSMutableAttributedString(string: String(describing: messages[indexPath.row])) if let redRangeFunction = pastAllowedLengthFunction, let redRange = redRangeFunction(messages[indexPath.row].contents) { let redAttribute: [String: AnyObject] = [ NSBackgroundColorAttributeName: #colorLiteral(red: 0.9859465361, green: 0, blue: 0.04060116783, alpha: 0.4969499144) ] let contents = messages[indexPath.row].contents let location = contents.distance(from:contents.startIndex, to: redRange.lowerBound) let length = contents.distance(from: redRange.lowerBound, to: redRange.upperBound) attributedString.setAttributes(redAttribute, range: NSRange(location: location, length: length)) } cell.textLabel!.numberOfLines = 0 cell.textLabel!.attributedText = attributedString return cell } } private let chatController = GroupChatController(style: .plain) private var chatView: UIView { return chatController.view } public func showChatView(_ rangeFunc: @escaping (_ contents: String) -> Range<String.Index>?) -> UIView { pastAllowedLengthFunction = rangeFunc return chatView }
mit
0a43b902b2d1351762c2051cfc7b0005
39.982456
132
0.694349
4.991453
false
false
false
false
wikimedia/wikipedia-ios
Wikipedia/Code/ArticleViewController+LinkPreviewing.swift
1
8779
// MARK: - Context Menu for ArticleVC (iOS 13 and later) // All functions in this extension are for Context Menus (used in iOS 13 and later) extension ArticleViewController: ArticleContextMenuPresenting, WKUIDelegate { func getPeekViewControllerAsync(for destination: Router.Destination, completion: @escaping (UIViewController?) -> Void) { switch destination { case .inAppLink(let linkURL): // Request the media list to see if this is a link from the gallery getMediaList { (result) in switch result { case .success(let mediaList): // Check the media list items to find the item for this link let fileName = linkURL.lastPathComponent if let item = mediaList.items.first(where: { (item) -> Bool in return item.title == fileName }) { let galleryVC = self.getGalleryViewController(for: item, in: mediaList) galleryVC.setOverlayViewTopBarHidden(true) completion(galleryVC) } else { completion(nil) } case .failure(let error): self.showError(error) completion(nil) } } default: completion(getPeekViewController(for: destination)) } } var contextMenuItems: [UIAction] { // Read action let readActionTitle = WMFLocalizedString("button-read-now", value: "Read now", comment: "Read now button text used in various places.") let readAction = UIAction(title: readActionTitle, handler: { (action) in self.articlePreviewingDelegate?.readMoreArticlePreviewActionSelected(with: self) }) var actions = [readAction] // Save action let logReadingListsSaveIfNeeded = { [weak self] in guard let delegate = self?.articlePreviewingDelegate as? EventLoggingEventValuesProviding else { return } self?.readingListsFunnel.logSave(category: delegate.eventLoggingCategory, label: delegate.eventLoggingLabel, articleURL: self?.articleURL) } if articleURL.namespace == .main { let saveActionTitle = article.isAnyVariantSaved ? WMFLocalizedString("button-saved-remove", value: "Remove from saved", comment: "Remove from saved button text used in various places.") : CommonStrings.saveTitle let saveAction = UIAction(title: saveActionTitle, handler: { (action) in let isSaved = self.dataStore.savedPageList.toggleSavedPage(for: self.articleURL) let notification = isSaved ? CommonStrings.accessibilitySavedNotification : CommonStrings.accessibilityUnsavedNotification UIAccessibility.post(notification: .announcement, argument: notification) self.articlePreviewingDelegate?.saveArticlePreviewActionSelected(with: self, didSave: isSaved, articleURL: self.articleURL) }) actions.append(saveAction) } // Location action if article.location != nil { let placeActionTitle = WMFLocalizedString("page-location", value: "View on a map", comment: "Label for button used to show an article on the map") let placeAction = UIAction(title: placeActionTitle, handler: { (action) in self.articlePreviewingDelegate?.viewOnMapArticlePreviewActionSelected(with: self) }) actions.append(placeAction) } // Share action let shareActionTitle = CommonStrings.shareMenuTitle let shareAction = UIAction(title: shareActionTitle, handler: { (action) in guard let presenter = self.articlePreviewingDelegate as? UIViewController else { return } let customActivity = self.addToReadingListActivity(with: presenter, eventLogAction: logReadingListsSaveIfNeeded) guard let shareActivityViewController = self.sharingActivityViewController(with: nil, button: self.toolbarController.shareButton, shareFunnel: self.shareFunnel, customActivities: [customActivity]) else { return } self.articlePreviewingDelegate?.shareArticlePreviewActionSelected(with: self, shareActivityController: shareActivityViewController) }) actions.append(shareAction) return actions } var previewMenuItems: [UIMenuElement]? { return contextMenuItems } func webView(_ webView: WKWebView, contextMenuConfigurationForElement elementInfo: WKContextMenuElementInfo, completionHandler: @escaping (UIContextMenuConfiguration?) -> Void) { self.contextMenuConfigurationForElement(elementInfo, completionHandler: completionHandler) } func webView(_ webView: WKWebView, contextMenuForElement elementInfo: WKContextMenuElementInfo, willCommitWithAnimator animator: UIContextMenuInteractionCommitAnimating) { guard elementInfo.linkURL != nil, let vc = animator.previewViewController else { return } animator.preferredCommitStyle = .pop animator.addCompletion { self.commitPreview(of: vc) } } func getPeekViewController(for destination: Router.Destination) -> UIViewController? { switch destination { case .article(let articleURL): let articleVC = ArticleViewController(articleURL: articleURL, dataStore: dataStore, theme: theme) articleVC?.articlePreviewingDelegate = self articleVC?.wmf_addPeekableChildViewController(for: articleURL, dataStore: dataStore, theme: theme) return articleVC default: return nil } } func commitPreview(of viewControllerToCommit: UIViewController) { if let vc = viewControllerToCommit as? ArticleViewController { readMoreArticlePreviewActionSelected(with: vc) } else { if let vc = viewControllerToCommit as? WMFImageGalleryViewController { vc.setOverlayViewTopBarHidden(false) } presentEmbedded(viewControllerToCommit, style: .gallery) } } } // MARK: Peek/Pop for Lead Image of ArticleVC extension ArticleViewController: UIContextMenuInteractionDelegate { func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? { // If gallery has not been opened on that article, self.mediaList is nil - and we need to create the media list guard let mediaList = self.mediaList ?? MediaList(from: leadImageView.wmf_imageURLToFetch) else { return nil } let previewProvider: UIContextMenuContentPreviewProvider = { let completion: ((Result<MediaList, Error>) -> Void) = { _ in // Nothing - We preload the medialist (if needed) to provide better performance in the likely case the user pops into image gallery. } self.getMediaList(completion) let galleryVC = self.getGalleryViewController(for: mediaList.items.first, in: mediaList) galleryVC.setOverlayViewTopBarHidden(true) return galleryVC } return UIContextMenuConfiguration(identifier: nil, previewProvider: previewProvider, actionProvider: nil) } func contextMenuInteraction(_ interaction: UIContextMenuInteraction, willPerformPreviewActionForMenuWith configuration: UIContextMenuConfiguration, animator: UIContextMenuInteractionCommitAnimating) { animator.addCompletion { if self.mediaList != nil { self.showLeadImage() } else { // fetchAndDisplayGalleryViewController() is very similar to showLeadImage(). In both cases, if self.mediaList doesn't exist, we make // a network request to load it. When that mediaList network fetch is happening in showLeadImage, we don't do anything - so when // transitioning from peek to pop, we are back to the main article with no indication we are in the process of popping. This // only happens on very slow networks (especially since we try to preload the mediaList when peeking - see above), but when it happens // it is not great for the user. Solution: If a mediaList needs to be fetched, fetchAndDisplayGalleryViewController() fakes the loading // photo screen while loading that mediaList - providing a much smoother user experience. self.fetchAndDisplayGalleryViewController() } } } }
mit
222f22975e9f9e07b5252ec5861f12ab
51.568862
223
0.664768
5.563371
false
false
false
false
abreis/swift-gissumo
src/network.swift
1
26261
/* Andre Braga Reis, 2016 * Licensing information can be found in the accompanying LICENSE file. */ import Foundation class Network { // A standard message delay for all transmissions, 10ms let messageDelay = SimulationTime(milliseconds: 10) // Delay between beacon broadcasts (1 sec) let beaconingInterval = SimulationTime(seconds: 1) // Multiplier, to be able to extend the radio range at will var propagationMultiplier: Double = 1.0 // Maximum radio range (for GIS queries) // Match with the chosen propagation algorithm var maxRange: Double { get { return 155*propagationMultiplier } } // The size, in cells, of a local coverage map // Our coverage maps are 13x13, or ~390m wide (enough for a 155m radio range + margin of error) var selfCoverageMapSize: Int { get { let errorMargin = 1.25 let cellSize = 30.0 // Note: adjust this for other SRIDs let mapCellSize = Int(ceil(maxRange*2.0*errorMargin/cellSize)) // Ensure odd-sized maps (with a center cell to locate the RSU at) return (mapCellSize % 2 == 0) ? mapCellSize+1 : mapCellSize } } // Propagation algorithm func getSignalStrength(_ distance: Double, _ lineOfSight: Bool) -> Double { return portoEmpiricalDataModel(distance: distance, lineOfSight: lineOfSight, multiplier: propagationMultiplier) } // Packet ID generator (can also be made to create random IDs) var nextPacketID: UInt = 0 func getNextPacketID() -> UInt { defer { nextPacketID += 1 } return nextPacketID } } /*** GEOCAST AREAS ***/ /* ETSI GeoNetworking header * Type: Any(0), Beacon(1), GeoUnicast(2), GeoAnycast(3), GeoBroadcast(4), TSB(Topologically Scoped Broadcast: 5) or LS (6) * Subtype: Circle(0), Rectangle(1) or Ellipse(2); */ protocol AreaType { func isPointInside(_ point: (x: Double, y: Double)) -> Bool } struct Square: AreaType, CustomStringConvertible { var x: (min: Double, max: Double) var y: (min: Double, max: Double) // Ensure bounds are always correct (min<max) init(x xIn: (min: Double, max: Double), y yIn: (min: Double, max: Double)) { x = xIn y = yIn if x.min > x.max { x.min = xIn.max x.max = xIn.min } if y.min > y.max { y.min = yIn.max y.max = yIn.min } } func isPointInside(_ point: (x: Double, y: Double)) -> Bool { if point.x > x.min && point.x < x.max && point.y > y.min && point.y < y.max { return true } else { return false } } var description: String { return "(\(x.min),\(y.min))(\(x.max),\(y.max))" } } struct Circle: AreaType, CustomStringConvertible { var center: (x: Double, y: Double) var radius: Double init(centerIn: (x: Double, y: Double), radiusIn: Double) { center = centerIn radius = radiusIn } func isPointInside(_ point: (x: Double, y: Double)) -> Bool { // TODO Unimplemented exit(EXIT_FAILURE) } var description: String { return "center (\(center.x),\(center.x)), radius\(radius)" } } /*** PACKETS ***/ // A message packet struct Packet { // A unique packet identifier in the simulation var id: UInt // Time the packet was created in the simulation var created: SimulationTime // Layer 2 Network var l2src: UInt // var l2dst // Unimplemented, all packets are broadcast at the MAC level // Layer 3 Network */ enum Destination { case unicast(destinationID: UInt) case broadcast(hopLimit: UInt) case geocast(targetArea: AreaType) } var l3src: UInt var l3dst: Destination // The packet's payload var payload: Payload // A single-line description of the packet var traceDescription: String { return "\(id)\t\(created.asSeconds)\t\(l2src)\t\(l3src)\t\(l3dst)\t\(payload.type)\t\(payload.content.replacingOccurrences(of: "\n", with: "\\n"))\n" } } /*** PAYLOAD TYPE ***/ // List of payload types so a payload can be correctly cast to a message enum PayloadType: UInt { case beacon = 0 case coverageMapRequest case coverageMaps case activeTimeRequest case activeTime case cellMap case disableRSU } // A payload is a simple text field and a header with its type struct Payload { var type: PayloadType var content: String } // Objects that conform to PayloadConvertible must be able to be completely expressed // as a Payload type (i.e., a string) and be created from a Payload as well protocol PayloadConvertible { func toPayload() -> Payload init? (fromPayload: Payload) } // Entitites that implement the PacketReceiver protocol are able to receive packets, // keep track of seen packets, and process payloads protocol PacketReceiver { var receivedPacketIDs: [UInt] { get set } func receive(_ packet: Packet) } // Entities that implement PayloadReceiver are able to process payloads protocol PayloadReceiver { func processPayload(withinPacket packet: Packet) } /*** PAYLOADS ***/ // A network beacon struct Beacon: PayloadConvertible { // Our beacons are similar to Cooperative Awareness Messages (CAMs) // The payload is simply the sending vehicle's geographic coordinates let geo: (x: Double, y: Double) let src: UInt let entityType: RoadEntityType init(geo ingeo: (x: Double, y: Double), src insrc: UInt, entityType intype: RoadEntityType) { geo = ingeo; src = insrc; entityType = intype; } // Convert coordinates to a Payload string func toPayload() -> Payload { let payloadContent = "\(geo.x);\(geo.y);\(src);\(entityType.rawValue)" return Payload(type: .beacon, content: payloadContent) } // Split a payload's data init(fromPayload payload: Payload) { let payloadCoords = payload.content.components(separatedBy: ";") guard let xgeo = Double(payloadCoords[0]), let ygeo = Double(payloadCoords[1]), let psrc = UInt(payloadCoords[2]), let ptyperaw = UInt(payloadCoords[3]), let ptype = RoadEntityType(rawValue: ptyperaw) else { print("Error: Coordinate conversion from Beacon payload failed.") exit(EXIT_FAILURE) } geo = (x: xgeo, y: ygeo) src = psrc entityType = ptype } } // A request for coverage maps struct CoverageMapRequest: PayloadConvertible { let depth: UInt func toPayload() -> Payload { return Payload(type: .coverageMapRequest, content: "\(depth)")} init? (fromPayload payload: Payload) { guard let payloadDepth = UInt(payload.content) else { return nil } depth = payloadDepth } init (depth: UInt) { self.depth = depth } } // A payload containing one or more coverage maps // Add maps to self.maps, then convert everything to a Payload, or viceversa struct CoverageMaps: PayloadConvertible { var maps: [SelfCoverageMap] = [] init () {} func toPayload() -> Payload { guard maps.count > 0 else { print("Error: attempted to convert an empty coverage map array to a Payload.") exit(EXIT_FAILURE) } var payloadString: String = "" for map in maps { payloadString += "id" + String(format: "%08d", map.ownerID) payloadString += map.cellMap.toPayload().content payloadString += "m" // split maps with 'm' character; payload contains: "cdilpt-;" plus 0..9 } return Payload(type: .coverageMaps, content: payloadString) } init? (fromPayload payload: Payload) { guard payload.type == .coverageMaps else { return nil } let mapEntries = payload.content.components(separatedBy: "m").filter{!$0.isEmpty} guard mapEntries.count > 0 else { return nil } for entry in mapEntries { guard entry.hasPrefix("id") else { return nil } // Index where the map and the ID are split. We reserve 10 chars for the map ID and tag let splitIdAndMapIndex = entry.index(entry.startIndex, offsetBy: 10) // Substrings let idString = entry.substring(to: splitIdAndMapIndex) let mapString = entry.substring(from: splitIdAndMapIndex) // Obtain cell map and owner ID from substrings guard let mapOwnerID = UInt(idString.substring(from: idString.index(idString.startIndex, offsetBy: 2))), let cellMap = CellMap<Int>(fromString: mapString) else { return nil } // Store the coverage map maps.append( SelfCoverageMap(ownerID: mapOwnerID, cellMap: cellMap) ) } } } // A request for an RSU's active time struct ActiveTimeRequest: PayloadConvertible { func toPayload() -> Payload { return Payload(type: .activeTimeRequest, content: "")} init? (fromPayload payload: Payload) {} init () { } } // A reply to an RSU active time request struct ActiveTime: PayloadConvertible { let activeTime: Time func toPayload() -> Payload { return Payload(type: .activeTime, content: "\(activeTime.nanoseconds)")} init? (fromPayload payload: Payload) { guard let payloadContentNumeric = Int(payload.content) else { return nil } activeTime = Time(nanoseconds: payloadContentNumeric) } init (activeTime: Time) { self.activeTime = activeTime} } // A message to instruct an RSU to disable itself struct DisableRoadsideUnit: PayloadConvertible { let rsuID: UInt init (disableID inID: UInt) { rsuID = inID } func toPayload() -> Payload { return Payload(type: .disableRSU, content: "\(rsuID)")} init(fromPayload payload: Payload) { guard let payloadID = UInt(payload.content) else { print("Error: ID conversion from disableRSU payload failed.") exit(EXIT_FAILURE) } rsuID = payloadID } } // Extend CellMaps to conform with PayloadConvertible extension CellMap: PayloadConvertible { // Write the map to a payload func toPayload() -> Payload { var description = String() // Print top-left coordinate on the first line // 'tlc': top-left-cell // 'p': line separator; map contains: "clt-;" plus 0..9 description += "tlc" + String(topLeftCellCoordinate.x) + ";" + String(topLeftCellCoordinate.y) + "p" for (cellIndex, row) in cells.enumerated() { for (rowIndex, element) in row.enumerated() { let stringElement = String(describing: element) description += stringElement if rowIndex != row.count-1 { description += ";" } } if cellIndex != cells.count-1 { description += "p" } } // Note: Cell maps are not necessarily CoverageMaps, this can be generified return Payload(type: .cellMap, content: description) } // Initialize the map from a payload init?(fromPayload payload: Payload) { self.init(fromString: payload.content) } // Initialize the map from a string init?(fromString content: String) { // Break string into lines var lines: [String] = content.components(separatedBy: "p").filter{!$0.isEmpty} // Extract the coordinates of the top-left cell from the payload header guard let firstLine = lines.first, firstLine.hasPrefix("tlc") else { return nil } let headerCellCoordinates = firstLine.replacingOccurrences(of: "tlc", with: "").components(separatedBy: ";") guard let xTopLeft = Int(headerCellCoordinates[0]), let yTopLeft = Int(headerCellCoordinates[1]) else { return nil } topLeftCellCoordinate = (x: xTopLeft, y: yTopLeft) // Remove the header and load the map lines.removeFirst() // Get the y-size from the number of lines read size.y = lines.count // Load cell contents cells = Array(repeating: [], count: size.y) var nrow = 0 for row in lines { let rowItems = row.components(separatedBy: ";") for rowItem in rowItems { guard let item = T(string: rowItem) else { return nil } cells[nrow].append(item) } nrow += 1 } // Get the x-size from the number of elements read size.x = cells.first!.count } } /*** SIGNAL STRENGTH ALGORITHMS ***/ // A discrete propagation model built with empirical data from the city of Porto func portoEmpiricalDataModel(distance: Double, lineOfSight: Bool, multiplier: Double = 1.0) -> Double { // Instead of increasing the ranges, we decrease the received distance, same outcome, less code (but less readability) let distance = distance/multiplier if lineOfSight { switch distance { case 0..<70 : return 5 case 70..<115 : return 4 case 115..<135 : return 3 case 135..<155 : return 2 default : return 0 } } else { switch distance { case 0..<58 : return 5 case 58..<65 : return 4 case 65..<105 : return 3 case 105..<130 : return 2 default : return 0 } } } /*** TRANSPORT ***/ // Extend RoadEntity types with the ability to broadcast messages extension RoadEntity { func broadcastPacket(_ packet: Packet, toFeatureTypes features: GIS.FeatureType...) { // If no destination is specified, assume ALL var features = features if features.count == 0 { features = [.vehicle, .roadsideUnit, .parkedCar] } // Output packet trace, if enabled if city.stats.hooks["packetTrace"] != nil { city.stats.writeToHook("packetTrace", data: packet.traceDescription) } // Locate matching neighbor GIDs var neighborGIDs: [UInt] // If we're using the Haversine formula, skip the GIS query and locate neighbors right in the simulator if city.gis.useHaversine { neighborGIDs = city.getFeatureGIDs(inCircleWithRadius: city.network.maxRange, center: geo, featureTypes: features) } else { neighborGIDs = city.gis.getFeatureGIDs(inCircleWithRadius: city.network.maxRange, center: geo, featureTypes: features) } if neighborGIDs.count > 0 { // Remove ourselves from the list if let selfGID = self.gid, let selfIndex = neighborGIDs.index(of: selfGID) { neighborGIDs.remove(at: selfIndex) } // TODO: Broadcast packets to other Vehicles // Necessary for >1 hop transmissions, forwarding geocasts // Send the packet to all neighboring RSUs let matchingRSUs = city.roadsideUnits.filter( {neighborGIDs.contains($0.gid!)} ) for neighborRSU in matchingRSUs { // Schedule a receive(packet) event for time=now+transmissionDelay let newReceivePacketEvent = SimulationEvent(time: city.events.now + city.network.messageDelay, type: .network, action: { neighborRSU.receive(packet) }, description: "RSU \(neighborRSU.id) receive packet \(packet.id) from \(self.id)") city.events.add(newEvent: newReceivePacketEvent) } // Send the packet to all neighboring parked cars let matchingParkedCars = city.parkedCars.filter( {neighborGIDs.contains($0.gid!)} ) for neighborParkedCar in matchingParkedCars { // Schedule a receive(packet) event for time=now+transmissionDelay let newReceivePacketEvent = SimulationEvent(time: city.events.now + city.network.messageDelay, type: .network, action: { neighborParkedCar.receive(packet) }, description: "ParkedCar \(neighborParkedCar.id) receive packet \(packet.id) from \(self.id)") city.events.add(newEvent: newReceivePacketEvent) } } } } // Extend Roadside Units with the ability to receive packets extension RoadEntity: PacketReceiver { func receive(_ packet: Packet) { // We should never receive packets sent by ourselves on layer2 assert(packet.l2src != id) // Ignore retransmissions of packets originally sent by ourselves guard packet.l3src != id else { return } // Ignore packets we've already seen // Note: Packet IDs must not change during retransmissions guard !receivedPacketIDs.contains(packet.id) else { return } // Store the packet ID receivedPacketIDs.append(packet.id) // Debug if debug.contains("RoadEntity.receive()"){ print("\(city.events.now.asSeconds) \(type(of: self)).receive():".padding(toLength: 54, withPad: " ", startingAt: 0).cyan(), "RSU", id, "received packet", packet.id, "l2src", packet.l2src, "l3src", packet.l3src, "l3dst", packet.l3dst, "payload", packet.payload.type) } // Process destination field switch packet.l3dst { case .unicast(let destinationID): // Disregard if we're not the message target if destinationID != id { return } case .broadcast(let hopsRemaining): // Disregard if the hop limit is reached if hopsRemaining <= 1 { break } // 1. Clone the packet var rebroadcastPacket = packet // 2. Reduce TTL rebroadcastPacket.l3dst = .broadcast(hopLimit: hopsRemaining - 1) // 3. Refresh l2src rebroadcastPacket.l2src = self.id // 4. Rebroadcast self.broadcastPacket(rebroadcastPacket) // Debug if debug.contains("RoadEntity.receive()"){ print("\(city.events.now.asSeconds) \(type(of: self)).receive():".padding(toLength: 54, withPad: " ", startingAt: 0).cyan(), "RSU", id, "rebroadcasting packet", rebroadcastPacket.id, "l2src", rebroadcastPacket.l2src, "l3src", rebroadcastPacket.l3src, "l3dst", rebroadcastPacket.l3dst, "payload", rebroadcastPacket.payload.type) } case .geocast(let targetArea): // Disregard if we're not in the destination area if targetArea.isPointInside(geo) == false { return } // 1. Clone the packet var rebroadcastPacket = packet // 2. Refresh l2src rebroadcastPacket.l2src = self.id // 2. Rebroadcast self.broadcastPacket(rebroadcastPacket) // Debug if debug.contains("RoadEntity.receive()"){ print("\(city.events.now.asSeconds) \(type(of: self)).receive():".padding(toLength: 54, withPad: " ", startingAt: 0).cyan(), "RSU", id, "rebroadcasting packet", rebroadcastPacket.id, "l2src", rebroadcastPacket.l2src, "l3src", rebroadcastPacket.l3src, "l3dst", rebroadcastPacket.l3dst, "payload", rebroadcastPacket.payload.type) } } // Entity-independent payload processing // Code that all RoadEntities should run on payloads goes here // Process payload switch packet.payload.type { case .beacon: // Track number of beacons received if city.stats.hooks["beaconCount"] != nil { if var recvBeacons = city.stats.metrics["beaconsReceived"] as? UInt { recvBeacons += 1 city.stats.metrics["beaconsReceived"] = recvBeacons } } default: break } // Entity-specific payload processing // Call the entity's specific payload processing routine if self is PayloadReceiver { (self as! PayloadReceiver).processPayload(withinPacket: packet) } } } // Extend Vehicles with the ability to send beacons extension Vehicle { func broadcastBeacon() { // Construct the beacon payload with the sender's coordinates (Cooperative Awareness Message) let beaconPayload: Payload = Beacon(geo: self.geo, src: self.id, entityType: self.type).toPayload() // Construct the beacon packet, a broadcast with hoplimit = 1 let beaconPacket = Packet(id: city.network.getNextPacketID(), created: city.events.now, l2src: self.id, l3src: self.id, l3dst: .broadcast(hopLimit: 1), payload: beaconPayload) // Send the beacon to our neighbors self.broadcastPacket(beaconPacket) // Track number of beacons sent if city.stats.hooks["beaconCount"] != nil { if var sentBeacons = city.stats.metrics["beaconsSent"] as? UInt { sentBeacons += 1 city.stats.metrics["beaconsSent"] = sentBeacons } } } } // Extend Vehicles with a recurrent beaconing routine // This must be initiated when the vehicle is created extension Vehicle { func recurrentBeaconing() { // Ensure this vehicle is still active -- a beaconing event may have been scheduled for after the vehicle is removed // This requires tagging vehicles with active=false when they are removed guard self.active else { return } // A safer, but slower way to do this, is to check whether the vehicle in question is still in the City // guard city.vehicles.contains( {$0 === self} ) else { return } // Send a beacon right away self.broadcastBeacon() // Schedule a new beacon to be sent in now+beaconingInterval let newBeaconEvent = SimulationEvent(time: city.events.now + city.network.beaconingInterval, type: .network, action: {self.recurrentBeaconing()}, description: "broadcastBeacon vehicle \(self.id)") city.events.add(newEvent: newBeaconEvent) } } // Extend Fixed Road Entities (e.g. roadside units) with the ability to process payloads extension FixedRoadEntity: PayloadReceiver { func processPayload(withinPacket packet: Packet) { switch packet.payload.type { case .beacon: // RSUs use beacons to construct their coverage maps let receivedBeacon = Beacon(fromPayload: packet.payload) trackSignalStrength(fromBeacon: receivedBeacon) case .coverageMapRequest: // Only RSUs reply to requests for coverage maps if self is RoadsideUnit { guard let coverageRequest = CoverageMapRequest(fromPayload: packet.payload) else { print("Error: Failed to convert a CoverageMapRequest payload.") exit(EXIT_FAILURE) } switch coverageRequest.depth { /* DEPTH == 1 */ case 1: // depth 1 -> only send our own map, already appended earlier // Array to store the maps for the payload var coverageMapArray = CoverageMaps() // Append our own map coverageMapArray.maps.append( SelfCoverageMap(ownerID: self.id, cellMap: self.selfCoverageMap) ) let coverageMapReplyPacket = Packet(id: self.city.network.getNextPacketID(), created: self.city.events.now, l2src: self.id, l3src: self.id, l3dst: .unicast(destinationID: packet.l3src), payload: coverageMapArray.toPayload()) // We're sending coverage map replies to parked cars and roadside units, for the depth request to work self.broadcastPacket(coverageMapReplyPacket, toFeatureTypes: .parkedCar, .roadsideUnit) /* DEPTH == 2 */ case 2: /* depth 2: * -> broadcast a depth==1 request, wait for replies (0.5s) * -> send our map and our 1-hop neighbors' maps */ let onDemandCoverageMapRequestPacket = Packet(id: self.city.network.getNextPacketID(), created: self.city.events.now, l2src: self.id, l3src: self.id, l3dst: .broadcast(hopLimit: 1), payload: CoverageMapRequest(depth: 1).toPayload()) // We're only interested in maps from active roadside units here self.broadcastPacket(onDemandCoverageMapRequestPacket, toFeatureTypes: .roadsideUnit) // Create and schedule a reply to the original requester with the received maps let coverageBroadcastClosure = { // Array to store the maps for the payload var coverageMapArray = CoverageMaps() // Append our own map coverageMapArray.maps.append( SelfCoverageMap(ownerID: self.id, cellMap: self.selfCoverageMap) ) // Append 1-hop neighbor maps (distance == 1) // Don't send maps that are not new, as they may belong to RSUs that don't exist anymore // We're arbitrarily choosing 1 second since replies should have arrived in the last .5 seconds coverageMapArray.maps += self.neighborMaps .filter{ $1.distance == 1 } .filter{ $1.lastUpdated > self.city.events.now - SimulationTime(seconds: 1) } .map{ return SelfCoverageMap(ownerID: $0, cellMap: $1.coverageMap) } let coverageMapReplyPacket = Packet(id: self.city.network.getNextPacketID(), created: self.city.events.now, l2src: self.id, l3src: self.id, l3dst: .unicast(destinationID: packet.l3src), payload: coverageMapArray.toPayload()) // We're only sending coverage map replies to parked cars self.broadcastPacket(coverageMapReplyPacket, toFeatureTypes: .parkedCar) } let coverageMapReplyEvent = SimulationEvent(time: self.city.events.now + SimulationTime(milliseconds: 500), type: .network, action: coverageBroadcastClosure, description: "deferred coverage map reply src \(self.id) dst \(packet.l3src)") self.city.events.add(newEvent: coverageMapReplyEvent) default: print("Error: Invalid depth on coverage map request.") exit(EXIT_FAILURE) } } case .coverageMaps: // Pull coverage maps from the payload guard let coverageMapPayload = CoverageMaps(fromPayload: packet.payload) else { print("Error: failed to convert a CoverageMaps payload.") exit(EXIT_FAILURE) } // Call the neighbor map managing routine in FixedRoadEntity self.append(coverageMaps: coverageMapPayload.maps, sender: packet.l3src, currentTime: self.city.events.now) case .activeTimeRequest: // Only RSUs reply to requests for active time if self is RoadsideUnit { guard let creationTime = self.creationTime else { print("Error: Creation time not set for RSU.") exit(EXIT_FAILURE) } // Prepare a packet let activeTime = ActiveTime(activeTime: Time(self.city.events.now - creationTime)) let activeTimePacket = Packet(id: self.city.network.getNextPacketID(), created: self.city.events.now, l2src: self.id, l3src: self.id, l3dst: .unicast(destinationID: packet.l3src), payload: activeTime.toPayload()) // Unicast the packet to the requester self.broadcastPacket(activeTimePacket, toFeatureTypes: .parkedCar) } case .activeTime: // Only parked cars in decision mode keep active times of neighbors if self is ParkedCar { // Track the neighbor's active time (self as! ParkedCar).neighborActiveTimes[packet.l3src] = ActiveTime(fromPayload: packet.payload)!.activeTime } case .disableRSU: // Only RSUs can be disabled by a message if self is RoadsideUnit { // Pull the targed GID from the payload let disableMessage = DisableRoadsideUnit(fromPayload: packet.payload) // If the disable command was directed to us, schedule an event to remove us from the network if disableMessage.rsuID == self.id { let removalEvent = SimulationEvent(time: self.city.events.now + self.city.events.minTimestep, type: .vehicular, action: {self.city.removeEntity(self)}, description: "Remove RSU id \(self.id) by disableRSU packet \(packet.id)") self.city.events.add(newEvent: removalEvent) } } default: print("Error: Received an unknown payload.") exit(EXIT_FAILURE) } } } /*** SIGNAL STRENGTH MAPS ***/ // Extend Fixed Road Entities with the ability to receive a Beacon payload and register a signal coverage metric extension FixedRoadEntity { func trackSignalStrength(fromBeacon beacon: Beacon) { // Get the signal strength we see to the beacon's geographic coordinates let beaconDistance = city.gis.getDistance(fromPoint: self.geo, toPoint: beacon.geo) let beaconLOS = city.gis.checkForLineOfSight(fromPoint: self.geo, toPoint: beacon.geo) let beaconSignalStrength = city.network.getSignalStrength(beaconDistance, beaconLOS) // Store the signal strength seen at the beacon location selfCoverageMap[(beacon.geo)] = Int(beaconSignalStrength) // Debug if debug.contains("FixedRoadEntity.trackSignalStrength()"){ print("\(city.events.now.asSeconds) FixedRoadEntity.trackSignalStrength():".padding(toLength: 54, withPad: " ", startingAt: 0).cyan(), "RSU", id, "sees signal", beaconSignalStrength, "at geo", beacon.geo, "distance", beaconDistance, "los", beaconLOS) } } }
mit
f2ecb64897779e5adf464600d7bd51b9
34.061415
334
0.713415
3.524493
false
false
false
false
abecker3/SeniorDesignGroup7
ProvidenceWayfinding/ProvidenceWayfinding/FloorPlansViewController.swift
1
6013
// // FloorPlansViewController.swift // ProvidenceWayfinding // // Created by Andrew Becker on 1/26/16. // Copyright © 2016 GU. All rights reserved. // import UIKit class FloorPlansViewController: UIViewController { @IBOutlet weak var floorMap: UIImageView! @IBOutlet weak var scrollMap: UIScrollView! @IBOutlet weak var textTitle: UITextField! @IBOutlet weak var buildingWomens: UIButton! @IBOutlet weak var buildingChildrens: UIButton! @IBOutlet weak var buildingHeart: UIButton! @IBOutlet weak var buildingMain: UIButton! @IBOutlet weak var floorL3: UIButton! @IBOutlet weak var floorL2: UIButton! @IBOutlet weak var floorL1: UIButton! @IBOutlet weak var floor1: UIButton! @IBOutlet weak var floor2: UIButton! @IBOutlet weak var floor3: UIButton! @IBOutlet weak var floor4: UIButton! @IBOutlet weak var floor5: UIButton! @IBOutlet weak var floor6: UIButton! @IBOutlet weak var floor7: UIButton! @IBOutlet weak var floor8: UIButton! @IBOutlet weak var floor9: UIButton! @IBOutlet weak var floor10: UIButton! var building = String() var floor = String() var underscore = String() var fileExtension = String() var textBuilding = String() var imageName = String() override func viewDidLoad() { super.viewDidLoad() underscore = "_" fileExtension = ".jpg" initialize() self.scrollMap.maximumZoomScale = 5.0 self.scrollMap.clipsToBounds = true let tap = UITapGestureRecognizer(target: self, action: "doubleTapped") tap.numberOfTapsRequired = 2 view.addGestureRecognizer(tap) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? { return self.floorMap } func setButtons(a: Bool,b: Bool,c: Bool,d: Bool,e: Bool,f: Bool,g: Bool,h: Bool,i: Bool,j: Bool, k: Bool, l: Bool, m: Bool){ floorL3.enabled = a floorL2.enabled = b floorL1.enabled = c floor1.enabled = d floor2.enabled = e floor3.enabled = f floor4.enabled = g floor5.enabled = h floor6.enabled = i floor7.enabled = j floor8.enabled = k floor9.enabled = l floor10.enabled = m } func initialize(){ building = "Main" floor = "1" textBuilding = "Main Tower" setButtons(true, b: true, c: true, d: true, e: true, f: true, g: true, h: true, i: true, j: true, k: true, l: true, m: true) textTitle.text = textBuilding + " Floor " + floor imageName = building + underscore + floor + fileExtension floorMap.image = UIImage(named: imageName) floorMap.contentMode = UIViewContentMode.ScaleAspectFit } @IBAction func mainPressed(sender: UIButton) { building = "Main" floor = "1" textBuilding = "Main Tower" setButtons(true, b: true, c: true, d: true, e: true, f: true, g: true, h: true, i: true, j: true, k: true, l: true, m: true) textTitle.text = textBuilding + " Floor " + floor imageName = building + underscore + floor + fileExtension floorMap.image = UIImage(named: imageName) floorMap.contentMode = UIViewContentMode.ScaleAspectFit } @IBAction func heartPressed(sender: UIButton) { building = "Heart" floor = "1" textBuilding = "Heart Institute" setButtons(false, b: false, c: false, d: true, e: true, f: true, g: true, h: true, i: false, j: false, k: false, l: false, m: false) textTitle.text = textBuilding + " Floor " + floor imageName = building + underscore + floor + fileExtension floorMap.image = UIImage(named: imageName) floorMap.contentMode = UIViewContentMode.ScaleAspectFit } @IBAction func childrensPressed(sender: UIButton) { building = "Childrens" floor = "1" textBuilding = "Children's Hospital" setButtons(true, b: true, c: true, d: true, e: true, f: true, g: true, h: false, i: false, j: false, k: false, l: false, m: false) textTitle.text = textBuilding + " Floor " + floor imageName = building + underscore + floor + fileExtension floorMap.image = UIImage(named: imageName) floorMap.contentMode = UIViewContentMode.ScaleAspectFit } @IBAction func womensPressed(sender: UIButton) { building = "Womens" floor = "1" textBuilding = "Womens Health Center" setButtons(true, b: true, c: true, d: true, e: true, f: true, g: false, h: false, i: false, j: false, k: false, l: false, m: false) textTitle.text = textBuilding + " Floor " + floor imageName = building + underscore + floor + fileExtension floorMap.image = UIImage(named: imageName) floorMap.contentMode = UIViewContentMode.ScaleAspectFit } @IBAction func floorPressed(sender: UIButton) { switch sender{ case floorL3: floor = "L3" case floorL2: floor = "L2" case floorL1: floor = "L1" case floor2: floor = "2" case floor3: floor = "3" case floor4: floor = "4" case floor5: floor = "5" case floor6: floor = "6" case floor7: floor = "7" case floor8: floor = "8" case floor9: floor = "9" case floor10: floor = "10" default: floor = "1" } textTitle.text = textBuilding + " Floor " + floor imageName = building + underscore + floor + fileExtension floorMap.image = UIImage(named: imageName) floorMap.contentMode = UIViewContentMode.ScaleAspectFit } func doubleTapped() { if (scrollMap.zoomScale > 1){ scrollMap.setZoomScale(0.25, animated: true) } else{ scrollMap.setZoomScale(2, animated: true) } } }
apache-2.0
3fda7b771e9bdd94f378f1e22774ce98
35.216867
140
0.615602
4.04576
false
false
false
false
phatblat/octokit.swift
OctoKit/User.swift
1
3863
import Foundation import RequestKit // MARK: model @objc public class User: NSObject { public let id: Int public var login: String? public var avatarURL: String? public var gravatarID: String? public var type: String? public var name: String? public var company: String? public var blog: String? public var location: String? public var email: String? public var numberOfPublicRepos: Int? public var numberOfPublicGists: Int? public var numberOfPrivateRepos: Int? public init(_ json: [String: AnyObject]) { if let id = json["id"] as? Int { self.id = id login = json["login"] as? String avatarURL = json["avatar_url"] as? String gravatarID = json["gravatar_id"] as? String type = json["type"] as? String name = json["name"] as? String company = json["company"] as? String blog = json["blog"] as? String location = json["location"] as? String email = json["email"] as? String numberOfPublicRepos = json["public_repos"] as? Int numberOfPublicGists = json["public_gists"] as? Int numberOfPrivateRepos = json["total_private_repos"] as? Int } else { id = -1 } } } // MARK: request public extension Octokit { /** Fetches a user or organization - parameter session: RequestKitURLSession, defaults to NSURLSession.sharedSession() - parameter name: The name of the user or organization. - parameter completion: Callback for the outcome of the fetch. */ public func user(_ session: RequestKitURLSession = URLSession.shared, name: String, completion: @escaping (_ response: Response<User>) -> Void) -> URLSessionDataTaskProtocol? { let router = UserRouter.readUser(name, self.configuration) return router.loadJSON(session, expectedResultType: [String: AnyObject].self) { json, error in if let error = error { completion(Response.failure(error)) } else { if let json = json { let parsedUser = User(json) completion(Response.success(parsedUser)) } } } } /** Fetches the authenticated user - parameter session: RequestKitURLSession, defaults to NSURLSession.sharedSession() - parameter completion: Callback for the outcome of the fetch. */ public func me(_ session: RequestKitURLSession = URLSession.shared, completion: @escaping (_ response: Response<User>) -> Void) -> URLSessionDataTaskProtocol? { let router = UserRouter.readAuthenticatedUser(self.configuration) return router.loadJSON(session, expectedResultType: [String: AnyObject].self) { json, error in if let error = error { completion(Response.failure(error)) } else { if let json = json { let parsedUser = User(json) completion(Response.success(parsedUser)) } } } } } // MARK: Router enum UserRouter: Router { case readAuthenticatedUser(Configuration) case readUser(String, Configuration) var configuration: Configuration { switch self { case .readAuthenticatedUser(let config): return config case .readUser(_, let config): return config } } var method: HTTPMethod { return .GET } var encoding: HTTPEncoding { return .url } var path: String { switch self { case .readAuthenticatedUser: return "user" case .readUser(let username, _): return "users/\(username)" } } var params: [String: Any] { return [:] } }
mit
0e8943b0185f361499a49b49fff9edb0
31.462185
180
0.593839
4.840852
false
true
false
false
baottran/nSURE
nSURE/AddressListViewController.swift
1
4602
// // AddressListViewController.swift // nSURE // // Created by Bao Tran on 7/1/15. // Copyright (c) 2015 Sprout Designs. All rights reserved. // import UIKit class AddressListViewController: UITableViewController { @IBOutlet weak var addressLabel: UITextView! var customerAddresses: [PFObject]? var customer: PFObject? override func viewDidLoad() { super.viewDidLoad() print("customerAddresses: \(customerAddresses)", terminator: "") print("customer obj test for addressList: \(customer)", terminator: "") } override func viewDidAppear(animated: Bool) { self.tableView.reloadData() } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return customerAddresses!.count } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("AddressCell", forIndexPath: indexPath) as! CustomerAddressCell cell.addressTextView.userInteractionEnabled = false if let addresses = customerAddresses { // println("phones: \(addresses)") let addressToQuery = addresses[indexPath.row] // let query = PFQuery(className: "Address") query.getObjectInBackgroundWithId(addressToQuery.objectId!, block: { result, error in if let address = result { print("got the address", terminator: "") let addressStreet = address["street"] as! String let addressCity = address["city"] as! String let addressState = address["state"] as! String let addressZip = address["zip"] as! String let addressApartment = address["apartment"] as! String cell.addressTextView.text = "\(addressStreet) \(addressApartment)\n\(addressCity), \(addressState) \(addressZip)" cell.addressTextView.font = UIFont.systemFontOfSize(17) } if let currentCustomer = self.customer { if let defaultAddress = currentCustomer["defaultAddress"] as? PFObject { if defaultAddress.objectId == addressToQuery.objectId { cell.accessoryType = .Checkmark } else { cell.accessoryType = .DisclosureIndicator } } } }) // } // return cell } // func pfAddViewController(newPhone: PFObject) { // customerPhones?.append(newPhone) // } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "AddAddress" { let controller = segue.destinationViewController as! AddressNewViewController controller.customerObj = self.customer! } else if segue.identifier == "EditCurrentAddress" { let controller = segue.destinationViewController as! AddressNewViewController controller.customerObj = self.customer! if let indexPath = tableView.indexPathForCell(sender as! UITableViewCell) { let rowNum = indexPath.row controller.customerAddressObj = self.customerAddresses![rowNum] } } } // override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // if segue.identifier == "AddPhone" { // let controller = segue.destinationViewController as! PFAddPhoneViewController // controller.delegate = self // controller.customerObj = self.customer! // } else if segue.identifier == "EditPhone" { // let controller = segue.destinationViewController as! PFAddPhoneViewController // controller.delegate = self // controller.customerObj = self.customer! // // if let indexPath = tableView.indexPathForCell(sender as! UITableViewCell) { // let rowNum = indexPath.row // controller.phoneObj = self.customerPhones![rowNum] // } // } // } //end }
mit
22adafd512803acd6615a1297b94d98b
36.414634
133
0.593003
5.478571
false
false
false
false
dutchcoders/stacktray
StackTray/Models/Account.swift
1
6357
// // Account.swift // stacktray // // Created by Ruben Cagnie on 3/4/15. // Copyright (c) 2015 dutchcoders. All rights reserved. // import Cocoa public enum AccountType : Int, Printable { case AWS, DUMMY, Unknown /** Name of the thumbnail that should be show */ public var imageName: String { switch self{ case .AWS: return "AWS" case .DUMMY: return "DUMMY" case .Unknown: return "UNKNOWN" } } /** Description */ public var description: String { switch self{ case .AWS: return "Amazon Web Service" case .DUMMY: return "DUMMY Web Service" case .Unknown: return "Unknown Web Service" } } } public protocol AccountDelegate { func didAddAccountInstance(account: Account, instanceIndex: Int) func didUpdateAccountInstance(account: Account, instanceIndex: Int) func didDeleteAccountInstance(account: Account, instanceIndex: Int) func instanceDidStart(account: Account, instanceIndex: Int) func instanceDidStop(account: Account, instanceIndex: Int) } /** An account object represents the connection to a web service */ public class Account : NSObject, NSCoding { /** Meta Data */ public var name: String = "" /** Account Type */ public var accountType: AccountType = .Unknown /** Delegate */ public var delegate : AccountDelegate? func sortOnName(this:Instance, that:Instance) -> Bool { return this.name > that.name } /** Instances */ public var instances : [Instance] = [] { didSet{ if let d = delegate { let oldInstanceIds = oldValue.map{ $0.instanceId } let newInstanceIds = instances.map{ $0.instanceId } for instance in instances { if contains(oldInstanceIds, instance.instanceId) && contains(newInstanceIds, instance.instanceId) { d.didUpdateAccountInstance(self, instanceIndex: find(instances, instance)!) } else if contains(oldInstanceIds, instance.instanceId){ d.didDeleteAccountInstance(self, instanceIndex: find(instances, instance)!) } else if contains(newInstanceIds, instance.instanceId){ d.didAddAccountInstance(self, instanceIndex: find(instances, instance)!) } } } } } /** Init an Account Object */ public init(name: String, accountType: AccountType){ self.name = name self.accountType = accountType super.init() } required public init(coder aDecoder: NSCoder) { if let name = aDecoder.decodeObjectForKey("name") as? String { self.name = name } if let accountTypeNumber = aDecoder.decodeObjectForKey("accountType") as? NSNumber { if let accountType = AccountType(rawValue: accountTypeNumber.integerValue){ self.accountType = accountType } } if let data = aDecoder.decodeObjectForKey("instances") as? NSData { if let instances = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? [Instance] { self.instances = instances } } super.init() } public func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(name, forKey: "name") aCoder.encodeObject(NSNumber(integer: accountType.rawValue), forKey: "accountType") aCoder.encodeObject(NSKeyedArchiver.archivedDataWithRootObject(instances), forKey: "instances") } public func addInstance(instance: Instance){ instances.append(instance) if let d = delegate { d.didAddAccountInstance(self, instanceIndex: find(instances, instance)!) } } public func updateInstanceAtIndex(index: Int, instance: Instance){ let existingInstance = instances[index] let beforeState = existingInstance.state existingInstance.mergeInstance(instance) if let d = delegate { d.didUpdateAccountInstance(self, instanceIndex: index) if instance.lastUpdate != nil && instance.state != beforeState { if instance.state == .Running { d.instanceDidStart(self, instanceIndex: index) } else if instance.state == .Stopped { d.instanceDidStop(self, instanceIndex: index) } } } } public func removeInstances(instanceIds: [String]){ var toRemove = instances.filter { (instance) -> Bool in return contains(instanceIds, instance.instanceId) } for instance in toRemove { if let index = find(instances, instance){ instances.removeAtIndex(index) if let d = delegate { d.didDeleteAccountInstance(self, instanceIndex: index) } } } } } public class AWSAccount : Account { /** AWS Specific Keys */ public var accessKey: String = "" public var secretKey: String = "" public var region: String = "" /** Init an AWS Account Object */ public init(name: String, accessKey: String, secretKey: String, region: String){ self.accessKey = accessKey self.secretKey = secretKey self.region = region super.init(name: name, accountType: .AWS) } required public init(coder aDecoder: NSCoder) { if let accessKey = aDecoder.decodeObjectForKey("accessKey") as? String { self.accessKey = accessKey } if let secretKey = aDecoder.decodeObjectForKey("secretKey") as? String { self.secretKey = secretKey } if let region = aDecoder.decodeObjectForKey("region") as? String{ self.region = region } super.init(coder: aDecoder) } public override func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(accessKey, forKey: "accessKey") aCoder.encodeObject(secretKey, forKey: "secretKey") aCoder.encodeObject(region, forKey: "region") super.encodeWithCoder(aCoder) } }
mit
e01d6949642f32784d3abed440b363df
32.282723
119
0.596665
4.985882
false
false
false
false
accepton/accepton-apple
Pod/Vendor/Alamofire/Alamofire.swift
1
12195
// Alamofire.swift // // Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation // MARK: - URLStringConvertible /** Types adopting the `URLStringConvertible` protocol can be used to construct URL strings, which are then used to construct URL requests. */ protocol URLStringConvertible { /** A URL that conforms to RFC 2396. Methods accepting a `URLStringConvertible` type parameter parse it according to RFCs 1738 and 1808. See https://tools.ietf.org/html/rfc2396 See https://tools.ietf.org/html/rfc1738 See https://tools.ietf.org/html/rfc1808 */ var URLString: String { get } } extension String: URLStringConvertible { var URLString: String { return self } } extension NSURL: URLStringConvertible { var URLString: String { return absoluteString } } extension NSURLComponents: URLStringConvertible { var URLString: String { return URL!.URLString } } extension NSURLRequest: URLStringConvertible { var URLString: String { return URL!.URLString } } // MARK: - URLRequestConvertible /** Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests. */ protocol URLRequestConvertible { /// The URL request. var URLRequest: NSMutableURLRequest { get } } extension NSURLRequest: URLRequestConvertible { var URLRequest: NSMutableURLRequest { return self.mutableCopy() as! NSMutableURLRequest } } // MARK: - Convenience func URLRequest( method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil) -> NSMutableURLRequest { let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URLString.URLString)!) mutableURLRequest.HTTPMethod = method.rawValue if let headers = headers { for (headerField, headerValue) in headers { mutableURLRequest.setValue(headerValue, forHTTPHeaderField: headerField) } } return mutableURLRequest } // MARK: - Request Methods /** Creates a request using the shared manager instance for the specified method, URL string, parameters, and parameter encoding. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter parameters: The parameters. `nil` by default. - parameter encoding: The parameter encoding. `.URL` by default. - parameter headers: The HTTP headers. `nil` by default. - returns: The created request. */ func request( method: Method, _ URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL, headers: [String: String]? = nil) -> Request { return Manager.sharedInstance.request( method, URLString, parameters: parameters, encoding: encoding, headers: headers ) } /** Creates a request using the shared manager instance for the specified URL request. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter URLRequest: The URL request - returns: The created request. */ func request(URLRequest: URLRequestConvertible) -> Request { return Manager.sharedInstance.request(URLRequest.URLRequest) } // MARK: - Upload Methods // MARK: File /** Creates an upload request using the shared manager instance for the specified method, URL string, and file. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter headers: The HTTP headers. `nil` by default. - parameter file: The file to upload. - returns: The created upload request. */ func upload( method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil, file: NSURL) -> Request { return Manager.sharedInstance.upload(method, URLString, headers: headers, file: file) } /** Creates an upload request using the shared manager instance for the specified URL request and file. - parameter URLRequest: The URL request. - parameter file: The file to upload. - returns: The created upload request. */ func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request { return Manager.sharedInstance.upload(URLRequest, file: file) } // MARK: Data /** Creates an upload request using the shared manager instance for the specified method, URL string, and data. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter headers: The HTTP headers. `nil` by default. - parameter data: The data to upload. - returns: The created upload request. */ func upload( method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil, data: NSData) -> Request { return Manager.sharedInstance.upload(method, URLString, headers: headers, data: data) } /** Creates an upload request using the shared manager instance for the specified URL request and data. - parameter URLRequest: The URL request. - parameter data: The data to upload. - returns: The created upload request. */ func upload(URLRequest: URLRequestConvertible, data: NSData) -> Request { return Manager.sharedInstance.upload(URLRequest, data: data) } // MARK: Stream /** Creates an upload request using the shared manager instance for the specified method, URL string, and stream. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter headers: The HTTP headers. `nil` by default. - parameter stream: The stream to upload. - returns: The created upload request. */ func upload( method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil, stream: NSInputStream) -> Request { return Manager.sharedInstance.upload(method, URLString, headers: headers, stream: stream) } /** Creates an upload request using the shared manager instance for the specified URL request and stream. - parameter URLRequest: The URL request. - parameter stream: The stream to upload. - returns: The created upload request. */ func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> Request { return Manager.sharedInstance.upload(URLRequest, stream: stream) } // MARK: MultipartFormData /** Creates an upload request using the shared manager instance for the specified method and URL string. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter headers: The HTTP headers. `nil` by default. - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. `MultipartFormDataEncodingMemoryThreshold` by default. - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. */ func upload( method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil, multipartFormData: MultipartFormData -> Void, encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold, encodingCompletion: (Manager.MultipartFormDataEncodingResult -> Void)?) { return Manager.sharedInstance.upload( method, URLString, headers: headers, multipartFormData: multipartFormData, encodingMemoryThreshold: encodingMemoryThreshold, encodingCompletion: encodingCompletion ) } /** Creates an upload request using the shared manager instance for the specified method and URL string. - parameter URLRequest: The URL request. - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. `MultipartFormDataEncodingMemoryThreshold` by default. - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. */ func upload( URLRequest: URLRequestConvertible, multipartFormData: MultipartFormData -> Void, encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold, encodingCompletion: (Manager.MultipartFormDataEncodingResult -> Void)?) { return Manager.sharedInstance.upload( URLRequest, multipartFormData: multipartFormData, encodingMemoryThreshold: encodingMemoryThreshold, encodingCompletion: encodingCompletion ) } // MARK: - Download Methods // MARK: URL Request /** Creates a download request using the shared manager instance for the specified method and URL string. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter parameters: The parameters. `nil` by default. - parameter encoding: The parameter encoding. `.URL` by default. - parameter headers: The HTTP headers. `nil` by default. - parameter destination: The closure used to determine the destination of the downloaded file. - returns: The created download request. */ func download( method: Method, _ URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL, headers: [String: String]? = nil, destination: Request.DownloadFileDestination) -> Request { return Manager.sharedInstance.download( method, URLString, parameters: parameters, encoding: encoding, headers: headers, destination: destination ) } /** Creates a download request using the shared manager instance for the specified URL request. - parameter URLRequest: The URL request. - parameter destination: The closure used to determine the destination of the downloaded file. - returns: The created download request. */ func download(URLRequest: URLRequestConvertible, destination: Request.DownloadFileDestination) -> Request { return Manager.sharedInstance.download(URLRequest, destination: destination) } // MARK: Resume Data /** Creates a request using the shared manager instance for downloading from the resume data produced from a previous request cancellation. - parameter resumeData: The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask` when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional information. - parameter destination: The closure used to determine the destination of the downloaded file. - returns: The created download request. */ func download(resumeData data: NSData, destination: Request.DownloadFileDestination) -> Request { return Manager.sharedInstance.download(data, destination: destination) }
mit
993d42a6b1624e43bdc53c388ab5974e
32.133152
118
0.705979
5.023898
false
false
false
false
hakota/Sageru
Sageru/Sageru.swift
1
11566
// // Sageru.swift // Sageru // // Created by ArakiKenta on 2016/11/06. // Copyright © 2016年 Araki Kenta. All rights reserved. // import UIKit // MARK: - SageruDelegate - public protocol SageruDelegate: NSObjectProtocol { func didChangeSageruState(sageru: Sageru, state: SageruState) func didSelectCell(tableView: UITableView, indexPath: IndexPath) } // MARK: - State and Enums - public enum SageruState { case shown case closed case pulling } fileprivate struct SageruColor { static let white = UIColor.rgb(r: 250, g: 250, b: 250, alpha: 1) static let black = UIColor.rgb(r: 10, g: 10, b: 10, alpha: 1) static let orange = UIColor.rgb(r: 231, g: 114, b: 48, alpha: 1) } public struct Badge { public var cellIndex: Int = 0 public var count: Int = 0 public var badgePattern: BadgePattern = .new public init(cellIndex: Int, count: Int, badgePattern: BadgePattern = .new) { self.cellIndex = cellIndex self.count = count self.badgePattern = badgePattern } } open class Sageru: UIView { // MARK: - fileprivate settings - fileprivate let startIndex = 1 fileprivate var currentState: SageruState = .closed { didSet { self.delegate?.didChangeSageruState(sageru: self, state: currentState) } } fileprivate var contentController: UIViewController? fileprivate var screenHeight: CGFloat = UIScreen.main.bounds.height fileprivate var screenWidth: CGFloat = UIScreen.main.bounds.width fileprivate var backImageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill imageView.backgroundColor = UIColor.clear return imageView }() // MARK: - open settings - // delegate weak open var delegate: SageruDelegate? // authorization open var panGestureEnable = true open var cellBottomLineEnable = true // color open var textColor: UIColor = SageruColor.white open var menuBackgroundColor: UIColor = SageruColor.black open var selectCellLineColor: UIColor = SageruColor.orange // font open var titleFont: UIFont = UIFont(name: "HelveticaNeue-Light", size: 18)! open var bounceOffset: CGFloat = 0 open var animationDuration: TimeInterval = 0.3 // table and cell open var sageruTableView: UITableView? open var selectedIndex: Int = 1 open var cellHeight: CGFloat = 40 open var headerHeight: CGFloat = 30 open var contents: [SageruContent] = [] open var backgroundImage: UIImage? { didSet { backImageView.image = backgroundImage } } open var height: CGFloat = 400 { didSet { frame.size.height = height sageruTableView?.frame = frame } } override open var backgroundColor: UIColor? { didSet { UIApplication.shared.delegate?.window??.backgroundColor = backgroundColor } } open var badges: [Badge] = [Badge(cellIndex:0, count:0)] open var badgeMaxLimit: Int = 100 // MARK: - initialize - override public init(frame: CGRect) { super.init(frame: frame) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public init(contents: [SageruContent], parentController: UIViewController) { self.init() self.contents = contents height = screenHeight - 80 frame = CGRect(x: 0, y: 0, width: screenWidth, height: height) contentController = parentController sageruTableView = UITableView(frame: frame) sageruTableView?.delegate = self sageruTableView?.dataSource = self sageruTableView?.showsVerticalScrollIndicator = false sageruTableView?.separatorColor = UIColor.clear sageruTableView?.backgroundColor = UIColor.clear addSubview(backImageView) addSubview(sageruTableView!) if panGestureEnable { let panGesture = UIPanGestureRecognizer(target: self, action: #selector(Sageru.panGestureEvent(on:))) contentController?.view.addGestureRecognizer(panGesture) } UIApplication.shared.delegate?.window??.rootViewController = contentController UIApplication.shared.delegate?.window??.insertSubview(self, at: 0) UIApplication.shared.delegate?.window??.backgroundColor = menuBackgroundColor } open override func layoutSubviews() { frame = CGRect(x: 0, y: 0, width: screenWidth, height: height) backImageView.frame = frame sageruTableView?.frame = frame contentController?.view.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight) } open func show() { switch currentState { case .shown, .pulling: close() case .closed: open() } } // MARK: - events - open func panGestureEvent(on panGesture: UIPanGestureRecognizer) { if !panGestureEnable { return } guard let panView = panGesture.view, let parentPanView = panView.superview, var viewCenter = panGesture.view?.center, let contentController = contentController else { return } if panGesture.state == .began || panGesture.state == .changed { let translation = panGesture.translation(in: parentPanView) if viewCenter.y >= screenHeight/2 && viewCenter.y <= (screenHeight/2 + height) - bounceOffset { currentState = .pulling viewCenter.y = abs(viewCenter.y + translation.y) if viewCenter.y >= screenHeight/2 && viewCenter.y <= (screenHeight/2 + height) - bounceOffset { contentController.view.center = viewCenter } panGesture.setTranslation(CGPoint.zero, in: contentController.view) } } else if panGesture.state == .ended { if viewCenter.y > contentController.view.frame.size.height { open() } else { close() } } } fileprivate func open(animated: Bool = true, completion: (() -> Void)? = nil) { if currentState == .shown { return } guard let x = contentController?.view.center.x else { return } if animated { UIView.animate(withDuration: animationDuration, animations: { self.contentController?.view.center = CGPoint(x: x, y: self.screenHeight/2 + self.height) }, completion: { _ in UIView.animate(withDuration: self.animationDuration, animations: { self.contentController?.view.center = CGPoint(x: x, y: self.screenHeight/2 + self.height - self.bounceOffset) }, completion: { _ in self.currentState = .shown completion?() }) }) } else { contentController?.view.center = CGPoint(x: x, y: screenHeight/2 + height) currentState = .shown completion?() } } fileprivate func close(animated: Bool = true, completion: (() -> Void)? = nil) { guard let center = contentController?.view.center else { return } if animated { UIView.animate(withDuration: animationDuration, animations: { self.contentController?.view.center = CGPoint(x: center.x, y: center.y + self.bounceOffset) }, completion: { _ in UIView.animate(withDuration: self.animationDuration, animations: { self.contentController?.view.center = CGPoint(x: center.x, y: self.screenHeight/2) }, completion: { _ in self.currentState = .closed completion?() }) }) } else { contentController?.view.center = CGPoint(x: center.x, y: screenHeight/2) currentState = .closed completion?() } } } // MARK: - SageruTableView DataSource and Delegate - extension Sageru: UITableViewDataSource { public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return contents.count + 1 } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = SageruTableViewCell(style: .default, reuseIdentifier: "SageruCell") cell.backgroundColor = UIColor.clear cell.selectionStyle = .none cell.titleLabel.textColor = textColor cell.selectLine.backgroundColor = selectedIndex == indexPath.row ? selectCellLineColor : UIColor.clear cell.titleLabel.font = titleFont cell.textLabel?.textAlignment = .left if !cellBottomLineEnable { cell.bottomLine.backgroundColor = UIColor.clear } let content: SageruContent? if indexPath.row >= startIndex && indexPath.row <= (contents.count - 1 + startIndex) { content = contents[indexPath.row - startIndex] cell.titleLabel.text = content?.title cell.cellImage.image = content?.image?.withRenderingMode(.alwaysTemplate) } for badge in badges { if badge.cellIndex == indexPath.row { cell.setBadgeValue(value: badge.count, maxValue: badgeMaxLimit, limitOver: badge.badgePattern) } } return cell } } extension Sageru: UITableViewDelegate { public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.row < startIndex || indexPath.row > contents.count - 1 + startIndex { return } selectedIndex = indexPath.row tableView.reloadData() let selectedItem = contents[indexPath.row - startIndex] self.delegate?.didSelectCell(tableView: tableView, indexPath: indexPath) close(completion: selectedItem.completion) } public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let view = UIView(frame: CGRect(x: 0, y: 0, width: frame.width, height: 30)) view.backgroundColor = UIColor.clear return view } public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return headerHeight } public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return cellHeight } } // MARK: - Extention UIColor RGB - extension UIColor { class func rgb(r: Int, g: Int, b: Int, alpha: CGFloat) -> UIColor{ return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: alpha) } } // MARK: - Extention UINavigationBar sizeThatFits - extension UINavigationBar { open override func sizeThatFits(_ size: CGSize) -> CGSize { self.setBackgroundImage(UIImage(), for: .default) self.shadowImage = UIImage() self.center = CGPoint(x: self.center.x, y: self.frame.height-2) return CGSize(width: UIScreen.main.bounds.size.width, height: 44) } }
mit
fe3f191b138a6226066512f963d4932c
33.933535
129
0.609271
4.80191
false
false
false
false