repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
eligreg/ExhibitionSwift
ExhibitionSwift/Classes/ExhibitionDownloader.swift
1
1153
// // ExhibitionDownloader.swift // Exhibition // // Created by Eli Gregory on 12/27/16. // Copyright © 2016 Eli Gregory. All rights reserved. // import Foundation public typealias XDownloaderProtocol = ExhibitionDownloaderProtocol public protocol ExhibitionDownloaderProtocol { func downloadImage(image: ExhibitionImageProtocol, results: @escaping ((UIImage?, Error?)->())) } public typealias XDownloader = ExhibitionDownloader public class ExhibitionDownloader: ExhibitionDownloaderProtocol { public func downloadImage(image: ExhibitionImageProtocol, results: @escaping ((UIImage?, Error?)->())) { guard let url = image.url else { return } let imageRequest: URLRequest = URLRequest(url: url) let task = URLSession.shared.dataTask(with: imageRequest, completionHandler: { data, response, error in if let data = data { let img = UIImage(data: data) results(img, error) } else { results(nil, error) } }) task.resume() } }
mit
82e16a52b232242edb1f98cc5b418a9a
26.428571
111
0.614583
4.702041
false
false
false
false
yume190/JSONDecodeKit
Test/model/Recording.swift
1
976
// // Recording.swift // JSONShootout // // Created by Bart Whiteley on 5/17/16. // Copyright © 2016 Bart Whiteley. All rights reserved. // import Foundation @testable import JSONDecodeKit public struct Recording{ enum Status: String { case None = "0" case Recorded = "-3" case Recording = "-2" case Unknown } enum RecGroup: String { case Deleted = "Deleted" case Default = "Default" case LiveTV = "LiveTV" case Unknown } // Date parsing is slow. Remove dates to better measure performance. // let startTs:NSDate? // let endTs:NSDate? let startTsStr:String // let status:Status let recordId:String // let recGroup:RecGroup } extension Recording: JSONDecodable { public static func decode(json: JSON) throws -> Recording { return try Recording( startTsStr: json <| "StartTs", recordId: json <| "RecordId" ) } }
mit
e3b406f8fa7dc0d865505162e7990e26
21.674419
68
0.608205
3.963415
false
false
false
false
JBerendes/react-native-video-processing
ios/RNVideoProcessing/RNVideoTrimmer/RNVideoTrimmer.swift
1
18601
// // RNVideoTrimmer.swift // RNVideoProcessing // import Foundation import AVFoundation enum QUALITY_ENUM: String { case QUALITY_LOW = "low" case QUALITY_MEDIUM = "medium" case QUALITY_HIGHEST = "highest" case QUALITY_640x480 = "640x480" case QUALITY_960x540 = "960x540" case QUALITY_1280x720 = "1280x720" case QUALITY_1920x1080 = "1920x1080" case QUALITY_3840x2160 = "3840x2160" case QUALITY_PASS_THROUGH = "passthrough" } @objc(RNVideoTrimmer) class RNVideoTrimmer: NSObject { @objc func getVideoOrientationFromAsset(asset : AVAsset) -> UIImageOrientation { let videoTrack: AVAssetTrack? = asset.tracks(withMediaType: AVMediaTypeVideo)[0] let size = videoTrack!.naturalSize let txf: CGAffineTransform = videoTrack!.preferredTransform if (size.width == txf.tx && size.height == txf.ty) { return UIImageOrientation.left; } else if (txf.tx == 0 && txf.ty == 0) { return UIImageOrientation.right; } else if (txf.tx == 0 && txf.ty == size.width) { return UIImageOrientation.down; } else { return UIImageOrientation.up; } } @objc func crop(_ source: String, options: NSDictionary, callback: @escaping RCTResponseSenderBlock) { let cropOffsetXInt = options.object(forKey: "cropOffsetX") as! Int let cropOffsetYInt = options.object(forKey: "cropOffsetY") as! Int let cropWidthInt = options.object(forKey: "cropWidth") as? Int let cropHeightInt = options.object(forKey: "cropHeight") as? Int if ( cropWidthInt == nil ) { callback(["Invalid cropWidth", NSNull()]) return } if ( cropHeightInt == nil ) { callback(["Invalid cropHeight", NSNull()]) return } let cropOffsetX : CGFloat = CGFloat(cropOffsetXInt); let cropOffsetY : CGFloat = CGFloat(cropOffsetYInt); var cropWidth : CGFloat = CGFloat(cropWidthInt!); var cropHeight : CGFloat = CGFloat(cropHeightInt!); let quality = ((options.object(forKey: "quality") as? String) != nil) ? options.object(forKey: "quality") as! String : "" let sourceURL = getSourceURL(source: source) let asset = AVAsset(url: sourceURL as URL) let fileName = ProcessInfo.processInfo.globallyUniqueString let outputURL = "\(NSTemporaryDirectory())\(fileName).mp4" let useQuality = getQualityForAsset(quality: quality, asset: asset) print("RNVideoTrimmer passed quality: \(quality). useQuality: \(useQuality)") guard let exportSession = AVAssetExportSession(asset: asset, presetName: useQuality) else { callback(["Error creating AVAssetExportSession", NSNull()]) return } exportSession.outputURL = NSURL.fileURL(withPath: outputURL) exportSession.outputFileType = AVFileTypeMPEG4 exportSession.shouldOptimizeForNetworkUse = true let videoComposition = AVMutableVideoComposition(propertiesOf: asset) let clipVideoTrack: AVAssetTrack! = asset.tracks(withMediaType: AVMediaTypeVideo)[0] let videoOrientation = self.getVideoOrientationFromAsset(asset: asset) let videoWidth : CGFloat let videoHeight : CGFloat if ( videoOrientation == UIImageOrientation.up || videoOrientation == UIImageOrientation.down ) { videoWidth = clipVideoTrack.naturalSize.height videoHeight = clipVideoTrack.naturalSize.width } else { videoWidth = clipVideoTrack.naturalSize.width videoHeight = clipVideoTrack.naturalSize.height } videoComposition.frameDuration = CMTimeMake(1, 30) while( cropWidth.truncatingRemainder(dividingBy: 2) > 0 && cropWidth < videoWidth ) { cropWidth += 1.0 } while( cropWidth.truncatingRemainder(dividingBy: 2) > 0 && cropWidth > 0.0 ) { cropWidth -= 1.0 } while( cropHeight.truncatingRemainder(dividingBy: 2) > 0 && cropHeight < videoHeight ) { cropHeight += 1.0 } while( cropHeight.truncatingRemainder(dividingBy: 2) > 0 && cropHeight > 0.0 ) { cropHeight -= 1.0 } videoComposition.renderSize = CGSize(width: cropWidth, height: cropHeight) let instruction : AVMutableVideoCompositionInstruction = AVMutableVideoCompositionInstruction() instruction.timeRange = CMTimeRange(start: kCMTimeZero, end: asset.duration) var t1 = CGAffineTransform.identity var t2 = CGAffineTransform.identity let transformer = AVMutableVideoCompositionLayerInstruction(assetTrack: clipVideoTrack) switch videoOrientation { case UIImageOrientation.up: t1 = CGAffineTransform(translationX: clipVideoTrack.naturalSize.height - cropOffsetX, y: 0 - cropOffsetY ); t2 = t1.rotated(by: CGFloat(M_PI_2) ); break; case UIImageOrientation.left: t1 = CGAffineTransform(translationX: clipVideoTrack.naturalSize.width - cropOffsetX, y: clipVideoTrack.naturalSize.height - cropOffsetY ); t2 = t1.rotated(by: CGFloat(M_PI) ); break; case UIImageOrientation.right: t1 = CGAffineTransform(translationX: 0 - cropOffsetX, y: 0 - cropOffsetY ); t2 = t1.rotated(by: 0); break; case UIImageOrientation.down: t1 = CGAffineTransform(translationX: 0 - cropOffsetX, y: clipVideoTrack.naturalSize.width - cropOffsetY ); // not fixed width is the real height in upside down t2 = t1.rotated(by: -(CGFloat)(M_PI_2) ); break; default: NSLog("no supported orientation has been found in this video"); break; } let finalTransform: CGAffineTransform = t2 transformer.setTransform(finalTransform, at: kCMTimeZero) instruction.layerInstructions = [transformer] videoComposition.instructions = [instruction] exportSession.videoComposition = videoComposition exportSession.exportAsynchronously { switch exportSession.status { case .completed: callback( [NSNull(), outputURL] ) case .failed: callback( ["Failed: \(exportSession.error)", NSNull()] ) case .cancelled: callback( ["Cancelled: \(exportSession.error)", NSNull()] ) default: break } } } @objc func trim(_ source: String, options: NSDictionary, callback: @escaping RCTResponseSenderBlock) { var sTime = options.object(forKey: "startTime") as? Float var eTime = options.object(forKey: "endTime") as? Float let quality = ((options.object(forKey: "quality") as? String) != nil) ? options.object(forKey: "quality") as! String : "" let saveToCameraRoll = options.object(forKey: "saveToCameraRoll") as? Bool ?? false let saveWithCurrentDate = options.object(forKey: "saveWithCurrentDate") as? Bool ?? false let manager = FileManager.default guard let documentDirectory = try? manager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) else { callback(["Error creating FileManager", NSNull()]) return } let sourceURL = getSourceURL(source: source) let asset = AVAsset(url: sourceURL as URL) if eTime == nil { eTime = Float(asset.duration.seconds) } if sTime == nil { sTime = 0 } var outputURL = documentDirectory.appendingPathComponent("output") do { try manager.createDirectory(at: outputURL, withIntermediateDirectories: true, attributes: nil) let name = randomString() outputURL = outputURL.appendingPathComponent("\(name).mp4") } catch { callback([error.localizedDescription, NSNull()]) print(error) } //Remove existing file _ = try? manager.removeItem(at: outputURL) let useQuality = getQualityForAsset(quality: quality, asset: asset) print("RNVideoTrimmer passed quality: \(quality). useQuality: \(useQuality)") guard let exportSession = AVAssetExportSession(asset: asset, presetName: useQuality) else { callback(["Error creating AVAssetExportSession", NSNull()]) return } exportSession.outputURL = NSURL.fileURL(withPath: outputURL.path) exportSession.outputFileType = AVFileTypeMPEG4 exportSession.shouldOptimizeForNetworkUse = true if saveToCameraRoll && saveWithCurrentDate { let metaItem = AVMutableMetadataItem() metaItem.key = AVMetadataCommonKeyCreationDate as (NSCopying & NSObjectProtocol)? metaItem.keySpace = AVMetadataKeySpaceCommon metaItem.value = NSDate() as (NSCopying & NSObjectProtocol)? exportSession.metadata = [metaItem] } let startTime = CMTime(seconds: Double(sTime!), preferredTimescale: 1000) let endTime = CMTime(seconds: Double(eTime!), preferredTimescale: 1000) let timeRange = CMTimeRange(start: startTime, end: endTime) exportSession.timeRange = timeRange exportSession.exportAsynchronously{ switch exportSession.status { case .completed: callback( [NSNull(), outputURL.absoluteString] ) if saveToCameraRoll { UISaveVideoAtPathToSavedPhotosAlbum(outputURL.relativePath, self, nil, nil) } case .failed: callback( ["Failed: \(exportSession.error)", NSNull()] ) case .cancelled: callback( ["Cancelled: \(exportSession.error)", NSNull()] ) default: break } } } @objc func compress(_ source: String, options: NSDictionary, callback: @escaping RCTResponseSenderBlock) { var width = options.object(forKey: "width") as? Float var height = options.object(forKey: "height") as? Float let bitrateMultiplier = options.object(forKey: "bitrateMultiplier") as? Float ?? 1 let saveToCameraRoll = options.object(forKey: "saveToCameraRoll") as? Bool ?? false let minimumBitrate = options.object(forKey: "minimumBitrate") as? Float let saveWithCurrentDate = options.object(forKey: "saveWithCurrentDate") as? Bool ?? false let removeAudio = options.object(forKey: "removeAudio") as? Bool ?? false let manager = FileManager.default guard let documentDirectory = try? manager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) else { callback(["Error creating FileManager", NSNull()]) return } let sourceURL = getSourceURL(source: source) let asset = AVAsset(url: sourceURL as URL) guard let videoTrack = asset.tracks(withMediaType: AVMediaTypeVideo).first else { callback(["Error getting track info", NSNull()]) return } let naturalSize = videoTrack.naturalSize.applying(videoTrack.preferredTransform) let bps = videoTrack.estimatedDataRate width = width ?? Float(abs(naturalSize.width)) height = height ?? Float(abs(naturalSize.height)) var averageBitrate = bps / bitrateMultiplier if minimumBitrate != nil { if averageBitrate < minimumBitrate! { averageBitrate = minimumBitrate! } if bps < minimumBitrate! { averageBitrate = bps } } var outputURL = documentDirectory.appendingPathComponent("output") do { try manager.createDirectory(at: outputURL, withIntermediateDirectories: true, attributes: nil) let name = randomString() outputURL = outputURL.appendingPathComponent("\(name)-compressed.mp4") } catch { callback([error.localizedDescription, NSNull()]) print(error) } //Remove existing file _ = try? manager.removeItem(at: outputURL) let compressionEncoder = SDAVAssetExportSession(asset: asset) if compressionEncoder == nil { callback(["Error creating AVAssetExportSession", NSNull()]) return } compressionEncoder!.outputFileType = AVFileTypeMPEG4 compressionEncoder!.outputURL = NSURL.fileURL(withPath: outputURL.path) compressionEncoder!.shouldOptimizeForNetworkUse = true if saveToCameraRoll && saveWithCurrentDate { let metaItem = AVMutableMetadataItem() metaItem.key = AVMetadataCommonKeyCreationDate as (NSCopying & NSObjectProtocol)? metaItem.keySpace = AVMetadataKeySpaceCommon metaItem.value = NSDate() as (NSCopying & NSObjectProtocol)? compressionEncoder!.metadata = [metaItem] } compressionEncoder?.videoSettings = [ AVVideoCodecKey: AVVideoCodecH264, AVVideoWidthKey: NSNumber.init(value: width!), AVVideoHeightKey: NSNumber.init(value: height!), AVVideoCompressionPropertiesKey: [ AVVideoAverageBitRateKey: NSNumber.init(value: averageBitrate), AVVideoProfileLevelKey: AVVideoProfileLevelH264HighAutoLevel ] ] if !removeAudio { compressionEncoder?.audioSettings = [ AVFormatIDKey: kAudioFormatMPEG4AAC, AVNumberOfChannelsKey: 1, AVSampleRateKey: 44100, AVEncoderBitRateKey: 128000 ] } compressionEncoder!.exportAsynchronously(completionHandler: { switch compressionEncoder!.status { case .completed: callback( [NSNull(), outputURL.absoluteString] ) if saveToCameraRoll { UISaveVideoAtPathToSavedPhotosAlbum(outputURL.relativePath, self, nil, nil) } case .failed: callback( ["Failed: \(compressionEncoder!.error)", NSNull()] ) case .cancelled: callback( ["Cancelled: \(compressionEncoder!.error)", NSNull()] ) default: break } }) } @objc func getAssetInfo(_ source: String, callback: RCTResponseSenderBlock) { let sourceURL = getSourceURL(source: source) let asset = AVAsset(url: sourceURL) var assetInfo: [String: Any] = [ "duration" : asset.duration.seconds ] if let track = asset.tracks(withMediaType: AVMediaTypeVideo).first { let naturalSize = track.naturalSize let t = track.preferredTransform let isPortrait = t.a == 0 && abs(t.b) == 1 && t.d == 0 let size = [ "width": isPortrait ? naturalSize.height : naturalSize.width, "height": isPortrait ? naturalSize.width : naturalSize.height ] assetInfo["size"] = size } callback( [NSNull(), assetInfo] ) } @objc func getPreviewImageAtPosition(_ source: String, atTime: Float = 0, maximumSize: NSDictionary, format: String = "base64", callback: @escaping RCTResponseSenderBlock) { let sourceURL = getSourceURL(source: source) let asset = AVAsset(url: sourceURL) var width: CGFloat = 1080 if let _width = maximumSize.object(forKey: "width") as? CGFloat { width = _width } var height: CGFloat = 1080 if let _height = maximumSize.object(forKey: "height") as? CGFloat { height = _height } let imageGenerator = AVAssetImageGenerator(asset: asset) imageGenerator.maximumSize = CGSize(width: width, height: height) imageGenerator.appliesPreferredTrackTransform = true var second = atTime if atTime > Float(asset.duration.seconds) || atTime < 0 { second = 0 } let timestamp = CMTime(seconds: Double(second), preferredTimescale: 600) do { let imageRef = try imageGenerator.copyCGImage(at: timestamp, actualTime: nil) let image = UIImage(cgImage: imageRef) if ( format == "base64" ) { let imgData = UIImagePNGRepresentation(image) let base64string = imgData?.base64EncodedString(options: Data.Base64EncodingOptions.init(rawValue: 0)) if base64string != nil { callback( [NSNull(), base64string!] ) } else { callback( ["Unable to convert to base64)", NSNull()] ) } } else if ( format == "JPEG" ) { let imgData = UIImageJPEGRepresentation(image, 1.0) let fileName = ProcessInfo.processInfo.globallyUniqueString let fullPath = "\(NSTemporaryDirectory())\(fileName).jpg" try imgData?.write(to: URL(fileURLWithPath: fullPath), options: .atomic) let imageWidth = imageRef.width let imageHeight = imageRef.height let imageFormattedData: [AnyHashable: Any] = ["uri": fullPath, "width": imageWidth, "height": imageHeight] callback( [NSNull(), imageFormattedData] ) } else { callback( ["Failed format. Expected one of 'base64' or 'JPEG'", NSNull()] ) } } catch { callback( ["Failed to convert base64: \(error.localizedDescription)", NSNull()] ) } } func randomString() -> String { let letters: NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" let randomString: NSMutableString = NSMutableString(capacity: 20) let s:String = "RNTrimmer-Temp-Video" for _ in 0...19 { randomString.appendFormat("%C", letters.character(at: Int(arc4random_uniform(UInt32(letters.length))))) } return s.appending(randomString as String) } func getSourceURL(source: String) -> URL { var sourceURL: URL if source.contains("assets-library") { sourceURL = NSURL(string: source) as! URL } else { let bundleUrl = Bundle.main.resourceURL! sourceURL = URL(string: source, relativeTo: bundleUrl)! } return sourceURL } func getQualityForAsset(quality: String, asset: AVAsset) -> String { var useQuality: String switch quality { case QUALITY_ENUM.QUALITY_LOW.rawValue: useQuality = AVAssetExportPresetLowQuality case QUALITY_ENUM.QUALITY_MEDIUM.rawValue: useQuality = AVAssetExportPresetMediumQuality case QUALITY_ENUM.QUALITY_HIGHEST.rawValue: useQuality = AVAssetExportPresetHighestQuality case QUALITY_ENUM.QUALITY_640x480.rawValue: useQuality = AVAssetExportPreset640x480 case QUALITY_ENUM.QUALITY_960x540.rawValue: useQuality = AVAssetExportPreset960x540 case QUALITY_ENUM.QUALITY_1280x720.rawValue: useQuality = AVAssetExportPreset1280x720 case QUALITY_ENUM.QUALITY_1920x1080.rawValue: useQuality = AVAssetExportPreset1920x1080 case QUALITY_ENUM.QUALITY_3840x2160.rawValue: if #available(iOS 9.0, *) { useQuality = AVAssetExportPreset3840x2160 } else { useQuality = AVAssetExportPresetPassthrough } default: useQuality = AVAssetExportPresetPassthrough } let compatiblePresets = AVAssetExportSession.exportPresets(compatibleWith: asset) if !compatiblePresets.contains(useQuality) { useQuality = AVAssetExportPresetPassthrough } return useQuality } }
mit
e834297bba0f142ecd1dc063f57fafa3
36.730223
175
0.670555
4.668926
false
false
false
false
TheTekton/Malibu
Sources/Request/Message.swift
1
655
import Foundation public struct Message: Equatable { public var resource: URLStringConvertible public var parameters: [String: AnyObject] public var headers: [String: String] public init(resource: URLStringConvertible, parameters: [String: AnyObject] = [:], headers: [String: String] = [:]) { self.resource = resource self.parameters = parameters self.headers = headers } } public func ==(lhs: Message, rhs: Message) -> Bool { return lhs.resource.URLString == rhs.resource.URLString && (lhs.parameters as NSDictionary).isEqual(rhs.parameters as NSDictionary) && lhs.headers == rhs.headers }
mit
d5757b3e94001e0cad85dd2036fa0603
28.772727
79
0.683969
4.517241
false
false
false
false
exercism/xswift
exercises/pascals-triangle/Tests/PascalsTriangleTests/PascalsTriangleTests.swift
3
1665
import XCTest @testable import PascalsTriangle private extension XCTest { func XCTAssertEqualMultiArray(_ aArray1: [[Int]], _ aArray2: [[Int]]) { XCTAssertEqual(Array(aArray1.joined()), Array(aArray2.joined())) } } class PascalsTriangleTests: XCTestCase { func testOneRow() { let triangle = PascalsTriangle(1) XCTAssertEqualMultiArray([[1]], triangle.rows) } func testTwoRows() { let triangle = PascalsTriangle(2) XCTAssertEqualMultiArray([[1], [1, 1]], triangle.rows) } func testThreeRows() { let triangle = PascalsTriangle(3) XCTAssertEqualMultiArray([[1], [1, 1], [1, 2, 1]], triangle.rows) } func testFourthRow() { let triangle = PascalsTriangle(4) XCTAssertEqual([1, 3, 3, 1], triangle.rows.last!) } func testFifthRow() { let triangle = PascalsTriangle(5) XCTAssertEqual([1, 4, 6, 4, 1], triangle.rows.last!) } func testTwentiethRow() { let triangle = PascalsTriangle(20) let expected = [ 1, 19, 171, 969, 3876, 11_628, 27_132, 50_388, 75_582, 92_378, 92_378, 75_582, 50_388, 27_132, 11_628, 3876, 969, 171, 19, 1 ] XCTAssertEqual(expected, triangle.rows.last!) } static var allTests: [(String, (PascalsTriangleTests) -> () throws -> Void)] { return [ ("testOneRow", testOneRow), ("testTwoRows", testTwoRows), ("testThreeRows", testThreeRows), ("testFourthRow", testFourthRow), ("testFifthRow", testFifthRow), ("testTwentiethRow", testTwentiethRow), ] } }
mit
0256c724ce006b7c318411aef109517d
29.272727
82
0.587988
3.77551
false
true
false
false
AlucarDWeb/Weather
Weather/controller/ForecastUIViewController.swift
1
3442
// // ForecastUIViewController.swift // Weather // // // Copyright © 2017 Ferdinando Furci. All rights reserved. // import UIKit // MARK: UICollectionViewDataSource extension ForecastUIViewController { func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return self.forecastCollectionView.frame.size; } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if let forecast = getForecast() { return forecast.forecastList.count }else { return 0 } } /** Parsing the forecast object model and binding it to collection view cells */ func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! ForecastCell if let forecast = getForecast() { let viewModel = ForecastViewModel(dataModel: forecast, index: indexPath.row) cell.dayLabel.text = viewModel.dayText cell.conditionLabel.text = viewModel.conditionText cell.temperatureLabel.text = viewModel.temperatureText cell.forecastImage.image = UIImage(named:viewModel.weatherImageName) } return cell } } // MARK: UICollectionViewDelegate extension ForecastUIViewController { func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool { return true } } // MARK: getForecast extension ForecastUIViewController { /** Function that gets the forecast entity from the TabBarController - returns: the optional parsed forecast model */ func getForecast()-> ForecastModel? { return self.tempDataModel } } private let reuseIdentifier = "ForecastCell" // MARK: ForecastUIViewController class ForecastUIViewController: BaseViewController,UICollectionViewDataSource,UICollectionViewDelegate { @IBOutlet weak var forecastCollectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() DataProvider.sharedInstance.requestForecast() } override func viewWillAppear(_ animated: Bool) { reloadData() } override func viewDidAppear(_ animated: Bool) { self.navigationController?.navigationBar.topItem?.title = (getForecast()?.cityName ?? "Forecast") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } /** Function that reloads the collectionView Data */ func reloadData() { if getForecast() != nil { self.forecastCollectionView.reloadData() } } }
apache-2.0
0f695e318712713fe045428aa22cd6fc
22.09396
160
0.598663
6.431776
false
false
false
false
vmanot/swift-package-manager
Sources/Utility/Platform.swift
1
2366
/* 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 http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import Basic public enum Platform { case darwin case linux(LinuxFlavor) public enum LinuxFlavor { case debian } // Lazily return current platform. public static var currentPlatform = Platform.findCurrentPlatform() private static func findCurrentPlatform() -> Platform? { guard let uname = try? Process.checkNonZeroExit(args: "uname").chomp().lowercased() else { return nil } switch uname { case "darwin": return .darwin case "linux": if isFile(AbsolutePath("/etc/debian_version")) { return .linux(.debian) } default: return nil } return nil } /// Returns the cache directories used in Darwin. public static func darwinCacheDirectories() -> [AbsolutePath] { if let value = Platform._darwinCacheDirectories { return value } var directories = [AbsolutePath]() // Compute the directories. directories.append(AbsolutePath("/private/var/tmp")) directories.append(Basic.determineTempDirectory()) getconfPath(forVariable: "DARWIN_USER_TEMP_DIR").map({ directories.append($0) }) getconfPath(forVariable: "DARWIN_USER_CACHE_DIR").map({ directories.append($0) }) Platform._darwinCacheDirectories = directories return directories } private static var _darwinCacheDirectories: [AbsolutePath]? /// Returns the value of given path variable using `getconf` utility. /// /// Note: This method returns `nil` if the value is an invalid path. private static func getconfPath(forVariable variable: String) -> AbsolutePath? { do { let value = try Process.checkNonZeroExit(args: "getconf", variable).chomp() // Value must be a valid path. guard value.hasSuffix(AbsolutePath.root.asString) else { return nil } return resolveSymlinks(AbsolutePath(value)) } catch { return nil } } }
apache-2.0
c6d0d1726cd9928d7eba87cc6c67f4d4
34.313433
111
0.64497
4.789474
false
false
false
false
benlangmuir/swift
stdlib/public/core/Random.swift
4
6929
//===--- Random.swift -----------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 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 // //===----------------------------------------------------------------------===// import SwiftShims /// A type that provides uniformly distributed random data. /// /// When you call methods that use random data, such as creating new random /// values or shuffling a collection, you can pass a `RandomNumberGenerator` /// type to be used as the source for randomness. When you don't pass a /// generator, the default `SystemRandomNumberGenerator` type is used. /// /// When providing new APIs that use randomness, provide a version that accepts /// a generator conforming to the `RandomNumberGenerator` protocol as well as a /// version that uses the default system generator. For example, this `Weekday` /// enumeration provides static methods that return a random day of the week: /// /// enum Weekday: CaseIterable { /// case sunday, monday, tuesday, wednesday, thursday, friday, saturday /// /// static func random<G: RandomNumberGenerator>(using generator: inout G) -> Weekday { /// return Weekday.allCases.randomElement(using: &generator)! /// } /// /// static func random() -> Weekday { /// var g = SystemRandomNumberGenerator() /// return Weekday.random(using: &g) /// } /// } /// /// Conforming to the RandomNumberGenerator Protocol /// ================================================ /// /// A custom `RandomNumberGenerator` type can have different characteristics /// than the default `SystemRandomNumberGenerator` type. For example, a /// seedable generator can be used to generate a repeatable sequence of random /// values for testing purposes. /// /// To make a custom type conform to the `RandomNumberGenerator` protocol, /// implement the required `next()` method. Each call to `next()` must produce /// a uniform and independent random value. /// /// Types that conform to `RandomNumberGenerator` should specifically document /// the thread safety and quality of the generator. public protocol RandomNumberGenerator { /// Returns a value from a uniform, independent distribution of binary data. /// /// Use this method when you need random binary data to generate another /// value. If you need an integer value within a specific range, use the /// static `random(in:using:)` method on that integer type instead of this /// method. /// /// - Returns: An unsigned 64-bit random value. mutating func next() -> UInt64 } extension RandomNumberGenerator { // An unavailable default implementation of next() prevents types that do // not implement the RandomNumberGenerator interface from conforming to the // protocol; without this, the default next() method returning a generic // unsigned integer will be used, recursing infinitely and probably blowing // the stack. @available(*, unavailable) @_alwaysEmitIntoClient public mutating func next() -> UInt64 { fatalError() } /// Returns a value from a uniform, independent distribution of binary data. /// /// Use this method when you need random binary data to generate another /// value. If you need an integer value within a specific range, use the /// static `random(in:using:)` method on that integer type instead of this /// method. /// /// - Returns: A random value of `T`. Bits are randomly distributed so that /// every value of `T` is equally likely to be returned. @inlinable public mutating func next<T: FixedWidthInteger & UnsignedInteger>() -> T { return T._random(using: &self) } /// Returns a random value that is less than the given upper bound. /// /// Use this method when you need random binary data to generate another /// value. If you need an integer value within a specific range, use the /// static `random(in:using:)` method on that integer type instead of this /// method. /// /// - Parameter upperBound: The upper bound for the randomly generated value. /// Must be non-zero. /// - Returns: A random value of `T` in the range `0..<upperBound`. Every /// value in the range `0..<upperBound` is equally likely to be returned. @inlinable public mutating func next<T: FixedWidthInteger & UnsignedInteger>( upperBound: T ) -> T { _precondition(upperBound != 0, "upperBound cannot be zero.") // We use Lemire's "nearly divisionless" method for generating random // integers in an interval. For a detailed explanation, see: // https://arxiv.org/abs/1805.10941 var random: T = next() var m = random.multipliedFullWidth(by: upperBound) if m.low < upperBound { let t = (0 &- upperBound) % upperBound while m.low < t { random = next() m = random.multipliedFullWidth(by: upperBound) } } return m.high } } /// The system's default source of random data. /// /// When you generate random values, shuffle a collection, or perform another /// operation that depends on random data, this type is the generator used by /// default. For example, the two method calls in this example are equivalent: /// /// let x = Int.random(in: 1...100) /// var g = SystemRandomNumberGenerator() /// let y = Int.random(in: 1...100, using: &g) /// /// `SystemRandomNumberGenerator` is automatically seeded, is safe to use in /// multiple threads, and uses a cryptographically secure algorithm whenever /// possible. /// /// Platform Implementation of `SystemRandomNumberGenerator` /// ======================================================== /// /// While the system generator is automatically seeded and thread-safe on every /// platform, the cryptographic quality of the stream of random data produced by /// the generator may vary. For more detail, see the documentation for the APIs /// used by each platform. /// /// - Apple platforms use `arc4random_buf(3)`. /// - Linux platforms use `getrandom(2)` when available; otherwise, they read /// from `/dev/urandom`. /// - Windows uses `BCryptGenRandom`. @frozen public struct SystemRandomNumberGenerator: RandomNumberGenerator, Sendable { /// Creates a new instance of the system's default random number generator. @inlinable public init() { } /// Returns a value from a uniform, independent distribution of binary data. /// /// - Returns: An unsigned 64-bit random value. @inlinable public mutating func next() -> UInt64 { var random: UInt64 = 0 _withUnprotectedUnsafeMutablePointer(to: &random) { swift_stdlib_random($0, MemoryLayout<UInt64>.size) } return random } }
apache-2.0
2d1860d8cfa75589d6ba185f169d7b85
40.740964
95
0.675711
4.622415
false
false
false
false
mflint/ios-tldr-viewer
tldr-viewer/InfoViewModel.swift
1
5707
// // InfoViewModel.swift // tldr-viewer // // Created by Matthew Flint on 02/01/2016. // Copyright © 2016 Green Light. All rights reserved. // import UIKit class InfoViewModel { var groupViewModels = [GroupViewModel]() init() { updateCellViewModels() } private func updateCellViewModels() { var groups = [GroupViewModel]() groups.append(GroupViewModel(groupTitle: Localizations.Info.About.Header, cellViewModels:[aboutCell(), versionCell(), authorCell()])) groups.append(GroupViewModel(groupTitle: Localizations.Info.Contact.Header, cellViewModels: [leaveReview(), bugReports(), contactCell()])) groups.append(GroupViewModel(groupTitle: Localizations.Info.OpenSource.Header, cellViewModels: [forkMe()])) groups.append(GroupViewModel(groupTitle: Localizations.Info.Thanks.Header, cellViewModels: [thanks1(), thanks2(), thanks3(), thanks4(), thanks5()])) groupViewModels = groups } private func aboutCell() -> BaseCellViewModel { let message = attributedString(text: Localizations.Info.About.Message, anchors: [Localizations.Info.About.LinkAnchor, Localizations.Info.About.ContributionAnchor], urls: ["http://tldr-pages.github.io", "https://github.com/tldr-pages/tldr/blob/master/CONTRIBUTING.md"]) return TextCellViewModel(attributedText: message) } private func versionCell() -> BaseCellViewModel { let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String return TextCellViewModel(text: Localizations.Info.Version.Title, detailText: Localizations.Info.Version.Detail(version)) } private func authorCell() -> BaseCellViewModel { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy" let year = dateFormatter.string(from: Date()) return TextCellViewModel(text: Localizations.Info.Author.Title, detailText: Localizations.Info.Author.Detail(year)) } private func leaveReview() -> BaseCellViewModel { let message = attributedString(text: Localizations.Info.LeaveReview.Message, anchors: [Localizations.Info.LeaveReview.LinkAnchor], urls: ["https://itunes.apple.com/gb/app/tldr-pages/id1071725095?mt=8"]) return TextCellViewModel(attributedText: message) } private func bugReports() -> BaseCellViewModel { let message = attributedString(text: Localizations.Info.BugReports.Message, anchors: [Localizations.Info.BugReports.LinkAnchor], urls: ["https://github.com/mflint/ios-tldr-viewer/issues"]) return TextCellViewModel(attributedText: message) } private func contactCell() -> BaseCellViewModel { let message = attributedString(text: Localizations.Info.Contact.Message, anchors: [Localizations.Info.Contact.Email.LinkAnchor, Localizations.Info.Contact.Twitter.LinkAnchor], urls: [NSURL(string: "mailto:[email protected]")!, "https://twitter.com/intent/tweet?text=@mkflint%20"]) return TextCellViewModel(attributedText: message) } private func thanks1() -> BaseCellViewModel { let message = attributedString(text: Localizations.Info.Thanks.TldrPages.Message, anchors: [Localizations.Info.Thanks.TldrPages.LinkAnchor], urls: ["https://github.com/tldr-pages/tldr"]) return TextCellViewModel(attributedText: message) } private func thanks2() -> BaseCellViewModel { let message = attributedString(text: Localizations.Info.Thanks.DownLibrary.Message, anchors: [Localizations.Info.Thanks.DownLibrary.LinkAnchor1, Localizations.Info.Thanks.DownLibrary.LinkAnchor2], urls: ["https://github.com/iwasrobbed/Down", "https://github.com/commonmark/cmark"]) return TextCellViewModel(attributedText: message) } private func thanks3() -> BaseCellViewModel { let message = attributedString(text: Localizations.Info.Thanks.ZipLibrary.Message, anchors: [Localizations.Info.Thanks.ZipLibrary.LinkAnchor], urls: ["https://github.com/marmelroy/Zip"]) return TextCellViewModel(attributedText: message) } private func thanks4() -> BaseCellViewModel { let message = attributedString(text: Localizations.Info.Thanks.Artwork.Message, anchors: [Localizations.Info.Thanks.Artwork.LinkAnchor.Deviantart, Localizations.Info.Thanks.Artwork.LinkAnchor.Redbubble], urls: ["http://arabidopsis.deviantart.com/art/Teal-Deer-II-158802763", "http://www.redbubble.com/people/arabidopsis/works/5386340-1-teal-deer-too-long-didnt-read"]) return TextCellViewModel(attributedText: message) } private func thanks5() -> BaseCellViewModel { let message = attributedString(text: Localizations.Info.Thanks.Contributors.Message, anchors: [], urls: []) return TextCellViewModel(attributedText: message) } private func forkMe() -> BaseCellViewModel { let message = attributedString(text: Localizations.Info.OpenSource.Message, anchors: [Localizations.Info.OpenSource.LinkAnchor], urls: ["https://github.com/mflint/ios-tldr-viewer"]) return TextCellViewModel(attributedText: message) } private func attributedString(text: String, anchors: [String], urls: [Any]) -> NSAttributedString { let message = NSMutableAttributedString(attributedString: Theme.bodyAttributed(string: text)!) for (index, anchor) in anchors.enumerated() { let range = (text as NSString).range(of: anchor) message.addAttribute(NSAttributedString.Key.link, value: urls[index], range: range) } return message } }
mit
d86f61f57a36a58e6b2db693b9f13fb8
55.49505
376
0.709604
4.437014
false
false
false
false
exponent/exponent
packages/expo-dev-menu/ios/DevMenuSettings.swift
2
3558
// Copyright 2015-present 650 Industries. All rights reserved. let motionGestureEnabledKey = "EXDevMenuMotionGestureEnabled" let touchGestureEnabledKey = "EXDevMenuTouchGestureEnabled" let keyCommandsEnabledKey = "EXDevMenuKeyCommandsEnabled" let showsAtLaunchKey = "EXDevMenuShowsAtLaunch" let isOnboardingFinishedKey = "EXDevMenuIsOnboardingFinished" @objc public class DevMenuSettings: NSObject { /** Initializes dev menu settings by registering user defaults and applying some settings to static classes like interceptors. */ static func setup() { UserDefaults.standard.register(defaults: [ motionGestureEnabledKey: true, touchGestureEnabledKey: true, keyCommandsEnabledKey: true, showsAtLaunchKey: false, isOnboardingFinishedKey: false ]) /** We don't want to uninstall `DevMenuMotionInterceptor`, because otherwise, the app on shake gesture will bring up the dev-menu from the RN. So we added `isEnabled` to disable it, but not uninstall. */ DevMenuMotionInterceptor.isInstalled = true DevMenuMotionInterceptor.isEnabled = DevMenuSettings.motionGestureEnabled DevMenuTouchInterceptor.isInstalled = DevMenuSettings.touchGestureEnabled DevMenuKeyCommandsInterceptor.isInstalled = DevMenuSettings.keyCommandsEnabled } /** Whether to enable shake gesture. */ static var motionGestureEnabled: Bool { get { return boolForKey(motionGestureEnabledKey) } set { setBool(newValue, forKey: motionGestureEnabledKey) DevMenuMotionInterceptor.isEnabled = newValue } } /** Whether to enable three-finger long press gesture. */ static var touchGestureEnabled: Bool { get { return boolForKey(touchGestureEnabledKey) } set { setBool(newValue, forKey: touchGestureEnabledKey) DevMenuTouchInterceptor.isInstalled = newValue } } /** Whether to enable key commands. */ static var keyCommandsEnabled: Bool { get { return boolForKey(keyCommandsEnabledKey) } set { setBool(newValue, forKey: keyCommandsEnabledKey) DevMenuKeyCommandsInterceptor.isInstalled = newValue } } /** Whether to automatically show the dev menu once its delegate is set and the bridge is loaded. */ static var showsAtLaunch: Bool { get { return DevMenuTestInterceptorManager.interceptor?.shouldShowAtLaunch ?? boolForKey(showsAtLaunchKey) } set { setBool(newValue, forKey: showsAtLaunchKey) } } /** Returns `true` only if the user finished onboarding, `false` otherwise. */ static var isOnboardingFinished: Bool { get { return DevMenuTestInterceptorManager.interceptor?.isOnboardingFinishedKey ?? boolForKey(isOnboardingFinishedKey) } set { setBool(newValue, forKey: isOnboardingFinishedKey) } } /** Serializes settings into a dictionary so they can be passed through the bridge. */ static func serialize() -> [String: Any] { return [ "motionGestureEnabled": DevMenuSettings.motionGestureEnabled, "touchGestureEnabled": DevMenuSettings.touchGestureEnabled, "keyCommandsEnabled": DevMenuSettings.keyCommandsEnabled, "showsAtLaunch": DevMenuSettings.showsAtLaunch, "isOnboardingFinished": DevMenuSettings.isOnboardingFinished ] } } private func boolForKey(_ key: String) -> Bool { return UserDefaults.standard.bool(forKey: key) } private func setBool(_ value: Bool, forKey key: String) { UserDefaults.standard.set(value, forKey: key) }
bsd-3-clause
f33bc91c5f73dc7b90a26241d3bb7713
29.410256
143
0.729342
4.620779
false
false
false
false
BlenderSleuth/Unlokit
Unlokit/Nodes/BackButtonNode.swift
1
1691
// // BackButtonNode.swift // Unlokit // // Created by Ben Sutherland on 1/2/17. // Copyright © 2017 blendersleuthdev. All rights reserved. // import SpriteKit class BackButtonNode: SKSpriteNode { // MARK: Variable // Initialised as implicitly-unwrapped optionals for file archive compatability var label: SKLabelNode! var redCircle: SKShapeNode! var blueCircle: SKShapeNode! var pressed = false // Must be initalised from scene weak var delegate: LevelController! // Used for initialising from file required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) redCircle = SKShapeNode(circleOfRadius: size.width / 2) redCircle.fillColor = .red redCircle.strokeColor = .red redCircle.alpha = 0.2 blueCircle = SKShapeNode(circleOfRadius: size.width / 2) blueCircle.fillColor = .blue blueCircle.strokeColor = .blue blueCircle.isHidden = true label = SKLabelNode(text: "Back") label.position = CGPoint(x: 40, y: -40) label.fontName = neuropolFont label.fontSize = 26 label.zPosition = 10 self.position = position addChild(redCircle) addChild(blueCircle) addChild(label) isUserInteractionEnabled = true } private func press() { pressed = !pressed redCircle.isHidden = pressed blueCircle.isHidden = !pressed } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { press() } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { press() delegate.returnToLevelSelect() } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { press() } }
gpl-3.0
dfb7a58eb6b099dd334d47bb255a57ae
23.492754
80
0.720118
3.580508
false
false
false
false
ttlock/iOS_TTLock_Demo
Pods/iOSDFULibrary/iOSDFULibrary/Classes/Implementation/LegacyDFU/DFU/LegacyDFUExecutor.swift
2
5972
/* * Copyright (c) 2016, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import Foundation import Dispatch internal class LegacyDFUExecutor : DFUExecutor, LegacyDFUPeripheralDelegate { typealias DFUPeripheralType = LegacyDFUPeripheral internal let initiator : DFUServiceInitiator internal let logger : LoggerHelper internal let peripheral : LegacyDFUPeripheral internal var firmware : DFUFirmware internal var error : (error: DFUError, message: String)? /// Retry counter for peripheral invalid state issue. private let MaxRetryCount = 1 private var invalidStateRetryCount: Int // MARK: - Initialization required init(_ initiator: DFUServiceInitiator, _ logger: LoggerHelper) { self.initiator = initiator self.logger = logger self.peripheral = LegacyDFUPeripheral(initiator, logger) self.firmware = initiator.file! self.invalidStateRetryCount = MaxRetryCount } func start() { error = nil peripheral.delegate = self peripheral.start() } // MARK: - DFU Peripheral Delegate methods func peripheralDidBecomeReady() { if firmware.initPacket == nil && peripheral.isInitPacketRequired() { error(.extendedInitPacketRequired, didOccurWithMessage: "The init packet is required by the target device") return } delegate { $0.dfuStateDidChange(to: .starting) } peripheral.enableControlPoint() } func peripheralDidEnableControlPoint() { // Check whether the target is in application or bootloader mode if peripheral.isInApplicationMode(initiator.forceDfu) { delegate { $0.dfuStateDidChange(to: .enablingDfuMode) } peripheral.jumpToBootloader() } else { // The device is ready to proceed with DFU peripheral.sendStartDfu(withFirmwareType: firmware.currentPartType, andSize: firmware.currentPartSize) } } func peripheralDidFailToStartDfuWithType() { // The DFU target has an old implementation of DFU Bootloader, that allows only the application // to be updated. if firmware.currentPartType == FIRMWARE_TYPE_APPLICATION { // Try using the old DFU Start command, without type peripheral.sendStartDfu(withFirmwareSize: firmware.currentPartSize) } else { // Operation can not be continued error(.remoteLegacyDFUNotSupported, didOccurWithMessage: "Updating Softdevice or Bootloader is not supported") } } func peripheralDidStartDfu() { // Check if the init packet is present for this part if let initPacket = firmware.initPacket { peripheral.sendInitPacket(initPacket) return } sendFirmware() } func peripheralDidReceiveInitPacket() { sendFirmware() } func peripheralDidReceiveFirmware() { delegate { $0.dfuStateDidChange(to: .validating) } peripheral.validateFirmware() } func peripheralDidVerifyFirmware() { delegate { $0.dfuStateDidChange(to: .disconnecting) } peripheral.activateAndReset() } func peripheralDidReportInvalidState() { if invalidStateRetryCount > 0 { logger.w("Retrying...") invalidStateRetryCount -= 1 peripheral.start() } else { error(.remoteLegacyDFUInvalidState, didOccurWithMessage: "Peripheral is in an invalid state, please try to reset and start over again.") } } // MARK: - Private methods /** Sends the current part of the firmware to the target DFU device. */ private func sendFirmware() { delegate { $0.dfuStateDidChange(to: .uploading) } // First the service will send the number of packets of firmware data to be received // by the DFU target before sending a new Packet Receipt Notification. // After receiving status Success it will send the firmware. peripheral.sendFirmware(firmware, withPacketReceiptNotificationNumber: initiator.packetReceiptNotificationParameter, andReportProgressTo: initiator.progressDelegate, on: initiator.progressDelegateQueue) } }
mit
b6699aa611a2ea745510d531d3941d4f
39.351351
148
0.675318
5.458867
false
false
false
false
LeafPlayer/Leaf
Leaf/UIComponents/Video/ShortcutAvailableTextField.swift
1
1519
// // ShortcutAvailableTextField.swift // iina // // Created by lhc on 26/12/2016. // Copyright © 2016 lhc. All rights reserved. // http://stackoverflow.com/questions/970707 // import Cocoa class ShortcutAvailableTextField: NSTextField { private let commandKey: NSEvent.ModifierFlags = .command private let commandShiftKey: NSEvent.ModifierFlags = [.command, .shift] override func performKeyEquivalent(with event: NSEvent) -> Bool { if event.type == .keyDown { let flags = event.modifierFlags.intersection(.deviceIndependentFlagsMask) if flags == commandKey { switch event.charactersIgnoringModifiers! { case "x": if NSApp.sendAction(#selector(NSText.cut(_:)), to:nil, from:self) { return true } case "c": if NSApp.sendAction(#selector(NSText.copy(_:)), to:nil, from:self) { return true } case "v": if NSApp.sendAction(#selector(NSText.paste(_:)), to:nil, from:self) { return true } case "z": if NSApp.sendAction(Selector(("undo:")), to:nil, from:self) { return true } case "a": if NSApp.sendAction(#selector(NSResponder.selectAll(_:)), to:nil, from:self) { return true } default: break } } else if flags == commandShiftKey { if event.charactersIgnoringModifiers == "Z" { if NSApp.sendAction(Selector(("redo:")), to:nil, from:self) { return true } } } } return super.performKeyEquivalent(with: event) } }
gpl-3.0
a77257d5d93bc32e1b03811ea218f45d
32
102
0.629117
4.13624
false
false
false
false
groovelab/SwiftBBS
SwiftBBS/SwiftBBS Server/Pager.swift
1
1820
// // Pager.swift // SwiftBBS // // Created by Takeo Namba on 2016/01/30. // Copyright GrooveLab // struct Pager { let current: Int let countPerPage: Int let totalCount: Int let pages: [Int] var hasPrev: Bool { return current > 1 } var hasNext: Bool { return (pages.last ?? 0) > current } init(current: Int, countPerPage: Int, totalCount: Int, pages: [Int]) { self.current = current self.countPerPage = countPerPage self.totalCount = totalCount self.pages = pages } init(totalCount: Int, selectOption: SelectOption) { let totalPage = (totalCount / selectOption.rows) + (((totalCount % selectOption.rows) > 0) ? 1 : 0) var pages = [Int]() if totalPage > 0 { for i in 1...totalPage { pages.append(i) } } self.init(current: selectOption.page, countPerPage: selectOption.rows, totalCount: totalCount, pages: pages) } func toDictionary(acceptJson: Bool = false) -> [String: Any]? { if totalCount == 0 { return nil } var dict: [String: Any] = [ "hasPrev": hasPrev, "hasNext": hasNext, "prevPage": current - 1, "nextPage": current + 1, "countPerPage": countPerPage, "totalCount": totalCount, ] if acceptJson { dict["pages"] = self.pages.map { (page) -> [String: Any] in return ["page": page, "current": page == current] } as [Any] } else { dict["pages"] = self.pages.map { (page) -> [String: Any] in return ["page": page, "current": page == current] } } return dict } }
mit
b1c30532621c2a90341ec7ce5868a616
26.575758
116
0.513187
4.071588
false
false
false
false
sunshineclt/NKU-Helper
NKU Helper/AppDelegate.swift
1
10012
// // AppDelegate.swift // NKU Helper // // Created by 陈乐天 on 15/2/14. // Copyright (c) 2015年 陈乐天. All rights reserved. // import UIKit import Fabric import Crashlytics @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, WXApiDelegate{ var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { JSPatch.start(withAppKey: "bdeda28b488dda55") JSPatch.sync() let rootvc = self.window?.rootViewController as! UITabBarController let firstViewController = rootvc.childViewControllers[0] // To set up Flurry(App Analyse), Fabric.Crashlytics(Crash Analyse), AVOS(Push Service), ShareSDK func setUpAllTools() { Fabric.with([Crashlytics.self]) WXApi.registerApp("wx311e5377578127f1") ShareSDK.registerActivePlatforms([SSDKPlatformType.typeWechat.rawValue, SSDKPlatformType.typeQQ.rawValue, SSDKPlatformType.typeFacebook.rawValue, SSDKPlatformType.typeMail.rawValue, SSDKPlatformType.typeCopy.rawValue, SSDKPlatformType.typePrint.rawValue], onImport: { (platform) in switch platform { case .typeWechat: ShareSDKConnector.connectWeChat(WXApi.classForCoder()) case .typeQQ: ShareSDKConnector.connectQQ(QQApiInterface.classForCoder(), tencentOAuthClass: TencentOAuth.classForCoder()) default: break; } }) { (platform, appInfo) in switch platform { case SSDKPlatformType.typeWechat: //设置微信应用信息 appInfo?.ssdkSetupWeChat(byAppId: "wx311e5377578127f1", appSecret: "83c6080bc1957d3f8f7306f946eb3667") case SSDKPlatformType.typeQQ: //设置QQ应用信息 appInfo?.ssdkSetupQQ(byAppId: "1104934641", appKey: "W66uuRWLP9ZnFlkC", authType: SSDKAuthTypeBoth) case SSDKPlatformType.typeFacebook: //设置Facebook应用信息,其中authType设置为只用SSO形式授权 appInfo?.ssdkSetupFacebook(byApiKey: "576897682460678", appSecret: "20c9e13a474f9d603e488272a033d7d9", authType: SSDKAuthTypeSSO) default: break } } } // set up App Appearance func setUpApperance() { UINavigationBar.appearance().barTintColor = UIColor(red: 156/255, green: 89/255, blue: 182/255, alpha: 1) UINavigationBar.appearance().tintColor = UIColor.white UINavigationBar.appearance().isTranslucent = false UIBarButtonItem.appearance().tintColor = UIColor.white UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white, NSFontAttributeName: UIFont(name: "HelveticaNeue", size: 17)!] UITabBar.appearance().isTranslucent = false } // load Preferred Colors func loadPreferredColors() { do { let _ = try Color.getAllColors() } catch StoragedDataError.noColorInStorage { do { try Color.copyColorsToDocument() } catch { firstViewController.present(ErrorHandler.alert(withError: ErrorHandler.DataBaseError()), animated: true, completion: nil) } } catch { firstViewController.present(ErrorHandler.alert(withError: ErrorHandler.DataBaseError()), animated: true, completion: nil) } } // set up notification func setUpNotification() { let settings = UIUserNotificationSettings(types: [.badge, .alert, .sound], categories: nil) application.registerUserNotificationSettings(settings) application.registerForRemoteNotifications() } // 从1.x版本迁移到2.0版本 func transferFromVersion1ToVersion2() { // 迁移preferredColors数据 let userDefaults = UserDefaults.standard if let _ = userDefaults.object(forKey: "preferredColors") { userDefaults.removeObject(forKey: "preferredColors") } // 迁移密码数据 if let userInfo = userDefaults.object(forKey: UserAgent.sharedInstance.key) as? [String: String] { if let _ = userInfo["password"] { userDefaults.removeObject(forKey: UserAgent.sharedInstance.key) } } // 删除原有的课程数据 if let _ = userDefaults.object(forKey: "courses") as? NSDictionary { userDefaults.removeObject(forKey: "courses") userDefaults.removeObject(forKey: "courseStatus") CourseLoadedAgent.sharedInstance.signCourseToUnloaded() } } transferFromVersion1ToVersion2() setUpAllTools() setUpApperance() loadPreferredColors() setUpNotification() VersionInfoAgent.sharedInstance.saveData() // 推送来的消息需要打开哪个页面 if let launchOption = launchOptions { if let notificationPayload = launchOption[UIApplicationLaunchOptionsKey.remoteNotification] as? [String: Any] { if let action = notificationPayload["action"] as? [String: Any] { if let actionType1 = action["type1"] as? Int, // 一级TabViewController的导航 let actionType2 = action["type2"] as? Int { // 二级TableViewController的导航 NKRouter.sharedInstance.action = ["action1": actionType1, "action2": actionType2] let rootvc = self.window?.rootViewController as! UITabBarController rootvc.selectedIndex = actionType1 } } } } try! R.validate() // 清理已完成的任务 try? Task.updateStoredTasks() NKNetworkInfoHandler.registerUser() return true } func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { printLog("Register For Remote Notification With Device Token Successfully") var token = "" for i in 0..<deviceToken.count { token = token + String(format: "%02.2hhx", arguments: [deviceToken[i]]) } printLog("Device Token: \(token)") NKNetworkInfoHandler.uploadDeviceToken(token) } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { printLog("Register For Remote Notification With Device Token Unsuccessfully") } // 推送来的消息需要打开哪个页面 func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) { if let action = userInfo["action"] as? [String: Any] { if let actionType1 = action["type1"] as? Int, // 一级TabViewController的导航 let actionType2 = action["type2"] as? Int { // 二级TableViewController的导航 NKRouter.sharedInstance.action = ["action1": actionType1, "action2": actionType2] let rootvc = self.window?.rootViewController as! UITabBarController rootvc.selectedIndex = actionType1 } } } func onResp(_ resp: BaseResp!) { if resp.isKind(of: type(of: SendMessageToWXResp())) { printLog("分享到微信错误") } } 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. if application.applicationIconBadgeNumber != 0 { UIApplication.shared.applicationIconBadgeNumber = 0 } } }
gpl-3.0
d764e1682212a84f3907a063bb8fedcf
47.77
285
0.600677
5.586483
false
false
false
false
yulingtianxia/Spiral
Spiral/Background.swift
1
2484
// // Background.swift // Spiral // // Created by 杨萧玉 on 14-10-10. // Copyright (c) 2014年 杨萧玉. All rights reserved. // import SpriteKit /** * 游戏背景绘制 */ class Background: SKSpriteNode { init(size:CGSize, imageName:String?=nil){ let imageString:String if imageName == nil { switch Data.sharedData.currentMode { case .ordinary: imageString = "bg_ordinary" case .zen: imageString = "bg_zen" case .maze: imageString = "bg_maze" } } else{ imageString = imageName! } var resultTexture = SKTexture(imageNamed: imageString) if let bgImage = UIImage(named: imageString) { let xScale = size.width / bgImage.size.width let yScale = size.height / bgImage.size.height let scale = max(xScale, yScale) let scaleSize = CGSize(width: xScale / scale, height: yScale / scale) let scaleOrigin = CGPoint(x: (1 - scaleSize.width) / 2, y: (1 - scaleSize.height) / 2) if let cgimage = bgImage.cgImage?.cropping(to: CGRect(origin: CGPoint(x: scaleOrigin.x * bgImage.size.width, y: scaleOrigin.y * bgImage.size.height), size: CGSize(width: scaleSize.width * bgImage.size.width, height: scaleSize.height * bgImage.size.height))) { resultTexture = SKTexture(cgImage: cgimage) } } super.init(texture: resultTexture, color:SKColor.clear, size: size) normalTexture = resultTexture.generatingNormalMap(withSmoothness: 0.2, contrast: 2.5) zPosition = -100 alpha = 0.5 let light = SKLightNode() switch Data.sharedData.currentMode { case .ordinary: light.lightColor = SKColor.black light.ambientColor = SKColor.black case .zen: light.lightColor = SKColor.brown light.ambientColor = SKColor.brown case .maze: light.lightColor = SKColor.black light.ambientColor = SKColor.black } light.categoryBitMask = bgLightCategory lightingBitMask = playerLightCategory|killerLightCategory|scoreLightCategory|shieldLightCategory|bgLightCategory|reaperLightCategory addChild(light) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
apache-2.0
44e9442135c1b3d615b816ffcf79e35e
34.623188
271
0.599268
4.477231
false
false
false
false
sfurlani/addsumfun
Add Sum Fun/Add Sum Fun/Int+Extension.swift
1
1652
// // Int+Extension.swift // Add Sum Fun // // Created by SFurlani on 8/26/15. // Copyright © 2015 Dig-It! Games. All rights reserved. // import Foundation /// calls transform "self" number of times and returns the array extension UInt { func repeatMap<T>(transform: (UInt) -> T) -> [T] { var result = [T]() for index in 0..<self { result.append(transform(index)) } return result } } /// calls transform "self" number of times and returns the array extension Int { func repeatMap<T>(transform: (Int) -> T) -> [T] { var result = [T]() for index in 0..<self { result.append(transform(index)) } return result } } private func maximum(x: Int, _ y: Int) -> Int { return max(x, y) } extension UInt { func toDigits(places: Int = 0) -> [UInt?] { let characters = String(self).characters var digits = characters.map { UInt(String($0)) } if digits.count < places { let buffer = [UInt?](count: places - digits.count, repeatedValue: nil) digits.insertContentsOf(buffer, at: 0) } return digits } } extension Int { func toDigits(places: Int = 0) -> [Int?] { let characters = String(self).characters var digits = characters.map { Int(String($0)) } if digits.count < places { let buffer = [Int?](count: places - digits.count, repeatedValue: nil) digits.insertContentsOf(buffer, at: 0) } return digits } }
mit
e4a2012d8d03de8aab1700f82d03da5e
21.616438
82
0.535433
3.987923
false
false
false
false
wuzzapcom/Fluffy-Book
Pods/RealmSwift/RealmSwift/Sync.swift
11
30933
//////////////////////////////////////////////////////////////////////////// // // Copyright 2016 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import Realm import Realm.Private import Foundation /** An object representing a Realm Object Server user. - see: `RLMSyncUser` */ public typealias SyncUser = RLMSyncUser /** An immutable data object representing information retrieved from the Realm Object Server about a particular user. - see: `RLMSyncUserInfo` */ public typealias SyncUserInfo = RLMSyncUserInfo /** A singleton which configures and manages the Realm Object Server synchronization-related functionality. - see: `RLMSyncManager` */ public typealias SyncManager = RLMSyncManager extension SyncManager { /// The sole instance of the singleton. public static var shared: SyncManager { return __shared() } } /** A session object which represents communication between the client and server for a specific Realm. - see: `RLMSyncSession` */ public typealias SyncSession = RLMSyncSession /** A closure type for a closure which can be set on the `SyncManager` to allow errors to be reported to the application. - see: `RLMSyncErrorReportingBlock` */ public typealias ErrorReportingBlock = RLMSyncErrorReportingBlock /** A closure type for a closure which is used by certain APIs to asynchronously return a `SyncUser` object to the application. - see: `RLMUserCompletionBlock` */ public typealias UserCompletionBlock = RLMUserCompletionBlock /** An error associated with the SDK's synchronization functionality. All errors reported by an error handler registered on the `SyncManager` are of this type. - see: `RLMSyncError` */ public typealias SyncError = RLMSyncError /** An error associated with network requests made to the authentication server. This type of error may be returned in the callback block to `SyncUser.logIn()` upon certain types of failed login attempts (for example, if the request is malformed or if the server is experiencing an issue). - see: `RLMSyncAuthError` */ public typealias SyncAuthError = RLMSyncAuthError /** An error associated with retrieving or modifying user permissions to access a synchronized Realm. - see: `RLMSyncPermissionError` */ public typealias SyncPermissionError = RLMSyncPermissionError /** An enum which can be used to specify the level of logging. - see: `RLMSyncLogLevel` */ public typealias SyncLogLevel = RLMSyncLogLevel /** An enum representing the different states a sync management object can take. - see: `RLMSyncManagementObjectStatus` */ public typealias SyncManagementObjectStatus = RLMSyncManagementObjectStatus /** A data type whose values represent different authentication providers that can be used with the Realm Object Server. - see: `RLMIdentityProvider` */ public typealias Provider = RLMIdentityProvider public extension SyncError { /// Given a client reset error, extract and return the recovery file path and the reset closure. public func clientResetInfo() -> (String, () -> Void)? { if code == SyncError.clientResetError, let recoveryPath = userInfo[kRLMSyncPathOfRealmBackupCopyKey] as? String, let block = _nsError.__rlmSync_clientResetBlock() { return (recoveryPath, block) } return nil } /// Given a permission denied error, extract and return the reset closure. public func deleteRealmUserInfo() -> (() -> Void)? { return _nsError.__rlmSync_deleteRealmBlock() } } /** A `SyncConfiguration` represents configuration parameters for Realms intended to sync with a Realm Object Server. */ public struct SyncConfiguration { /// The `SyncUser` who owns the Realm that this configuration should open. public let user: SyncUser /** The URL of the Realm on the Realm Object Server that this configuration should open. - warning: The URL must be absolute (e.g. `realms://example.com/~/foo`), and cannot end with `.realm`, `.realm.lock` or `.realm.management`. */ public let realmURL: URL /** A policy that determines what should happen when all references to Realms opened by this configuration go out of scope. */ internal let stopPolicy: RLMSyncStopPolicy /** Whether the SSL certificate of the Realm Object Server should be validated. */ public let enableSSLValidation: Bool internal init(config: RLMSyncConfiguration) { self.user = config.user self.realmURL = config.realmURL self.stopPolicy = config.stopPolicy self.enableSSLValidation = config.enableSSLValidation } func asConfig() -> RLMSyncConfiguration { let config = RLMSyncConfiguration(user: user, realmURL: realmURL) config.stopPolicy = stopPolicy config.enableSSLValidation = enableSSLValidation return config } /** Initialize a sync configuration with a user and a Realm URL. Additional settings can be optionally specified. Descriptions of these settings follow. `enableSSLValidation` is true by default. It can be disabled for debugging purposes. - warning: The URL must be absolute (e.g. `realms://example.com/~/foo`), and cannot end with `.realm`, `.realm.lock` or `.realm.management`. - warning: NEVER disable SSL validation for a system running in production. */ public init(user: SyncUser, realmURL: URL, enableSSLValidation: Bool = true) { self.user = user self.realmURL = realmURL self.stopPolicy = .afterChangesUploaded self.enableSSLValidation = enableSSLValidation } } /// A `SyncCredentials` represents data that uniquely identifies a Realm Object Server user. public struct SyncCredentials { public typealias Token = String internal var token: Token internal var provider: Provider internal var userInfo: [String: Any] /** Initialize new credentials using a custom token, authentication provider, and user information dictionary. In most cases, the convenience initializers should be used instead. */ public init(customToken token: Token, provider: Provider, userInfo: [String: Any] = [:]) { self.token = token self.provider = provider self.userInfo = userInfo } internal init(_ credentials: RLMSyncCredentials) { self.token = credentials.token self.provider = credentials.provider self.userInfo = credentials.userInfo } /// Initialize new credentials using a Facebook account token. public static func facebook(token: Token) -> SyncCredentials { return SyncCredentials(RLMSyncCredentials(facebookToken: token)) } /// Initialize new credentials using a Google account token. public static func google(token: Token) -> SyncCredentials { return SyncCredentials(RLMSyncCredentials(googleToken: token)) } /// Initialize new credentials using a CloudKit account token. public static func cloudKit(token: Token) -> SyncCredentials { return SyncCredentials(RLMSyncCredentials(cloudKitToken: token)) } /// Initialize new credentials using a Realm Object Server username and password. public static func usernamePassword(username: String, password: String, register: Bool = false) -> SyncCredentials { return SyncCredentials(RLMSyncCredentials(username: username, password: password, register: register)) } /// Initialize new credentials using a Realm Object Server access token. public static func accessToken(_ accessToken: String, identity: String) -> SyncCredentials { return SyncCredentials(RLMSyncCredentials(accessToken: accessToken, identity: identity)) } } extension RLMSyncCredentials { internal convenience init(_ credentials: SyncCredentials) { self.init(customToken: credentials.token, provider: credentials.provider, userInfo: credentials.userInfo) } } extension SyncUser { /** Given credentials and a server URL, log in a user and asynchronously return a `SyncUser` object which can be used to open `Realm`s and retrieve `SyncSession`s. */ public static func logIn(with credentials: SyncCredentials, server authServerURL: URL, timeout: TimeInterval = 30, onCompletion completion: @escaping UserCompletionBlock) { return SyncUser.__logIn(with: RLMSyncCredentials(credentials), authServerURL: authServerURL, timeout: timeout, onCompletion: completion) } /// A dictionary of all valid, logged-in user identities corresponding to their `SyncUser` objects. public static var all: [String: SyncUser] { return __allUsers() } /** The logged-in user. `nil` if none exists. Only use this property if your application expects no more than one logged-in user at any given time. - warning: Throws an Objective-C exception if more than one logged-in user exists. */ public static var current: SyncUser? { return __current() } /** An optional error handler which can be set to notify the host application when the user encounters an error. - note: Check for `.invalidAccessToken` to see if the user has been remotely logged out because its refresh token expired, or because the third party authentication service providing the user's identity has logged the user out. - warning: Regardless of whether an error handler is defined, certain user errors will automatically cause the user to enter the logged out state. */ @nonobjc public var errorHandler: ((SyncUser, SyncAuthError) -> Void)? { get { return __errorHandler } set { if let newValue = newValue { __errorHandler = { (user, error) in newValue(user, error as! SyncAuthError) } } else { __errorHandler = nil } } } /** Returns an instance of the Management Realm owned by the user. This Realm can be used to control access permissions for Realms managed by the user. This includes granting other users access to Realms. */ public func managementRealm() throws -> Realm { var config = Realm.Configuration.fromRLMRealmConfiguration(.managementConfiguration(for: self)) guard let permissionChangeClass = NSClassFromString("RealmSwift.SyncPermissionChange") as? Object.Type else { fatalError("Internal error: could not build `SyncPermissionChange` metaclass from string.") } config.objectTypes = [permissionChangeClass, SyncPermissionOffer.self, SyncPermissionOfferResponse.self] return try Realm(configuration: config) } /** Returns an instance of the Permission Realm owned by the user. This read-only Realm contains `SyncPermission` objects reflecting the synchronized Realms and permission details this user has access to. */ @available(*, deprecated, message: "Use SyncUser.retrievePermissions()") public func permissionRealm() throws -> Realm { var config = Realm.Configuration.fromRLMRealmConfiguration(.permissionConfiguration(for: self)) config.objectTypes = [SyncPermission.self] return try Realm(configuration: config) } } /** A value which represents a permission granted to a user to interact with a Realm. These values are passed into APIs on `SyncUser`, and returned from `SyncPermissionResults`. - see: `RLMSyncPermissionValue` */ public typealias SyncPermissionValue = RLMSyncPermissionValue /** An enumeration describing possible access levels. - see: `RLMSyncAccessLevel` */ public typealias SyncAccessLevel = RLMSyncAccessLevel /** A collection of `SyncPermissionValue`s that represent the permissions that have been configured on all the Realms that some user is allowed to administer. - see: `RLMSyncPermissionResults` */ public typealias SyncPermissionResults = RLMSyncPermissionResults #if swift(>=3.1) extension SyncPermissionResults: RandomAccessCollection { public subscript(index: Int) -> SyncPermissionValue { return object(at: index) } public func index(after i: Int) -> Int { return i + 1 } public var startIndex: Int { return 0 } public var endIndex: Int { return count } } #else extension SyncPermissionResults { /// Return the first permission value in the results, or `nil` if /// the results are empty. public var first: SyncPermissionValue? { return count > 0 ? object(at: 0) : nil } /// Return the last permission value in the results, or `nil` if /// the results are empty. public var last: SyncPermissionValue? { return count > 0 ? object(at: count - 1) : nil } } extension SyncPermissionResults: Sequence { public struct Iterator: IteratorProtocol { private let iteratorBase: NSFastEnumerationIterator fileprivate init(results: SyncPermissionResults) { iteratorBase = NSFastEnumerationIterator(results) } public func next() -> SyncPermissionValue? { return iteratorBase.next() as! SyncPermissionValue? } } public func makeIterator() -> SyncPermissionResults.Iterator { return Iterator(results: self) } } #endif /** This model is used to reflect permissions. It should be used in conjunction with a `SyncUser`'s Permission Realm. You can only read this Realm. Use the objects in Management Realm to make request for modifications of permissions. See https://realm.io/docs/realm-object-server/#permissions for general documentation. */ @available(*, deprecated, message: "Use `SyncPermissionValue`") public final class SyncPermission: Object { /// The date this object was last modified. @objc public dynamic var updatedAt = Date() /// The ID of the affected user by the permission. @objc public dynamic var userId = "" /// The path to the realm. @objc public dynamic var path = "" /// Whether the affected user is allowed to read from the Realm. @objc public dynamic var mayRead = false /// Whether the affected user is allowed to write to the Realm. @objc public dynamic var mayWrite = false /// Whether the affected user is allowed to manage the access rights for others. @objc public dynamic var mayManage = false /// :nodoc: override public class func shouldIncludeInDefaultSchema() -> Bool { return false } /// :nodoc: override public class func _realmObjectName() -> String? { return "Permission" } } /** This model is used for requesting changes to a Realm's permissions. It should be used in conjunction with a `SyncUser`'s Management Realm. See https://realm.io/docs/realm-object-server/#permissions for general documentation. */ @available(*, deprecated, message: "Use `SyncUser.applyPermission()` and `SyncUser.revokePermission()`") public final class SyncPermissionChange: Object { /// The globally unique ID string of this permission change object. @objc public dynamic var id = UUID().uuidString /// The date this object was initially created. @objc public dynamic var createdAt = Date() /// The date this object was last modified. @objc public dynamic var updatedAt = Date() /// The status code of the object that was processed by Realm Object Server. public let statusCode = RealmOptional<Int>() /// An error or informational message, typically written to by the Realm Object Server. @objc public dynamic var statusMessage: String? /// Sync management object status. public var status: SyncManagementObjectStatus { return SyncManagementObjectStatus(statusCode: statusCode) } /// The remote URL to the realm. @objc public dynamic var realmUrl = "*" /// The identity of a user affected by this permission change. @objc public dynamic var userId = "*" /// Define read access. Set to `true` or `false` to update this value. Leave unset /// to preserve the existing setting. public let mayRead = RealmOptional<Bool>() /// Define write access. Set to `true` or `false` to update this value. Leave unset /// to preserve the existing setting. public let mayWrite = RealmOptional<Bool>() /// Define management access. Set to `true` or `false` to update this value. Leave /// unset to preserve the existing setting. public let mayManage = RealmOptional<Bool>() /** Construct a permission change object used to change the access permissions for a user on a Realm. - parameter realmURL: The Realm URL whose permissions settings should be changed. Use `*` to change the permissions of all Realms managed by the Management Realm's `SyncUser`. - parameter userID: The user or users who should be granted these permission changes. Use `*` to change the permissions for all users. - parameter mayRead: Define read access. Set to `true` or `false` to update this value. Leave unset to preserve the existing setting. - parameter mayWrite: Define write access. Set to `true` or `false` to update this value. Leave unset to preserve the existing setting. - parameter mayManage: Define management access. Set to `true` or `false` to update this value. Leave unset to preserve the existing setting. */ public convenience init(realmURL: String, userID: String, mayRead: Bool?, mayWrite: Bool?, mayManage: Bool?) { self.init() self.realmUrl = realmURL self.userId = userID self.mayRead.value = mayRead self.mayWrite.value = mayWrite self.mayManage.value = mayManage } /// :nodoc: override public class func primaryKey() -> String? { return "id" } /// :nodoc: override public class func shouldIncludeInDefaultSchema() -> Bool { return false } /// :nodoc: override public class func _realmObjectName() -> String? { return "PermissionChange" } } /** This model is used for offering permission changes to other users. It should be used in conjunction with a `SyncUser`'s Management Realm. See https://realm.io/docs/realm-object-server/#permissions for general documentation. */ public final class SyncPermissionOffer: Object { /// The globally unique ID string of this permission offer object. @objc public dynamic var id = UUID().uuidString /// The date this object was initially created. @objc public dynamic var createdAt = Date() /// The date this object was last modified. @objc public dynamic var updatedAt = Date() /// The status code of the object that was processed by Realm Object Server. public let statusCode = RealmOptional<Int>() /// An error or informational message, typically written to by the Realm Object Server. @objc public dynamic var statusMessage: String? /// Sync management object status. public var status: SyncManagementObjectStatus { return SyncManagementObjectStatus(statusCode: statusCode) } /// A token which uniquely identifies this offer. Generated by the server. @objc public dynamic var token: String? /// The remote URL to the realm. @objc public dynamic var realmUrl = "" /// Whether this offer allows the receiver to read from the Realm. @objc public dynamic var mayRead = false /// Whether this offer allows the receiver to write to the Realm. @objc public dynamic var mayWrite = false /// Whether this offer allows the receiver to manage the access rights for others. @objc public dynamic var mayManage = false /// When this token will expire and become invalid. @objc public dynamic var expiresAt: Date? /** Construct a permission offer object used to offer permission changes to other users. - parameter realmURL: The URL to the Realm on which to apply these permission changes to, once the offer is accepted. - parameter expiresAt: When this token will expire and become invalid. Pass `nil` if this offer should not expire. - parameter mayRead: Grant or revoke read access. - parameter mayWrite: Grant or revoked read-write access. - parameter mayManage: Grant or revoke administrative access. */ public convenience init(realmURL: String, expiresAt: Date?, mayRead: Bool, mayWrite: Bool, mayManage: Bool) { self.init() self.realmUrl = realmURL self.expiresAt = expiresAt self.mayRead = mayRead self.mayWrite = mayWrite self.mayManage = mayManage } /// :nodoc: override public class func indexedProperties() -> [String] { return ["token"] } /// :nodoc: override public class func primaryKey() -> String? { return "id" } /// :nodoc: override public class func shouldIncludeInDefaultSchema() -> Bool { return false } /// :nodoc: override public class func _realmObjectName() -> String? { return "PermissionOffer" } } /** This model is used to apply permission changes defined in the permission offer object represented by the specified token, which was created by another user's `SyncPermissionOffer` object. It should be used in conjunction with a `SyncUser`'s Management Realm. See https://realm.io/docs/realm-object-server/#permissions for general documentation. */ public final class SyncPermissionOfferResponse: Object { /// The globally unique ID string of this permission offer response object. @objc public dynamic var id = UUID().uuidString /// The date this object was initially created. @objc public dynamic var createdAt = Date() /// The date this object was last modified. @objc public dynamic var updatedAt = Date() /// The status code of the object that was processed by Realm Object Server. public let statusCode = RealmOptional<Int>() /// An error or informational message, typically written to by the Realm Object Server. @objc public dynamic var statusMessage: String? /// Sync management object status. public var status: SyncManagementObjectStatus { return SyncManagementObjectStatus(statusCode: statusCode) } /// The received token which uniquely identifies another user's `SyncPermissionOffer`. @objc public dynamic var token = "" /// The remote URL to the realm on which these permission changes were applied. @objc public dynamic var realmUrl: String? /** Construct a permission offer response object used to apply permission changes defined in the permission offer object represented by the specified token, which was created by another user's `SyncPermissionOffer` object. - parameter token: The received token which uniquely identifies another user's `SyncPermissionOffer`. */ public convenience init(token: String) { self.init() self.token = token } /// :nodoc: override public class func primaryKey() -> String? { return "id" } /// :nodoc: override public class func shouldIncludeInDefaultSchema() -> Bool { return false } /// :nodoc: override public class func _realmObjectName() -> String? { return "PermissionOfferResponse" } } fileprivate extension SyncManagementObjectStatus { fileprivate init(statusCode: RealmOptional<Int>) { guard let statusCode = statusCode.value else { self = .notProcessed return } if statusCode == 0 { self = .success } else { self = .error } } } public extension SyncSession { /** The transfer direction (upload or download) tracked by a given progress notification block. Progress notification blocks can be registered on sessions if your app wishes to be informed how many bytes have been uploaded or downloaded, for example to show progress indicator UIs. */ public enum ProgressDirection { /// For monitoring upload progress. case upload /// For monitoring download progress. case download } /** The desired behavior of a progress notification block. Progress notification blocks can be registered on sessions if your app wishes to be informed how many bytes have been uploaded or downloaded, for example to show progress indicator UIs. */ public enum ProgressMode { /** The block will be called forever, or until it is unregistered by calling `ProgressNotificationToken.stop()`. Notifications will always report the latest number of transferred bytes, and the most up-to-date number of total transferrable bytes. */ case reportIndefinitely /** The block will, upon registration, store the total number of bytes to be transferred. When invoked, it will always report the most up-to-date number of transferrable bytes out of that original number of transferrable bytes. When the number of transferred bytes reaches or exceeds the number of transferrable bytes, the block will be unregistered. */ case forCurrentlyOutstandingWork } /** A token corresponding to a progress notification block. Call `stop()` on the token to stop notifications. If the notification block has already been automatically stopped, calling `stop()` does nothing. `stop()` should be called before the token is destroyed. */ public typealias ProgressNotificationToken = RLMProgressNotificationToken /** A struct encapsulating progress information, as well as useful helper methods. */ public struct Progress { /// The number of bytes that have been transferred. public let transferredBytes: Int /** The total number of transferrable bytes (bytes that have been transferred, plus bytes pending transfer). If the notification block is tracking downloads, this number represents the size of the changesets generated by all other clients using the Realm. If the notification block is tracking uploads, this number represents the size of the changesets representing the local changes on this client. */ public let transferrableBytes: Int /// The fraction of bytes transferred out of all transferrable bytes. If this value is 1, /// no bytes are waiting to be transferred (either all bytes have already been transferred, /// or there are no bytes to be transferred in the first place). public var fractionTransferred: Double { if transferrableBytes == 0 { return 1 } let percentage = Double(transferredBytes) / Double(transferrableBytes) return percentage > 1 ? 1 : percentage } /// Whether all pending bytes have already been transferred. public var isTransferComplete: Bool { return transferredBytes >= transferrableBytes } fileprivate init(transferred: UInt, transferrable: UInt) { transferredBytes = Int(transferred) transferrableBytes = Int(transferrable) } } /** Register a progress notification block. If the session has already received progress information from the synchronization subsystem, the block will be called immediately. Otherwise, it will be called as soon as progress information becomes available. Multiple blocks can be registered with the same session at once. Each block will be invoked on a side queue devoted to progress notifications. The token returned by this method must be retained as long as progress notifications are desired, and the `stop()` method should be called on it when notifications are no longer needed and before the token is destroyed. If no token is returned, the notification block will never be called again. There are a number of reasons this might be true. If the session has previously experienced a fatal error it will not accept progress notification blocks. If the block was configured in the `forCurrentlyOutstandingWork` mode but there is no additional progress to report (for example, the number of transferrable bytes and transferred bytes are equal), the block will not be called again. - parameter direction: The transfer direction (upload or download) to track in this progress notification block. - parameter mode: The desired behavior of this progress notification block. - parameter block: The block to invoke when notifications are available. - returns: A token which must be held for as long as you want notifications to be delivered. - see: `ProgressDirection`, `Progress`, `ProgressNotificationToken` */ public func addProgressNotification(for direction: ProgressDirection, mode: ProgressMode, block: @escaping (Progress) -> Void) -> ProgressNotificationToken? { return __addProgressNotification(for: (direction == .upload ? .upload : .download), mode: (mode == .reportIndefinitely ? .reportIndefinitely : .forCurrentlyOutstandingWork)) { transferred, transferrable in block(Progress(transferred: transferred, transferrable: transferrable)) } } }
mit
920ee56c21ce2a6e4aa2ef68c6d8ff6a
36.403869
121
0.67866
5.18923
false
false
false
false
KyleKing/My-Programming-Sketchbook
iOS/XCode - Test/Test/AppDelegate.swift
1
3322
// // AppDelegate.swift // Test // // Created by Kyle King on 12/26/15. // Copyright © 2015 Kyle King. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. let splitViewController = self.window!.rootViewController as! UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem() splitViewController.delegate = self 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:. } // MARK: - Split view func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool { guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false } guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false } if topAsDetailController.detailItem == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } return false } }
mit
6cb42108d80cb865c0c208836f25cd10
53.442623
285
0.764228
6.184358
false
false
false
false
lyft/SwiftLint
Source/SwiftLintFramework/Rules/ColonRule+Type.swift
1
2918
import Foundation import SourceKittenFramework internal extension ColonRule { var pattern: String { // If flexible_right_spacing is true, match only 0 whitespaces. // If flexible_right_spacing is false or omitted, match 0 or 2+ whitespaces. let spacingRegex = configuration.flexibleRightSpacing ? "(?:\\s{0})" : "(?:\\s{0}|\\s{2,})" return "(\\w)" + // Capture an identifier "(?:" + // start group "\\s+" + // followed by whitespace ":" + // to the left of a colon "\\s*" + // followed by any amount of whitespace. "|" + // or ":" + // immediately followed by a colon spacingRegex + // followed by right spacing regex ")" + // end group "(" + // Capture a type identifier "[\\[|\\(]*" + // which may begin with a series of nested parenthesis or brackets "\\S)" // lazily to the first non-whitespace character. } func typeColonViolationRanges(in file: File, matching pattern: String) -> [NSRange] { let nsstring = file.contents.bridge() let commentAndStringKindsSet = SyntaxKind.commentAndStringKinds return file.rangesAndTokens(matching: pattern).filter { _, syntaxTokens in let syntaxKinds = syntaxTokens.compactMap { SyntaxKind(rawValue: $0.type) } guard syntaxKinds.count == 2 else { return false } let validKinds: Bool switch (syntaxKinds[0], syntaxKinds[1]) { case (.identifier, .typeidentifier), (.typeidentifier, .typeidentifier): validKinds = true case (.identifier, .keyword), (.typeidentifier, .keyword): validKinds = file.isTypeLike(token: syntaxTokens[1]) case (.keyword, .typeidentifier): validKinds = file.isTypeLike(token: syntaxTokens[0]) default: validKinds = false } guard validKinds else { return false } return Set(syntaxKinds).isDisjoint(with: commentAndStringKindsSet) }.compactMap { range, syntaxTokens in let identifierRange = nsstring .byteRangeToNSRange(start: syntaxTokens[0].offset, length: 0) return identifierRange.map { NSUnionRange($0, range) } } } } private extension File { func isTypeLike(token: SyntaxToken) -> Bool { let nsstring = contents.bridge() guard let text = nsstring.substringWithByteRange(start: token.offset, length: token.length), let firstLetter = text.unicodeScalars.first else { return false } return CharacterSet.uppercaseLetters.contains(firstLetter) } }
mit
b11a44dd37d7e35d7758e73e56e26871
39.527778
100
0.559973
4.962585
false
false
false
false
watson-developer-cloud/ios-sdk
Sources/AssistantV1/Models/RuntimeResponseGenericRuntimeResponseTypeChannelTransfer.swift
1
3192
/** * (C) Copyright IBM Corp. 2021. * * 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 /** RuntimeResponseGenericRuntimeResponseTypeChannelTransfer. Enums with an associated value of RuntimeResponseGenericRuntimeResponseTypeChannelTransfer: RuntimeResponseGeneric */ public struct RuntimeResponseGenericRuntimeResponseTypeChannelTransfer: Codable, Equatable { /** The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. */ public var responseType: String /** The message to display to the user when initiating a channel transfer. */ public var messageToUser: String /** Information used by an integration to transfer the conversation to a different channel. */ public var transferInfo: ChannelTransferInfo /** An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended only for a built-in integration and should not be handled by an API client. */ public var channels: [ResponseGenericChannel]? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case responseType = "response_type" case messageToUser = "message_to_user" case transferInfo = "transfer_info" case channels = "channels" } /** Initialize a `RuntimeResponseGenericRuntimeResponseTypeChannelTransfer` with member variables. - parameter responseType: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - parameter messageToUser: The message to display to the user when initiating a channel transfer. - parameter transferInfo: Information used by an integration to transfer the conversation to a different channel. - parameter channels: An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended only for a built-in integration and should not be handled by an API client. - returns: An initialized `RuntimeResponseGenericRuntimeResponseTypeChannelTransfer`. */ public init( responseType: String, messageToUser: String, transferInfo: ChannelTransferInfo, channels: [ResponseGenericChannel]? = nil ) { self.responseType = responseType self.messageToUser = messageToUser self.transferInfo = transferInfo self.channels = channels } }
apache-2.0
8f802d4640c56517296ba76975836e6e
37
121
0.722431
5.042654
false
false
false
false
nghialv/VersionTracker
VersionTracker/VersionTracker.swift
1
1925
// // VersionTracker.swift // Example // // Created by Le VanNghia on 7/3/15. // Copyright (c) 2015 Le Van Nghia. All rights reserved. // import Foundation private let VersionTrailKey = "VersionTracker.VersionTrailKey" private let VersionsKey = "VersionTracker.VersionsKey" private let BuildsKey = "VersionTracker.BuildsKey" public struct VersionTracker { typealias VersionTrailDictionary = [String: [String]] private static var versionTrail: VersionTrailDictionary = [:] public private(set) static var isFirstLaunchEver = false public private(set) static var isFirstLaunchForVersion = false public private(set) static var isFirstLaunchForBuild = false public static var currentVersion: String { return Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String } public static var currentBuild: String { return Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as! String } public static func track() { let standardUserDefaults = UserDefaults.standard let oldVersionTrail = standardUserDefaults.object(forKey: VersionTrailKey) as? VersionTrailDictionary versionTrail = oldVersionTrail ?? [:] isFirstLaunchEver = oldVersionTrail == nil if let versions = versionTrail[VersionsKey], versions.contains(currentVersion) { isFirstLaunchForVersion = false } else { isFirstLaunchForVersion = true var versions = versionTrail[VersionsKey] ?? [] versions.append(currentVersion) versionTrail[VersionsKey] = versions } if let builds = versionTrail[BuildsKey], builds.contains(currentBuild) { isFirstLaunchForBuild = false } else { isFirstLaunchForBuild = true var builds = versionTrail[BuildsKey] ?? [] builds.append(currentBuild) versionTrail[BuildsKey] = builds } // Store version trail standardUserDefaults.set(versionTrail, forKey: VersionTrailKey) standardUserDefaults.synchronize() } }
mit
c6f2344f0cfa90c5137a05c97669d5e8
30.557377
103
0.758442
4.148707
false
false
false
false
CrawlingSnail/CardStack
CardStackdemo/CardStacking/KZCardStacking/KZCardStacking.swift
1
5606
// // KZCardStackingCollectionView.swift // CardStacking // // Created by Mr.Huang on 2017/7/4. // Copyright © 2017年 Mr.Huang. All rights reserved. // import UIKit @objc public protocol KZCardStackingDelegate:NSObjectProtocol{ /// 卡片需要从视图中删除,外界需要删除data中的数据并删掉对应cell /// /// - Parameter at: IndexPath func cardStackingDeleteCard(at:IndexPath) /// 卡片移动过中可以添加动画什么的 /// /// - Parameters: /// - collectionView: collectionView /// - moveCell: 移动中的cell @objc optional func panGestureRecognizerChanged(collectionView:UICollectionView,moveCell:UICollectionViewCell) } public class KZCardStackingCollectionView: UICollectionView { weak open var cardDelegate: KZCardStackingDelegate? private static var moveCell:UIView? = nil func panHandle(_ panGesture:UIPanGestureRecognizer){ /// 当前cell总数 let count:Int = (numberOfItems(inSection: 0)) if (!(count > 0)) {return} if (KZCardStackingCollectionView.moveCell == nil) { let indexPath:IndexPath = IndexPath(row: 0, section: 0) let cell = cellForItem(at: indexPath) //获取手势点 判断是否在作用范围 let xpoint = panGesture.location(in: self) if !((cell?.frame.contains(xpoint))!) {return} KZCardStackingCollectionView.moveCell = cell let layout = collectionViewLayout as! KZCardStackingLayout layout.moved = true if count > 1 { reloadItems(at: [IndexPath.init(row: 1, section: 0)]) } } let point = panGesture.translation(in: self) panGesture.setTranslation(.zero, in: self) KZCardStackingCollectionView.moveCell?.center = CGPoint.init(x: KZCardStackingCollectionView.moveCell!.center.x + point.x, y: KZCardStackingCollectionView.moveCell!.center.y + point.y) switch panGesture.state { case .changed: cardDelegate?.panGestureRecognizerChanged?(collectionView: self, moveCell: KZCardStackingCollectionView.moveCell as! UICollectionViewCell) break default: let indexPath = IndexPath.init(row: 0, section: 0) if count > 1 { let cell = cellForItem(at: IndexPath.init(row: 1, section: 0)) let layout = collectionViewLayout as! KZCardStackingLayout layout.moved = false if Double((KZCardStackingCollectionView.moveCell?.center.x)!) > Double((cell?.frame.minX)!) && Double((KZCardStackingCollectionView.moveCell?.center.x)!) < Double((cell?.frame.maxX)!){ reloadItems(at: [indexPath]) }else{ //删除视图 cardDelegate?.cardStackingDeleteCard(at:indexPath) } }else{ //只有一张的时候直接删除 //删除视图 cardDelegate?.cardStackingDeleteCard(at:indexPath) } KZCardStackingCollectionView.moveCell = nil break } } override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) { super.init(frame: frame, collectionViewLayout: layout) let panG = UIPanGestureRecognizer.init(target:self , action: #selector(panHandle(_:))) addGestureRecognizer(panG) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } public class KZCardStackingLayout: UICollectionViewLayout { /// cell头部距离 var cardDrop = 0.0 /// 各个cell之间的比例 var scale = 0.8 /// cell宽高比(默认1:1) var aspectRatio = 1.0 /// 显示的图片数目,默认比设置的多一张 var maxlevel = 2 /// cell宽度和collectionView的比例 var widthScale = 0.5 /// 顶端cell是否在移动 var moved = false private var attrsAry:[UICollectionViewLayoutAttributes] = [] override public func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { return attrsAry } override public func prepare() { super.prepare() self.attrsAry.removeAll() let count:Int = (self.collectionView?.numberOfItems(inSection: 0))! for index in 0 ..< count { let indexPath = IndexPath.init(item: index, section: 0) let attrs = layoutAttributesForItemAtIndexPath(indexPath: indexPath) attrsAry.append(attrs) } } func layoutAttributesForItemAtIndexPath(indexPath:IndexPath) -> UICollectionViewLayoutAttributes { let width = (self.collectionView?.frame.size.width)! * CGFloat(widthScale) let attrs = UICollectionViewLayoutAttributes.init(forCellWith: indexPath) var level = indexPath.row - (self.moved ? 1:0) if level > maxlevel { level = maxlevel } /// 设置cell层级关系 attrs.zIndex = (self.collectionView?.numberOfItems(inSection: 0))! - indexPath.row let dump = CGFloat(aspectRatio)*width*CGFloat(1 - pow(scale, Double(level))) + CGFloat(Double(level)*cardDrop) attrs.center = CGPoint.init(x: (self.collectionView?.center.x)!, y: (self.collectionView?.center.y)! - dump) attrs.bounds = CGRect.init(x: 0, y: 0, width:width*CGFloat(pow(scale, Double(level))), height: CGFloat(aspectRatio)*width*CGFloat(pow(scale, Double(level)))) return attrs } }
mit
fc37d7c5908b5628bce9ae21b6ddc80c
38.518519
201
0.638051
4.394563
false
false
false
false
AaronMT/firefox-ios
Extensions/NotificationService/NotificationService.swift
6
10347
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Account import Shared import Storage import Sync import UserNotifications import os.log func consoleLog(_ msg: String) { os_log("%{public}@", log: OSLog(subsystem: "org.mozilla.firefox", category: "firefoxnotificationservice"), type: OSLogType.debug, msg) } class NotificationService: UNNotificationServiceExtension { var display: SyncDataDisplay? var profile: ExtensionProfile? // This is run when an APNS notification with `mutable-content` is received. // If the app is backgrounded, then the alert notification is displayed. // If the app is foregrounded, then the notification.userInfo is passed straight to // AppDelegate.application(_:didReceiveRemoteNotification:completionHandler:) // Once the notification is tapped, then the same userInfo is passed to the same method in the AppDelegate. override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) { consoleLog("push received") let userInfo = request.content.userInfo let content = request.content.mutableCopy() as! UNMutableNotificationContent if self.profile == nil { self.profile = ExtensionProfile(localName: "profile") } guard let profile = self.profile else { self.didFinish(with: .noProfile) return } let queue = profile.queue let display = SyncDataDisplay(content: content, contentHandler: contentHandler, tabQueue: queue) self.display = display profile.syncDelegate = display let handler = FxAPushMessageHandler(with: profile) handler.handle(userInfo: userInfo).upon { res in self.didFinish(res.successValue, with: res.failureValue as? PushMessageError) } } func didFinish(_ what: PushMessage? = nil, with error: PushMessageError? = nil) { consoleLog("push didFinish start") defer { // We cannot use tabqueue after the profile has shutdown; // however, we can't use weak references, because TabQueue isn't a class. // Rather than changing tabQueue, we manually nil it out here. self.display?.tabQueue = nil profile?._shutdown() consoleLog("push didFinish end") } guard let display = self.display else { return } display.messageDelivered = false display.displayNotification(what, profile: profile, with: error) if !display.messageDelivered { display.displayUnknownMessageNotification(debugInfo: "Not delivered") } } override func serviceExtensionTimeWillExpire() { // Called just before the extension will be terminated by the system. // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used. didFinish(with: .timeout) } } class SyncDataDisplay { var contentHandler: ((UNNotificationContent) -> Void) var notificationContent: UNMutableNotificationContent var sentTabs: [SentTab] var tabQueue: TabQueue? var messageDelivered: Bool = false init(content: UNMutableNotificationContent, contentHandler: @escaping (UNNotificationContent) -> Void, tabQueue: TabQueue) { self.contentHandler = contentHandler self.notificationContent = content self.sentTabs = [] self.tabQueue = tabQueue Sentry.shared.setup(sendUsageData: true) } func displayNotification(_ message: PushMessage? = nil, profile: ExtensionProfile?, with error: PushMessageError? = nil) { guard let message = message, error == nil else { return displayUnknownMessageNotification(debugInfo: "Error \(error?.description ?? "")") } switch message { case .commandReceived(let tab): displayNewSentTabNotification(tab: tab) case .deviceConnected(let deviceName): displayDeviceConnectedNotification(deviceName) case .deviceDisconnected(let deviceName): displayDeviceDisconnectedNotification(deviceName) case .thisDeviceDisconnected: displayThisDeviceDisconnectedNotification() default: displayUnknownMessageNotification(debugInfo: "Unknown: \(message)") break } } } extension SyncDataDisplay { func displayDeviceConnectedNotification(_ deviceName: String) { presentNotification(title: Strings.FxAPush_DeviceConnected_title, body: Strings.FxAPush_DeviceConnected_body, bodyArg: deviceName) } func displayDeviceDisconnectedNotification(_ deviceName: String?) { if let deviceName = deviceName { presentNotification(title: Strings.FxAPush_DeviceDisconnected_title, body: Strings.FxAPush_DeviceDisconnected_body, bodyArg: deviceName) } else { // We should never see this branch presentNotification(title: Strings.FxAPush_DeviceDisconnected_title, body: Strings.FxAPush_DeviceDisconnected_UnknownDevice_body) } } func displayThisDeviceDisconnectedNotification() { presentNotification(title: Strings.FxAPush_DeviceDisconnected_ThisDevice_title, body: Strings.FxAPush_DeviceDisconnected_ThisDevice_body) } func displayAccountVerifiedNotification() { Sentry.shared.send(message: "SentTab error: account not verified") #if MOZ_CHANNEL_BETA || DEBUG presentNotification(title: Strings.SentTab_NoTabArrivingNotification_title, body: "DEBUG: Account Verified") return #endif presentNotification(title: Strings.SentTab_NoTabArrivingNotification_title, body: Strings.SentTab_NoTabArrivingNotification_body) } func displayUnknownMessageNotification(debugInfo: String) { Sentry.shared.send(message: "SentTab error: \(debugInfo)") #if MOZ_CHANNEL_BETA || DEBUG presentNotification(title: Strings.SentTab_NoTabArrivingNotification_title, body: "DEBUG: " + debugInfo) return #endif presentNotification(title: Strings.SentTab_NoTabArrivingNotification_title, body: Strings.SentTab_NoTabArrivingNotification_body) } } extension SyncDataDisplay { func displayNewSentTabNotification(tab: [String: String]) { if let urlString = tab["url"], let url = URL(string: urlString), url.isWebPage(), let title = tab["title"] { let tab = [ "title": title, "url": url.absoluteString, "displayURL": url.absoluteDisplayExternalString, "deviceName": nil ] as NSDictionary notificationContent.userInfo["sentTabs"] = [tab] as NSArray // Add tab to the queue. let item = ShareItem(url: urlString, title: title, favicon: nil) _ = tabQueue?.addToQueue(item).value // Force synchronous. presentNotification(title: Strings.SentTab_TabArrivingNotification_NoDevice_title, body: url.absoluteDisplayExternalString) } } } extension SyncDataDisplay { func presentSentTabsNotification(_ tabs: [NSDictionary]) { let title: String let body: String if tabs.count == 0 { title = Strings.SentTab_NoTabArrivingNotification_title #if MOZ_CHANNEL_BETA || DEBUG body = "DEBUG: Sent Tabs with no tab" #else body = Strings.SentTab_NoTabArrivingNotification_body #endif Sentry.shared.send(message: "SentTab error: no tab") } else { let deviceNames = Set(tabs.compactMap { $0["deviceName"] as? String }) if let deviceName = deviceNames.first, deviceNames.count == 1 { title = String(format: Strings.SentTab_TabArrivingNotification_WithDevice_title, deviceName) } else { title = Strings.SentTab_TabArrivingNotification_NoDevice_title } if tabs.count == 1 { // We give the fallback string as the url, // because we have only just introduced "displayURL" as a key. body = (tabs[0]["displayURL"] as? String) ?? (tabs[0]["url"] as! String) } else if deviceNames.count == 0 { body = Strings.SentTab_TabArrivingNotification_NoDevice_body } else { body = String(format: Strings.SentTab_TabArrivingNotification_WithDevice_body, AppInfo.displayName) } } presentNotification(title: title, body: body) } func presentNotification(title: String, body: String, titleArg: String? = nil, bodyArg: String? = nil) { func stringWithOptionalArg(_ s: String, _ a: String?) -> String { if let a = a { return String(format: s, a) } return s } notificationContent.title = stringWithOptionalArg(title, titleArg) notificationContent.body = stringWithOptionalArg(body, bodyArg) // This is the only place we call the contentHandler. contentHandler(notificationContent) // This is the only place we change messageDelivered. We can check if contentHandler hasn't be called because of // our logic (rather than something funny with our environment, or iOS killing us). messageDelivered = true } } extension SyncDataDisplay: SyncDelegate { func displaySentTab(for url: URL, title: String, from deviceName: String?) { if url.isWebPage() { sentTabs.append(SentTab(url: url, title: title, deviceName: deviceName)) let item = ShareItem(url: url.absoluteString, title: title, favicon: nil) _ = tabQueue?.addToQueue(item).value // Force synchronous. } } } struct SentTab { let url: URL let title: String let deviceName: String? }
mpl-2.0
c9198bbfc84b3ff577d515a8963a9c93
39.73622
142
0.64927
5.287174
false
false
false
false
Anviking/Tentacle
Tests/Fixture.swift
1
4023
// // Fixtures.swift // Tentacle // // Created by Matt Diephouse on 3/3/16. // Copyright © 2016 Matt Diephouse. All rights reserved. // import Argo import Foundation @testable import Tentacle /// A dummy class, so we can ask for the current bundle in Fixture.URL private class ImportedWithFixture { } protocol FixtureType { var server: Server { get } var endpoint: Client.Endpoint { get } } extension FixtureType { /// The filename used for the local fixture, without an extension private func filenameWithExtension(ext: String) -> NSString { let path: NSString = endpoint.path let filename: NSString = path .pathComponents .dropFirst() .joinWithSeparator("-") return filename.stringByAppendingPathExtension(ext)! } /// The filename used for the local fixture's data. var dataFilename: NSString { return filenameWithExtension(Fixture.DataExtension) } /// The filename used for the local fixture's HTTP response. var responseFilename: NSString { return filenameWithExtension(Fixture.ResponseExtension) } /// The URL of the fixture on the API. var URL: NSURL { return NSURLRequest.create(self.server, self.endpoint, nil).URL! } private func fileURLWithExtension(ext: String) -> NSURL { let bundle = NSBundle(forClass: ImportedWithFixture.self) let filename = filenameWithExtension(ext) return bundle.URLForResource(filename.stringByDeletingPathExtension, withExtension: filename.pathExtension)! } /// The URL of the fixture's data within the test bundle. var dataFileURL: NSURL { return fileURLWithExtension(Fixture.DataExtension) } /// The URL of the fixture's HTTP response within the test bundle. var responseFileURL: NSURL { return fileURLWithExtension(Fixture.ResponseExtension) } /// The data from the endpoint. var data: NSData { return NSData(contentsOfURL: dataFileURL)! } /// The HTTP response from the endpoint. var response: NSHTTPURLResponse { let data = NSData(contentsOfURL: responseFileURL)! return NSKeyedUnarchiver.unarchiveObjectWithData(data) as! NSHTTPURLResponse } /// The JSON from the Endpoint. var JSON: NSDictionary { return try! NSJSONSerialization.JSONObjectWithData(data, options: []) as! NSDictionary } /// Decode the fixture's JSON as an object of the returned type. func decode<Object: Decodable where Object.DecodedType == Object>() -> Object? { return Argo.decode(JSON).value } } struct Fixture { private static let DataExtension = "data" private static let ResponseExtension = "response" static var allFixtures: [FixtureType] = [ Release.Carthage0_15, Release.Nonexistent, Release.TagOnly, ] /// Returns the fixture for the given URL, or nil if no such fixture exists. static func fixtureForURL(URL: NSURL) -> FixtureType? { if let index = allFixtures.indexOf({ $0.URL == URL }) { return allFixtures[index] } return nil } struct Release: FixtureType { static var Carthage0_15 = Release(.DotCom, owner: "Carthage", name: "Carthage", tag: "0.15") static var Nonexistent = Release(.DotCom, owner: "mdiep", name: "NonExistent", tag: "tag") static var TagOnly = Release(.DotCom, owner: "torvalds", name: "linux", tag: "v4.4") let server: Server let repository: Repository let tag: String var endpoint: Client.Endpoint { return .ReleaseByTagName(owner: repository.owner, repository: repository.name, tag: tag) } init(_ server: Server, owner: String, name: String, tag: String) { self.server = server repository = Repository(owner: owner, name: name) self.tag = tag } } }
mit
400b0cd06a38d91ff77e2b9617d974e9
31.967213
116
0.64719
4.682189
false
false
false
false
rnystrom/GitHawk
Classes/Views/ClearAllHeaderCell.swift
1
1842
// // SearchRecentHeaderCell.swift // Freetime // // Created by Ryan Nystrom on 9/4/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import UIKit import SnapKit protocol ClearAllHeaderCellDelegate: class { func didSelectClear(cell: ClearAllHeaderCell) } final class ClearAllHeaderCell: UICollectionViewCell { weak var delegate: ClearAllHeaderCellDelegate? private let label = UILabel() private let button = UIButton() override init(frame: CGRect) { super.init(frame: frame) backgroundColor = Styles.Colors.Gray.lighter.color label.font = Styles.Text.secondary.preferredFont label.textColor = Styles.Colors.Gray.medium.color contentView.addSubview(label) label.snp.makeConstraints { make in make.left.equalTo(Styles.Sizes.gutter) make.centerY.equalTo(contentView) } button.setTitle(Constants.Strings.clearAll, for: .normal) button.setTitleColor(Styles.Colors.Blue.medium.color, for: .normal) button.titleLabel?.font = Styles.Text.button.preferredFont button.addTarget(self, action: #selector(ClearAllHeaderCell.onClear), for: .touchUpInside) contentView.addSubview(button) button.snp.makeConstraints { make in make.right.equalTo(-Styles.Sizes.gutter) make.centerY.equalTo(label) } addBorder(.bottom, useSafeMargins: false) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() layoutContentView() } func configure(title text: String) { label.text = text } // MARK: Private API @objc func onClear() { delegate?.didSelectClear(cell: self) } }
mit
31bd31b0211c5a215261ecd37603d89b
26.073529
98
0.667572
4.44686
false
false
false
false
ApacheExpress/ApacheExpress3
Sources/ApacheExpress3/http/ApacheExpressHandler.swift
1
2371
// // Copyright (C) 2017-2019 ZeeZide GmbH, All Rights Reserved // Created by Helge Hess on 26/01/2017. // import CApache public extension http_internal.ApacheServer { // The main entry point to generate ApacheExpress.http server callbacks func handler(request p: UnsafeMutablePointer<request_rec>?) -> Int32 { // Note: `handler` is handled in ApacheExpress let context = http_internal.ApacheRequest(handle: p!, server: self) assert(context.request != nil) // should be there right after init assert(context.response != nil) // invoke server callbacks do { try emitOnRequest(request: context.request!, response: context.response!) } catch (let error) { apz_log_rerror_(#file, #line, -1 /*TBD*/, APLOG_ERR, -1, p, "ApacheExpress handler failed: \(error)") context.onHandlerDone() return HTTP_INTERNAL_SERVER_ERROR } // teardown / finish up let result = context.handlerResult context.onHandlerDone() return result // Note: this is too late to set a different status! } } // MARK: - Raw Request // This could be used, but remember that you usually get a pointer to the // struct, not the struct itself. Hence you would need to do this: // // let method = req?.pointee.oMethod // extension request_rec { var oMethod : String { return String(cString: method) } var oURI : String { return String(cString: uri) } var oUnparsedURI : String { return String(cString: unparsed_uri) } var oHandler : String { return String(cString: handler) } var oTheRequest : String { return String(cString: the_request) } var oProtocol : String { return String(cString: self.protocol) } } // MARK: - Module public extension CApache.module { init(name: String, register_hooks: @escaping @convention(c) (OpaquePointer?) -> Void) { self.init() // Replica of STANDARD20_MODULE_STUFF (could also live as a C support fn) version = MODULE_MAGIC_NUMBER_MAJOR minor_version = MODULE_MAGIC_NUMBER_MINOR module_index = -1 self.name = UnsafePointer(strdup(name)) // leak dynamic_load_handle = nil next = nil magic = MODULE_MAGIC_COOKIE rewrite_args = nil self.register_hooks = register_hooks } }
apache-2.0
e8f2b5ee2594792c6e0e6c3c23a3e677
29.792208
77
0.643189
3.849026
false
false
false
false
PhillipEnglish/TIY-Assignments
VenueMenu/VenueMenu/AppDelegate.swift
1
6097
// // AppDelegate.swift // VenueMenu // // Created by Phillip English on 11/29/15. // Copyright © 2015 The Iron Yard. 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. 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.tiy.VenueMenu" 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("VenueMenu", 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("SingleViewCoreData.sqlite") 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() } } } }
cc0-1.0
c0d9d942cfc698e050b2545c92793eb6
53.918919
291
0.719488
5.895551
false
false
false
false
STShenZhaoliang/STWeiBo
STWeiBo/STWeiBo/Classes/Common/UILabel+Category.swift
1
592
// // UILabel+Category.swift // STWeiBo // // Created by ST on 15/11/17. // Copyright © 2015年 ST. All rights reserved. // import UIKit extension UILabel{ /// 快速创建一个UILabel class func createLabel(color: UIColor, fontSize: CGFloat) -> UILabel { let label = UILabel() label.textColor = color label.font = UIFont.systemFontOfSize(fontSize) return label } convenience init(color: UIColor, fontSize: CGFloat){ self.init() textColor = color font = UIFont.systemFontOfSize(fontSize) } }
mit
204df16ecab8a4125761c65b7dd8a234
18.266667
72
0.615251
4.181159
false
false
false
false
ArnavChawla/InteliChat
Carthage/Checkouts/swift-sdk/Source/NaturalLanguageClassifierV1/NaturalLanguageClassifier.swift
1
14762
/** * Copyright IBM Corporation 2018 * * 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 /** IBM Watson Natural Language Classifier uses machine learning algorithms to return the top matching predefined classes for short text input. You create and train a classifier to connect predefined classes to example texts so that the service can apply those classes to new inputs. */ public class NaturalLanguageClassifier { /// The base URL to use when contacting the service. public var serviceURL = "https://gateway.watsonplatform.net/natural-language-classifier/api" /// The default HTTP headers for all requests to the service. public var defaultHeaders = [String: String]() private let credentials: Credentials private let domain = "com.ibm.watson.developer-cloud.NaturalLanguageClassifierV1" /** Create a `NaturalLanguageClassifier` object. - parameter username: The username used to authenticate with the service. - parameter password: The password used to authenticate with the service. */ public init(username: String, password: String) { self.credentials = .basicAuthentication(username: username, password: password) } /** If the response or data represents an error returned by the Natural Language Classifier service, then return NSError with information about the error that occured. Otherwise, return nil. - parameter response: the URL response returned from the service. - parameter data: Raw data returned from the service that may represent an error. */ private func responseToError(response: HTTPURLResponse?, data: Data?) -> NSError? { // First check http status code in response if let response = response { if (200..<300).contains(response.statusCode) { return nil } } // ensure data is not nil guard let data = data else { if let code = response?.statusCode { return NSError(domain: domain, code: code, userInfo: nil) } return nil // RestKit will generate error for this case } let code = response?.statusCode ?? 400 do { let json = try JSONWrapper(data: data) let error = try? json.getString(at: "error") let description = try? json.getString(at: "description") let userInfo = [NSLocalizedDescriptionKey: error ?? "", NSLocalizedFailureReasonErrorKey: description ?? ""] return NSError(domain: domain, code: code, userInfo: userInfo) } catch { return NSError(domain: domain, code: code, userInfo: nil) } } /** Classify a phrase. Returns label information for the input. The status must be `Available` before you can use the classifier to classify text. - parameter classifierID: Classifier ID to use. - parameter text: The submitted phrase. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func classify( classifierID: String, text: String, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (Classification) -> Void) { // construct body let classifyRequest = ClassifyInput(text: text) guard let body = try? JSONEncoder().encode(classifyRequest) else { failure?(RestError.serializationError) return } // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" // construct REST request let path = "/v1/classifiers/\(classifierID)/classify" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { failure?(RestError.encodingError) return } let request = RestRequest( method: "POST", url: serviceURL + encodedPath, credentials: credentials, headerParameters: headerParameters, messageBody: body ) // execute REST request request.responseObject(responseToError: responseToError) { (response: RestResponse<Classification>) in switch response.result { case .success(let retval): success(retval) case .failure(let error): failure?(error) } } } /** Classify multiple phrases. Returns label information for multiple phrases. The status must be `Available` before you can use the classifier to classify text. Note that classifying Japanese texts is a beta feature. - parameter classifierID: Classifier ID to use. - parameter collection: The submitted phrases. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func classifyCollection( classifierID: String, collection: [ClassifyInput], headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (ClassificationCollection) -> Void) { // construct body let classifyCollectionRequest = ClassifyCollectionInput(collection: collection) guard let body = try? JSONEncoder().encode(classifyCollectionRequest) else { failure?(RestError.serializationError) return } // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" // construct REST request let path = "/v1/classifiers/\(classifierID)/classify_collection" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { failure?(RestError.encodingError) return } let request = RestRequest( method: "POST", url: serviceURL + encodedPath, credentials: credentials, headerParameters: headerParameters, messageBody: body ) // execute REST request request.responseObject(responseToError: responseToError) { (response: RestResponse<ClassificationCollection>) in switch response.result { case .success(let retval): success(retval) case .failure(let error): failure?(error) } } } /** Create classifier. Sends data to create and train a classifier and returns information about the new classifier. - parameter metadata: Metadata in JSON format. The metadata identifies the language of the data, and an optional name to identify the classifier. Specify the language with the 2-letter primary language code as assigned in ISO standard 639. Supported languages are English (`en`), Arabic (`ar`), French (`fr`), German, (`de`), Italian (`it`), Japanese (`ja`), Korean (`ko`), Brazilian Portuguese (`pt`), and Spanish (`es`). - parameter trainingData: Training data in CSV format. Each text value must have at least one class. The data can include up to 20,000 records. For details, see [Data preparation](https://console.bluemix.net/docs/services/natural-language-classifier/using-your-data.html). - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func createClassifier( metadata: URL, trainingData: URL, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (Classifier) -> Void) { // construct body let multipartFormData = MultipartFormData() multipartFormData.append(metadata, withName: "training_metadata") multipartFormData.append(trainingData, withName: "training_data") guard let body = try? multipartFormData.toData() else { failure?(RestError.encodingError) return } // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = multipartFormData.contentType // construct REST request let request = RestRequest( method: "POST", url: serviceURL + "/v1/classifiers", credentials: credentials, headerParameters: headerParameters, messageBody: body ) // execute REST request request.responseObject(responseToError: responseToError) { (response: RestResponse<Classifier>) in switch response.result { case .success(let retval): success(retval) case .failure(let error): failure?(error) } } } /** List classifiers. Returns an empty array if no classifiers are available. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func listClassifiers( headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (ClassifierList) -> Void) { // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" // construct REST request let request = RestRequest( method: "GET", url: serviceURL + "/v1/classifiers", credentials: credentials, headerParameters: headerParameters ) // execute REST request request.responseObject(responseToError: responseToError) { (response: RestResponse<ClassifierList>) in switch response.result { case .success(let retval): success(retval) case .failure(let error): failure?(error) } } } /** Get information about a classifier. Returns status and other information about a classifier. - parameter classifierID: Classifier ID to query. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func getClassifier( classifierID: String, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping (Classifier) -> Void) { // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" // construct REST request let path = "/v1/classifiers/\(classifierID)" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { failure?(RestError.encodingError) return } let request = RestRequest( method: "GET", url: serviceURL + encodedPath, credentials: credentials, headerParameters: headerParameters ) // execute REST request request.responseObject(responseToError: responseToError) { (response: RestResponse<Classifier>) in switch response.result { case .success(let retval): success(retval) case .failure(let error): failure?(error) } } } /** Delete classifier. - parameter classifierID: Classifier ID to delete. - parameter headers: A dictionary of request headers to be sent with this request. - parameter failure: A function executed if an error occurs. - parameter success: A function executed with the successful result. */ public func deleteClassifier( classifierID: String, headers: [String: String]? = nil, failure: ((Error) -> Void)? = nil, success: @escaping () -> Void) { // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } headerParameters["Accept"] = "application/json" // construct REST request let path = "/v1/classifiers/\(classifierID)" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { failure?(RestError.encodingError) return } let request = RestRequest( method: "DELETE", url: serviceURL + encodedPath, credentials: credentials, headerParameters: headerParameters ) // execute REST request request.responseVoid(responseToError: responseToError) { (response: RestResponse) in switch response.result { case .success: success() case .failure(let error): failure?(error) } } } }
mit
f8212d5067bc2128d61481021ab8648b
37.342857
139
0.634806
5.183287
false
false
false
false
xibe/WordPress-iOS
WordPress/Classes/Networking/Remote Objects/RemoteNotificationSettings.swift
10
7519
import Foundation /** * @class RemoteNotificationSettings * @brief The goal of this class is to parse Notification Settings data from the backend, and structure it * in a meaningful way. Notification Settings come in three different flavors: * * - "Our Own" Blog Settings * - "Third Party" Site Settings * - WordPress.com Settings * * Each one of the possible channels may post notifications via different streams: Email, * Push Notifications, and Timeline. */ public class RemoteNotificationSettings { /** * @details Represents the Channel to which the current settings are associated. */ public let channel : Channel /** * @details Contains an array of the available Notification Streams. */ public let streams : [Stream] /** * @enum Channel * @brief Represents a communication channel that may post notifications to the user. */ public enum Channel : Equatable { case Blog(blogId: Int) case Other case WordPressCom } /** * @class Stream * @brief Contains the Notification Settings for a specific communications stream. */ public class Stream { public var kind : Kind public var preferences : [String : Bool]? /** * @enum Stream.Kind * @brief Enumerates all of the possible Stream Kinds */ public enum Kind : String { case Timeline = "timeline" case Email = "email" case Device = "device" static let allValues = [ Timeline, Email, Device ] } /** * @details Private Designated Initializer * @param kind The Kind of stream we're currently dealing with * @param preferences Raw remote preferences, retrieved from the backend */ private init(kind: Kind, preferences: NSDictionary?) { self.kind = kind self.preferences = filterNonBooleanEntries(preferences) } /** * @brief Helper method that will filter out non boolean entries, and return a native Swift collection. * @param dictionary NextStep Dictionary containing raw values * @return A native Swift dictionary, containing only the Boolean entries */ private func filterNonBooleanEntries(dictionary: NSDictionary?) -> [String : Bool] { var filtered = [String : Bool]() if dictionary == nil { return filtered } for (key, value) in dictionary! { if let stringKey = key as? String, let boolValue = value as? Bool { // NSNumbers might get converted to Bool anyways if value === kCFBooleanFalse || value === kCFBooleanTrue { filtered[stringKey] = boolValue } } } return filtered } /** * @brief Parser method that will convert a raw dictionary of stream settings into Swift Native objects. * @param dictionary NextStep Dictionary containing raw Stream Preferences * @return A native Swift array containing Stream entities */ private static func fromDictionary(dictionary: NSDictionary?) -> [Stream] { var parsed = [Stream]() for kind in Kind.allValues { if let preferences = dictionary?[kind.rawValue] as? NSDictionary { parsed.append(Stream(kind: kind, preferences: preferences)) } } return parsed } } /** * @details Private Designated Initializer * @param channel The communications channel that uses the current settings * @param settings Raw dictionary containing the remote settings response */ private init(channel: Channel, settings: NSDictionary?) { self.channel = channel self.streams = Stream.fromDictionary(settings) } /** * @details Private Designated Initializer * @param wpcomSettings Dictionary containing the collection of WordPress.com Settings */ private init(wpcomSettings: NSDictionary?) { // WordPress.com is a special scenario: It contains just one (unspecified) stream: Email self.channel = Channel.WordPressCom self.streams = [ Stream(kind: .Email, preferences: wpcomSettings) ] } /** * @details Private Convenience Initializer * @param blogSettings Dictionary containing the collection of settings for a single blog */ private convenience init(blogSettings: NSDictionary?) { let blogId = blogSettings?["blog_id"] as? Int ?? Int.max self.init(channel: Channel.Blog(blogId: blogId), settings: blogSettings) } /** * @details Private Convenience Initializer * @param otherSettings Dictionary containing the collection of "Other Settings" */ private convenience init(otherSettings: NSDictionary?) { self.init(channel: Channel.Other, settings: otherSettings) } /** * @details Static Helper that will parse all of the Remote Settings, into a collection of * Swift Native RemoteNotificationSettings objects * @param dictionary Dictionary containing the remote Settings response * @returns An array of RemoteNotificationSettings objects */ public static func fromDictionary(dictionary: NSDictionary?) -> [RemoteNotificationSettings] { var parsed = [RemoteNotificationSettings]() if let rawBlogs = dictionary?["blogs"] as? [NSDictionary] { for rawBlog in rawBlogs { let parsedBlog = RemoteNotificationSettings(blogSettings: rawBlog) parsed.append(parsedBlog) } } let other = RemoteNotificationSettings(otherSettings: dictionary?["other"] as? NSDictionary) parsed.append(other) let wpcom = RemoteNotificationSettings(wpcomSettings: dictionary?["wpcom"] as? NSDictionary) parsed.append(wpcom) return parsed } } /** * @brief RemoteNotificationSettings.Channel Equatable Implementation * @details Swift requires this method to be implemented globally. Sorry about that! * * @param lhs Left Hand Side Channel * @param rhs Right Hand Side Channel * @returns A boolean indicating whether two channels are equal. Or not! */ public func ==(lhs: RemoteNotificationSettings.Channel, rhs: RemoteNotificationSettings.Channel) -> Bool { switch (lhs, rhs) { case (let .Blog(firstBlogId), let .Blog(secondBlogId)) where firstBlogId == secondBlogId: return true case (.Other, .Other): return true case (.WordPressCom, .WordPressCom): return true default: return false } }
gpl-2.0
4d5eb4baf23e2d5d40e1e5c3162833ee
34.804762
116
0.57614
5.336409
false
false
false
false
giapnh/TadiSDK
TadiSDK/Classes/Core/BaseModel.swift
1
808
// // BaseModel.swift // TADISharedSDK // Version: 1.0 // // Created by Duong Van Lam on 11/9/16. // Copyright © 2016 TADI. All rights reserved. // import Foundation class BaseModel { static let DEFAULT_INT = -1 static let DEFAULT_STRING = "" static let DEFAULT_FLOAT: Float = -1.0 static let DEFAULT_BOOL = false static let DEFAULT_STRING_ARRAY = [String]() required init() { } required init(json: JSONObject) { from(json: json) } func from(json: JSONObject) { preconditionFailure("This method must be overridden") } func toJson() -> JSONObject { preconditionFailure("This method must be overridden") } func toString() -> String { return "\(self.toJson().toString())" } }
mit
3ea74c3a0c8ad90fe1fc73273c477668
19.692308
61
0.593556
4.014925
false
false
false
false
AntiMoron/SwiftyNSDictionary
Sources/SwiftyNSDictionary.swift
1
1462
// Author: AntiMoron // Createtime: 2017-02-21 import Foundation //MARK: swift 3 private func getImpl_<T>(_ o: Any?) -> T? { if let o_ = o as? T { return o_ } return nil } public extension NSDictionary { private func get<T>(_ key: String) -> T? { let ret: T? = getImpl_(flatten(self.object(forKey: key))) return ret } private func flatten(_ o: Any?) -> Any? { guard let o_ = o else { return nil } switch o_ { case let _ as NSNull: return nil case let num as NSNumber: return num.doubleValue case let str as NSString: return String(str) case let arr as [Any]: return arr.flatMap { flatten($0) } case let dict as [String: Any]: var ret = [String: Any]() _ = dict.flatMap { ret[$0.0] = flatten($0.1) } return ret default: return o_ } } public func valueAsInt(forKey: String) -> Int? { return get(forKey) } public func valueAsArray(forKey: String) -> [Any]? { return get(forKey) } public func valueAsDouble(forKey: String) -> Double? { return get(forKey) } public func valueAsBool(forKey: String) -> Bool? { return get(forKey) } public func valueAsDictionary(forKey: String) -> [String: Any]? { return get(forKey) } public func valueAsString(forKey: String) -> String? { return get(forKey) } public func valueAsAny(forKey: String) -> Any? { return get(forKey) } }
mit
0cb8e90ab4d83f465fdadcd4e79f3634
23.366667
67
0.593023
3.557178
false
false
false
false
foresterre/mal
swift3/Sources/step4_if_fn_do/main.swift
8
4148
import Foundation // read func READ(_ str: String) throws -> MalVal { return try read_str(str) } // eval func eval_ast(_ ast: MalVal, _ env: Env) throws -> MalVal { switch ast { case MalVal.MalSymbol: return try env.get(ast) case MalVal.MalList(let lst, _): return list(try lst.map { try EVAL($0, env) }) case MalVal.MalVector(let lst, _): return vector(try lst.map { try EVAL($0, env) }) case MalVal.MalHashMap(let dict, _): var new_dict = Dictionary<String,MalVal>() for (k,v) in dict { new_dict[k] = try EVAL(v, env) } return hash_map(new_dict) default: return ast } } func EVAL(_ ast: MalVal, _ env: Env) throws -> MalVal { switch ast { case MalVal.MalList(let lst, _): if lst.count == 0 { return ast } default: return try eval_ast(ast, env) } switch ast { case MalVal.MalList(let lst, _): switch lst[0] { case MalVal.MalSymbol("def!"): return try env.set(lst[1], try EVAL(lst[2], env)) case MalVal.MalSymbol("let*"): let let_env = try Env(env) var binds = Array<MalVal>() switch lst[1] { case MalVal.MalList(let l, _): binds = l case MalVal.MalVector(let l, _): binds = l default: throw MalError.General(msg: "Invalid let* bindings") } var idx = binds.startIndex while idx < binds.endIndex { let v = try EVAL(binds[binds.index(after: idx)], let_env) try let_env.set(binds[idx], v) idx = binds.index(idx, offsetBy: 2) } return try EVAL(lst[2], let_env) case MalVal.MalSymbol("do"): let slc = lst[lst.index(after: lst.startIndex)..<lst.endIndex] switch try eval_ast(list(Array(slc)), env) { case MalVal.MalList(let elst, _): return elst[elst.index(before: elst.endIndex)] default: throw MalError.General(msg: "Invalid do form") } case MalVal.MalSymbol("if"): switch try EVAL(lst[1], env) { case MalVal.MalFalse, MalVal.MalNil: if lst.count > 3 { return try EVAL(lst[3], env) } else { return MalVal.MalNil } default: return try EVAL(lst[2], env) } case MalVal.MalSymbol("fn*"): return malfunc( { return try EVAL(lst[2], Env(env, binds: lst[1], exprs: list($0))) }) default: switch try eval_ast(ast, env) { case MalVal.MalList(let elst, _): switch elst[0] { case MalVal.MalFunc(let fn,_,_,_,_,_): let args = Array(elst[1..<elst.count]) return try fn(args) default: throw MalError.General(msg: "Cannot apply on '\(elst[0])'") } default: throw MalError.General(msg: "Invalid apply") } } default: throw MalError.General(msg: "Invalid apply") } } // print func PRINT(_ exp: MalVal) -> String { return pr_str(exp, true) } // repl @discardableResult func rep(_ str:String) throws -> String { return PRINT(try EVAL(try READ(str), repl_env)) } var repl_env: Env = try Env() // core.swift: defined using Swift for (k, fn) in core_ns { try repl_env.set(MalVal.MalSymbol(k), malfunc(fn)) } // core.mal: defined using the language itself try rep("(def! not (fn* (a) (if a false true)))") while true { print("user> ", terminator: "") let line = readLine(strippingNewline: true) if line == nil { break } if line == "" { continue } do { print(try rep(line!)) } catch (MalError.Reader(let msg)) { print("Error: \(msg)") } catch (MalError.General(let msg)) { print("Error: \(msg)") } catch (MalError.MalException(let obj)) { print("Error: \(pr_str(obj, true))") } }
mpl-2.0
fdbb05568eff8e9d4d10fe713c96ab50
30.18797
79
0.517117
3.924314
false
false
false
false
dche/FlatCG
Sources/Bounds.swift
1
5900
// // FlatCG - Circle.swift // // Copyright (c) 2016 The FlatCG authors. // Licensed under MIT License. import simd import GLMath /// Axis-aligned bounding box. public protocol Bounds: Equatable, CustomDebugStringConvertible, Transformable { associatedtype PointType: Point var pmin: PointType { get } var pmax: PointType { get } init (_ a: PointType, _ b: PointType) /// A degenerate bounding box that can be contained in any boxes. static var empty: Self { get } var surfaceArea: PointType.VectorType.Component { get } func contains(point: PointType) -> Bool } extension Bounds { public init (_ point: PointType) { self.init(point, point) } public static func == (lhs: Self, rhs: Self) -> Bool { return lhs.pmin == rhs.pmin && lhs.pmax == rhs.pmax } public var debugDescription: String { return "Bounds(min: \(pmin), max: \(pmax))" } } extension Bounds { /// Returns `true` if the receiver is the empty bounding box. public var isEmpty: Bool { return self == .empty } /// Merges the receiver with `other` `Bounds`. /// /// - returns: The new `Bounds`. public func merge(_ other: Self) -> Self { guard !self.isEmpty else { return other } let mn = min(self.pmin.vector, other.pmin.vector) let mx = max(self.pmax.vector, other.pmax.vector) return Self(PointType(mn), PointType(mx)) } public func merge(point: PointType) -> Self { let v = point.vector let mn = min(self.pmin.vector, v) let mx = max(self.pmax.vector, v) return Self(PointType(mn), PointType(mx)) } /// Constructs a `Bounds` that contains all the `points`. public init (of points: [PointType]) { if points.count < 1 { self = .empty } else { var mn = points[0].vector var mx = points[0].vector for p in points.dropFirst() { mn = min(mn, p.vector) mx = max(mx, p.vector) } self = Self(PointType(mn), PointType(mx)) } } /// Expands the bounding box by the amound `delta` in all dimensions. public func expand(_ delta: PointType.VectorType.Component) -> Self { let d = PointType.VectorType(max(delta, 0)) let mn = pmin.vector - d let mx = pmax.vector + d return Self(PointType(mn), PointType(mx)) } } extension Bounds { /// Center of the bounding box. public var center: PointType { if self.isEmpty { return PointType.origin } return PointType((self.pmax.vector + self.pmin.vector) * 0.5) } /// The vector from the minimal point of the `Bounds` to its maximal /// point. public var diagnal: PointType.VectorType { if self.isEmpty { return .zero } return self.pmax.vector - self.pmin.vector } public var extent: PointType.VectorType { return self.diagnal * 0.5 } } /// 2D axis-aligned bounding box. public struct Bounds2<T: Point>: Bounds where T: Transformable, T.TransformType == Transform<T>, T.VectorType: Vector2 { public typealias PointType = T public let pmin, pmax: T private init (_ mn: T.VectorType, _ mx: T.VectorType) { self.pmin = PointType(mn) self.pmax = PointType(mx) } public init(_ a: PointType, _ b: PointType) { self.init(min(a.vector, b.vector), max(a.vector, b.vector)) } public static var empty: Bounds2<T> { return Bounds2<T>(.infinity, -.infinity) } public var surfaceArea: T.VectorType.Component { let d = diagnal return d.x * d.y } public func contains(point: T) -> Bool { let v = point.vector let vmn = pmin.vector let vmx = pmax.vector return v.x >= vmn.x && v.x <= vmx.x && v.y >= vmn.y && v.y <= vmx.y } public func apply(transform: Transform<T>) -> Bounds2<T> { let pts = [ pmin, pmax, T(T.VectorType(pmin.vector.x, pmax.vector.y)), T(T.VectorType(pmax.vector.x, pmin.vector.y)) ] return Bounds2<T>(of: pts.map { $0.apply(transform: transform) }) } } /// 3D axis-aligned bounding box. public struct Bounds3D: Bounds { public typealias PointType = Point3D public let pmin, pmax: Point3D private init (_ mn: vec3, _ mx: vec3) { self.pmin = PointType(mn) self.pmax = PointType(mx) } public init(_ a: Point3D, _ b: Point3D) { self.init(min(a.vector, b.vector), max(a.vector, b.vector)) } public static var empty: Bounds3D { return Bounds3D(.infinity, -.infinity) } public var surfaceArea: Float { let d: vec3 = self.diagnal let a0 = d.x * d.y let a1 = d.y * d.z let a2 = d.z * d.x return (a0 + a1 + a2) * 2 } public var volume: Float { let d = diagnal return d.x * d.y * d.z } public func contains(point: Point3D) -> Bool { let v = point.vector let vmn = pmin.vector let vmx = pmax.vector return v.x >= vmn.x && v.x <= vmx.x && v.y >= vmn.y && v.y <= vmx.y && v.z >= vmn.z && v.z <= vmx.z } public func apply(transform: Transform3D) -> Bounds3D { let m = transform.matrix var nmin = m[3].xyz var nmax = nmin for i in 0 ..< 3 { for j in 0 ..< 3 { let x = m[j, i] * self.pmin.vector[j] let y = m[j, i] * self.pmax.vector[j] if x < y { nmin[i] += x nmax[i] += y } else { nmin[i] += y nmax[i] += x } } } return Bounds3D(Point3D(nmin), Point3D(nmax)) } } public typealias Bounds2D = Bounds2<Point2D>
mit
89a86beec4e1836a462a0c89c8145ed0
26.570093
120
0.556441
3.520286
false
false
false
false
thomaskamps/SlideFeedback
SlideFeedback/SlideFeedback/HistoryViewController.swift
1
3673
// // HistoryViewController.swift // SlideFeedback // // Created by Thomas Kamps on 22-06-17. // Copyright © 2017 Thomas Kamps. All rights reserved. // import UIKit class HistoryViewController: UIViewController { // declare outlets @IBOutlet weak var tableView: UITableView! // declare models let db = FirebaseManager.sharedInstance override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.tableView.delegate = self self.tableView.dataSource = self NotificationCenter.default.addObserver(self, selector: #selector(self.newHistory(notification:)), name: Notification.Name("newHistory"), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.alertConnection(notification:)), name: Notification.Name("alertConnection"), object: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(_ animated: Bool) { // when view appears get history from db db.getHistory() } deinit { NotificationCenter.default.removeObserver(self) } func newHistory(notification: Notification) { // when new history is pushed, reload tableView tableView.reloadData() } } extension HistoryViewController: UITableViewDelegate { override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showHistorySegue" { // prepare data for next viewController let vc = segue.destination as! HistorySlideViewController let unique_id = Array(db.history!.keys)[(tableView.indexPathForSelectedRow?.row)!] var data = self.db.history?[unique_id] // add/rename a few items data?["timestamp"] = data?["timeStamp"] data?["unique_id"] = unique_id data?["currentPage"] = 0 // set currentPresentation vc.currentPresentation = Slide(data: data!) } } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == UITableViewCellEditingStyle.delete { // fetch ID let uniqueID = Array(self.db.history!.keys)[indexPath.row] // remove slides self.db.history!.removeValue(forKey: uniqueID) self.db.deletePresentation(uniqueID: uniqueID) tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic) } } } extension HistoryViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // check if any slides are there, return count if db.history != nil { return db.history!.keys.count } else { return 0 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // create cell let cell = self.tableView.dequeueReusableCell(withIdentifier: "historyCell", for: indexPath) as! HistoryTableViewCell let test = db.history?[Array(db.history!.keys)[indexPath.row]] cell.label.text = (test?["timeStamp"] as? String)! + " - " + (test?["name"] as? String)! return cell } }
unlicense
56eb7a6eca9428cf1da7750500736351
31.495575
167
0.615741
5.275862
false
false
false
false
dnseitz/YAPI
YAPI/YAPI/V2/V2_YelpBusinessDataModels.swift
1
12753
// // YelpDataModels.swift // Chowroulette // // Created by Daniel Seitz on 7/24/16. // Copyright © 2016 Daniel Seitz. All rights reserved. // import Foundation import UIKit public struct YelpBusiness { /// Yelp ID for business public let id: String /// Whether business has been claimed by a business owner public let claimed: Bool /// Whether business has been (permenantly) closed public let closed: Bool /// Name of this business public let name: String /// url of photo for this business public let image: ImageReference? /// url for business page on Yelp public let url: URL /// url for mobile business page on Yelp public let mobileURL: URL /// Phone number for this business with international dialing code (e.g. +442079460000) public let phoneNumber: String? /// Phone number for this business formatted for display public let displayPhoneNumber: String? /// Number of reviews for this business public let reviewCount: Int /// Provides a list of category name, alias pairs that this business is associated with. For example, [["Local Flavor", "localflavor"], ["Active Life", "active"], ["Mass Media", "massmedia"]] The alias is provided so you can search with the category_filter. public let categories: [YelpCategory] public let rating: YelpRating public let snippet: YelpSnippet /// Location data for this business public let location: YelpLocation /// Deal info for this business (optional: this field is present only if there’s a Deal) public let deals: [YelpDeal]? /// Gift certificate info for this business (optional: this field is present only if there are gift certificates available) public let giftCertificates: [YelpGiftCertificate]? /// Provider of the menu for this busin public let menuProvider: String? /// Last time this menu was updated on Yelp (Unix timestamp) public let menuUpdateDate: Int? /// URL to the SeatMe reservation page for this business. This key will not be present if the business does not take reservations through SeatMe or if the query param 'actionlinks' is not set to True in the request public let reservationURL: URL? /// URL to the Eat24 page for this business. This key will not be present if the business does not offer delivery through Eat24 or if the query param 'actionlinks' is not set to True in the request public let eat24URL: URL? init(withDict dict: [String: AnyObject]) { self.id = dict["id"] as! String self.claimed = dict["is_claimed"] as! Bool self.closed = dict["is_closed"] as! Bool self.name = dict["name"] as! String if let imageURL = dict["image_url"] as? String { self.image = ImageReference(from: URL(string: imageURL)!) } else { self.image = nil } self.url = URL(string: dict["url"] as! String)! self.mobileURL = URL(string: dict["mobile_url"] as! String)! self.phoneNumber = dict["phone"] as? String self.displayPhoneNumber = dict["display_phone"] as? String self.reviewCount = dict["review_count"] as! Int var categories = [YelpCategory]() for category in dict["categories"] as! [[String]] { let yelpCategory = YelpCategory(withTuple: category) categories.append(yelpCategory) } self.categories = categories self.rating = YelpRating(withDict: dict) self.snippet = YelpSnippet(withDict: dict) self.location = YelpLocation(withDict: dict["location"] as! [String: AnyObject]) if let deals = dict["deals"] as? [[String: AnyObject]] { var yelpDeals = [YelpDeal]() for deal in deals { let yelpDeal = YelpDeal(withDict: deal) yelpDeals.append(yelpDeal) } self.deals = yelpDeals } else { self.deals = nil } if let certificates = dict["gift_certificates"] as? [[String: AnyObject]] { var yelpCertificates = [YelpGiftCertificate]() for certificate in certificates { let yelpCertificate = YelpGiftCertificate(withDict: certificate) yelpCertificates.append(yelpCertificate) } self.giftCertificates = yelpCertificates } else { self.giftCertificates = nil } self.menuProvider = dict["menu_provider"] as? String self.menuUpdateDate = dict["menu_date_updated"] as? Int if let reservationURL = dict["reservation_url"] as? String { self.reservationURL = URL(string: reservationURL) } else { self.reservationURL = nil } if let eat24URL = dict["eat24_url"] as? String { self.eat24URL = URL(string: eat24URL) } else { self.eat24URL = nil } } } public struct YelpCategory { private enum Params { static let alias = "alias" static let title = "title" } public let categoryName: String public let alias: String init(withTuple tuple: [String]) { self.categoryName = tuple[0] self.alias = tuple[1] } init(withDict dict: [String: AnyObject]) throws { self.categoryName = try dict.parseParam(key: Params.title) self.alias = try dict.parseParam(key: Params.alias) } init(name: String, alias: String) { self.categoryName = name self.alias = alias } } public struct YelpRating { /// Rating for this business (value ranges from 1, 1.5, ... 4.5, 5) public let rating: Float /// URL to star rating image for this business (size = 84x17) public let image: ImageReference /// URL to small version of rating image for this business (size = 50x10) public let smallImage: ImageReference /// URL to large version of rating image for this business (size = 166x30) public let largeImage: ImageReference init(withDict dict: [String: AnyObject]) { self.rating = dict["rating"] as! Float self.image = ImageReference(from: URL(string: dict["rating_img_url"] as! String)!) self.smallImage = ImageReference(from: URL(string: dict["rating_img_url_small"] as! String)!) self.largeImage = ImageReference(from: URL(string: dict["rating_img_url_large"] as! String)!) } } public struct YelpSnippet { /// Snippet text associated with this business public let text: String? /// URL of snippet image associated with this business public let image: ImageReference? init(withDict dict: [String: AnyObject]) { self.text = dict["snippet_text"] as? String if let imageURL = dict["snippet_image_url"] as? String { self.image = ImageReference(from: URL(string: imageURL)!) } else { self.image = nil } } } public struct YelpLocation { /// Address for this business. Only includes address fields. public let address: [String] /// Address for this business formatted for display. Includes all address fields, cross streets and city, state_code, etc. public let displayAddress: [String] /// City for this business public let city: String /// ISO 3166-2 state code for this business public let stateCode: String /// Postal code for this business public let postalCode: String? /// ISO 3166-1 country code for this business public let countryCode: String /// Cross streets for this business public let crossStreets: String? /// List that provides neighborhood(s) information for business public let neighborhoods: [String]? /// Coordinates of this location. This will be omitted if coordinates are not known for the location. public let coordinate: YelpGeoLocation? public let geoAccuraccy: Float init(withDict dict: [String: AnyObject]) { self.address = dict["address"] as! [String] self.displayAddress = dict["display_address"] as! [String] self.city = dict["city"] as! String self.stateCode = dict["state_code"] as! String self.postalCode = dict["postal_code"] as? String self.countryCode = dict["country_code"] as! String self.crossStreets = dict["cross_streets"] as? String self.neighborhoods = dict["neighborhoods"] as? [String] if let coordinate = dict["coordinate"] as? [String: Double] { self.coordinate = YelpGeoLocation(withDict: coordinate) } else { self.coordinate = nil } self.geoAccuraccy = dict["geo_accuracy"] as! Float } } public struct YelpGeoLocation { public let latitude: Double public let longitude: Double init(withDict dict: [String: Double]) { self.latitude = dict["latitude"]! self.longitude = dict["longitude"]! } } public struct YelpDeal { /// Deal identifier public let id: String? /// Deal title public let title: String /// Deal url public let url: URL /// Deal image url public let image: ImageReference /// ISO_4217 Currency Code public let currencyCode: String /// Deal start time (Unix timestamp) public let startTime: Int /// Deal end time (optional: this field is present only if the Deal ends) public let endTime: Int? /// Whether the Deal is popular (optional: this field is present only if true) public let popular: Bool? /// Additional details for the Deal, separated by newlines public let details: String? /// Important restrictions for the Deal, separated by newlines public let importantRestrictions: String? /// Deal additional restrictions public let additionalRestrictions: String? /// Deal options public let options: [YelpDealOptions] init(withDict dict: [String: AnyObject]) { self.id = dict["id"] as? String self.title = dict["title"] as! String self.url = URL(string: dict["url"] as! String)! self.image = ImageReference(from: URL(string: dict["image_url"] as! String)!) self.currencyCode = dict["currency_code"] as! String self.startTime = dict["time_start"] as! Int self.endTime = dict["time_end"] as? Int self.popular = dict["is_popular"] as? Bool self.details = dict["what_you_get"] as? String self.importantRestrictions = dict["important_restrictions"] as? String self.additionalRestrictions = dict["additional_restrictions"] as? String var options = [YelpDealOptions]() for option in dict["options"] as! [[String: AnyObject]] { let yelpDealOption = YelpDealOptions(withDict: option) options.append(yelpDealOption) } self.options = options } } public struct YelpDealOptions { /// Deal option title public let title: String /// Deal option url for purchase public let purchaseURL: URL /// Deal option price (in cents) public let price: Int /// Deal option price (formatted, e.g. "$6") public let formattedPrice: String /// Deal option original price (in cents) public let originalPrice: Int /// Deal option original price (formatted, e.g. "$12") public let formattedOriginalPrice: String /// Whether the deal option is limited or unlimited public let limitedQuantity: Bool /// The remaining deal options available for purchase (optional: this field is only present if the deal is limited) public let remainingCount: Int? init(withDict dict: [String: AnyObject]) { self.title = dict["title"] as! String self.purchaseURL = URL(string: dict["purchase_url"] as! String)! self.price = dict["price"] as! Int self.formattedPrice = dict["formatted_price"] as! String self.originalPrice = dict["original_price"] as! Int self.formattedOriginalPrice = dict["formatted_original_price"] as! String self.limitedQuantity = dict["is_quantity_limited"] as! Bool self.remainingCount = dict["remaining_count"] as? Int } } public struct YelpGiftCertificate { /// Gift certificate identifier public let id: String /// Gift certificate landing page url public let url: URL /// Gift certificate image url public let image: ImageReference /// ISO_4217 Currency Code public let currencyCode: String /// Whether unused balances are returned as cash or store credit public let unusedBalances: String /// Gift certificate options public let options: [YelpGiftCertificateOption] init(withDict dict: [String: AnyObject]) { self.id = dict["id"] as! String self.url = URL(string: dict["url"] as! String)! self.image = ImageReference(from: URL(string: dict["image_url"] as! String)!) self.currencyCode = dict["currency_code"] as! String self.unusedBalances = dict["unused_balances"] as! String var options = [YelpGiftCertificateOption]() for option in dict["options"] as! [[String: AnyObject]] { let yelpOption = YelpGiftCertificateOption(withDict: option) options.append(yelpOption) } self.options = options } } public struct YelpGiftCertificateOption { /// Gift certificate option price (in cents) public let price: Int /// Gift certificate option price (formatted, e.g. "$50") public let formattedPrice: String init(withDict dict: [String: AnyObject]) { self.price = dict["price"] as! Int self.formattedPrice = dict["formatted_price"] as! String } }
mit
608555a4d28b0a3e17b262bc45d98f00
36.390029
259
0.696
4.066986
false
false
false
false
guidomb/Portal
Portal/View/Components/Progress.swift
1
3496
// // Progress.swift // PortalView // // Created by Cristian Ames on 4/11/17. // Copyright © 2017 Guido Marucci Blas. All rights reserved. // public struct ProgressCounter { public static let initial = ProgressCounter() // sourcery: ignoreInChangeSet public var partial: UInt // sourcery: ignoreInChangeSet public let total: UInt public var progress: Float { return Float(partial) / Float(total) } // sourcery: ignoreInChangeSet public var remaining: UInt { return total - partial } private init() { partial = 0 total = 1 } public init?(partial: UInt, total: UInt) { guard partial <= total else { return nil } self.partial = partial self.total = total } public func add(progress: UInt) -> ProgressCounter? { return ProgressCounter(partial: partial + progress, total: total) } } public func progress<MessageType>( progress: ProgressCounter = ProgressCounter.initial, style: StyleSheet<ProgressStyleSheet> = ProgressStyleSheet.defaultStyleSheet, layout: Layout = layout()) -> Component<MessageType> { return .progress(progress, style, layout) } // MARK: - Style sheet public enum ProgressContentType: AutoEquatable { case color(Color) case image(Image) } public struct ProgressStyleSheet: AutoPropertyDiffable { public static let defaultStyleSheet = StyleSheet<ProgressStyleSheet>(component: ProgressStyleSheet()) public var progressStyle: ProgressContentType public var trackStyle: ProgressContentType public init( progressStyle: ProgressContentType = .color(defaultProgressColor), trackStyle: ProgressContentType = .color(defaultTrackColor)) { self.progressStyle = progressStyle self.trackStyle = trackStyle } } public func progressStyleSheet( configure: (inout BaseStyleSheet, inout ProgressStyleSheet) -> Void) -> StyleSheet<ProgressStyleSheet> { var base = BaseStyleSheet() var custom = ProgressStyleSheet() configure(&base, &custom) return StyleSheet(component: custom, base: base) } // MARK: Change Set public struct ProgressChangeSet { static func fullChangeSet( progress: ProgressCounter, style: StyleSheet<ProgressStyleSheet>, layout: Layout) -> ProgressChangeSet { return ProgressChangeSet( progress: .change(to: progress), baseStyleSheet: style.base.fullChangeSet, progressStyleSheet: style.component.fullChangeSet, layout: layout.fullChangeSet ) } let progress: PropertyChange<ProgressCounter> let baseStyleSheet: [BaseStyleSheet.Property] let progressStyleSheet: [ProgressStyleSheet.Property] let layout: [Layout.Property] var isEmpty: Bool { guard case .noChange = progress else { return false } return baseStyleSheet.isEmpty && progressStyleSheet.isEmpty && layout.isEmpty } init( progress: PropertyChange<ProgressCounter>, baseStyleSheet: [BaseStyleSheet.Property] = [], progressStyleSheet: [ProgressStyleSheet.Property] = [], layout: [Layout.Property] = []) { self.progress = progress self.baseStyleSheet = baseStyleSheet self.progressStyleSheet = progressStyleSheet self.layout = layout } }
mit
94cdfca382301fe54bd65551b7329715
27.185484
108
0.656938
4.827348
false
false
false
false
nheagy/WordPress-iOS
WordPress/Classes/ViewRelated/Views/AlertView/AlertInternalView.swift
1
1614
import Foundation import WordPressShared /** * @class AlertInternalView * @brief Helper class, used internally by AlertView. Not designed for general usage. */ public class AlertInternalView : UIView { // MARK: - Public Properties public var onClick : (() -> ())? // MARK: - View Methods public override func awakeFromNib() { super.awakeFromNib() assert(backgroundView != nil) assert(alertView != nil) assert(titleLabel != nil) assert(descriptionLabel != nil) alertView.layer.cornerRadius = cornerRadius titleLabel.font = Styles.titleRegularFont descriptionLabel.font = Styles.detailsRegularFont titleLabel.textColor = Styles.titleColor descriptionLabel.textColor = Styles.detailsColor dismissButton.titleLabel?.font = Styles.buttonFont } /** * @details Handles the Dismiss Button Tap. * @param sender The button that was pressed. */ @IBAction private func buttonWasPressed(sender: AnyObject!) { onClick?() onClick = nil } // MARK: - Private Aliases private typealias Styles = WPStyleGuide.AlertView // MARK: - Private Constants private let cornerRadius = CGFloat(7) // MARK: - Outlets @IBOutlet var backgroundView : UIView! @IBOutlet var alertView : UIView! @IBOutlet var titleLabel : UILabel! @IBOutlet var descriptionLabel : UILabel! @IBOutlet var dismissButton : UIButton! }
gpl-2.0
78824e8316d4dcd3ee3359c581c77dab
25.9
95
0.612763
5.257329
false
false
false
false
imxieyi/iosu
iosu/ViewControllers/SelectionView.swift
1
3342
// // SelectionView.swift // iosu // // Created by xieyi on 2017/4/3. // Copyright © 2017年 xieyi. All rights reserved. // import Foundation import UIKit class SelectionViewController:UIViewController,UIPickerViewDelegate,UIPickerViewDataSource { @IBOutlet var picker: UIPickerView! @IBOutlet var gameSwitch: UISwitch! @IBOutlet var videoSwitch: UISwitch! @IBOutlet var sbSwitch: UISwitch! @IBOutlet var dimSlider: UISlider! @IBOutlet var dimLabel: UILabel! @IBOutlet var musicSlider: UISlider! @IBOutlet var musicLabel: UILabel! @IBOutlet var effectSlider: UISlider! @IBOutlet var effectLabel: UILabel! @IBOutlet var skinSwitch: UISwitch! let bs=BeatmapScanner() override func viewDidLoad() { picker.dataSource=self picker.delegate=self UIApplication.shared.isIdleTimerDisabled=true } func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return bs.beatmaps.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return bs.beatmaps[row] } @IBAction func playPressed(_ sender: Any) { SkinBuffer.bmPath = bs.beatmapdirs[picker.selectedRow(inComponent: 0)] SkinBuffer.useSkin = skinSwitch.isOn GamePlayScene.testBMIndex = picker.selectedRow(inComponent: 0) StoryBoardScene.testBMIndex = picker.selectedRow(inComponent: 0) GamePlayScene.bgdim = Double(dimSlider.value)/100 GameViewController.showgame = gameSwitch.isOn GameViewController.showvideo = videoSwitch.isOn GameViewController.showsb = sbSwitch.isOn BGMusicPlayer.instance.bgmvolume = musicSlider.value/100 GamePlayScene.effvolume = effectSlider.value/100 self.performSegue(withIdentifier: "play", sender: self.view) } @IBAction func dimChanged(_ sender: UISlider) { dimLabel.text = "\(Int(sender.value))%" } @IBAction func musicChanged(_ sender: UISlider) { musicLabel.text = "\(Int(sender.value))%" } @IBAction func effectChanged(_ sender: UISlider) { effectLabel.text = "\(Int(sender.value))%" } @IBAction func gameSwitched(_ sender: Any) { if !sbSwitch.isOn && !gameSwitch.isOn { Alerts.show(self, title: "Warning", message: "You should turn on either game or storyboard!", style: .alert, actiontitle: "OK", actionstyle: .default, handler: {(act:UIAlertAction) -> Void in self.gameSwitch.setOn(true, animated: true) self.skinSwitch.isEnabled = true }) } if gameSwitch.isOn { skinSwitch.isEnabled = true } else { skinSwitch.isEnabled = false } } @IBAction func sbSwitched(_ sender: Any) { if !sbSwitch.isOn && !gameSwitch.isOn { Alerts.show(self, title: "Warning", message: "You should turn on either game or storyboard!", style: .alert, actiontitle: "OK", actionstyle: .default, handler: {(act:UIAlertAction) -> Void in self.sbSwitch.setOn(true, animated: true) }) } } }
mit
ca8d37dc4e0d50e68b02e0449c81a41b
34.147368
203
0.649596
4.428382
false
false
false
false
marklin2012/iOS_Animation
Section1/Chapter5/O2Flight_completed/O2Flight/ViewController.swift
1
7924
// // ViewController.swift // O2Flight // // Created by O2.LinYi on 16/3/11. // Copyright © 2016年 jd.com. All rights reserved. // import UIKit enum AnimationDirection: Int { case Positive = 1 case Negative = -1 } func delay(seconds seconds: Double, completion:()->()) { let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64( Double(NSEC_PER_SEC) * seconds )) dispatch_after(popTime, dispatch_get_main_queue()) { completion() } } class ViewController: UIViewController { @IBOutlet weak var bgImageView: UIImageView! @IBOutlet weak var summaryIcon: UIImageView! @IBOutlet weak var summaryLabel: UILabel! @IBOutlet weak var flightNrLabel: UILabel! @IBOutlet weak var gateNrLabel: UILabel! @IBOutlet weak var departingForm: UILabel! @IBOutlet weak var arrivingTo: UILabel! @IBOutlet weak var planeImageView: UIImageView! @IBOutlet weak var flightStatusLabel: UILabel! @IBOutlet weak var statusBanner: UIImageView! var snowView: SnowView! // MARK: - Life Cycle override func viewDidLoad() { super.viewDidLoad() // adjust ui summaryLabel.addSubview(summaryIcon) summaryIcon.center.y = summaryLabel.frame.size.height/2 // add the snow effect layer snowView = SnowView(frame: CGRect(x: -150, y: -100, width: 300, height: 50)) let snowClipView = UIView(frame: CGRectOffset(view.frame, 0, 50)) snowClipView.clipsToBounds = true snowClipView.addSubview(snowView) view.addSubview(snowClipView) // start rotating the flights changeFlightDataTo(londonToParis) } func changeFlightDataTo(data: FlightData, animated: Bool = false) { // populate the UI with the next flight's data summaryLabel.text = data.summary departingForm.text = data.departingFrom arrivingTo.text = data.arrivingTo if animated { fadeImageView(bgImageView, toImage: UIImage(named: data.weatherImageName)!, showEffects: data.showWeatherEffects) let direction : AnimationDirection = data.isTakingOff ? .Positive : .Negative cubeTransition(label: flightNrLabel, text: data.flightNr, direction: direction) cubeTransition(label: gateNrLabel, text: data.gateNr, direction: direction) let offsetDeparting = CGPoint(x: CGFloat(direction.rawValue * 80), y: 0) moveLabel(departingForm, text: data.departingFrom, offset: offsetDeparting) let offsetArriving = CGPoint(x: 0, y: CGFloat(direction.rawValue * 50)) moveLabel(arrivingTo, text: data.arrivingTo, offset: offsetArriving) cubeTransition(label: flightStatusLabel, text: data.flightStatus, direction: direction) planeDepart() } else { bgImageView.image = UIImage(named: data.weatherImageName) snowView.hidden = !data.showWeatherEffects flightNrLabel.text = data.flightNr gateNrLabel.text = data.gateNr flightStatusLabel.text = data.flightStatus } delay(seconds: 3) { () -> () in self.changeFlightDataTo(data.isTakingOff ? parisToRome : londonToParis, animated: true) } } // MARK: - further method func fadeImageView(imageView: UIImageView, toImage: UIImage, showEffects: Bool) { UIView.transitionWithView(imageView, duration: 1, options: .TransitionCrossDissolve, animations: { () -> Void in imageView.image = toImage }, completion: nil) UIView.animateWithDuration(1, delay: 0, options: [.CurveEaseOut], animations: { () -> Void in self.snowView.alpha = showEffects ? 1 : 0 }, completion: nil) } func cubeTransition(label label: UILabel, text: String, direction: AnimationDirection) { let auxLabel = UILabel(frame: label.frame) auxLabel.text = text auxLabel.font = label.font auxLabel.textAlignment = label.textAlignment auxLabel.textColor = label.textColor auxLabel.backgroundColor = label.backgroundColor let auxLabelOffset = CGFloat(direction.rawValue) * label.frame.size.height/2.0 auxLabel.transform = CGAffineTransformConcat(CGAffineTransformMakeScale(1, 0.1), CGAffineTransformMakeTranslation(0, auxLabelOffset)) label.superview?.addSubview(auxLabel) UIView.animateWithDuration(0.5, delay: 0, options: [.CurveEaseOut], animations: { () -> Void in auxLabel.transform = CGAffineTransformIdentity label.transform = CGAffineTransformConcat(CGAffineTransformMakeScale(1, 0.1), CGAffineTransformMakeTranslation(0, -auxLabelOffset)) }, completion: { _ in label.text = auxLabel.text label.transform = CGAffineTransformIdentity auxLabel.removeFromSuperview() }) } func moveLabel(label: UILabel, text: String, offset: CGPoint) { let auxLabel = UILabel(frame: label.frame) auxLabel.text = text auxLabel.font = label.font auxLabel.textAlignment = label.textAlignment auxLabel.textColor = label.textColor auxLabel.backgroundColor = UIColor.clearColor() auxLabel.transform = CGAffineTransformMakeTranslation(offset.x, offset.y) auxLabel.alpha = 0 view.addSubview(auxLabel) UIView.animateWithDuration(0.5, delay: 0, options: [.CurveEaseIn], animations: { () -> Void in label.transform = CGAffineTransformMakeTranslation(offset.x, offset.y) label.alpha = 0 }, completion: nil) UIView.animateWithDuration(0.25, delay: 0.1, options: [.CurveEaseIn], animations: { () -> Void in auxLabel.transform = CGAffineTransformIdentity auxLabel.alpha = 1 }, completion: { _ in // clean up auxLabel.removeFromSuperview() label.text = text label.alpha = 1 label.transform = CGAffineTransformIdentity }) } func planeDepart() { let originalCenter = planeImageView.center UIView.animateKeyframesWithDuration(1.5, delay: 0, options: [], animations: { () -> Void in // add keyframe UIView.addKeyframeWithRelativeStartTime(0, relativeDuration: 0.25, animations: { () -> Void in self.planeImageView.center.x += 80 self.planeImageView.center.y -= 10 }) UIView.addKeyframeWithRelativeStartTime(0.1, relativeDuration: 0.4, animations: { () -> Void in self.planeImageView.transform = CGAffineTransformMakeRotation(CGFloat(-M_PI_4/2)) }) UIView.addKeyframeWithRelativeStartTime(0.25, relativeDuration: 0.25, animations: { () -> Void in self.planeImageView.center.x += 100 self.planeImageView.center.y -= 50 self.planeImageView.alpha = 0 }) UIView.addKeyframeWithRelativeStartTime(0.51, relativeDuration: 0.01, animations: { () -> Void in self.planeImageView.transform = CGAffineTransformIdentity self.planeImageView.center = CGPoint(x: 0, y: originalCenter.y) }) UIView.addKeyframeWithRelativeStartTime(0.55, relativeDuration: 0.45, animations: { () -> Void in self.planeImageView.alpha = 1 self.planeImageView.center = originalCenter }) }, completion: nil) } }
mit
1701efa6282bd6e6e30841ae55d2f9d1
38.019704
143
0.614064
4.874462
false
false
false
false
stephentyrone/swift
test/IRGen/prespecialized-metadata/enum-inmodule-1argument-1distinct_generic_use.swift
3
3542
// 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: @"$s4main5OuterOyAA5InnerVySiGGWV" = linkonce_odr hidden constant %swift.enum_vwtable // CHECK: @"$s4main5OuterOyAA5InnerVySiGGMf" = linkonce_odr hidden constant <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: i64 // CHECK-SAME: }> <{ // CHECK-SAME: i8** getelementptr inbounds ( // CHECK-SAME: %swift.enum_vwtable, // CHECK-SAME: %swift.enum_vwtable* @"$s4main5OuterOyAA5InnerVySiGGWV", // CHECK-SAME: i32 0, // CHECK-SAME: i32 0 // CHECK-SAME: ), // CHECK-SAME: [[INT]] 513, // CHECK-SAME: %swift.type_descriptor* bitcast ( // CHECK-SAME: {{.*}}$s4main5OuterOMn{{.*}} to %swift.type_descriptor* // CHECK-SAME: ), // CHECK-SAME: %swift.type* getelementptr inbounds ( // CHECK-SAME: %swift.full_type, // CHECK-SAME: %swift.full_type* bitcast ( // CHECK-SAME: <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: i32, // CHECK-SAME: {{(\[4 x i8\],)?}} // CHECK-SAME: i64 // CHECK-SAME: }>* @"$s4main5InnerVySiGMf" // CHECK-SAME: to %swift.full_type* // CHECK-SAME: ), // CHECK-SAME: i32 0, // CHECK-SAME: i32 1 // CHECK-SAME: ), // CHECK-SAME: i64 3 // CHECK-SAME: }>, align [[ALIGNMENT]] enum Outer<First> { case first(First) } struct Inner<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"( // CHECK-SAME: %swift.opaque* noalias nocapture %{{[0-9]+}}, // CHECK-SAME: %swift.type* getelementptr inbounds ( // CHECK-SAME: %swift.full_type, // CHECK-SAME: %swift.full_type* bitcast ( // CHECK-SAME: <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: i64 // CHECK-SAME: }>* @"$s4main5OuterOyAA5InnerVySiGGMf" // CHECK-SAME: to %swift.full_type* // CHECK-SAME: ), // CHECK-SAME: i32 0, // CHECK-SAME: i32 1 // CHECK-SAME: ) // CHECK-SAME: ) // CHECK: } func doit() { consume( Outer.first(Inner(first: 13)) ) } doit() // CHECK: ; Function Attrs: noinline nounwind readnone // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5OuterOMa"([[INT]] %0, %swift.type* %1) #{{[0-9]+}} { // CHECK: entry: // CHECK: [[ERASED_TYPE:%[0-9]+]] = bitcast %swift.type* %1 to i8* // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateGenericMetadata( // CHECK-SAME: [[INT]] %0, // CHECK-SAME: i8* [[ERASED_TYPE]], // CHECK-SAME: i8* undef, // CHECK-SAME: i8* undef, // CHECK-SAME: %swift.type_descriptor* bitcast ( // CHECK-SAME: {{.*}}$s4main5OuterOMn{{.*}} to %swift.type_descriptor* // CHECK-SAME: ) // CHECK-SAME: ) #{{[0-9]+}} // CHECK: ret %swift.metadata_response {{%[0-9]+}} // CHECK: }
apache-2.0
ed1667b7d9ca2d81b8da79ede49a0ad7
35.142857
157
0.58131
2.929694
false
false
false
false
Stitch7/Instapod
Instapod/Podcast/CollectionView/PodcastsCollectionViewController.swift
1
4956
// // PodcastsCollectionViewController.swift // Instapod // // Created by Christopher Reitz on 03.09.16. // Copyright © 2016 Christopher Reitz. All rights reserved. // import UIKit class PodcastsCollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout, FeedUpdaterDelegate { // MARK: - Properties var delegate: PodcastListDelegate? var podcasts = [Podcast]() var thumbnails = [String: UIImage]() var refreshControl: UIRefreshControl? let refreshControlTitle = "Pull to refresh …" // TODO: i18n let reuseIdentifier = "PodcastCell" // MARK: - UIViewController override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = ColorPalette.Background configureCollectionView() configureRefreshControl() } func configureCollectionView() { collectionView?.backgroundColor = ColorPalette.Background collectionView?.contentInset = UIEdgeInsetsMake(20, 0, 0, 0) let nib = UINib(nibName: "PodcastCollectionViewCell", bundle: nil) collectionView?.register(nib, forCellWithReuseIdentifier: reuseIdentifier) } func configureRefreshControl() { let refreshControl = UIRefreshControl() refreshControl.attributedTitle = NSAttributedString(string: refreshControlTitle) refreshControl.addTarget(self, action: #selector(handleRefresh), for: .valueChanged) self.refreshControl = refreshControl collectionView?.addSubview(refreshControl) collectionView?.sendSubview(toBack: refreshControl) } // MARK: - Actions func handleRefresh(_ refreshControl: UIRefreshControl) { refreshControl.attributedTitle = NSAttributedString(string: "Searching for new episodes …") // TODO: i18n delegate?.updateFeeds() } // MARK: - UICollectionViewDelegate override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { performSegue(withIdentifier: "ShowFeed", sender: indexPath) } // MARK: - UICollectionViewDataSource override func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return podcasts.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! PodcastCollectionViewCell let podcast = podcasts[(indexPath as NSIndexPath).row] cell.layer.shouldRasterize = true cell.layer.rasterizationScale = UIScreen.main.scale cell.imageData = podcast.image?.thumbnail return cell } // MARK: - UICollectionViewDelegateFlowLayout func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: 100, height: 100) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsets(top: 50.0, left: 20.0, bottom: 50.0, right: 20.0) } // MARK: - FeedUpdaterDelegate func feedUpdater(_ feedupdater: FeedUpdater, didFinishWithEpisode foundEpisode: Episode, ofPodcast podcast: Podcast) { if let refreshControl = refreshControl, let feedTitle = podcast.title, let episodeTitle = foundEpisode.title { refreshControl.attributedTitle = NSAttributedString(string: "Found \(feedTitle) - \(episodeTitle)") // TODO: i18n } } func feedUpdater(_ feedupdater: FeedUpdater, didFinishWithNumberOfEpisodes numberOfEpisodes: Int) { collectionView?.reloadData() collectionView?.layoutIfNeeded() if let refreshControl = refreshControl { refreshControl.endRefreshing() refreshControl.attributedTitle = NSAttributedString(string: refreshControlTitle) } } // MARK: - Segues override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let segueIdentifier = segue.identifier , segueIdentifier == "ShowFeed", let indexPath = sender as? IndexPath else { return } let podcast = podcasts[(indexPath as NSIndexPath).row] let navigationController = segue.destination as! UINavigationController let episodesTVC = navigationController.topViewController as! EpisodesViewController episodesTVC.podcast = podcast episodesTVC.navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem episodesTVC.navigationItem.leftItemsSupplementBackButton = true } }
mit
d6c868b45c0231661a8012ab891e724f
37.084615
162
0.711775
5.845336
false
false
false
false
bigxodus/candlelight
candlelight/screen/main/controller/crawler/TodayHumorBoardCrawler.swift
1
1692
import Foundation import BrightFutures import enum Result.Result import enum Result.NoError import Alamofire import Kanna class TodayHumorBoardCrawler: BoardCrawler { let siteUrl = "http://www.todayhumor.co.kr/board/list.php?table=bestofbest&page=" let contentsBaseUrl = "http://www.todayhumor.co.kr" func getList(page: Int) -> Future<[BoardItem]?, NoError> { let url = self.siteUrl + String(page + 1) return AlamofireRequest(url).map(parseHTML) } func parseHTML(html: String) -> [BoardItem]? { guard let doc = HTML(html: html, encoding: .utf8) else { return nil } var result = [BoardItem]() for content in doc.xpath("//table[contains(@class, 'table_list')]//tr[contains(@class, 'view')]") { let title = content.xpath("td[3]").map({ (XMLElement) -> String in XMLElement.text! }).joined(separator: " ") let pageIdOption = content.xpath("td[1]").first?.text.flatMap{v in Int(v)} let urlOption = content.xpath("td[3]//a").first?["href"] let authorOption = content.xpath("td[4]//a").first?.text let readCountOption = content.xpath("td[6]").first?.text.flatMap{v in Int(v)} guard let pageId = pageIdOption, let url = urlOption, let author = authorOption, let readCount = readCountOption else { continue } let contentsUrl = contentsBaseUrl + url result.append(BoardItem(id: pageId, title: title, url: contentsUrl, author: author, date: "", readCount: readCount)) } return result } }
apache-2.0
42e80ffe78a51b73f03704b7735bcf6b
38.348837
128
0.594563
4.086957
false
false
false
false
BrianCorbin/SwiftRangeSlider
Examples/SwiftRangeSliderExample/Pods/RappleColorPicker/Pod/Classes/RappleColorPickerViewController.swift
1
13288
/* ** RappleColorPicker.swift Custom Activity Indicator with swift 2.0 Created by Rajeev Prasad on 28/11/15. The MIT License (MIT) Copyright (c) 2015 Rajeev Prasad <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ** */ import UIKit class RappleColorPickerViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate { fileprivate var collectionView : UICollectionView! fileprivate var titleLabel : UILabel! var delegate: RappleColorPickerDelegate? var tag: Int = 1 var attributes : [RappleCPAttributeKey : AnyObject] = [ .Title : "Color Picker" as AnyObject, .BGColor : UIColor.black, .TintColor : UIColor.white, .Style : RappleCPStyleCircle as AnyObject ] fileprivate var colorDic = [Int: [UIColor]]() override func viewDidLoad() { super.viewDidLoad() setAllColor() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.view.backgroundColor = attributes[RappleCPAttributeKey.BGColor] as? UIColor self.view.layer.cornerRadius = 4.0 self.view.layer.borderWidth = 2.0 self.view.layer.borderColor = UIColor.darkGray.cgColor self.view.layer.masksToBounds = true let layout = RappleColorPickerFlowLayout() layout.sectionInset = UIEdgeInsets(top: 2, left: 0, bottom: 0, right: 0) layout.minimumInteritemSpacing = 0 layout.minimumLineSpacing = 0 layout.itemSize = CGSize(width: 30, height: 30) let colRect = CGRect(x: 2, y: 30, width: view.frame.width, height: view.frame.height - 30) collectionView = UICollectionView(frame: colRect, collectionViewLayout: layout) collectionView.dataSource = self collectionView.delegate = self collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell") collectionView.backgroundColor = UIColor.clear self.view.addSubview(collectionView) collectionView.reloadData() titleLabel = UILabel(frame: CGRect(x: 2,y: 2,width: view.frame.width-4,height: 28)) titleLabel.font = UIFont.boldSystemFont(ofSize: 16) titleLabel.textAlignment = .center titleLabel.textColor = attributes[RappleCPAttributeKey.TintColor] as? UIColor titleLabel.text = attributes[RappleCPAttributeKey.Title] as? String self.view.addSubview(titleLabel) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func numberOfSections(in collectionView: UICollectionView) -> Int { return colorDic.count } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return (colorDic[section]?.count)! } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) cell.backgroundColor = getColor(indexPath.section, row: indexPath.row) if attributes[RappleCPAttributeKey.Style] as? String == RappleCPStyleCircle { cell.layer.cornerRadius = 15.0 } else { cell.layer.cornerRadius = 1.0 } cell.layer.borderColor = (attributes[RappleCPAttributeKey.TintColor] as? UIColor)?.cgColor cell.layer.borderWidth = 1.0 return cell } func getColor(_ section:Int, row:Int) -> UIColor { return colorDic[section]![row] } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if delegate?.responds(to: "colorSelected:") == true { delegate?.colorSelected?(getColor(indexPath.section, row: indexPath.row)) } if delegate?.responds(to: "colorSelected:tag:") == true { delegate?.colorSelected?(getColor(indexPath.section, row: indexPath.row), tag: tag) } } } class RappleColorPickerFlowLayout : UICollectionViewFlowLayout { let cellSpacing:CGFloat = 1 override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { if let attributes = super.layoutAttributesForElements(in: rect) { for (index, attribute) in attributes.enumerated() { if index == 0 { continue } let prevLayoutAttributes = attributes[index - 1] let origin = prevLayoutAttributes.frame.maxX if(origin + cellSpacing + attribute.frame.size.width < self.collectionViewContentSize.width) { attribute.frame.origin.x = origin + cellSpacing } } return attributes } return nil } } extension RappleColorPickerViewController { fileprivate func setAllColor(){ colorDic[0] = [ UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), UIColor(red: 0.886274509803922, green: 0.886274509803922, blue: 0.886274509803922, alpha: 1.0), UIColor(red: 0.666666666666667, green: 0.666666666666667, blue: 0.666666666666667, alpha: 1.0), UIColor(red: 0.43921568627451, green: 0.43921568627451, blue: 0.43921568627451, alpha: 1.0), UIColor(red: 0.219607843137255, green: 0.219607843137255, blue: 0.219607843137255, alpha: 1.0), UIColor(red: 0.109803921568627, green: 0.109803921568627, blue: 0.109803921568627, alpha: 1.0), UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0) ] colorDic[1] = [ UIColor(red: 0.847058823529412, green: 1.0, blue: 0.972549019607843, alpha: 1.0), UIColor(red: 0.568627450980392, green: 1.0, blue: 0.925490196078431, alpha: 1.0), UIColor(red: 0.0, green: 1.0, blue: 0.831372549019608, alpha: 1.0), UIColor(red: 0.0, green: 0.717647058823529, blue: 0.6, alpha: 1.0), UIColor(red: 0.0, green: 0.458823529411765, blue: 0.380392156862745, alpha: 1.0), UIColor(red: 0.0, green: 0.329411764705882, blue: 0.274509803921569, alpha: 1.0), UIColor(red: 0.0, green: 0.2, blue: 0.164705882352941, alpha: 1.0) ] colorDic[2] = [ UIColor(red: 0.847058823529412, green: 1.0, blue: 0.847058823529412, alpha: 1.0), UIColor(red: 0.63921568627451, green: 1.0, blue: 0.63921568627451, alpha: 1.0), UIColor(red: 0.219607843137255, green: 1.0, blue: 0.219607843137255, alpha: 1.0), UIColor(red: 0.0, green: 0.83921568627451, blue: 0.0, alpha: 1.0), UIColor(red: 0.0, green: 0.517647058823529, blue: 0.0, alpha: 1.0), UIColor(red: 0.0, green: 0.356862745098039, blue: 0.0, alpha: 1.0), UIColor(red: 0.0, green: 0.2, blue: 0.0, alpha: 1.0) ] colorDic[3] = [ UIColor(red: 1.0, green: 1.0, blue: 0.847058823529412, alpha: 1.0), UIColor(red: 1.0, green: 1.0, blue: 0.568627450980392, alpha: 1.0), UIColor(red: 1.0, green: 1.0, blue: 0.0, alpha: 1.0), UIColor(red: 0.717647058823529, green: 0.717647058823529, blue: 0.0, alpha: 1.0), UIColor(red: 0.458823529411765, green: 0.458823529411765, blue: 0.0, alpha: 1.0), UIColor(red: 0.329411764705882, green: 0.329411764705882, blue: 0.0, alpha: 1.0), UIColor(red: 0.2, green: 0.2, blue: 0.0, alpha: 1.0) ] colorDic[4] = [ UIColor(red: 1.0, green: 0.92156862745098, blue: 0.847058823529412, alpha: 1.0), UIColor(red: 1.0, green: 0.83921568627451, blue: 0.67843137254902, alpha: 1.0), UIColor(red: 1.0, green: 0.666666666666667, blue: 0.337254901960784, alpha: 1.0), UIColor(red: 1.0, green: 0.498039215686275, blue: 0.0, alpha: 1.0), UIColor(red: 0.627450980392157, green: 0.313725490196078, blue: 0.0, alpha: 1.0), UIColor(red: 0.43921568627451, green: 0.219607843137255, blue: 0.0, alpha: 1.0), UIColor(red: 0.247058823529412, green: 0.12156862745098, blue: 0.0, alpha: 1.0) ] colorDic[5] = [ UIColor(red: 1.0, green: 0.886274509803922, blue: 0.847058823529412, alpha: 1.0), UIColor(red: 1.0, green: 0.756862745098039, blue: 0.67843137254902, alpha: 1.0), UIColor(red: 1.0, green: 0.501960784313725, blue: 0.337254901960784, alpha: 1.0), UIColor(red: 1.0, green: 0.247058823529412, blue: 0.0, alpha: 1.0), UIColor(red: 0.658823529411765, green: 0.164705882352941, blue: 0.0, alpha: 1.0), UIColor(red: 0.47843137254902, green: 0.117647058823529, blue: 0.0, alpha: 1.0), UIColor(red: 0.298039215686275, green: 0.0745098039215686, blue: 0.0, alpha: 1.0) ] colorDic[6] = [ UIColor(red: 1.0, green: 0.847058823529412, blue: 0.847058823529412, alpha: 1.0), UIColor(red: 1.0, green: 0.67843137254902, blue: 0.67843137254902, alpha: 1.0), UIColor(red: 1.0, green: 0.337254901960784, blue: 0.337254901960784, alpha: 1.0), UIColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0), UIColor(red: 0.627450980392157, green: 0.0, blue: 0.0, alpha: 1.0), UIColor(red: 0.43921568627451, green: 0.0, blue: 0.0, alpha: 1.0), UIColor(red: 0.247058823529412, green: 0.0, blue: 0.0, alpha: 1.0) ] colorDic[7] = [ UIColor(red: 1.0, green: 0.847058823529412, blue: 1.0, alpha: 1.0), UIColor(red: 1.0, green: 0.63921568627451, blue: 1.0, alpha: 1.0), UIColor(red: 1.0, green: 0.219607843137255, blue: 1.0, alpha: 1.0), UIColor(red: 0.83921568627451, green: 0.0, blue: 0.83921568627451, alpha: 1.0), UIColor(red: 0.517647058823529, green: 0.0, blue: 0.517647058823529, alpha: 1.0), UIColor(red: 0.356862745098039, green: 0.0, blue: 0.356862745098039, alpha: 1.0), UIColor(red: 0.2, green: 0.0, blue: 0.2, alpha: 1.0) ] colorDic[8] = [ UIColor(red: 0.92156862745098, green: 0.847058823529412, blue: 1.0, alpha: 1.0), UIColor(red: 0.83921568627451, green: 0.67843137254902, blue: 1.0, alpha: 1.0), UIColor(red: 0.666666666666667, green: 0.337254901960784, blue: 1.0, alpha: 1.0), UIColor(red: 0.498039215686275, green: 0.0, blue: 1.0, alpha: 1.0), UIColor(red: 0.298039215686275, green: 0.0, blue: 0.6, alpha: 1.0), UIColor(red: 0.2, green: 0.0, blue: 0.4, alpha: 1.0), UIColor(red: 0.0980392156862745, green: 0.0, blue: 0.2, alpha: 1.0) ] colorDic[9] = [ UIColor(red: 0.847058823529412, green: 0.847058823529412, blue: 1.0, alpha: 1.0), UIColor(red: 0.67843137254902, green: 0.67843137254902, blue: 1.0, alpha: 1.0), UIColor(red: 0.337254901960784, green: 0.337254901960784, blue: 1.0, alpha: 1.0), UIColor(red: 0.0, green: 0.0, blue: 1.0, alpha: 1.0), UIColor(red: 0.0, green: 0.0, blue: 0.627450980392157, alpha: 1.0), UIColor(red: 0.0, green: 0.0, blue: 0.43921568627451, alpha: 1.0), UIColor(red: 0.0, green: 0.0, blue: 0.247058823529412, alpha: 1.0) ] colorDic[10] = [ UIColor(red: 0.847058823529412, green: 0.898039215686275, blue: 1.0, alpha: 1.0), UIColor(red: 0.67843137254902, green: 0.784313725490196, blue: 1.0, alpha: 1.0), UIColor(red: 0.337254901960784, green: 0.556862745098039, blue: 1.0, alpha: 1.0), UIColor(red: 0.0, green: 0.333333333333333, blue: 1.0, alpha: 1.0), UIColor(red: 0.0, green: 0.2, blue: 0.6, alpha: 1.0), UIColor(red: 0.0, green: 0.133333333333333, blue: 0.4, alpha: 1.0), UIColor(red: 0.0, green: 0.0666666666666667, blue: 0.2, alpha: 1.0) ] } }
mit
caf0835ebfdd62211189bc3670a5d025
45.954064
121
0.620334
3.573964
false
false
false
false
lkzhao/Hero
Sources/Transition/HeroTransition.swift
1
7706
// The MIT License (MIT) // // Copyright (c) 2016 Luke Zhao <[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 canImport(UIKit) import UIKit /** ### The singleton class/object for controlling interactive transitions. ```swift Hero.shared ``` #### Use the following methods for controlling the interactive transition: ```swift func update(progress:Double) func end() func cancel() func apply(modifiers:[HeroModifier], to view:UIView) ``` */ public class Hero: NSObject { /// Shared singleton object for controlling the transition public static var shared = HeroTransition() } public protocol HeroTransitionDelegate: class { func heroTransition(_ hero: HeroTransition, didUpdate state: HeroTransitionState) func heroTransition(_ hero: HeroTransition, didUpdate progress: Double) } open class HeroTransition: NSObject { public weak var delegate: HeroTransitionDelegate? public var defaultAnimation: HeroDefaultAnimationType = .auto public var containerColor: UIColor = .black public var isUserInteractionEnabled = false public var viewOrderingStrategy: HeroViewOrderingStrategy = .auto public var defaultAnimationDirectionStrategy: HeroDefaultAnimationType.Strategy = .forceLeftToRight public internal(set) var state: HeroTransitionState = .possible { didSet { if state != .notified, state != .starting { beginCallback?(state == .animating) beginCallback = nil } delegate?.heroTransition(self, didUpdate: state) } } public var isTransitioning: Bool { return state != .possible } public internal(set) var isPresenting: Bool = true @available(*, renamed: "isTransitioning") public var transitioning: Bool { return isTransitioning } @available(*, renamed: "isPresenting") public var presenting: Bool { return isPresenting } /// container we created to hold all animating views, will be a subview of the /// transitionContainer when transitioning public internal(set) var container: UIView! /// this is the container supplied by UIKit internal var transitionContainer: UIView? internal var completionCallback: ((Bool) -> Void)? internal var beginCallback: ((Bool) -> Void)? internal var processors: [HeroPreprocessor] = [] internal var animators: [HeroAnimator] = [] internal var plugins: [HeroPlugin] = [] internal var animatingFromViews: [UIView] = [] internal var animatingToViews: [UIView] = [] internal static var enabledPlugins: [HeroPlugin.Type] = [] /// destination view controller public internal(set) var toViewController: UIViewController? /// source view controller public internal(set) var fromViewController: UIViewController? /// context object holding transition informations public internal(set) var context: HeroContext! /// whether or not we are handling transition interactively public var interactive: Bool { return !progressRunner.isRunning } internal var progressUpdateObservers: [HeroProgressUpdateObserver]? /// max duration needed by the animators public internal(set) var totalDuration: TimeInterval = 0.0 /// progress of the current transition. 0 if no transition is happening public internal(set) var progress: Double = 0 { didSet { if state == .animating { if let progressUpdateObservers = progressUpdateObservers { for observer in progressUpdateObservers { observer.heroDidUpdateProgress(progress: progress) } } let timePassed = progress * totalDuration if interactive { for animator in animators { animator.seekTo(timePassed: timePassed) } } else { for plugin in plugins where plugin.requirePerFrameCallback { plugin.seekTo(timePassed: timePassed) } } transitionContext?.updateInteractiveTransition(CGFloat(progress)) } delegate?.heroTransition(self, didUpdate: progress) } } lazy var progressRunner: HeroProgressRunner = { let runner = HeroProgressRunner() runner.delegate = self return runner }() /// a UIViewControllerContextTransitioning object provided by UIKit, /// might be nil when transitioning. This happens when calling heroReplaceViewController internal weak var transitionContext: UIViewControllerContextTransitioning? internal var fullScreenSnapshot: UIView? // By default, Hero will always appear to be interactive to UIKit. This forces it to appear non-interactive. // Used when doing a hero_replaceViewController within a UINavigationController, to fix a bug with // UINavigationController.setViewControllers not able to handle interactive transition internal var forceNotInteractive = false internal var forceFinishing: Bool? internal var startingProgress: CGFloat? internal var inNavigationController = false internal var inTabBarController = false internal var inContainerController: Bool { return inNavigationController || inTabBarController } internal var toOverFullScreen: Bool { return !inContainerController && (toViewController?.modalPresentationStyle == .overFullScreen || toViewController?.modalPresentationStyle == .overCurrentContext) } internal var fromOverFullScreen: Bool { return !inContainerController && (fromViewController?.modalPresentationStyle == .overFullScreen || fromViewController?.modalPresentationStyle == .overCurrentContext) } internal var toView: UIView? { return toViewController?.view } internal var fromView: UIView? { return fromViewController?.view } public override init() { super.init() } func complete(after: TimeInterval, finishing: Bool) { guard [HeroTransitionState.animating, .starting, .notified].contains(state) else { return } if after <= 1.0 / 120 { complete(finished: finishing) return } let totalTime: TimeInterval if finishing { totalTime = after / max((1 - progress), 0.01) } else { totalTime = after / max(progress, 0.01) } progressRunner.start(timePassed: progress * totalTime, totalTime: totalTime, reverse: !finishing) } // MARK: Observe Progress /** Receive callbacks on each animation frame. Observers will be cleaned when transition completes - Parameters: - observer: the observer */ public func observeForProgressUpdate(observer: HeroProgressUpdateObserver) { if progressUpdateObservers == nil { progressUpdateObservers = [] } progressUpdateObservers!.append(observer) } } extension HeroTransition: HeroProgressRunnerDelegate { func updateProgress(progress: Double) { self.progress = progress } } #endif
mit
3248bc7e53cd1060a5803e787b01da60
34.187215
169
0.733454
5.033312
false
false
false
false
poetmountain/MotionMachine
Examples/MotionExamples/Classes/SequenceViewController.swift
1
5170
// // SequenceNoncontiguousViewController.swift // MotionExamples // // Created by Brett Walker on 6/2/16. // Copyright © 2016 Poet & Mountain, LLC. All rights reserved. // import UIKit public class SequenceViewController: UIViewController, ButtonsViewDelegate { var createdUI: Bool = false var buttonsView: ButtonsView! var squares: [UIView] = [] var sequence: MotionSequence! var constraints: [NSLayoutConstraint] = [] convenience init() { self.init(nibName: nil, bundle: nil) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } public override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() if (!createdUI) { setupUI() // setup motion sequence = MotionSequence(options: [.reverses]) .stepCompleted({ (sequence) in print("step complete") }) .completed({ (sequence) in print("sequence complete") }) for x in 0..<4 { let down = Motion(target: constraints[x], properties: [PropertyData("constant", 250.0)], duration: 0.6, easing: EasingQuartic.easeInOut()) let color = Motion(target: squares[x], statesForProperties: [PropertyStates(path: "backgroundColor", end: UIColor.init(red: 91.0/255.0, green:189.0/255.0, blue:231.0/255.0, alpha:1.0))], duration: 0.7, easing: EasingQuadratic.easeInOut()) let group = MotionGroup(motions: [down, color], options: [.reverses]) sequence.add(group) } createdUI = true } } public override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) sequence.start() } override public func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) sequence.stop() for step in sequence.steps { sequence.remove(step) } } // MARK: - Private methods private func setupUI() { view.backgroundColor = UIColor.white var margins : UILayoutGuide let top_offset : CGFloat = 20.0 if #available(iOS 11.0, *) { margins = view.safeAreaLayoutGuide } else { margins = topLayoutGuide as! UILayoutGuide } var top_anchor: NSLayoutYAxisAnchor if #available(iOS 11.0, *) { top_anchor = margins.topAnchor } else { top_anchor = margins.bottomAnchor } buttonsView = ButtonsView.init(frame: CGRect.zero) view.addSubview(buttonsView) buttonsView.delegate = self buttonsView.translatesAutoresizingMaskIntoConstraints = false buttonsView.widthAnchor.constraint(equalTo: margins.widthAnchor, constant: 0.0).isActive = true buttonsView.heightAnchor.constraint(equalTo: margins.heightAnchor, constant: 0.0).isActive = true // set up motion views var currx: CGFloat = 48.0 let spacer: CGFloat = 20.0 for _ in 0..<4 { let w: CGFloat = 40.0 let square = UIView.init() square.backgroundColor = UIColor.init(red: 76.0/255.0, green:164.0/255.0, blue:68.0/255.0, alpha:1.0) square.layer.masksToBounds = true square.layer.cornerRadius = w * 0.5 self.view.addSubview(square) square.translatesAutoresizingMaskIntoConstraints = false squares.append(square) // set up motion constraints let square_x = square.centerXAnchor.constraint(equalTo: margins.leadingAnchor, constant: currx) square_x.isActive = true let square_y = square.topAnchor.constraint(equalTo: top_anchor, constant: top_offset) square_y.isActive = true let square_height = square.heightAnchor.constraint(equalToConstant: w) square_height.isActive = true let square_width = square.widthAnchor.constraint(equalToConstant: w) square_width.isActive = true constraints.append(square_y) currx += 40.0 + spacer } } // MARK: - ButtonsViewDelegate methods func didStart() { sequence.start() } func didStop() { sequence.stop() } func didPause() { sequence.pause() } func didResume() { sequence.resume() } }
mit
0e7d9644783d3960d8de9f6152d10798
28.537143
182
0.539563
5.11276
false
false
false
false
mutfak/MCalendarKit
MCalendarKit/Classes/MCalendarHeaderView.swift
1
2012
// // MCalendarHeaderView.swift // Pods // // Created by Ridvan Kucuk on 5/25/16. // // import UIKit class MCalendarHeaderView: UIView { lazy var monthLabel : UILabel = { let lbl = UILabel() lbl.textAlignment = NSTextAlignment.Center lbl.font = UIFont(name: "Helvetica", size: 20.0) lbl.textColor = UIColor.grayColor() self.addSubview(lbl) return lbl }() lazy var dayLabelContainerView : UIView = { let v = UIView() let formatter : NSDateFormatter = NSDateFormatter() for index in 1...7 { let day : NSString = formatter.weekdaySymbols[index % 7] as NSString let weekdayLabel = UILabel() weekdayLabel.font = UIFont(name: "Helvetica", size: 14.0) weekdayLabel.text = day.substringToIndex(2).uppercaseString weekdayLabel.textColor = UIColor.grayColor() weekdayLabel.textAlignment = NSTextAlignment.Center v.addSubview(weekdayLabel) } self.addSubview(v) return v }() override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func layoutSubviews() { super.layoutSubviews() var frm = self.bounds frm.origin.y += 5.0 frm.size.height = 40.0 self.monthLabel.frame = frm var labelFrame = CGRect(x: 0.0, y: self.bounds.size.height / 2.0, width: self.bounds.size.width / 7.0, height: self.bounds.size.height / 2.0) for lbl in self.dayLabelContainerView.subviews { lbl.frame = labelFrame labelFrame.origin.x += labelFrame.size.width } } }
mit
209011ebbf46377595d0d7434f439956
22.670588
149
0.522863
4.82494
false
false
false
false
Beninho85/BBDesignable
BBDesignable/BBDesignable/UIView/UIView.swift
1
2052
// // UIView.swift // BBDesignable // // Created by Benjamin Bourasseau on 2017-05-12. // Copyright © 2017 Benjamin. All rights reserved. // import Foundation import UIKit public extension UIView { @IBInspectable public var cornerRadius: CGFloat { get { return layer.cornerRadius } set { layer.cornerRadius = newValue } } @IBInspectable public var borderColor: UIColor? { get { guard let color = layer.borderColor else { return nil } return UIColor(cgColor: color) } set { layer.borderColor = newValue?.cgColor } } @IBInspectable public var borderWidth: CGFloat { get { return layer.borderWidth } set { layer.borderWidth = newValue } } @IBInspectable public var shadowRadius: CGFloat { get { return layer.shadowRadius } set { layer.shadowRadius = newValue } } @IBInspectable public var shadowColor: UIColor? { get { guard let color = layer.shadowColor else { return nil } return UIColor(cgColor: color) } set { layer.shadowColor = newValue?.cgColor } } @IBInspectable public var shadowOpacity: Float { get { return layer.shadowOpacity } set { layer.shadowOpacity = newValue } } @IBInspectable public var shadowOffset: CGPoint { get { return CGPoint(x: layer.shadowOffset.width, y: layer.shadowOffset.height) } set { layer.shadowOffset = CGSize(width: newValue.x, height: newValue.y) } } @IBInspectable public var masksToBounds: Bool { get { return layer.masksToBounds } set { layer.masksToBounds = newValue } } }
mit
2567d339afd26cd42dd232744402e636
21.538462
85
0.519746
5.299742
false
false
false
false
ashfurrow/RxSwift
RxCocoa/iOS/Proxies/RxCollectionViewDataSourceProxy.swift
3
3990
// // RxCollectionViewDataSourceProxy.swift // RxCocoa // // Created by Krunoslav Zaher on 6/29/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) import Foundation import UIKit #if !RX_NO_MODULE import RxSwift #endif let collectionViewDataSourceNotSet = CollectionViewDataSourceNotSet() class CollectionViewDataSourceNotSet : NSObject , UICollectionViewDataSource { func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return rxAbstractMethodWithMessage(dataSourceNotSet) } // The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath: func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { return rxAbstractMethodWithMessage(dataSourceNotSet) } } /** For more information take a look at `DelegateProxyType`. */ public class RxCollectionViewDataSourceProxy : DelegateProxy , UICollectionViewDataSource , DelegateProxyType { /** Typed parent object. */ public weak private(set) var collectionView: UICollectionView? private weak var _requiredMethodsDataSource: UICollectionViewDataSource? = collectionViewDataSourceNotSet /** Initializes `RxCollectionViewDataSourceProxy` - parameter parentObject: Parent object for delegate proxy. */ public required init(parentObject: AnyObject) { self.collectionView = (parentObject as! UICollectionView) super.init(parentObject: parentObject) } // MARK: delegate /** Required delegate method implementation. */ public func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return (_requiredMethodsDataSource ?? collectionViewDataSourceNotSet).collectionView(collectionView, numberOfItemsInSection: section) ?? 0 } /** Required delegate method implementation. */ public func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { return (_requiredMethodsDataSource ?? collectionViewDataSourceNotSet).collectionView(collectionView, cellForItemAtIndexPath: indexPath) } // MARK: proxy /** For more information take a look at `DelegateProxyType`. */ public override class func createProxyForObject(object: AnyObject) -> AnyObject { let collectionView = (object as! UICollectionView) return castOrFatalError(collectionView.rx_createDataSourceProxy()) } /** For more information take a look at `DelegateProxyType`. */ public override class func delegateAssociatedObjectTag() -> UnsafePointer<Void> { return _pointer(&dataSourceAssociatedTag) } /** For more information take a look at `DelegateProxyType`. */ public class func setCurrentDelegate(delegate: AnyObject?, toObject object: AnyObject) { let collectionView: UICollectionView = castOrFatalError(object) collectionView.dataSource = castOptionalOrFatalError(delegate) } /** For more information take a look at `DelegateProxyType`. */ public class func currentDelegateFor(object: AnyObject) -> AnyObject? { let collectionView: UICollectionView = castOrFatalError(object) return collectionView.dataSource } /** For more information take a look at `DelegateProxyType`. */ public override func setForwardToDelegate(forwardToDelegate: AnyObject?, retainDelegate: Bool) { let requiredMethodsDataSource: UICollectionViewDataSource? = castOptionalOrFatalError(forwardToDelegate) _requiredMethodsDataSource = requiredMethodsDataSource ?? collectionViewDataSourceNotSet super.setForwardToDelegate(forwardToDelegate, retainDelegate: retainDelegate) } } #endif
mit
9d79d8a970beefdc6122705140c25a5a
32.813559
146
0.732581
6.091603
false
false
false
false
Zeitblick/Zeitblick-iOS
Zeitblick/StartViewController.swift
1
4955
// // StartViewController.swift // Zeitblick // // Created by Bastian Clausdorff on 29.10.16. // Copyright © 2016 Epic Selfie. All rights reserved. // import UIKit import Async import Alamofire import PromiseKit import SwiftyJSON enum StartError: Error { case invalidData } class StartViewController: UIViewController { typealias Me = StartViewController private static let hasSelfieTopConstant: CGFloat = 42 @IBOutlet weak var photoButton: DesignableButton! @IBOutlet weak var selfieImageView: DesignableImageView! var logoHasSelfieConstraint: NSLayoutConstraint! @IBOutlet var logoNoSelfieConstraint: NSLayoutConstraint! @IBOutlet weak var logo: UIImageView! @IBOutlet weak var logoSubtitle: UILabel! var resultImage: UIImage? var metadata: ImageMetadata? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. logoHasSelfieConstraint = logo.topAnchor.constraint(equalTo: view.topAnchor) logoHasSelfieConstraint.constant = Me.hasSelfieTopConstant resetController() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func pickPhoto(_ sender: AnyObject) { let imagePicker = UIImagePickerController() imagePicker.delegate = self Alerts.photo(viewController: self, takePhotoAction: { [weak self] in guard let strongSelf = self else { return } imagePicker.sourceType = .camera imagePicker.cameraDevice = .front strongSelf.present(imagePicker, animated: true) { UIApplication.shared.setStatusBarHidden(true, with: .fade) } }, choosePhotoAction: { [weak self] in guard let strongSelf = self else { return } imagePicker.sourceType = .photoLibrary strongSelf.present(imagePicker, animated: true, completion: nil) }) } func resetController() { selfieImageView.image = nil selfieImageView.isHidden = true photoButton.isHidden = false logoHasSelfieConstraint.isActive = false logoNoSelfieConstraint.isActive = true logoSubtitle.isHidden = false } } extension StartViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { print("selected photo") dismiss(animated: true) { [weak self] in UIApplication.shared.setStatusBarHidden(false, with: .fade) self?.view.showLoading() } guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage else { return } // Change UI selfieImageView.image = image selfieImageView.isHidden = false photoButton.isHidden = true logoNoSelfieConstraint.isActive = false logoHasSelfieConstraint.isActive = true logoSubtitle.isHidden = true let q = DispatchQueue.global() // Find match firstly { return try GoogleVision().analyse(image: image) }.then { visionResponseJson -> Promise<ImageMetadata> in dump(visionResponseJson) return try ZeitblickBackend().findSimilarEmotion(json: visionResponseJson) }.then { [weak self] metadata -> Promise<UIImage> in self?.metadata = metadata return try GoogleDatastore().getImage(inventoryNumber: metadata.inventoryNumber) }.then { [weak self] image -> Void in print("got image") self?.resultImage = image guard let result = self?.resultImage, let metadata = self?.metadata, let selfie = self?.selfieImageView.image else { throw StartError.invalidData } let controller = ResultController(resultImage: result , metadata: metadata, selfieImage: selfie, errorHappened: false) self?.present(controller, animated: false) { self?.resetController() } }.always(on: q) { [weak self] in self?.view.hideLoading() }.catch { [weak self] error in print(error) let errorImage = R.image.errorJpg() let controller = ResultController(resultImage: errorImage!, errorHappened: true) self?.present(controller, animated: false) { self?.resetController() } } } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true) { UIApplication.shared.setStatusBarHidden(false, with: .fade) } } }
gpl-3.0
aedba5599a5a10a4323c5124a183a98c
32.472973
130
0.635042
5.304069
false
false
false
false
MateuszKarwat/Napi
Napi/Models/Subtitle Provider/Supported Subtitle Providers/Napisy24.swift
1
5416
// // Created by Mateusz Karwat on 18/12/2016. // Copyright © 2016 Mateusz Karwat. All rights reserved. // import Foundation struct Napisy24: SubtitleProvider { let name = "Napisy24" let homepage = URL(string: "http://napisy24.pl")! func searchSubtitles(using searchCritera: SearchCriteria, completionHandler: @escaping ([SubtitleEntity]) -> Void) { log.info("Sending search request.") guard let searchRequest = searchRequest(with: searchCritera) else { log.warning("Search request couldn't be created.") completionHandler([]) return } let dataTask = URLSession.shared.dataTask(with: searchRequest) { data, encoding in log.info("Search response received.") guard let data = data, let encoding = encoding, let stringResponse = String(data: data, encoding: encoding) ?? String(data: data, encoding: .isoLatin1), let subtitleEntity = self.subtitleEntity(from: stringResponse, in: searchCritera.language) else { completionHandler([]) return } completionHandler([subtitleEntity]) } dataTask.resume() } func download(_ subtitleEntity: SubtitleEntity, completionHandler: @escaping (SubtitleEntity?) -> Void) { log.info("Downloading subtitles.") var downloadedSubtitleEntity: SubtitleEntity? = nil defer { completionHandler(downloadedSubtitleEntity) } guard subtitleEntity.format == .archive else { return } let directoryManager = TemporaryDirectoryManager.default directoryManager.createTemporaryDirectory() let extractedArchive = subtitleEntity.temporaryPathWithoutFormatExtension Unziper.unzipFile(at: subtitleEntity.url, to: extractedArchive, overwrite: true) if extractedArchive.exists && extractedArchive.isDirectory { let fileManager = FileManager.default do { let content = try fileManager.contentsOfDirectory(at: extractedArchive, includingPropertiesForKeys: nil, options: .skipsHiddenFiles) let onlySubtitles = content.filter { SupportedSubtitleFormat.allFileExtensions.contains($0.pathExtension) } if let subtitle = onlySubtitles.first { let extractedSubtitlePath = subtitleEntity.temporaryPathWithoutFormatExtension .appendingPathExtension(SubtitleEntity.Format.text.pathExtension) try fileManager.moveItem(at: subtitle, to: extractedSubtitlePath) try fileManager.removeItem(at: extractedArchive) try fileManager.removeItem(at: subtitleEntity.url) downloadedSubtitleEntity = subtitleEntity downloadedSubtitleEntity?.format = .text downloadedSubtitleEntity?.url = extractedSubtitlePath log.info("Subtitles downloaded.") } else { return } } catch let error { log.error(error.localizedDescription) return } } return } private func subtitleEntity(from stringResponse: String, in language: Language) -> SubtitleEntity? { log.verbose("Parsing search response.") guard stringResponse.substring(to: 4) == "OK-2", let archiveStartIndex = stringResponse.range(of: "||")?.upperBound else { log.verbose("Subtitles has not been found.") return nil } let subtitleEntity = SubtitleEntity(language: language, format: .archive) let archiveString = stringResponse[archiveStartIndex...] let archiveData = archiveString.data(using: .isoLatin1) do { TemporaryDirectoryManager.default.createTemporaryDirectory() try archiveData?.write(to: subtitleEntity.url) log.verbose("Subtitles has been found.") } catch let error { log.error(error.localizedDescription) return nil } return subtitleEntity } private func searchRequest(with searchCriteria: SearchCriteria) -> URLRequest? { guard searchCriteria.language.isoCode == "pl", // Napisy24 returns only subtitles in Polish. let fileInformation = FileInformation(url: searchCriteria.fileURL), let checksum = fileInformation.checksum, let md5 = fileInformation.md5(chunkSize: 10 * 1024 * 1024) else { return nil } let baseURL = URL(string: "http://napisy24.pl/run/CheckSubAgent.php")! var parameters = [String: String]() parameters["postAction"] = "CheckSub" parameters["ua"] = "tantalosus" parameters["ap"] = "susolatnat" parameters["fh"] = checksum parameters["md"] = md5 parameters["fn"] = fileInformation.name parameters["nl"] = searchCriteria.language.isoCode parameters["fs"] = String(fileInformation.size) var urlRequest = URLRequest(url: baseURL) urlRequest.httpMethod = "POST" urlRequest.httpBody = parameters.httpBodyFormat.data(using: .utf8) return urlRequest } }
mit
ec414d4f109b878c13c7145484d97b37
36.089041
148
0.61699
5.26751
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformUIKit/Components/LinkedBankAccountTableViewCell/LinkedBankAccountTableViewCell.swift
1
2926
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import RxSwift import UIKit public final class LinkedBankAccountTableViewCell: UITableViewCell { public var presenter: LinkedBankAccountCellPresenter! { willSet { disposeBag = DisposeBag() } didSet { guard let presenter = presenter else { titleLabel.content = .empty descriptionLabel.content = .empty badgeImageView.viewModel = nil multiBadgeView.model = nil return } presenter.multiBadgeViewModel .drive(multiBadgeView.rx.viewModel) .disposed(by: disposeBag) presenter.badgeImageViewModel .drive(badgeImageView.rx.viewModel) .disposed(by: disposeBag) presenter.title .drive(titleLabel.rx.content) .disposed(by: disposeBag) presenter.description .drive(descriptionLabel.rx.content) .disposed(by: disposeBag) } } // MARK: - Private Properties private var disposeBag = DisposeBag() private let badgeImageView = BadgeImageView() private let stackView = UIStackView() private let titleLabel = UILabel() private let descriptionLabel = UILabel() private let multiBadgeView = MultiBadgeView() private let separatorView = UIView() // MARK: - Lifecycle override public init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setup() } required init?(coder: NSCoder) { super.init(coder: coder) setup() } override public func prepareForReuse() { super.prepareForReuse() presenter = nil } func setup() { addSubview(badgeImageView) addSubview(multiBadgeView) addSubview(stackView) addSubview(separatorView) stackView.axis = .vertical stackView.spacing = 4.0 stackView.addArrangedSubview(titleLabel) stackView.addArrangedSubview(descriptionLabel) separatorView.layout(dimension: .height, to: 1) separatorView.layoutToSuperview(.leading, .trailing, .bottom) badgeImageView.layout(size: .edge(32)) badgeImageView.layoutToSuperview(.leading, offset: 24) badgeImageView.layout(to: .centerY, of: stackView) stackView.layoutToSuperview(.top, offset: 16) stackView.layout(edge: .leading, to: .trailing, of: badgeImageView, offset: 16) stackView.layout(edge: .bottom, to: .top, of: multiBadgeView, offset: -4) multiBadgeView.layoutToSuperview(.leading, .trailing) multiBadgeView.layout(edge: .bottom, to: .top, of: separatorView, offset: -16) separatorView.backgroundColor = .lightBorder } }
lgpl-3.0
fb31ef87cf55ed51eb45d84f24571973
29.789474
87
0.629402
5.176991
false
false
false
false
nzaghini/mastering-reuse-viper
Weather/Modules/WeatherList/Core/View/WeatherListViewController.swift
2
2622
import Foundation import UIKit class WeatherListViewController: UITableViewController, WeatherListView { var viewModel: LocationListViewModel? var presenter: WeatherListPresenter? override func viewDidLoad() { super.viewDidLoad() self.navigationItem.rightBarButtonItem = self.addButtonItem() self.presenter?.loadContent() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.presenter?.loadContent() } // MARK: - CityListView func displayLocationList(_ viewModel: LocationListViewModel) { self.viewModel = viewModel self.tableView.reloadData() } func displayError(_ errorMessage: String) { let alert = UIAlertController(title: "Error", message: errorMessage, preferredStyle: .alert) let cancelAction = UIAlertAction(title: "OK", style: .cancel, handler: nil) alert.addAction(cancelAction) self.present(alert, animated: true, completion: nil) } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let viewModel = self.viewModel { return viewModel.locations.count } return 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: "WeatherCell") if cell == nil { cell = UITableViewCell(style: .subtitle, reuseIdentifier: "WeatherCell") cell?.accessoryType = .disclosureIndicator } if let item = self.viewModel?.locations[indexPath.row] { cell?.textLabel?.text = item.name cell?.detailTextLabel?.text = item.detail } return cell! } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let viewModel = self.viewModel { let locationId = viewModel.locations[indexPath.row].locationId self.presenter?.presentWeatherDetail(locationId) } } // MARK: - Utils func addButtonItem() -> UIBarButtonItem { return UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(self.addWeatherLocation)) } func addWeatherLocation() { self.presenter?.presentAddWeatherLocation() } }
mit
28485f64acaf36ea5c53fe350c94b5ab
30.590361
115
0.638444
5.417355
false
false
false
false
SeriousChoice/SCSwift
SCSwift/Controllers/SCMediaViewController.swift
1
2097
// // SCMediaViewController.swift // SCSwiftExample // // Created by Nicola Innocenti on 08/01/2022. // Copyright © 2022 Nicola Innocenti. All rights reserved. // import UIKit protocol SCMediaViewControllerDelegate : AnyObject { func mediaDidTapView() func mediaDidDoubleTap() func mediaDidFailLoad(media: SCMedia) } open class SCMediaViewController: UIViewController { public var index: Int = 0 weak var delegate: SCMediaViewControllerDelegate? private var tap: UITapGestureRecognizer! private var doubleTap: UITapGestureRecognizer! public var media: SCMedia! // MARK: - Initialization public convenience init(media: SCMedia) { self.init() self.media = media } // MARK: - UIViewController Methods override open func viewDidLoad() { super.viewDidLoad() setGestures(on: view) } // MARK: - Other Methods func setGestures(on view: UIView) { tap = UITapGestureRecognizer(target: self, action: #selector(self.didSingleTap(gesture:))) tap.numberOfTapsRequired = 1 tap.cancelsTouchesInView = false view.addGestureRecognizer(tap) if media.type != .pdf { doubleTap = UITapGestureRecognizer(target: self, action: #selector(self.didDoubleTap)) doubleTap.cancelsTouchesInView = false doubleTap.numberOfTapsRequired = 2 view.addGestureRecognizer(doubleTap) tap.require(toFail: doubleTap) } } @objc public func didSingleTap(gesture: UITapGestureRecognizer) { self.didTap() } @objc public func didTap() { delegate?.mediaDidTapView() } @objc public func didDoubleTap() { delegate?.mediaDidDoubleTap() } open func refresh(media: SCMedia) { self.media = media } override open func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
82fe9ac4e32814d96f6f2f7147cba06c
24.560976
98
0.629771
5.137255
false
false
false
false
tensorflow/examples
lite/examples/pose_estimation/ios/PoseEstimation/Camera/CameraFeedManager.swift
1
3432
// Copyright 2021 The TensorFlow Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ============================================================================= import AVFoundation import Accelerate.vImage import UIKit /// Delegate to receive the frames captured from the device's camera. protocol CameraFeedManagerDelegate: AnyObject { /// Callback method that receives frames from the camera. /// - Parameters: /// - cameraFeedManager: The CameraFeedManager instance which calls the delegate. /// - pixelBuffer: The frame received from the camera. func cameraFeedManager( _ cameraFeedManager: CameraFeedManager, didOutput pixelBuffer: CVPixelBuffer) } /// Manage the camera pipeline. final class CameraFeedManager: NSObject, AVCaptureVideoDataOutputSampleBufferDelegate { /// Delegate to receive the frames captured by the device's camera. var delegate: CameraFeedManagerDelegate? override init() { super.init() configureSession() } /// Start capturing frames from the camera. func startRunning() { captureSession.startRunning() } /// Stop capturing frames from the camera. func stopRunning() { captureSession.stopRunning() } let captureSession = AVCaptureSession() /// Initialize the capture session. private func configureSession() { captureSession.sessionPreset = AVCaptureSession.Preset.photo guard let backCamera = AVCaptureDevice.default( .builtInWideAngleCamera, for: .video, position: .back) else { return } do { let input = try AVCaptureDeviceInput(device: backCamera) captureSession.addInput(input) } catch { return } let videoOutput = AVCaptureVideoDataOutput() videoOutput.videoSettings = [ (kCVPixelBufferPixelFormatTypeKey as String): NSNumber(value: kCVPixelFormatType_32BGRA) ] videoOutput.alwaysDiscardsLateVideoFrames = true let dataOutputQueue = DispatchQueue( label: "video data queue", qos: .userInitiated, attributes: [], autoreleaseFrequency: .workItem) if captureSession.canAddOutput(videoOutput) { captureSession.addOutput(videoOutput) videoOutput.connection(with: .video)?.videoOrientation = .portrait captureSession.startRunning() } videoOutput.setSampleBufferDelegate(self, queue: dataOutputQueue) } // MARK: Methods of the AVCaptureVideoDataOutputSampleBufferDelegate func captureOutput( _ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection ) { guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return } CVPixelBufferLockBaseAddress(pixelBuffer, CVPixelBufferLockFlags.readOnly) delegate?.cameraFeedManager(self, didOutput: pixelBuffer) CVPixelBufferUnlockBaseAddress(pixelBuffer, CVPixelBufferLockFlags.readOnly) } }
apache-2.0
985dbaed69b8cb7f1a68f6d7ba8c910c
32.980198
94
0.722028
5.271889
false
false
false
false
nbhasin2/Sudoku
Sudoku/3rd Party/Device/Device.swift
1
6480
// // Device.swift // Device // // Created by Lucas Ortis on 30/10/2015. // Copyright © 2015 Ekhoo. All rights reserved. // import UIKit public class Device { static private func getVersionCode() -> String { var systemInfo = utsname() uname(&systemInfo) let versionCode: String = String(UTF8String: NSString(bytes: &systemInfo.machine, length: Int(_SYS_NAMELEN), encoding: NSASCIIStringEncoding)!.UTF8String)! return versionCode } static private func getVersion(code code: String) -> Version { switch code { /*** iPhone ***/ case "iPhone3,1", "iPhone3,2", "iPhone3,3": return Version.iPhone4 case "iPhone4,1", "iPhone4,2", "iPhone4,3": return Version.iPhone4S case "iPhone5,1", "iPhone5,2": return Version.iPhone5 case "iPhone5,3", "iPhone5,4": return Version.iPhone5C case "iPhone6,1", "iPhone6,2": return Version.iPhone5S case "iPhone7,2": return Version.iPhone6 case "iPhone7,1": return Version.iPhone6Plus case "iPhone8,1": return Version.iPhone6S case "iPhone8,2": return Version.iPhone6SPlus case "iPhone8,4": return Version.iPhoneSE /*** iPad ***/ case "iPad1,1": return Version.iPad1 case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4": return Version.iPad2 case "iPad3,1", "iPad3,2", "iPad3,3": return Version.iPad3 case "iPad3,4", "iPad3,5", "iPad3,6": return Version.iPad4 case "iPad4,1", "iPad4,2", "iPad4,3": return Version.iPadAir case "iPad5,3", "iPad5,4": return Version.iPadAir2 case "iPad2,5", "iPad2,6", "iPad2,7": return Version.iPadMini case "iPad4,4", "iPad4,5", "iPad4,6": return Version.iPadMini2 case "iPad4,7", "iPad4,8", "iPad4,9": return Version.iPadMini3 case "iPad5,1", "iPad5,2": return Version.iPadMini4 case "iPad6,3", "iPad6,4", "iPad6,7", "iPad6,8": return Version.iPadPro /*** iPod ***/ case "iPod1,1": return Version.iPodTouch1Gen case "iPod2,1": return Version.iPodTouch2Gen case "iPod3,1": return Version.iPodTouch3Gen case "iPod4,1": return Version.iPodTouch4Gen case "iPod5,1": return Version.iPodTouch5Gen case "iPod7,1": return Version.iPodTouch6Gen /*** Simulator ***/ case "i386", "x86_64": return Version.Simulator default: return Version.Unknown } } static private func getType(code code: String) -> Type { let versionCode = Device.getVersionCode() switch versionCode { case "iPhone3,1", "iPhone3,2", "iPhone3,3", "iPhone4,1", "iPhone4,2", "iPhone4,3", "iPhone5,1", "iPhone5,2", "iPhone5,3", "iPhone5,4", "iPhone6,1", "iPhone6,2", "iPhone7,2", "iPhone7,1", "iPhone8,1", "iPhone8,2", "iPhone8,4": return Type.iPhone case "iPad1,1", "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4", "iPad3,1", "iPad3,2", "iPad3,3", "iPad3,4", "iPad3,5", "iPad3,6", "iPad4,1", "iPad4,2", "iPad4,3", "iPad5,3", "iPad5,4", "iPad2,5", "iPad2,6", "iPad2,7", "iPad4,4", "iPad4,5", "iPad4,6", "iPad4,7", "iPad4,8", "iPad4,9", "iPad5,1", "iPad5,2", "iPad6,3", "iPad6,4", "iPad6,7", "iPad6,8": return Type.iPad case "iPod1,1", "iPod2,1", "iPod3,1", "iPod4,1", "iPod5,1", "iPod7,1": return Type.iPod case "i386", "x86_64": return Type.Simulator default: return Type.Unknown } } static public func version() -> Version { let versionName = Device.getVersionCode() return Device.getVersion(code: versionName) } static public func size() -> Size { let w: Double = Double(CGRectGetWidth(UIScreen.mainScreen().bounds)) let h: Double = Double(CGRectGetHeight(UIScreen.mainScreen().bounds)) let screenHeight: Double = max(w, h) switch screenHeight { case 480: return Size.Screen3_5Inch case 568: return Size.Screen4Inch case 667: return UIScreen.mainScreen().scale == 3.0 ? Size.Screen5_5Inch : Size.Screen4_7Inch case 736: return Size.Screen5_5Inch case 1024: switch Device.version() { case .iPadMini,.iPadMini2,.iPadMini3,.iPadMini4: return Size.Screen7_9Inch default: return Size.Screen9_7Inch } case 1366: return Size.Screen12_9Inch default: return Size.UnknownSize } } static public func type() -> Type { let versionName = Device.getVersionCode() return Device.getType(code: versionName) } static public func isEqualToScreenSize(size: Size) -> Bool { return size == Device.size() ? true : false; } static public func isLargerThanScreenSize(size: Size) -> Bool { return size.rawValue < Device.size().rawValue ? true : false; } static public func isSmallerThanScreenSize(size: Size) -> Bool { return size.rawValue > Device.size().rawValue ? true : false; } }
apache-2.0
07ef679f21b0fc12d16d8b10ca2127cb
41.071429
163
0.471215
4.240183
false
false
false
false
sudeepag/Phobia
Phobia/WordManager.swift
1
2046
// // WordManager.swift // Phobia // // Created by Sudeep Agarwal on 11/21/15. // Copyright © 2015 Sudeep Agarwal. All rights reserved. // import Foundation import UIKit class WordManager { static let sharedManager = WordManager() func createWordList() -> [Word] { var wordList = [Word]() let heightList = ["mountain", "peak", "summit", "edge", "deep", "cliff", "fall", "collapse", "release", "descent", "leap", "plunge", "crash", "drop-off", "skyscraper", "slip", "clinging", "ladder", "balance"] for item in heightList { wordList.append(Word(text: item, color: randomColor(), type: WordType.TriggerHeights)) } let spiderList = ["web", "crawly", "hair", "angular", "bite", "leggy", "beady", "venom", "fang", "orb", "egg sack", "skitter", "molting", "furry", "scurry", "scuttle", "scamper", "scatter", "cobweb", "pointy"] for item in spiderList { wordList.append(Word(text: item, color: randomColor(), type: WordType.TriggerSpiders)) } let snakeList = ["slither", "squeeze", "poison", "squirm", "scaly", "hiss", "viper", "forked", "suffocate", "slimy", "wriggle", "coil", "reptile", "twine", "legless", "serpent", "oily", "sly"] for item in snakeList { wordList.append(Word(text: item, color: randomColor(), type: WordType.TriggerSnakes)) } let neutralList = ["apple", "square", "pineapple", "drink", "sleepy", "mango", "creative", "microphone", "pen", "highlighter", "pencil", "popcorn", "remote", "internet", "phone", "dance", "mouse", "cat", "fish", "makeup"] for item in neutralList { wordList.append(Word(text: item, color: randomColor(), type: WordType.Neutral)) } wordList.shuffleInPlace() return wordList } func randomColor() -> ColorType { let colors = [ColorType.Red, ColorType.Blue, ColorType.Green] return colors[Int(arc4random_uniform(3))] } }
mit
c1e1e5852c21d7297688a5645cbf044b
39.92
229
0.583374
3.581436
false
false
false
false
perrywky/CCFlexbox
Source/CCFlexbox.swift
1
24400
// // CCFlexbox.swift // CCFlexbox // // Created by Perry on 15/12/30. // Copyright © 2015年 Perry. All rights reserved. // import UIKit import ObjectiveC private struct FlexboxAssociatedKeys { static var flexGrow = "cfb_flexGrow" static var flexShrink = "cfb_flexShrink" static var flexBasis = "cfb_flexBasis" static var alignSelf = "cfb_alignSelf" static var margin = "cfb_margin" } private struct AxisLayoutAttributes { let mainAxis: UILayoutConstraintAxis let crossAxis: UILayoutConstraintAxis let mainPrevious: NSLayoutAttribute let mainNext: NSLayoutAttribute let crossPrevious: NSLayoutAttribute let crossNext: NSLayoutAttribute let mainSize: NSLayoutAttribute let crossSize: NSLayoutAttribute let mainCenter:NSLayoutAttribute let crossCenter:NSLayoutAttribute init(vertical:Bool) { if vertical { mainAxis = .Vertical crossAxis = .Horizontal mainPrevious = .Top mainNext = .Bottom crossPrevious = .Left crossNext = .Right mainSize = .Height crossSize = .Width mainCenter = .CenterY crossCenter = .CenterX } else { mainAxis = .Horizontal crossAxis = .Vertical mainPrevious = .Left mainNext = .Right crossPrevious = .Top crossNext = .Bottom mainSize = .Width crossSize = .Height mainCenter = .CenterX crossCenter = .CenterY } } } private struct AxisMargins { var mainPrevious: CGFloat var mainNext: CGFloat var crossPrevious: CGFloat var crossNext: CGFloat } private struct AxisBasis { let mainBasis: CGFloat let crossBasis: CGFloat } public let MarginAuto:CGFloat = CGFloat.max public extension UIView { func cfb_flexBasis(size:CGSize) -> UIView { objc_setAssociatedObject(self, &FlexboxAssociatedKeys.flexBasis, NSValue.init(CGSize: size), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) if let parent = superview { parent.setNeedsUpdateConstraints() } return self } func cfb_flexBasis(width:CGFloat, height:CGFloat) -> UIView { objc_setAssociatedObject(self, &FlexboxAssociatedKeys.flexBasis, NSValue.init(CGSize: CGSizeMake(width, height)), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) if let parent = superview { parent.setNeedsUpdateConstraints() } return self } func cfb_flexBasis(width:CGFloat, _ height:CGFloat) -> UIView { objc_setAssociatedObject(self, &FlexboxAssociatedKeys.flexBasis, NSValue.init(CGSize: CGSizeMake(width, height)), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) if let parent = superview { parent.setNeedsUpdateConstraints() } return self } func cfb_flexGrow(grow:Int) -> UIView { objc_setAssociatedObject(self, &FlexboxAssociatedKeys.flexGrow, NSNumber.init(long: grow), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) if let parent = superview { parent.setNeedsUpdateConstraints() } return self } func cfb_flexShrink(shrink:Int) -> UIView { objc_setAssociatedObject(self, &FlexboxAssociatedKeys.flexShrink, NSNumber.init(long: shrink), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) if let parent = superview { parent.setNeedsUpdateConstraints() } return self } func cfb_alignSelf(align:AlignItems) -> UIView { objc_setAssociatedObject(self, &FlexboxAssociatedKeys.alignSelf, NSNumber.init(long: align.rawValue), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) if let parent = superview { parent.setNeedsUpdateConstraints() } return self } func cfb_margin(margin:UIEdgeInsets) -> UIView { objc_setAssociatedObject(self, &FlexboxAssociatedKeys.margin, NSValue.init(UIEdgeInsets: margin), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) if let parent = superview { parent.setNeedsUpdateConstraints() } return self } func cfb_top(top:CGFloat) -> UIView { let marginValue = objc_getAssociatedObject(self, &FlexboxAssociatedKeys.margin) var margin = marginValue == nil ? UIEdgeInsetsZero : marginValue.UIEdgeInsetsValue() margin.top = top cfb_margin(margin) return self } func cfb_left(left:CGFloat) -> UIView { let marginValue = objc_getAssociatedObject(self, &FlexboxAssociatedKeys.margin) var margin = marginValue == nil ? UIEdgeInsetsZero : marginValue.UIEdgeInsetsValue() margin.left = left cfb_margin(margin) return self } func cfb_bottom(bottom:CGFloat) -> UIView { let marginValue = objc_getAssociatedObject(self, &FlexboxAssociatedKeys.margin) var margin = marginValue == nil ? UIEdgeInsetsZero : marginValue.UIEdgeInsetsValue() margin.bottom = bottom cfb_margin(margin) return self } func cfb_right(right:CGFloat) -> UIView { let marginValue = objc_getAssociatedObject(self, &FlexboxAssociatedKeys.margin) var margin = marginValue == nil ? UIEdgeInsetsZero : marginValue.UIEdgeInsetsValue() margin.right = right cfb_margin(margin) return self } func cfb_topAuto() -> UIView { let marginValue = objc_getAssociatedObject(self, &FlexboxAssociatedKeys.margin) var margin = marginValue == nil ? UIEdgeInsetsZero : marginValue.UIEdgeInsetsValue() margin.top = MarginAuto cfb_margin(margin) return self } func cfb_leftAuto() -> UIView { let marginValue = objc_getAssociatedObject(self, &FlexboxAssociatedKeys.margin) var margin = marginValue == nil ? UIEdgeInsetsZero : marginValue.UIEdgeInsetsValue() margin.left = MarginAuto cfb_margin(margin) return self } func cfb_rightAuto() -> UIView { let marginValue = objc_getAssociatedObject(self, &FlexboxAssociatedKeys.margin) var margin = marginValue == nil ? UIEdgeInsetsZero : marginValue.UIEdgeInsetsValue() margin.right = MarginAuto cfb_margin(margin) return self } func cfb_bottomAuto() -> UIView { let marginValue = objc_getAssociatedObject(self, &FlexboxAssociatedKeys.margin) var margin = marginValue == nil ? UIEdgeInsetsZero : marginValue.UIEdgeInsetsValue() margin.bottom = MarginAuto cfb_margin(margin) return self } } private class CCLayoutGuide: UIView { } private class CCLabelLayoutGuide: UILabel { } @objc public enum JustifyContent: Int{ case FlexStart, FlexEnd, Center, SpaceBetween, SpaceAround, SpaceSeperate } @objc public enum AlignItems: Int { case Auto, FlexStart, FlexEnd, Center, Baseline, Stretch } @objc public class CCFlexbox: UIView { private var items: [UIView] = [] private var vertical: Bool = false private var justifyContent: JustifyContent = .FlexStart private var alignItems: AlignItems = .Auto private let baseline:CCLabelLayoutGuide = CCLabelLayoutGuide.init() //for baseline alignment private let layoutGuideSize:CGFloat = 0 //used for debugging private var constraintIdentifier:String = NSUUID().UUIDString //used for clearing existing constraints public var updateConstraintsCount = 0; private var axisAttributes:AxisLayoutAttributes = AxisLayoutAttributes.init(vertical: false) private init(items: [UIView]) { super.init(frame: CGRectZero) self.items = items for item in items { self.addSubview(item) } } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public class func row(items: UIView...) -> CCFlexbox { let box = CCFlexbox.init(items: items) box.setupItems() return box } public class func row(items: [UIView]) -> CCFlexbox { let box = CCFlexbox.init(items: items) box.setupItems() return box } public class func column(items: UIView...) -> CCFlexbox { let box = CCFlexbox.init(items: items) box.vertical = true box.axisAttributes = AxisLayoutAttributes.init(vertical: true) box.setupItems() return box } public class func column(items: [UIView]) -> CCFlexbox { let box = CCFlexbox.init(items: items) box.vertical = true box.axisAttributes = AxisLayoutAttributes.init(vertical: true) box.setupItems() return box } public func justifyContent(value:JustifyContent) -> CCFlexbox { self.justifyContent = value self.setNeedsUpdateConstraints() return self } public func alignItems(value:AlignItems) -> CCFlexbox { self.alignItems = value self.setNeedsUpdateConstraints() return self } private func setupItems() -> Void { for index in 0 ..< items.count { let item = items[index] self.addSubview(item) item.translatesAutoresizingMaskIntoConstraints = false } } override public func updateConstraints() { clearFlexConstraints(self) applyFlexLayout() super.updateConstraints() self.updateConstraintsCount += 1 } private func applyFlexLayout() { var grows = 0 var autoMarginCount = 0 for item in items { let grow = getFlexGrowForItem(item) grows += grow let margin = getAxisMarginsForItem(item) if margin.mainPrevious == MarginAuto { autoMarginCount += 1 } if margin.mainNext == MarginAuto { autoMarginCount += 1 } } for subview in self.subviews { if subview is CCLayoutGuide { subview.removeFromSuperview() clearFlexConstraints(subview) } } baseline.removeFromSuperview() clearFlexConstraints(baseline) var subviews:[UIView] = [] var autoSpaces:[UIView] = [] var lastNextMargin:CGFloat = 0 for index in 0 ..< items.count { let item = items[index] clearFlexConstraints(item) let basis = getAxisBasisForItem(item) let grow = max(getFlexGrowForItem(item), 0) let shrink = max(getFlexShrinkForItem(item), 0) if basis.mainBasis != UIViewNoIntrinsicMetric { setConstantConstraint(item, attribute: axisAttributes.mainSize, constant: basis.mainBasis, .GreaterThanOrEqual, Float(750-shrink)) //ContentCompressionResistancePriority setConstantConstraint(item, attribute: axisAttributes.mainSize, constant: basis.mainBasis, .LessThanOrEqual, Float(251-grow)) //ContentHuggingPriority //prevent content size changing bound size item.setContentCompressionResistancePriority(1, forAxis: axisAttributes.mainAxis) item.setContentHuggingPriority(1, forAxis: axisAttributes.mainAxis) } else{ item.setContentCompressionResistancePriority(Float(750 - shrink), forAxis: axisAttributes.mainAxis) //no shrinking item.setContentHuggingPriority(Float(251 - grow), forAxis: axisAttributes.mainAxis)//make sibing column's inner label width grow } var margin = getAxisMarginsForItem(item) let previousMargin = margin.mainPrevious == MarginAuto ? 0 : margin.mainPrevious //no items can grow enabling auto margin let insertLeftAutoSpace = autoMarginCount == 0 && grows == 0 && ( (justifyContent == .Center && index == 0) || justifyContent == .SpaceAround || justifyContent == .SpaceSeperate) if (margin.mainPrevious == MarginAuto && grows == 0) || insertLeftAutoSpace { let previousAutoSpace = CCLayoutGuide.init() previousAutoSpace.backgroundColor = UIColor.blackColor() previousAutoSpace.translatesAutoresizingMaskIntoConstraints = false self.addSubview(previousAutoSpace) setAlignConstraint(item: previousAutoSpace, attribute: axisAttributes.crossPrevious) setConstantConstraint(previousAutoSpace, attribute: axisAttributes.crossSize, constant: layoutGuideSize) if subviews.count > 0 { setAlignConstraint(item: previousAutoSpace, attribute: axisAttributes.mainPrevious, constant: 0, relatedBy: .Equal, toItem: subviews.last!, attribute: axisAttributes.mainNext, priority: UILayoutPriorityRequired) } else { setAlignConstraint(item: previousAutoSpace, attribute: axisAttributes.mainPrevious, constant: 0, relatedBy: .Equal, toItem: self, attribute: axisAttributes.mainPrevious, priority: UILayoutPriorityRequired) } subviews.append(previousAutoSpace) autoSpaces.append(previousAutoSpace) } if subviews.count > 0 { setAlignConstraint(item: item, attribute: axisAttributes.mainPrevious, constant: previousMargin + lastNextMargin, relatedBy: .Equal, toItem: subviews.last!, attribute: axisAttributes.mainNext, priority: UILayoutPriorityRequired) } else { if justifyContent == .FlexEnd { setAlignConstraint(item: item, attribute: axisAttributes.mainPrevious, constant: previousMargin, relatedBy: .GreaterThanOrEqual, toItem: self, attribute: axisAttributes.mainPrevious, priority: 999) if grows > 0 { setAlignConstraint(item: item, attribute: axisAttributes.mainPrevious, constant: previousMargin, relatedBy: .Equal, toItem: self, attribute: axisAttributes.mainPrevious, priority: 999) } else { setAlignConstraint(item: item, attribute: axisAttributes.mainPrevious, constant: previousMargin, relatedBy: .Equal, toItem: self, attribute: axisAttributes.mainPrevious, priority: UILayoutPriorityDefaultLow) } } else { setAlignConstraint(item: item, attribute: axisAttributes.mainPrevious, constant: previousMargin, relatedBy: .Equal, toItem: self, attribute: axisAttributes.mainPrevious, priority: UILayoutPriorityRequired) } } subviews.append(item) lastNextMargin = margin.mainNext == MarginAuto ? 0 : margin.mainNext let insertRightAutoSpace = autoMarginCount == 0 && grows == 0 && ( (justifyContent == .Center && index == items.count - 1) || (justifyContent == .SpaceBetween && index < items.count - 1) || justifyContent == .SpaceAround || (justifyContent == .SpaceSeperate && index == items.count - 1)) if (margin.mainNext == MarginAuto && grows == 0) || insertRightAutoSpace { let nextAutoSpace = CCLayoutGuide.init() nextAutoSpace.backgroundColor = UIColor.blackColor() nextAutoSpace.translatesAutoresizingMaskIntoConstraints = false self.addSubview(nextAutoSpace) setAlignConstraint(item: nextAutoSpace, attribute: axisAttributes.crossPrevious) setConstantConstraint(nextAutoSpace, attribute: axisAttributes.crossSize, constant: layoutGuideSize) setAlignConstraint(item: nextAutoSpace, attribute: axisAttributes.mainPrevious, constant: 0, relatedBy: .Equal, toItem: item, attribute: axisAttributes.mainNext, priority: UILayoutPriorityRequired) if index == items.count - 1 { setAlignConstraint(item: nextAutoSpace, attribute: axisAttributes.mainNext, constant: 0, relatedBy: .Equal, toItem: self, attribute: axisAttributes.mainNext, priority: UILayoutPriorityRequired) } subviews.append(nextAutoSpace) autoSpaces.append(nextAutoSpace) } else { if index == items.count - 1 { if justifyContent == .FlexEnd { setAlignConstraint(item: self, attribute: axisAttributes.mainNext, constant: lastNextMargin, relatedBy: .Equal, toItem: item, attribute: axisAttributes.mainNext, priority: UILayoutPriorityRequired) } else { setAlignConstraint(item: self, attribute: axisAttributes.mainNext, constant: lastNextMargin, relatedBy: .GreaterThanOrEqual, toItem: item, attribute: axisAttributes.mainNext, priority: 999) if grows > 0 { setAlignConstraint(item: self, attribute: axisAttributes.mainNext, constant: lastNextMargin, relatedBy: .Equal, toItem: item, attribute: axisAttributes.mainNext, priority: 999) } else { setAlignConstraint(item: self, attribute: axisAttributes.mainNext, constant: lastNextMargin, relatedBy: .Equal, toItem: item, attribute: axisAttributes.mainNext, priority: UILayoutPriorityDefaultLow) } } } } var align = getAlignSelfForItem(item) if align == .Auto { align = alignItems } if margin.crossPrevious == MarginAuto { margin.crossPrevious = 0 } if margin.crossNext == MarginAuto { margin.crossNext = 0 } switch align { case .FlexStart: setAlignConstraint(item: item, attribute: axisAttributes.crossPrevious, constant: margin.crossPrevious) break; case .FlexEnd: setAlignConstraint(item: item, attribute: axisAttributes.crossNext, constant: -margin.crossNext) break; case .Center: setAlignConstraint(item: item, attribute: axisAttributes.crossCenter) break; case .Baseline: if !vertical { addSubview(baseline) baseline.translatesAutoresizingMaskIntoConstraints = false setAlignConstraint(item: baseline, attribute: axisAttributes.mainPrevious) setAlignConstraint(item: baseline, attribute: axisAttributes.crossPrevious) setAlignConstraint(item: baseline, attribute: axisAttributes.mainSize, constant: layoutGuideSize) setAlignConstraint(item: baseline, attribute: axisAttributes.crossSize) setAlignConstraint(item: item, attribute: .Baseline, constant: 0, relatedBy: .Equal, toItem: baseline, attribute: .Baseline) } break; case .Stretch, .Auto: setAlignConstraint(item: item, attribute: axisAttributes.crossPrevious, constant: margin.crossPrevious) setAlignConstraint(item: item, attribute: axisAttributes.crossNext, constant: -margin.crossNext) break; } if align != .Stretch && align != .Auto && basis.crossBasis != UIViewNoIntrinsicMetric { setConstantConstraint(item, attribute: axisAttributes.crossSize, constant: basis.crossBasis, .GreaterThanOrEqual, 750) setConstantConstraint(item, attribute: axisAttributes.crossSize, constant: basis.crossBasis, .LessThanOrEqual, 750) setConstantConstraint(item, attribute: axisAttributes.crossSize, constant: basis.crossBasis, .Equal, 750) } setAlignConstraint(item: item, attribute: axisAttributes.crossSize, constant: 0, relatedBy: .LessThanOrEqual, toItem: self, attribute: axisAttributes.crossSize, priority: 999); } if autoSpaces.count > 0 { //auto spaces consume all extra space let firstSpace = autoSpaces.first! setConstantConstraint(firstSpace, attribute: axisAttributes.mainSize, constant: 0, .GreaterThanOrEqual) for space in autoSpaces[1..<autoSpaces.count] { setAlignConstraint(item: space, attribute: axisAttributes.mainSize, constant: 0, relatedBy: .Equal, toItem: firstSpace, attribute: axisAttributes.mainSize) } } } private func getAxisBasisForItem(item:UIView) -> AxisBasis { let basisValue = objc_getAssociatedObject(item, &FlexboxAssociatedKeys.flexBasis) let size = basisValue == nil ? CGSizeMake(UIViewNoIntrinsicMetric, UIViewNoIntrinsicMetric) : basisValue.CGSizeValue() if vertical { return AxisBasis.init(mainBasis: size.height, crossBasis: size.width) } else { return AxisBasis.init(mainBasis: size.width, crossBasis: size.height) } } private func getAxisMarginsForItem(item:UIView) -> AxisMargins { let marginValue = objc_getAssociatedObject(item, &FlexboxAssociatedKeys.margin) let edges = marginValue == nil ? UIEdgeInsetsZero : marginValue.UIEdgeInsetsValue() if vertical { return AxisMargins.init(mainPrevious: edges.top, mainNext: edges.bottom, crossPrevious: edges.left, crossNext: edges.right) } else { return AxisMargins.init(mainPrevious: edges.left, mainNext: edges.right, crossPrevious: edges.top, crossNext: edges.bottom) } } private func getFlexGrowForItem(item:UIView) -> Int { let growValue = objc_getAssociatedObject(item, &FlexboxAssociatedKeys.flexGrow) return growValue == nil ? 0 : growValue.integerValue } private func getFlexShrinkForItem(item:UIView) -> Int { let shrinkValue = objc_getAssociatedObject(item, &FlexboxAssociatedKeys.flexShrink) return shrinkValue == nil ? 0 : shrinkValue.integerValue } private func getAlignSelfForItem(item:UIView) -> AlignItems { let alignValue = objc_getAssociatedObject(item, &FlexboxAssociatedKeys.alignSelf) return alignValue == nil ? AlignItems.Auto : AlignItems(rawValue: alignValue.integerValue)! } private func clearFlexConstraints(item:UIView) { let flexConstraints = item.constraints.filter { (constraint) -> Bool in return constraint.identifier == constraintIdentifier } if #available(iOS 8.0, *) { NSLayoutConstraint.deactivateConstraints(flexConstraints) } else { item.removeConstraints(flexConstraints) } } private func setConstantConstraint(item:UIView, attribute: NSLayoutAttribute, constant:CGFloat, _ relation:NSLayoutRelation = .Equal, _ priority:UILayoutPriority = UILayoutPriorityRequired) { let constraint = NSLayoutConstraint(item: item, attribute: attribute, relatedBy: relation, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: constant) constraint.priority = priority constraint.identifier = constraintIdentifier if #available(iOS 8.0, *) { constraint.active = true } else { item.addConstraint(constraint) } } private func setAlignConstraint(item view1: AnyObject, attribute attr1: NSLayoutAttribute, constant c: CGFloat = 0, relatedBy relation: NSLayoutRelation = .Equal, toItem view2: AnyObject, attribute attr2: NSLayoutAttribute, priority:UILayoutPriority = UILayoutPriorityRequired){ let constraint = NSLayoutConstraint(item: view1, attribute: attr1, relatedBy: relation, toItem: view2, attribute: attr2, multiplier: 1, constant:c) constraint.identifier = constraintIdentifier constraint.priority = priority if #available(iOS 8.0, *) { constraint.active = true } else { view1.addConstraint(constraint) } } private func setAlignConstraint(item view1: AnyObject, attribute attr1: NSLayoutAttribute, constant c: CGFloat = 0, relatedBy relation: NSLayoutRelation = .Equal){ setAlignConstraint(item: view1, attribute: attr1, constant: c, relatedBy: relation, toItem: self, attribute: attr1) } }
mit
f5e944439922583335c43f1acff690ec
43.358182
282
0.651597
4.881353
false
false
false
false
ZakariyyaSv/LYNetwork
LYNetwork/LYNetworkDemo/TestApi.swift
1
1793
// // TestApi.swift // LYNetwork // // Created by XuHaonan on 2017/7/9. // Copyright © 2017年 yangqianguan.com. All rights reserved. // import Foundation class loginApi: LYRequest { private var phone: String private var password: String public init(_ username: String, _ password: String) { self.phone = username self.password = password super.init() } public func userIdAndticket() -> (String, String) { guard let response = (self.responseJSON as? Dictionary<String, Any>) else { return ("", "") } return (response["userId"] as! String, response["ticket"] as! String) } override func requestUrl() -> String { return "login" } override func requestMethod() -> LYRequestMethod { return .POST } override func responseSerializerType() -> LYResponseSerializerType { return .JSON } override func requestArgument() -> [String : Any]? { return ["phone" : self.phone, "password" : self.password] } } class getUserInfoApi: LYRequest { private var userId: String private var ticket: String public init(_ userId: String, _ ticket: String) { self.userId = userId self.ticket = ticket super.init() } override func requestUrl() -> String { return "get_index_info" } override func requestArgument() -> [String : Any]? { return ["userId" : self.userId, "ticket" : self.ticket] } override func cacheTimeInSeconds() -> Int { return 60 * 3 } } class getImageApi: LYRequest { private var imageId: String public init(_ imageId: String) { self.imageId = imageId super.init() } override func requestUrl() -> String { return "/iphone/images/" + self.imageId } override func useCDN() -> Bool { return true } }
mit
e4dedbbd2831e0c18d07260d9c57a84b
19.340909
79
0.635754
3.942731
false
false
false
false
alblue/com.packtpub.swift.essentials
playing/MyPlayground.playground/Pages/Playground Code.xcplaygroundpage/Contents.swift
1
1169
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" for i in 1...12 { let j = (i-7) * (i-6) let k = i print("I is \(i)") } let blue = UIColor.blueColor() let size = CGRect(x:0,y:0,width:200,height:100) let label = UILabel(frame:size) label.text = str label.textColor = blue; label.font = UIFont.systemFontOfSize(24) let alblue = UIImage(named:"alblue") import XCPlayground let page = XCPlaygroundPage.currentPage page.captureValue(alblue, withIdentifier:"Al Blue") dispatch_async(dispatch_get_main_queue()) { for n in 1...6 { if n % 2 == 0 { page.captureValue(n,withIdentifier:"even") page.captureValue(0,withIdentifier:"odd") } else { page.captureValue(n,withIdentifier:"odd") page.captureValue(0,withIdentifier:"even") } } } page.needsIndefiniteExecution = true /** Returns the string in SHOUTY CAPS - parameter input: the input string - author: Alex Blewitt - returns: The input string, but in upper case - throws: No errors thrown - note: Please don't shout - seealso: String.uppercaseString - since: 2016 */ func shout(input:String) -> String { return input.uppercaseString } shout(str)
mit
ad5c0bbbc0640a8a0175c8d413c0ed6b
21.480769
52
0.710009
3.193989
false
false
false
false
MoralAlberto/SlackWebAPIKit
SlackWebAPIKit/Classes/Data/APIClient/Endpoints/PostMessageEndpoint.swift
1
742
public class PostMessageEndpoint: Endpoint { private struct Parameters { static let text = "text" static let channel = "channel" static let asUser = "as_user" } private let text: String private let channel: String private let asUser: Bool public var endpointType: EndpointType = .postMessage init(text: String, channel: String, asUser: Bool = true) { self.text = text self.channel = channel self.asUser = asUser } public var parameters: [String: String]? { get { return [Parameters.channel: "\(channel)", Parameters.text: "\(text)", Parameters.asUser: "\(asUser)"] } } }
mit
e8d0ea0354d263bdb6c1ca95fa73677f
27.538462
62
0.566038
4.608696
false
false
false
false
0x7fffffff/Stone
Sources/Channel.swift
2
7871
// // Channel.swift // Stone // // Created by Michael MacCallum on 5/16/16. // Copyright © 2016 Tethr Technologies Inc. All rights reserved. // import SwiftWebSocket import Unbox import Wrap struct TestType: Unboxable, Hashable { init(unboxer: Unboxer) { } var hashValue: Int { return 0 } } func ==(lhs: TestType, rhs: TestType) -> Bool { return true } /** Defines a Channel for communicating with a given topic on your Phoenix server. */ public final class Channel: Hashable, Equatable, CustomStringConvertible { public let topic: String public typealias ResultCallback = (_ result: Stone.Result<Stone.Message>) -> Void public typealias EventCallback = (_ message: Stone.Message) -> Void /// The state of the connection to this Channel. public internal(set) var state: Stone.ChannelState = .closed public var shouldTrackPresence = false fileprivate var eventBindings = [String: ResultCallback]() fileprivate var callbackBindings = [String: ResultCallback?]() internal weak var socket: Socket? /// Channels are unique by their topics. public var hashValue: Int { return topic.hashValue } public var description: String { return "Channel(topic: \(topic), tracks presence: \(shouldTrackPresence), state: \(state))" } /** Creates a new channel for the given topic. Topic can either be a String, or any enum you've defined whose RawValue == String for convenience. */ public convenience init<RawType: RawRepresentable>(topic: RawType) where RawType.RawValue == String { self.init(topic: topic.rawValue) } /** Creates a new channel for the given topic. Topic can either be a String, or any enum you've defined whose RawValue == String for convenience. */ public init(topic: String) { self.topic = topic } /** Returns true iff the receiver is a member of the given topic, false otherwise. This method does not take connection status into account. */ public func isMemberOfTopic(_ otherTopic: String) -> Bool { return topic == otherTopic } public func isMemberOfTopic<RawType: RawRepresentable>(_ otherTopic: RawType) -> Bool where RawType.RawValue == String { return isMemberOfTopic(otherTopic.rawValue) } internal func triggerEvent(_ event: Stone.Event, ref: String? = nil, payload: WrappedDictionary = [:]) { guard state != .closed else { return } let message = Stone.Message( topic: topic, event: event, payload: payload, ref: ref ) if event == .Reply { guard let ref = ref else { return } if let defaultEvent = Event.PhoenixEvent(rawValue: ref) { handleDefaultEvent(defaultEvent, message: message) } if let replyCallback = callbackBindings.removeValue(forKey: ref) { replyCallback?(.success(message)) } } else { if let eventBinding = eventBindings[event.rawValue] { eventBinding(.success(message)) } if let presenceEvent = Stone.Event.PhoenixEvent.PresenceEvent(rawValue: event.rawValue) , shouldTrackPresence { handlePresenceEvent(presenceEvent, withPayload: message.payload) } } } fileprivate func handleDefaultEvent(_ event: Event.PhoenixEvent, message: Message) { switch event { case .Join: onJoin?(message) case .Reply: onReply?(message) case .Leave: onLeave?(message) case .Close: onClose?(message) case .Error: onError?(message) default: break } } fileprivate func handlePresenceEvent(_ event: Stone.Event.PhoenixEvent.PresenceEvent, withPayload payload: WrappedDictionary) { switch event { case .State: presenceStateCallback?( Stone.Result.success( payload.map { Stone.PresenceChange( name: $0.0, metas: ($0.1 as? [String: AnyObject]) ?? [String: AnyObject]() ) } ) ) case .Diff: do { presenceDiffCallback?( .success( try unbox(dictionary: payload) ) ) } catch { presenceDiffCallback?(.failure(Stone.StoneError.invalidJSON)) } } } public var onJoin: EventCallback? public var onReply: EventCallback? public var onError: EventCallback? public var onLeave: EventCallback? public var onClose: EventCallback? fileprivate func triggerInternalEvent(_ event: Stone.Event.PhoenixEvent, withMessage message: Stone.Message) { switch message.topic { case topic: state = .joined onJoin?(message) default: onReply?(message) } } /** Registers a callback to occur when this Channel receives the given event. - returns: The last function given as a callback for this Event on this Channel if one exists, nil otherwise. */ @discardableResult public func onEvent(_ event: Stone.Event, callback: @escaping ResultCallback) -> ResultCallback? { return eventBindings.updateValue(callback, forKey: event.rawValue) } /** Unregisters a callback from occurring when this Channel receives the given event. - returns: The function that used to be the callback for this Event if one exists, nil otherwise. */ public func offEvent(_ event: Stone.Event) -> ResultCallback? { return eventBindings.removeValue(forKey: event.rawValue) } fileprivate var presenceDiffCallback: ((_ result: Stone.Result<Stone.PresenceDiff>) -> Void)? /** Registers a callback to be received whenever a presence diff update occurs. */ public func onPresenceDiff(_ callback: @escaping (_ result: Stone.Result<Stone.PresenceDiff>) -> Void) { presenceDiffCallback = callback } fileprivate var presenceStateCallback: ((_ result: Stone.Result<Array<Stone.PresenceChange>>) -> Void)? // public func test<T: protocol<Unboxable, Hashable>>(closure: (result: Stone.Presence<T>) -> Void) { //// testState = closure // let p = Presence<T>(name: "", metas: []) // closure(result: p) // } var presence: Stone.Presence? public func presences<T: Unboxable & Hashable>(_ closure: (_ presences: [String: Set<T>]) -> Void) { closure([:]) } /** Registers a callback to be received whenever a presence state update occurs. */ public func onPresenceState(_ callback: @escaping (_ result: Stone.Result<Array<Stone.PresenceChange>>) -> Void) { presenceStateCallback = callback } /** Sends the given Message over the receiving Channel. When the server replies, the contents of the reply will be given in the completion handler. */ public func sendMessage(_ message: Stone.Message, completion: ResultCallback? = nil) { guard let socket = socket else { completion?(.failure(Stone.StoneError.lostSocket)) return } do { try socket.push(message) callbackBindings.updateValue( completion, forKey: message.ref! ) } catch { completion?(.failure(Stone.StoneError.invalidJSON)) } } /** Sends a join message to the Channel's topic. */ public func join(_ completion: ResultCallback? = nil) { guard state == .closed || state == Stone.ChannelState.errored else { return } state = .joining let joinMessage = Stone.Message( topic: topic, event: Stone.Event.phoenix(.Join), payload: [:], ref: Stone.Event.phoenix(.Join).description ) callbackBindings[joinMessage.ref!] = completion sendMessage(joinMessage, completion: nil) } /** Leaves the receiving Channel. If you leave a Channel, you won't continue to get callbacks for the messages that it receives, even if the Channel object happens to still be alive. */ public func leave(_ completion: ((_ success: Bool) -> Void)? = nil) { let leaveMessage = Stone.Message( topic: topic, event: Stone.Event.phoenix(.Leave) ) sendMessage(leaveMessage) { [weak self] result in self?.state = .closed do { let message = try result.value() self?.triggerEvent( leaveMessage.event, ref: message.ref, payload: message.payload ) completion?(true) } catch { completion?(false) } } } } public func == (lhs: Stone.Channel, rhs: Stone.Channel) -> Bool { return lhs.hashValue == rhs.hashValue }
mit
88e91a2e15550a9577f3a6ada81424a5
25.059603
128
0.701906
3.648586
false
false
false
false
everald/JetPack
Sources/UI/TableViewController.swift
1
2580
import UIKit @objc(JetPack_TableViewController) open class TableViewController: ViewController { fileprivate let style: UITableView.Style public init(style: UITableView.Style) { self.style = style super.init() } public required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } open var automaticallyAdjustsTableViewInsets = true open var clearsSelectionOnViewWillAppear = true fileprivate func createTableView() -> TableView { let child = TableView(style: style) child.estimatedRowHeight = 44 child.dataSource = self child.delegate = self return child } open override func setEditing(_ editing: Bool, animated: Bool) { super.setEditing(editing, animated: animated) if isViewLoaded { tableView.setEditing(editing, animated: animated) } } open fileprivate(set) lazy var tableView: TableView = self.createTableView() open override func viewDidLayoutSubviewsWithAnimation(_ animation: Animation?) { super.viewDidLayoutSubviewsWithAnimation(animation) animation.runAlways { var tableViewFrame = CGRect(size: view.bounds.size) if automaticallyAdjustsTableViewInsets { var contentInsets = self.innerDecorationInsets var scrollIndicatorInsets = outerDecorationInsets tableViewFrame.left += contentInsets.left tableViewFrame.width -= tableViewFrame.left + contentInsets.right contentInsets.left = 0 contentInsets.right = 0 scrollIndicatorInsets.left = 0 scrollIndicatorInsets.right = 0 tableView.setContentInset(contentInsets, maintainingVisualContentOffset: true) tableView.scrollIndicatorInsets = scrollIndicatorInsets } tableView.isEditing = isEditing tableView.frame = tableViewFrame } } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if clearsSelectionOnViewWillAppear, let indexPaths = tableView.indexPathsForSelectedRows { for indexPath in indexPaths { tableView.deselectRow(at: indexPath, animated: animated) } } } open override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = tableView.backgroundColor view.addSubview(tableView) } } extension TableViewController: UITableViewDataSource { open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { fatalError("override tableView(_:cellForRowAt:) without calling super") } open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 0 } } extension TableViewController: UITableViewDelegate {}
mit
7b871057dcee3b9db30365fc94d6b4db
22.243243
102
0.763953
4.607143
false
false
false
false
swordfishyou/fieldstool
FieldTool/Sources/Parsers/WKTParser.swift
1
1278
// // WKTParser.swift // FieldTool // import CoreLocation protocol WKTParserType { func parse(_ input: String) -> WKTType? } struct WKTParser: WKTParserType { private let delimiter = "\t" func parse(_ input: String) -> WKTType? { if input.isEmpty { return nil } var coordinates = [CoordinatesCollection]() for component in input.geometryComponents(separatedBy: self.delimiter) { coordinates.append(self.coordinatesCollection(from: component)) } return WKTType(name: input.geometryName(), components: coordinates) } private func coordinatesCollection(from component: String) -> CoordinatesCollection { let scanner = Scanner(string: component) var lat: Double = 0 var lon: Double = 0 var coordinates = [CLLocationCoordinate2D]() while !scanner.isAtEnd { if scanner.scanDouble(&lon) && scanner.scanDouble(&lat) { coordinates.append(CLLocationCoordinate2D(latitude: lat, longitude: lon)) } scanner.scanString(self.delimiter, into: nil) } return CoordinatesContainer(coordinates: coordinates) } }
mit
b721c3251adacff57a5c30eefea91472
26.782609
89
0.600156
4.896552
false
false
false
false
apple/swift
test/SILGen/generic_literals.swift
22
4103
// RUN: %target-swift-emit-silgen %s | %FileCheck %s // CHECK-LABEL: sil hidden [ossa] @$s16generic_literals0A14IntegerLiteral1xyx_ts013ExpressibleBycD0RzlF : $@convention(thin) <T where T : ExpressibleByIntegerLiteral> (@in_guaranteed T) -> () { func genericIntegerLiteral<T : ExpressibleByIntegerLiteral>(x: T) { var x = x // CHECK: [[INTLIT:%.*]] = integer_literal $Builtin.IntLiteral, 17 // CHECK: [[LITMETA:%.*]] = metatype $@thick T.IntegerLiteralType.Type // CHECK: [[LITVAR:%.*]] = alloc_stack $T.IntegerLiteralType // CHECK: [[BUILTINCONV:%.*]] = witness_method $T.IntegerLiteralType, #_ExpressibleByBuiltinIntegerLiteral.init!allocator // CHECK: [[LIT:%.*]] = apply [[BUILTINCONV]]<T.IntegerLiteralType>([[LITVAR]], [[INTLIT]], [[LITMETA]]) : $@convention(witness_method: _ExpressibleByBuiltinIntegerLiteral) <τ_0_0 where τ_0_0 : _ExpressibleByBuiltinIntegerLiteral> (Builtin.IntLiteral, @thick τ_0_0.Type) -> @out τ_0_0 // CHECK: [[TMETA:%.*]] = metatype $@thick T.Type // CHECK: [[ADDR:%.*]] = alloc_stack $T // CHECK: [[TCONV:%.*]] = witness_method $T, #ExpressibleByIntegerLiteral.init!allocator // CHECK: apply [[TCONV]]<T>([[ADDR]], [[LITVAR]], [[TMETA]]) : $@convention(witness_method: ExpressibleByIntegerLiteral) <τ_0_0 where τ_0_0 : ExpressibleByIntegerLiteral> (@in τ_0_0.IntegerLiteralType, @thick τ_0_0.Type) -> @out τ_0_0 x = 17 } // CHECK-LABEL: sil hidden [ossa] @$s16generic_literals0A15FloatingLiteral1xyx_ts018ExpressibleByFloatD0RzlF : $@convention(thin) <T where T : ExpressibleByFloatLiteral> (@in_guaranteed T) -> () { func genericFloatingLiteral<T : ExpressibleByFloatLiteral>(x: T) { var x = x // CHECK: [[LIT_VALUE:%.*]] = float_literal $Builtin.FPIEEE{{64|80}}, {{0x4004000000000000|0x4000A000000000000000}} // CHECK: [[TFLT_META:%.*]] = metatype $@thick T.FloatLiteralType.Type // CHECK: [[FLT_VAL:%.*]] = alloc_stack $T.FloatLiteralType // CHECK: [[BUILTIN_CONV:%.*]] = witness_method $T.FloatLiteralType, #_ExpressibleByBuiltinFloatLiteral.init!allocator // CHECK: apply [[BUILTIN_CONV]]<T.FloatLiteralType>([[FLT_VAL]], [[LIT_VALUE]], [[TFLT_META]]) : $@convention(witness_method: _ExpressibleByBuiltinFloatLiteral) <τ_0_0 where τ_0_0 : _ExpressibleByBuiltinFloatLiteral> (Builtin.FPIEEE{{64|80}}, @thick τ_0_0.Type) -> @out τ_0_0 // CHECK: [[TMETA:%.*]] = metatype $@thick T.Type // CHECK: [[TVAL:%.*]] = alloc_stack $T // CHECK: [[CONV:%.*]] = witness_method $T, #ExpressibleByFloatLiteral.init!allocator // CHECK: apply [[CONV]]<T>([[TVAL]], [[FLT_VAL]], [[TMETA]]) : $@convention(witness_method: ExpressibleByFloatLiteral) <τ_0_0 where τ_0_0 : ExpressibleByFloatLiteral> (@in τ_0_0.FloatLiteralType, @thick τ_0_0.Type) -> @out τ_0_0 x = 2.5 } // CHECK-LABEL: sil hidden [ossa] @$s16generic_literals0A13StringLiteral1xyx_ts013ExpressibleBycD0RzlF : $@convention(thin) <T where T : ExpressibleByStringLiteral> (@in_guaranteed T) -> () { func genericStringLiteral<T : ExpressibleByStringLiteral>(x: T) { var x = x // CHECK: [[LIT_VALUE:%.*]] = string_literal utf8 "hello" // CHECK: [[TSTR_META:%.*]] = metatype $@thick T.StringLiteralType.Type // CHECK: [[STR_VAL:%.*]] = alloc_stack $T.StringLiteralType // CHECK: [[BUILTIN_CONV:%.*]] = witness_method $T.StringLiteralType, #_ExpressibleByBuiltinStringLiteral.init!allocator // CHECK: apply [[BUILTIN_CONV]]<T.StringLiteralType>([[STR_VAL]], [[LIT_VALUE]], {{.*}}, [[TSTR_META]]) : $@convention(witness_method: _ExpressibleByBuiltinStringLiteral) <τ_0_0 where τ_0_0 : _ExpressibleByBuiltinStringLiteral> (Builtin.RawPointer, Builtin.Word, Builtin.Int1, @thick τ_0_0.Type) -> @out τ_0_0 // CHECK: [[TMETA:%.*]] = metatype $@thick T.Type // CHECK: [[TVAL:%.*]] = alloc_stack $T // CHECK: [[CONV:%.*]] = witness_method $T, #ExpressibleByStringLiteral.init!allocator // CHECK: apply [[CONV]]<T>([[TVAL]], [[STR_VAL]], [[TMETA]]) : $@convention(witness_method: ExpressibleByStringLiteral) <τ_0_0 where τ_0_0 : ExpressibleByStringLiteral> (@in τ_0_0.StringLiteralType, @thick τ_0_0.Type) -> @out τ_0_0 x = "hello" }
apache-2.0
3f8070c3a55e4d89b52de74b3baced75
80.52
312
0.682532
3.581722
false
false
false
false
hgl888/firefox-ios
Storage/SQL/SQLiteHistory.swift
1
42121
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import XCGLogger private let log = Logger.syncLogger class NoSuchRecordError: MaybeErrorType { let guid: GUID init(guid: GUID) { self.guid = guid } var description: String { return "No such record: \(guid)." } } func failOrSucceed<T>(err: NSError?, op: String, val: T) -> Deferred<Maybe<T>> { if let err = err { log.debug("\(op) failed: \(err.localizedDescription)") return deferMaybe(DatabaseError(err: err)) } return deferMaybe(val) } func failOrSucceed(err: NSError?, op: String) -> Success { return failOrSucceed(err, op: op, val: ()) } private var ignoredSchemes = ["about"] public func isIgnoredURL(url: NSURL) -> Bool { let scheme = url.scheme if let _ = ignoredSchemes.indexOf(scheme) { return true } if url.host == "localhost" { return true } return false } public func isIgnoredURL(url: String) -> Bool { if let url = NSURL(string: url) { return isIgnoredURL(url) } return false } /* // Here's the Swift equivalent of the below. func simulatedFrecency(now: MicrosecondTimestamp, then: MicrosecondTimestamp, visitCount: Int) -> Double { let ageMicroseconds = (now - then) let ageDays = Double(ageMicroseconds) / 86400000000.0 // In SQL the .0 does the coercion. let f = 100 * 225 / ((ageSeconds * ageSeconds) + 225) return Double(visitCount) * max(1.0, f) } */ // The constants in these functions were arrived at by utterly unscientific experimentation. func getRemoteFrecencySQL() -> String { let visitCountExpression = "remoteVisitCount" let now = NSDate.nowMicroseconds() let microsecondsPerDay = 86_400_000_000.0 // 1000 * 1000 * 60 * 60 * 24 let ageDays = "((\(now) - remoteVisitDate) / \(microsecondsPerDay))" return "\(visitCountExpression) * max(1, 100 * 110 / (\(ageDays) * \(ageDays) + 110))" } func getLocalFrecencySQL() -> String { let visitCountExpression = "((2 + localVisitCount) * (2 + localVisitCount))" let now = NSDate.nowMicroseconds() let microsecondsPerDay = 86_400_000_000.0 // 1000 * 1000 * 60 * 60 * 24 let ageDays = "((\(now) - localVisitDate) / \(microsecondsPerDay))" return "\(visitCountExpression) * max(2, 100 * 225 / (\(ageDays) * \(ageDays) + 225))" } extension SDRow { func getTimestamp(column: String) -> Timestamp? { return (self[column] as? NSNumber)?.unsignedLongLongValue } func getBoolean(column: String) -> Bool { if let val = self[column] as? Int { return val != 0 } return false } } /** * The sqlite-backed implementation of the history protocol. */ public class SQLiteHistory { let db: BrowserDB let favicons: FaviconsTable<Favicon> let prefs: Prefs required public init?(db: BrowserDB, prefs: Prefs, version: Int? = nil) { self.db = db self.favicons = FaviconsTable<Favicon>() self.prefs = prefs // BrowserTable exists only to perform create/update etc. operations -- it's not // a queryable thing that needs to stick around. if !db.createOrUpdate(BrowserTable(version: version ?? BrowserTable.DefaultVersion)) { return nil } } } extension SQLiteHistory: BrowserHistory { public func removeSiteFromTopSites(site: Site) -> Success { if let host = site.url.asURL?.normalizedHost() { return db.run([("UPDATE \(TableDomains) set showOnTopSites = 0 WHERE domain = ?", [host])]) } return deferMaybe(DatabaseError(description: "Invalid url for site \(site.url)")) } public func removeHistoryForURL(url: String) -> Success { let visitArgs: Args = [url] let deleteVisits = "DELETE FROM \(TableVisits) WHERE siteID = (SELECT id FROM \(TableHistory) WHERE url = ?)" let markArgs: Args = [NSDate.nowNumber(), url] let markDeleted = "UPDATE \(TableHistory) SET url = NULL, is_deleted = 1, should_upload = 1, local_modified = ? WHERE url = ?" return db.run([(deleteVisits, visitArgs), (markDeleted, markArgs), favicons.getCleanupCommands()]) } // Note: clearing history isn't really a sane concept in the presence of Sync. // This method should be split to do something else. // Bug 1162778. public func clearHistory() -> Success { return self.db.run([ ("DELETE FROM \(TableVisits)", nil), ("DELETE FROM \(TableHistory)", nil), ("DELETE FROM \(TableDomains)", nil), self.favicons.getCleanupCommands(), ]) // We've probably deleted a lot of stuff. Vacuum now to recover the space. >>> effect(self.db.vacuum) } func recordVisitedSite(site: Site) -> Success { var error: NSError? = nil // Don't store visits to sites with about: protocols if isIgnoredURL(site.url) { return deferMaybe(IgnoredSiteError()) } db.withWritableConnection(&error) { (conn, inout err: NSError?) -> Int in let now = NSDate.nowNumber() let i = self.updateSite(site, atTime: now, withConnection: conn) if i > 0 { return i } // Insert instead. return self.insertSite(site, atTime: now, withConnection: conn) } return failOrSucceed(error, op: "Record site") } func updateSite(site: Site, atTime time: NSNumber, withConnection conn: SQLiteDBConnection) -> Int { // We know we're adding a new visit, so we'll need to upload this record. // If we ever switch to per-visit change flags, this should turn into a CASE statement like // CASE WHEN title IS ? THEN max(should_upload, 1) ELSE should_upload END // so that we don't flag this as changed unless the title changed. // // Note that we will never match against a deleted item, because deleted items have no URL, // so we don't need to unset is_deleted here. if let host = site.url.asURL?.normalizedHost() { let update = "UPDATE \(TableHistory) SET title = ?, local_modified = ?, should_upload = 1, domain_id = (SELECT id FROM \(TableDomains) where domain = ?) WHERE url = ?" let updateArgs: Args? = [site.title, time, host, site.url] if Logger.logPII { log.debug("Setting title to \(site.title) for URL \(site.url)") } let error = conn.executeChange(update, withArgs: updateArgs) if error != nil { log.warning("Update failed with \(error?.localizedDescription)") return 0 } return conn.numberOfRowsModified } return 0 } private func insertSite(site: Site, atTime time: NSNumber, withConnection conn: SQLiteDBConnection) -> Int { if let host = site.url.asURL?.normalizedHost() { if let error = conn.executeChange("INSERT OR IGNORE INTO \(TableDomains) (domain) VALUES (?)", withArgs: [host]) { log.warning("Domain insertion failed with \(error.localizedDescription)") return 0 } let insert = "INSERT INTO \(TableHistory) " + "(guid, url, title, local_modified, is_deleted, should_upload, domain_id) " + "SELECT ?, ?, ?, ?, 0, 1, id FROM \(TableDomains) WHERE domain = ?" let insertArgs: Args? = [site.guid ?? Bytes.generateGUID(), site.url, site.title, time, host] if let error = conn.executeChange(insert, withArgs: insertArgs) { log.warning("Site insertion failed with \(error.localizedDescription)") return 0 } return 1 } if Logger.logPII { log.warning("Invalid URL \(site.url). Not stored in history.") } return 0 } // TODO: thread siteID into this to avoid the need to do the lookup. func addLocalVisitForExistingSite(visit: SiteVisit) -> Success { var error: NSError? = nil db.withWritableConnection(&error) { (conn, inout err: NSError?) -> Int in // INSERT OR IGNORE because we *might* have a clock error that causes a timestamp // collision with an existing visit, and it would really suck to error out for that reason. let insert = "INSERT OR IGNORE INTO \(TableVisits) (siteID, date, type, is_local) VALUES (" + "(SELECT id FROM \(TableHistory) WHERE url = ?), ?, ?, 1)" let realDate = NSNumber(unsignedLongLong: visit.date) let insertArgs: Args? = [visit.site.url, realDate, visit.type.rawValue] error = conn.executeChange(insert, withArgs: insertArgs) if error != nil { log.warning("Visit insertion failed with \(err?.localizedDescription)") return 0 } return 1 } return failOrSucceed(error, op: "Record visit") } public func addLocalVisit(visit: SiteVisit) -> Success { return recordVisitedSite(visit.site) >>> { self.addLocalVisitForExistingSite(visit) } } public func getSitesByFrecencyWithLimit(limit: Int) -> Deferred<Maybe<Cursor<Site>>> { return self.getSitesByFrecencyWithLimit(limit, includeIcon: true) } public func getSitesByFrecencyWithLimit(limit: Int, includeIcon: Bool) -> Deferred<Maybe<Cursor<Site>>> { // Exclude redirect domains. Bug 1194852. let (whereData, groupBy) = self.topSiteClauses() return self.getFilteredSitesByFrecencyWithLimit(limit, groupClause: groupBy, whereData: whereData, includeIcon: includeIcon) } public func getTopSitesWithLimit(limit: Int) -> Deferred<Maybe<Cursor<Site>>> { let topSitesQuery = "SELECT * FROM \(TableCachedTopSites) ORDER BY frecencies DESC LIMIT (?)" let factory = SQLiteHistory.iconHistoryColumnFactory return self.db.runQuery(topSitesQuery, args: [limit], factory: factory) } public func setTopSitesNeedsInvalidation() { prefs.setBool(false, forKey: PrefsKeys.KeyTopSitesCacheIsValid) } public func updateTopSitesCacheIfInvalidated() -> Deferred<Maybe<Bool>> { if prefs.boolForKey(PrefsKeys.KeyTopSitesCacheIsValid) ?? false { return deferMaybe(false) } return refreshTopSitesCache() >>> always(true) } public func setTopSitesCacheSize(size: Int32) { let oldValue = prefs.intForKey(PrefsKeys.KeyTopSitesCacheSize) ?? 0 if oldValue != size { prefs.setInt(size, forKey: PrefsKeys.KeyTopSitesCacheSize) setTopSitesNeedsInvalidation() } } public func refreshTopSitesCache() -> Success { let cacheSize = Int(prefs.intForKey(PrefsKeys.KeyTopSitesCacheSize) ?? 0) return self.clearTopSitesCache() >>> { self.updateTopSitesCacheWithLimit(cacheSize) } } private func updateTopSitesCacheWithLimit(limit : Int) -> Success { let (whereData, groupBy) = self.topSiteClauses() let (query, args) = self.filteredSitesByFrecencyQueryWithLimit(limit, groupClause: groupBy, whereData: whereData) let insertQuery = "INSERT INTO \(TableCachedTopSites) \(query)" return self.clearTopSitesCache() >>> { self.db.run(insertQuery, withArgs: args) >>> { self.prefs.setBool(true, forKey: PrefsKeys.KeyTopSitesCacheIsValid) return succeed() } } } public func clearTopSitesCache() -> Success { let deleteQuery = "DELETE FROM \(TableCachedTopSites)" return self.db.run(deleteQuery, withArgs: nil) >>> { self.prefs.removeObjectForKey(PrefsKeys.KeyTopSitesCacheIsValid) return succeed() } } public func getSitesByFrecencyWithLimit(limit: Int, whereURLContains filter: String) -> Deferred<Maybe<Cursor<Site>>> { return self.getFilteredSitesByFrecencyWithLimit(limit, whereURLContains: filter) } public func getSitesByLastVisit(limit: Int) -> Deferred<Maybe<Cursor<Site>>> { return self.getFilteredSitesByVisitDateWithLimit(limit, whereURLContains: nil, includeIcon: true) } private class func basicHistoryColumnFactory(row: SDRow) -> Site { let id = row["historyID"] as! Int let url = row["url"] as! String let title = row["title"] as! String let guid = row["guid"] as! String let site = Site(url: url, title: title) site.guid = guid site.id = id // Find the most recent visit, regardless of which column it might be in. let local = row.getTimestamp("localVisitDate") ?? 0 let remote = row.getTimestamp("remoteVisitDate") ?? 0 let either = row.getTimestamp("visitDate") ?? 0 let latest = max(local, remote, either) if latest > 0 { site.latestVisit = Visit(date: latest, type: VisitType.Unknown) } return site } private class func iconColumnFactory(row: SDRow) -> Favicon? { if let iconType = row["iconType"] as? Int, let iconURL = row["iconURL"] as? String, let iconDate = row["iconDate"] as? Double, let _ = row["iconID"] as? Int { let date = NSDate(timeIntervalSince1970: iconDate) return Favicon(url: iconURL, date: date, type: IconType(rawValue: iconType)!) } return nil } private class func iconHistoryColumnFactory(row: SDRow) -> Site { let site = basicHistoryColumnFactory(row) site.icon = iconColumnFactory(row) return site } private func topSiteClauses() -> (String, String) { let whereData = "(\(TableDomains).showOnTopSites IS 1) AND (\(TableDomains).domain NOT LIKE 'r.%') " let groupBy = "GROUP BY domain_id " return (whereData, groupBy) } private func getFilteredSitesByVisitDateWithLimit(limit: Int, whereURLContains filter: String? = nil, includeIcon: Bool = true) -> Deferred<Maybe<Cursor<Site>>> { let args: Args? let whereClause: String if let filter = filter { args = ["%\(filter)%", "%\(filter)%"] // No deleted item has a URL, so there is no need to explicitly add that here. whereClause = "WHERE ((\(TableHistory).url LIKE ?) OR (\(TableHistory).title LIKE ?)) " + "AND (\(TableHistory).is_deleted = 0)" } else { args = [] whereClause = "WHERE (\(TableHistory).is_deleted = 0)" } let ungroupedSQL = "SELECT \(TableHistory).id AS historyID, \(TableHistory).url AS url, title, guid, domain_id, domain, " + "COALESCE(max(case \(TableVisits).is_local when 1 then \(TableVisits).date else 0 end), 0) AS localVisitDate, " + "COALESCE(max(case \(TableVisits).is_local when 0 then \(TableVisits).date else 0 end), 0) AS remoteVisitDate, " + "COALESCE(count(\(TableVisits).is_local), 0) AS visitCount " + "FROM \(TableHistory) " + "INNER JOIN \(TableDomains) ON \(TableDomains).id = \(TableHistory).domain_id " + "INNER JOIN \(TableVisits) ON \(TableVisits).siteID = \(TableHistory).id " + whereClause + " GROUP BY historyID" let historySQL = "SELECT historyID, url, title, guid, domain_id, domain, visitCount, " + "max(localVisitDate) AS localVisitDate, " + "max(remoteVisitDate) AS remoteVisitDate " + "FROM (" + ungroupedSQL + ") " + "WHERE (visitCount > 0) " + // Eliminate dead rows from coalescing. "GROUP BY historyID " + "ORDER BY max(localVisitDate, remoteVisitDate) DESC " + "LIMIT \(limit) " if includeIcon { // We select the history items then immediately join to get the largest icon. // We do this so that we limit and filter *before* joining against icons. let sql = "SELECT " + "historyID, url, title, guid, domain_id, domain, " + "localVisitDate, remoteVisitDate, visitCount, " + "iconID, iconURL, iconDate, iconType, iconWidth " + "FROM (\(historySQL)) LEFT OUTER JOIN " + "view_history_id_favicon ON historyID = view_history_id_favicon.id" let factory = SQLiteHistory.iconHistoryColumnFactory return db.runQuery(sql, args: args, factory: factory) } let factory = SQLiteHistory.basicHistoryColumnFactory return db.runQuery(historySQL, args: args, factory: factory) } private func getFilteredSitesByFrecencyWithLimit(limit: Int, whereURLContains filter: String? = nil, groupClause: String = "GROUP BY historyID ", whereData: String? = nil, includeIcon: Bool = true) -> Deferred<Maybe<Cursor<Site>>> { let factory: (SDRow) -> Site if includeIcon { factory = SQLiteHistory.iconHistoryColumnFactory } else { factory = SQLiteHistory.basicHistoryColumnFactory } let (query, args) = filteredSitesByFrecencyQueryWithLimit(limit, whereURLContains: filter, groupClause: groupClause, whereData: whereData, includeIcon: includeIcon ) return db.runQuery(query, args: args, factory: factory) } private func filteredSitesByFrecencyQueryWithLimit(limit: Int, whereURLContains filter: String? = nil, groupClause: String = "GROUP BY historyID ", whereData: String? = nil, includeIcon: Bool = true) -> (String, Args?) { let localFrecencySQL = getLocalFrecencySQL() let remoteFrecencySQL = getRemoteFrecencySQL() let sixMonthsInMicroseconds: UInt64 = 15_724_800_000_000 // 182 * 1000 * 1000 * 60 * 60 * 24 let sixMonthsAgo = NSDate.nowMicroseconds() - sixMonthsInMicroseconds let args: Args? let whereClause: String let whereFragment = (whereData == nil) ? "" : " AND (\(whereData!))" if let filter = filter { args = ["%\(filter)%", "%\(filter)%"] // No deleted item has a URL, so there is no need to explicitly add that here. whereClause = " WHERE ((\(TableHistory).url LIKE ?) OR (\(TableHistory).title LIKE ?)) \(whereFragment)" } else { args = [] whereClause = " WHERE (\(TableHistory).is_deleted = 0) \(whereFragment)" } // Innermost: grab history items and basic visit/domain metadata. let ungroupedSQL = "SELECT \(TableHistory).id AS historyID, \(TableHistory).url AS url, title, guid, domain_id, domain" + ", COALESCE(max(case \(TableVisits).is_local when 1 then \(TableVisits).date else 0 end), 0) AS localVisitDate" + ", COALESCE(max(case \(TableVisits).is_local when 0 then \(TableVisits).date else 0 end), 0) AS remoteVisitDate" + ", COALESCE(sum(\(TableVisits).is_local), 0) AS localVisitCount" + ", COALESCE(sum(case \(TableVisits).is_local when 1 then 0 else 1 end), 0) AS remoteVisitCount" + " FROM \(TableHistory) " + "INNER JOIN \(TableDomains) ON \(TableDomains).id = \(TableHistory).domain_id " + "INNER JOIN \(TableVisits) ON \(TableVisits).siteID = \(TableHistory).id " + whereClause + " GROUP BY historyID" // Next: limit to only those that have been visited at all within the last six months. // (Don't do that in the innermost: we want to get the full count, even if some visits are older.) // Discard all but the 1000 most frecent. // Compute and return the frecency for all 1000 URLs. let frecenciedSQL = "SELECT *, (\(localFrecencySQL) + \(remoteFrecencySQL)) AS frecency" + " FROM (" + ungroupedSQL + ")" + " WHERE (" + "((localVisitCount > 0) OR (remoteVisitCount > 0)) AND " + // Eliminate dead rows from coalescing. "((localVisitDate > \(sixMonthsAgo)) OR (remoteVisitDate > \(sixMonthsAgo)))" + // Exclude really old items. ") ORDER BY frecency DESC" + " LIMIT 1000" // Don't even look at a huge set. This avoids work. // Next: merge by domain and sum frecency, ordering by that sum and reducing to a (typically much lower) limit. let historySQL = "SELECT historyID, url, title, guid, domain_id, domain" + ", max(localVisitDate) AS localVisitDate" + ", max(remoteVisitDate) AS remoteVisitDate" + ", sum(localVisitCount) AS localVisitCount" + ", sum(remoteVisitCount) AS remoteVisitCount" + ", sum(frecency) AS frecencies" + " FROM (" + frecenciedSQL + ") " + groupClause + " " + "ORDER BY frecencies DESC " + "LIMIT \(limit) " // Finally: join this small list to the favicon data. if includeIcon { // We select the history items then immediately join to get the largest icon. // We do this so that we limit and filter *before* joining against icons. let sql = "SELECT" + " historyID, url, title, guid, domain_id, domain" + ", localVisitDate, remoteVisitDate, localVisitCount, remoteVisitCount" + ", iconID, iconURL, iconDate, iconType, iconWidth, frecencies" + " FROM (\(historySQL)) LEFT OUTER JOIN " + "view_history_id_favicon ON historyID = view_history_id_favicon.id" return (sql, args) } return (historySQL, args) } } extension SQLiteHistory: Favicons { // These two getter functions are only exposed for testing purposes (and aren't part of the public interface). func getFaviconsForURL(url: String) -> Deferred<Maybe<Cursor<Favicon?>>> { let sql = "SELECT iconID AS id, iconURL AS url, iconDate AS date, iconType AS type, iconWidth AS width FROM " + "\(ViewWidestFaviconsForSites), \(TableHistory) WHERE " + "\(TableHistory).id = siteID AND \(TableHistory).url = ?" let args: Args = [url] return db.runQuery(sql, args: args, factory: SQLiteHistory.iconColumnFactory) } func getFaviconsForBookmarkedURL(url: String) -> Deferred<Maybe<Cursor<Favicon?>>> { let sql = "SELECT \(TableFavicons).id AS id, \(TableFavicons).url AS url, \(TableFavicons).date AS date, \(TableFavicons).type AS type, \(TableFavicons).width AS width FROM \(TableFavicons), \(TableBookmarks) WHERE \(TableBookmarks).faviconID = \(TableFavicons).id AND \(TableBookmarks).url IS ?" let args: Args = [url] return db.runQuery(sql, args: args, factory: SQLiteHistory.iconColumnFactory) } public func clearAllFavicons() -> Success { var err: NSError? = nil db.withWritableConnection(&err) { (conn, inout err: NSError?) -> Int in err = conn.executeChange("DELETE FROM \(TableFaviconSites)", withArgs: nil) if err == nil { err = conn.executeChange("DELETE FROM \(TableFavicons)", withArgs: nil) } return 1 } return failOrSucceed(err, op: "Clear favicons") } public func addFavicon(icon: Favicon) -> Deferred<Maybe<Int>> { var err: NSError? let res = db.withWritableConnection(&err) { (conn, inout err: NSError?) -> Int in // Blind! We don't see failure here. let id = self.favicons.insertOrUpdate(conn, obj: icon) return id ?? 0 } if err == nil { return deferMaybe(res) } return deferMaybe(DatabaseError(err: err)) } /** * This method assumes that the site has already been recorded * in the history table. */ public func addFavicon(icon: Favicon, forSite site: Site) -> Deferred<Maybe<Int>> { if Logger.logPII { log.verbose("Adding favicon \(icon.url) for site \(site.url).") } func doChange(query: String, args: Args?) -> Deferred<Maybe<Int>> { var err: NSError? let res = db.withWritableConnection(&err) { (conn, inout err: NSError?) -> Int in // Blind! We don't see failure here. let id = self.favicons.insertOrUpdate(conn, obj: icon) // Now set up the mapping. err = conn.executeChange(query, withArgs: args) if let err = err { log.error("Got error adding icon: \(err).") return 0 } // Try to update the favicon ID column in the bookmarks table as well for this favicon // if this site has been bookmarked if let id = id { conn.executeChange("UPDATE \(TableBookmarks) SET faviconID = ? WHERE url = ?", withArgs: [id, site.url]) } return id ?? 0 } if res == 0 { return deferMaybe(DatabaseError(err: err)) } return deferMaybe(icon.id!) } let siteSubselect = "(SELECT id FROM \(TableHistory) WHERE url = ?)" let iconSubselect = "(SELECT id FROM \(TableFavicons) WHERE url = ?)" let insertOrIgnore = "INSERT OR IGNORE INTO \(TableFaviconSites)(siteID, faviconID) VALUES " if let iconID = icon.id { // Easy! if let siteID = site.id { // So easy! let args: Args? = [siteID, iconID] return doChange("\(insertOrIgnore) (?, ?)", args: args) } // Nearly easy. let args: Args? = [site.url, iconID] return doChange("\(insertOrIgnore) (\(siteSubselect), ?)", args: args) } // Sigh. if let siteID = site.id { let args: Args? = [siteID, icon.url] return doChange("\(insertOrIgnore) (?, \(iconSubselect))", args: args) } // The worst. let args: Args? = [site.url, icon.url] return doChange("\(insertOrIgnore) (\(siteSubselect), \(iconSubselect))", args: args) } } extension SQLiteHistory: SyncableHistory { /** * TODO: * When we replace an existing row, we want to create a deleted row with the old * GUID and switch the new one in -- if the old record has escaped to a Sync server, * we want to delete it so that we don't have two records with the same URL on the server. * We will know if it's been uploaded because it'll have a server_modified time. */ public func ensurePlaceWithURL(url: String, hasGUID guid: GUID) -> Success { let args: Args = [guid, url, guid] // The additional IS NOT is to ensure that we don't do a write for no reason. return db.run("UPDATE \(TableHistory) SET guid = ? WHERE url = ? AND guid IS NOT ?", withArgs: args) } public func deleteByGUID(guid: GUID, deletedAt: Timestamp) -> Success { let args: Args = [guid] // This relies on ON DELETE CASCADE to remove visits. return db.run("DELETE FROM \(TableHistory) WHERE guid = ?", withArgs: args) } // Fails on non-existence. private func getSiteIDForGUID(guid: GUID) -> Deferred<Maybe<Int>> { let args: Args = [guid] let query = "SELECT id FROM history WHERE guid = ?" let factory: SDRow -> Int = { return $0["id"] as! Int } return db.runQuery(query, args: args, factory: factory) >>== { cursor in if cursor.count == 0 { return deferMaybe(NoSuchRecordError(guid: guid)) } return deferMaybe(cursor[0]!) } } public func storeRemoteVisits(visits: [Visit], forGUID guid: GUID) -> Success { return self.getSiteIDForGUID(guid) >>== { (siteID: Int) -> Success in let visitArgs = visits.map { (visit: Visit) -> Args in let realDate = NSNumber(unsignedLongLong: visit.date) let isLocal = 0 let args: Args = [siteID, realDate, visit.type.rawValue, isLocal] return args } // Magic happens here. The INSERT OR IGNORE relies on the multi-column uniqueness // constraint on `visits`: we allow only one row for (siteID, date, type), so if a // local visit already exists, this silently keeps it. End result? Any new remote // visits are added with only one query, keeping any existing rows. return self.db.bulkInsert(TableVisits, op: .InsertOrIgnore, columns: ["siteID", "date", "type", "is_local"], values: visitArgs) } } private struct HistoryMetadata { let id: Int let serverModified: Timestamp? let localModified: Timestamp? let isDeleted: Bool let shouldUpload: Bool let title: String } private func metadataForGUID(guid: GUID) -> Deferred<Maybe<HistoryMetadata?>> { let select = "SELECT id, server_modified, local_modified, is_deleted, should_upload, title FROM \(TableHistory) WHERE guid = ?" let args: Args = [guid] let factory = { (row: SDRow) -> HistoryMetadata in return HistoryMetadata( id: row["id"] as! Int, serverModified: row.getTimestamp("server_modified"), localModified: row.getTimestamp("local_modified"), isDeleted: row.getBoolean("is_deleted"), shouldUpload: row.getBoolean("should_upload"), title: row["title"] as! String ) } return db.runQuery(select, args: args, factory: factory) >>== { cursor in return deferMaybe(cursor[0]) } } public func insertOrUpdatePlace(place: Place, modified: Timestamp) -> Deferred<Maybe<GUID>> { // One of these things will be true here. // 0. The item is new. // (a) We have a local place with the same URL but a different GUID. // (b) We have never visited this place locally. // In either case, reconcile and proceed. // 1. The remote place is not modified when compared to our mirror of it. This // can occur when we redownload after a partial failure. // (a) And it's not modified locally, either. Nothing to do. Ideally we // will short-circuit so we don't need to update visits. (TODO) // (b) It's modified locally. Don't overwrite anything; let the upload happen. // 2. The remote place is modified (either title or visits). // (a) And it's not locally modified. Update the local entry. // (b) And it's locally modified. Preserve the title of whichever was modified last. // N.B., this is the only instance where we compare two timestamps to see // which one wins. // We use this throughout. let serverModified = NSNumber(unsignedLongLong: modified) // Check to see if our modified time is unchanged, if the record exists locally, etc. let insertWithMetadata = { (metadata: HistoryMetadata?) -> Deferred<Maybe<GUID>> in if let metadata = metadata { // The item exists locally (perhaps originally with a different GUID). if metadata.serverModified == modified { log.verbose("History item \(place.guid) is unchanged; skipping insert-or-update.") return deferMaybe(place.guid) } // Otherwise, the server record must have changed since we last saw it. if metadata.shouldUpload { // Uh oh, it changed locally. // This might well just be a visit change, but we can't tell. Usually this conflict is harmless. log.debug("Warning: history item \(place.guid) changed both locally and remotely. Comparing timestamps from different clocks!") if metadata.localModified > modified { log.debug("Local changes overriding remote.") // Update server modified time only. (Though it'll be overwritten again after a successful upload.) let update = "UPDATE \(TableHistory) SET server_modified = ? WHERE id = ?" let args: Args = [serverModified, metadata.id] return self.db.run(update, withArgs: args) >>> always(place.guid) } log.verbose("Remote changes overriding local.") // Fall through. } // The record didn't change locally. Update it. log.verbose("Updating local history item for guid \(place.guid).") let update = "UPDATE \(TableHistory) SET title = ?, server_modified = ?, is_deleted = 0 WHERE id = ?" let args: Args = [place.title, serverModified, metadata.id] return self.db.run(update, withArgs: args) >>> always(place.guid) } // The record doesn't exist locally. Insert it. log.verbose("Inserting remote history item for guid \(place.guid).") if let host = place.url.asURL?.normalizedHost() { if Logger.logPII { log.debug("Inserting: \(place.url).") } let insertDomain = "INSERT OR IGNORE INTO \(TableDomains) (domain) VALUES (?)" let insertHistory = "INSERT INTO \(TableHistory) (guid, url, title, server_modified, is_deleted, should_upload, domain_id) " + "SELECT ?, ?, ?, ?, 0, 0, id FROM \(TableDomains) where domain = ?" return self.db.run([ (insertDomain, [host]), (insertHistory, [place.guid, place.url, place.title, serverModified, host]) ]) >>> always(place.guid) } else { // This is a URL with no domain. Insert it directly. if Logger.logPII { log.debug("Inserting: \(place.url) with no domain.") } let insertHistory = "INSERT INTO \(TableHistory) (guid, url, title, server_modified, is_deleted, should_upload, domain_id) " + "VALUES (?, ?, ?, ?, 0, 0, NULL)" return self.db.run([ (insertHistory, [place.guid, place.url, place.title, serverModified]) ]) >>> always(place.guid) } } // Make sure that we only need to compare GUIDs by pre-merging on URL. return self.ensurePlaceWithURL(place.url, hasGUID: place.guid) >>> { self.metadataForGUID(place.guid) >>== insertWithMetadata } } public func getDeletedHistoryToUpload() -> Deferred<Maybe<[GUID]>> { // Use the partial index on should_upload to make this nice and quick. let sql = "SELECT guid FROM \(TableHistory) WHERE \(TableHistory).should_upload = 1 AND \(TableHistory).is_deleted = 1" let f: SDRow -> String = { $0["guid"] as! String } return self.db.runQuery(sql, args: nil, factory: f) >>== { deferMaybe($0.asArray()) } } public func getModifiedHistoryToUpload() -> Deferred<Maybe<[(Place, [Visit])]>> { // What we want to do: find all items flagged for update, selecting some number of their // visits alongside. // // A difficulty here: we don't want to fetch *all* visits, only some number of the most recent. // (It's not enough to only get new ones, because the server record should contain more.) // // That's the greatest-N-per-group problem in SQL. Please read and understand the solution // to this (particularly how the LEFT OUTER JOIN/HAVING clause works) before changing this query! // // We can do this in a single query, rather than the N+1 that desktop takes. // We then need to flatten the cursor. We do that by collecting // places as a side-effect of the factory, producing visits as a result, and merging in memory. let args: Args = [ 20, // Maximum number of visits to retrieve. ] // Exclude 'unknown' visits, because they're not syncable. let filter = "history.should_upload = 1 AND v1.type IS NOT 0" let sql = "SELECT " + "history.id AS siteID, history.guid AS guid, history.url AS url, history.title AS title, " + "v1.siteID AS siteID, v1.date AS visitDate, v1.type AS visitType " + "FROM " + "visits AS v1 " + "JOIN history ON history.id = v1.siteID AND \(filter) " + "LEFT OUTER JOIN " + "visits AS v2 " + "ON v1.siteID = v2.siteID AND v1.date < v2.date " + "GROUP BY v1.date " + "HAVING COUNT(*) < ? " + "ORDER BY v1.siteID, v1.date DESC" var places = [Int: Place]() var visits = [Int: [Visit]]() // Add a place to the accumulator, prepare to accumulate visits, return the ID. let ensurePlace: SDRow -> Int = { row in let id = row["siteID"] as! Int if places[id] == nil { let guid = row["guid"] as! String let url = row["url"] as! String let title = row["title"] as! String places[id] = Place(guid: guid, url: url, title: title) visits[id] = Array() } return id } // Store the place and the visit. let factory: SDRow -> Int = { row in let date = row.getTimestamp("visitDate")! let type = VisitType(rawValue: row["visitType"] as! Int)! let visit = Visit(date: date, type: type) let id = ensurePlace(row) visits[id]?.append(visit) return id } return db.runQuery(sql, args: args, factory: factory) >>== { c in // Consume every row, with the side effect of populating the places // and visit accumulators. var ids = Set<Int>() for row in c { // Collect every ID first, so that we're guaranteed to have // fully populated the visit lists, and we don't have to // worry about only collecting each place once. ids.insert(row!) } // Now we're done with the cursor. Close it. c.close() // Now collect the return value. return deferMaybe(ids.map { return (places[$0]!, visits[$0]!) } ) } } public func markAsDeleted(guids: [GUID]) -> Success { // TODO: support longer GUID lists. assert(guids.count < BrowserDB.MaxVariableNumber) if guids.isEmpty { return succeed() } log.debug("Wiping \(guids.count) deleted GUIDs.") // We deliberately don't limit this to records marked as should_upload, just // in case a coding error leaves records with is_deleted=1 but not flagged for // upload -- this will catch those and throw them away. let inClause = BrowserDB.varlist(guids.count) let sql = "DELETE FROM \(TableHistory) WHERE " + "is_deleted = 1 AND guid IN \(inClause)" let args: Args = guids.map { $0 as AnyObject } return self.db.run(sql, withArgs: args) } public func markAsSynchronized(guids: [GUID], modified: Timestamp) -> Deferred<Maybe<Timestamp>> { // TODO: support longer GUID lists. assert(guids.count < 99) if guids.isEmpty { return deferMaybe(modified) } log.debug("Marking \(guids.count) GUIDs as synchronized. Returning timestamp \(modified).") let inClause = BrowserDB.varlist(guids.count) let sql = "UPDATE \(TableHistory) SET " + "should_upload = 0, server_modified = \(modified) " + "WHERE guid IN \(inClause)" let args: Args = guids.map { $0 as AnyObject } return self.db.run(sql, withArgs: args) >>> always(modified) } public func doneApplyingRecordsAfterDownload() -> Success { self.db.checkpoint() return succeed() } public func doneUpdatingMetadataAfterUpload() -> Success { self.db.checkpoint() return succeed() } } extension SQLiteHistory: ResettableSyncStorage { // We don't drop deletions when we reset -- we might need to upload a deleted item // that never made it to the server. public func resetClient() -> Success { let flag = "UPDATE \(TableHistory) SET should_upload = 1, server_modified = NULL" return self.db.run(flag) } } extension SQLiteHistory: AccountRemovalDelegate { public func onRemovedAccount() -> Success { log.info("Clearing history metadata and deleted items after account removal.") let discard = "DELETE FROM \(TableHistory) WHERE is_deleted = 1" return self.db.run(discard) >>> self.resetClient } }
mpl-2.0
715257203072559a0e4f19e62de4ae2d
42.967641
304
0.587118
4.702579
false
false
false
false
CD1212/Doughnut
Doughnut/AppDelegate.swift
1
3653
/* * Doughnut Podcast Client * Copyright (C) 2017 Chris Dyer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import Cocoa import MASPreferences @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { var mediaKeyTap: SPMediaKeyTap? lazy var preferencesWindowController: NSWindowController = { return MASPreferencesWindowController(viewControllers: [ PrefGeneralViewController.instantiate(), PrefPlaybackViewController.instantiate(), PrefLibraryViewController.instantiate() ], title: NSLocalizedString("preference.title", comment: "Preference")) }() override init() { UserDefaults.standard.register( defaults: [kMediaKeyUsingBundleIdentifiersDefaultsKey : SPMediaKeyTap.defaultMediaKeyUserBundleIdentifiers()]) } func applicationDidFinishLaunching(_ aNotification: Notification) { UserDefaults.standard.register(defaults: Preference.defaultPreference) mediaKeyTap = SPMediaKeyTap(delegate: self) UserDefaults.standard.addObserver(self, forKeyPath: Preference.Key.enableMediaKeys.rawValue, options: [], context: nil) if Preference.bool(for: Preference.Key.enableMediaKeys) { setupMediaKeyTap() } /*do { try Player.audioOutputDevices() } catch {}*/ let connected = Library.global.connect() if !connected { abort() } } func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool { if !flag { for window in sender.windows { window.makeKeyAndOrderFront(self) } } return true } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { switch keyPath { case Preference.Key.enableMediaKeys.rawValue?: setupMediaKeyTap() default: return } } func setupMediaKeyTap() { guard let mediaKeyTap = mediaKeyTap else { return } if Preference.bool(for: Preference.Key.enableMediaKeys) { if SPMediaKeyTap.usesGlobalMediaKeyTap() { mediaKeyTap.startWatchingMediaKeys() } } else { mediaKeyTap.stopWatchingMediaKeys() } } override func mediaKeyTap(_ keyTap: SPMediaKeyTap!, receivedMediaKeyEvent event: NSEvent!) { let keyCode = Int((event.data1 & 0xFFFF0000) >> 16); let keyFlags = (event.data1 & 0x0000FFFF); let keyIsPressed = (((keyFlags & 0xFF00) >> 8)) == 0xA; if (keyIsPressed) { switch keyCode { case Int(NX_KEYTYPE_PLAY): Player.global.togglePlay() case Int(NX_KEYTYPE_FAST): Player.global.skipAhead() case Int(NX_KEYTYPE_REWIND): Player.global.skipBack() default: break } } } @IBAction func showPreferences(_ sender: AnyObject) { preferencesWindowController.showWindow(self) } }
gpl-3.0
b2dad651d15c2db1177382d0d28f69b2
29.190083
149
0.692308
4.46577
false
false
false
false
anasmeister/nRF-Coventry-University
nRF Toolbox/UART/NORUARTViewController.swift
1
12502
// // NORUARTViewController.swift // nRF Toolbox // // Created by Mostafa Berg on 11/05/16. // Copyright © 2016 Nordic Semiconductor. All rights reserved. // import UIKit import CoreBluetooth class NORUARTViewController: UIViewController, NORBluetoothManagerDelegate, NORScannerDelegate, UIPopoverPresentationControllerDelegate, ButtonConfigureDelegate { //MARK: - View Properties var bluetoothManager : NORBluetoothManager? var uartPeripheralName : String? var buttonsCommands : NSMutableArray? var buttonsHiddenStatus : NSMutableArray? var buttonsImageNames : NSMutableArray? var buttonIcons : NSArray? var selectedButton : UIButton? var logger : NORLogViewController? var editMode : Bool? //MARK: - View Actions @IBAction func connectionButtonTapped(_ sender: AnyObject) { bluetoothManager?.cancelPeripheralConnection() } @IBAction func editButtonTapped(_ sender: AnyObject) { let currentEditMode = editMode! setEditMode(mode: !currentEditMode) } @IBAction func showLogButtonTapped(_ sender: AnyObject) { self.revealViewController().revealToggle(animated: true) } @IBAction func buttonTapped(_ sender: AnyObject){ if editMode == true { self.selectedButton = sender as? UIButton; self.showPopoverOnButton() } else { let command = buttonsCommands![sender.tag-1] self.send(value: String(describing: command)) } } //MARK: - View OUtlets @IBOutlet weak var verticalLabel: UILabel! @IBOutlet weak var editButton: UIButton! @IBOutlet weak var deviceName: UILabel! @IBOutlet var buttons: [UIButton]! @IBOutlet weak var connectionButton: UIButton! //MARK: - UIViewControllerDelegate required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) buttonIcons = ["Stop","Play","Pause","FastForward","Rewind","End","Start","Shuffle","Record","Number_1", "Number_2","Number_3","Number_4","Number_5","Number_6","Number_7","Number_8","Number_9",] } override func viewDidLoad() { super.viewDidLoad() // Rotate the vertical label self.verticalLabel.transform = CGAffineTransform(translationX: -20.0, y: 0.0).rotated(by: CGFloat(-M_PI_2)); // Retrieve three arrays (icons names (NSString), commands (NSString), visibility(Bool)) from NSUserDefaults retrieveButtonsConfiguration() editMode = false // Configure the SWRevealViewController let revealViewController = self.revealViewController() if revealViewController != nil { self.view.addGestureRecognizer((revealViewController?.panGestureRecognizer())!) logger = revealViewController?.rearViewController as? NORLogViewController } } //MARK: - Segue methods override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool { // The 'scan' seque will be performed only if bluetoothManager == nil (if we are not connected already). return identifier != "scan" || self.bluetoothManager == nil } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard segue.identifier == "scan" else { return } // Set this contoller as scanner delegate let nc = segue.destination as! UINavigationController let controller = nc.childViewControllerForStatusBarHidden as! NORScannerViewController // controller.filterUUID = CBUUID.init(string: NORServiceIdentifiers.uartServiceUUIDString) controller.delegate = self } //MARK: - UIPopoverPresentationCtonrollerDelegate func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle { return UIModalPresentationStyle.none } //MARK: - NORScannerViewDelegate func centralManagerDidSelectPeripheral(withManager aManager: CBCentralManager, andPeripheral aPeripheral: CBPeripheral) { // We may not use more than one Central Manager instance. Let's just take the one returned from Scanner View Controller bluetoothManager = NORBluetoothManager(withManager: aManager) bluetoothManager!.delegate = self bluetoothManager!.logger = logger logger!.clearLog() if let name = aPeripheral.name { self.uartPeripheralName = name self.deviceName.text = name } else { self.uartPeripheralName = "device" self.deviceName.text = "No name" } self.connectionButton.setTitle("CANCEL", for: UIControlState()) bluetoothManager!.connectPeripheral(peripheral: aPeripheral) } //MARK: - BluetoothManagerDelegate func peripheralReady() { print("Peripheral is ready") } func peripheralNotSupported() { print("Peripheral is not supported") } func didConnectPeripheral(deviceName aName: String?) { // Scanner uses other queue to send events. We must edit UI in the main queue DispatchQueue.main.async(execute: { self.logger!.bluetoothManager = self.bluetoothManager self.connectionButton.setTitle("DISCONNECT", for: UIControlState()) }) //Following if condition display user permission alert for background notification if UIApplication.instancesRespond(to: #selector(UIApplication.registerUserNotificationSettings(_:))){ UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.sound, .alert], categories: nil)) } NotificationCenter.default.addObserver(self, selector: #selector(self.applicationDidEnterBackgroundCallback), name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.applicationDidBecomeActiveCallback), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil) } func didDisconnectPeripheral() { // Scanner uses other queue to send events. We must edit UI in the main queue DispatchQueue.main.async(execute: { self.logger!.bluetoothManager = nil self.connectionButton.setTitle("CONNECT", for: UIControlState()) self.deviceName.text = "DEFAULT UART" if NORAppUtilities.isApplicationInactive() { NORAppUtilities.showBackgroundNotification(message: "Peripheral \(self.uartPeripheralName!) is disconnected") } self.uartPeripheralName = nil }) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil) bluetoothManager = nil } //MARK: - ButtonconfigureDelegate func didConfigureButton(_ aButton: UIButton, withCommand aCommand: String, andIconIndex index: Int, shouldHide hide: Bool) { let userDefaults = UserDefaults.standard let buttonTag = (selectedButton?.tag)!-1 buttonsHiddenStatus![(selectedButton?.tag)!-1] = NSNumber(value: hide as Bool) userDefaults.set(buttonsHiddenStatus, forKey: "buttonsHiddenStatus") if hide == true { selectedButton?.setImage(nil, for: UIControlState()) }else{ let image = UIImage(named: buttonIcons![index] as! String) selectedButton?.setImage(image, for: UIControlState()) } buttonsImageNames![buttonTag] = buttonIcons![index] buttonsCommands![buttonTag] = aCommand userDefaults.set(buttonsImageNames, forKey: "buttonsImageNames") userDefaults.set(self.buttonsCommands, forKey: "buttonsCommands") userDefaults.synchronize() } //MARK: - NORUArtViewController Implementation func retrieveButtonsConfiguration() { let userDefaults = UserDefaults.standard if userDefaults.object(forKey: "buttonsCommands") != nil { //Buttons configurations already saved in NSUserDefaults buttonsCommands = NSMutableArray(array: userDefaults.object(forKey: "buttonsCommands") as! NSArray) buttonsHiddenStatus = NSMutableArray(array: userDefaults.object(forKey: "buttonsHiddenStatus") as! NSArray) buttonsImageNames = NSMutableArray(array: userDefaults.object(forKey: "buttonsImageNames") as! NSArray) self.showButtonsWithSavedConfiguration() } else { //First time viewcontroller is loaded and there is no saved buttons configurations in NSUserDefaults //Setting up the default values for the first time self.buttonsCommands = NSMutableArray(array: ["","","","","","","","",""]) self.buttonsHiddenStatus = NSMutableArray(array: [true,true,true,true,true,true,true,true,true]) self.buttonsImageNames = NSMutableArray(array: ["Play","Play","Play","Play","Play","Play","Play","Play","Play"]) userDefaults.set(buttonsCommands, forKey: "buttonsCommands") userDefaults.set(buttonsHiddenStatus, forKey: "buttonsHiddenStatus") userDefaults.set(buttonsImageNames, forKey: "buttonsImageNames") userDefaults.synchronize() } } func showButtonsWithSavedConfiguration() { for aButton : UIButton in buttons! { if (buttonsHiddenStatus![aButton.tag-1] as AnyObject).boolValue == true { aButton.backgroundColor = UIColor(red: 200.0/255.0, green: 200.0/255.0, blue: 200.0/255.0, alpha: 1.0) aButton.setImage(nil, for: UIControlState()) aButton.isEnabled = false } else { aButton.backgroundColor = UIColor(red: 0.0/255.0, green:156.0/255.0, blue:222.0/255.0, alpha: 1.0) aButton.setImage(UIImage(named: buttonsImageNames![aButton.tag-1] as! String), for: UIControlState()) aButton.isEnabled = true } } } func showPopoverOnButton() { let popOverViewController = storyboard?.instantiateViewController(withIdentifier: "StoryboardIDEditPopup") as! NOREditPopupViewController popOverViewController.delegate = self popOverViewController.isHidden = false popOverViewController.command = buttonsCommands![(selectedButton?.tag)!-1] as? String let buttonImageName = buttonsImageNames![(selectedButton?.tag)!-1] popOverViewController.setIconIndex((buttonIcons?.index(of: buttonImageName))!) popOverViewController.modalPresentationStyle = UIModalPresentationStyle.popover popOverViewController.popoverPresentationController?.delegate = self self.present(popOverViewController, animated: true, completion: nil) popOverViewController.popoverPresentationController?.sourceView = self.view! popOverViewController.popoverPresentationController?.sourceRect = self.view.bounds popOverViewController.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0) popOverViewController.preferredContentSize = CGSize(width: 300.0, height: 300.0) } func setEditMode(mode aMode : Bool){ editMode = aMode if editMode == true { editButton.setTitle("Done", for: UIControlState()) for aButton : UIButton in buttons { aButton.backgroundColor = UIColor(red: 222.0/255.0, green: 74.0/266.0, blue: 19.0/255.0, alpha: 1.0) aButton.isEnabled = true } } else { editButton.setTitle("Edit", for: UIControlState()) showButtonsWithSavedConfiguration() } } func applicationDidEnterBackgroundCallback(){ NORAppUtilities.showBackgroundNotification(message: "You are still connected to \(self.uartPeripheralName!)") } func applicationDidBecomeActiveCallback(){ UIApplication.shared.cancelAllLocalNotifications() } //MARK: - UART API func send(value aValue : String) { if self.bluetoothManager != nil { bluetoothManager?.send(text: aValue) } } }
bsd-3-clause
68d19fee01b2a3d0231557bbaecf802a
45.3
189
0.670426
5.349166
false
false
false
false
zrtalent/SwiftPictureViewer
SwiftPictureViewer/SwiftPictureViewer/String+Hash.swift
2
1113
// // StringHash.swift // 黑马微博 // // Created by 刘凡 on 15/2/21. // Copyright (c) 2015年 joyios. All rights reserved. // /// 注意:要使用本分类,需要在 bridge.h 中添加以下头文件导入 /// #import <CommonCrypto/CommonCrypto.h> /// 如果使用了单元测试,项目 和 测试项目的 bridge.h 中都需要导入 import Foundation extension String { /// 返回字符串的 MD5 散列结果 var md5: String! { let str = self.cStringUsingEncoding(NSUTF8StringEncoding) let strLen = CC_LONG(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)) let digestLen = Int(CC_MD5_DIGEST_LENGTH) let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen) CC_MD5(str!, strLen, result) // var hash = NSMutableString() var hash = String() for i in 0..<digestLen { // hash.appendFormat("%02x", result[i]) hash += String(format: "%02x", arguments: [result[i]]) } result.dealloc(digestLen) return hash.copy() as! String } }
mit
19bee1f1afae18534aba4347052dded0
27.142857
83
0.608122
3.648148
false
false
false
false
salesforce-ux/design-system-ios
Demo-Swift/slds-sample-app/demo/views/AccountMasterHeaderView.swift
1
1516
// Copyright (c) 2015-present, salesforce.com, inc. All rights reserved // Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license import UIKit class AccountMasterHeaderView: AccountHeaderView { var headerSubText = UILabel() var headerDownArrow = UIImageView() //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– override func makeLayout() { super.makeLayout() headerTitle.text = "My Accounts" headerDownArrow = UIImageView(image: UIImage.sldsUtilityIcon(.chevrondown, withSize: SLDSSquareIconUtilitySmall)) self.addSubview(headerDownArrow) headerDownArrow.constrainRightOf(self.headerTitle, yAlignment: .center, xOffset: 15, yOffset: 2) headerSubText = UILabel() headerSubText.text = "5 items, sorted by Account Name" headerSubText.font = UIFont.sldsFont(.regular, with: .small) headerSubText.textColor = UIColor.sldsTextColor(.colorTextDefault) self.addSubview(headerSubText) headerSubText.constrainBelow(self.headerTitle, xAlignment: .left, yOffset: 2) } }
bsd-3-clause
496c65fc1a6b5f1cbe2e83d5f46fd07c
37.857143
121
0.545588
5.55102
false
false
false
false
cdmx/MiniMancera
miniMancera/Model/Option/WhistlesVsZombies/Abstract/MOptionWhistlesVsZombiesContact.swift
1
4860
import SpriteKit class MOptionWhistlesVsZombiesContact:MGameUpdate<MOptionWhistlesVsZombies> { private var queue:[SKPhysicsContact] override init() { queue = [] super.init() } override func update( elapsedTime:TimeInterval, scene:ViewGameScene<MOptionWhistlesVsZombies>) { lookContacts(scene:scene) queue = [] } //MARK: private private func lookContacts(scene:ViewGameScene<MOptionWhistlesVsZombies>) { for contact:SKPhysicsContact in queue { contactBegin(contact:contact, scene:scene) } } private func contactBegin( contact:SKPhysicsContact, scene:ViewGameScene<MOptionWhistlesVsZombies>) { let bodyA:SKNode? = contact.bodyA.node let bodyB:SKNode? = contact.bodyB.node if let sonicBoom:VOptionWhistlesVsZombiesSonicBoom = bodyA as? VOptionWhistlesVsZombiesSonicBoom { sonicBoomAndBody( sonicBoom:sonicBoom, body:bodyB, scene:scene) } else if let sonicBoom:VOptionWhistlesVsZombiesSonicBoom = bodyB as? VOptionWhistlesVsZombiesSonicBoom { sonicBoomAndBody( sonicBoom:sonicBoom, body:bodyA, scene:scene) } else if let zombie:VOptionWhistlesVsZombiesZombie = bodyA as? VOptionWhistlesVsZombiesZombie { zombieAndBody( zombie:zombie, body:bodyB, scene:scene) } else if let zombie:VOptionWhistlesVsZombiesZombie = bodyB as? VOptionWhistlesVsZombiesZombie { zombieAndBody( zombie:zombie, body:bodyA, scene:scene) } } private func sonicBoomAndBody( sonicBoom:VOptionWhistlesVsZombiesSonicBoom, body:SKNode?, scene:ViewGameScene<MOptionWhistlesVsZombies>) { guard let sonicBoomModel:MOptionWhistlesVsZombiesSonicBoomItem = sonicBoom.model else { return } let alive:Bool = sonicBoomModel.alive() if alive { sonicBoom.stop() if let _:VOptionWhistlesVsZombiesPhysicSonicLimit = body as? VOptionWhistlesVsZombiesPhysicSonicLimit { sonicBoomModel.collisionFinish(scene:scene) } else if let zombie:VOptionWhistlesVsZombiesZombie = body as? VOptionWhistlesVsZombiesZombie { sonicBoomAndZombie( sonicBoomModel:sonicBoomModel, zombie:zombie) } } } private func zombieAndBody( zombie:VOptionWhistlesVsZombiesZombie, body:SKNode?, scene:ViewGameScene<MOptionWhistlesVsZombies>) { if let whistle:VOptionWhistlesVsZombiesWhistle = body as? VOptionWhistlesVsZombiesWhistle { zombieAndWhistle( zombie:zombie, whistle:whistle) } else if let _:VOptionWhistlesVsZombiesPhysicHome = body as? VOptionWhistlesVsZombiesPhysicHome { zombieAndHome(scene:scene) } } private func sonicBoomAndZombie( sonicBoomModel:MOptionWhistlesVsZombiesSonicBoomItem, zombie:VOptionWhistlesVsZombiesZombie) { sonicBoomModel.collisionStart() guard let modelZombie:MOptionWhistlesVsZombiesZombieItem = zombie.model else { return } modelZombie.sonicHit(sonicBoom:sonicBoomModel) } private func zombieAndWhistle( zombie:VOptionWhistlesVsZombiesZombie, whistle:VOptionWhistlesVsZombiesWhistle) { let whistleModel:MOptionWhistlesVsZombiesWhistleBase = whistle.model let alive:Bool = whistleModel.alive() if alive { whistleModel.explodeStart() guard let modelZombie:MOptionWhistlesVsZombiesZombieItem = zombie.model else { return } modelZombie.exploded() } } private func zombieAndHome(scene:ViewGameScene<MOptionWhistlesVsZombies>) { guard let controller:COptionWhistlesVsZombies = scene.controller as? COptionWhistlesVsZombies else { return } controller.zombiesGotHome() } //MARK: public func addContact(contact:SKPhysicsContact) { queue.append(contact) } }
mit
238e1b717b3f03c1e1bef91fe8fdd2ba
26
113
0.569959
5.503964
false
false
false
false
febus/SwiftWeather
Swift Weather/ViewController.swift
1
8330
// // ViewController.swift // Swift Weather // // Created by Jake Lin on 4/06/2014. // Copyright (c) 2014 rushjet. All rights reserved. // import UIKit import CoreLocation import Alamofire import SwiftyJSON import SwiftWeatherService class ViewController: UIViewController, CLLocationManagerDelegate { private let locationManager = CLLocationManager() @IBOutlet weak var loadingIndicator : UIActivityIndicatorView! = nil @IBOutlet weak var icon : UIImageView! @IBOutlet weak var temperature : UILabel! @IBOutlet weak var loading : UILabel! @IBOutlet weak var location : UILabel! @IBOutlet weak var time1: UILabel! @IBOutlet weak var time2: UILabel! @IBOutlet weak var time3: UILabel! @IBOutlet weak var time4: UILabel! @IBOutlet weak var image1: UIImageView! @IBOutlet weak var image2: UIImageView! @IBOutlet weak var image3: UIImageView! @IBOutlet weak var image4: UIImageView! @IBOutlet weak var temp1: UILabel! @IBOutlet weak var temp2: UILabel! @IBOutlet weak var temp3: UILabel! @IBOutlet weak var temp4: UILabel! override func viewDidLoad() { super.viewDidLoad() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest self.loadingIndicator.startAnimating() let background = UIImage(named: "background.png") self.view.backgroundColor = UIColor(patternImage: background!) let singleFingerTap = UITapGestureRecognizer(target: self, action: "handleSingleTap:") self.view.addGestureRecognizer(singleFingerTap) locationManager.requestAlwaysAuthorization() locationManager.startUpdatingLocation() } func handleSingleTap(recognizer: UITapGestureRecognizer) { locationManager.startUpdatingLocation() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // It maybe a Xcode 6.2 beta Swift compiler's bug, it throws "command failed due to signal segmentation fault 11" error /* func updateWeatherInfo(latitude: CLLocationDegrees, longitude: CLLocationDegrees) { let service = SwiftWeatherService.WeatherService() service.retrieveForecast(latitude, longitude: longitude, success: { response in println(response) // self.updateUISuccess(response.object!) }, failure:{ response in println(response) println("Error: " + response.error!.localizedDescription) self.loading.text = "Internet appears down!" }) } */ func updateWeatherInfo(latitude: CLLocationDegrees, longitude: CLLocationDegrees) { let url = "http://api.openweathermap.org/data/2.5/forecast" let params = ["lat":latitude, "lon":longitude] print(params) Alamofire.request(.GET, url, parameters: params) .responseJSON { (request, response, result) in if(result.error != nil) { print("Error: \(result.error)") print(request) print(response) self.loading.text = "Internet appears down!" } else { print("Success: \(url)") print(request) let json = JSON(result.value!) self.updateUISuccess(json) } } } func updateUISuccess(json: JSON) { self.loading.text = nil self.loadingIndicator.hidden = true self.loadingIndicator.stopAnimating() let service = SwiftWeatherService.WeatherService() // If we can get the temperature from JSON correctly, we assume the rest of JSON is correct. if let tempResult = json["list"][0]["main"]["temp"].double { // Get country let country = json["city"]["country"].stringValue // Get and convert temperature let temperature = service.convertTemperature(country, temperature: tempResult) self.temperature.text = "\(temperature)°" // Get city name self.location.text = json["city"]["name"].stringValue // Get and set icon let weather = json["list"][0]["weather"][0] let condition = weather["id"].intValue let icon = weather["icon"].stringValue let nightTime = service.isNightTime(icon) service.updateWeatherIcon(condition, nightTime: nightTime, index: 0, callback: self.updatePictures) // Get forecast for index in 1...4 { print(json["list"][index]) if let tempResult = json["list"][index]["main"]["temp"].double { // Get and convert temperature let temperature = service.convertTemperature(country, temperature: tempResult) if (index==1) { self.temp1.text = "\(temperature)°" } else if (index==2) { self.temp2.text = "\(temperature)°" } else if (index==3) { self.temp3.text = "\(temperature)°" } else if (index==4) { self.temp4.text = "\(temperature)°" } // Get forecast time let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "HH:mm" let rawDate = json["list"][index]["dt"].doubleValue let date = NSDate(timeIntervalSince1970: rawDate) let forecastTime = dateFormatter.stringFromDate(date) if (index==1) { self.time1.text = forecastTime } else if (index==2) { self.time2.text = forecastTime } else if (index==3) { self.time3.text = forecastTime } else if (index==4) { self.time4.text = forecastTime } // Get and set icon let weather = json["list"][index]["weather"][0] let condition = weather["id"].intValue let icon = weather["icon"].stringValue let nightTime = service.isNightTime(icon) service.updateWeatherIcon(condition, nightTime: nightTime, index: index, callback: self.updatePictures) } else { continue } } } else { self.loading.text = "Weather info is not available!" } } func updatePictures(index: Int, name: String) { if (index==0) { self.icon.image = UIImage(named: name) } if (index==1) { self.image1.image = UIImage(named: name) } if (index==2) { self.image2.image = UIImage(named: name) } if (index==3) { self.image3.image = UIImage(named: name) } if (index==4) { self.image4.image = UIImage(named: name) } } //MARK: - CLLocationManagerDelegate func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let location:CLLocation = locations[locations.count-1] if (location.horizontalAccuracy > 0) { self.locationManager.stopUpdatingLocation() print(location.coordinate) updateWeatherInfo(location.coordinate.latitude, longitude: location.coordinate.longitude) } } func locationManager(manager: CLLocationManager, didFailWithError error: NSError) { print(error) self.loading.text = "Can't get your location!" } override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } }
mit
4e3c1d29b7aafcba11d592239ec22294
37.013699
123
0.555556
5.409357
false
false
false
false
bsmith11/ScoreReporter
ScoreReporter/Events/EventsViewModel.swift
1
674
// // MyEventsViewModel.swift // ScoreReporter // // Created by Bradley Smith on 11/22/16. // Copyright © 2016 Brad Smith. All rights reserved. // import Foundation import ScoreReporterCore class EventsViewModel: NSObject { fileprivate let eventService = EventService(client: APIClient.sharedInstance) fileprivate(set) dynamic var loading = false fileprivate(set) dynamic var error: NSError? = nil } // MARK: - Public extension EventsViewModel { func downloadEvents() { loading = true eventService.downloadEventList { [weak self] result in self?.loading = false self?.error = result.error } } }
mit
8cd34631bc4010a5ef283ee9bd453df5
21.433333
81
0.677563
4.341935
false
false
false
false
johntmcintosh/BarricadeKit
DevelopmentApp/Pods/Sourcery/bin/Sourcery.app/Contents/Resources/SwiftTemplateRuntime/TemplateContext.swift
1
5761
// // Created by Krzysztof Zablocki on 31/12/2016. // Copyright (c) 2016 Pixle. All rights reserved. // import Foundation final class TemplateContext: NSObject, SourceryModel { let types: Types let arguments: [String: NSObject] init(types: Types, arguments: [String: NSObject]) { self.types = types self.arguments = arguments } // sourcery:inline:TemplateContext.AutoCoding /// :nodoc: required internal init?(coder aDecoder: NSCoder) { guard let types: Types = aDecoder.decode(forKey: "types") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["types"])); fatalError() }; self.types = types guard let arguments: [String: NSObject] = aDecoder.decode(forKey: "arguments") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["arguments"])); fatalError() }; self.arguments = arguments } /// :nodoc: internal func encode(with aCoder: NSCoder) { aCoder.encode(self.types, forKey: "types") aCoder.encode(self.arguments, forKey: "arguments") } // sourcery:end var stencilContext: [String: Any] { return [ "types": types, "type": types.typesByName, "argument": arguments ] } // sourcery: skipDescription, skipEquality var jsContext: [String: Any] { return [ "types": [ "all": types.all, "protocols": types.protocols, "classes": types.classes, "structs": types.structs, "enums": types.enums, "based": types.based, "inheriting": types.inheriting, "implementing": types.implementing ], "type": types.typesByName, "argument": arguments ] } } // sourcery: skipJSExport /// Collection of scanned types for accessing in templates public final class Types: NSObject, SourceryModel { let types: [Type] init(types: [Type]) { self.types = types } // sourcery:inline:Types.AutoCoding /// :nodoc: required public init?(coder aDecoder: NSCoder) { guard let types: [Type] = aDecoder.decode(forKey: "types") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["types"])); fatalError() }; self.types = types } /// :nodoc: public func encode(with aCoder: NSCoder) { aCoder.encode(self.types, forKey: "types") } // sourcery:end // sourcery: skipDescription, skipEquality, skipCoding /// :nodoc: public lazy internal(set) var typesByName: [String: Type] = { var typesByName = [String: Type]() self.types.forEach { typesByName[$0.name] = $0 } return typesByName }() // sourcery: skipDescription, skipEquality, skipCoding /// All known types, excluding protocols public lazy internal(set) var all: [Type] = { return self.types.filter { !($0 is Protocol) } }() // sourcery: skipDescription, skipEquality, skipCoding /// All known protocols public lazy internal(set) var protocols: [Protocol] = { return self.types.flatMap { $0 as? Protocol } }() // sourcery: skipDescription, skipEquality, skipCoding /// All known classes public lazy internal(set) var classes: [Class] = { return self.all.flatMap { $0 as? Class } }() // sourcery: skipDescription, skipEquality, skipCoding /// All known structs public lazy internal(set) var structs: [Struct] = { return self.all.flatMap { $0 as? Struct } }() // sourcery: skipDescription, skipEquality, skipCoding /// All known enums public lazy internal(set) var enums: [Enum] = { return self.all.flatMap { $0 as? Enum } }() // sourcery: skipDescription, skipEquality, skipCoding /// Types based on any other type, grouped by its name, even if they are not known. /// `types.based.MyType` returns list of types based on `MyType` public lazy internal(set) var based: [String: [Type]] = { var content = [String: [Type]]() self.types.forEach { type in type.based.keys.forEach { name in var list = content[name] ?? [Type]() list.append(type) content[name] = list } } return content }() // sourcery: skipDescription, skipEquality, skipCoding /// Classes inheriting from any known class, grouped by its name. /// `types.inheriting.MyClass` returns list of types inheriting from `MyClass` public lazy internal(set) var inheriting: [String: [Type]] = { var content = [String: [Type]]() self.classes.forEach { type in type.inherits.keys.forEach { name in var list = content[name] ?? [Type]() list.append(type) content[name] = list } } return content }() // sourcery: skipDescription, skipEquality, skipCoding /// Types implementing known protocol, grouped by its name. /// `types.implementing.MyProtocol` returns list of types implementing `MyProtocol` public lazy internal(set) var implementing: [String: [Type]] = { var content = [String: [Type]]() self.types.forEach { type in type.implements.keys.forEach { name in var list = content[name] ?? [Type]() list.append(type) content[name] = list } } return content }() }
mit
4af26e1acd95365ea81bf9c559c2e521
34.343558
264
0.5933
4.438367
false
false
false
false
Raizlabs/SketchyCode
Pods/Marshal/Sources/MarshaledObject.swift
5
8412
// // M A R S H A L // // () // /\ // ()--' '--() // `. .' // / .. \ // ()' '() // // import Foundation public protocol MarshaledObject { func any(for key: KeyType) throws -> Any func optionalAny(for key: KeyType) -> Any? } public extension MarshaledObject { public func any(for key: KeyType) throws -> Any { let pathComponents = key.stringValue.characters.split(separator: ".").map(String.init) var accumulator: Any = self for component in pathComponents { if let componentData = accumulator as? Self, let value = componentData.optionalAny(for: component) { accumulator = value continue } throw MarshalError.keyNotFound(key: key.stringValue) } if let _ = accumulator as? NSNull { throw MarshalError.nullValue(key: key.stringValue) } return accumulator } public func value<A: ValueType>(for key: KeyType) throws -> A { let any = try self.any(for: key) do { guard let result = try A.value(from: any) as? A else { throw MarshalError.typeMismatchWithKey(key: key.stringValue, expected: A.self, actual: type(of: any)) } return result } catch let MarshalError.typeMismatch(expected: expected, actual: actual) { throw MarshalError.typeMismatchWithKey(key: key.stringValue, expected: expected, actual: actual) } } public func value<A: ValueType>(for key: KeyType) throws -> A? { do { return try self.value(for: key) as A } catch MarshalError.keyNotFound { return nil } catch MarshalError.nullValue { return nil } } public func value<A: ValueType>(for key: KeyType, discardingErrors: Bool = false) throws -> [A] { let any = try self.any(for: key) do { return try Array<A>.value(from: any, discardingErrors: discardingErrors) } catch let MarshalError.typeMismatch(expected: expected, actual: actual) { throw MarshalError.typeMismatchWithKey(key: key.stringValue, expected: expected, actual: actual) } } public func value<A: ValueType>(for key: KeyType) throws -> [A?] { let any = try self.any(for: key) do { return try Array<A>.value(from: any) } catch let MarshalError.typeMismatch(expected: expected, actual: actual) { throw MarshalError.typeMismatchWithKey(key: key.stringValue, expected: expected, actual: actual) } } public func value<A: ValueType>(for key: KeyType, discardingErrors: Bool = false) throws -> [A]? { do { return try self.value(for: key, discardingErrors: discardingErrors) as [A] } catch MarshalError.keyNotFound { return nil } catch MarshalError.nullValue { return nil } } public func value<A: ValueType>(for key: KeyType) throws -> [A?]? { do { return try self.value(for: key) as [A] } catch MarshalError.keyNotFound { return nil } catch MarshalError.nullValue { return nil } } public func value<A: ValueType>(for key: KeyType) throws -> [String: A] { let any = try self.any(for: key) do { return try [String: A].value(from: any) } catch let MarshalError.typeMismatch(expected: expected, actual: actual) { throw MarshalError.typeMismatchWithKey(key: key.stringValue, expected: expected, actual: actual) } } public func value<A: ValueType>(for key: KeyType) throws -> [String: A]? { do { let any = try self.any(for: key) return try [String: A].value(from: any) } catch MarshalError.keyNotFound { return nil } catch MarshalError.nullValue { return nil } } public func value(for key: KeyType) throws -> [MarshalDictionary] { let any = try self.any(for: key) guard let object = any as? [MarshalDictionary] else { throw MarshalError.typeMismatchWithKey(key: key.stringValue, expected: [MarshalDictionary].self, actual: type(of: any)) } return object } public func value(for key: KeyType) throws -> [MarshalDictionary]? { do { return try value(for: key) as [MarshalDictionary] } catch MarshalError.keyNotFound { return nil } catch MarshalError.nullValue { return nil } } public func value(for key: KeyType) throws -> MarshalDictionary { let any = try self.any(for: key) guard let object = any as? MarshalDictionary else { throw MarshalError.typeMismatchWithKey(key: key.stringValue, expected: MarshalDictionary.self, actual: type(of: any)) } return object } public func value(for key: KeyType) throws -> MarshalDictionary? { do { return try value(for: key) as MarshalDictionary } catch MarshalError.keyNotFound { return nil } catch MarshalError.nullValue { return nil } } public func value<A: ValueType>(for key: KeyType) throws -> Set<A> { let any = try self.any(for: key) do { return try Set<A>.value(from: any) } catch let MarshalError.typeMismatch(expected: expected, actual: actual) { throw MarshalError.typeMismatchWithKey(key: key.stringValue, expected: expected, actual: actual) } } public func value<A: ValueType>(for key: KeyType) throws -> Set<A>? { do { return try self.value(for: key) as Set<A> } catch MarshalError.keyNotFound { return nil } catch MarshalError.nullValue { return nil } } public func value<A: RawRepresentable>(for key: KeyType) throws -> A where A.RawValue: ValueType { let raw = try self.value(for: key) as A.RawValue guard let value = A(rawValue: raw) else { throw MarshalError.typeMismatchWithKey(key: key.stringValue, expected: A.self, actual: raw) } return value } public func value<A: RawRepresentable>(for key: KeyType) throws -> A? where A.RawValue: ValueType { do { return try self.value(for: key) as A } catch MarshalError.keyNotFound { return nil } catch MarshalError.nullValue { return nil } } public func value<A: RawRepresentable>(for key: KeyType) throws -> [A] where A.RawValue: ValueType { let rawArray = try self.value(for: key) as [A.RawValue] return try rawArray.map({ raw in guard let value = A(rawValue: raw) else { throw MarshalError.typeMismatchWithKey(key: key.stringValue, expected: A.self, actual: raw) } return value }) } public func value<A: RawRepresentable>(for key: KeyType) throws -> [A]? where A.RawValue: ValueType { do { return try self.value(for: key) as [A] } catch MarshalError.keyNotFound { return nil } catch MarshalError.nullValue { return nil } } public func value<A: RawRepresentable>(for key: KeyType) throws -> Set<A> where A.RawValue: ValueType { let rawArray = try self.value(for: key) as [A.RawValue] let enumArray: [A] = try rawArray.map({ raw in guard let value = A(rawValue: raw) else { throw MarshalError.typeMismatchWithKey(key: key.stringValue, expected: A.self, actual: raw) } return value }) return Set<A>(enumArray) } public func value<A: RawRepresentable>(for key: KeyType) throws -> Set<A>? where A.RawValue: ValueType { do { return try self.value(for: key) as Set<A> } catch MarshalError.keyNotFound { return nil } catch MarshalError.nullValue { return nil } } }
mit
27130d1f8fc1204f7ade27a9edd6b466
31.353846
131
0.567166
4.418067
false
false
false
false
SpeChen/SwiftDictModel
SwiftDictModel/02- 字典转模型/ViewController.swift
2
1043
// // ViewController.swift // 02- 字典转模型 // // Created by coderCSF on 15/3/13. // Copyright (c) 2015年 coderCSF. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let json = loadJSON() let obj = SwiftDictModel.sharedManager.objectWithDictionary(json, cls: SubModel.self) as! SubModel println("OTHER") for value in obj.other! { println(value.name) } println("OTHERS") for value in obj.others! { let o = value as! Info println(o.name) } println("Demo \(obj.demo!)") } func loadJSON() -> NSDictionary { let path = NSBundle.mainBundle().pathForResource("Model01.json", ofType: nil) let data = NSData(contentsOfFile: path!) let json = NSJSONSerialization.JSONObjectWithData(data!, options: .allZeros, error: nil) as! NSDictionary return json } }
mit
0cb32f2723c9e57b3ba7eea32c6af09e
24.146341
113
0.586809
4.368644
false
false
false
false
sun409377708/swiftDemo
SinaSwiftPractice/SinaSwiftPractice/Classes/View/Home/View/JQStatusCell.swift
1
5619
// // JQStatusCell.swift // SinaSwiftPractice // // Created by maoge on 16/11/16. // Copyright © 2016年 maoge. All rights reserved. // import UIKit import SDWebImage import YYText import SVProgressHUD let commonMargin: CGFloat = 8 //图片之间的间距 private let pictureCellMargin: CGFloat = 3 //计算图片的宽度 private let maxWidth = ScreenWidth - 2 * commonMargin private let itemWidth = (maxWidth - 2 * pictureCellMargin) / 3 private var isFirst = true class JQStatusCell: UITableViewCell { @IBOutlet weak var iconView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var memberImage: UIImageView! @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var sourceLabel: UILabel! @IBOutlet weak var contentLabel: YYLabel! @IBOutlet weak var avatarImage: UIImageView! @IBOutlet weak var pictureViewWidthCons: NSLayoutConstraint! @IBOutlet weak var pictureViewHeightCons: NSLayoutConstraint! @IBOutlet weak var pictureViewTopCons: NSLayoutConstraint! @IBOutlet weak var pictureView: JQPictureView! @IBOutlet weak var flowLayout: UICollectionViewFlowLayout! @IBOutlet weak var commentBtn: UIButton! @IBOutlet weak var repostBtn: UIButton! @IBOutlet weak var ohYeahBtn: UIButton! @IBOutlet weak var retweetedText: UILabel! @IBOutlet weak var toolBarView: UIView! var viewmodel: JQStatusViewModel? { didSet { iconView.sd_setImage(with: viewmodel?.iconURL) memberImage.image = viewmodel?.memberImage avatarImage.image = viewmodel?.avatarImage nameLabel.text = viewmodel?.status?.user?.name timeLabel.text = viewmodel?.dateString sourceLabel.text = viewmodel?.sourceText // contentLabel.text = viewmodel?.status?.text contentLabel.attributedText = viewmodel?.originalAttributeString //计算配图视图大小 let count = viewmodel?.pictureInfos?.count ?? 0 let size = changePictureViewSize(count: count) pictureViewWidthCons.constant = size.width pictureViewHeightCons.constant = size.height flowLayout.itemSize = count == 1 ? size : CGSize(width: itemWidth, height: itemWidth) //传递数据给配图视图 pictureView.pictureInfo = viewmodel?.pictureInfos if !isFirst { isFirst = false } retweetedText?.text = viewmodel?.status?.retweeted_status?.text //根据是否有配图调整顶部间距 pictureViewTopCons.constant = (count == 0 ? 0 : commonMargin) //设置工具条按钮 commentBtn.setTitle(viewmodel?.comment_text, for: .normal) repostBtn.setTitle(viewmodel?.repost_text, for: .normal) ohYeahBtn.setTitle(viewmodel?.ohYeah_text, for: .normal) //高亮文本点击响应 contentLabel.highlightTapAction = {(containerView, text, range, rect) in let subStr = (text.string as NSString).substring(with: range) SVProgressHUD.showInfo(withStatus: subStr) if subStr.contains("http") { let temp = JQTempController() temp.URLString = subStr self.navController()?.pushViewController(temp, animated: true) } } } } func ToolBarHeight(viewmodel: JQStatusViewModel) -> CGFloat { //调用set方法 self.viewmodel = viewmodel self.contentView.layoutIfNeeded() return toolBarView.frame.maxY } override func awakeFromNib() { super.awakeFromNib() // Initialization code selectionStyle = .none contentLabel.preferredMaxLayoutWidth = ScreenWidth - 2 * commonMargin retweetedText?.preferredMaxLayoutWidth = ScreenWidth - 2 * commonMargin contentLabel.numberOfLines = 0 retweetedText?.numberOfLines = 0 //设置配图视图流水布局 // flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth) flowLayout.minimumLineSpacing = pictureCellMargin flowLayout.minimumInteritemSpacing = pictureCellMargin } private func changePictureViewSize(count: Int) -> CGSize { //0 图 if count == 0{ return CGSize.zero } // 1 图 if count == 1 { let urlString = viewmodel?.pictureInfos?.first?.wap_pic ?? "" //获取磁盘中的图片根据路径 let image = SDWebImageManager.shared().imageCache.imageFromDiskCache(forKey: urlString) guard let imageSize = image?.size else { return CGSize.zero } return CGSize(width: imageSize.width, height: imageSize.height) } //4 图 if count == 4 { let width = 2 * itemWidth + pictureCellMargin return CGSize(width: width, height: width) } //其他图 let rowCount = CGFloat((count - 1) / 3 + 1) let height = rowCount * itemWidth + (rowCount - 1) * pictureCellMargin return CGSize(width: maxWidth, height: height) } }
mit
57a8cda9e6affc8092229e97a84aa1e0
29.875
99
0.590357
5.358974
false
false
false
false
bingwenfu/Mandelbrot-Set
Mandelbrot/Mandelbrot/AppDelegate.swift
1
8725
// // AppDelegate.swift // Mandelbrot // // Created by Bingwen Fu on 8/26/15. // Copyright (c) 2015 Bingwen. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate, NSTableViewDataSource, NSTableViewDelegate { var allPoints = NSMutableArray() var dataManager = DataManager(dbPath: "/Users/Bingwen/Library/Mobile Documents/com~apple~CloudDocs/Projects/Mandelbrot Set/Mandelbrot/Mandelbrot/DB/md.db") var hasDeviceInfo = false @IBOutlet weak var window: NSWindow! @IBOutlet weak var deviceInfoPanel: NSPanel! @IBOutlet weak var deviceInfoTextField: NSTextField! @IBOutlet weak var pointsTableView: NSTableView! @IBOutlet weak var mandelbrotGLView: MandelbrotGLView! @IBOutlet weak var spectrumView: SpectrumView! @IBOutlet weak var iterationHistView: IterationHistView! @IBOutlet weak var iterationTextField: NSTextField! @IBOutlet weak var leftXTextField: NSTextField! @IBOutlet weak var leftYTextField: NSTextField! @IBOutlet weak var BottomXTextField: NSTextField! @IBOutlet weak var bottomYTextField: NSTextField! @IBOutlet weak var zoomRatioTextField: NSTextField! @IBOutlet weak var widthTextField: NSTextField! @IBOutlet weak var colorwell1: NSColorWell! @IBOutlet weak var colorwell2: NSColorWell! @IBOutlet weak var colorwell3: NSColorWell! @IBOutlet weak var colorwell4: NSColorWell! @IBOutlet weak var slider1: NSSlider! @IBOutlet weak var slider2: NSSlider! @IBOutlet weak var slider3: NSSlider! @IBOutlet weak var slider4: NSSlider! func applicationDidFinishLaunching(_ aNotification: Notification) { NotificationCenter.default.addObserver(self, selector:#selector(AppDelegate.updateControlPanel), name: NSNotification.Name(rawValue: "mandelbrotGLViewFinishedDrawing"), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(AppDelegate.tableViewSelectionDidChange(_:)), name: NSNotification.Name.NSTableViewSelectionDidChange, object: nil) allPoints = (dataManager?.fetchAllPoints())! pointsTableView.dataSource = self pointsTableView.delegate = self } func colorFromColorWell(_ cw: NSColorWell) -> Color { var c = Color() c.r = Float(cw.color.redComponent) c.g = Float(cw.color.greenComponent) c.b = Float(cw.color.blueComponent) return c } func updateControlPanel() { let p = mandelbrotGLView.p leftXTextField.stringValue = String(stringInterpolationSegment: p.x1) BottomXTextField.stringValue = String(stringInterpolationSegment: p.x2) leftYTextField.stringValue = String(stringInterpolationSegment: p.y1) bottomYTextField.stringValue = String(stringInterpolationSegment: p.y2) iterationTextField.stringValue = String(mandelbrotGLView.iterLimit) zoomRatioTextField.stringValue = String(stringInterpolationSegment: mandelbrotGLView.zoomRatio) widthTextField.stringValue = String(stringInterpolationSegment: (p.x2-p.x1)) let cs = mandelbrotGLView.colorScheme colorwell1.color = cColor2NSColor(cs.color1) colorwell2.color = cColor2NSColor(cs.color2) colorwell3.color = cColor2NSColor(cs.color3) colorwell4.color = cColor2NSColor(cs.color4) slider1.doubleValue = Double(mandelbrotGLView.colorScheme.colorLine1*100) slider2.doubleValue = Double(mandelbrotGLView.colorScheme.colorLine2*100) let upper: Float = 30.0 let lower: Float = 1.0 var a = mandelbrotGLView.colorScheme.a a = (a - lower)/(upper-lower) a = a*100 slider3.doubleValue = Double(a) spectrumView.iterLimit = mandelbrotGLView.iterLimit spectrumView.colorSchme = mandelbrotGLView.colorScheme spectrumView.refreshView() if mandelbrotGLView.displayType == MANDELBROT_SET { iterationHistView.colorSchme = mandelbrotGLView.colorScheme iterationHistView.histArr = mandelbrotGLView.histArr iterationHistView.nBins = Int(mandelbrotGLView.histBins) iterationHistView.iterLimit = mandelbrotGLView.iterLimit iterationHistView.refreshView() } if hasDeviceInfo == false { updateDeviceInfo() hasDeviceInfo = true } } func updateDeviceInfo() { } @IBAction func colorweel1Changed(_ sender: NSColorWell) { mandelbrotGLView.colorScheme.color1 = colorFromColorWell(sender) mandelbrotGLView.updateColor() } @IBAction func colorwell2Changed(_ sender: NSColorWell) { mandelbrotGLView.colorScheme.color2 = colorFromColorWell(sender) mandelbrotGLView.updateColor() } @IBAction func colorwell3Changed(_ sender: NSColorWell) { mandelbrotGLView.colorScheme.color3 = colorFromColorWell(sender) mandelbrotGLView.updateColor() } @IBAction func colorwell4Changed(_ sender: NSColorWell) { mandelbrotGLView.colorScheme.color4 = colorFromColorWell(sender) mandelbrotGLView.updateColor() } @IBAction func slider1Changes(_ sender: NSSlider) { mandelbrotGLView.colorScheme.colorLine1 = Float(sender.doubleValue*0.01) mandelbrotGLView.updateColor() } @IBAction func slider2Changes(_ sender: NSSlider) { mandelbrotGLView.colorScheme.colorLine2 = Float(sender.doubleValue*0.01) mandelbrotGLView.updateColor() } @IBAction func slider3Changes(_ sender: NSSlider) { let upper: Float = 30.0 let lower: Float = 1.0 var a: Float = Float(sender.doubleValue) a = (a/100.0)*(upper-lower) + lower mandelbrotGLView.colorScheme.a = a mandelbrotGLView.updateColor() } @IBAction func slider4Changes(_ sender: NSSlider) { } @IBAction func clipColorChecked(_ sender: NSButton) { mandelbrotGLView.clipColor = (sender.state == 1) mandelbrotGLView.updateColor() } @IBAction func zoomOutButtomClick(_ sender: AnyObject) { mandelbrotGLView.zoomOut() } @IBAction func zoomRatioTextFieldEntered(_ sender: AnyObject) { mandelbrotGLView.zoomRatio = zoomRatioTextField.doubleValue } @IBAction func iterationTextFieldEntered(_ sender: NSTextField) { if sender.integerValue <= 0 { return } mandelbrotGLView.iterLimit = Int32(sender.integerValue) mandelbrotGLView.redrawMandelbrot(withCalculation: true) } @IBAction func saveImageButtomClick(_ sender: AnyObject) { mandelbrotGLView.writeCurrentFrameAsImageToDisk() } @IBAction func savePointsClick(_ sender: AnyObject) { dataManager?.saveParameters(toDB: mandelbrotGLView.p, colorScheme: mandelbrotGLView.colorScheme, iterLimit:mandelbrotGLView.iterLimit) } @IBAction func fractalTypeSelected(_ sender: NSPopUpButton) { if let str = sender.titleOfSelectedItem { if str == "Mandelbrot Set" { mandelbrotGLView.displayType = MANDELBROT_SET } else if str == "Julia Set" { mandelbrotGLView.displayType = JULIA_SET } else { print("Unknown selection: \(str) [\( #function)]") } } } func numberOfRows(in tableView: NSTableView) -> Int { return allPoints.count } func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { if let v = tableView.make(withIdentifier: "PointsCell", owner: self) as? NSTableCellView { if let parameters = allPoints[row] as? MandelbrotParameters { if tableColumn?.identifier == "leftColumn" { v.textField!.stringValue = String(parameters.id) } else { v.textField!.stringValue = String(parameters.iterLimit) } } return v; } return nil; } @objc(tableViewSelectionDidChange:) func tableViewSelectionDidChange(_ notification: Notification) { let row = pointsTableView.selectedRow if let parameters = allPoints[row] as? MandelbrotParameters { mandelbrotGLView.iterLimit = parameters.iterLimit mandelbrotGLView.colorScheme = parameters.colorScheme mandelbrotGLView.p = parameters.plane mandelbrotGLView.redrawMandelbrot(withCalculation: true) } } }
mit
a718e642db3c671764d22d5a0d05c66a
37.606195
189
0.672206
4.623741
false
false
false
false
ioscreator/ioscreator
IOSMoveViewKeyboardTutorial/IOSMoveViewKeyboardTutorial/ViewController.swift
1
1582
// // ViewController.swift // IOSMoveViewKeyboardTutorial // // Created by Arthur Knopper on 18/11/2018. // Copyright © 2018 Arthur Knopper. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var textView: UITextView! override func viewDidLoad() { super.viewDidLoad() let notificationCenter = NotificationCenter.default notificationCenter.addObserver(self, selector: #selector(adjustForKeyboard), name: UIResponder.keyboardWillHideNotification, object: nil) notificationCenter.addObserver(self, selector: #selector(adjustForKeyboard), name: UIResponder.keyboardWillChangeFrameNotification, object: nil) } @objc func adjustForKeyboard(notification: Notification) { // 1 let userInfo = notification.userInfo! // 2 let keyboardScreenEndFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue let keyboardViewEndFrame = view.convert(keyboardScreenEndFrame, from: view.window) // 3 if notification.name == UIResponder.keyboardWillHideNotification { textView.contentInset = UIEdgeInsets.zero } else { textView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardViewEndFrame.height, right: 0) } // 4 textView.scrollIndicatorInsets = textView.contentInset // 5 let selectedRange = textView.selectedRange textView.scrollRangeToVisible(selectedRange) } }
mit
a28109e8084670be2ce1f3064dd2c90c
31.9375
152
0.681214
5.508711
false
false
false
false
sol/aeson
tests/JSONTestSuite/parsers/test_PMJSON_1_2_0/JSONObject.swift
8
7191
// // JSONObject.swift // PMJSON // // Created by Kevin Ballard on 11/10/15. // Copyright © 2016 Postmates. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // /// A collection of key-value pairs that maps `String` to `JSON`. /// /// This collection abstracts away the underlying representation and allows for JSON-specific /// methods to be added. public struct JSONObject { /// Creates an empty object. public init() { dictionary = [:] } /// Creates an object from a sequence of `(String,JSON)` pairs. public init<S: Sequence>(_ seq: S) where S.Iterator.Element == (String,JSON) { // optimize for the case where the sequence doesn't contain duplicate keys dictionary = Dictionary(minimumCapacity: seq.underestimatedCount) for (key,value) in seq { dictionary[key] = value } } /// The JSON object represented as a `[String: JSON]`. public fileprivate(set) var dictionary: [String: JSON] public subscript(key: String) -> JSON? { @inline(__always) get { return dictionary[key] } @inline(__always) set { dictionary[key] = newValue } } } extension JSONObject: Collection { /// The position of the first element in a non-empty object. /// /// Identical to `endIndex` in an empty object. public var startIndex: Index { return Index(dictionary.startIndex) } /// The collection's "past the end" position. /// /// `endIndex` is not a valid argument to `subscript`, and is always reachable from `startIndex` /// by zero or more applications of `successor()`. public var endIndex: Index { return Index(dictionary.endIndex) } /// Returns `true` iff `self` is empty. public var isEmpty: Bool { return dictionary.isEmpty } /// The number of entries in the object. public var count: Int { return dictionary.count } public func makeIterator() -> Iterator { return Iterator(dictionary.makeIterator()) } public subscript(position: Index) -> (String,JSON) { return dictionary[position.base] } public func index(after i: Index) -> Index { return Index(dictionary.index(after: i.base)) } public func formIndex(after i: inout Index) { dictionary.formIndex(after: &i.base) } /// Represents a position in a `JSONObject`. public struct Index: Comparable { fileprivate var base: Dictionary<String,JSON>.Index fileprivate init(_ base: Dictionary<String,JSON>.Index) { self.base = base } public static func ==(lhs: JSONObject.Index, rhs: JSONObject.Index) -> Bool { return lhs.base == rhs.base } public static func <(lhs: JSONObject.Index, rhs: JSONObject.Index) -> Bool { return lhs.base < rhs.base } } public struct Iterator: IteratorProtocol { private var base: Dictionary<String,JSON>.Iterator fileprivate init(_ base: Dictionary<String,JSON>.Iterator) { self.base = base } /// Advance to the next element and return it, or `nil` if no next element exists. /// /// - Requires: No preceding call to `self.next()` has returned `nil`. public mutating func next() -> (String,JSON)? { return base.next() } } } extension JSONObject { /// A collection containing just the keys of `self`. /// /// Keys appear in the same order as they occur as the `.0` member of key-value pairs in `self`. /// Each key in the result has a unique value. public var keys: LazyMapCollection<JSONObject, String> { return lazy.map({ $0.0 }) } /// A collection containing just the values of `self`. /// /// Values appear in the same order as they occur as the `.1` member of key-value pairs in `self`. public var values: LazyMapCollection<JSONObject, JSON> { return lazy.map({ $0.1 }) } /// Returns the `Index` for the given key, or `nil` if the key is not present in the object. public func indexForKey(_ key: String) -> Index? { return dictionary.index(forKey: key).map(Index.init) } /// Update the value stored in the object for the given key, or, if the key does not exist, /// add a new key-value pair to the object. /// /// Returns the value that was replaced, or `nil` if a new key-value pair was added. public mutating func updateValue(_ value: JSON, forKey key: String) -> JSON? { return dictionary.updateValue(value, forKey: key) } /// Remove the key-value pair at `index`. /// /// Invalidates all indices with respect to `self`. public mutating func removeAtIndex(_ index: Index) -> (String,JSON)? { return dictionary.remove(at: index.base) } /// Remove a given key and the associated value from the object. /// Returns the value that was removed, or `nil` if the key was not present in the object. public mutating func removeValueForKey(_ key: String) -> JSON? { return dictionary.removeValue(forKey: key) } /// Remove all elements. /// /// Invalidates all indices with respect to `self`. public mutating func removeAll() { dictionary.removeAll() } /// If `!self.isEmpty`, return the first key-value pair in the sequence of elements, otherwise return `nil`. public mutating func popFirst() -> (String,JSON)? { return dictionary.popFirst() } } extension JSONObject: ExpressibleByDictionaryLiteral { /// Creates an object from a dictionary. public init(_ dictionary: [String: JSON]) { self.dictionary = dictionary } /// Creates an object initialized with `elements`. public init(dictionaryLiteral elements: (String, JSON)...) { self.init(elements) } } extension JSONObject: TextOutputStreamable, CustomStringConvertible, CustomDebugStringConvertible { public func write<Target : TextOutputStream>(to target: inout Target) { JSON.encode(JSON(self), to: &target) } public var description: String { return JSON.encodeAsString(JSON(self)) } public var debugDescription: String { let desc = JSON.encodeAsString(JSON(self)) return "JSONObject(\(desc))" } } extension JSONObject: Equatable { public static func ==(lhs: JSONObject, rhs: JSONObject) -> Bool { return lhs.dictionary == rhs.dictionary } } extension JSONObject: CustomReflectable { public var customMirror: Mirror { let children: LazyMapCollection<Dictionary<String, JSON>, Mirror.Child> = dictionary.lazy.map({ ($0,$1) }) return Mirror(self, children: children, displayStyle: .dictionary) } }
bsd-3-clause
99d4495bace279a2911ac5993ec39801
32.44186
114
0.626008
4.446506
false
false
false
false
andrebocchini/SwiftChattyOSX
Pods/SwiftChatty/SwiftChatty/Requests/Users/GetUserRegistrationDateRequest.swift
1
832
// // UserRegistrationDate.swift // SwiftChatty // // Created by Andre Bocchini on 1/21/16. // Copyright © 2016 Andre Bocchini. All rights reserved. // /// - SeeAlso: http://winchatty.com/v2/readme#_Toc421451687 public struct GetUserRegistrationDateRequest: Request { public let endpoint: ApiEndpoint = .GetUserRegistrationDate public var parameters: [String : AnyObject] = [:] public init(withUsers users: [String]) { if users.count > 0 { var concatenatedUsers: String = "" for i in 0...(users.count - 1) { if i == 0 { concatenatedUsers += users[i] } else { concatenatedUsers += ("," + users[i]) } } self.parameters["username"] = concatenatedUsers } } }
mit
ae1ae19b8948abe37c9028ca79931fdc
27.655172
63
0.559567
4.396825
false
false
false
false
calebd/ReactiveCocoa
ReactiveCocoa/NSObject+Association.swift
4
785
import ReactiveSwift extension Reactive where Base: NSObject { /// Retrieve the associated value for the specified key. If the value does not /// exist, `initial` would be called and the returned value would be /// associated subsequently. /// /// - parameters: /// - key: An optional key to differentiate different values. /// - initial: The action that supples an initial value. /// /// - returns: /// The associated value for the specified key. internal func associatedValue<T>(forKey key: StaticString = #function, initial: (Base) -> T) -> T { var value = objc_getAssociatedObject(base, key.utf8Start) as! T? if value == nil { value = initial(base) objc_setAssociatedObject(base, key.utf8Start, value, .OBJC_ASSOCIATION_RETAIN) } return value! } }
mit
5896b69a0508f19df35f9650e39f6921
34.681818
100
0.699363
3.685446
false
false
false
false
myfreeweb/freepass
ios/Freepass/Freepass/LoginViewController.swift
1
2455
import UIKit class LoginViewController: UITableViewController, UISplitViewControllerDelegate { @IBOutlet weak var userName: UITextField! @IBOutlet weak var password: UITextField! override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = Colors.primaryAccent print(documentsPath()?.path) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func documentsPath() -> NSURL? { return NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first } // MARK: - Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "openVault" { let splitViewController = segue.destinationViewController as! UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem() splitViewController.delegate = self } } override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool { if identifier == "openVault" { do { let path = documentsPath()?.URLByAppendingPathComponent("test.fpass").path! // TODO file selection try Vault.open(path!, userName: userName.text!, password: password.text!) } catch { let alert = UIAlertController(title: "Error", message: "Error", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "OK", style: .Default) { (action) in }) self.presentViewController(alert, animated: true, completion: nil) return false } } return true } // MARK: - Split view func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool { guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false } guard let topAsDetailController = secondaryAsNavController.topViewController as? EntryViewController else { return false } if topAsDetailController.entry == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } return false } }
unlicense
10f3530c5fd1306e44c35779ec83a93f
39.245902
219
0.771894
5.26824
false
false
false
false
Witcast/witcast-ios
WiTcast/ViewController/Player/PlayerPageTabBarController.swift
1
3127
/* * Copyright (C) 2015 - 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit import Material class PlayerPageTabBarController: TabsController { open override func prepare() { super.prepare() view.backgroundColor = Color.blueGrey.lighten5 preparePageTabBar() } } extension PlayerPageTabBarController { fileprivate func preparePageTabBar() { tabBarAlignment = .top tabBar.isDividerHidden = true tabBar.lineAlignment = .bottom tabBar.lineColor = UIColor.black tabBar.backgroundColor = CustomFunc.UIColorFromRGB(rgbValue: colorMain) } } //class PlayerPageTabBarController: TabsController { // open override func prepare() { // super.prepare() // view.backgroundColor = Color.blueGrey.lighten5 // // delegate = self // self.isBounceEnabled = false // preparePageTabBar() // } //} // //extension PlayerPageTabBarController { // fileprivate func preparePageTabBar() { // pageTabBarAlignment = .top // pageTabBar.dividerColor = nil // pageTabBar.lineColor = UIColor.black // pageTabBar.lineAlignment = .bottom // pageTabBar.backgroundColor = CustomFunc.UIColorFromRGB(rgbValue: colorMain) // } //} // //extension PlayerPageTabBarController: TabsController { // func pageTabBarController(pageTabBarController: PageTabBarController, didTransitionTo viewController: UIViewController) { //// print("pageTabBarController", pageTabBarController, "didTransitionTo viewController:", viewController) // } //}
apache-2.0
a2daff2af78c162e486a114a7804515f
39.089744
127
0.730093
4.632593
false
false
false
false
huangboju/Moots
Examples/Lumia/Lumia/Component/UltraDrawerView/Sources/UltraDrawerView/Utils/UIView+AutoLayout.swift
1
2434
import UIKit internal extension UIView { @discardableResult func set( _ attribute: NSLayoutConstraint.Attribute, equalTo view: UIView, multiplier: CGFloat = 1, constant: CGFloat = 0, priority: UILayoutPriority = .required ) -> NSLayoutConstraint { let constraint = NSLayoutConstraint( item: self, attribute: attribute, relatedBy: .equal, toItem: view, attribute: attribute, multiplier: multiplier, constant: constant ) constraint.priority = priority constraint.isActive = true return constraint } @discardableResult func set( _ attributes: [NSLayoutConstraint.Attribute], equalTo view: UIView, multiplier: CGFloat = 1, constant: CGFloat = 0, priority: UILayoutPriority = .required ) -> [NSLayoutConstraint] { return attributes.map { set($0, equalTo: view, multiplier: multiplier, constant: constant, priority: priority) } } @discardableResult func set( _ attribute: NSLayoutConstraint.Attribute, equalTo view: UIView, attribute toAttribute: NSLayoutConstraint.Attribute, multiplier: CGFloat = 1, constant: CGFloat = 0, priority: UILayoutPriority = .required ) -> NSLayoutConstraint { let constraint = NSLayoutConstraint( item: self, attribute: attribute, relatedBy: .equal, toItem: view, attribute: toAttribute, multiplier: multiplier, constant: constant ) constraint.priority = priority constraint.isActive = true return constraint } @discardableResult func set(_ attribute: NSLayoutConstraint.Attribute, equalTo value: CGFloat, priority: UILayoutPriority = .required) -> NSLayoutConstraint { let constraint = NSLayoutConstraint( item: self, attribute: attribute, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 0, constant: value ) constraint.priority = priority constraint.isActive = true return constraint } }
mit
b151340bbe21f8f0570d76c4dcf712cc
25.747253
120
0.56327
5.936585
false
false
false
false
huangboju/Moots
Examples/Lumia/Lumia/Component/ScrollExample/ScrollMechanics/Sources/Utils/TimerAnimation.swift
1
1571
import QuartzCore public final class TimerAnimation { public typealias Animations = (_ progress: Double, _ time: TimeInterval) -> Void public typealias Completion = (_ finished: Bool) -> Void public init(duration: TimeInterval, animations: @escaping Animations, completion: Completion? = nil) { self.duration = duration self.animations = animations self.completion = completion firstFrameTimestamp = CACurrentMediaTime() let displayLink = CADisplayLink(target: self, selector: #selector(handleFrame(_:))) displayLink.add(to: .main, forMode: RunLoop.Mode.common) self.displayLink = displayLink } deinit { invalidate() } public func invalidate() { guard running else { return } running = false completion?(false) displayLink?.invalidate() } private let duration: TimeInterval private let animations: Animations private let completion: Completion? private weak var displayLink: CADisplayLink? private var running: Bool = true private let firstFrameTimestamp: CFTimeInterval @objc private func handleFrame(_ displayLink: CADisplayLink) { guard running else { return } let elapsed = CACurrentMediaTime() - firstFrameTimestamp if elapsed >= duration { animations(1, duration) running = false completion?(true) displayLink.invalidate() } else { animations(elapsed / duration, elapsed) } } }
mit
88eb6b3a1abce90f2b32fb6132a4b329
29.211538
106
0.640356
5.551237
false
false
false
false
ABTSoftware/SciChartiOSTutorial
v2.x/Examples/SciChartSwiftDemo/SciChartSwiftDemo/Views/TooltipsAndHitTest/CustomTooltipViewSwift.swift
1
1517
//****************************************************************************** // SCICHART® Copyright SciChart Ltd. 2011-2018. All rights reserved. // // Web: http://www.scichart.com // Support: [email protected] // Sales: [email protected] // // CustomTooltipViewSwift.swift is part of the SCICHART® Examples. Permission is hereby granted // to modify, create derivative works, distribute and publish any part of this source // code whether for commercial, private or personal use. // // The SCICHART® examples are distributed in the hope that they will be useful, but // without any warranty. It is provided "AS IS" without warranty of any kind, either // expressed or implied. //****************************************************************************** import UIKit class CustomTooltipViewSwift: SCIXySeriesDataView { @IBOutlet weak var xLabel: UILabel! @IBOutlet weak var yLabel: UILabel! @IBOutlet weak var seriesName: UILabel! static override func createInstance() -> SCITooltipDataView! { let view : CustomTooltipViewSwift = (Bundle.main.loadNibNamed("CustomTooltipViewSwift", owner: nil, options: nil)![0] as? CustomTooltipViewSwift)! view.translatesAutoresizingMaskIntoConstraints = false return view } func setData(_ data: SCIXySeriesInfo!) { xLabel.text = data.formatXCursorValue(data.xValue()) yLabel.text = data.formatXCursorValue(data.yValue()) seriesName.text = data.seriesName() } }
mit
fc7525e7fbe9599ee7405d47fa5804ae
39.918919
154
0.641347
4.791139
false
false
false
false
edx/edx-app-ios
Source/DiscussionTopic.swift
2
1508
// // DiscussionTopic.swift // edX // // Created by Akiva Leffert on 7/6/15. // Copyright (c) 2015 edX. All rights reserved. // import UIKit import edXCore public struct DiscussionTopic { public let id: String? public let name: String? public let children: [DiscussionTopic] public let depth : UInt public let icon : Icon? public init(id: String?, name: String?, children: [DiscussionTopic], depth : UInt = 0, icon : Icon? = nil) { self.id = id self.name = name self.children = children self.depth = depth self.icon = icon } init?(json: JSON, depth : UInt = 0) { if let name = json["name"].string { self.id = json["id"].string self.name = name self.depth = depth self.icon = nil let childJSON = json["children"].array ?? [] self.children = childJSON.mapSkippingNils { return DiscussionTopic(json: $0, depth : depth + 1) } } else { return nil } } public static func linearizeTopics(topics : [DiscussionTopic]) -> [DiscussionTopic] { var result : [DiscussionTopic] = [] var queue : [DiscussionTopic] = Array(topics.reversed()) while queue.count > 0 { let topic = queue.removeLast() result.append(topic) queue.append(contentsOf: Array(topic.children.reversed())) } return result } }
apache-2.0
c2cdc58454e299e8218da6317ce55b4a
26.925926
112
0.556366
4.284091
false
false
false
false
PekanMmd/Pokemon-XD-Code
enums/GoDTextureFormats.swift
1
2696
// // GoDTextureFormats.swift // GoD Tool // // Created by The Steez on 13/09/2017. // // import Foundation enum GoDTextureFormats: Int, CaseIterable { case I4 = 0x40 case I8 = 0x42 case IA4 = 0x41 case IA8 = 0x43 case RGB565 = 0x44 case RGB5A3 = 0x90 case RGBA32 = 0x45 case C4 = 0x0 case C8 = 0x1 case C14X2 = 0x30 case CMPR = 0xB0 var standardRawValue : Int { switch self { case .I4: return 0 case .I8: return 1 case .IA4: return 2 case .IA8: return 3 case .RGB565: return 4 case .RGB5A3: return 5 case .RGBA32: return 6 case .C4: return 8 case .C8: return 9 case .C14X2: return 10 case .CMPR: return 14 } } var isIndexed: Bool { switch self { case .C4, .C8, .C14X2: return true default: return false } } var paletteCount : Int { return Int(pow(2, Double(bitsPerPixel))) } var blockWidth : Int { switch self { case .IA8 : fallthrough case .RGB565 : fallthrough case .RGB5A3 : fallthrough case .RGBA32 : fallthrough case .C14X2 : return 4 default : return 8 } } var blockHeight : Int { switch self { case .I4 : fallthrough case .C4 : fallthrough case .CMPR : return 8 default : return 4 } } var bitsPerPixel : Int { switch self { case .I4: return 4 case .I8: return 8 case .IA4: return 8 case .IA8: return 16 case .RGB565: return 16 case .RGB5A3: return 16 case .RGBA32: return 32 case .C4: return 4 case .C8: return 8 case .C14X2: return 16 case .CMPR: return 4 } } var name : String { switch self { case .C14X2: return "C14X2" case .I4: return "I4" case .I8: return "I8" case .IA4: return "IA4" case .IA8: return "IA8" case .RGB565: return "RGB565" case .RGB5A3: return "RGB5A3" case .RGBA32: return "RGBA32" case .C4: return "C4" case .C8: return "C8" case .CMPR: return "CMPR" } } var paletteID : Int? { switch self { case .IA8: return 0 case .RGB565: return 1 // case .RGB5A3: return 2 // Models use 2 case .RGB5A3: return 3 // note other games use 2 for this, including .dat models in these games default: return nil } } static func fromStandardRawValue(_ value: Int) -> GoDTextureFormats? { for format in allCases { if format.standardRawValue == value { return format } } return nil } static func fromPaletteID(_ value: Int) -> GoDTextureFormats? { if value == 2 { return .RGB5A3 // In .dat models, 2 is used for these. Seems to be the standard in other games. Also seen in PBR } for format in allCases { if format.paletteID == value { return format } } return nil } }
gpl-2.0
d77aad15f8db48aa52c07bfd0d1ed0d1
15.143713
115
0.623145
2.584851
false
false
false
false
vmagaziy/PDFInspector
Sources/iOS/RootViewController.swift
1
1519
// PDFInspector // Author: Vladimir Magaziy <[email protected]> import UIKit class RootViewController: UITableViewController { var documents: [PIPDFDocument] = [] override func viewDidLoad() { super.viewDidLoad() self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: cellID()) let url = NSBundle.mainBundle().URLForResource("test", withExtension: "pdf") self.documents = [ PIPDFDocument(contentsOfURL: url) ] self.title = NSLocalizedString("PDF Documents", comment:"") } } // MARK: Table view extension RootViewController : UITableViewDataSource, UITableViewDelegate { override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return documents.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(cellID(), forIndexPath: indexPath) as! UITableViewCell let document = documents[indexPath.row] cell.textLabel?.text = document.name return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) let document = documents[indexPath.row] let vc = PDFObjectViewController() vc.PDFObject = document navigationController?.pushViewController(vc, animated: true) } func cellID() -> String { return "cellID" } }
unlicense
9178ab83375c7b4dea474f929c95d038
30
116
0.735352
5.114478
false
false
false
false
kaltura/playkit-ios
Classes/Player/PlayerWrapper/DefaultPlayerWrapper.swift
1
5648
// =================================================================================================== // Copyright (C) 2017 Kaltura Inc. // // Licensed under the AGPLv3 license, unless a different license for a // particular library is specified in the applicable library path. // // You may obtain a copy of the License at // https://www.gnu.org/licenses/agpl-3.0.html // =================================================================================================== import Foundation class DefaultPlayerWrapper: NSObject, PlayerEngine { private func printInvocationWarning(_ action: String) { PKLog.warning("Attempt to invoke \(action) on null instance of the player") } // ***************************** // // MARK: - PlayerEngine // ***************************** // var onEventBlock: ((PKEvent) -> Void)? public var startPosition: TimeInterval { get { printInvocationWarning("\(#function)") return 0.0 } set { printInvocationWarning("\(#function)") } } public var currentPosition: TimeInterval { get { printInvocationWarning("\(#function)") return 0.0 } set { printInvocationWarning("\(#function)") } } var mediaConfig: MediaConfig? public var playbackType: String? { printInvocationWarning("\(#function)") return nil } func loadMedia(from mediaSource: PKMediaSource?, handler: AssetHandler) { printInvocationWarning("\(#function)") } func playFromLiveEdge() { printInvocationWarning("\(#function)") } public func updateTextTrackStyling(_ textTrackStyling: PKTextTrackStyling) { printInvocationWarning("\(#function)") } // ***************************** // // MARK: - BasicPlayer // ***************************** // public var duration: Double { printInvocationWarning("\(#function)") return 0.0 } public var currentState: PlayerState { printInvocationWarning("\(#function)") return .idle } public var isPlaying: Bool { printInvocationWarning("\(#function)") return false } /// Save view reference till prepare public weak var view: PlayerView? public var currentTime: TimeInterval { get { printInvocationWarning("\(#function)") return 0.0 } set { printInvocationWarning("\(#function)") } } public var currentProgramTime: Date? { printInvocationWarning("\(#function)") return nil } public var currentAudioTrack: String? { get { printInvocationWarning("\(#function)") return nil } set { printInvocationWarning("\(#function)") } } public var currentTextTrack: String? { get { printInvocationWarning("\(#function)") return nil } set { printInvocationWarning("\(#function)") } } public var rate: Float { get { printInvocationWarning("\(#function)") return 0.0 } set { printInvocationWarning("\(#function)") } } public var volume: Float { get { printInvocationWarning("\(#function)") return 0.0 } set { printInvocationWarning("\(#function)") } } public var loadedTimeRanges: [PKTimeRange]? { printInvocationWarning("\(#function)") return nil } public var bufferedTime: TimeInterval { printInvocationWarning("\(#function)") return 0.0 } func play() { printInvocationWarning("\(#function)") } func pause() { printInvocationWarning("\(#function)") } func resume() { printInvocationWarning("\(#function)") } func stop() { printInvocationWarning("\(#function)") } func replay() { printInvocationWarning("\(#function)") } func seek(to time: TimeInterval) { printInvocationWarning("\(#function)") } func seekToLiveEdge() { printInvocationWarning("\(#function)") } func selectTrack(trackId: String) { printInvocationWarning("\(#function)") } func destroy() { printInvocationWarning("\(#function)") } func prepare(_ mediaConfig: MediaConfig) { printInvocationWarning("\(#function)") } func startBuffering() { printInvocationWarning("\(#function)") } // ***************************** // // MARK: - Time Observation // ***************************** // func addPeriodicObserver(interval: TimeInterval, observeOn dispatchQueue: DispatchQueue?, using block: @escaping (TimeInterval) -> Void) -> UUID { printInvocationWarning("\(#function)") return UUID() } func addBoundaryObserver(boundaries: [PKBoundary], observeOn dispatchQueue: DispatchQueue?, using block: @escaping (TimeInterval, Double) -> Void) -> UUID { printInvocationWarning("\(#function)") return UUID() } func removePeriodicObserver(_ token: UUID) { printInvocationWarning("\(#function)") } func removeBoundaryObserver(_ token: UUID) { printInvocationWarning("\(#function)") } func removePeriodicObservers() { printInvocationWarning("\(#function)") } func removeBoundaryObservers() { printInvocationWarning("\(#function)") } }
agpl-3.0
e0b9fb4a7dec2adc06e99bdc273923f1
25.895238
160
0.535588
5.521017
false
false
false
false
twtstudio/WePeiYang-iOS
WePeiYang/Read/Controller/BookShelfViewController.swift
1
5126
// // BookShelfViewController.swift // YuePeiYang // // Created by Halcao on 2016/10/22. // Copyright © 2016年 Halcao. All rights reserved. // import UIKit class BookShelfViewController: UITableViewController { var bookShelf: [MyBook] = [] var label = UILabel() override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // self.navigationController?.navigationBar.backgroundColor = UIColor(colorLiteralRed: 234.0/255.0, green: 74.0/255.0, blue: 70/255.0, alpha: 1.0) // //titleLabel设置 let titleLabel = UILabel(text: "我的收藏", fontSize: 17) titleLabel.backgroundColor = UIColor.clearColor() titleLabel.textAlignment = .Center titleLabel.textColor = UIColor.whiteColor() self.navigationItem.titleView = titleLabel; //NavigationBar 的背景,使用了View self.navigationController!.jz_navigationBarBackgroundAlpha = 0; let bgView = UIView(frame: CGRect(x: 0, y: -664, width: self.view.frame.size.width, height: self.navigationController!.navigationBar.frame.size.height+UIApplication.sharedApplication().statusBarFrame.size.height+600)) bgView.backgroundColor = UIColor(colorLiteralRed: 234.0/255.0, green: 74.0/255.0, blue: 70/255.0, alpha: 1.0) self.view.addSubview(bgView) // //改变 statusBar 颜色 UIApplication.sharedApplication().setStatusBarStyle(.LightContent, animated: true) self.bookShelf = User.sharedInstance.bookShelf addNoBookLabel() } override func viewDidLoad() { super.viewDidLoad() self.title = "我的收藏" self.tableView.tableFooterView = UIView() self.tableView.separatorStyle = .None } func addNoBookLabel() { if self.bookShelf.count == 0 { label.text = "你还没有收藏哦,快去添加收藏吧!" label.sizeToFit() self.view.addSubview(label) label.snp_makeConstraints { make in make.center.equalTo(self.view.snp_center) } } else { label.removeFromSuperview() } } // Mark: UITableViewDataSource override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return bookShelf.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = UITableViewCell(style: .Value1, reuseIdentifier: "cell1") cell.textLabel?.text = self.bookShelf[indexPath.row].title // cell.textLabel?.font = UIFont.systemFontOfSize(13) // cell.detailTextLabel?.font = UIFont.systemFontOfSize(12) let width = UIScreen.mainScreen().bounds.size.width if width >= bigiPhoneWidth { cell.textLabel?.font = UIFont.systemFontOfSize(16) cell.detailTextLabel?.font = UIFont.systemFontOfSize(12) } else { cell.textLabel?.font = UIFont.systemFontOfSize(14) cell.detailTextLabel?.font = UIFont.systemFontOfSize(10) } cell.detailTextLabel?.text = self.bookShelf[indexPath.row].author //cell.tag = self.bookShelf[indexPath.row].isbn var separatorMargin = 20 // MARK: 这个效果看起来很奇怪 if indexPath.row == self.bookShelf.count - 1 { separatorMargin = 0 } let separator = UIView() separator.backgroundColor = UIColor.init(red: 227/255, green: 227/255, blue: 229/255, alpha: 1) cell.addSubview(separator) separator.snp_makeConstraints { make in make.height.equalTo(1) make.left.equalTo(cell).offset(separatorMargin) make.right.equalTo(cell).offset(-separatorMargin) make.bottom.equalTo(cell).offset(0) } return cell } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { User.sharedInstance.delFromFavourite(with: "\(self.bookShelf[indexPath.row].id)") { self.bookShelf.removeAtIndex(indexPath.row) User.sharedInstance.bookShelf = self.bookShelf self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) self.addNoBookLabel() } } } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 40 } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let vc = BookDetailViewController(bookID: "\(self.bookShelf[indexPath.row].id)") self.navigationController?.showViewController(vc, sender: nil) self.tableView.deselectRowAtIndexPath(indexPath, animated: true) } }
mit
93981bc446793e0770a77f81a5d9fb74
39.232
225
0.65003
4.656481
false
false
false
false
jtbales/Face-To-Name
Face-To-Name/Acquaintances/AcquaintancesTableViewController.swift
1
8372
// // AcquaintancesTableViewController.swift // Face-To-Name // // Created by John Bales on 4/26/17. // Copyright © 2017 John T Bales. All rights reserved. // import UIKit import AWSDynamoDB import AWSMobileHubHelper /* * Table of the User's Acquaintances queried from Face table. */ class AcquaintancesTableViewController: UITableViewController { var acquaintanceRows: [Face]? var doneLoading: Bool = false var lastEvaluatedKey:[String : AWSDynamoDBAttributeValue]! var lock: NSLock? override func viewDidLoad() { super.viewDidLoad() acquaintanceRows = [] lock = NSLock() //Add refresh function self.refreshControl?.addTarget(self, action: #selector(self.refresh(_:)), for: UIControlEvents.valueChanged) self.refreshList(true) // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false } func refresh(_ sender: AnyObject) { print("Refreshing") self.refreshList(true) self.refreshControl?.endRefreshing() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // return the number of rows if let rowCount = self.acquaintanceRows?.count { return rowCount; } else { return 0 } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "acquaintanceCell", for: indexPath) as! AcquaintancesTableViewCell // Configure the cell... if let acquaintanceRows = self.acquaintanceRows { let acquaintance = acquaintanceRows[indexPath.row] cell.nameLabel.text = acquaintance.name cell.face = acquaintance } return cell } //Allow edits/deletions override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source print("Deleting cell at index \(indexPath.row)") //Assign object map details let cell = tableView.cellForRow(at: indexPath) as! AcquaintancesTableViewCell //Get cell details if let faceToDelete = cell.face { //Automatically remove the cell for fluidness self.acquaintanceRows?.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic) //Delete on AWS Face.deleteFaceData(faceToDelete, { () -> Void? in //Success //self.refreshList(true) //Why refresh when it's already removed from table? return nil }, { (alertParams) -> Void? in //Failure self.alertMessageOkay(alertParams) return nil }) } else { self.alertMessageOkay("Can't Delete", "Cell content's empty. Refreshing List.") self.refreshList(true) } } } //Load more by dragging override func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { // UITableView only moves in one direction, y axis let currentOffset = scrollView.contentOffset.y let maximumOffset = scrollView.contentSize.height - scrollView.frame.size.height // Change 10.0 to adjust the distance from bottom if maximumOffset - currentOffset <= 10.0 { //Load more refreshList(false) } } //Refresh Table List func refreshList(_ startFromBeginning: Bool) { //verify logged in if !AWSIdentityManager.default().isLoggedIn { presentSignInViewController() } else if self.lock?.try() != nil { if startFromBeginning { self.lastEvaluatedKey = nil; self.doneLoading = false } //Exit if there is nothing else to load else if self.doneLoading { return } UIApplication.shared.isNetworkActivityIndicatorVisible = true //Set up DynamoDB query let dynamoDBObjectMapper = AWSDynamoDBObjectMapper.default() let queryExpression = AWSDynamoDBQueryExpression() queryExpression.exclusiveStartKey = self.lastEvaluatedKey queryExpression.limit = 50 queryExpression.keyConditionExpression = "#userId = :userId" queryExpression.expressionAttributeNames = ["#userId": "userId"] queryExpression.expressionAttributeValues = [":userId": AWSIdentityManager.default().identityId!,] dynamoDBObjectMapper.query(Face.self, expression: queryExpression).continueWith(executor: AWSExecutor.mainThread(), block: { (task:AWSTask!) -> AnyObject! in if self.lastEvaluatedKey == nil { self.acquaintanceRows?.removeAll(keepingCapacity: true) } if let paginatedOutput = task.result { for item in paginatedOutput.items as! [Face] { self.acquaintanceRows?.append(item) } self.lastEvaluatedKey = paginatedOutput.lastEvaluatedKey if paginatedOutput.lastEvaluatedKey == nil { self.doneLoading = true } } UIApplication.shared.isNetworkActivityIndicatorVisible = false self.tableView.reloadData() if let error = task.error as NSError? { print("Error: \(error)") } return nil }) } } /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ // MARK: - Navigation //Select row override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) //Get selected cell let cell = tableView.cellForRow(at: indexPath) as! AcquaintancesTableViewCell print("Selected cell with name \(cell.nameLabel.text ?? "nil")") //Segue to Edit view performSegue(withIdentifier: "EditAcquaintanceShowSegue", sender: cell) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { //Edit if let destinationViewController = segue.destination as? EditAcquaintanceViewController { let cell = sender as? AcquaintancesTableViewCell destinationViewController.faceToEdit = cell?.face //Pass face object } } //MARK: Actions @IBAction func unwindToAcquaintList(segue: UIStoryboardSegue) { refreshList(true) } } class AcquaintancesTableViewCell : UITableViewCell { @IBOutlet weak var nameLabel: UILabel! //Non-visable data var face: Face? }
mit
b2305075dd0ce951e1b7f234545f831a
33.307377
169
0.597061
5.400645
false
false
false
false
ricealexanderb/forager
Foragr/MapViewController.swift
1
2642
// // MapViewController.swift // Foragr // // Created by Alex on 8/12/14. // Copyright (c) 2014 Alex Rice. All rights reserved. // import UIKit import MapKit class MapViewController: UIViewController, MKMapViewDelegate { @IBOutlet weak var displayMap: MKMapView! override func viewDidLoad() { super.viewDidLoad() displayMap.delegate = self self.displayMap.showsUserLocation = true var region = MKCoordinateRegionMakeWithDistance(self.displayMap.userLocation.coordinate, 500, 500) displayMap.setRegion(region, animated: false) // var locationManager = CLLocationManager() // locationManager.requestWhenInUseAuthorization() // switch CLLocationManager.authorizationStatus() { // case .Authorized: // println("authorized") // case .AuthorizedWhenInUse: // println("authorized when in use") // case .Denied: // println("denied") // case .Restricted: // println("restricted") // case .NotDetermined: // println("not determined") // } // if CLLocationManager.authorizationStatus() == CLAuthorizationStatus.Denied { // var permissionAlert = UIAlertView(title: "Location Data", message: "Forager needs your location data so that we can show you the correct map area.\nThings are going to be jankey unless you go to Settings and turn on Location Services", delegate: self, cancelButtonTitle: "ok") // permissionAlert.show() // } for patch in patchListGlobal { //Casting as workaround to bug descibed here http://stackoverflow.com/questions/24087011/ambiguous-use-of-propertyname-error-given-overridden-property-with-didset-ob var plat = (patch as Patch).lat var plon = (patch as Patch).lon var pin = MKPointAnnotation() // in a just world, the following lines would work... //pin.coordinate.latitude = patch.lat //pin.coordinate.longitude = patch.lon // ..but until the compiler bug is fixed I will set the values using 'plat' and 'plon' pin.coordinate.latitude = plat pin.coordinate.longitude = plon pin.title = patch.plantName displayMap.addAnnotation(pin) } } func mapView(mapView: MKMapView!, didUpdateUserLocation userLocation: MKUserLocation!) { var region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 500, 500) mapView.setRegion(region, animated: true) } }
mit
978de7e0c8389a1ba1b3f2dc392a8481
39.045455
290
0.635882
4.829982
false
false
false
false
silence0201/Swift-Study
AdvancedSwift/可选值/A Tour of Optional Techniques - 3.playgroundpage/Contents.swift
1
840
/*: By contrast, the Ruby and Python code is more along the lines of the following: */ //#-editable-code var a: [() -> Int] = [] do { var g = (1...3).makeIterator() var i: Int var o: Int? = g.next() while o != nil { i = o! a.append { i } o = g.next() } } //#-end-editable-code /*: Here, `i` is declared *outside* the loop — and reused — so every closure captures the same `i`. If you run each of them, they'll all return 3. The `do` is there because, despite `i` being declared outside the loop, it's still scoped in such a way that it isn't *accessible* outside that loop — it's sandwiched in a narrow outer shell. C\# had the same behavior as Ruby until C\# 5, when it was decided that this behavior was dangerous enough to justify a breaking change in order to work like Swift. */
mit
2a1c45fa3eb7ede0a40f85bb60510c4c
25.0625
80
0.642686
3.418033
false
false
false
false
Pencroff/ai-hackathon-2017
IOS APP/Pods/Cloudinary/Cloudinary/Features/Helpers/CLDTranformation.swift
1
57191
// // CLDTransformation.swift // // Copyright (c) 2016 Cloudinary (http://cloudinary.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation /** The CLDTransformation class represents a full transformation performed by Cloudinay on-the-fly on a certain asset. */ @objc open class CLDTransformation: NSObject { fileprivate var currentTransformationParams: [String : String] = [:] fileprivate var transformations: [[String : String]] = [] // MARK: - Init public override init() { super.init() } // MARK: - Get Values open var width: String? { return getParam(.WIDTH) } open var height: String? { return getParam(.HEIGHT) } open var named: String? { return getParam(.NAMED) } open var crop: String? { return getParam(.CROP) } open var background: String? { return getParam(.BACKGROUND) } open var color: String? { return getParam(.COLOR) } open var effect: String? { return getParam(.EFFECT) } open var angle: String? { return getParam(.ANGLE) } open var opacity: String? { return getParam(.OPACITY) } open var border: String? { return getParam(.BORDER) } open var x: String? { return getParam(.X) } open var y: String? { return getParam(.Y) } open var radius: String? { return getParam(.RADIUS) } open var quality: String? { return getParam(.QUALITY) } open var defaultImage: String? { return getParam(.DEFAULT_IMAGE) } open var gravity: String? { return getParam(.GRAVITY) } open var colorSpace: String? { return getParam(.COLOR_SPACE) } open var prefix: String? { return getParam(.PREFIX) } open var overlay: String? { return getParam(.OVERLAY) } open var underlay: String? { return getParam(.UNDERLAY) } open var fetchFormat: String? { return getParam(.FETCH_FORMAT) } open var density: String? { return getParam(.DENSITY) } open var page: String? { return getParam(.PAGE) } open var delay: String? { return getParam(.DELAY) } open var rawTransformation: String? { return getParam(.RAW_TRANSFORMATION) } open var flags: String? { return getParam(.FLAGS) } open var dpr: String? { return getParam(.DPR) } open var zoom: String? { return getParam(.ZOOM) } open var aspectRatio: String? { return getParam(.ASPECT_RATIO) } open var audioCodec: String? { return getParam(.AUDIO_CODEC) } open var audioFrequency: String? { return getParam(.AUDIO_FREQUENCY) } open var bitRate: String? { return getParam(.BIT_RATE) } open var videoSampling: String? { return getParam(.VIDEO_SAMPLING) } open var duration: String? { return getParam(.DURATION) } open var startOffset: String? { return getParam(.START_OFFSET) } open var endOffset: String? { return getParam(.END_OFFSET) } open var offset: [String]? { guard let start = startOffset, let end = endOffset else { return nil } return [start, end] } open var videoCodec: String? { return getParam(.VIDEO_CODEC) } fileprivate func getParam(_ param: TransformationParam) -> String? { return getParam(param.rawValue) } open func getParam(_ param: String) -> String? { return currentTransformationParams[param] } // MARK: - Set Values /** Set the image width. - parameter width: The width to set. - returns: The same instance of CLDTransformation. */ @objc(setWidthWithInt:) @discardableResult open func setWidth(_ width: Int) -> CLDTransformation { return setWidth(String(width)) } /** Set the image width. - parameter width: The width to set. - returns: The same instance of CLDTransformation. */ @objc(setWidthWithFloat:) @discardableResult open func setWidth(_ width: Float) -> CLDTransformation { return setWidth(width.cldFloatFormat()) } /** Set the image width. - parameter width: The width to set. - returns: The same instance of CLDTransformation. */ @discardableResult open func setWidth(_ width: String) -> CLDTransformation { return setParam(TransformationParam.WIDTH, value: width) } /** Set the image height. - parameter height: The height to set. - returns: The same instance of CLDTransformation. */ @objc(setHeightWithInt:) @discardableResult open func setHeight(_ height: Int) -> CLDTransformation { return setHeight(String(height)) } /** Set the image height. - parameter height: The height to set. - returns: The same instance of CLDTransformation. */ @objc(setHeightWithFloat:) @discardableResult open func setHeight(_ height: Float) -> CLDTransformation { return setHeight(height.cldFloatFormat()) } /** Set the image height. - parameter height: The height to set. - returns: The same instance of CLDTransformation. */ @discardableResult open func setHeight(_ height: String) -> CLDTransformation { return setParam(TransformationParam.HEIGHT, value: height) } /** A named transformation is a set of image transformations that has been given a custom name for easy reference. It is useful to define a named transformation when you have a set of relatively complex transformations that you use often and that you want to easily reference. - parameter names: The names of the transformations to set. - returns: The same instance of CLDTransformation. */ @objc(setNamedWithArray:) @discardableResult open func setNamed(_ names: [String]) -> CLDTransformation { return setNamed(names.joined(separator: ".")) } /** A named transformation is a set of image transformations that has been given a custom name for easy reference. It is useful to define a named transformation when you have a set of relatively complex transformations that you use often and that you want to easily reference. - parameter names: The names of the transformations to set. - returns: The same instance of CLDTransformation. */ @discardableResult open func setNamed(_ names: String) -> CLDTransformation { return setParam(TransformationParam.NAMED, value: names) } /** Set the image crop. - parameter crop: The crop to set. - returns: The same instance of CLDTransformation. */ @objc(setCropWithCrop:) @discardableResult open func setCrop(_ crop: CLDCrop) -> CLDTransformation { return setCrop(String(describing: crop)) } /** Set the image crop. - parameter crop: The crop to set. - returns: The same instance of CLDTransformation. */ @discardableResult open func setCrop(_ crop: String) -> CLDTransformation { return setParam(TransformationParam.CROP, value: crop) } /** Defines the background color to use instead of transparent background areas when converting to JPG format or using the pad crop mode. The background color can be set as an RGB hex triplet (e.g. '#3e2222'), a 3 character RGB hex (e.g. '#777') or a named color (e.g. 'green'). - parameter background: The background color to set. - returns: The same instance of CLDTransformation. */ @discardableResult open func setBackground(_ background: String) -> CLDTransformation { return setParam(TransformationParam.BACKGROUND, value: background.replacingOccurrences(of: "#", with: "rgb:")) } /** Customize the color to use together with: text captions, the shadow effect and the colorize effect. The color can be set as an RGB hex triplet (e.g. '#3e2222'), a 3 character RGB hex (e.g. '#777') or a named color (e.g. 'green'). - parameter color: The color to set. - returns: The same instance of CLDTransformation. */ @discardableResult open func setColor(_ color: String) -> CLDTransformation { return setParam(TransformationParam.COLOR, value: color.replacingOccurrences(of: "#", with: "rgb:")) } /** Apply a filter or an effect on an image. - parameter effect: The effect to apply. - returns: The same instance of CLDTransformation. */ @objc(setEffectWithEffect:) @discardableResult open func setEffect(_ effect: CLDEffect) -> CLDTransformation { return setEffect(String(describing: effect)) } /** Apply a filter or an effect on an image. The value includes the name of the effect and an additional parameter that controls the behavior of the specific effect. - parameter effect: The effect to apply. - parameter effectParam: The effect value to apply. - returns: The same instance of CLDTransformation. */ @objc(setEffectWithEffect:param:) @discardableResult open func setEffect(_ effect: CLDEffect, param: String) -> CLDTransformation { return setEffect(String(describing: effect), param: param) } /** Apply a filter or an effect on an image. The value includes the name of the effect and an additional parameter that controls the behavior of the specific effect. - parameter effect: The effect to apply. - parameter effectParam: The effect value to apply. - returns: The same instance of CLDTransformation. */ @discardableResult open func setEffect(_ effect: String, param: String) -> CLDTransformation { return setEffect("\(effect):\(param)") } /** Apply a filter or an effect on an image. - parameter effect: The effect to apply. - returns: The same instance of CLDTransformation. */ @discardableResult open func setEffect(_ effect: String) -> CLDTransformation { return setParam(TransformationParam.EFFECT, value: effect) } /** Rotate or flip an image by the given degrees or automatically according to its orientation or available meta-data. - parameter angle: The angle to rotate. - returns: The same instance of CLDTransformation. */ @objc(setAngleWithInt:) @discardableResult open func setAngle(_ angle: Int) -> CLDTransformation { return setAngle(String(angle)) } /** Rotate or flip an image by the given degrees or automatically according to its orientation or available meta-data. - parameter angles: The angles to rotate. - returns: The same instance of CLDTransformation. */ @objc(setAngleWithArray:) @discardableResult open func setAngle(_ angles: [String]) -> CLDTransformation { return setAngle(angles.joined(separator: ".")) } /** Rotate or flip an image by the given degrees or automatically according to its orientation or available meta-data. - parameter angle: The angle to rotate. - returns: The same instance of CLDTransformation. */ @discardableResult open func setAngle(_ angles: String) -> CLDTransformation { return setParam(TransformationParam.ANGLE, value: angles) } /** Adjust the opacity of the image and make it semi-transparent. 100 means opaque, while 0 is completely transparent. - parameter opacity: The opacity level to apply. - returns: The same instance of CLDTransformation. */ @objc(setOpacityWithInt:) @discardableResult open func setOpacity(_ opacity: Int) -> CLDTransformation { return setOpacity(String(opacity)) } /** Adjust the opacity of the image and make it semi-transparent. 100 means opaque, while 0 is completely transparent. - parameter opacity: The opacity level to apply. - returns: The same instance of CLDTransformation. */ @discardableResult open func setOpacity(_ opacity: String) -> CLDTransformation { return setParam(TransformationParam.OPACITY, value: opacity) } /** Add a solid border around the image. - parameter width: The border width. - parameter color: The border color. - returns: The same instance of CLDTransformation. */ @discardableResult open func setBorder(_ width: Int, color: String) -> CLDTransformation { return setBorder("\(width)px_solid_\(color)") } /** Add a solid border around the image. Should conform to the form: [width]px_solid_[color], e.g - 5px_solid_#111111 or 5px_solid_red - parameter border: The border to add. - returns: The same instance of CLDTransformation. */ @discardableResult open func setBorder(_ border: String) -> CLDTransformation { return setParam(TransformationParam.BORDER, value: border.replacingOccurrences(of: "#", with: "rgb:")) } /** Horizontal position for custom-coordinates based cropping, overlay placement and certain region related effects. - parameter x: The x position to add. - returns: The same instance of CLDTransformation. */ @objc(setXFromInt:) @discardableResult open func setX(_ x: Int) -> CLDTransformation { return setX(String(x)) } /** Horizontal position for custom-coordinates based cropping, overlay placement and certain region related effects. - parameter x: The x position to add. - returns: The same instance of CLDTransformation. */ @objc(setXFromFloat:) @discardableResult open func setX(_ x: Float) -> CLDTransformation { return setX(x.cldFloatFormat()) } /** Horizontal position for custom-coordinates based cropping, overlay placement and certain region related effects. - parameter x: The x position to add. - returns: The same instance of CLDTransformation. */ @discardableResult open func setX(_ x: String) -> CLDTransformation { return setParam(TransformationParam.X, value: x) } /** Vertical position for custom-coordinates based cropping and overlay placement. - parameter y: The y position to add. - returns: The same instance of CLDTransformation. */ @objc(setYFromInt:) @discardableResult open func setY(_ y: Int) -> CLDTransformation { return setY(String(y)) } /** Vertical position for custom-coordinates based cropping and overlay placement. - parameter y: The y position to add. - returns: The same instance of CLDTransformation. */ @objc(setYFromFloat:) @discardableResult open func setY(_ y: Float) -> CLDTransformation { return setY(y.cldFloatFormat()) } /** Vertical position for custom-coordinates based cropping and overlay placement. - parameter y: The y position to add. - returns: The same instance of CLDTransformation. */ @discardableResult open func setY(_ y: String) -> CLDTransformation { return setParam(TransformationParam.Y, value: y) } /** Round the corners of an image or make it completely circular or oval (ellipse). - parameter radius: The radius to apply. - returns: The same instance of CLDTransformation. */ @objc(setRadiusFromInt:) @discardableResult open func setRadius(_ radius: Int) -> CLDTransformation { return setRadius(String(radius)) } /** Round the corners of an image or make it completely circular or oval (ellipse). - parameter radius: The radius to apply. - returns: The same instance of CLDTransformation. */ @discardableResult open func setRadius(_ radius: String) -> CLDTransformation { return setParam(TransformationParam.RADIUS, value: radius) } /** Control the JPEG, WebP, GIF, JPEG XR and JPEG 2000 compression quality. 1 is the lowest quality and 100 is the highest. Reducing quality generates JPG images much smaller in file size. The default values are: * JPEG: 90 * WebP: 80 (100 quality for WebP is lossless) * GIF: lossless by default. 80 if the `lossy` flag is added * JPEG XR and JPEG 2000: 70 - parameter quality: The quality to apply. - returns: The same instance of CLDTransformation. */ @objc(setQualityFromInt:) @discardableResult open func setQuality(_ quality: Int) -> CLDTransformation { return setQuality(String(quality)) } /** Control the JPEG, WebP, GIF, JPEG XR and JPEG 2000 compression quality. 1 is the lowest quality and 100 is the highest. Reducing quality generates JPG images much smaller in file size. The default values are: * JPEG: 90 * WebP: 80 (100 quality for WebP is lossless) * GIF: lossless by default. 80 if the `lossy` flag is added * JPEG XR and JPEG 2000: 70 - parameter quality: The quality to apply. - returns: The same instance of CLDTransformation. */ @discardableResult open func setQuality(_ quality: String) -> CLDTransformation { return setParam(TransformationParam.QUALITY, value: quality) } /** Specify the public ID of a placeholder image to use if the requested image or social network picture does not exist. - parameter defaultImage: The identifier of the default image. - returns: The same instance of CLDTransformation. */ @discardableResult open func setDefaultImage(_ defaultImage: String) -> CLDTransformation { return setParam(TransformationParam.DEFAULT_IMAGE, value: defaultImage) } /** Decides which part of the image to keep while 'crop', 'pad' and 'fill' crop modes are used. - parameter gravity: The gravity to apply. - returns: The same instance of CLDTransformation. */ @objc(setGravityWithGravity:) @discardableResult open func setGravity(_ gravity: CLDGravity) -> CLDTransformation { return setGravity(String(describing: gravity)) } /** Decides which part of the image to keep while 'crop', 'pad' and 'fill' crop modes are used. - parameter gravity: The gravity to apply. - returns: The same instance of CLDTransformation. */ @discardableResult open func setGravity(_ gravity: String) -> CLDTransformation { return setParam(TransformationParam.GRAVITY, value: gravity) } /** Set the transformation color space. - parameter colorSpace: The color space to set. - returns: The same instance of CLDTransformation. */ @discardableResult open func setColorSpace(_ colorSpace: String) -> CLDTransformation { return setParam(TransformationParam.COLOR_SPACE, value: colorSpace) } /** Set the transformation prefix. - parameter prefix: The prefix to set. - returns: The same instance of CLDTransformation. */ @discardableResult open func setPrefix(_ prefix: String) -> CLDTransformation { return setParam(TransformationParam.PREFIX, value: prefix) } /** Add an overlay over the base image. You can control the dimension and position of the overlay using the width, height, x, y and gravity parameters. The overlay can take one of the following forms: identifier can be a public ID of an uploaded image or a specific image kind, public ID and settings. **You can use the convenience method `addOverlayWithLayer`** - parameter overlay: The overlay to set. - returns: The same instance of CLDTransformation. */ @discardableResult open func setOverlay(_ overlay: String) -> CLDTransformation { return setParam(TransformationParam.OVERLAY, value: overlay) } /** Add an underlay image below a base partially-transparent image. You can control the dimensions and position of the underlay using the width, height, x, y and gravity parameters. The identifier can be a public ID of an uploaded image or a specific image kind, public ID and settings. The underlay parameter shares the same features as the overlay parameter. **You can use the convenience method `addUnderlayWithLayer`** - parameter underlay: The underlay to set. - returns: The same instance of CLDTransformation. */ @discardableResult open func setUnderlay(_ underlay: String) -> CLDTransformation { return setParam(TransformationParam.UNDERLAY, value: underlay) } /** Force format conversion to the given image format for remote 'fetch' URLs and auto uploaded images that already have a different format as part of their URLs. - parameter fetchFormat: The fetchFormat to set. - returns: The same instance of CLDTransformation. */ @discardableResult open func setFetchFormat(_ fetchFormat: String) -> CLDTransformation { return setParam(TransformationParam.FETCH_FORMAT, value: fetchFormat) } /** Control the density to use while converting a PDF document to images. (range: 50-300, default is 150) - parameter density: The density to use. - returns: The same instance of CLDTransformation. */ @objc(setDensityWithInt:) @discardableResult open func setDensity(_ density: Int) -> CLDTransformation { return setDensity(String(density)) } /** Control the density to use while converting a PDF document to images. (range: 50-300, default is 150) - parameter density: The density to use. - returns: The same instance of CLDTransformation. */ @discardableResult open func setDensity(_ density: String) -> CLDTransformation { return setParam(TransformationParam.DENSITY, value: density) } /** Given a multi-page file (PDF, animated GIF, TIFF), generate an image of a single page using the given index. - parameter page: The index of the page to use to use. - returns: The same instance of CLDTransformation. */ @objc(setPageWithInt:) @discardableResult open func setPage(_ page: Int) -> CLDTransformation { return setPage(String(page)) } /** Given a multi-page file (PDF, animated GIF, TIFF), generate an image of a single page using the given index. - parameter page: The index of the page to use to use. - returns: The same instance of CLDTransformation. */ @discardableResult open func setPage(_ page: String) -> CLDTransformation { return setParam(TransformationParam.PAGE, value: page) } /** Controls the time delay between the frames of an animated image, in milliseconds. - parameter delay: The delay between the frames of an animated image, in milliseconds. - returns: The same instance of CLDTransformation. */ @objc(setDelayWithInt:) @discardableResult open func setDelay(_ delay: Int) -> CLDTransformation { return setDelay(String(delay)) } /** Controls the time delay between the frames of an animated image, in milliseconds. - parameter delay: The delay between the frames of an animated image, in milliseconds. - returns: The same instance of CLDTransformation. */ @discardableResult open func setDelay(_ delay: String) -> CLDTransformation { return setParam(TransformationParam.DELAY, value: delay) } /** Add a raw transformation, it will be appended to the other transformation parameter. the transformation must conform to [Cloudinary's transformation documentation](http://cloudinary.com/documentation/image_transformation_reference) - parameter rawTransformation: The raw transformation to add. - returns: The same instance of CLDTransformation. */ @discardableResult open func setRawTransformation(_ rawTransformation: String) -> CLDTransformation { return setParam(TransformationParam.RAW_TRANSFORMATION, value: rawTransformation) } /** Set one or more flags that alter the default transformation behavior. - parameter flags: An array of the flags to apply. - returns: The same instance of CLDTransformation. */ @objc(setFlagsWithArray:) @discardableResult open func setFlags(_ flags: [String]) -> CLDTransformation { return setFlags(flags.joined(separator: ".")) } /** Set one or more flags that alter the default transformation behavior. - parameter flags: An array of the flags to apply. - returns: The same instance of CLDTransformation. */ @discardableResult open func setFlags(_ flags: String) -> CLDTransformation { return setParam(TransformationParam.FLAGS, value: flags) } /** Deliver the image in the specified device pixel ratio. - parameter dpr: The DPR ot set. - returns: The same instance of CLDTransformation. */ @objc(setDprWithFloat:) @discardableResult open func setDpr(_ dpr: Float) -> CLDTransformation { return setDpr(dpr.cldFloatFormat()) } /** Deliver the image in the correct device pixel ratio, according to the used device. - returns: The same instance of CLDTransformation. */ @discardableResult open func setDprAuto() -> CLDTransformation { let scale = Float(UIScreen.main.scale) return setDpr(scale) } /** Deliver the image in the specified device pixel ratio. The parameter accepts any positive float value. - parameter dpr: The DPR ot set. - returns: The same instance of CLDTransformation. */ @discardableResult open func setDpr(_ dpr: String) -> CLDTransformation { return setParam(TransformationParam.DPR, value: dpr) } /** Control how much of the original image surrounding the face to keep when using either the 'crop' or 'thumb' cropping modes with face detection. default is 1.0. - parameter zoom: The zoom ot set. - returns: The same instance of CLDTransformation. */ @objc(setZoomWithFloat:) @discardableResult open func setZoom(_ zoom: Float) -> CLDTransformation { return setZoom(zoom.cldFloatFormat()) } /** Control how much of the original image surrounding the face to keep when using either the 'crop' or 'thumb' cropping modes with face detection. default is 1.0. - parameter zoom: The zoom ot set. - returns: The same instance of CLDTransformation. */ @discardableResult open func setZoom(_ zoom: String) -> CLDTransformation { return setParam(TransformationParam.ZOOM, value: zoom) } /** Resize or crop the image to a new aspect ratio using a nominator and dominator (e.g. 16 and 9 for 16:9). This parameter is used together with a specified crop mode that determines how the image is adjusted to the new dimensions. - parameter nominator: The nominator ot use. - parameter dominator: The dominator ot use. - returns: The same instance of CLDTransformation. */ @discardableResult open func setAspectRatio(nominator: Int, denominator: Int) -> CLDTransformation { return setAspectRatio("\(nominator):\(denominator)") } /** Resize or crop the image to a new aspect ratio. This parameter is used together with a specified crop mode that determines how the image is adjusted to the new dimensions. - parameter aspectRatio: The aspect ratio ot use. - returns: The same instance of CLDTransformation. */ @objc(setAspectRatioWithFloat:) @discardableResult open func setAspectRatio(_ aspectRatio: Float) -> CLDTransformation { return setAspectRatio(aspectRatio.cldFloatFormat()) } /** Resize or crop the image to a new aspect ratio. This parameter is used together with a specified crop mode that determines how the image is adjusted to the new dimensions. - parameter aspectRatio: The aspect ratio ot use. - returns: The same instance of CLDTransformation. */ @discardableResult open func setAspectRatio(_ aspectRatio: String) -> CLDTransformation { return setParam(TransformationParam.ASPECT_RATIO, value: aspectRatio) } /** Use the audio_codec parameter to set the audio codec or remove the audio channel completely as follows: * **none** removes the audio channel * **aac** (mp4 or flv only) * **vorbis** (ogv or webm only) * **mp3** (mp4 or flv only) - parameter audioCodec: The audio codec ot set. - returns: The same instance of CLDTransformation. */ @discardableResult open func setAudioCodec(_ audioCodec: String) -> CLDTransformation { return setParam(TransformationParam.AUDIO_CODEC, value: audioCodec) } /** Use the audio_frequency parameter to control the audio sampling frequency. This parameter represents an integer value in Hz. See the documentation in the [Video transformations reference table](http://cloudinary.com/documentation/video_manipulation_and_delivery#video_transformations_reference) for the possible values. - parameter audioFrequency: The audio frequency ot set. - returns: The same instance of CLDTransformation. */ @objc(setAudioFrequencyWithInt:) @discardableResult open func setAudioFrequency(_ audioFrequency: Int) -> CLDTransformation { return setAudioFrequency(String(audioFrequency)) } /** Use the audio_frequency parameter to control the audio sampling frequency. This parameter represents an integer value in Hz. See the documentation in the [Video transformations reference table](http://cloudinary.com/documentation/video_manipulation_and_delivery#video_transformations_reference) for the possible values. - parameter audioFrequency: The audio frequency ot set. - returns: The same instance of CLDTransformation. */ @discardableResult open func setAudioFrequency(_ audioFrequency: String) -> CLDTransformation { return setParam(TransformationParam.AUDIO_FREQUENCY, value: audioFrequency) } /** Use the bit_rate parameter for advanced control of the video bit rate. This parameter controls the number of bits used to represent the video data. The higher the bit rate, the higher the visual quality of the video, but the larger the file size as well. - parameter bitRate: The bit rate ot set. - returns: The same instance of CLDTransformation. */ @objc(setBitRateWithInt:) @discardableResult open func setBitRate(_ bitRate: Int) -> CLDTransformation { return setBitRate(String(bitRate)) } /** Use the bit_rate parameter for advanced control of the video bit rate. This parameter controls the number of bits used to represent the video data. The higher the bit rate, the higher the visual quality of the video, but the larger the file size as well. - parameter bitRate: The bit rate ot set in kilobytes. - returns: The same instance of CLDTransformation. */ @discardableResult open func setBitRate(kb bitRate: Int) -> CLDTransformation { return setBitRate("\(bitRate)k") } /** Use the bit_rate parameter for advanced control of the video bit rate. This parameter controls the number of bits used to represent the video data. The higher the bit rate, the higher the visual quality of the video, but the larger the file size as well. Bit rate can take one of the following values: * An integer e.g. 120000. * A string supporting ‘k’ and ‘m’ (kilobits and megabits respectively) e.g. 500k or 2m. - parameter bitRate: The bit rate ot set. - returns: The same instance of CLDTransformation. */ @discardableResult open func setBitRate(_ bitRate: String) -> CLDTransformation { return setParam(TransformationParam.BIT_RATE, value: bitRate) } /** The total number of frames to sample from the original video. The frames are spread out over the length of the video, e.g. 20 takes one frame every 5%. - parameter frames: The video sampling frames ot set. - returns: The same instance of CLDTransformation. */ @discardableResult open func setVideoSampling(frames: Int) -> CLDTransformation { return setVideoSampling(String(frames)) } /** Controls the time delay between the frames of an animated image, in milliseconds. - parameter delay: The delay ot set in milliseconds. - returns: The same instance of CLDTransformation. */ @discardableResult open func setVideoSampling(delay: Float) -> CLDTransformation { return setVideoSampling("\(delay.cldFloatFormat())s") } /** Relevant for conversion of video to animated GIF or WebP. If not specified, the resulting GIF or WebP samples the whole video (up to 400 frames, at up to 10 frames per second). By default the duration of the animated image is the same as the duration of the video, no matter how many frames are sampled from the original video (use the delay parameter to adjust the amount of time between frames). - parameter videoSampling: The video sampling ot set. - returns: The same instance of CLDTransformation. */ @discardableResult open func setVideoSampling(_ videoSampling: String) -> CLDTransformation { return setParam(TransformationParam.VIDEO_SAMPLING, value: videoSampling) } /** Offset in seconds or percent of a video, normally used together with the start_offset and end_offset parameters. Used to specify: * The duration the video displays. * The duration an overlay displays. - parameter seconds: The duration to set in seconds. - returns: The same instance of CLDTransformation. */ @discardableResult open func setDuration(seconds: Float) -> CLDTransformation { return setDuration(seconds.cldFloatFormat()) } /** Offset in seconds or percent of a video, normally used together with the start_offset and end_offset parameters. Used to specify: * The duration the video displays. * The duration an overlay displays. - parameter percent: The duration percent to set. - returns: The same instance of CLDTransformation. */ @discardableResult open func setDuration(percent: Int) -> CLDTransformation { return setDuration("\(percent)p") } /** Offset in seconds or percent of a video, normally used together with the start_offset and end_offset parameters. Used to specify: * The duration the video displays. * The duration an overlay displays. - parameter duration: The duration to set in seconds. - returns: The same instance of CLDTransformation. */ @discardableResult open func setDuration(_ duration: String) -> CLDTransformation { return setParam(TransformationParam.DURATION, value: duration) } /** Set an offset in seconds to cut a video at the start. - parameter seconds: The start time to set. - returns: The same instance of CLDTransformation. */ @discardableResult open func setStartOffset(seconds: Float) -> CLDTransformation { return setStartOffset(seconds.cldFloatFormat()) } /** Set an offset in percent to cut a video at the start. - parameter percent: The percent of time to cut. - returns: The same instance of CLDTransformation. */ @discardableResult open func setStartOffset(percent: Int) -> CLDTransformation { return setStartOffset("\(percent)p") } /** Set an offset in seconds or percent of a video to cut a video at the start. - parameter duration: The start time to set. - returns: The same instance of CLDTransformation. */ @discardableResult open func setStartOffset(_ duration: String) -> CLDTransformation { return setParam(TransformationParam.START_OFFSET, value: duration) } /** Set an offset in seconds to cut a video at the end. - parameter seconds: The end time to set. - returns: The same instance of CLDTransformation. */ @discardableResult open func setEndOffset(seconds: Float) -> CLDTransformation { return setEndOffset(seconds.cldFloatFormat()) } /** Set an offset in percent to cut a video at the end. - parameter percent: The percent of time to cut. - returns: The same instance of CLDTransformation. */ @discardableResult open func setEndOffset(percent: Int) -> CLDTransformation { return setEndOffset("\(percent)p") } /** Set an offset in seconds or percent of a video to cut a video at the end. - parameter duration: The end time to set. - returns: The same instance of CLDTransformation. */ @discardableResult open func setEndOffset(_ duration: String) -> CLDTransformation { return setParam(TransformationParam.END_OFFSET, value: duration) } /** Used to determine the video codec, video profile and level to use. You can set this parameter to auto instead. - parameter videoCodec: The video codec to set. - parameter videoProfile: The video profile to set. - parameter level: The level to set. - returns: The same instance of CLDTransformation. */ @discardableResult open func setVideoCodecAndProfileAndLevel(_ videoCodec: String, videoProfile: String, level: String? = nil) -> CLDTransformation { return level == nil ? setVideoCodec("\(videoCodec):\(videoProfile)") : setVideoCodec("\(videoCodec):\(videoProfile):\(level!)") } /** Used to determine the video codec to use. You can set this parameter to auto instead. - parameter videoCodec: The video codec to set. - returns: The same instance of CLDTransformation. */ @discardableResult open func setVideoCodec(_ videoCodec: String) -> CLDTransformation { return setParam(TransformationParam.VIDEO_CODEC, value: videoCodec) } // MARK: Setters fileprivate func setParam(_ key: TransformationParam, value: String) -> CLDTransformation { return setParam(key.rawValue, value: value) } @discardableResult open func setParam(_ key: String, value: String) -> CLDTransformation { currentTransformationParams[key] = value return self } // MARK: - Convenience /** A convenience method to set video cutting in seconds. Must provide an array with exactly 2 values: 1. start offset. 2. end offset. - parameter seconds: The array of both start and end offsets to set. - returns: The same instance of CLDTransformation. */ func setOffset(seconds: [Float]) -> CLDTransformation { guard let start = seconds.first, let end = seconds.last else { return self } return setOffset([start.cldFloatFormat(), end.cldFloatFormat()]) } /** A convenience method to set video cutting in percent. Must provide an array with exactly 2 values: 1. start offset. 2. end offset. - parameter seconds: The array of both start and end offsets to set. - returns: The same instance of CLDTransformation. */ func setOffset(percents: [Int]) -> CLDTransformation { guard let start = percents.first, let end = percents.last else { return self } return setOffset(["\(start)p", "\(end)p"]) } /** A convenience method to set video cutting in seconds or percent. Should provide an array with 2 values: 1. start offset. 2. end offset. Or one value for both. - parameter seconds: The array of both start and end offsets to set. - returns: The same instance of CLDTransformation. */ func setOffset(_ durations: [String]) -> CLDTransformation { guard let start = durations.first, let end = durations.last else { return self } setStartOffset(start) setEndOffset(end) return self } /** Shortcut to set video cutting in seconds using a combination of start_offset and end_offset values. - parameter startSeconds: The start time to set. - parameter endSeconds: The end time to set. - returns: The same instance of CLDTransformation. */ @discardableResult open func setStartOffsetAndEndOffset(startSeconds: Float, endSeconds: Float) -> CLDTransformation { setStartOffset(seconds: startSeconds) setEndOffset(seconds: endSeconds) return self } /** Shortcut to set video cutting in percent of video using a combination of start_offset and end_offset values. - parameter startPercent: The start time to set. - parameter endPercent: The end time to set. - returns: The same instance of CLDTransformation. */ @discardableResult open func setStartOffsetAndEndOffset(startPercent: Int, endPercent: Int) -> CLDTransformation { setStartOffset(percent: startPercent) setEndOffset(percent: endPercent) return self } /** Set an overlay using the helper class CLDLayer. - parameter layer: The layer to add as an overlay. - returns: The same instance of CLDTransformation. */ @discardableResult open func setOverlayWithLayer(_ layer: CLDLayer) -> CLDTransformation { if let layerString = layer.asString() { return setOverlay(layerString) } else { return setOverlay("") } } /** Set an underlay using the helper class CLDLayer. - parameter layer: The layer to add as an underlay. - returns: The same instance of CLDTransformation. */ @discardableResult open func setUnderlayWithLayer(_ layer: CLDLayer) -> CLDTransformation { if let layerString = layer.asString() { return setUnderlay(layerString) } else { return setUnderlay("") } } /** A convenience method to set the transformation X and Y parameters. - parameter point: The top left pont to set. - returns: The same instance of CLDTransformation. */ @discardableResult open func setTopLeftPoint(_ point: CGPoint) -> CLDTransformation { setX(Float(point.x)) return setY(Float(point.y)) } // MARK: - Actions /** Cloudinary supports powerful image transformations that are applied on the fly using dynamic URLs, and you can also combine multiple transformations together as part of a single delivery request, e.g. crop an image and then add a border. In certain cases you may want to perform additional transformations on the result of a single transformation request. In order to do that, you can chain the transformations together. In practice, the chain allows you to start seting properties to a new transformation, which will be chained to the transformation you worked on, even though you still use the same CLDTransformation instance. - returns: The same instance of CLDTransformation. */ @discardableResult open func chain() -> Self { transformations.append(currentTransformationParams) currentTransformationParams = [:] return self } internal func asString() -> String? { chain() var components: [String] = [] for params in self.transformations { if let singleTransStringRepresentation = self.getStringRepresentationFromParams(params) { components.append(singleTransStringRepresentation) } else { return nil } } return components.joined(separator: "/") } // MARK: - Private fileprivate func getStringRepresentationFromParams(_ params: [String : String]) -> String? { let emptyParams = params.filter{$0.0.isEmpty || $0.1.isEmpty} if emptyParams.count > 0 { printLog(.error, text: "An empty string key or value are not allowed.") return nil } var components: [String] = params.sorted{$0.0 < $1.0} .filter{$0.0 != TransformationParam.RAW_TRANSFORMATION.rawValue && !$0.1.isEmpty} .map{"\($0)_\($1)"} if let rawTrans = params[TransformationParam.RAW_TRANSFORMATION.rawValue] , !rawTrans.isEmpty { components.append(rawTrans) } return components.joined(separator: ",") } // MARK: - Params internal enum TransformationParam: String { case WIDTH = "w" case HEIGHT = "h" case NAMED = "t" case CROP = "c" case BACKGROUND = "b" case COLOR = "co" case EFFECT = "e" case ANGLE = "a" case OPACITY = "o" case BORDER = "bo" case X = "x" case Y = "y" case RADIUS = "r" case QUALITY = "q" case DEFAULT_IMAGE = "d" case GRAVITY = "g" case COLOR_SPACE = "cs" case PREFIX = "p" case OVERLAY = "l" case UNDERLAY = "u" case FETCH_FORMAT = "f" case DENSITY = "dn" case PAGE = "pg" case DELAY = "dl" case FLAGS = "fl" case DPR = "dpr" case ZOOM = "z" case ASPECT_RATIO = "ar" case AUDIO_CODEC = "ac" case AUDIO_FREQUENCY = "af" case BIT_RATE = "br" case VIDEO_SAMPLING = "vs" case DURATION = "du" case START_OFFSET = "so" case END_OFFSET = "eo" case VIDEO_CODEC = "vc" case RAW_TRANSFORMATION = "raw_transformation" } // MARK: Crop @objc public enum CLDCrop: Int, CustomStringConvertible { case fill, crop, scale, fit, limit, mFit, lFill, pad, lPad, mPad, thumb, imaggaCrop, imaggaScale public var description: String { get { switch self { case .fill: return "fill" case .crop: return "crop" case .scale: return "scale" case .fit: return "fit" case .limit: return "limit" case .mFit: return "mfit" case .lFill: return "lfill" case .pad: return "pad" case .lPad: return "lpad" case .mPad: return "mpad" case .thumb: return "thumb" case .imaggaCrop: return "imagga_crop" case .imaggaScale: return "imagga_scale" } } } } // MARK: Effect @objc public enum CLDEffect: Int, CustomStringConvertible { case hue, red, green, blue, negate, brightness, sepia, grayscale, blackwhite, saturation, colorize, contrast, autoContrast, vibrance, autoColor, improve, autoBrightness, fillLight, viesusCorrect, gamma, screen, multiply, overlay, makeTransparent, trim, shadow, distort, shear, displace, oilPaint, redeye, advRedeye, vignette, gradientFade, pixelate, pixelateRegion, pixelateFaces, blur, blurRegion, blurFaces, sharpen, unsharpMask, orderedDither public var description: String { get { switch self { case .hue: return "hue" case .red: return "red" case .green: return "green" case .blue: return "blue" case .negate: return "negate" case .brightness: return "brightness" case .sepia: return "sepia" case .grayscale: return "grayscale" case .blackwhite: return "blackwhite" case .saturation: return "saturation" case .colorize: return "colorize" case .contrast: return "contrast" case .autoContrast: return "auto_contrast" case .vibrance: return "vibrance" case .autoColor: return "auto_color" case .improve: return "improve" case .autoBrightness: return "auto_brightness" case .fillLight: return "fill_light" case .viesusCorrect: return "viesus_correct" case .gamma: return "gamma" case .screen: return "screen" case .multiply: return "multiply" case .overlay: return "overlay" case .makeTransparent: return "make_transparent" case .trim: return "trim" case .shadow: return "shadow" case .distort: return "distort" case .shear: return "shear" case .displace: return "displace" case .oilPaint: return "oil_paint" case .redeye: return "redeye" case .advRedeye: return "adv_redeye" case .vignette: return "vignette" case .gradientFade: return "gradient_fade" case .pixelate: return "pixelate" case .pixelateRegion: return "pixelate_region" case .pixelateFaces: return "pixelate_faces" case .blur: return "blur" case .blurRegion: return "blur_region" case .blurFaces: return "blur_faces" case .sharpen: return "sharpen" case .unsharpMask: return "unsharp_mask" case .orderedDither: return "ordered_dither" } } } } // MARK: Gravity @objc public enum CLDGravity: Int, CustomStringConvertible { case center, face, faceCenter, faces, facesCenter, advFace, advFaces, advEyes, north, northWest, northEast, south, southWest, southEast, east, west, xyCenter, custom, customFace, customFaces, customAdvFace, customAdvFaces public var description: String { get { switch self { case .center: return "center" case .face: return "face" case .faceCenter: return "faceCenter" case .faces: return "faces" case .facesCenter: return "facesCenter" case .advFace: return "adv_face" case .advFaces: return "adv_faces" case .advEyes: return "adv_eyes" case .north: return "north" case .northWest: return "north_west" case .northEast: return "north_east" case .south: return "south" case .southWest: return "south_west" case .southEast: return "south_east" case .west: return "west" case .east: return "east" case .xyCenter: return "xy_center" case .custom: return "custom" case .customFace: return "custom:face" case .customFaces: return "custom:faces" case .customAdvFace: return "custom:adv_face" case .customAdvFaces: return "custom:adv_faces" } } } } }
mit
b4fdc010ac68ac4afcdcb9cd37d71d60
34.91897
453
0.598657
4.99633
false
false
false
false
devxoul/URLNavigator
Tests/URLNavigatorTests/TopMostViewControllerSpec.swift
1
7689
#if os(iOS) || os(tvOS) import UIKit import Nimble import Quick import URLNavigator final class TopMostViewControllerSpec: QuickSpec { fileprivate static var currentWindow: UIWindow? override func spec() { var window: UIWindow! var topMost: UIViewController? { return UIViewController.topMost(of: window.rootViewController) } beforeEach { window = UIWindow(frame: UIScreen.main.bounds) TopMostViewControllerSpec.currentWindow = window } context("when the root view controller is a view controller") { context("when there is only a root view controller") { it("returns root view controller") { let viewController = UIViewController().asRoot() expect(topMost) == viewController } } context("when there is a presented view controller") { it("returns a presented view controller") { let A = UIViewController("A").asRoot() let B = UIViewController("B") A.present(B, animated: false, completion: nil) expect(topMost) == B } } context("when there is a presented tab bar controller") { it("returns the selected view controller of the presented tab bar controller") { let A = UIViewController("A").asRoot() let B = UIViewController("B") let C = UIViewController("C") let tabBarController = UITabBarController() tabBarController.viewControllers = [B, C] tabBarController.selectedIndex = 1 A.present(tabBarController, animated: false, completion: nil) expect(topMost) == C } } context("when there is a presented navigation controller") { it("returns a top view controller of the presented navigation controller") { let A = UIViewController("A").asRoot() let B = UIViewController("B") let C = UIViewController("C") let D = UIViewController("D") let navigationController = UINavigationController(rootViewController: B) navigationController.pushViewController(C, animated: false) navigationController.pushViewController(D, animated: false) A.present(navigationController, animated: false, completion: nil) expect(topMost) == D } } context("when there is a presented page view controller") { it("returns the selected view controller of the presented page view controller") { let A = UIViewController("A").asRoot() let B = UIViewController("B") let pageViewController = UIPageViewController() pageViewController.setViewControllers([B], direction: .forward, animated: false, completion: nil) A.present(pageViewController, animated: false, completion: nil) expect(topMost) == B } } } context("when the root view controller is a tab bar controller") { context("when there is no view controller") { it("returns the tab bar controller") { let tabBarController = UITabBarController().asRoot() expect(topMost) == tabBarController } } context("when there is a single view controller") { it("returns the only view controller") { let A = UIViewController("A") let tabBarController = UITabBarController().asRoot() tabBarController.viewControllers = [A] expect(topMost) == A } } context("when there are multiple view controllers") { it("returns the selected view controller of the tab bar controller") { let A = UIViewController("A") let B = UIViewController("B") let C = UIViewController("C") let tabBarController = UITabBarController().asRoot() tabBarController.viewControllers = [A, B, C] tabBarController.selectedIndex = 1 expect(topMost) == B } } context("when a view controller is presented from the view controller in the tab bar controller") { it("returns the presented view controller") { let A = UIViewController("A") let B = UIViewController("B") let C = UIViewController("C") let tabBarController = UITabBarController().asRoot() tabBarController.viewControllers = [A, B, C] tabBarController.selectedIndex = 2 let D = UIViewController("D") C.present(D, animated: false, completion: nil) expect(topMost) == D } } } context("when the root view controller is a navigation controller") { context("when there is no view controller") { it("returns the navigation controller") { let navigationController = UINavigationController().asRoot() expect(topMost) == navigationController } } context("when there is only a root view controller") { it("returns the root view controller of the navigation controller") { let A = UIViewController("A") UINavigationController(rootViewController: A).asRoot() expect(topMost) == A } } context("when there are multiple view controllers") { it("returns the top view controller of the navigation controller") { let A = UIViewController("A") let B = UIViewController("B") let navigationController = UINavigationController(rootViewController: A).asRoot() navigationController.pushViewController(B, animated: false) expect(topMost) == B } } context("when a view controller is presented from the view controller in the navigation controller") { it("returns the presented view controller") { let A = UIViewController("A") let B = UIViewController("B") let C = UIViewController("C") let navigationController = UINavigationController(rootViewController: A).asRoot() navigationController.pushViewController(B, animated: false) navigationController.pushViewController(C, animated: false) let D = UIViewController("D") C.present(D, animated: false, completion: nil) expect(topMost) == D } } } context("when the root view controller is a page view controller") { context("when there is a view controller") { it("returns the visible view controller") { let A = UIViewController("A") let pageViewController = UIPageViewController().asRoot() pageViewController.setViewControllers([A], direction: .forward, animated: false, completion: nil) expect(topMost) == A } } context("when a view controller is presented from the view controller in the page view controller") { it("returns the presented view controller") { let A = UIViewController("A") let B = UIViewController("B") let pageViewController = UIPageViewController().asRoot() pageViewController.setViewControllers([A], direction: .forward, animated: false, completion: nil) A.present(B, animated: false, completion: nil) expect(topMost) == B } } } } } extension UIViewController { convenience init(_ title: String) { self.init() self.title = title } override open var description: String { let title = self.title ?? String(format: "0x%x", self) return "<\(type(of: self)): \(title)>" } @discardableResult func asRoot() -> Self { TopMostViewControllerSpec.currentWindow?.rootViewController = self TopMostViewControllerSpec.currentWindow?.addSubview(self.view) return self } } #endif
mit
a5370d122b8d59f1798b43595737eda1
36.144928
108
0.630771
5.10897
false
false
false
false
apple/swift-syntax
Tests/SwiftParserTest/translated/GenericDisambiguationTests.swift
1
5391
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2022 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 // //===----------------------------------------------------------------------===// // This test file has been translated from swift/test/Parse/generic_disambiguation.swift import SwiftSyntax import XCTest final class GenericDisambiguationTests: XCTestCase { func testGenericDisambiguation1() { AssertParse( """ struct A<B> { init(x:Int) {} static func c() {} struct C<D> { static func e() {} } struct F {} } struct B {} struct D {} """ ) } func testGenericDisambiguation2() { AssertParse( """ protocol Runcible {} protocol Fungible {} """ ) } func testGenericDisambiguation3() { AssertParse( """ func meta<T>(_ m: T.Type) {} func meta2<T>(_ m: T.Type, _ x: Int) {} """ ) } func testGenericDisambiguation4() { AssertParse( """ func generic<T>(_ x: T) {} """ ) } func testGenericDisambiguation5() { AssertParse( """ var a, b, c, d : Int """ ) } func testGenericDisambiguation6a() { AssertParse( """ _ = a < b """ ) } func testGenericDisambiguation6b() { AssertParse( """ _ = (a < b, c > d) """ ) } func testGenericDisambiguation6c() { // Parses as generic because of lparen after '>' AssertParse( """ (a < b, c > (d)) """, substructure: Syntax(GenericArgumentListSyntax([ GenericArgumentSyntax( argumentType: TypeSyntax(SimpleTypeIdentifierSyntax( name: .identifier("b"), genericArgumentClause: nil )), trailingComma: .commaToken() ), GenericArgumentSyntax( argumentType: TypeSyntax(SimpleTypeIdentifierSyntax( name: .identifier("c"), genericArgumentClause: nil )), trailingComma: nil ) ])) ) } func testGenericDisambiguation6d() { // Parses as generic because of lparen after '>' AssertParse( """ (a<b, c>(d)) """, substructure: Syntax(GenericArgumentListSyntax([ GenericArgumentSyntax( argumentType: TypeSyntax(SimpleTypeIdentifierSyntax( name: .identifier("b"), genericArgumentClause: nil )), trailingComma: .commaToken() ), GenericArgumentSyntax( argumentType: TypeSyntax(SimpleTypeIdentifierSyntax( name: .identifier("c"), genericArgumentClause: nil )), trailingComma: nil ) ])) ) } func testGenericDisambiguation6e() { AssertParse( """ _ = a>(b) """ ) } func testGenericDisambiguation6f() { AssertParse( """ _ = a > (b) """ ) } func testGenericDisambiguation7() { AssertParse( """ generic<Int>(0) """ ) } func testGenericDisambiguation8() { AssertParse( """ A<B>.c() A<A<B>>.c() A<A<B>.F>.c() A<(A<B>) -> B>.c() A<[[Int]]>.c() A<[[A<B>]]>.c() A<(Int, UnicodeScalar)>.c() A<(a:Int, b:UnicodeScalar)>.c() A<Runcible & Fungible>.c() A<@convention(c) () -> Int32>.c() A<(@autoclosure @escaping () -> Int, Int) -> Void>.c() _ = [@convention(block) () -> Int]().count _ = [String: (@escaping (A<B>) -> Int) -> Void]().keys """ ) } func testGenericDisambiguation9() { AssertParse( """ A<B>(x: 0) """ ) } func testGenericDisambiguation10() { AssertParse( """ meta(A<B>.self) """ ) } func testGenericDisambiguation11() { AssertParse( """ meta2(A<B>.self, 0) """ ) } func testGenericDisambiguation12() { AssertParse( """ // FIXME: Nested generic types. Need to be able to express $T0<A, B, C> in the // typechecker. /* A<B>.C<D>.e() """ ) } func testGenericDisambiguation13() { AssertParse( """ A<B>.C<D>(0) """ ) } func testGenericDisambiguation14() { AssertParse( """ meta(A<B>.C<D>.self) meta2(A<B>.C<D>.self, 0) 1️⃣*/ """, diagnostics: [ DiagnosticSpec(message: "extraneous code '*/' at top level"), ] ) } func testGenericDisambiguation15() { AssertParse( """ // TODO: parse empty <> list //A<>.c() // e/xpected-error{{xxx}} """ ) } func testGenericDisambiguation16() { AssertParse( """ A<B, D>.c() """ ) } func testGenericDisambiguation17() { AssertParse( """ A<B?>(x: 0) // parses as type _ = a < b ? c : d """ ) } func testGenericDisambiguation18() { AssertParse( """ A<(B) throws -> D>(x: 0) """ ) } }
apache-2.0
ba56da8585c3373b2d65fcb7a529e1db
18.878229
88
0.493967
4.121653
false
true
false
false
AlesTsurko/DNMKit
DNMModel/TokenContainer.swift
1
2377
// // TokenBranch.swift // Tokenizer3 // // Created by James Bean on 11/8/15. // Copyright © 2015 James Bean. All rights reserved. // import Foundation /** TokenContainer is an hierarchical structure containing 0...n tokens (which may be TokenContainers, themselves) */ public class TokenContainer: Token { /// String representation of TokenContainer public var description: String { return getDescription() } /// Identifier of TokenContainer public var identifier: String /// String value that opens the scope of a command (e.g., "p" for Pitch value) public var openingValue: String /// All of the Tokens contained by this TokenContainer (may be TokenContainers, themselves) public var tokens: [Token] = [] // MARK: Syntax highlighting /// Index in the source file where this Token starts (used for syntax highlighting) public var startIndex: Int /// Index in the source file where this Token stops (used for syntax highlighting) public var stopIndex: Int = -1 // to be calculated with contents /** Create a TokenContainer with an identifier, opening value, and start index - parameter identifier: String that is used by syntax highlighter to identify Tokens - parameter openingValue: String value that opens scope of a command - parameter startIndex: Index in the source file where this Token starts - returns: TokenContainer */ public init(identifier: String, openingValue: String = "", startIndex: Int) { self.identifier = identifier self.openingValue = openingValue self.startIndex = startIndex self.stopIndex = startIndex + openingValue.characters.count - 1 } /** Add Token to contained Tokens - parameter token: Token */ public func addToken(token: Token) { tokens.append(token) } private func getDescription() -> String { var description: String = "\(identifier)" if openingValue != "" { description += ": \(openingValue)" } description += "; from \(startIndex) to \(stopIndex)" for token in tokens { if token is TokenContainer { description += "\n\(token)" } else { description += "\n-- \(token)" } } return description } }
gpl-2.0
b62d4220c5e0554223c6726efcd1852d
30.693333
95
0.641835
4.95
false
false
false
false